diff --git "a/5143.jsonl" "b/5143.jsonl" new file mode 100644--- /dev/null +++ "b/5143.jsonl" @@ -0,0 +1,706 @@ +{"seq_id":"501927783","text":"from flask_restful import Resource, reqparse\n\nfrom models.Rating import Rating\nfrom models.Store import Store\nfrom config.DataBase import db_session as db\n\nparser = reqparse.RequestParser()\nparser.add_argument('store_id', help = 'This field cannot be blank', required = True)\nparser.add_argument('rating', help = 'This field cannot be blank', required = True)\n\nclass RantingApi(Resource):\n def post(self, user_id):\n args = parser.parse_args()\n list_ratings = Rating.query.filter(Rating.user_id == user_id).all()\n\n for line in list_ratings:\n if (line.store_id == int(args['store_id'])):\n line.rating = args['rating']\n db.commit()\n\n updateRating(args['store_id'])\n return line.serialize(), 200\n \n rating = Rating(\n user_id=user_id, \n store_id=args['store_id'],\n rating=args['rating'])\n db.add(rating)\n db.commit()\n\n updateRating(args['store_id'])\n return rating.serialize(), 200\n\ndef updateRating(store_id):\n list_ratings = Rating.query.filter(Rating.store_id == store_id).all()\n\n acc = 0\n for line in list_ratings:\n acc = acc + line.rating\n \n new_value = round(acc/len(list_ratings))\n store = Store.query.filter(Store.id == store_id).first()\n store.rating = new_value\n db.commit()\n","sub_path":"BackEnd/routes/RatingApi.py","file_name":"RatingApi.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"16473190","text":"\n# simple_index.py\n\n# Run this file to build the index for the main index,\n# then run search.\n# This should prob be put in the m1 file later on\n# and run at the end of the index creation.\n\n\ndef index_simplifier(file_index: 'file'):\n counter = 0\n simple_index = open(\"simple_index.txt\", \"w\")\n with open(file_index) as f:\n # to get the first token\n item = f.readline()\n simple_index.write(item.strip('\\n'))\n simple_index.write(\",\" + str(0) + '\\n')\n counter += len(item) + 1\n\n # file.seek() works char by char, so adds the length\n # of the line to counter and if line is \\n, \n # the next line must be a token so writes token and \n # seek position to file\n for line in f:\n if line == \"\\n\":\n counter += len(line) + 1\n l = f.readline()\n simple_index.write(l.strip('\\n'))\n simple_index.write(\",\" + str(counter) + '\\n')\n counter += len(l) + 1\n else:\n counter += len(line) + 1\n simple_index.close()\n\n\nimport time\nif __name__ == '__main__':\n start = time.time()\n index_simplifier(\"index.txt\")\n end = time.time()\n print(str(end-start))\n","sub_path":"simple_index.py","file_name":"simple_index.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"170358309","text":"# https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/shares_get?view=odsp-graph-online\n\nimport requests\nimport os\n\nimport logging\n\nfrom downloader import download\n\nlogger = logging.getLogger('OneDrive')\nurl_patterns = ['live', 'onedrive', '1drv.ms']\n\n\ndef _get_id(link_id):\n if not link_id.lower().startswith(\"https://\"):\n return link_id # id only\n linkparts = link_id.split(\"/\")\n for i in range(0, len(linkparts)):\n if linkparts[i] == \"1drv.ms\" and len(linkparts[i+1]) == 1:\n return linkparts[i+2].rsplit(\"?\", 1)[0] # id from link\n return \"\" # no id found\n\n\ndef _get_driveitem(link, base_url=\"https://api.onedrive.com/v1.0/shares/\"):\n response = requests.get(base_url + _get_id(link) + \"/driveItem/?$expand=children\")\n return response.json()\n\n\ndef _get_download_item(driveItem, folder=\"\"):\n logger.debug(\"Adding \" + driveItem[\"name\"])\n return {\n \"fdir\": folder,\n \"fname\": driveItem[\"name\"],\n \"downloadUrl\": driveItem[\"@content.downloadUrl\"]\n }\n\n\ndef _get_content(link, folder=\"\"):\n driveItem = _get_driveitem(link)\n contents = []\n children = []\n if \"folder\" in driveItem:\n folder = os.path.join(folder, driveItem[\"name\"])\n if \"@content.downloadUrl\" in driveItem:\n contents.append(_get_download_item(driveItem, folder))\n if \"children\" in driveItem:\n for child in driveItem[\"children\"]:\n if \"@content.downloadUrl\" in child:\n contents.append(_get_download_item(child, folder))\n if \"folder\" in child:\n children.append(child[\"webUrl\"])\n logger.info('Found ' + str(len(children)) + ' child items and ' + str(len(contents)) + ' content downloads in ' + link)\n logger.debug(\"Children: \" + str(children))\n logger.debug(\"Contents: \" + str(contents))\n if children:\n for child in children:\n recursive_contents, recursive_children = _get_content(child, folder)\n contents.extend(recursive_contents)\n return contents, children\n\n\ndef get_link(link):\n content = _get_content(link)[0]\n for item in content:\n logger.debug(\"Downloading \" + str(item))\n download.download(\n url=item[\"downloadUrl\"],\n fname=os.path.join(item[\"fdir\"], item[\"fname\"])\n )\n\n\n# Get all links to MS OneDrive and save them to a text file.\ndef get_soup(soup):\n links = []\n for link in soup.findAll('a'):\n this_link = link.get('href')\n if any(pattern in str(this_link).lower() for pattern in url_patterns):\n links.append(str(this_link))\n links = list(dict.fromkeys(links))\n logger.debug('Found onedrive links: ' + str(links))\n for link in links:\n get_link(link)\n","sub_path":"downloader/onedrive.py","file_name":"onedrive.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"433624490","text":"import torch\nimport argparse\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch_geometric.transforms as T\nimport torch_geometric.nn as pyg_nn\nimport torch.optim as optim\n\nfrom torch.utils.data import DataLoader\nfrom torch_geometric.datasets import Planetoid\nfrom sklearn.metrics import *\nfrom torch.nn import Sequential, Linear, ReLU\nfrom deepsnap.dataset import GraphDataset\nfrom deepsnap.batch import Batch\n\ndef arg_parse():\n parser = argparse.ArgumentParser(description='Node classification arguments.')\n\n parser.add_argument('--device', type=str,\n help='CPU / GPU device.')\n parser.add_argument('--epochs', type=int,\n help='Number of epochs to train.')\n parser.add_argument('--dataset', type=str,\n help='Node classification dataset. Cora, CiteSeer, PubMed')\n parser.add_argument('--model', type=str,\n help='GCN, GAT, GraphSAGE.')\n parser.add_argument('--batch_size', type=int,\n help='Batch size for node classification.')\n parser.add_argument('--hidden_dim', type=int,\n help='Hidden dimension of GNN.')\n parser.add_argument('--num_layers', type=int,\n help='Number of graph convolution layers.')\n parser.add_argument('--opt', type=str,\n help='Optimizer such as adam, sgd, rmsprop or adagrad.')\n parser.add_argument('--weight_decay', type=float,\n help='Weight decay.')\n parser.add_argument('--dropout', type=float,\n help='The dropout ratio.')\n parser.add_argument('--lr', type=float,\n help='Learning rate.')\n parser.add_argument('--netlib', type=str,\n help='Backend network library.')\n parser.add_argument('--split', type=str,\n help='Randomly split dataset, or use fixed split in PyG. fixed, random')\n\n parser.set_defaults(\n device='cuda:0',\n epochs=200,\n dataset='Cora',\n model='GCN',\n batch_size=1,\n hidden_dim=32,\n num_layers=2,\n opt='adam',\n weight_decay=5e-4,\n dropout=0.0,\n lr=0.01,\n netlib=\"nx\",\n split='random'\n )\n return parser.parse_args()\n\n\ndef build_optimizer(args, params):\n weight_decay = args.weight_decay\n filter_fn = filter(lambda p: p.requires_grad, params)\n if args.opt == 'adam':\n optimizer = optim.Adam(filter_fn, lr=args.lr, weight_decay=weight_decay)\n elif args.opt == 'sgd':\n optimizer = optim.SGD(filter_fn, lr=args.lr, momentum=0.95, weight_decay=weight_decay)\n elif args.opt == 'rmsprop':\n optimizer = optim.RMSprop(filter_fn, lr=args.lr, weight_decay=weight_decay)\n elif args.opt == 'adagrad':\n optimizer = optim.Adagrad(filter_fn, lr=args.lr, weight_decay=weight_decay)\n return optimizer\n\n\nclass GNN(torch.nn.Module):\n def __init__(self, input_dim, hidden_dim, output_dim, args):\n super(GNN, self).__init__()\n self.dropout = args.dropout\n self.num_layers = args.num_layers\n\n conv_model = self.build_conv_model(args.model)\n self.convs = nn.ModuleList()\n self.convs.append(conv_model(input_dim, hidden_dim))\n\n for l in range(args.num_layers - 2):\n self.convs.append(conv_model(hidden_dim, hidden_dim))\n self.convs.append(conv_model(hidden_dim, output_dim))\n\n def build_conv_model(self, model_type):\n if model_type == 'GCN':\n return pyg_nn.GCNConv\n elif model_type == 'GAT':\n return pyg_nn.GATConv\n elif model_type == \"GraphSage\":\n return pyg_nn.SAGEConv\n else:\n raise ValueError(\n \"Model {} unavailable, please add it to GNN.build_conv_model.\".format(model_type))\n\n def forward(self, data):\n x, edge_index, batch = data.node_feature, data.edge_index, data.batch\n\n for i in range(len(self.convs) - 1):\n x = self.convs[i](x, edge_index)\n x = F.relu(x)\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = self.convs[len(self.convs) - 1](x, edge_index)\n x = F.log_softmax(x, dim=1)\n return x\n\n def loss(self, pred, label):\n return F.nll_loss(pred, label)\n\n\ndef train(train_loader, val_loader, test_loader, args, num_node_features, num_classes,\n device=\"cpu\"):\n model_cls = GNN\n\n model = model_cls(num_node_features, args.hidden_dim, num_classes, args).to(device)\n opt = build_optimizer(args, model.parameters())\n\n for epoch in range(args.epochs):\n total_loss = 0\n model.train()\n for batch in train_loader:\n batch.to(device)\n opt.zero_grad()\n pred = model(batch)\n label = batch.node_label\n loss = model.loss(pred[batch.node_label_index], label)\n total_loss += loss.item()\n loss.backward()\n opt.step()\n\n train_acc = test(train_loader, model, device)\n val_acc = test(val_loader, model, device)\n test_acc = test(test_loader, model, device)\n print(\"Epoch {}: Train: {:.4f}, Validation: {:.4f}. Test: {:.4f}, Loss: {:.4f}\".format(\n epoch + 1, train_acc, val_acc, test_acc, total_loss))\n\n\ndef test(loader, model, device='cuda'):\n model.eval()\n\n for batch in loader:\n batch.to(device)\n logits = model(batch)\n pred = logits[batch.node_label_index].max(1)[1]\n acc = pred.eq(batch.node_label).sum().item()\n total = batch.node_label_index.shape[0]\n acc /= total\n return acc\n\n\nif __name__ == \"__main__\":\n args = arg_parse()\n if args.dataset in ['Cora', 'CiteSeer', 'Pubmed']:\n pyg_dataset = Planetoid('./planetoid', args.dataset) # load some format of graph data\n else:\n raise ValueError(\"Unsupported dataset.\")\n \n if args.netlib == \"nx\":\n import networkx as netlib\n print(\"Use NetworkX as the backend network library.\")\n elif args.netlib == \"sx\":\n import snap\n import snapx as netlib\n print(\"Use SnapX as the backend network library.\")\n else:\n raise ValueError(\"{} network library is not supported.\".format(args.netlib))\n\n if args.split == 'random':\n graphs = GraphDataset.pyg_to_graphs(pyg_dataset, verbose=True,\n fixed_split=False, netlib=netlib)\n dataset = GraphDataset(graphs, task='node') # node, edge, link_pred, graph\n dataset_train, dataset_val, dataset_test = dataset.split(\n transductive=True,\n split_ratio=[0.8, 0.1, 0.1]) # transductive split, inductive split\n else:\n graphs_train, graphs_val, graphs_test = \\\n GraphDataset.pyg_to_graphs(pyg_dataset, verbose=True,\n fixed_split=True, netlib=netlib)\n\n dataset_train, dataset_val, dataset_test = \\\n GraphDataset(graphs_train, task='node'), GraphDataset(graphs_val,task='node'), \\\n GraphDataset(graphs_test, task='node')\n\n train_loader = DataLoader(dataset_train, collate_fn=Batch.collate(),\n batch_size=16) # basic data loader\n val_loader = DataLoader(dataset_val, collate_fn=Batch.collate(),\n batch_size=16) # basic data loader\n test_loader = DataLoader(dataset_test, collate_fn=Batch.collate(),\n batch_size=16) # basic data loader\n\n num_node_features = dataset_train.num_node_features\n num_classes = dataset_train.num_node_labels\n\n train(train_loader, val_loader,test_loader,\n args, num_node_features, num_classes, args.device)\n\n","sub_path":"examples/node_classification/node_classification_planetoid.py","file_name":"node_classification_planetoid.py","file_ext":"py","file_size_in_byte":7729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"562652293","text":"#!/usr/bin/env python\n\"\"\"\nPandoc filter to pass all code blocks through pygments highlighter.\n\"\"\"\n__url__ = \"https://github.com/or/pandocfilter-pygments\"\n__version__ = \"0.0.2\"\n__license__ = \"MIT License\"\n__author__ = \"Oliver Runge\"\n__author_email__ = \"oliver.runge@gmail.com\"\n__keywords__ = \"hosted.by.github pygments orgmode lexer highlighting\"\n","sub_path":"src/pandocfilter_pygments/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"425257396","text":"import os\nimport time\nimport logging\n\nfrom pacman.model.placements import placement\nfrom pacman import exceptions\n\nfrom spinn_machine.sdram import SDRAM\n\nlogger = logging.getLogger(__name__)\n\n\ndef tag_allocator_report(report_folder, tag_infos):\n pass\n\n\ndef placer_reports_with_partitionable_graph(\n report_folder, hostname, graph, graph_mapper, placements, machine):\n \"\"\" Reports that can be produced from placement given a partitionable\\\n graph's existence\n :param report_folder: the folder to which the reports are being written\n :param hostname: the machine's hostname to which the placer worked on\n :param graph: the partitionable graph to which placements were built\n :param graph_mapper: the mapping between partitionable and partitioned \\\n graphs\n :param placements: the placements objects built by the placer.\n :param machine: the python machine object\n :return None\n \"\"\"\n placement_report_with_partitionable_graph_by_vertex(\n report_folder, hostname, graph, graph_mapper, placements)\n placement_report_with_partitionable_graph_by_core(\n report_folder, hostname, placements, machine, graph_mapper)\n sdram_usage_report_per_chip(\n report_folder, hostname, placements, machine)\n\n\ndef placer_reports_without_partitionable_graph(\n report_folder, hostname, sub_graph, placements, machine):\n \"\"\"\n :param report_folder: the folder to which the reports are being written\n :param hostname: the machine's hostname to which the placer worked on\n :param placements: the placements objects built by the placer.\n :param machine: the python machine object\n :param sub_graph: the partitioned graph to which the reports are to\\\n operate on\n :return None\n \"\"\"\n placement_report_without_partitionable_graph_by_vertex(\n report_folder, hostname, placements, sub_graph)\n placement_report_without_partitionable_graph_by_core(\n report_folder, hostname, placements, machine)\n sdram_usage_report_per_chip(\n report_folder, hostname, placements, machine)\n\n\ndef router_reports(report_folder, routing_paths, hostname):\n router_report_from_paths(report_folder, routing_paths, hostname)\n\n\ndef routing_info_reports(\n report_folder, subgraph, routing_infos, routing_tables):\n routing_info_report(report_folder, subgraph, routing_infos)\n router_report_from_router_tables(report_folder, routing_tables)\n\n\ndef partitioner_reports(report_folder, hostname, graph,\n graph_to_subgraph_mapper):\n partitioner_report(report_folder, hostname,\n graph, graph_to_subgraph_mapper)\n\n\ndef router_report_from_paths(report_folder, routing_paths, hostname):\n \"\"\" Generates a text file of routing paths\n\n :param routing_paths:\n :return:\n \"\"\"\n file_name = os.path.join(report_folder, \"edge_routing_info.rpt\")\n f_routing = None\n try:\n f_routing = open(file_name, \"w\")\n except IOError:\n logger.error(\"Generate_routing_reports: Can't open file {} for \"\n \"writing.\".format(file_name))\n\n f_routing.write(\" Edge Routing Report\\n\")\n f_routing.write(\" ===================\\n\\n\")\n time_date_string = time.strftime(\"%c\")\n f_routing.write(\"Generated: {}\".format(time_date_string))\n f_routing.write(\" for target machine '{}'\".format(hostname))\n f_routing.write(\"\\n\\n\")\n\n link_labels = {0: 'E', 1: 'NE', 2: 'N', 3: 'W', 4: 'SW', 5: 'S'}\n\n for e in routing_paths.all_subedges():\n text = \"**** SubEdge '{}', from vertex: '{}' to vertex: '{}'\".format(\n e.label, e.pre_subvertex.label, e.post_subvertex.label)\n f_routing.write(text)\n f_routing.write(\"\\n\")\n\n path_entries = routing_paths.get_entries_for_edge(e)\n first = True\n for entry in path_entries:\n if not first:\n text = \"--->\"\n else:\n text = \"\"\n if entry.incoming_processor is not None:\n text = text + \"P{}\".format(entry.incoming_processor)\n else:\n text = \"(L:{}\".format(link_labels[entry.incoming_link])\n text += \"->{}:{}\".format(entry.router_x, entry.router_y)\n if entry.defaultable:\n text += \":D\"\n if len(entry.out_going_processors) != 0:\n for processor in entry.out_going_processors:\n text = text + \"->P{}\".format(processor)\n if len(entry.out_going_links) != 0:\n for link in entry.out_going_links:\n text += \"->{}\".format(link_labels[link])\n f_routing.write(text)\n f_routing.write(\"\\n\")\n\n text = \"{} has route length: {}\\n\".format(e.label, len(path_entries))\n f_routing.write(text)\n\n # End one entry:\n f_routing.write(\"\\n\")\n f_routing.flush()\n f_routing.close()\n\n\ndef partitioner_report(report_folder, hostname, graph, graph_mapper):\n \"\"\" Generate report on the placement of sub-vertices onto cores.\n \"\"\"\n\n # Cycle through all vertices, and for each cycle through its sub-vertices.\n # For each sub-vertex, describe its core mapping.\n file_name = os.path.join(report_folder, \"partitioned_by_vertex.rpt\")\n f_place_by_vertex = None\n try:\n f_place_by_vertex = open(file_name, \"w\")\n except IOError:\n logger.error(\"Generate_placement_reports: Can't open file {} for\"\n \" writing.\".format(file_name))\n\n f_place_by_vertex.write(\n \" Placement Information by Vertex\\n\")\n f_place_by_vertex.write(\" ===============================\\n\\n\")\n time_date_string = time.strftime(\"%c\")\n f_place_by_vertex.write(\"Generated: {}\".format(time_date_string))\n f_place_by_vertex.write(\" for target machine '{}'\".format(hostname))\n f_place_by_vertex.write(\"\\n\\n\")\n\n vertices = sorted(graph.vertices, key=lambda x: x.label)\n for v in vertices:\n vertex_name = v.label\n vertex_model = v.model_name\n num_atoms = v.n_atoms\n f_place_by_vertex.write(\n \"**** Vertex: '{}'\\n\".format(vertex_name))\n f_place_by_vertex.write(\"Model: {}\\n\".format(vertex_model))\n f_place_by_vertex.write(\"Pop sz: {}\\n\".format(num_atoms))\n f_place_by_vertex.write(\"Sub-vertices: \\n\")\n\n partitioned_vertices = \\\n sorted(graph_mapper.get_subvertices_from_vertex(v),\n key=lambda x: x.label)\n partitioned_vertices = \\\n sorted(partitioned_vertices,\n key=lambda x: graph_mapper.get_subvertex_slice(x).lo_atom)\n for sv in partitioned_vertices:\n lo_atom = graph_mapper.get_subvertex_slice(sv).lo_atom\n hi_atom = graph_mapper.get_subvertex_slice(sv).hi_atom\n num_atoms = hi_atom - lo_atom + 1\n my_string = \" Slice {}:{} ({} atoms) \\n\"\\\n .format(lo_atom, hi_atom, num_atoms)\n f_place_by_vertex.write(my_string)\n f_place_by_vertex.flush()\n f_place_by_vertex.write(\"\\n\")\n\n # Close file:\n f_place_by_vertex.close()\n\n\ndef placement_report_with_partitionable_graph_by_vertex(\n report_folder, hostname, graph, graph_mapper, placements):\n \"\"\" Generate report on the placement of sub-vertices onto cores by vertex.\n\n :param report_folder: the folder to which the reports are being written\n :param hostname: the machine's hostname to which the placer worked on\n :param graph: the partitionable graph to which placements were built\n :param graph_mapper: the mapping between partitionable and partitioned\\\n graphs\n :param placements: the placements objects built by the placer.\n \"\"\"\n\n # Cycle through all vertices, and for each cycle through its sub-vertices.\n # For each sub-vertex, describe its core mapping.\n file_name = os.path.join(report_folder, \"placement_by_vertex.rpt\")\n f_place_by_vertex = None\n try:\n f_place_by_vertex = open(file_name, \"w\")\n except IOError:\n logger.error(\"Generate_placement_reports: Can't open file {} for\"\n \" writing.\".format(file_name))\n\n f_place_by_vertex.write(\n \" Placement Information by Vertex\\n\")\n f_place_by_vertex.write(\" ===============================\\n\\n\")\n time_date_string = time.strftime(\"%c\")\n f_place_by_vertex.write(\"Generated: {}\".format(time_date_string))\n f_place_by_vertex.write(\" for target machine '{}'\".format(hostname))\n f_place_by_vertex.write(\"\\n\\n\")\n\n used_processors_by_chip = dict()\n used_sdram_by_chip = dict()\n subvertex_by_processor = dict()\n\n vertices = sorted(graph.vertices, key=lambda x: x.label)\n for v in vertices:\n vertex_name = v.label\n vertex_model = v.model_name\n num_atoms = v.n_atoms\n f_place_by_vertex.write(\n \"**** Vertex: '{}'\\n\".format(vertex_name))\n f_place_by_vertex.write(\"Model: {}\\n\".format(vertex_model))\n f_place_by_vertex.write(\"Pop sz: {}\\n\".format(num_atoms))\n f_place_by_vertex.write(\"Sub-vertices: \\n\")\n\n partitioned_vertices = \\\n sorted(graph_mapper.get_subvertices_from_vertex(v),\n key=lambda vert: vert.label)\n partitioned_vertices = \\\n sorted(partitioned_vertices,\n key=lambda pvert:\n graph_mapper.get_subvertex_slice(pvert).lo_atom)\n for sv in partitioned_vertices:\n lo_atom = graph_mapper.get_subvertex_slice(sv).lo_atom\n hi_atom = graph_mapper.get_subvertex_slice(sv).hi_atom\n num_atoms = hi_atom - lo_atom + 1\n cur_placement = placements.get_placement_of_subvertex(sv)\n x, y, p = cur_placement.x, cur_placement.y, cur_placement.p\n key = \"{},{}\".format(x, y)\n if key in used_processors_by_chip:\n used_procs = used_processors_by_chip[key]\n else:\n used_procs = list()\n used_sdram_by_chip.update({key: 0})\n subvertex_by_processor[\"{},{},{}\".format(x, y, p)] = sv\n new_proc = [p, cur_placement]\n used_procs.append(new_proc)\n used_processors_by_chip.update({key: used_procs})\n my_string = \" Slice {}:{} ({} atoms) on core ({}, {}, {}) \\n\"\\\n .format(lo_atom, hi_atom, num_atoms, x, y, p)\n f_place_by_vertex.write(my_string)\n f_place_by_vertex.write(\"\\n\")\n\n # Close file:\n f_place_by_vertex.close()\n\n\ndef placement_report_without_partitionable_graph_by_vertex(\n report_folder, hostname, placements, partitioned_graph):\n \"\"\" Generate report on the placement of sub-vertices onto cores by vertex.\n :param report_folder: the folder to which the reports are being written\n :param hostname: the machine's hostname to which the placer worked on\n :param placements: the placements objects built by the placer.\n :param partitioned_graph: the partitioned graph generated by the end user\n \"\"\"\n\n # Cycle through all vertices, and for each cycle through its sub-vertices.\n # For each sub-vertex, describe its core mapping.\n file_name = os.path.join(report_folder, \"placement_by_vertex.rpt\")\n f_place_by_vertex = None\n try:\n f_place_by_vertex = open(file_name, \"w\")\n except IOError:\n logger.error(\"Generate_placement_reports: Can't open file {} for\"\n \" writing.\".format(file_name))\n\n f_place_by_vertex.write(\n \" Placement Information by AbstractConstrainedVertex\\n\")\n f_place_by_vertex.write(\" ===============================\\n\\n\")\n time_date_string = time.strftime(\"%c\")\n f_place_by_vertex.write(\"Generated: {}\".format(time_date_string))\n f_place_by_vertex.write(\" for target machine '{}'\".format(hostname))\n f_place_by_vertex.write(\"\\n\\n\")\n\n used_processors_by_chip = dict()\n used_sdram_by_chip = dict()\n subvertex_by_processor = dict()\n\n vertices = sorted(partitioned_graph.subvertices, key=lambda sub: sub.label)\n for v in vertices:\n vertex_name = v.label\n vertex_model = v.model_name\n f_place_by_vertex.write(\n \"**** AbstractConstrainedVertex: '{}'\\n\".format(vertex_name))\n f_place_by_vertex.write(\"Model: {}\\n\".format(vertex_model))\n\n cur_placement = placements.get_placement_of_subvertex(v)\n x, y, p = cur_placement.x, cur_placement.y, cur_placement.p\n key = \"{},{}\".format(x, y)\n if key in used_processors_by_chip:\n used_procs = used_processors_by_chip[key]\n else:\n used_procs = list()\n used_sdram_by_chip.update({key: 0})\n subvertex_by_processor[\"{},{},{}\".format(x, y, p)] = v\n new_proc = [p, cur_placement]\n used_procs.append(new_proc)\n used_processors_by_chip.update({key: used_procs})\n my_string = \" Placed on core ({}, {}, {}) \\n\".format(x, y, p)\n f_place_by_vertex.write(my_string)\n f_place_by_vertex.write(\"\\n\")\n\n # Close file:\n f_place_by_vertex.close()\n\n\ndef placement_report_with_partitionable_graph_by_core(\n report_folder, hostname, placements, machine, graph_mapper):\n \"\"\" Generate report on the placement of sub-vertices onto cores by core.\n :param report_folder: the folder to which the reports are being written\n :param hostname: the machiens hostname to which the placer worked on\n :param graph_mapper: the mapping between partitionable and partitioned\\\n graphs\n :param machine: the spinnaker machine object\n :param placements: the placements objects built by the placer.\n \"\"\"\n\n # File 2: Placement by core.\n # Cycle through all chips and by all cores within each chip.\n # For each core, display what is held on it.\n file_name = os.path.join(report_folder, \"placement_by_core.rpt\")\n f_place_by_core = None\n try:\n f_place_by_core = open(file_name, \"w\")\n except IOError:\n logger.error(\"Generate_placement_reports: Can't open file {} for \"\n \"writing.\".format(file_name))\n\n f_place_by_core.write(\" Placement Information by Core\\n\")\n f_place_by_core.write(\" =============================\\n\\n\")\n time_date_string = time.strftime(\"%c\")\n f_place_by_core.write(\"Generated: {}\".format(time_date_string))\n f_place_by_core.write(\" for target machine '{}'\".format(hostname))\n f_place_by_core.write(\"\\n\\n\")\n\n for chip in machine.chips:\n written_header = False\n for processor in chip.processors:\n if placements.is_subvertex_on_processor(chip.x, chip.y,\n processor.processor_id):\n if not written_header:\n f_place_by_core.write(\"**** Chip: ({}, {})\\n\"\n .format(chip.x, chip.y))\n f_place_by_core.write(\"Application cores: {}\\n\"\n .format(len(list(chip.processors))))\n written_header = True\n proc_id = processor.processor_id\n subvertex = \\\n placements.get_subvertex_on_processor(\n chip.x, chip.y, processor.processor_id)\n vertex = \\\n graph_mapper\\\n .get_vertex_from_subvertex(subvertex)\n vertex_label = vertex.label\n vertex_model = vertex.model_name\n vertex_atoms = vertex.n_atoms\n lo_atom = graph_mapper.get_subvertex_slice(subvertex).lo_atom\n hi_atom = graph_mapper.get_subvertex_slice(subvertex).hi_atom\n num_atoms = hi_atom - lo_atom + 1\n p_str = (\" Processor {}: Vertex: '{}',\"\n \" pop sz: {}\\n\".format(\n proc_id, vertex_label, vertex_atoms))\n f_place_by_core.write(p_str)\n p_str = (\" Slice on this core: {}:{} ({} atoms)\\n\"\n .format(lo_atom, hi_atom, num_atoms))\n f_place_by_core.write(p_str)\n p_str = \" Model: {}\\n\\n\".format(vertex_model)\n f_place_by_core.write(p_str)\n f_place_by_core.write(\"\\n\")\n # Close file:\n f_place_by_core.close()\n\n\ndef placement_report_without_partitionable_graph_by_core(\n report_folder, hostname, placements, machine):\n \"\"\"\n Generate report on the placement of sub-vertices onto cores by core.\n :param report_folder: the folder to which the reports are being written\n :param hostname: the machiens hostname to which the placer worked on\n :param machine: the spinnaker machine object\n :param placements: the placements objects built by the placer.\n \"\"\"\n\n # File 2: Placement by core.\n # Cycle through all chips and by all cores within each chip.\n # For each core, display what is held on it.\n file_name = os.path.join(report_folder, \"placement_by_core.rpt\")\n f_place_by_core = None\n try:\n f_place_by_core = open(file_name, \"w\")\n except IOError:\n logger.error(\"Generate_placement_reports: Can't open file {} for \"\n \"writing.\".format(file_name))\n\n f_place_by_core.write(\" Placement Information by Core\\n\")\n f_place_by_core.write(\" =============================\\n\\n\")\n time_date_string = time.strftime(\"%c\")\n f_place_by_core.write(\"Generated: {}\".format(time_date_string))\n f_place_by_core.write(\" for target machine '{}'\".format(hostname))\n f_place_by_core.write(\"\\n\\n\")\n\n for chip in machine.chips:\n written_header = False\n for processor in chip.processors:\n if placements.is_subvertex_on_processor(chip.x, chip.y,\n processor.processor_id):\n if not written_header:\n f_place_by_core.write(\"**** Chip: ({}, {})\\n\"\n .format(chip.x, chip.y))\n f_place_by_core.write(\"Application cores: {}\\n\"\n .format(len(list(chip.processors))))\n written_header = True\n proc_id = processor.processor_id\n subvertex = \\\n placements.get_subvertex_on_processor(\n chip.x, chip.y, processor.processor_id)\n\n vertex_label = subvertex.label\n vertex_model = subvertex.model_name\n\n p_str = (\" Processor {}: AbstractConstrainedVertex: '{}' \\n\"\n .format(proc_id, vertex_label))\n f_place_by_core.write(p_str)\n f_place_by_core.write(p_str)\n p_str = \" Model: {}\\n\\n\".format(vertex_model)\n f_place_by_core.write(p_str)\n f_place_by_core.write(\"\\n\")\n\n # Close file:\n f_place_by_core.close()\n\n\ndef sdram_usage_report_per_chip(report_folder, hostname, placements, machine):\n \"\"\" Reports the SDRAM used per chip\n\n :param report_folder: the folder to which the reports are being written\n :param hostname: the machine's hostname to which the placer worked on\n :param placements: the placements objects built by the placer.\n :param machine: the python machine object\n :return None\n \"\"\"\n\n file_name = os.path.join(report_folder, \"chip_sdram_usage_by_core.rpt\")\n f_mem_used_by_core = None\n try:\n f_mem_used_by_core = open(file_name, \"w\")\n except IOError:\n logger.error(\"Generate_placement_reports: Can't open file {} for \"\n \"writing.\".format(file_name))\n\n f_mem_used_by_core.write(\" Memory Usage by Core\\n\")\n f_mem_used_by_core.write(\" ====================\\n\\n\")\n time_date_string = time.strftime(\"%c\")\n f_mem_used_by_core.write(\"Generated: %s\" % time_date_string)\n f_mem_used_by_core.write(\" for target machine '{}'\".format(hostname))\n f_mem_used_by_core.write(\"\\n\\n\")\n used_sdram_by_chip = dict()\n\n placements = sorted(placements.placements, key=lambda x: x.subvertex.label)\n\n for cur_placement in placements:\n subvert = cur_placement.subvertex\n requirements = subvert.resources_required\n\n x, y, p = cur_placement.x, cur_placement.y, cur_placement.p\n f_mem_used_by_core.write(\n \"SDRAM requirements for core ({},{},{}) is {} KB\\n\".format(\n x, y, p, int(requirements.sdram.get_value() / 1024.0)))\n if (x, y) not in used_sdram_by_chip:\n used_sdram_by_chip[(x, y)] = requirements.sdram.get_value()\n else:\n used_sdram_by_chip[(x, y)] += requirements.sdram.get_value()\n\n for chip in machine.chips:\n try:\n used_sdram = used_sdram_by_chip[(chip.x, chip.y)]\n if used_sdram != 0:\n f_mem_used_by_core.write(\n \"**** Chip: ({}, {}) has total memory usage of\"\n \" {} KB out of a max of \"\n \"{} MB \\n\\n\".format(chip.x, chip.y,\n int(used_sdram / 1024.0),\n int(SDRAM.DEFAULT_SDRAM_BYTES /\n (1024.0 * 1024.0))))\n except KeyError:\n\n # Do Nothing\n pass\n\n # Close file:\n f_mem_used_by_core.close()\n\n\ndef routing_info_report(report_folder, subgraph, routing_infos):\n \"\"\" Generates a report which says which keys is being allocated to each\\\n subvertex\n :param report_folder: the\n :param subgraph:\n :param routing_infos:\n \"\"\"\n file_name = os.path.join(report_folder,\n \"virtual_key_space_information_report.rpt\")\n output = None\n try:\n output = open(file_name, \"w\")\n except IOError:\n logger.error(\"generate virtual key space information report: \"\n \"Can't open file {} for writing.\".format(file_name))\n\n for subvert in subgraph.subvertices:\n output.write(\"Subvert: {} \\n\".format(subvert))\n outgoing_subedges = subgraph.outgoing_subedges_from_subvertex(subvert)\n for outgoing_subedge in outgoing_subedges:\n subedge_routing_info = routing_infos.\\\n get_subedge_information_from_subedge(outgoing_subedge)\n output.write(\"{} \\n\".format(subedge_routing_info))\n output.write(\"\\n\\n\")\n output.flush()\n output.close()\n\n\ndef router_report_from_router_tables(report_folder, routing_tables):\n top_level_folder = os.path.join(report_folder, \"routing_tables_generated\")\n if not os.path.exists(top_level_folder):\n os.mkdir(top_level_folder)\n for routing_table in routing_tables.routing_tables:\n if routing_table.number_of_entries > 0:\n file_sub_name = \"routing_table_{}_{}.rpt\"\\\n .format(routing_table.x, routing_table.y)\n file_name = os.path.join(top_level_folder, file_sub_name)\n try:\n output = open(file_name, \"w\")\n except IOError:\n logger.error(\"Generate_placement_reports: Can't open file\"\n \" {} for writing.\".format(file_name))\n\n output.write(\"router contains {} entries \\n \"\n \"\\n\".format(routing_table.number_of_entries))\n output.write(\" Index Key(hex) Mask(hex) Route(hex)\"\n \" Src. Core -> [Cores][Links]\\n\")\n output.write(\"----------------------------------------------------\"\n \"--------------------------\\n\")\n\n entry_count = 0\n for entry in routing_table.multicast_routing_entries:\n index = entry_count & 0xFFFF\n key = entry.routing_entry_key\n mask = entry.mask\n hex_route = _reduce_route_value(entry.processor_ids,\n entry.link_ids)\n hex_key = _uint_32_to_hex_string(key)\n hex_mask = _uint_32_to_hex_string(mask)\n route_txt = _expand_route_value(entry.processor_ids,\n entry.link_ids)\n core_id = \"({}, {}, {})\"\\\n .format((key >> 24 & 0xFF), (key >> 16 & 0xFF),\n (key >> 11 & 0xF))\n entry_str = (\" {} {} {} {} {} \"\n \" {}\\n\".format(index, hex_key, hex_mask,\n hex_route, core_id, route_txt))\n entry_count += 1\n output.write(entry_str)\n output.flush()\n output.close()\n\n\ndef _reduce_route_value(processors_ids, link_ids):\n value = 0\n for link in link_ids:\n value += 1 << link\n for processor in processors_ids:\n value += 1 << (processor + 6)\n return _uint_32_to_hex_string(value)\n\n\ndef _uint_32_to_hex_string(number):\n \"\"\" Convert a 32-bit unsigned number into a hex string.\n \"\"\"\n return \"0x{:08X}\".format(number)\n\n\ndef _expand_route_value(processors_ids, link_ids):\n \"\"\" Convert a 32-bit route word into a string which lists the target cores\\\n and links.\n \"\"\"\n\n # Convert processor targets to readable values:\n route_string = \"[\"\n first = True\n for processor in processors_ids:\n if first:\n route_string += \"{}\".format(processor)\n first = False\n else:\n route_string += \", {}\".format(processor)\n\n route_string += \"] [\"\n # Convert link targets to readable values:\n link_labels = {0: 'E', 1: 'NE', 2: 'N', 3: 'W', 4: 'SW', 5: 'S'}\n\n first = True\n for link in link_ids:\n if first:\n route_string += \"{}\".format(link_labels[link])\n first = False\n else:\n route_string += \", {}\".format(link_labels[link])\n route_string += \"]\"\n return route_string\n\n\ndef _get_associated_routing_entries_from(\n fr_placement, to_placement, routing_tables, routing_data, machine):\n\n routing_table = routing_tables.get_routing_table_for_chip(\n to_placement.x, to_placement.y)\n key_combo = routing_data.key_combo\n mask = routing_data.mask\n destinations = \\\n routing_table.get_multicast_routing_entry_by_routing_entry_key(\n key_combo, mask)\n\n if fr_placement.x == to_placement.x and fr_placement.y == to_placement.y:\n\n # check that the last route matches the destination core in the\n # to_placement add the destination core to the associated chips list\n # and return the associated chip list\n processors = destinations.processor_ids()\n if to_placement.p in processors:\n associated_chips = list()\n step = dict()\n step['x'] = fr_placement.x\n step['y'] = fr_placement.y\n associated_chips.append(step)\n return associated_chips\n else:\n raise exceptions.PacmanRoutingException(\n \"Although routing path with key_combo {0:X} reaches chip\"\n \" ({1:d}, {2:d}), it does not reach processor {3:d} as\"\n \" requested by the destination placement\".format(\n key_combo, to_placement.x, to_placement.y, to_placement.p))\n else:\n links = destinations.link_ids()\n current_x = fr_placement.x\n current_y = fr_placement.y\n current_chip = machine.get_chip_at(current_x, current_y)\n current_router = current_chip.router\n for i in links:\n next_link = current_router.get_link(i)\n next_x = next_link.destination_x\n next_y = next_link.destination_y\n next_placement = placement.Placement(None, next_x, next_y, None)\n associated_chips = _get_associated_routing_entries_from(\n next_placement, to_placement, routing_tables, routing_data,\n machine)\n if associated_chips is not None:\n step = dict()\n step['x'] = current_x\n step['y'] = current_y\n associated_chips.insert(0, step)\n return associated_chips\n else:\n return None\n","sub_path":"pacman/operations/algorithm_reports/reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":28280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"548648183","text":"import requests\nfrom lxml import etree\nimport redis\nheaders = {\n\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit 537.36 (KHTML, like Gecko) Chrome\"\n}\nstart_url ='https://news.china.com'\nr = redis.Redis(host='localhost',port=6379,db=0)\ndef get_cate():\n resp =requests.get(url=start_url,headers=headers).text\n html = etree.HTML(resp)\n cate_url = html.xpath(\"//div[@id='newsNav']//a/@href\")\n c_cate_url=list(map(lambda x:'https:'+x,cate_url))\n for ur in c_cate_url:\n get_list(ur)\ndef get_list(url):\n resp = requests.get(url, headers=headers).text\n html = etree.HTML(resp)\n info_list=html.xpath(\"//div[@class='bd defList']//h3/a/@href\")\n\n if len(info_list)==0:\n info_list = html.xpath(\"//div[@class='left']//a/@href\")#政务\n if len(info_list)==0:\n info_list = html.xpath(\"//div[@class='r1_left']//a/@href\")#公益\n # if len(info_list)==0:\n # info_list = html.xpath(\"//div[@id='js-media-0']/div//h3/a/@href\")#财经\n if len(info_list)==0:\n fina_cateurl = html.xpath(\"//div[@class='bd defList']//h3/a/@href\")#财经分类URL\n for u in fina_cateurl:\n cont_resp = requests.get(url='https:'+u, headers=headers).text\n info_list = cont_resp.xpath(\"//h3/a/@href\")\n for info_url in info_list:\n print(info_url)\n if r.sadd('zhonghua_allurl',info_url):\n r.lpush('zh_info',info_url)\n\n\n\nif __name__ == '__main__':\n get_cate()","sub_path":"中华测试/zhonghua/zhonghua/spiders/get_info.py","file_name":"get_info.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"566639148","text":"from multiprocessing import Process\nimport os\n\n#子进程要执行的代码\ndef run_func(test):\n print('这是子进程is pid = {},我的父进程是{}'.format(os.getpid(), os.getppid()))\n print(test)\n\ndef main():\n print('父进程{}'.format(os.getpid()))\n print('创建子进程')\n p = Process(target=run_func, args=(100,))\n p.start()\n p.join()\n\nif __name__ == '__main__':\n main()\n\n\n#target :表示这个进程示例所调用的对象\n#args:调用对象的位置参数元祖\n#name:当前进程实例的别名\n#kwargs:调用对象的位置参数字典\n#terminta :不管进程有没有完成,立刻终止","sub_path":"就业/linux网络编程/05/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"434755251","text":"#!/usr/bin/env python3\n\nimport math\n\ndef checkQuarters(amount):\n\n\tquarters = int(math.floor(amount / 25))\n\tquarters_left = int(amount % 25)\n\tresult = [];\n\tresult.append(quarters);\n\tresult.append(quarters_left)\n\treturn result\n\t\n\ndef checkDimes(amount):\n\n\tdimes = int(math.floor(amount / 10))\n\tdimes_left = int(amount % 10)\n\tresult = [];\n\tresult.append(dimes);\n\tresult.append(dimes_left)\n\treturn result\n\t\n\t\ndef checkNickels(amount):\n\n\tnickels = int(math.floor(amount / 5))\n\tnickels_left = int(amount % 5)\n\tresult = [];\n\tresult.append(nickels);\n\tresult.append(nickels_left)\n\treturn result\n\t\n\ndef checkPennies(amount):\n\n\tpennies = int(math.floor(amount / 1))\n\tpennies_left = int(amount % 1)\n\tresult = [];\n\tresult.append(pennies);\n\tresult.append(pennies_left)\n\treturn result\n\t\n\ndef output_results(coin_results):\n\n\tif coin_results[0] > 0:\n\t\tprint(\"Quarters:\", coin_results[0])\n\tif coin_results[1] > 0:\n\t\tprint(\"Dimes:\", coin_results[1])\n\tif coin_results[2] > 0:\n\t\tprint(\"Nickels:\", coin_results[2])\n\tif coin_results[3] > 0:\n\t\tprint(\"Pennies:\", coin_results[3])\n\t\n\t\ncoin_results = [0, 0, 0, 0]\n\t\namount = input(\"Enter Amount: \")\namount = float(amount)\nif amount > 25:\n\tquarter_result = checkQuarters(amount)\n\tquarters = quarter_result[0]\n\tcoin_results[0] = quarters\n\tamount = quarter_result[1]\n\t\nif amount > 10:\n\tdimes_result = checkDimes(amount)\n\tdimes = dimes_result[0]\n\tcoin_results[1] = dimes\n\tamount = dimes_result[1]\n\t\nif amount > 5:\n\tnickels_result = checkNickels(amount)\n\tnickels = nickels_result[0]\n\tcoin_results[2] = nickels\n\tamount = nickels_result[1]\n\t\nif amount > 0:\n\tpennies_result = checkPennies(amount)\n\tpennies = pennies_result[0]\n\tcoin_results[3] = pennies\n\tamount = pennies_result[1]\n\t\noutput_results(coin_results)","sub_path":"MakeChange/src/make_change.py","file_name":"make_change.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"221559195","text":"import os\nimport numpy as np\nfrom tqdm import tqdm\nimport cv2\nfrom PIL import Image\nimport sys\nfrom scipy.spatial import ConvexHull\n\n\ndef get_xy_floors(vertices, faces, dist_threshold=-0.98):\n z_faces = []\n z = np.array([0, 0, 1])\n faces_selected = []\n for face in tqdm(faces):\n normal = np.cross(\n vertices[face[2]] - vertices[face[1]], vertices[face[1]] - vertices[face[0]])\n dist = np.dot(normal, z) / np.linalg.norm(normal)\n if (dist_threshold is None) or ((dist_threshold is not None) and (dist < dist_threshold)):\n z_faces.append(vertices[face[0]][2])\n faces_selected.append(face)\n\n return np.array(z_faces), vertices, faces_selected\n\n\ndef gen_trav_map(vertices, faces, output_folder, add_clutter=False,\n trav_map_filename_format='floor_trav_{}.png',\n obstacle_map_filename_format='floor_{}.png'):\n \"\"\"\n Generate traversability maps.\n \"\"\"\n floors = [0.0]\n\n z_faces, vertices, faces_selected = get_xy_floors(vertices, faces)\n z_faces_all, vertices_all, faces_selected_all = get_xy_floors(\n vertices, faces, dist_threshold=None)\n\n xmin, ymin, _ = vertices.min(axis=0)\n xmax, ymax, _ = vertices.max(axis=0)\n\n max_length = np.max([np.abs(xmin), np.abs(ymin),\n np.abs(xmax), np.abs(ymax)])\n max_length = np.ceil(max_length).astype(np.int)\n\n wall_maps = gen_map(vertices, faces, output_folder,\n img_filename_format=obstacle_map_filename_format)\n wall_pts = np.array(np.where(wall_maps[0] == 0)).T\n wall_convex_hull = ConvexHull(wall_pts)\n wall_map_hull = np.zeros(wall_maps[0].shape).astype(np.uint8)\n cv2.fillPoly(wall_map_hull, [wall_convex_hull.points[wall_convex_hull.vertices][:, ::-1].reshape((-1, 1, 2)).astype(\n np.int32)], 255)\n\n for i_floor in range(len(floors)):\n floor = floors[i_floor]\n mask = (np.abs(z_faces - floor) < 0.2)\n faces_new = np.array(faces_selected)[mask, :]\n\n t = (vertices[faces_new][:, :, :2] + max_length) * 100\n t = t.astype(np.int32)\n\n floor_map = np.zeros((2 * max_length * 100, 2 * max_length * 100))\n\n cv2.fillPoly(floor_map, t, 1)\n\n if add_clutter is True: # Build clutter map\n mask1 = ((z_faces_all - floor) < 2.0) * \\\n ((z_faces_all - floor) > 0.05)\n faces_new1 = np.array(faces_selected_all)[mask1, :]\n\n t1 = (vertices_all[faces_new1][:, :, :2] + max_length) * 100\n t1 = t1.astype(np.int32)\n\n clutter_map = np.zeros(\n (2 * max_length * 100, 2 * max_length * 100))\n cv2.fillPoly(clutter_map, t1, 1)\n floor_map = np.float32((clutter_map == 0) * (floor_map == 1))\n\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))\n erosion = cv2.dilate(floor_map, kernel, iterations=2)\n erosion = cv2.erode(erosion, kernel, iterations=2)\n wall_map = wall_maps[i_floor]\n wall_map = cv2.erode(wall_map, kernel, iterations=1)\n erosion[wall_map == 0] = 0\n erosion[wall_map_hull == 0] = 0 # crop using convex hull\n\n cur_img = Image.fromarray((erosion * 255).astype(np.uint8))\n #cur_img = Image.fromarray(np.flipud(cur_img))\n cur_img.save(os.path.join(\n output_folder, trav_map_filename_format.format(i_floor)))\n\n\nINTERSECT_EDGE = 0\nINTERSECT_VERTEX = 1\n\n\nclass Plane(object):\n def __init__(self, orig, normal):\n self.orig = orig\n self.n = normal / np.linalg.norm(normal)\n\n def __str__(self):\n return 'plane(o=%s, n=%s)' % (self.orig, self.n)\n\n\ndef point_to_plane_dist(p, plane):\n return np.dot((p - plane.orig), plane.n)\n\n\ndef compute_triangle_plane_intersections(vertices, faces, tid, plane, dists, dist_tol=1e-8):\n \"\"\"\n Compute the intersection between a triangle and a plane\n Returns a list of intersections in the form\n (INTERSECT_EDGE, , ) for edges intersection\n (INTERSECT_VERTEX, , ) for vertices\n This return between 0 and 2 intersections :\n - 0 : the plane does not intersect the plane\n - 1 : one of the triangle's vertices lies on the plane (so it just\n \"touches\" the plane without really intersecting)\n - 2 : the plane slice the triangle in two parts (either vertex-edge,\n vertex-vertex or edge-edge)\n \"\"\"\n\n # TODO: Use an edge intersection cache (we currently compute each edge\n # intersection twice : once for each tri)\n\n # This is to avoid registering the same vertex intersection twice\n # from two different edges\n vert_intersect = {vid: False for vid in faces[tid]}\n\n # Iterate through the edges, cutting the ones that intersect\n intersections = []\n for e in ((faces[tid][0], faces[tid][1]),\n (faces[tid][0], faces[tid][2]),\n (faces[tid][1], faces[tid][2])):\n v1 = vertices[e[0]]\n d1 = dists[e[0]]\n v2 = vertices[e[1]]\n d2 = dists[e[1]]\n\n if np.fabs(d1) < dist_tol:\n # Avoid creating the vertex intersection twice\n if not vert_intersect[e[0]]:\n # point on plane\n intersections.append((INTERSECT_VERTEX, v1, e[0]))\n vert_intersect[e[0]] = True\n if np.fabs(d2) < dist_tol:\n if not vert_intersect[e[1]]:\n # point on plane\n intersections.append((INTERSECT_VERTEX, v2, e[1]))\n vert_intersect[e[1]] = True\n\n # If vertices are on opposite sides of the plane, we have an edge\n # intersection\n if d1 * d2 < 0:\n # Due to numerical accuracy, we could have both a vertex intersect\n # and an edge intersect on the same vertex, which is impossible\n if not vert_intersect[e[0]] and not vert_intersect[e[1]]:\n # intersection factor (between 0 and 1)\n # here is a nice drawing :\n # https://ravehgonen.files.wordpress.com/2013/02/slide8.png\n # keep in mind d1, d2 are *signed* distances (=> d1 - d2)\n s = d1 / (d1 - d2)\n vdir = v2 - v1\n ipos = v1 + vdir * s\n intersections.append((INTERSECT_EDGE, ipos, e))\n\n return intersections\n\n\ndef gen_map(vertices, faces, output_folder, img_filename_format='floor_{}.png'):\n xmin, ymin, _ = vertices.min(axis=0)\n xmax, ymax, _ = vertices.max(axis=0)\n\n max_length = np.max([np.abs(xmin), np.abs(ymin),\n np.abs(xmax), np.abs(ymax)])\n max_length = np.ceil(max_length).astype(np.int)\n\n floors = [0.0]\n print(floors)\n\n floor_maps = []\n\n for i_floor, floor in enumerate(floors):\n dists = []\n z = float(floor) + 0.5\n cross_section = []\n plane = Plane(np.array([0, 0, z]), np.array([0, 0, 1]))\n\n for v in vertices:\n dists.append(point_to_plane_dist(v, plane))\n\n for i in tqdm(range(len(faces))):\n res = compute_triangle_plane_intersections(vertices, faces,\n i, plane, dists)\n if len(res) == 2:\n cross_section.append((res[0][1], res[1][1]))\n\n floor_map = np.ones((2 * max_length * 100, 2 * max_length * 100))\n\n for item in cross_section:\n x1, x2 = (item[0][0]+max_length) * \\\n 100, (item[1][0]+max_length) * 100\n y1, y2 = (item[0][1]+max_length) * \\\n 100, (item[1][1]+max_length) * 100\n\n cv2.line(floor_map, (int(x1), int(y1)),\n (int(x2), int(y2)), color=(0, 0, 0), thickness=2)\n\n floor_maps.append(floor_map)\n cur_img = Image.fromarray((floor_map * 255).astype(np.uint8))\n #cur_img = Image.fromarray(np.flipud(cur_img))\n img_filename = img_filename_format.format(i_floor)\n cur_img.save(os.path.join(output_folder, img_filename))\n\n return floor_maps\n","sub_path":"igibson/utils/map_utils.py","file_name":"map_utils.py","file_ext":"py","file_size_in_byte":8011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"496650538","text":"import re\nimport os\n\nimport utils\n\n\ndef tokenize(s):\n \"\"\"\n Tokenize on parenthesis, punctuation, spaces and American units followed by a slash.\n\n We sometimes give American units and metric units for baking recipes. For example:\n * 2 tablespoons/30 milliliters milk or cream\n * 2 1/2 cups/300 grams all-purpose flour\n\n The recipe database only allows for one unit, and we want to use the American one.\n But we must split the text on \"cups/\" etc. in order to pick it up.\n \"\"\"\n\n s = _expand_unit_abbreviations(s)\n s = _normalize_us_uk_split(s)\n s = _identify_multi_unit_brackets(s)\n\n return filter(None, re.split(r'([,\\(\\)])?\\s*', utils.clumpFractions(s)))\n\n\ndef _expand_unit_abbreviations(s):\n s = re.sub(r'(\\d+)g\\.?', r'\\1 grams', s)\n s = re.sub(r'(\\d+)kg\\.?', r'\\1 kilograms', s)\n s = re.sub(r'(\\d+)oz\\.?', r'\\1 ounces', s)\n s = re.sub(r'(\\d+)lbs?\\.?', r'\\1 pounds', s)\n s = re.sub(r'(\\d+)ml\\.?', r'\\1 milliliters', s)\n s = re.sub(r'(\\d+)l\\.?', r'\\1 litres', s)\n s = re.sub(r'(\\d+)tsp\\.?', r'\\1 teaspoons', s)\n s = re.sub(r'(\\d+)tbsp\\.?', r'\\1 tablespoons', s)\n return s\n\n\ndef _normalize_us_uk_split(s):\n units = [\n 'tablespoon', 'teaspoon', 'pound', 'ounce', 'pint', 'gram', 'milliliter', 'kilogram', 'liter', 'litre', 'millilitre'\n ]\n for unit in units:\n s = s.replace(unit + '/', unit + ' ')\n s = s.replace(unit + 's/', unit + 's ')\n return s\n\ndef _identify_multi_unit_brackets(s):\n units = ['tablespoon', 'teaspoon', 'pound', 'ounce', 'pint', 'gram', 'milliliter', 'kilogram', 'liter', 'litre',\n 'millilitre', 'milliliter', 'fl oz', 'oz', 'lb', 'g', 'kg', 'ml', 'l']\n\n for unit in units:\n s = s.replace(' ' + unit + ')', 'x )')\n s = s.replace(' ' + unit + ' )', 'x )')\n s = s.replace(' ' + unit + 's)', 'x )')\n s = s.replace(' ' + unit + 's )', 'x )')\n\n s = re.sub('\\(\\s*[\\d\\s\\d/\\d]+\\s*[x]\\s*\\)', '', s) # deletes the alt unit bracket\n return s\n","sub_path":"ingredient_phrase_tagger/training/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"165401396","text":"import pygame\nimport os\n\n# Special code to center window\nos.environ['SDL_VIDEO_CENTERED'] = '1'\n\ndef main():\n # Settings\n FRAMES_PER_SECOND = 30\n RESOLUTION = WIDTH, HEGIHT = 800, 600\n WINDOWS_TITLE = 'Snake v1.0 by raz'\n \n # Initial Setup\n pygame.init()\n screen_surface = pygame.display.set_mode(RESOLUTION)\n pygame.display.set_caption(WINDOWS_TITLE)\n\n done = False\n clock = pygame.time.Clock()\n while not done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n\n # Delays until next frame\n clock.tick(FRAMES_PER_SECOND)\n pygame.quit()\n\nmain()","sub_path":"snake/snake01.py","file_name":"snake01.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"276335021","text":"import sys\nimport os\n\nimport logging\nfrom bioagents import Bioagent\nfrom indra.statements import Agent\nfrom .bmeg_agent import BMEGAgent\nfrom indra.sources.trips.processor import TripsProcessor\nfrom kqml import KQMLModule, KQMLPerformative, KQMLList, KQMLString, KQMLToken\n\n\nlogging.basicConfig(format='%(levelname)s: %(name)s - %(message)s',\n level=logging.INFO)\nlogger = logging.getLogger('BMEGA')\n\nclass BMEGModule(Bioagent):\n name = 'BMEGA'\n tasks = ['FIND-GENE-MUTATION-DATASET','FIND-MUTATION-FREQUENCY', 'FIND-COMMON-PHENOTYPES-FOR-GENES', 'FIND-DRUGS-FOR-MUTATION-DATASET', 'FIND-VARIANTS-FOR-GENES', 'SHOW-MUTATION-DATA', 'GET-VARIANT-INFO']\n\n def __init__(self, **kwargs):\n self.BA = BMEGAgent()\n # Call the constructor of KQMLModule\n super(BMEGModule, self).__init__(**kwargs)\n\n\n def send_display_oncoprint(self, oncoprint_data):\n content = KQMLList('display-oncoprint')\n\n content.sets('data', str(oncoprint_data))\n\n self.tell(content)\n\n def respond_show_mutation_data(self, content):\n \"\"\"Response content to show-mutation-data request\"\"\"\n gene_arg = content.get('GENE')\n\n\n if not gene_arg:\n self.make_failure('MISSING_MECHANISM')\n\n gene_names = _get_kqml_names(gene_arg)\n if not gene_names:\n return self.make_failure('MISSING_MECHANISM')\n gene_name = gene_names[0]\n\n disease_arg = content.get('DISEASE')\n if not disease_arg:\n return self.make_failure('MISSING_MECHANISM')\n\n disease_names = _get_kqml_names(disease_arg)\n if not disease_names:\n return self.make_failure('INVALID_DISEASE')\n\n disease_name = _sanitize_disase_name(disease_names[0])\n disease_abbr = self.BA.get_tcga_abbr(disease_name)\n if disease_abbr is None:\n return self.make_failure('INVALID_DISEASE')\n\n oncoprint_data = self.BA.find_variants_for_genes_cbio(gene_names, disease_abbr, \"tcga\")\n\n self.send_display_oncoprint(oncoprint_data)\n\n reply = KQMLList('SUCCESS')\n\n reply.sets('oncoprint', 'SUCCESS' if len(oncoprint_data) > 0 else 'FAILURE')\n\n\n\n return reply\n\n def respond_find_mutation_frequency(self, content):\n \"\"\"Response content to find-mutation-frequency request\"\"\"\n gene_arg = content.get('GENE')\n\n if not gene_arg:\n self.make_failure('MISSING_MECHANISM')\n\n gene_names = _get_kqml_names(gene_arg)\n\n if not gene_names:\n return self.make_failure('MISSING_MECHANISM')\n gene_name = gene_names[0]\n\n disease_arg = content.get('DISEASE')\n if not disease_arg:\n return self.make_failure('MISSING_MECHANISM')\n\n disease_names = _get_kqml_names(disease_arg)\n if not disease_names:\n return self.make_failure('INVALID_DISEASE')\n\n disease_name = _sanitize_disase_name(disease_names[0])\n disease_abbr = self.BA.get_tcga_abbr(disease_name)\n if disease_abbr is None:\n return self.make_failure('INVALID_DISEASE')\n\n result = self.BA.find_mutation_frequency(gene_name, disease_abbr)\n\n if not result:\n return self.make_failure('MISSING_MECHANISM')\n\n reply = KQMLList('SUCCESS')\n reply.sets('mutfreq', result)\n\n oncoprint_data = self.BA.find_variants_for_genes_cbio(gene_names, disease_abbr, \"tcga\")\n\n self.send_display_oncoprint(oncoprint_data)\n\n\n return reply\n\n def respond_find_variants_for_genes(self, content):\n \"\"\"Response content to find-variants-for-genes\"\"\"\n gene_arg = content.get('GENES')\n\n if not gene_arg:\n self.make_failure('MISSING_MECHANISM')\n\n gene_names = _get_kqml_names(gene_arg)\n if not gene_names:\n return self.make_failure('MISSING_MECHANISM')\n\n disease_arg = content.get('DISEASE')\n if not disease_arg:\n return self.make_failure('MISSING_MECHANISM')\n\n disease_names = _get_kqml_names(disease_arg)\n if not disease_names:\n return self.make_failure('INVALID_DISEASE')\n\n disease_name = _sanitize_disase_name(disease_names[0])\n disease_abbr = self.BA.get_tcga_abbr(disease_name)\n\n if disease_abbr is None:\n return self.make_failure('INVALID_DISEASE')\n\n result = self.BA.find_variants_for_genes_cbio(gene_names, disease_abbr, \"tcga\")\n\n if not result:\n return self.make_failure('MISSING_MECHANISM')\n\n reply = KQMLList('SUCCESS')\n reply.sets('variants', str(result))\n\n return reply\n\n\n\n def respond_find_drugs_for_mutation_dataset(self, content):\n genes_arg = content.get('GENES')\n\n if not genes_arg:\n return self.make_failure('MISSING_MECHANISM')\n\n gene_names = _get_kqml_names(genes_arg)\n\n if not gene_names:\n return self.make_failure('MISSING_MECHANISM')\n\n dataset_arg = content.gets('DATASET')\n\n if not dataset_arg:\n dataset_arg = \"CCLE\" # default cell line\n\n result = self.BA.find_drugs_for_mutation_dataset(gene_names, dataset_arg)\n\n if not result:\n return self.make_failure('NO_DRUGS_FOUND')\n\n reply = KQMLList('SUCCESS')\n\n drugs = _get_drugs_cljson(result)\n\n reply.set('drugs', drugs)\n\n return reply\n\n def respond_get_variant_info(self, content):\n # TODO: may need to be revised if considered to be used by clic in the future\n gene_arg = content.get('GENE')\n mutation_name = content.gets('MUTATION')\n\n gene_name = _get_kqml_names(gene_arg)[0]\n result = self.BA.get_variant_info(gene_name, mutation_name)\n\n if not result:\n return self.make_failure('NO_INFO_FOUND')\n\n reply = KQMLList('SUCCESS')\n\n reply.sets('info', str(result))\n\n return reply\n\n\ndef _sanitize_disase_name(name):\n \"\"\"Given a disease name returns the sanitized version of it\"\"\"\n sanitized_name = name.replace(\"-\", \" \").lower()\n return sanitized_name\n\ndef _get_kqml_names(kqmlList):\n \"\"\"Given a kqml list returns the names of sublists in the list\"\"\"\n if not kqmlList:\n return None\n\n arr = kqmlList.data;\n if len(arr) == 0:\n return []\n\n if not isinstance(arr[0], KQMLList):\n arr = [kqmlList]\n\n res = list(map(lambda kl: kl.gets('NAME'), arr))\n\n return res\n\ndef _get_drugs_cljson(drug_names):\n agents = list(map(lambda n: Agent(n, db_refs={'TYPE': 'ont::pharmacologic-substance'}), drug_names))\n return Bioagent.make_cljson(agents)\n\n\nif __name__ == \"__main__\":\n BMEGModule(argv=sys.argv[1:])\n","sub_path":"bmeg_agent/bmeg_module.py","file_name":"bmeg_module.py","file_ext":"py","file_size_in_byte":6665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"220206340","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 ('base', '0002_auto_20141221_0207'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='production',\n name='production_company',\n field=models.ForeignKey(blank=True, to='base.ProductionCompany', on_delete=models.CASCADE, help_text=b'Leave this field blank if the production is a one-person show.', null=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"base/migrations/0003_auto_20141221_0336.py","file_name":"0003_auto_20141221_0336.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"503182088","text":"import os\nimport sys\nimport json\nfrom time import sleep\nimport uuid\nimport errno\nimport random\nimport timeit\nimport datetime\nimport traceback\nfrom functools import partial\n\nimport requests\nimport psycopg2\nimport psycopg2.extras\nimport psycopg2.errors\n\nfrom app.rmv_scraper import RmvScraper\n\nfrom app import util, filters, general_constants, ranking, rmv_constants\nfrom travel import travel_time\n\nDEBUG = os.environ.get(\"DEBUG\").lower() == 'true' or False\nMAX_USER_RESULTS = int(os.environ.get(\"MAX_USER_RESULTS\"))\n\nUSER = 'test_user'\nNEW_RUN = True\n\nWEBFLOW_COLLECTION_ID = \"5e62aadc51beef34cfbc64d8\"\n\n# ------------------------- // -------------------------\n\nUSER_CONFIG_PATH = './users/{}/input/user_config.json'.format(USER)\nUSER_OUTPUT_DATA_PATH = './users/{}/output/'.format(USER)\nUSER_ALL_CACHE_FILE = USER_OUTPUT_DATA_PATH + '.lastrunall'\nUSER_FILTER_CACHE_FILE = USER_OUTPUT_DATA_PATH + '.lastrunfiltered'\n\n\ndef new_search(config):\n print(\"This is a new run so going to the Internet to get deets ...\")\n start = timeit.default_timer()\n rmv = RmvScraper(config)\n try:\n rmv_properties = rmv.search_parallel()\n\n except KeyError as e:\n print(\"The config file is malformed: {} does not exist\".format(e))\n exit()\n\n end = timeit.default_timer()\n print(\"It took {} seconds to get back all deets from the Internet\".format(end - start))\n\n return rmv_properties\n\n\ndef get_prev_filtered_props_id(user_uuid: uuid.UUID):\n get_prev_results_query = \"\"\"\n SELECT website_unique_id, score FROM filtered_properties \n WHERE user_uuid = %s\n \"\"\"\n\n with psycopg2.connect(general_constants.DB_URL, sslmode='allow') as conn:\n with conn.cursor() as curs:\n curs.execute(get_prev_results_query, (user_uuid,))\n prev_filtered_properties = {x[0]: x[1] for x in curs.fetchall()}\n\n return prev_filtered_properties\n\n\ndef remove_duplicates(user_uuid: uuid.UUID, curr_properties_list: list):\n print(\"Identifying any properties from previous runs that have the same scores so that these can be discarded ...\")\n\n try:\n indexed_curr_properties = {x[rmv_constants.RmvPropDetails.rmv_unique_link.name]: x for x in\n curr_properties_list}\n\n prev_filtered_properties_id_score = get_prev_filtered_props_id(user_uuid)\n curr_filtered_properties_id_score = {x[rmv_constants.RmvPropDetails.rmv_unique_link.name]: x[\"score\"]\n for x in curr_properties_list}\n duplicate_properties_id = []\n\n for k, v in curr_filtered_properties_id_score.items():\n if k in prev_filtered_properties_id_score and v == prev_filtered_properties_id_score[k]:\n duplicate_properties_id.append(k)\n\n except (ValueError, KeyError):\n print(traceback.format_exc(), file=sys.stderr)\n\n # This is because sometimes code goes through the same RMV ID twice possibly because RMV returns same property\n # for different areas. This is guaranteed positive or 0 since indexed object will be unique\n # through dict construction and set is unique\n curr_properties_duplicates = len(curr_properties_list) - len(indexed_curr_properties)\n\n # duplicate_properties_id = curr_filtered_properties_id.intersection(prev_filtered_properties_id)\n unique_properties = []\n for x in indexed_curr_properties:\n try:\n if x not in duplicate_properties_id:\n unique_properties.append(indexed_curr_properties[x])\n # unique_properties = [list(x.values())[0] for x in indexed_curr_properties_list\n # if x not in duplicate_properties_id]\n except Exception:\n print(traceback.format_exc(), file=sys.stderr)\n print(\"Remove duplicates - CULPRIT: {}\".format(x))\n continue\n\n # for each in indexed_curr_properties_list:\n # if list(each.keys())[0] not in duplicate_properties_id:\n # unique_properties.append(list(each.values())[0])\n #\n # for prop_id in duplicate_properties_id:\n # for each in indexed_curr_properties_list:\n # if prop_id in each.keys():\n # indexed_curr_properties_list.pop()\n\n # for i, each in enumerate(curr_properties_list):\n # for k, v in each.items():\n # if k == rmv_constants.RmvPropDetails.rmv_unique_link.name:\n # if v in duplicate_properties_id:\n # del curr_properties_list[i]\n # break\n\n print(\"Removed {} duplicates from previous runs\".format(len(duplicate_properties_id) + curr_properties_duplicates))\n\n return unique_properties\n\n\ndef upsert_user_db(user_config):\n psycopg2.extras.register_uuid()\n user_uuid = util.gen_uuid()\n\n insert_user_query = \"\"\"\n INSERT INTO users \n (user_uuid, email, max_rent, min_beds, keywords, destinations, date_low, date_high, desired_cats, desired_nhoods, \n webflow_form_number)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n ON CONFLICT (email)\n DO UPDATE\n SET max_rent = EXCLUDED.max_rent,\n min_beds = EXCLUDED.min_beds,\n keywords = EXCLUDED.keywords,\n destinations = EXCLUDED.destinations,\n date_low = EXCLUDED.date_low,\n date_high = EXCLUDED.date_high,\n desired_cats = EXCLUDED.desired_cats,\n desired_nhoods = EXCLUDED.desired_nhoods,\n webflow_form_number = EXCLUDED.webflow_form_number\n RETURNING (user_uuid)\n \"\"\"\n\n insert_user_transaction_query = \"\"\"\n INSERT INTO user_transactions\n (user_uuid, insert_timestamp, payload)\n VALUES (%s, %s, %s)\n \"\"\"\n\n user = {\n \"user_uuid\": str(user_uuid),\n \"email\": user_config['email'],\n \"maxPrice\": user_config[\"maxPrice\"],\n \"minBedrooms\": user_config[\"minBedrooms\"],\n \"keywords\": ','.join([x.name for x in user_config['keywords']]),\n \"destinations\": json.dumps(user_config['destinations']),\n \"date_low\": user_config['date_low'],\n \"date_high\": user_config['date_high'],\n \"desired_cats\": ','.join([x.name for x in user_config['desired_cats']]),\n \"desired_nhoods\": ','.join([x for x in user_config['desired_areas']]),\n \"webflow_form_number\": user_config[\"webflow_form_number\"]\n }\n\n with psycopg2.connect(general_constants.DB_URL, sslmode='allow') as conn:\n with conn.cursor() as curs:\n curs.execute(insert_user_query, tuple([*user.values()]))\n user_uuid = curs.fetchone()[0]\n curs.execute(insert_user_transaction_query,\n (user_uuid,\n datetime.datetime.strftime(datetime.datetime.now(), \"%Y-%m-%d %H:%M:%S\"),\n json.dumps(user)))\n\n print(\"Stored/updated user details with email {} in DB. UUID is {}\".format(user_config['email'], user_uuid))\n\n return user_uuid\n\n\ndef standardise_filtered_listing(user_uuid: uuid.UUID, filtered_listing: dict):\n return {\n \"user_uuid\": user_uuid,\n \"prop_uuid\": filtered_listing['prop_uuid'],\n \"website_unique_id\": filtered_listing[rmv_constants.RmvPropDetails.rmv_unique_link.name],\n \"url\": filtered_listing[rmv_constants.RmvPropDetails.url.name],\n \"date_sent_to_user\": datetime.datetime.strftime(datetime.datetime.now(), \"%Y-%m-%d %H:%M:%S\"),\n \"avg_travel_time_transit\": filtered_listing['avg_travel_time_transit'],\n \"avg_travel_time_walking\": filtered_listing['avg_travel_time_walking'],\n \"avg_travel_time_bicycling\": filtered_listing[\"avg_travel_time_bicycling\"],\n \"avg_travel_time_driving\": filtered_listing[\"avg_travel_time_driving\"],\n \"augment\": json.dumps(filtered_listing['augment']),\n \"score\": filtered_listing[\"score\"]\n }\n\n\ndef get_webflow_users():\n url = \"https://api.webflow.com/collections/5e9cb6cb572a494febd4efb3/items\"\n\n headers = {\n \"Authorization\": \"Bearer {}\".format(os.environ['WEBFLOW_API_KEY']),\n \"accept-version\": \"1.0.0\",\n \"Content-Type\": \"application/json\"\n }\n\n user_mapping = {}\n try:\n r = requests.get(url, headers=headers)\n r.raise_for_status()\n data = r.json()\n\n for each in data['items']:\n user_mapping[int(each[\"name\"])] = each[\"_id\"]\n\n except requests.exceptions.HTTPError as e:\n raise e\n\n return user_mapping\n\n\ndef get_tube_stops_cms_items():\n url = \"https://api.webflow.com/collections/5eaf0803a0d3e484ca69b0db/items\"\n\n headers = {\n \"Authorization\": \"Bearer {}\".format(os.environ['WEBFLOW_API_KEY']),\n \"accept-version\": \"1.0.0\",\n \"Content-Type\": \"application/json\"\n }\n\n r = requests.get(url, headers=headers)\n\n tube_stop_collection_id_mapping = {}\n\n if r.status_code == 200:\n data = r.json()\n for each in data['items']:\n tube_stop_collection_id_mapping[each['name']] = each['_id']\n total_results = data['total']\n if total_results > data[\"count\"]:\n iters = int(total_results / data[\"count\"])\n for i in range(1, iters + 1):\n r = requests.get(url, headers=headers, params={\"offset\": i * 100})\n if r.status_code == 200:\n data = r.json()\n for each in data['items']:\n tube_stop_collection_id_mapping[each['name']] = each['_id']\n\n return tube_stop_collection_id_mapping\n\n\ndef write_webflow_cms(final_properties_list, webflow_user_mapping, user_config):\n tube_stop_collection_id_mapping = get_tube_stops_cms_items()\n\n webflow_db_mapping_query = \"\"\"\n INSERT INTO properties_cms_mapping \n (prop_uuid, webflow_cms_id)\n VALUES (%s, %s)\n \"\"\"\n\n image_indices = random.sample(\n [x for x in range(0, len(final_properties_list[rmv_constants.RmvPropDetails.image_links.name]))], 4)\n\n headers = {\n \"Authorization\": \"Bearer {}\".format(os.environ['WEBFLOW_API_KEY']),\n \"accept-version\": \"1.0.0\",\n \"Content-Type\": \"application/json\"\n }\n\n payload = {\n \"fields\": {\n \"_archived\": False,\n \"_draft\": False,\n \"name\": final_properties_list[rmv_constants.RmvPropDetails.rmv_unique_link.name],\n \"slug\": str(final_properties_list[rmv_constants.RmvPropDetails.prop_uuid.name]),\n \"full-address\": final_properties_list[rmv_constants.RmvPropDetails.street_address.name],\n \"original-ad-link\": final_properties_list[rmv_constants.RmvPropDetails.url.name],\n \"rent-pcm\": round(float(final_properties_list[rmv_constants.RmvPropDetails.rent_pcm.name]), 2),\n \"bedrooms\": int(final_properties_list[rmv_constants.RmvPropDetails.beds.name]),\n \"main-image\": final_properties_list[rmv_constants.RmvPropDetails.image_links.name][image_indices[0]],\n \"image-2\": final_properties_list[rmv_constants.RmvPropDetails.image_links.name][image_indices[1]],\n \"image-3\": final_properties_list[rmv_constants.RmvPropDetails.image_links.name][image_indices[2]],\n \"image-4\": final_properties_list[rmv_constants.RmvPropDetails.image_links.name][image_indices[3]],\n \"score\": final_properties_list['score'],\n \"user-email\": user_config['email'],\n \"user-email-2\": webflow_user_mapping[user_config[\"webflow_form_number\"]],\n \"tube-stop\": []\n }\n }\n\n for stop in final_properties_list[\"augment\"][\"nearby_station_zones\"]:\n tube_stop = list(stop.keys())[0] + \" \" + \"Underground Station\"\n try:\n if tube_stop in tube_stop_collection_id_mapping:\n payload[\"fields\"][\"tube-stop\"].append(tube_stop_collection_id_mapping[tube_stop])\n\n except KeyError:\n pass\n\n for i, each in enumerate(user_config['destinations']):\n dest = list(each.keys())[0]\n modes = [list(x.keys())[0] for x in each[dest]['modes']]\n commute_strings = []\n for mode in modes:\n commute_strings.append(\"{}min {}\".\n format(int(final_properties_list['augment']['travel_time'][i][dest][mode]), mode))\n\n final_commute_string = ', '.join(commute_strings).replace('transit', 'public transport')\n\n payload[\"fields\"][\"commute-{}\".format(i + 1)] = \"{}: {}\".format(dest, final_commute_string).capitalize()\n\n url = \"https://api.webflow.com/collections/{}/items?live=true\".format(WEBFLOW_COLLECTION_ID)\n\n r = requests.post(url, headers=headers, json=payload)\n\n if r.status_code == 200:\n print(\"Successfully added property ID {} in CMS\".\n format(final_properties_list[rmv_constants.RmvPropDetails.rmv_unique_link.name]))\n content = json.loads(r.content)\n\n with psycopg2.connect(general_constants.DB_URL, sslmode='allow') as conn:\n with conn.cursor() as curs:\n curs.execute(webflow_db_mapping_query,\n (final_properties_list[rmv_constants.RmvPropDetails.prop_uuid.name], content['_id']))\n try:\n if int(r.headers['X-RateLimit-Remaining']) <= 1: # 1 instead of 0 because of bug in Webflow API\n print(\"Going to sleep for 70s to reset Webflow rate limit ...\")\n sleep(70) # Sleep for 60s before making new requests to Webflow\n except KeyError:\n pass\n\n else:\n # TODO: the error occurs when rent-pcm = inf. Need to fix this so these props don't make it through the pipeline\n print(\"An error occurred for property ID {} writing to CMS: {}\".format(\n final_properties_list[rmv_constants.RmvPropDetails.rmv_unique_link.name], r.content))\n print(\"CULPRIT: {}\".format(payload))\n\n\ndef update_prop_status(prop_id, status):\n get_cms_item_id_query = \"\"\"\n SELECT webflow_cms_id FROM properties_cms_mapping \n WHERE prop_uuid = %s\n \"\"\"\n\n update_property_status_query = \"\"\"\n UPDATE filtered_properties \n SET user_favourites = %s\n WHERE prop_uuid = %s\n RETURNING website_unique_id\n \"\"\"\n\n with psycopg2.connect(general_constants.DB_URL, sslmode='allow') as conn:\n with conn.cursor() as curs:\n curs.execute(get_cms_item_id_query, (prop_id,))\n cms_item_id = curs.fetchone()\n curs.execute(update_property_status_query, (status, prop_id))\n website_id = curs.fetchone()[0]\n print(\"Updated status of property {} in DB to {}\".format(website_id, status))\n\n url = \"https://api.webflow.com/collections/{}/items/{}?live=true\".format(WEBFLOW_COLLECTION_ID, cms_item_id[0])\n\n headers = {\n \"Authorization\": \"Bearer {}\".format(os.environ['WEBFLOW_API_KEY']),\n \"accept-version\": \"1.0.0\",\n \"Content-Type\": \"application/json\"\n }\n\n payload = {\n \"fields\": {\n \"user-rating\": status\n }\n }\n r = requests.patch(url, headers=headers, json=payload)\n\n if r.status_code == 200:\n print(\"Updated status of property {} in CMS to {}\".format(website_id, status))\n else:\n print(\"An error occurred updating status of property {} in CMS: {}\".format(website_id, json.loads(r.content)))\n\n\ndef main(config):\n user_uuid = upsert_user_db(config)\n if NEW_RUN:\n rmv_properties = new_search(config)\n else:\n try:\n with open(USER_ALL_CACHE_FILE, 'r') as f:\n backup_file = f.read()\n print(\"This is a re-run so reading deets from backup file: {}\".format(backup_file))\n rmv_properties = util.csv_reader(backup_file)\n except FileNotFoundError as e:\n print(\"{}. Quitting now ...\".format(e))\n exit(errno.ENOENT)\n\n # Filtering properties\n lower_threshold = datetime.datetime.strptime(config['date_low'], \"%Y-%m-%d %H:%M:%S\") - datetime.timedelta(days=5)\n upper_threshold = datetime.datetime.strptime(config['date_high'], \"%Y-%m-%d %H:%M:%S\") + datetime.timedelta(days=5)\n\n images_threshold = 4\n min_rent_factor = 0.55\n\n properties_to_filter = rmv_properties\n while True:\n print(\"Filtering criteria: Images Threshold: {}. Min Rent Factor: {}\".format(images_threshold, min_rent_factor))\n filters_to_use = [partial(filters.enough_images_filter, threshold=images_threshold),\n partial(filters.date_available_filter,\n lower_threshold=datetime.datetime.strftime(lower_threshold, \"%Y-%m-%d %H:%M:%S\"),\n upper_threshold=datetime.datetime.strftime(upper_threshold, \"%Y-%m-%d %H:%M:%S\")),\n partial(filters.min_rent_filter, threshold=min_rent_factor * config['maxPrice'])]\n\n print(\"Filtering properties now ...\")\n for i, f in enumerate(filters_to_use):\n filtered_properties = [x for x in properties_to_filter if f(x)]\n print(\"Step {} Filter: Removed {} properties\".format(i, len(properties_to_filter) - len(filtered_properties)))\n properties_to_filter = filtered_properties\n\n # filtered_properties = list(filter(lambda x: all(f(x) for f in filters_to_use), rmv_properties))\n print(\"Retained {} properties after filtering\".format(len(filtered_properties)))\n\n if len(filtered_properties) <= MAX_USER_RESULTS:\n break\n\n if images_threshold < 6:\n images_threshold += 1\n\n if min_rent_factor < 0.8:\n min_rent_factor += 0.05\n\n if images_threshold > 6 or min_rent_factor > 0.8:\n break\n\n print(\"Updating filtering criteria ...\")\n\n insert_many_filtered_prop_query = \"\"\"\n INSERT into filtered_properties \n (user_uuid, prop_uuid, website_unique_id, url, date_sent_to_user, \n avg_travel_time_transit, avg_travel_time_walking, \n avg_travel_time_bicycling, avg_travel_time_driving,\n augment, score)\n VALUES %s\n ON CONFLICT (user_uuid, website_unique_id)\n DO NOTHING\n \"\"\"\n\n insert_many_zone_address_query = \"\"\"\n UPDATE property_listings\n SET (street_address, zone_best_guess) = (data.street_address, data.zone_best_guess)\n FROM (VALUES %s) AS data(street_address, zone_best_guess, prop_uuid)\n WHERE property_listings.prop_uuid = data.prop_uuid\n \"\"\"\n\n # Score properties before removing duplicates incase scoring has changed\n property_scorer = ranking.PropertyScorer()\n print(\"Scoring properties now ...\")\n [x.update(\n {\"score\": property_scorer.score(x, config['desired_areas'], config['desired_cats'], config['keywords'])})\n for x in filtered_properties]\n\n # Remove duplicates\n filtered_properties = remove_duplicates(user_uuid, filtered_properties)\n\n if filtered_properties:\n sorted_filtered_properties = sorted(filtered_properties, key=lambda k: k['score'], reverse=True)\n top_results = sorted_filtered_properties[:MAX_USER_RESULTS]\n # no list comprehension needed for commute times because GMAPS API can take in 25 x 25 (origins x destinations)\n print(\"Getting travel times and zones for properties now ...\")\n travel_time.get_commute_times(top_results, [k for x in config['destinations'] for k in x.keys()])\n [travel_time.get_property_zone(x) for x in top_results]\n standardised_filtered_listing = [standardise_filtered_listing(user_uuid, x) for x in top_results]\n\n try:\n with psycopg2.connect(general_constants.DB_URL, sslmode='allow') as conn:\n with conn.cursor() as curs:\n # template = \"%(user_uuid)s,%(prop_uuid)s,%(website_unique_id)s,%(url)s,\" \\\n # \"%(date_sent_to_user)s,%(avg_travel_time_transit)s,\" \\\n # \"%(avg_travel_time_walking)s,%(avg_travel_time_bicycling)s,\" \\\n # \"%(avg_travel_time_driving)s,%(augment)s,%(score)s\"\n # print(curs.mogrify(template, standardised_filtered_listing[0]))\n psycopg2.extras.execute_values(curs, insert_many_filtered_prop_query,\n [tuple(x.values()) for x in standardised_filtered_listing],\n template=None)\n template = \"(%s::varchar, %s::int, %s)\"\n psycopg2.extras.execute_values(curs, insert_many_zone_address_query,\n [(x[rmv_constants.RmvPropDetails.street_address.name],\n x[rmv_constants.RmvPropDetails.zone_best_guess.name],\n x[rmv_constants.RmvPropDetails.prop_uuid.name])\n for x in top_results], template=template)\n print(\"Stored {} new filtered properties in DB.\".format(len(standardised_filtered_listing)))\n if not DEBUG:\n user_mapping = get_webflow_users()\n [write_webflow_cms(x, user_mapping, config) for x in top_results]\n else:\n print(\"Skipping writing to Webflow because DEBUG is {}\".format(DEBUG))\n\n except Exception as e:\n print(\"Could not store some properties in DB: {}\".format(e))\n print(traceback.format_exc(), file=sys.stderr)\n\n print(\"All done now! Thanks for running!\")\n\n else:\n print(\"FINAL RESULT: No new properties so not writing to DB. Thanks for running!\")\n\n\nif __name__ == '__main__':\n psycopg2.extras.register_uuid()\n # filtered_properties = {\n # 'description': \"Letting information:Date available:NowFurnishing:FurnishedLetting type:Long termReduced on \"\n # \"Rightmove: 13 March 2020 (28 minutes ago)Key featuresDouble BedroomsBalcony24 Hour \"\n # \"ConciergeCommunal Roof TerraceResidents RoomCommunal GardensCommunal 24hr GymFull description \"\n # \" This is a stunning apartment within the South Gardens development, the first of the \"\n # \"wider Elephant Park scheme. The apartment is set in the Baldwin Point tower.This apartment \"\n # \"comprises of two double bedrooms, a bathroom an open plan reception with a fitted kitchen \"\n # \"with Bosch appliances including a washer dryer and balcony. The apartment is finished to a \"\n # \"high internal specification including oak engineered wood flooring and underfloor heating \"\n # \"throughout. Other benefits of the building include a 24 hour concierge, communal gardens and \"\n # \"a communal roof terrace. South Gardens is perfectly located for transport links to the City, \"\n # \"the West End and beyond with a range of local bus routes, the tube and National Rail \"\n # \"services. The development features a residents gym, Communal Gardens, 24 hour concierge, \"\n # \"communal residents room and communal roof terrace.More information from this agentTo view \"\n # \"this media, please visit the on-line version of this page at \"\n # \"www.rightmove.co.uk/property-to-rent/property-67134849.html?premiumA=trueParticularsEnergy \"\n # \"Performance Certificate (EPC) graphsView EPC Rating Graph for this propertySee full size \"\n # \"version online\",\n # 'postcode': 'SE17 1AF',\n # 'geo_lat': '51.491705786609934',\n # 'geo_long': '-0.08592939071585458',\n # 'rmv_unique_link': '67134849',\n # 'rent_pcm': '2296.6666666666665',\n # 'beds': '2',\n # 'estate_agent': 'Gordon & Co', 'estate_agent_address': 'Strata Pavillion, 4 Walworth Road, London, SE1 6EB',\n # 'date_available': '2020-03-13 12:57:10',\n # 'image_links': [\n # 'https://media.rightmove.co.uk/dir/70k/69202/67134849/69202_ELE170658_L_IMG_01_0000_max_656x437.jpg',\n # 'https://media.rightmove.co.uk/dir/70k/69202/67134849/69202_ELE170658_L_IMG_02_0000_max_656x437.jpg',\n # 'https://media.rightmove.co.uk/dir/70k/69202/67134849/69202_ELE170658_L_IMG_03_0000_max_656x437.jpg',\n # 'https://media.rightmove.co.uk/dir/70k/69202/67134849/69202_ELE170658_L_IMG_04_0000_max_656x437.jpg',\n # 'https://media.rightmove.co.uk/dir/70k/69202/67134849/69202_ELE170658_L_IMG_05_0000_max_656x437.jpg',\n # 'https://media.rightmove.co.uk/dir/70k/69202/67134849/69202_ELE170658_L_IMG_06_0000_max_656x437.jpg',\n # 'https://media.rightmove.co.uk/dir/70k/69202/67134849/69202_ELE170658_L_IMG_07_0000_max_656x437.jpg',\n # 'https://media.rightmove.co.uk/dir/70k/69202/67134849/69202_ELE170658_L_IMG_08_0000_max_656x437.jpg'],\n # 'floorplan_links': [\n # 'https://media.rightmove.co.uk/dir/70k/69202/67134849/69202_ELE170658_L_FLP_01_0000_max_600x600.jpg',\n # 'https://media.rightmove.co.uk/dir/70k/69202/67134849/69202_ELE170658_L_FLP_01_0000_max_900x900.jpg',\n # 'https://media.rightmove.co.uk/dir/70k/69202/67134849/69202_ELE170658_L_FLP_01_0000_max_1350x1350.jpg'],\n # 'prop_uuid': '428bb0b2-852c-49df-9114-df660fee4622',\n # 'url': 'https://www.rightmove.co.uk/property-to-rent/property-67134849.html',\n # 'zone_best_guess': 1,\n # 'street_address': '1 Townsend St, London SE17 1HY, UK',\n # 'augment': {\n # 'travel_time': [\n # {\n # 'EC1R 0EB': {\n # 'transit': 38.2,\n # 'walking': 57.666666666666664,\n # 'bicycling': 19.216666666666665,\n # 'driving': 20.183333333333334\n # }\n # },\n # {\n # 'soho': {\n # 'transit': 30.0,\n # 'walking': 66.48333333333333,\n # 'bicycling': 21.933333333333334,\n # 'driving': 24.8\n # }\n # }],\n # 'nearby_station_zones': [{'Borough': '1'}]},\n # 'avg_travel_time_transit': 34.1,\n # 'avg_travel_time_walking': 62.075,\n # 'avg_travel_time_bicycling': 20.575,\n # 'avg_travel_time_driving': 22.491666666666667\n # }\n DEBUG = True\n try:\n print(\"Trying to open user {} config file from this location {}\".format(USER, USER_CONFIG_PATH))\n with open(USER_CONFIG_PATH, 'r') as data_file:\n config = json.load(data_file)\n except FileNotFoundError:\n print(\"Unable to find a config file for user {} at this location: {}. \"\n \"Please make sure the file exists at the right location before running the code again\"\n .format(USER, USER_CONFIG_PATH))\n exit(errno.ENOENT)\n\n get_tube_stops_cms_items()\n main(config)\n","sub_path":"potential_tenants/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":26946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"285499597","text":"\"\"\"\nProblem 2,3,4: Given an array of characters, give an algorithm for removing the duplicates.\n\nSolution: 1. Start with first element and replace it with last element if duplicate is found\n 2. Hash the elements and insert only unique elements in a diff. array\n\"\"\"\n\n\ndef remove_duplicate_1(A):\n for i in range(len(A)):\n for j in range(i+1, len(A)):\n if A[i] == A[j]:\n A[i], A[-1] = A[-1], A[i]\n A = A[:-1]\n break\n\n\ndef remove_duplicate_2(A):\n unique = []\n helper_set = set()\n for el in A:\n if el not in helper_set:\n unique.append(el)\n helper_set.add(el)\n\n print(unique)\n\n\n\n","sub_path":"karumanchi/Hashing/Remove duplicates from stirng.py","file_name":"Remove duplicates from stirng.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"634661192","text":"\n\nfrom pybrain.rl.agents.logging import LoggingAgent\nimport random\nfrom menu_model import SearchEnvironment\n#from menu_model_short import SearchEnvironment\nimport numpy as np\n\nclass GPSARSA_Agent(LoggingAgent):\n\n\n init_exploration = 1.0 # aka epsilon\n #exploration_decay = 0.10 # per episode\n\n\n def __init__(self, learner, **kwargs):\n LoggingAgent.__init__(self,9,1, **kwargs)\n self.learner = learner\n #self.reset()\n self.learning=True\n self.learner.dataset=self.history\n\n def _actionProbs(self, state):\n self.q_mean=[]\n self.q_cov=[]\n i=0\n for act in SearchEnvironment.actions :\n self.K=[]\n for i in range(self.learner.ret_dict().shape[0]):\n\n self.K=np.append(self.K,self.learner.kernel(self.learner.ret_dict()[i],np.append(state,act))) #k(s,a) with previous sequence\n self.K=np.reshape(self.K,(1,len(self.K)))\n cum_reward=np.reshape(self.learner.ret_reward(),(len(self.learner.ret_reward()),1))\n #print('inv dot',np.dot(self.learner.inv,cum_reward))\n self.q_mean=np.append(self.q_mean,np.dot(self.K,np.dot(self.learner.inv,cum_reward))) #q mean list for every action\n self.q_cov=np.append(self.q_cov,self.learner.kernel(np.append(state,act),np.append(state,act))-np.dot(np.dot(self.K,self.learner.inv),np.dot(self.learner.ret_h(),self.K.T))) #q_covariance for every action\n\n print(max(self.q_mean),np.argmax(self.q_mean))\n print(min(self.q_mean),np.argmin(self.q_mean))\n\n return self.q_mean,self.q_cov\n\n def getAction(self):\n action=None\n if (self.learner.ret_dict() is not None):\n q_meanlist, q_covlist = self._actionProbs(self.lastobs)\n #print('mean',q_meanlist)\n for some in q_meanlist:\n if some>10000 or some<-10000:\n #print('error',q_meanlist)\n raise ValueError('wtf')\n if (random.random() > self.init_exploration):\n action = SearchEnvironment.actions[np.argmax(q_meanlist)]\n\n else:\n action = random.choice(SearchEnvironment.actions)\n #action=SearchEnvironment.actions[np.argmax(q_covlist)]\n else:\n action=random.choice(SearchEnvironment.actions)\n\n self.lastaction = action\n return action\n\n def integrateObservation(self, obs):\n\n LoggingAgent.integrateObservation(self, obs)\n\n def reset(self):\n LoggingAgent.reset(self) #clear dataset sequences\n\n self.learner.reset()\n\n self.newEpisode()\n\n def newEpisode(self):\n \"\"\" Indicate the beginning of a new episode in the training cycle. \"\"\"\n if self.logging:\n self.history.newSequence()\n\n\n def learn(self):\n if not self.learning:\n return\n self.learner.learn()\n\n\n","sub_path":"agents/baseline_agent_menu.py","file_name":"baseline_agent_menu.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"79887331","text":"import time\n\nfrom metasdk import MetaApp\n\nMETA = MetaApp()\nlog = META.log\n\n# Установка таской для отладки кода\nMETA.worker.debug_tasks = [{\n \"data\": {\n \"username\": \"Artur\"\n }\n}]\n\n\n@META.worker.single_task\ndef main(task):\n log.info('Hello task')\n time.sleep(10)\n\n data = task['data']\n username_ = data.get('username', '%USERNAME%')\n log.info('Hello task', {'welcome': 'Hello, ' + username_, 't': task})\n time.sleep(10)\n","sub_path":"metasdk/examples/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"8063603","text":"\nimport serial\nfrom time import sleep\n\nprint(\"arduino serial\")\n\nport='/dev/ttyUSB0' #메 뉴 > 도 구> 시리얼포 트\nbaudrate=9600\nse = serial.Serial(port,baudrate)\n\nwhile True:\t\n print(\"input num:\")\n # var = input()\n num = '1'\n se.write(num.encode())\n # se.write(var.encode())\n se.flush()\n sleep(0.5)\n","sub_path":"serialPy/serialWrite.py","file_name":"serialWrite.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"547645252","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, api\n\nclass product_barcode_wizard(models.TransientModel):\n _name = 'product.barcode.wizard'\n\n col = fields.Char(string=\"Columna\", required=False)\n row = fields.Char(string=\"Fila\",required=False)\n\n def print_barcode(self, cr, uid, ids, context=None):\n \"\"\"\n To get the date and print the report\n @return : return report\n \"\"\"\n if context is None:\n context = {}\n datas = {'ids': context.get('active_ids', [])}\n res = self.read(cr, uid, ids, ['col','row'], context=context)\n res = res and res[0] or {} \n datas['form'] = res\n return self.pool['report'].get_action(cr, uid, [], 'product_barcode.report_barcode_print_template', data=datas, context=context)\n","sub_path":"product_barcode/wizard/print_barcode_wizard.py","file_name":"print_barcode_wizard.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"127746510","text":"import math\nt=int(input())\nfor i in range(t):\n a1,b1,n1 = input().split()\n a=int(a1)\n b=int(b1)\n n=int(n1)\n m=1000000007\n if n<=10:\n x=((a**n)%m)+((b**n)%m)\n y=abs(a-b)\n z=math.gcd( x, y )\n print (z)\n else:\n \n if a==b:\n print((pow(a,n,m)+pow(b,n,m))%m)\n else:\n x=(pow(a,n,abs(a-b))+pow(b,n,abs(a-b)))%abs(a-b)\n y=abs(a-b)\n z=(math.gcd(x,y))%abs(a-b)\n print(z)\n","sub_path":"gagan42/Practice/GCDMOD.py","file_name":"GCDMOD.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"357387395","text":"from pytun import TunTapDevice\n\n\ndef read(tun):\n while True:\n try:\n buf = tun.read(tun.mtu)\n tun.write(buf)\n print(buf)\n except KeyboardInterrupt:\n print('Stop')\n break\n\n\nif __name__ == '__main__':\n tun = TunTapDevice(name='tun_device')\n print('Tun name:', tun.name)\n tun.addr = '192.168.137.1'\n tun.dstaddr = '192.168.137.10'\n tun.netmask = '255.255.255.0'\n tun.mtu = 1500\n tun.persist(True)\n tun.up()\n\n read(tun)\n\n tun.close()\n","sub_path":"tun.py","file_name":"tun.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"310438489","text":"import pandas as pd\r\n#import matplotlib.pyplot as plt\r\nfrom sklearn import svm\r\n#import numpy as np\r\nfrom sklearn.decomposition import PCA\r\n\r\n\r\ntrain = pd.read_csv(\"train.csv\")\r\nX_test = pd.read_csv(\"test.csv\")\r\ny_train = train['label']\r\n#print(y_train)\r\nX_train = train.drop(labels = ['label'],axis = 1)\r\n#print(train)\r\n\r\n#train_data = np.array(X_train)\r\n#train_labels = np.array(y_train)\r\n\r\npca = PCA(n_components = 50,whiten=True)\r\npca.fit(X_train)\r\nX_train = pca.transform(X_train)\r\n\r\n\r\nprint (\"Training SVC Classifier...\")\r\nmodel = svm.SVC()\r\nmodel.fit(X_train,y_train)\r\n\r\n#test_data = np.array()\r\nX_test = pca.transform(X_test)\r\n\r\nprint (\"Scoring SVC Classifier...\")\r\nscore = model.predict(X_test);\r\nwith open('predict.csv', 'w') as writer:\r\n writer.write('\"ImageId\",\"Label\"\\n')\r\n count = 0\r\n for p in score:\r\n count += 1\r\n writer.write(str(count) + ',\"' + str(p) + '\"\\n')\r\nprint (\"Done:\\n\")\r\n","sub_path":"Machine Learning/Data Science/digit/digit.py","file_name":"digit.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"375090326","text":"# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-\n# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the datalad package for the\n# copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Primarily a smoke test for ls\n\n\"\"\"\n\n__docformat__ = 'restructuredtext'\n\nimport logging\n\nfrom os import makedirs\nfrom os.path import join as opj\nfrom ...api import clean\nfrom ...consts import (\n ARCHIVES_TEMP_DIR,\n ANNEX_TEMP_DIR,\n ANNEX_TRANSFER_DIR,\n SEARCH_INDEX_DOTGITDIR\n)\nfrom ...distribution.dataset import Dataset\nfrom ...support.annexrepo import AnnexRepo\nfrom ...utils import (\n chpwd,\n Path,\n swallow_outputs\n)\nfrom ...tests.utils import (\n assert_equal,\n assert_false,\n assert_status,\n assert_true,\n with_tempfile\n)\n\n\n@with_tempfile(mkdir=True)\ndef test_clean(d):\n AnnexRepo(d, create=True)\n ds = Dataset(d)\n assert_status('notneeded', clean(dataset=ds))\n\n archives_path = ds.pathobj / Path(ARCHIVES_TEMP_DIR)\n annex_tmp_path = ds.pathobj / Path(ANNEX_TEMP_DIR)\n annex_trans_path = ds.pathobj / Path(ANNEX_TRANSFER_DIR)\n index_path = ds.repo.dot_git / Path(SEARCH_INDEX_DOTGITDIR)\n\n # if we create some temp archives directory\n (archives_path / 'somebogus').mkdir(parents=True)\n res = clean(dataset=ds, return_type='item-or-list',\n result_filter=lambda x: x['status'] == 'ok')\n assert_equal(res['path'], str(archives_path))\n assert_equal(res['message'][0] % tuple(res['message'][1:]),\n \"Removed 1 temporary archive directory: somebogus\")\n assert_false(archives_path.exists())\n\n # relative path\n (archives_path / 'somebogus').mkdir(parents=True)\n (archives_path / 'somebogus2').mkdir(parents=True)\n with chpwd(d), swallow_outputs() as cmo:\n res = clean(return_type='item-or-list',\n result_filter=lambda x: x['status'] == 'ok')\n assert_equal(res['message'][0] % tuple(res['message'][1:]),\n \"Removed 2 temporary archive directories: somebogus, \"\n \"somebogus2\")\n assert_false(archives_path.exists())\n\n # and what about git annex temporary files?\n annex_tmp_path.mkdir(parents=True)\n (annex_tmp_path / \"somebogus\").write_text(\"load\")\n with chpwd(d):\n res = clean(return_type='item-or-list',\n result_filter=lambda x: x['status'] == 'ok')\n assert_equal(res['path'], str(annex_tmp_path))\n assert_equal(res['message'][0] % tuple(res['message'][1:]),\n \"Removed 1 temporary annex file: somebogus\")\n assert_false(annex_tmp_path.exists())\n\n (annex_trans_path / 'somebogus').mkdir(parents=True, exist_ok=True)\n with chpwd(d):\n res = clean(return_type='item-or-list',\n result_filter=lambda x: x['status'] == 'ok')\n assert_equal(res['path'], str(annex_trans_path))\n assert_equal(res['message'][0] % tuple(res['message'][1:]),\n \"Removed 1 annex temporary transfer directory: somebogus\")\n assert_false(annex_trans_path.exists())\n\n # search index\n index_path.mkdir(parents=True)\n (index_path / \"MAIN_r55n3hiyvxkdf1fi.seg, _MAIN_1.toc\").write_text(\"noop\")\n with chpwd(d):\n res = clean(return_type='item-or-list',\n result_filter=lambda x: x['status'] == 'ok')\n assert_equal(res['path'], str(index_path))\n assert_equal(res['message'][0] % tuple(res['message'][1:]),\n \"Removed 1 metadata search index file: \"\n \"MAIN_r55n3hiyvxkdf1fi.seg, _MAIN_1.toc\")\n assert_false(index_path.exists())\n\n # remove empty directories, too\n archives_path.mkdir(parents=True)\n with chpwd(d):\n res = clean(return_type='item-or-list',\n result_filter=lambda x: x['status'] == 'ok')\n assert_equal(res['path'], str(archives_path))\n assert_equal(res['message'][0] % tuple(res['message'][1:]),\n \"Removed empty temporary archive directory\")\n assert_false(archives_path.exists())\n\n annex_tmp_path.mkdir(parents=True)\n with chpwd(d):\n res = clean(return_type='item-or-list',\n result_filter=lambda x: x['status'] == 'ok')\n assert_equal(res['path'], str(annex_tmp_path))\n assert_equal(res['message'][0] % tuple(res['message'][1:]),\n \"Removed empty temporary annex directory\")\n assert_false(annex_tmp_path.exists())\n\n annex_trans_path.mkdir(parents=True)\n with chpwd(d):\n res = clean(return_type='item-or-list',\n result_filter=lambda x: x['status'] == 'ok')\n assert_equal(res['path'], str(annex_trans_path))\n assert_equal(res['message'][0] % tuple(res['message'][1:]),\n \"Removed empty annex temporary transfer directory\")\n assert_false(annex_trans_path.exists())\n\n index_path.mkdir(parents=True)\n with chpwd(d):\n res = clean(return_type='item-or-list',\n result_filter=lambda x: x['status'] == 'ok')\n assert_equal(res['path'], str(index_path))\n assert_equal(res['message'][0] % tuple(res['message'][1:]),\n \"Removed empty metadata search index directory\")\n assert_false(index_path.exists())\n","sub_path":"datalad/interface/tests/test_clean.py","file_name":"test_clean.py","file_ext":"py","file_size_in_byte":5480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"166584597","text":"#RELEASE: 0.0.1\n\nsupplies = {}\nexit_status = False\ndone = False\n\nwhile exit_status == False:\n print('1) Display available supplies')\n print('2) Add supplies')\n print('3) exit')\n choice = int(input('please enter your choice: '))\n if choice == 1:\n print(f\"{supplies} \\n\")\n continue\n elif choice == 2:\n supply_name_and_unit = input('enter supply name and unit: ')\n supply_qty = int(input('enter supply qty: '))\n supplies[supply_name_and_unit] = supply_qty\n #done = input('are you satisfied? y/n')\n #if done == 'y':\n # done == True\n # continue\n #else:\n # done == False\n elif choice == 3:\n print('thanks for useing the supply manager!')\n exit()\n\n\n","sub_path":"supplies.py","file_name":"supplies.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"220343232","text":"import os\nimport sqlite3\nimport pandas as pd\nfrom nempy import markets, historical_spot_market_inputs as hi\nfrom time import time\n\n# Create a list of the historical dispatch intervals to be used.\ndispatch_intervals = hi.datetime_dispatch_sequence(start_time='2020/01/02 00:00:00',\n end_time='2020/01/03 00:00:00')\n\n# Build a database of historical inputs if it doesn't already exist.\nif not os.path.isfile('historical_inputs.db'):\n con = sqlite3.connect('historical_inputs.db')\n\n # Create a data base manager.\n inputs_manager = hi.DBManager(connection=con)\n\n # This is the first time the database has been used so we need to add the tables.\n inputs_manager.create_tables()\n\n # Download the relevant historical data from http://nemweb.com.au/#mms-data-model and into the database.\n inputs_manager.DUDETAILSUMMARY.set_data(year=2020, month=1) # Unit information\n inputs_manager.BIDPEROFFER_D.add_data(year=2020, month=1) # historical volume bids\n inputs_manager.BIDDAYOFFER_D.add_data(year=2020, month=1) # historical price bids\n inputs_manager.DISPATCHLOAD.add_data(year=2020, month=1) # unit operating limits\n inputs_manager.DISPATCHREGIONSUM.add_data(year=2020, month=1) # historical demand\n inputs_manager.INTERCONNECTOR.set_data(year=2020, month=1) # Regions connected by interconnector\n inputs_manager.DISPATCHINTERCONNECTORRES.add_data(year=2020, month=1) # Interconnectors in each dispatch interval\n inputs_manager.INTERCONNECTORCONSTRAINT.set_data(year=2020, month=1) # Interconnector data\n inputs_manager.LOSSFACTORMODEL.set_data(year=2020, month=1) # Regional demand coefficients in loss functions\n inputs_manager.LOSSMODEL.set_data(year=2020, month=1) # Break points for linear interpolation of loss functions\n\n con.close()\n\n# Connect to the database of historical inputs\ncon = sqlite3.connect('historical_inputs.db')\ninputs_manager = hi.DBManager(connection=con)\n\n# List for saving inputs to.\noutputs = []\n\n# Create and dispatch the spot market for each dispatch interval.\nfor interval in dispatch_intervals:\n # Transform the historical input data into the format accepted by the Spot market class.\n # Unit info.\n DUDETAILSUMMARY = inputs_manager.DUDETAILSUMMARY.get_data(interval)\n DUDETAILSUMMARY = DUDETAILSUMMARY[DUDETAILSUMMARY['DISPATCHTYPE'] == 'GENERATOR']\n unit_info = hi.format_unit_info(DUDETAILSUMMARY)\n\n # Unit bids.\n BIDPEROFFER_D = inputs_manager.BIDPEROFFER_D.get_data(interval)\n BIDPEROFFER_D = BIDPEROFFER_D[BIDPEROFFER_D['BIDTYPE'] == 'ENERGY']\n volume_bids = hi.format_volume_bids(BIDPEROFFER_D)\n BIDDAYOFFER_D = inputs_manager.BIDDAYOFFER_D.get_data(interval)\n BIDDAYOFFER_D = BIDDAYOFFER_D[BIDDAYOFFER_D['BIDTYPE'] == 'ENERGY']\n price_bids = hi.format_price_bids(BIDDAYOFFER_D)\n\n # The unit operating conditions at the start of the historical interval.\n DISPATCHLOAD = inputs_manager.DISPATCHLOAD.get_data(interval)\n unit_limits = hi.determine_unit_limits(DISPATCHLOAD, BIDPEROFFER_D)\n\n # Demand on regional basis.\n DISPATCHREGIONSUM = inputs_manager.DISPATCHREGIONSUM.get_data(interval)\n regional_demand = hi.format_regional_demand(DISPATCHREGIONSUM)\n\n # Interconnector details.\n INTERCONNECTOR = inputs_manager.INTERCONNECTOR.get_data()\n INTERCONNECTORCONSTRAINT = inputs_manager.INTERCONNECTORCONSTRAINT.get_data(interval)\n interconnectors = hi.format_interconnector_definitions(INTERCONNECTOR,\n INTERCONNECTORCONSTRAINT)\n interconnector_loss_coefficients = hi.format_interconnector_loss_coefficients(INTERCONNECTORCONSTRAINT)\n LOSSFACTORMODEL = inputs_manager.LOSSFACTORMODEL.get_data(interval)\n interconnector_demand_coefficients = hi.format_interconnector_loss_demand_coefficient(LOSSFACTORMODEL)\n LOSSMODEL = inputs_manager.LOSSMODEL.get_data(interval)\n interpolation_break_points = hi.format_interpolation_break_points(LOSSMODEL)\n loss_functions = hi.create_loss_functions(interconnector_loss_coefficients, interconnector_demand_coefficients,\n regional_demand.loc[:, ['region', 'loss_function_demand']])\n\n # Create a market instance.\n market = markets.Spot()\n\n # Add generators to the market.\n market.set_unit_info(unit_info.loc[:, ['unit', 'region']])\n\n # Set volume of each bids.\n volume_bids = volume_bids[volume_bids['unit'].isin(list(unit_info['unit']))]\n market.set_unit_volume_bids(volume_bids.loc[:, ['unit', '1', '2', '3', '4', '5',\n '6', '7', '8', '9', '10']])\n\n # Set prices of each bid.\n price_bids = price_bids[price_bids['unit'].isin(list(unit_info['unit']))]\n market.set_unit_price_bids(price_bids.loc[:, ['unit', '1', '2', '3', '4', '5',\n '6', '7', '8', '9', '10']])\n\n # Set unit operating limits.\n market.set_unit_capacity_constraints(unit_limits.loc[:, ['unit', 'capacity']])\n market.set_unit_ramp_up_constraints(unit_limits.loc[:, ['unit', 'initial_output', 'ramp_up_rate']])\n market.set_unit_ramp_down_constraints(unit_limits.loc[:, ['unit', 'initial_output', 'ramp_down_rate']])\n\n # Set regional demand.\n market.set_demand_constraints(regional_demand.loc[:, ['region', 'demand']])\n\n # Create the interconnectors.\n market.set_interconnectors(interconnectors)\n\n # Create loss functions on per interconnector basis.\n market.set_interconnector_losses(loss_functions, interpolation_break_points)\n\n # Calculate dispatch.\n market.dispatch()\n\n print('Dispatch for interval {} complete.'.format(interval))\n\n # Save prices from this interval\n prices = market.get_energy_prices()\n prices['time'] = interval\n outputs.append(prices)\n\ncon.close()\nprint(pd.concat(outputs))\n# region price time\n# 0 NSW1 61.114147 2020/01/02 15:05:00\n# 1 QLD1 58.130015 2020/01/02 15:05:00\n# 2 SA1 72.675411 2020/01/02 15:05:00\n# 3 TAS1 73.013327 2020/01/02 15:05:00\n# 4 VIC1 68.778493 2020/01/02 15:05:00\n# .. ... ... ...\n# 0 NSW1 54.630861 2020/01/02 21:00:00\n# 1 QLD1 55.885854 2020/01/02 21:00:00\n# 2 SA1 53.038412 2020/01/02 21:00:00\n# 3 TAS1 61.537939 2020/01/02 21:00:00\n# 4 VIC1 57.040000 2020/01/02 21:00:00\n#\n# [360 rows x 3 columns]\n","sub_path":"examples/recreating_historical_dispatch.py","file_name":"recreating_historical_dispatch.py","file_ext":"py","file_size_in_byte":6455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"406802161","text":"\"\"\"Ejercicio 12:\nEscribe un programa que lea dos cadenas y devuelva el prefijo común más largo de\nambas. Ejemplo: las cadenas \"politécnico\" y \"polinización\" tienen como prefijo común más\nlargo a la cadena \"poli\".\"\"\"\n\n\ndef encontrar_prefijo (pal1,pal2):\n prefijo =\"\"\n for l1,l2 in zip(pal1,pal2):\n #print(l1,l2)\n if l1 == l2:\n prefijo=prefijo + l1\n else:\n break\n return prefijo \n \n\npalabra1 = input(\"Ingrese su palabra \")\npalabra2 = input (\"ingrese su palabra \")\n\nprefijo_comun = encontrar_prefijo(palabra1,palabra2)\n\nprint(\"El prefijo de las palabras es \", prefijo_comun)","sub_path":"eje12guia3.py","file_name":"eje12guia3.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"131971083","text":"from django.utils.translation import ugettext as _\n\nfrom article.forms import CommentForm\nfrom article.models import Article, Comments\nfrom django.shortcuts import render, get_object_or_404\nfrom django.views.generic import TemplateView\n\n# Create your views here.\ndef index(request):\n articles = Article.objects.all()\n if 'q' in request.GET:\n articles=articles.filter(title=request.GET['q'])\n return render(request, 'article/index.html', {'articles': articles})\n\nclass ArticleView(TemplateView):\n template_name = 'article/inner_page.html'\n def get_context_data(self, id, **kwargs):\n kwargs['form']= CommentForm()\n kwargs['article']= get_object_or_404(Article, id=id)\n\n def post(self, request, id):\n article = get_object_or_404(Article, id=id)\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.article = article\n form.save()\n\ndef get_article(request, id):\n article = get_object_or_404(Article, id=id)\n if request.method == 'POST':\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.article = article\n form.save()\n form = CommentForm()\n text = _('Hello')\n\n return render(request, 'article/inner_page.html', locals())\n","sub_path":"first_app/article/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"424835596","text":"import math\r\n\r\n\r\ndef num(l , length, d):\r\n res=0\r\n nl=l\r\n for j in range(length):\r\n res+=nl*(d**j)\r\n nl-=1\r\n \r\n return res\r\n \r\n\r\n\r\ndef solve():\r\n a=input()\r\n K=int(a.split()[0])\r\n C=int(a.split()[1])\r\n S=int(a.split()[2])\r\n\r\n if S*C < K :\r\n return 'IMPOSSIBLE'\r\n\r\n res=''\r\n n=1\r\n while(n*C < K):\r\n res+= str(num(n*C-1, C, K) + 1)\r\n res+=' '\r\n n+=1\r\n\r\n diff=n*C-K\r\n temp = num(K-1, C-diff , K)\r\n res+= str( (temp+1)*(K**diff) )\r\n \r\n return res\r\n\r\nT=int(input());\r\n\r\nfor t in range(1,T+1):\r\n print (\"Case #\" + str(t) + \": \" + solve())","sub_path":"codes/CodeJamCrawler/16_0_4_neat/16_0_4_nakahara_d.py","file_name":"16_0_4_nakahara_d.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"114254376","text":"import cv2\nimport pyopenpose as op\nimport numpy as np\nimport os\n\nparams = dict()\nparams[\"model_folder\"] = \"../../../openpose/models/\"\nparams[\"hand\"] = True\n\n# Starting OpenPose\nopWrapper = op.WrapperPython()\nopWrapper.configure(params)\nopWrapper.start()\ndatum = op.Datum()\n\npoint_left = []\npoint_right = []\nno_pose = []\n\nno_pose_path = \"../../../images_to_train/no_pose\"\npoint_l_path = \"../../../images_to_train/point_l_train/\"\npoint_r_path = \"../../../images_to_train/point_r_train/\"\n\nopWrapper = op.WrapperPython()\nopWrapper.configure(params)\nopWrapper.start()\n\ndef append_keypoints(folder, pose = \"None\"):\n keypoints = []\n for img in os.listdir(folder):\n img_process = cv2.imread(os.path.join(folder, img))\n datum.cvInputData = img_process\n opWrapper.emplaceAndPop([datum])\n p = np.append(datum.poseKeypoints, datum.handKeypoints[0])\n p = np.append(p, datum.handKeypoints[1])\n p = p.reshape(67, 3)\n if pose == 'left':\n point_left.append(p)\n elif pose == 'right':\n point_right.append(p)\n else:\n \tno_pose.append(p)\n\nappend_keypoints(point_l_path, 'left')\nappend_keypoints(point_r_path, 'right')\nappend_keypoints(no_pose_path)\n\npoint_left = np.asarray(point_left)\npoint_right = np.asarray(point_right)\nno_pose = np.asarray(no_pose)\nnp.save('gesture_data/point_left.npy', point_left)\nnp.save('gesture_data/point_right.npy', point_right)\nnp.save('gesture_data/no_pose.npy', no_pose)\n","sub_path":"vision/gesture/.ipynb_checkpoints/get_keypoints-checkpoint.py","file_name":"get_keypoints-checkpoint.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"36938773","text":"import copy\n\nfrom .resource import ResourceCrawler\n\n\nclass ArticleCrawler(ResourceCrawler):\n RESOURCE_TYPE = 'article'\n SOURCE_EXCHANGE = 'articles'\n SOURCE_KEY = 'crawl_article'\n RESULT_EXCHANGE = 'articles'\n\n async def crawl(self, article, contents, headers=None,\n result_producer=None):\n \"\"\"\n Currently just returns the contents of the article and does not do\n any further crawling for links.\n \"\"\"\n\n url = article['url']\n self.log.info(f'crawling article {url}')\n\n if result_producer is not None:\n # Send the article to be scraped (only for its canonical URL)\n article = copy.copy(article)\n article['url'] = article['canonical_url']\n article['contents'] = contents\n await result_producer.proxy.scrape_article(resource=article)\n\n # An article 'crawled' resource update message will be sent, along with\n # the article contents; see ResourceCrawler.crawl_resource\n return {'contents': contents}\n\n\nif __name__ == '__main__':\n ArticleCrawler.main()\n","sub_path":"backend/renewal_backend/crawlers/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"83871078","text":"import traceback\nimport sys\n\n\nclass ControlledOutput(object):\n \"\"\"docstring for ControlledOutput\"\"\"\n def __init__(self, protected_output, name, on_state=0, control_scale=1):\n super(ControlledOutput, self).__init__()\n\n self.output = protected_output\n self.name = name\n self.on_state = on_state\n self.control_scale = control_scale\n\n self.override = 'auto'\n self.off_state = 1\n if on_state == 1:\n self.off_state = 0\n\n self.info = None\n\n def get_state_str(self):\n if self.output.get_output() == self.on_state:\n return 'On'\n else:\n return 'Off'\n\n def get_mode(self):\n return self.override\n\n def mode_toggle(self):\n if self.override == 'off':\n self.mode_auto()\n else:\n self.mode_off\n\n def mode_off(self):\n self.override = 'off'\n\n def mode_auto(self):\n self.override = 'auto'\n\n def control(self, desired_value):\n self.info = None\n\n try:\n if (self.override == 'off'):\n self.output.set_output(self.off_state)\n self.info = 'Off Mode'\n elif (control_value * self.control_scale) > 10:\n self.output.set_output(self.on_state)\n else:\n self.output.set_output(self.off_state)\n except ProtectedOutputProtectedError as pe:\n print(str(pe))\n self.chiller_ssr_info = 'Wait minumum cycle time'\n except Exception as e:\n print(e)\n self.err = str(e)\n traceback.print_exc(file=sys.stdout)\n\n print(self.name, ':', self.get_state_str())\n\n def get_info(self):\n return self.info\n\n def get_raw(self):\n return self.output.get_output()\n","sub_path":"py/Brumulus/output/ControlledOutput.py","file_name":"ControlledOutput.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"568062513","text":"def universe_age():\n while True:\n try:\n age = int(input(\"Type in the age of the universe in years\"))\n if (age <= 0):\n print(\"Please enter a non-negative integer\")\n universe_age()\n else:\n print(age)\n break\n except ValueError:\n print(\"Please enter a numeric value\")\n except: # a blanket catch all to handle what might not e handled by exisitng handlers \n print(\"Some weird has happened here\")\n finally: # this will always be executed\n print(\"this will always get executed\")\n \nuniverse_age()\n","sub_path":"Modules_code/Module 3/simple_exception_handling.py","file_name":"simple_exception_handling.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"516365431","text":"import numpy as np\nimport tensorflow as tf\nimport keras.models\nfrom keras.models import Sequential\nfrom keras.layers import Activation, Dense\nfrom tensorflow.keras.callbacks import TensorBoard\nimport time\nimport random\n\n\nclass replay_memory():\n def __init__(self, size, obs_space,action_space):\n self.size = size\n self.obs_space = obs_space\n self.action_space = action_space\n self.obs = np.zeros((size, obs_space))\n self.actions = np.zeros(size)\n self.rewards = np.zeros(size)\n self.obs_nexts = np.zeros((size,obs_space))\n self.done = np.zeros(size)\n self.counter = 0\n self.replay_memory_full = False\n\n def add_experience(self, s, a ,r, s_, d):\n self.obs[self.counter] = s\n self.actions[self.counter] = a\n self.rewards[self.counter] = r\n self.obs_nexts[self.counter]=s_\n self.done[self.counter] = d\n self.counter +=1\n if self.counter == self.size :\n self.replay_memory_full = True\n self.counter =0\n def is_replay_memory_full(self):\n return self.replay_memory_full\n def print_replay_memory(self):\n if self.replay_memory_full:\n for i in range(0,self.size):\n print(i,self.obs[i],self.actions[i],self.rewards[i],self.obs_nexts[i],self.done[i])\n else:\n for i in range(0,self.counter):\n print(i,self.obs[i],self.actions[i],self.rewards[i],self.obs_nexts[i],self.done[i])\n\n def get_mini_batch(self, mini_batch_size):\n if mini_batch_size > self.size:\n return False\n else:\n if self.replay_memory_full == False :\n return False\n else:\n numbers = random.sample(range(0,self.size), mini_batch_size)\n s = np.zeros((mini_batch_size,self.obs_space))\n a = np.zeros(mini_batch_size)\n r = np.zeros(mini_batch_size)\n s_ = np.zeros((mini_batch_size,self.obs_space))\n d = np.zeros(mini_batch_size)\n for i in range(0,mini_batch_size):\n s[i]=self.obs[i]\n a[i]=self.actions[i]\n r[i]=self.rewards[i]\n s_[i]=self.obs_nexts[i]\n d[i]=self.done[i]\n return s,a,r,s_,d\n\n\nclass DQN_Agent():\n #self.Q_function = Q_function()\n #self.replay_memory = Replay\n#obs space and action space just wants their lengths, and they are all assumed to be discrete?\n def __init__(self, model):\n self.target_model = model\n\n def __init__(self,replay_size,obs_space, action_space, epsilon, gamma, alpha, activation_function,hidden_layers_dim):\n\n self.target_update_counter = 0\n self.epsilon = epsilon\n self.gamma = gamma\n self.alpha = alpha #learning learning_rate\n self.obs_space = obs_space\n self.action_space = action_space\n self.hidden_layers_dim = hidden_layers_dim\n self.activation_function = activation_function\n #datatype=[tf.int64]*(self.obs_space*2+2)\n #datatype.append(tf.bool)\n #self.replay_memory = tf.queue.FIFOQueue(REPLAY_MEMORY_SIZE, dtypes=datatype)#, shape=[obs_space,1,1,obs_space,1], shape = [self.obs_space, self.action_space,1, self.obs_space])\n #self.replay_memory = np.array((50,5))\n #self.replay_memory_counter = 0\n #self.replay_memory_full = False\n self.replay_memory = replay_memory(replay_size,obs_space,action_space)\n\n self.model = self.createNN()\n self.target_model = self.createNN()\n self.target_model.set_weights(self.model.get_weights())\n\n #self.tensorboard = ModifiedTensorBoard(log_dir=\"logs/{}-{}\".format('MODEL_NAME', int(time.time())))\n\n def createNN(self):\n model = Sequential()\n #print(\"!!!!!\", self.obs_space)\n model.add(Dense(self.hidden_layers_dim[0], input_dim=self.obs_space+self.action_space))\n for i in range(1,len(self.hidden_layers_dim)):\n if len(self.hidden_layers_dim)== len(self.activation_function): #If there are different activation functions for different hidden layers\n model.add(Dense(self.hidden_layers_dim[i], activation = self.activation_function[i]))\n else:\n model.add(Dense(self.hidden_layers_dim[i], activation = self.activation_function[0]))\n model.add(Dense(1, activation = None))\n model.compile(loss='mse', optimizer='sgd')#learning_rate = self.alpha,\n return model\n\n def merge_obs_action(self, obs, action):\n actions = np.zeros(self.action_space)\n for i in range(0, self.action_space):\n if action == i:\n actions[i]=1\n break\n obs = np.append(obs,actions)\n return obs\n\n def get_q_values_model(self, obs):\n #print(self.action_space)\n predictions = np.zeros(self.action_space)\n for i in range(0, self.action_space):\n input = self.merge_obs_action(obs,i)\n #print(input)\n #print(np.shape(input))\n predictions[i] = self.model.predict([[input]])\n return predictions\n def get_q_values_target_model(self, obs):\n #print(self.action_space)\n predictions = np.zeros(self.action_space)\n for i in range(0, self.action_space):\n input =self.merge_obs_action(obs,i)\n #print(np.shape(input))\n #print(input)\n predictions[i] = self.target_model.predict([[input]])\n return predictions\n\n\n def get_action_target_model(self, obs, action):\n return np.argmax(self.target_model.predict(self.merge_obs_action(obs,i)))\n\n def get_best_action_model(self, obs):\n return np.argmax(agent.get_q_values(obs))\n\n def update_replay_memory(self,sars_d):\n\n if self.replay_memory_counter == REPLAY_MEMORY_SIZE:\n if self.replay_memory_full == False:\n self.replay_memory_full = True\n self.replay_memory_counter = 0\n self.replay_memory[self.replay_memory_counter] = sars_d\n self.replay_memory_counter += 1\n\n\n\n\n def update_network_minibatch(self,s,a,r,s_,d):\n inputs = np.zeros((len(a),self.obs_space+self.action_space))\n y = np.zeros(len(a))\n for i in range(0,len(a)):\n inputs[i] = self.merge_obs_action(s[i],a[i])\n if d[i] :\n y[i]=r[i]\n else:\n y[i] = r[i] + self.gamma*np.max(self.get_q_values_model(s_[i]))\n self.model.fit(inputs,y, batch_size = len(a),epochs = 10, verbose = 0)\n\n def update_target_network(self):\n t_w = np.array(self.target_model.get_weights())\n m_w = np.array(self.model.get_weights())\n new_weights = 0.1*t_w + 0.9*m_w\n self.target_model.set_weights(new_weights)\n\n def save_target_model(self):\n self.target_model.save(\"Target_model040220_2\")\n print(\"Model saved.\")\n\n #self.target_model.set_weights(self.model.get_weights()*0.9 + self.target_model.get_weights()*0.1)\n\n\nclass Pretrained_Agent(DQN_Agent):\n def __init__(self,model, action_space):\n self.target_model = model\n self.action_space = action_space\nclass ModifiedTensorBoard(TensorBoard):\n\n # Overriding init to set initial step and writer (we want one log file for all .fit() calls)\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.step = 1\n self.writer = tf.summary.FileWriter(self.log_dir)\n\n # Overriding this method to stop creating default log writer\n def set_model(self, model):\n pass\n\n # Overrided, saves logs with our step number\n # (otherwise every .fit() will start writing from 0th step)\n def on_epoch_end(self, epoch, logs=None):\n self.update_stats(**logs)\n\n # Overrided\n # We train for one batch only, no need to save anything at epoch end\n def on_batch_end(self, batch, logs=None):\n pass\n\n # Overrided, so won't close writer\n def on_train_end(self, _):\n pass\n\n # Custom method for saving own metrics\n # Creates writer, writes custom metrics and closes writer\n def update_stats(self, **stats):\n self._write_logs(stats, self.step)\n","sub_path":"Agent_cont.py","file_name":"Agent_cont.py","file_ext":"py","file_size_in_byte":8230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"635910895","text":"class Rakutan:\n lecID = None\n facultyName = None\n lectureName = None\n groups = None\n credits = None\n accepted = []\n total = []\n url = None\n\n def __init__(self, lecID, fN, lN, g, c, a, t, u):\n self.lecID: int = lecID\n self.facultyName: str = fN\n self.lectureName: str = lN\n self.groups: str = g\n self.credits: int = c\n self.accepted: list = a\n self.total: list = t\n self.url: str = u\n\n @classmethod\n def from_dict(cls, dbRakutanDict: dict):\n return Rakutan(\n lecID=dbRakutanDict['id'],\n fN=dbRakutanDict['facultyname'],\n lN=dbRakutanDict['lecturename'],\n g=dbRakutanDict['groups'],\n c=dbRakutanDict['credits'],\n a=[dbRakutanDict['accept_prev'], dbRakutanDict['accept_prev2'], dbRakutanDict['accept_prev3']],\n t=[dbRakutanDict['total_prev'], dbRakutanDict['total_prev2'], dbRakutanDict['total_prev3']],\n u=dbRakutanDict['url']\n )\n\n @classmethod\n def from_list(cls, dbRakutanList: list):\n rakutanList = []\n for rakutan in dbRakutanList:\n rakutanList.append(cls.from_dict(rakutan))\n return rakutanList\n\n def to_dict(self):\n return {\n 'lecID': self.lecID,\n 'facultyName': self.facultyName,\n 'lectureName': self.lectureName,\n 'groups': self.groups,\n 'credits': self.credits,\n 'accepted': self.accepted,\n 'total': self.total,\n 'url': self.url\n }\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"283884127","text":"from collections import defaultdict\nimport numpy as np\n\n\"\"\"\nTest case #3\n\nSimple grid: nodes 'p', and factors 'f' (and labels count in [])\n\np0[3] <--(f0)--> p1[3] <--(f1)--> p2[3]\n | | |\n(f2) (f3) (f4)\n | | |\np3[3] <--(f5)--> p4[3] <--(f6)--> p5[3]\n\n\"\"\"\n\nnodes = range(6)\nfactors = range(7)\n\nedges = {\n factors[0]: [nodes[0], nodes[1]],\n factors[1]: [nodes[1], nodes[2]],\n factors[2]: [nodes[0], nodes[3]],\n factors[3]: [nodes[1], nodes[4]],\n factors[4]: [nodes[2], nodes[5]],\n factors[5]: [nodes[3], nodes[4]],\n factors[6]: [nodes[4], nodes[5]],\n}\n\nreversed_edges = defaultdict(list)\nfor key, val in edges.iteritems():\n for node in val:\n reversed_edges[node].append(key)\n\n\ndef theta_p(node):\n discrete_unaries_theta_p = {\n nodes[0]: np.array([0.3, 1.5, 0.2]),\n nodes[1]: np.array([1.1, 0.5, 1.2]),\n nodes[2]: np.array([0.4, 0.9, 0.3]),\n nodes[3]: np.array([0.9, 1.1, 1.8]),\n nodes[4]: np.array([0.6, 0.5, 1.2]),\n nodes[5]: np.array([0.3, 0.1, 0.2]),\n }\n return discrete_unaries_theta_p[node]\n\n\ndef theta_f(factor):\n return np.array([[0, 0.1, 0.1],\n [0.1, 0, 0.1],\n [0.1, 0.1, 0]])\n","sub_path":"applications/factorGraphs/tests/analytical_example_3_microgrid.py","file_name":"analytical_example_3_microgrid.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"8532015","text":"#!/usr/bin/env python \n# encoding: utf-8 \n\n\"\"\"\n测试 读取 投资登记簿excel文件入库\n\n1.2.3 投资登记簿 -- OD_INVESTMENT\n\n@version: v1.0 \n@author: Jeffrey Wang\n@license: Apache Licence \n@contact: shwangjj@163.com\n@file: Test_Load_GL0100.py \n@time: 2018/5/1 0001 下午 20:41 \n\"\"\"\n\nimport unittest\nimport os\nimport tools.DbUtlis as db\nfrom cmbc_ft.sourceDataDealer.INVESTMENT_Dealer import INVESTMENT_Dealer as dealer\n\nclass Test_Load_INVESTMENT(unittest.TestCase) :\n\n # table_name = \"OD_INVESTMENT\" + \"_temp\"\n\n table_name = \"OD_INVESTMENT\" + \"_temp\"\n\n def test_load_file_20180331(self):\n '''\n 测试,读取正确的文件情况\n\n :return:\n '''\n filename = os.path.dirname(os.path.abspath(__file__)) + \"//\" + \"1.2.3 投资登记簿.xls\";\n bizDate = \"20180331\"\n\n d = dealer()\n result = d.load_excel(bizdate=bizDate, filename=filename)\n self.assertEqual(711, result)\n\n # 检查汇总:\n self.assertEqual(711, db.db_count(table_name=self.table_name))\n\n # 抽查\n record = db.db_record(self.table_name, where_sql=\"trade_no='4848'\")\n self.assertIsNotNone(record)\n self.assertEqual(\"EUR\", record[16]) # 币种,Q\n self.assertEqual(\"20210320\", record[19]) # 债券到期日,T\n self.assertEqual(0.025, round(float(record[23]), 6)) # 票面利率,X\n self.assertEqual(\"按年付息\", record[12]) # 付息频率,M\n self.assertEqual(\"ACT/nACT\", record[15]) # 计息基准,P\n\n\n\n\n","sub_path":"src_testcase/test_sourceDataDealer/Test_Load_INVESTMENT.py","file_name":"Test_Load_INVESTMENT.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"333823435","text":"from term import Term\nfrom type_term import Type, BadTypingException\nfrom bool_term import Bool\n\nclass If(Term):\n\tdef __init__(self, name, subt = []):\n\t\tself.name = name\n\t\tself.subt = subt\n\t\tself.is_value = False\n\n\tdef small_step(self, mem):\n\t\tc = self.subt[0]\n\t\tt = self.subt[1]\n\t\te = self.subt[2]\n\t\tif c.is_value:\n\t\t\tif c == Bool('true'):\n\t\t\t\treturn t\n\t\t\telse:\n\t\t\t\treturn e\n\t\telse:\n\t\t\treturn If(self.name, [c.small_step(mem), t, e])\n\n\n\tdef free_vars(self):\n\t\tc = self.subt[0]\n\t\tt = self.subt[1]\n\t\te = self.subt[2]\n\t\treturn c.free_vars() | t.free_vars() | e.free_vars()\n\n\tdef subst(self, var, term):\n\t\tc = self.subt[0]\n\t\tt = self.subt[1]\n\t\te = self.subt[2]\n\t\treturn If(self.name, [c.subst(var, term), t.subst(var, term), e.subst(var, term)])\n\n\tdef check_type(self, env):\n\t\tc = self.subt[0]\n\t\tt = self.subt[1]\n\t\te = self.subt[2]\n\t\tif c.check_type(env) == Type('bool') and t.check_type(env) == e.check_type(env):\n\t\t\treturn t.check_type(env)\n\t\telse:\n\t\t\traise BadTypingException()\n","sub_path":"lang/terms/if_term.py","file_name":"if_term.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"115051556","text":"import boto3\nimport botocore\nimport json\n\nBUCKET_NAME = 'my-bucket' # replace with your bucket name\nKEY = 'my_image_in_s3.jpg' # replace with your object key\n\ns3 = boto3.resource('s3')\n\n\ndef read_stac_item(bucket_name, item_key):\n s3 = boto3.resource('s3')\n\n try:\n content_object = s3.Object(bucket_name, item_key)\n file_content = content_object.get()['Body'].read().decode('utf-8')\n json_content = json.loads(file_content)\n\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == \"404\":\n json_content = {}\n else:\n raise\n\n return json_content\n","sub_path":"app/s3_tools.py","file_name":"s3_tools.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"213089761","text":"import openpyxl as px\nfrom shutil import copyfile\nfrom os import path\nimport sys\nfrom analyzeGPA_okadai import AnalyzeGPA_Okadai\nfrom open_gradefile import open_gradefile\n\n\nclass ExportToExcelFile:\n def __init__(self):\n self.filename, updated_date, gpa_list = open_gradefile()\n if self.filename is not False:\n self.analyzegpa_okadai = AnalyzeGPA_Okadai(gpa_list)\n self.excel_filename =\\\n (\"gpaAnalyzer_{}\"\n \".xlsx\".format(updated_date.strftime('%Y%m%d')))\n self.excel_filename = path.join(path.dirname(self.filename),\n self.excel_filename)\n self.original_excel_filename =\\\n path.join(path.dirname(path.abspath(sys.argv[0])),\n \"../excel_file/gpaAnalyzer.xlsx\")\n\n def export_to_excel_file(self):\n if not self.filename:\n return False\n try:\n wb = px.load_workbook(self.original_excel_filename)\n ws_gpa_okadai = wb['Okadai']\n ws_gpa_summary = wb['Summary']\n\n year_completed_list, gpa_dict = self.analyzegpa_okadai.get_gpa()\n for i, yc in enumerate(year_completed_list):\n ws_gpa_okadai.cell(row=i+2, column=1, value=yc)\n ws_gpa_okadai.cell(row=i+2, column=2,\n value=gpa_dict[yc][\"gpa\"])\n ws_gpa_okadai.cell(row=i+2, column=3,\n value=gpa_dict[yc][\"accumulated_gpa\"])\n ws_gpa_okadai.row_dimensions.group(i+3, 32, hidden=True)\n wb.save(self.excel_filename)\n finally:\n wb.close()\n\n\nif __name__ == \"__main__\":\n etef = ExportToExcelFile()\n etef.export_to_excel_file()\n","sub_path":"src/export_to_excelfile.py","file_name":"export_to_excelfile.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"325313457","text":"import PySimpleGUI as sg\r\nimport os\r\nimport base64\r\n\r\n\r\ndef main():\r\n OUTPUT_FILENAME = 'output.txt'\r\n\r\n folder = sg.popup_get_folder('Masukkin nama folder %s' % OUTPUT_FILENAME,\r\n title='Base64 Encoder')\r\n\r\n if not folder:\r\n sg.popup_cancel('Folder Invalid')\r\n return\r\n try:\r\n namesonly = [f for f in os.listdir(folder) if f.endswith(\r\n '.png') or f.endswith('.ico') or f.endswith('.gif')]\r\n except:\r\n sg.popup_cancel('Cancelled - No valid folder entered')\r\n return\r\n\r\n outfile = open(os.path.join(folder, OUTPUT_FILENAME), 'w')\r\n\r\n for i, file in enumerate(namesonly):\r\n contents = open(os.path.join(folder, file), 'rb').read()\r\n encoded = base64.b64encode(contents)\r\n outfile.write('\\n{} = {}'.format(file[:file.index(\".\")], encoded))\r\n sg.OneLineProgressMeter('Base64 Encoding', i+1,\r\n len(namesonly), key='-METER-')\r\n\r\n outfile.close()\r\n sg.popup('EZPZ!', 'Encoded %s files' % (i+1))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"src/output/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"143482102","text":"# This will be completed...\n\nimport pandas as pd\nimport numpy as np\n\n\n\ndef convert_to_csv(filepath, sep, header, prefix, usecols, index_col, skiprows):\n data = pd.read_csv(filepath_or_buffer=filepath,\n sep=sep,\n header=header,\n prefix=prefix,\n usecols=usecols,\n index_col=index_col,\n skiprows=skiprows,\n parse_dates=True)\n return data\n\ndef main():\n filepath = str(input(\"Enter the filepath: \"))\n sep = str(input(\"Enter the delimiter to use: \"))\n header_decision = str(input(\"Does the data set have a header? (yes/no): \"))\n if header_decision == \"yes\":\n header = 0\n prefix = \"dummy\"\n else:\n header = None\n prefix = str(input(\"What prefix do you want to add to column numbers?: \"))\n usecols = str(input(\"Enter the column number of the columns to import (separated by comma): \"))\n usecols = [int(colNum) for colNum in usecols.split(\",\")]\n index_col = int(input(\"What column contains the date/time information?: \"))\n skiprows_decision = str(input(\"Do you want to skip any row in the data set? (yes/no): \"))\n if skiprows_decision == \"yes\":\n skiprows = str(input(\"Determine the rows to skip (x:y): \"))\n skiprows = np.arange([int(rowNum) for rowNum in skiprows.split(\":\")][0],\n [int(rowNum) for rowNum in skiprows.split(\":\")][1])\n else:\n skiprows = None\n\n dataFrame = convert_to_csv(filepath, sep, header, prefix, usecols, index_col, skiprows)\n duration_decision = str(input(\"Does the dataset contain duration information? (yes/no): \"))\n if duration_decision == \"no\":\n duration = int(input(\"What is the duration of the data (in minutes)?: \"))\n dataFrame[\"Duration\"] = duration\n\n finalpath = str(input(\"Specify the final path for your dataset (include name.csv): \"))\n print(dataFrame)\n dataFrame.to_csv(path_or_buf=finalpath)\n print(\"-- Congratulations! your final data is stored--\")\n print(\"### SUMMARY ###\")\n print(\"The number of samples in the data set is: {}\".format(dataFrame.shape[0]))\n print(\"The first datetime is: {}\".format(dataFrame.index[0]))\n print(\"The last datatime is: {}\".format(dataFrame.index[-1]))\n print(\"The number of rows with NA values is: {}\".format(dataFrame.isnull().values.ravel().sum()))\n\nmain()\n\n","sub_path":"convert_to_csv.py","file_name":"convert_to_csv.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"117996220","text":"# -*- coding: utf-8 -*-\n# @project : just_to_eat\n# @file : python_yield.py\n# @time : 2019-07-03\n\n'''\n简单地讲,yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,\nPython 解释器会将其视为一个 generator���调用 fab(5) 不会执行 fab 函数,而是返回一个 iterable 对象!\n\n优点:把一个函数改写为一个 generator 就获得了迭代能力\n 节约内存\n'''\n\ndef fab(max):\n n, a, b = 0, 0, 1\n while n < max:\n print (b)\n a, b = b, a + b\n n = n + 1\n\ndef fab2(max):\n n, a, b = 0, 0, 1\n while n < max:\n yield b\n # print b\n a, b = b, a + b\n n = n + 1\n\na = fab2(5)\n# for i in a:\n# print (i)\nprint (a.__next__()) # python3中写法\nprint (a.__next__())\nprint (a.__next__())","sub_path":"practice/python_yield.py","file_name":"python_yield.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"119418518","text":"\"\"\"\ndjango-helpdesk - A Django powered ticket tracker for small enterprise.\n\n(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.\n\nviews/public.py - All public facing views, eg non-staff (no authentication\n required) views.\n\"\"\"\n\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.utils.translation import ugettext as _\n\nfrom helpdesk import settings as helpdesk_settings\nfrom helpdesk.forms import PublicTicketForm\nfrom helpdesk.lib import text_is_spam\nfrom helpdesk.models import Ticket, Queue, UserSettings, KBCategory\n\n\ndef homepage(request):\n if not request.user.is_authenticated() and helpdesk_settings.HELPDESK_REDIRECT_TO_LOGIN_BY_DEFAULT:\n return HttpResponseRedirect(reverse('login'))\n\n if request.user.is_staff:\n try:\n if getattr(request.user.usersettings.settings, 'login_view_ticketlist', False):\n return HttpResponseRedirect(reverse('helpdesk_list'))\n else:\n return HttpResponseRedirect(reverse('helpdesk_dashboard'))\n except UserSettings.DoesNotExist:\n return HttpResponseRedirect(reverse('helpdesk_dashboard'))\n\n knowledgebase_categories = KBCategory.objects.all()\n\n open_tickets = None\n closed_tickets = None\n if request.user.is_authenticated():\n open_tickets = Ticket.objects.filter(status=Ticket.OPEN_STATUS)\n if not request.user.is_staff:\n open_tickets = open_tickets.filter(submitter_email=request.user.email)\n closed_tickets = Ticket.objects.filter(status=Ticket.CLOSED_STATUS,\n submitter_email=request.user.email)\n\n return render_to_response('helpdesk/public_homepage.html',\n RequestContext(request, {\n 'kb_categories': knowledgebase_categories,\n 'open_tickets': open_tickets,\n 'closed_tickets': closed_tickets\n }))\n\n\ndef view_ticket(request):\n ticket_req = request.GET.get('ticket', '')\n ticket = False\n email = request.GET.get('email', '')\n error_message = ''\n\n if ticket_req and email:\n parts = ticket_req.split('-')\n queue = '-'.join(parts[0:-1])\n ticket_id = parts[-1]\n\n try:\n ticket = Ticket.objects.get(id=ticket_id, queue__slug__iexact=queue, submitter_email__iexact=email)\n except:\n ticket = False\n error_message = _('Invalid ticket ID or e-mail address. Please try again.')\n\n if ticket:\n\n if request.user.is_staff:\n redirect_url = reverse('helpdesk_view', args=[ticket_id])\n if request.GET.has_key('close'):\n redirect_url += '?close'\n return HttpResponseRedirect(redirect_url)\n\n if request.GET.has_key('close') and ticket.status == Ticket.RESOLVED_STATUS:\n from helpdesk.views.staff import update_ticket\n # Trick the update_ticket() view into thinking it's being called with\n # a valid POST.\n request.POST = {\n 'new_status': Ticket.CLOSED_STATUS,\n 'public': 1,\n 'title': ticket.title,\n 'comment': _('Submitter accepted resolution and closed ticket'),\n }\n if ticket.assigned_to:\n request.POST['owner'] = ticket.assigned_to.id\n request.GET = {}\n\n return update_ticket(request, ticket_id, public=True)\n\n # redirect user back to this ticket if possible.\n redirect_url = ''\n if helpdesk_settings.HELPDESK_NAVIGATION_ENABLED:\n redirect_url = reverse('helpdesk_view', args=[ticket_id])\n\n return render_to_response('helpdesk/public_view_ticket.html',\n RequestContext(request, {\n 'ticket': ticket,\n 'next': redirect_url,\n }))\n\n return render_to_response('helpdesk/public_view_form.html',\n RequestContext(request, {\n 'ticket': ticket,\n 'email': email,\n 'error_message': error_message,\n }))\n\ndef change_language(request):\n return_to = ''\n if request.GET.has_key('return_to'):\n return_to = request.GET['return_to']\n\n return render_to_response('helpdesk/public_change_language.html',\n RequestContext(request, {'next': return_to}))\n","sub_path":"helpdesk/views/public.py","file_name":"public.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"651736193","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\n\nurlpatterns = [\n\turl(r'^polls/', include('polls.urls',namespace='polls')),\n\turl(r'^admin/', admin.site.urls),\n\turl(r'^trading/',include('trading.urls')),\n url(r'^home/',include('welcomeapp.urls', namespace='home')),\n url(r'^tradeviewer/',include('tradeviewer.urls',namespace='tradeviewer')),\n \n\t]\n","sub_path":"mysite/mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"205650995","text":"import os\nimport simpleaudio as sa\nimport soundfile\nimport random\nimport sys, select\n\nprint (\"Press return to stop audio playing\")\n\n# initialise lists\nnameList = [] # to contain all wav files\nnewNameList = [] # to contain all new wav files\nentryList = [] # all different audio files\ncurrentTrack = []\n\n# set functions\ndef playTrack(name):\n wave_obj = sa.WaveObject.from_wave_file(name)\n print(\"playing: \" + name)\n play_obj = wave_obj.play()\n play_obj.wait_done()\n\ndef play():\n print (\"Now playing\")\n # start by playing first track\n for entry in entryList:\n if int(entry[1]) == 1:\n currentTrack = entry\n break\n playTrack(currentTrack[0])\n currentTransitionOptions = currentTrack[2]\n # play loop\n while True:\n # choose which track to play\n transitionValue = currentTransitionOptions[random.randint(1, len(currentTransitionOptions)) - 1]\n # find track\n for entry in entryList:\n # check if first track\n if entry[1] == transitionValue:\n currentTrack = entry\n break\n # play track\n playTrack(currentTrack[0])\n currentTransitionOptions = currentTrack[2]\n # check if return is pressed \n i,o,e = select.select([sys.stdin],[],[],0.0001)\n if i == [sys.stdin]: \n break\n\n# get al wav files in a list\nprint(\"Loaded audio loops:\")\nfor root, dirs, files in os.walk(\".\"):\n for filename in files:\n if filename.endswith('.wav'): \n print(\" - \" + filename)\n nameList.append(filename)\n\n# convert tot 16 bit to make sure audio is playable and copy the audio so the source files are safe\nfor name in nameList:\n data, samplerate = soundfile.read(name)\n newName = \"\".join((\"new_\", name))\n soundfile.write(newName, data, samplerate, subtype='PCM_16')\n newNameList.append(newName)\n\n# set all entrys\nfor name in newNameList:\n # set possible transitions\n possibleTransitions = []\n tempName = name[:-4] # remove .wav\n while True:\n possibleTransition = tempName[-1]\n if possibleTransition != \"_\":\n possibleTransitions.append(possibleTransition)\n tempName = tempName[:-1]\n else:\n break\n \n # add entry\n entryList.append([name, name[4], possibleTransitions])\n\nwhile True:\n while True:\n i = input(\"Press 'p' to play or 'q' to quit\")\n if i == \"p\" or i == \"q\":\n break\n if i == \"p\":\n \"Playing\"\n play()\n else: \n print(\"bye!\")\n break\n\n# remove created files\nfor name in newNameList:\n os.remove(name)\n\n","sub_path":"VASD_EXP1_PY/VASD.py","file_name":"VASD.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"122669","text":"#!/usr/bin/env python\n# Created by James Upton\n\n\nfrom random import gauss, randint\nfrom keith import Process\nfrom Employee import Employee, SalaryEmployee, BookEmployee\nimport time\nimport Queue\nimport Manager\n\nProcess.chgProcessName('simulate') # sets the process name\n\n\ndef biased_random(minimum, mean, maximum, stdev): # returns a float based on a gaussian\n # distribution around an average\n # between a min and max\n value = gauss(mean, stdev)\n if minimum < value < maximum:\n return value\n else: value = gauss(mean, stdev)\n return value\n\ndef phone_time(): # generates inbound telephone call time stamps\n import phonecall\n return phonecall.gen_call_time()\n\ndef main():\n employees = list()\n employees.append(SalaryEmployee(\"Clay\", [1, 2, 3, 4], 23.14))\n employees.append(SalaryEmployee(\"Karen\", [1, 2, 3, 4], 15.43))\n employees.append(Employee(\"Mary\", [1, 2, 3, 4], 9))\n employees.append(BookEmployee(\"Joe\", [5, 8], 18.5, eff_rate=0.75, error_rate=4))\n employees.append(BookEmployee(\"Scott\", [5, 8], 18.5, eff_rate=1.7, error_rate=3))\n employees.append(BookEmployee(\"Eddie\", [5, 8], 18.5, eff_rate=1.2, error_rate=2))\n employees.append(Employee(\"Brandi\", [6], 12))\n employees.append(BookEmployee(\"Ronnie\", [7, 9], 18.5, eff_rate=0.4))\n employees.append(Employee(\"Porter\", [10], 8))\n manager = Manager.Manager(employees)\n\n manager.dtime = 100000\n manager.debug = False\n run_time = 72 #720 makes a year\n\n stime = time.time() # time stamp for begining \n start_time = time.time() # time the program started\n end_time = start_time + run_time \n call = time.time() + (phone_time()/manager.dtime)\n try:\n while time.time() < end_time:\n if time.time() >= call: # ring phone at times\n stime += call # \n manager.ringPhone()\n call = time.time() + (phone_time()/manager.dtime)\n else:\n manager.check()\n\n except(KeyboardInterrupt):\n pass\n except:\n # Check new errors here\n print(\"Exception!!\")\n raise\n finally:\n manager.close()\n print(manager.Queues)\n hours = round((float((time.time() - start_time) * manager.dtime) / 3600), 2)\n summary = \"\"\"Hours Open = {hours}\nTotal Calls = {calls}\nTotal Estimates = {estimates}\nTotal Repair Orders = {orders}\nTotal Completed Orders = {completed}\nEstimate Per Calls = {estimates_per_calls}%\nRepair per Estimates = {ro_per_estimates}%\n\"\"\".format(hours=hours,\n calls=manager.totalPhoneCalls,\n estimates=manager.totalEstimates,\n orders=manager.totalRepairOrders,\n completed=manager.totalCompletedRepairOrders,\n estimates_per_calls = round(float(manager.totalEstimates) / float(manager.totalPhoneCalls) * 100, 2),\n ro_per_estimates = round(float(manager.totalRepairOrders) / float(manager.totalEstimates) * 100, 2),\n )\n employee_summary = \"\\nEmployee\\tWorking\\tIdle\\tCost\\n\"\n employee_cost = 0\n total_idle = []\n for employee in sorted(manager.employees, key=lambda x: x.name):\n worked = round(float(employee.worked * manager.dtime) / 3600, 2)\n idle = round(float((hours - worked) / hours * 100), 2)\n total_idle.append(idle)\n cost = employee.calculateCost(hours)\n employee_cost += cost\n employee_summary += \"\"\"{name}\\t\\t{worked}\\t{idle}\\t${cost}\\n\"\"\".format(name=employee.name, worked=worked, idle=idle, cost=cost)\n with open(\"it1out.txt\", 'a') as f:\n f.write('\\n\\n')\n f.write(summary)\n f.write(employee_summary)\n f.write('\\tAverage idle time: {}%\\n'.format(round(sum(total_idle)/len(total_idle), 2)))\n f.write(\"\\tTotal Cost of Employees: ${}\\n\".format(employee_cost))\n job_cost = manager.totalCompletedRepairOrders * 2346.54\n f.write(\"\\tGross Profit : ${}\\n\".format(job_cost))\n f.write(\"\\tActual Profit : ${}\\n\".format(job_cost - employee_cost))\n\n\nif __name__ == '__main__':\n with open('it1out.txt', 'w') as f:\n f.write(\"\")\n for _ in xrange(10):\n main()\n \n","sub_path":"Iteration 1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"252614105","text":"from bisect import bisect_left\nfrom itertools import combinations\n\n\ndef make_all_cases(item):\n cases = []\n for k in range(5):\n for combi in combinations([0, 1, 2, 3], k):\n case = \"\"\n for idx in range(4):\n if idx not in combi:\n case += item[idx]\n else:\n case += '-'\n cases.append(case)\n return cases\n\n\ndef solution(info, query):\n info = [i.split() for i in info]\n query = [q.replace(' and', '').split() for q in query]\n res = []\n db = {}\n\n for item in info:\n cases = make_all_cases(item)\n for case in cases:\n if case not in db.keys():\n db[case] = [int(item[4])]\n else:\n db[case].append(int(item[4]))\n\n for value in db.values():\n value.sort()\n\n for item in query:\n target = ''\n\n for i in item[:4]:\n target += i\n\n if target in db.keys():\n res.append(len(db[target]) - bisect_left(db[target],\n int(item[4]), lo=0, hi=len(db[target])))\n else:\n res.append(0)\n\n return res\n","sub_path":"programmers/level2/[1차] 프렌즈4블록.py","file_name":"[1차] 프렌즈4블록.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"440672345","text":"USERID_FOR_MASSLOOKER = [\n \"mohamed.3_annouri\",\n \"sarah.refai\",\n \"bulkingbull\",\n \"mr.aouari\",\n \"dzmoney22\",\n \"roymx_official\",\n \"moadbattahi\",\n \"glorynaire\",\n \"coach_3ammar\",\n \"toop.quote\",\n \"taqif_nefsak\",\n \"millionairesarab\",\n \"arabic_billionaire\",\n \"tatwirdat\",\n \"learn_english_with_us2016\",\n \"zenglish_a\",\n \"maroc.motivation\",\n \"edlibrecom\",\n \"simowesta\"\n ]\n\nUSERID_FOR_INSHACKLE = [\n\"chouftv_official\",\n \"hespress\",\n \"welovebuzzar\",\n \"kawtarbamo\",\n \"rajaabelmir\",\n \"reda_elwahabii\",\n \"omarbelmir\",\n \"adiltaouil\",\n \"meryemasouab\",\n \"oussamaramzi1\",\n \"ezzoubairhilal\",\n \"tahaessou\",\n \"fayssal_vlog\",\n \"mr_cazafonia\",\n \"elgrandetoto\",\n \"chroukate\",\n \"salimhammoumii\",\n \"amine_aouni\",\n \"bassou_mohammed\",\n \"yassarlemghar\",\n \"salmarachid.official\",\n \"hbirkousafae_officiel\",\n \"dunia_batma\",\n \"manalbenchlikha\",\n \"kawtarbamo\",\n \"saadlamjarred1\",\n \"simosedraty\",\n \"fatimazahraqanboua_\",\n \"rabii.skalli\",\n \"ibtissamtiskatofficial\",\n \"nouhaila_barbie\",\n \"rawaa_beauty\",\n \"ihssanebenalluch\",\n \"salmasalaheddine\",\n \"l7or75\",\n \"zouhairzair\",\n \"iam.ily\",\n \"fatijamaliofficiel\",\n \"hatimammor\",\n \"sofiacharafofficiel\",\n \"nouamanbelaiachi\", \n \"noraskaliofficial\",\n \"jaylann_official\",\n \"allalirachid\",\n \"farahelfassi1\",\n \"haytammiftah\",\n \"ahlamzaimiofficiel\",\n \"mariahnadim\",\n \"hindziadi\",\n ]\n","sub_path":"FunctionData/USER_DATABase.py","file_name":"USER_DATABase.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"83333800","text":"from time import sleep\n\nfrom auto_everything.base import Terminal\nt = Terminal()\n\nfrom auto_everything.gui import GUI\ngui = GUI()\npyautogui = gui.autogui\n\n\nprint(\"You have to make sure you got chrome and terminator installed. (Press enter to continue)\")\n\n\n# 1. start chrome\nt.kill(\"chrome\")\nt.run_program(\"google-chrome-stable --force-device-scale-factor=1.5\")\nsleep(2)\npyautogui.press(\"f11\")\n\"\"\"\npyautogui.moveTo(0,0)\nwhile 1:\n if gui.exists(\"chrome_new_tab\"):\n gui.click_after_exists(\"chrome_new_tab\")\n break\n if gui.exists(\"chrome_untitled\"):\n gui.click_after_exists(\"chrome_untitled\")\n break\npyautogui.typewrite(\"https://google.com\")\npyautogui.press(\"enter\")\nif gui.exists(\"chrome_x\"):\n gui.click_after_exists(\"chrome_x\")\n\"\"\"\n\n\n# 2. run terminator\nt.run(\"terminator --profile=mine\", cwd=t.fix_path(\"~\"), wait=False)\nsleep(2)\npyautogui.press(\"f11\")\n\n\nprint(\"Done!\")\n","sub_path":"lyingdown/personal_usage/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"639703421","text":"import warnings\n\nimport pickle\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.utils.data as data\n\nfrom torch.autograd import Variable\nfrom sklearn.model_selection import train_test_split\n\nwarnings.filterwarnings(\"ignore\")\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n\nclass DataBuilder(data.Dataset):\n \n def __init__(self, df, input_col, target_col, idx_dict, seq_length):\n \n self.df = df\n self.df.set_index(np.arange(self.df.shape[0]))\n \n self.input = self.df[input_col].tolist()\n self.target = self.df[target_col].tolist()\n \n self.idx_dict = idx_dict\n self.seq_length = seq_length\n \n def __getitem__(self, index):\n \n #构造idx特征\n input_ = self.input[index]\n target = self.target[index]\n\n input_idx, mask = self.get_idx(input_, self.idx_dict, self.seq_length)\n input_tensor = torch.LongTensor(input_idx)\n mask = torch.FloatTensor(mask)\n target_tensor = torch.LongTensor([target])\n\n return input_tensor, mask, target_tensor\n\n def __len__(self):\n return len(self.target)\n\n def get_idx(self, sentence, idx_dict, max_length):\n\n idxs = []\n sentence = list(str(sentence))\n pad_index = idx_dict['PAD']\n \n for word in sentence:\n if word in idx_dict.keys():\n idx = idx_dict[word]\n else:\n idx = idx_dict['UKN']\n idxs.append(idx)\n\n L = len(idxs)\n if L >= max_length:\n idxs = idxs[:max_length]\n mask = [1] * max_length\n else:\n idxs = idxs + (max_length - L) * [pad_index]\n mask = [1] * L + [0] * (max_length - L)\n\n return idxs, mask\n \n \ndef dict_build(cols, use_char=True, save_dir=None):\n if type(cols) != list:\n cols = [cols]\n\n word = pd.concat(cols).tolist()\n \n if use_char is True:\n word = ['UKN', 'PAD'] + list(''.join(word))\n else:\n word = ['UKN', 'PAD'] + ','.join(word).split(',')\n \n word = list(set(word))\n idx = range(0, len(word))\n\n items = zip(word, idx)\n word2idx = dict((i, j) for i, j in items)\n\n if save_dir is not None:\n output = open(save_dir, 'wb')\n pickle.dump(word2idx, output)\n output.close()\n\n return word2idx\n\n\ndef get_data(data_path, input_col, rebulid=False, train_size=0.7, random_seed=42):\n\n\n if rebulid:\n d = pd.read_csv(data_path)\n d_train, d_dev = train_test_split(d, test_size=1 - train_size, random_state=random_seed)\n d_dev, d_test = train_test_split(d_dev, test_size=0.5, random_state=random_seed)\n\n d_train.to_csv('../data/train.csv', index=None)\n d_dev.to_csv('../data/dev.csv', index=None)\n d_test.to_csv('../data/test.csv', index=None)\n\n char2idx = dict_build(d_train[input_col], save_dir='../resource/char2idx.pkl')\n\n else:\n d_train = pd.read_csv('../data/train.csv')\n d_dev = pd.read_csv('../data/dev.csv')\n d_test = pd.read_csv('../data/test.csv')\n\n char2idx = open('../resource/char2idx.pkl', 'rb')\n char2idx = pickle.load(char2idx)\n\n \n return d_train, d_dev, d_test, char2idx\n \n \ndef eval(model, dataloader, lossfunc):\n\n y_pred = []\n y_true = []\n total_loss = 0\n batch_count = len(dataloader)\n\n for (sentence, mask, label) in dataloader:\n\n sentence = Variable(sentence).to(device)\n label = Variable(label).view(-1).to(device)\n mask = Variable(mask).to(device)\n \n logits = model(sentence, mask)\n predict = logits.max(1)[1]\n loss = lossfunc(logits, label)\n total_loss += loss.item() \n\n y_pred += predict.tolist()\n y_true += label.tolist()\n \n return y_true, y_pred, total_loss / batch_count\n","sub_path":"python/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"107413679","text":"# -*- encoding: utf-8 -*-\n'''\n@File : homework2.7.py\n@Time : 2020/03/09 17:24:57\n@Author : xdbcb8 \n@Version : 1.0\n@Contact : xdbcb8@qq.com\n@WebSite : www.xdbcb8.com\n'''\n\n# here put the import lib\nfrom random import randint\ndef stu( L ):\n G = []\n for i in range(0,len(L)):\n if L[i] >= 90:\n G.append('A')\n elif L[i] >= 80 and L[i] < 90:\n G.append('B')\n elif L[i] >= 70 and L[i] < 80:\n G.append('C')\n elif L[i] < 70:\n G.append('D')\n return G\ns = []\nfor i in range(0,10):\n s.append(randint(0,101))\nprint(\"学生的成绩为:\",s)\nprint(\"等级为:\",stu( s ))\n ","sub_path":"homework2.7.py","file_name":"homework2.7.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"31601781","text":"import time\n\nfrom Algorithms.Constraints.better_treatment_constraint import Constraint\nfrom Algorithms.constrained_dynamic_programming import ConstrainedDynamicProgramming\nfrom Algorithms.constrained_greedy import ConstrainedGreedy\nfrom Algorithms.naive_dynamic_programming import NaiveDynamicProgramming\nfrom Algorithms.naive_greedy import NaiveGreedy\nfrom Algorithms.Approximators.statistical_approximator import StatisticalApproximator\nfrom DataGenerator.data_generator import split_patients, generate_data, generate_test_data\nfrom DataGenerator.distributions import DiscreteDistributionWithSmoothOutcomes\n\n\ndef setup_data_sets(n_z, n_x, n_a, n_y, n_training_samples, n_test_samples, seed):\n start = time.time()\n print(\"Generating training and test data\")\n dist = DiscreteDistributionWithSmoothOutcomes(n_z, n_x, n_a, n_y, seed=seed)\n training_data = split_patients(generate_data(dist, n_training_samples))\n test_data = generate_test_data(dist, n_test_samples)\n print(\"Generating data took {:.3f} seconds\".format(time.time() - start))\n return dist, training_data, test_data\n\n\ndef setup_algorithms(training_data, dist, delta, train=True):\n start = time.time()\n n_x = dist.n_x\n n_a = dist.n_a\n n_y = dist.n_y\n statistical_approximation_prior = StatisticalApproximator(n_x, n_a, n_y, training_data, smoothing_mode='gaussian')\n\n constraint_prior = Constraint(training_data, n_a, n_y, approximator=statistical_approximation_prior, delta=delta)\n\n algorithms = [\n ConstrainedDynamicProgramming(n_x, n_a, n_y, training_data, constraint_prior, statistical_approximation_prior, name=\"Constrained Dynamic Programming\", label=\"CDP\"),\n ConstrainedGreedy(n_x, n_a, n_y, training_data, constraint_prior, statistical_approximation_prior, name=\"Constrained Greedy\", label=\"CG\"),\n NaiveGreedy(n_x, n_a, n_y, statistical_approximation_prior, round(delta * (n_a-1))+1, name='Naive Greedy', label='NG'),\n NaiveDynamicProgramming(n_x, n_a, n_y, training_data, statistical_approximation_prior, reward=-(delta+0.0001), name='Naive Dynamic Programming', label='NDP'),\n ]\n\n print(\"Setting up algorithms took {:.3f} seconds\".format(time.time() - start))\n return algorithms\n\n\ndef load_settings():\n starting_seed = 10342\n n_data_sets = 2\n n_deltas = 4\n n_z = 3\n n_x = 1\n n_a = 5\n n_y = 3\n n_training_samples = 15000\n n_test_samples = 3000\n file_name_prefix = \"GeneralComparisonDeltaSweep_15ksamples_\"\n\n return starting_seed, n_data_sets, n_deltas, n_z, n_x, n_a, n_y, n_training_samples, n_test_samples, file_name_prefix","sub_path":"Main/SingleEvaluations/Settings/GeneralDeltaSweepSettings.py","file_name":"GeneralDeltaSweepSettings.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"627923526","text":"# -*- coding: utf-8 -*-\n\"\"\"SaltOPS URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom auth import views\n\nurlpatterns = [\n\turl(r'^admin/', admin.site.urls),\n\turl(r'^$',views.index ,name='index'),\n\turl(r'^help/$',views.help ,name='help'),\n\turl(r'^auth/', include('auth.urls')),\n\turl(r'^main/',include('main.urls')),\n\turl(r'^salt/',include('main.urls')),\n\turl(r'^files/',include('files.urls')),\n\turl(r'^cmdb/',include('cmdb.urls')),\n\turl(r'^items/',include('items.urls')),\n]\n","sub_path":"SaltOPS/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"307013536","text":"# -*- coding: utf-8 -*-\nimport copy\n\nBLACK = 1\nWHITE = -1\nEMPTY = 0\n\n\nclass Reversi:\n def __init__(self, board_size=8):\n self.board_size = board_size\n self.board = [[EMPTY] * self.board_size for _ in range(self.board_size)]\n mid = self.board_size // 2\n self.board[mid-1][mid] = self.board[mid][mid-1] = BLACK\n self.board[mid-1][mid-1] = self.board[mid][mid] = WHITE\n self.num_black = self.num_white = 2\n self.round = 0\n self.current_player = BLACK\n self.winner = None\n self.done = False\n \n @property\n def current_player_name(self):\n return \"BLACK\" if self.current_player == BLACK else \"WHITE\"\n\n def state(self):\n return copy.deepcopy(self.board)\n\n def reward(self, player):\n if not self.done:\n return 0\n else:\n if player == BLACK:\n return self.num_black - self.num_white\n else:\n return self.num_white - self.num_black\n \n def step(self, action):\n # action pass\n if action == -1:\n if len(self.available_action(self.current_player)) != 0:\n self.__lose()\n else:\n self.__take_turn()\n # valid action\n elif 0 <= action < self.board_size ** 2:\n row, col = action // self.board_size, action % self.board_size\n if self.__process_action(action, self.current_player) is False:\n self.__lose()\n elif len(self.available_action(BLACK)) == 0 and len(self.available_action(WHITE)) == 0:\n self.__game_over()\n else:\n self.__take_turn()\n # invalid action\n else:\n self.__lose()\n\n def reset(self):\n self.board = [[EMPTY] * self.board_size for _ in range(self.board_size)]\n mid = self.board_size // 2\n self.board[mid - 1][mid] = self.board[mid][mid - 1] = BLACK\n self.board[mid - 1][mid - 1] = self.board[mid][mid] = WHITE\n self.num_black = self.num_white = 2\n self.round = 0\n self.current_player = BLACK\n self.winner = None\n self.done = False\n\n def render(self):\n print(\"round: {round}, player: {player}, #black: {num_black}, #white: {num_white}\".format(\n round=self.round, player=self.current_player_name,\n num_black=self.num_black,num_white=self.num_white))\n print(\" \" + \" \".join([str(i) for i in range(self.board_size)]))\n render_mapping = {BLACK: \"B\", WHITE: \"W\", EMPTY: \".\"}\n for i, row in enumerate(self.board):\n render = [render_mapping[position] for position in row]\n print(\"{row} {row_board}\".format(row=i, row_board=\" \".join(render)))\n available_action = self.available_action(self.current_player)\n if len(available_action) == 0:\n print(\"no available action for {player}\".format(player=self.current_player_name))\n else:\n print(\"{player}'s available action(s):\".format(player=self.current_player_name))\n print(\" \".join([\"({row}, {col})\".format(row=a // self.board_size, col=a % self.board_size) for a in available_action]))\n\n @staticmethod\n def _next_position(row, col, direction):\n \"\"\"Compute next position based on current position and direction\n 4 3 2\n 5 X 1\n 6 7 0\n\n :param row: int, current row position\n :param col: int, current column position\n :param direction: int, direction defined above\n :return: tuple(int, int), next row and column position\n \"\"\"\n if direction in (0, 6, 7):\n row += 1\n if direction in (0, 1, 2):\n col += 1\n if direction in (2, 3, 4):\n row -=1\n if direction in (4, 5, 6):\n col -= 1\n return row, col\n\n def __process_action(self, action, player, check_only=False):\n row, col = action // self.board_size, action % self.board_size\n if self.board[row][col] != EMPTY:\n return False\n flip_positions = []\n is_valid_action = False\n for direction in range(8):\n i, j = row, col\n num_flip = 0\n while True:\n i, j = self._next_position(i, j, direction)\n if i < 0 or i >= self.board_size or j < 0 or j >= self.board_size \\\n or self.board[i][j] == EMPTY:\n num_flip = 0\n break\n if self.board[i][j] == player:\n break\n num_flip += 1\n flip_positions.append((i, j))\n if num_flip != 0:\n if check_only:\n return True\n is_valid_action = True\n for flip_i, flip_j in flip_positions:\n self.board[flip_i][flip_j] = player\n if player == BLACK:\n self.num_black += num_flip\n self.num_white -= num_flip\n else:\n self.num_black -= num_flip\n self.num_white += num_flip\n flip_positions = []\n if is_valid_action:\n self.board[row][col] = player\n if player == BLACK:\n self.num_black += 1\n else:\n self.num_white += 1\n return is_valid_action\n\n def __take_turn(self):\n if self.current_player == BLACK:\n self.current_player = WHITE\n else:\n self.current_player = BLACK\n self.round += 1\n\n def __game_over(self):\n self.done = True\n if self.winner is None:\n if self.num_black == self.num_white:\n self.winner = EMPTY\n elif self.num_black > self.num_white:\n self.winner = BLACK\n else:\n self.winner = WHITE\n\n def __lose(self):\n if self.current_player == BLACK:\n self.winner = WHITE\n else:\n self.winner = BLACK\n self.__game_over()\n\n def available_action(self, player=None):\n if player is None:\n player = self.current_player\n available_action = []\n for i in range(self.board_size):\n for j in range(self.board_size):\n action = i * self.board_size + j\n if self.__process_action(action, player, check_only=True):\n available_action.append(action)\n return available_action\n\n# demo\nif __name__ == \"__main__\":\n import random\n\n game = Reversi()\n while not game.done:\n game.render()\n available_action = game.available_action()\n if len(available_action) > 0:\n action = random.choice(game.available_action())\n else:\n action = -1 # no position to step\n game.step(action)\n game.render()\n black_score, white_score = game.reward(BLACK), game.reward(WHITE)\n print(\"BLACK:\", black_score, \"WHITE:\", white_score)\n if black_score == white_score:\n print(\"DRAW\")\n elif black_score > white_score:\n print(\"BLACK wins\")\n else:\n print(\"WHITE wins\")\n","sub_path":"games/reversi.py","file_name":"reversi.py","file_ext":"py","file_size_in_byte":7122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"602764806","text":"def sequentialsearch(list,x):\n\tpos=0\n\tfound=False\n\twhile pos 0:\n now = datetime.now()\n str_time = now.strftime(\"%m_%d_%Y_%H_%M_%S_\" + str(self._counter))\n self.env.export_video(str_time + '.mp4')\n else:\n if self._counter % 100 == 3:\n self.env.recording = True\n elif self._counter % 100 == 4:\n now = datetime.now()\n str_time = now.strftime(\"%m_%d_%Y_%H_%M_%S_\" + str(self._counter))\n self.env.export_video(str_time + '.mp4')\n self.env.recording = False\n self._counter = self._counter + 1\n \n return self.env.reset()\n\n def close(self):\n self.reset()\n self.env.close()\n\nimport math\n\ndef euclidean_distance(x1, y1, x2, y2):\n\n res = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))\n\n #print('points:', x1, y1, x2, y2, 'fist:', res)\n\n return res\n\nimport tensorflow as tf\n\nclass LogPlayerEntropy(gym.Wrapper):\n def __init__(self, env, logdir):\n gym.Wrapper.__init__(self, env)\n self.logdir = logdir\n self.summary_writer = tf.summary.create_file_writer(self.logdir)\n self.summary_step = 0\n\n self.sum_dist_metrics = []\n self.sum_of_closest_to_edges_metric = []\n\n\n def _calculate_sum_dist(self, positions):\n sum = 0.0\n for x1, y1 in positions:\n for x2, y2 in positions:\n sum += euclidean_distance(x1, y1, x2, y2)\n\n return sum\n\n def _calculate_sum_of_closest_to_core_points(self, positions, core_points):\n sum = 0.0\n for x1, y1 in core_points:\n best = None\n for x2, y2 in positions:\n dist = euclidean_distance(x1, y1, x2, y2)\n if best is None or best > dist:\n best = dist\n sum += best\n \n return sum\n\n\n def step(self, action):\n agents = self.env.unwrapped.agents\n positions = list(map(lambda a: a.pos, agents))\n\n sum_dist = self._calculate_sum_dist(positions)\n self.sum_dist_metrics.append(sum_dist)\n #print('after_dist')\n\n edges = [\n (0, 0),\n (self.env.unwrapped.width - 1, 0),\n (self.env.unwrapped.width - 1, self.env.unwrapped.height - 1),\n (0, self.env.unwrapped.height - 1)\n ]\n sum_of_closest = self._calculate_sum_of_closest_to_core_points(positions, edges)\n self.sum_of_closest_to_edges_metric.append(sum_of_closest)\n\n #print(sum_dist, sum_of_closest)\n \n return self.env.step(action)\n\n def reset(self):\n if len(self.sum_dist_metrics) != 0:\n sum_dist_mean = np.mean(self.sum_dist_metrics)\n sum_of_closest_mean = np.mean(self.sum_of_closest_to_edges_metric)\n\n with self.summary_writer.as_default():\n tf.summary.scalar(\"metrics/sum_of_dist_mean\", sum_dist_mean, step=self.summary_step)\n tf.summary.scalar(\"metrics/sum_of_closest_to_edges\", sum_of_closest_mean, step=self.summary_step)\n self.summary_step += 1\n\n self.sum_dist_metrics = []\n self.sum_of_closest_to_edges_metric = []\n return self.env.reset()\n\ndef get_tile_range(x, y, tile_size):\n ymin = y * tile_size\n ymax = (y + 1) * tile_size\n xmin = x * tile_size\n xmax = (x + 1) * tile_size\n\n return xmin, xmax, ymin, ymax\n\ndef rgb2gray(rgb):\n\n rgb = rgb.astype(np.float32)\n\n r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]\n gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n\n return gray.astype(np.uint8)\n\nfrom marlgrid.base import MultiGrid\n\nclass FullGridImgObservation(gym.ObservationWrapper):\n def __init__(self, env, tile_size=8):\n gym.ObservationWrapper.__init__(self, env)\n self._num_agents = len(self.env.unwrapped.agents)\n assert self._num_agents == len(self.env.observation_space)\n\n self._width = self.env.unwrapped.width\n self._height = self.env.unwrapped.height\n self._tile_size = tile_size\n\n one_obs_shape = (self._height * self._tile_size, self._width * self._tile_size, 4)\n self.observation_space = [gym.spaces.Box(\n low=0,\n high=255,\n shape=one_obs_shape,\n dtype=\"uint8\"\n )] * self._num_agents\n\n def observation(self, org_obs):\n assert len(org_obs) == self._num_agents\n\n grid = self.env.unwrapped.grid.render(self._tile_size).astype(np.uint8)\n \n new_obs_list = []\n for i in range(self._num_agents):\n agent = self.env.unwrapped.agents[i]\n ax, ay = agent.pos\n agent_img = MultiGrid.render_tile(self.env.unwrapped.grid.get(ax, ay), tile_size=self._tile_size)\n agent_img = rgb2gray(agent_img)\n\n agent_layer = np.zeros(shape=(self._height * self._tile_size, self._width * self._tile_size), dtype=np.uint8)\n xmin, xmax, ymin, ymax = get_tile_range(ax, ay, self._tile_size)\n agent_layer[ymin:ymax, xmin:xmax] = agent_img\n \n agent_layer = np.expand_dims(agent_layer, axis=-1).astype(np.uint8)\n\n agent_obs = np.concatenate([grid, agent_layer], axis=-1).astype(np.uint8)\n assert agent_obs.shape == self.observation_space[i].shape\n new_obs_list.append(agent_obs)\n return new_obs_list\n\n\nfrom marlgrid.objects import Wall, BonusTile\n\ndef xy_in_dir(dir, x, y):\n if dir == 0:\n return x + 1, y\n elif dir == 1:\n return x, y + 1\n elif dir == 2:\n return x - 1, y\n elif dir == 3:\n return x, y - 1\n else:\n assert False\n\nclass FullGridImgObservationCompact(gym.ObservationWrapper):\n def __init__(self, env):\n gym.ObservationWrapper.__init__(self, env)\n self._num_agents = len(self.env.unwrapped.agents)\n assert self._num_agents == len(self.env.observation_space)\n\n self._width = self.env.unwrapped.width\n self._height = self.env.unwrapped.height\n self._tile_size = 8\n\n one_obs_shape = (self._height, self._width, 6)\n self.observation_space = [gym.spaces.Box(\n low=0,\n high=255,\n shape=one_obs_shape,\n dtype=\"uint8\"\n )] * self._num_agents\n\n def observation(self, org_obs):\n assert len(org_obs) == self._num_agents\n\n wall_layer = np.zeros((self._height, self._width), dtype=np.uint8)\n target_layer = np.zeros((self._height, self._width), dtype=np.uint8)\n players_layer = np.zeros((self._height, self._width), dtype=np.uint8)\n players_dir_layer = np.zeros((self._height, self._width), dtype=np.uint8)\n\n for x in range(self._width):\n for y in range(self._height):\n obj = self.env.unwrapped.grid.get(x, y)\n if isinstance(obj, Wall):\n wall_layer[y, x] = 255\n elif isinstance(obj, BonusTile) and obj.active:\n target_layer[y, x] = 255\n\n \n for aid in range(len(self.env.unwrapped.agents)):\n agent = self.env.unwrapped.agents[aid]\n ax, ay = agent.pos\n players_layer[ay, ax] = 255\n adx, ady = xy_in_dir(agent.dir, ax, ay)\n players_dir_layer[ady, adx] = 255\n #print(f'player {aid}, {ax}, {ay} orientation: {agent.dir}')\n\n\n new_obs_list = []\n for aid in range(len(self.env.unwrapped.agents)):\n agent = self.env.unwrapped.agents[aid]\n agent_layer = np.zeros((self._height, self._width), dtype=np.uint8)\n agent_dir_layer = np.zeros((self._height, self._width), dtype=np.uint8)\n ax, ay = agent.pos\n agent_layer[ay, ax] = 255\n adx, ady = xy_in_dir(agent.dir, ax, ay)\n agent_dir_layer[ady, adx] = 255\n\n agent_obs = np.stack([wall_layer, target_layer, players_layer, players_dir_layer, agent_layer, agent_dir_layer], axis=-1)\n assert agent_obs.shape == self.observation_space[aid].shape\n new_obs_list.append(agent_obs)\n #print(f'player {aid}, {ay}, {ax} orientation: {agent.observe_orientation}')\n\n return new_obs_list\n\n\nclass ObservationForMultiHeadFromFull(gym.ObservationWrapper):\n def __init__(self, env):\n gym.ObservationWrapper.__init__(self, env)\n\n self._num_players = len(self.env.observation_space)\n assert len(set(map(lambda x: x.shape, self.env.observation_space))) == 1\n obs_shape = (1,) + self.env.observation_space[0].shape[:-1] + (3 + self._num_players,)\n\n\n self.observation_space = gym.spaces.Box(\n low=0,\n high=255,\n shape=obs_shape,\n dtype=\"uint8\",\n )\n def observation(self, old_obs):\n full_level_obs = old_obs[0][:, :, 0:3]\n #print(full_level_obs.shape)\n obs_list = [full_level_obs]\n for i in range(self._num_players):\n player_mark_layer = np.expand_dims(old_obs[i][:, :, 3], axis=-1)\n #print(player_mark_layer.shape)\n obs_list.append(player_mark_layer)\n\n #print(obs_list)\n obs = np.concatenate(obs_list, axis=-1)\n obs = np.expand_dims(obs, axis=0)\n return obs\n\ndef ObservationForOneHeadFromFull(env):\n return ObservationForOneHead(env)\n","sub_path":"JointInternRepo/marlgrid/marlgrid/custom/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":12500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"279329118","text":"import numpy as np\nimport pandas as pd\nimport func.date as date\n\nimport sys\nsys.path.append(\"..\")\nsys.path.append(\"..\")\n\nimport py.base.nd as nd\n\ndef nalmark(data):\n if isinstance(data, pd.core.series.Series):\n return data.isin([np.nan, np.inf, -np.inf])\n else:\n return data.isin([np.nan, np.inf, -np.inf]).any(1)\n\ndef dropnal(data, fillordrop=False, fillval=0): \n if fillordrop:\n data[nalmark(data)] = fillval\n return data\n else: \n return data[~nalmark(data)]\n\ndef dataclean(data, **kwargs):\n if nd.isnull(data):\n return data\n\n fillordrop = kwargs.get('fillordrop', False)\n fillval = kwargs.get('fillval', 0)\n\n data = dropnal(data, fillordrop, fillval)\n\n resample = kwargs.get('resample', 'A-Dec')\n if resample:\n data = data.resample(resample).last()\n\n lastyear = kwargs.get('lastyear', True)\n if lastyear:\n data = data.truncate(after = date.year_end())\n\n return data\n\ndef fullrange(data, freq='Q', **kwargs):\n daterange = pd.date_range(start=data.index[0], end=data.index[-1], freq=freq)\n return data.reindex(daterange)\n\n\n","sub_path":"B.TII/func/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"550819100","text":"# -*- encoding:utf-8 -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 6\n_modified_time = 1326569363.138\n_template_filename='G:\\\\Workspace\\\\Python\\\\ARM\\\\src\\\\Web Front End\\\\01-StaticPages\\\\StaticPages\\\\staticpages\\\\templates/page2.mako'\n_template_uri='page2.mako'\n_template_cache=cache.Cache(__name__, _modified_time)\n_source_encoding='utf-8'\nfrom webhelpers.html import escape\n_exports = []\n\n\ndef render_body(context,**pageargs):\n context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n __M_writer = context.writer()\n # SOURCE LINE 1\n __M_writer(u'This is page 2\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n","sub_path":"21 Web Application Frameworks/Pylons/01-StaticPages/StaticPages/data/templates/page2.mako.py","file_name":"page2.mako.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"378676626","text":"import cv2\nimport numpy as np\nimport math\n\ncap = cv2.VideoCapture(0)\nwhile(cap.isOpened()):\n ret, img = cap.read()\n img = cv2.resize(img,(800,640))\n img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n _, thresh = cv2.threshold(img_gray, 127, 255,\n cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n cv2.imshow('Thresholded', thresh)\n\n _, contours,hierarchy = cv2.findContours(thresh,2,1)\n cnt = contours[0]\n\n hull = cv2.convexHull(cnt,returnPoints = False)\n defects = cv2.convexityDefects(cnt,hull)\n drawing = np.zeros(img_gray.shape,np.uint8)\n cv2.drawContours(drawing,[cnt],0,(255,255,0),0)\n cv2.imshow('thresh',thresh)\n cv2.imshow('draw',drawing)\n for i in range(defects.shape[0]):\n s,e,f,d = defects[i,0]\n start = tuple(cnt[s][0])\n end = tuple(cnt[e][0])\n far = tuple(cnt[f][0])\n #cv2.line(img,start,end,[0,255,0],2)\n #cv2.circle(img,far,5,[0,0,255],-1)\n\n a = math.sqrt((end[0] - start[0])**2 + (end[1] - start[1])**2)\n b = math.sqrt((far[0] - start[0])**2 + (far[1] - start[1])**2)\n c = math.sqrt((end[0] - far[0])**2 + (end[1] - far[1])**2)\n angle = math.acos((b**2 + c**2 - a**2)/(2*b*c)) * 57\n if angle <= 90:\n cv2.circle(img,far,3,[0,0,255],-1)\n #dist = cv2.pointPolygonTest(cnt,far,True)\n #cv2.line(crop_img,start,end,[0,255,0],2)\n #cv2.circle(crop_img,far,5,[0,0,255],-1)\n\n cv2.imshow('img',img)\n k = cv2.waitKey(10)\n if k == 27:\n break\ncv2.destroyAllWindows()\n","sub_path":"ConvexHull/convex2.py","file_name":"convex2.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"108036073","text":"# !/usr/bin/env python3.x\n# -*-coding:utf-8\n__author__ = 'ZhangLei'\n__email__ = 'blylei@163.com'\n__GitHub__ = 'https://github.com/Bilingyun/SRT'\n\nimport time\nimport os\nimport re\nimport requests\nimport csv\nimport random\nfrom bs4 import BeautifulSoup as bs\nimport lxml\nfrom selenium import webdriver as web_dr\nfrom self_module import UserAgents as UA\n\n\nheaders = UA.choice_header()\noptions = web_dr.ChromeOptions()\noptions.add_argument('lang=zh_CN.UTF-8') # 设置中文看\noptions.add_argument(str(headers)) # 更换头部\n\ndir_path = r'E\\DaChuang' # 设置爬取文件的基础存储路径\nbase_url = 'http://taocan.ctrip.com/sh/search?FromMenu=hotel&kwfrom=70022&destcity=0&' \\\n 'AreaType=0&keywords=%u5982%u5BB6%u5FEB%u6377%u9152%u5E97'\n\n\nclass HotelItems:\n \"\"\"酒店结构化数据包含项目\"\"\"\n hotel_name = None # 快捷酒店名\n hotel_loc = None # 快捷酒店位置\n hotel_price = None # 快捷酒店房间价格\n hotel_score = None # 快捷酒店评分\n house_style = None # 房间类型\n hotel_user_recom_perc = None # 快捷酒店用户推荐百分比\n hotel_dist = None # 快捷酒店与景区之间的距离\n\n\n\"\"\"爬虫部分\"\"\"\nclass GetHotel:\n \"\"\"获取酒店结构化数据+评论+图片\"\"\"\n def __init__(self):\n \"\"\"自动顺序执行下列方法\"\"\"\n print(\"把舞台交给你!\\n----请开始你的表演\")\n # self.pages = self.get_page_num(self.base_url)\n self.hotel_urls = self.get_urls()\n self.struct_data = self.spider(self.hotel_urls)\n self.save_data(self.struct_data)\n\n def get_page_num(self, base_url):\n \"\"\"根据基础URL,获取总的页面数\"\"\"\n bro = web_dr.Chrome(chrome_options=options)\n bro.get(base_url)\n bro.implicitly_wait(10) # 最大等待渲染时间10s,智能缩减等待时间\n # pn = bro.find_element_by_xpath('./div[@class=\"pkg_page basefix\"]')\n pn = bro.find_element_by_class_name('jmp_alert')\n pages = pn.find_element_by_xpath('//a[@href][last()-1]').text\n pages = int(pages)\n bro.quit() # 退出浏览器\n return pages\n\n def get_urls(self,pages=1):\n \"\"\"根据基础URL获取全国如家快捷酒店的页面\"\"\"\n hotel_urls = [] # 快捷酒店URL池\n bro = web_dr.Chrome(chrome_options=options)\n for i in range(1,pages+1):\n print(\"-*-现在开始获取第{}页面-*-\".format(i))\n time.sleep(0.2)\n base_url = 'http://taocan.ctrip.com'\n # 构造酒店页面的url,i表示页数\n url = 'http://taocan.ctrip.com/sh/search?FromMenu=hotel&kwfrom=70022&destcity=/' \\\n '&AreaType=0&keywords=%u5982%u5BB6%u5FEB%u6377%u9152%u5E97={}'.format(i)\n bro.get(url)\n bro.implicitly_wait(10) # 最大等待渲染时间10s,智能缩减等待时间\n elements = bro.find_elements_by_class_name('pr_comment')\n for element in elements:\n end_url = element.find_element_by_tag_name('a')\n end_url = end_url.get_attribute('href')\n url = str(end_url)\n hotel_urls.append(url)\n set(hotel_urls) # 去除重复的酒店URL\n bro.quit() # 退出浏览器\n for url in hotel_urls:\n print('{}:已加入到酒店URL列表'.format(url))\n print(\"****酒店页面获取完毕****\")\n time.sleep(3)\n print('总共获取到%d个如家快捷酒店URL'%len(hotel_urls))\n return hotel_urls\n\n def spider(self, hotel_urls):\n \"\"\"根据各地区个酒店的URL,获取各地区各快捷酒店的结构化数据\"\"\"\n struct_data = [] # 存储结构化数据\n bro = web_dr.Chrome(chrome_options=options)\n item = HotelItems() # 实例化HotelItems类\n for url in hotel_urls:\n \"\"\"根据get_urls方法返回的hotel_urls获取个页面上的如家快捷酒店\"\"\"\n # num = len(struct_data)+1 # 计数器\n # print(\" 开始获取第{}家酒店\".format(num))\n bro.get(url)\n bro.implicitly_wait(20) # 最大等待渲染时间20s,智能缩减等待时间\n tags = bro.find_elements_by_id('base_bd')\n for tag in tags:\n \"\"\"don't care about anything right now\"\"\"\n try:\n item.hotel_price = tag.find_element_by_class_name('detail_price').text\n except :\n print(\"出现小小的意外,程序照样运行,别担心\")\n finally:\n hotel_lists = tag.find_elements_by_id('tempCanBookHotel')\n for hotel in hotel_lists:\n \"\"\"一个url里包含一个至多个价格相同的酒店\"\"\"\n num = len(struct_data) + 1 # 计数器\n print(\" 开始获取第{}家酒店\".format(num))\n item.hotel_name = hotel.find_element_by_class_name('hotel_name').text\n item.house_style = hotel.find_element_by_xpath('//span[@title]')\\\n .get_attribute('title')\n item.hotel_score = hotel.find_element_by_class_name('htl_pj ')\\\n .find_element_by_xpath('//dfn').text\n item.hotel_user_recom_perc = \\\n hotel.find_element_by_xpath(\"//a[@class='htl_pj htl_recommend ']\").text\n item.hotel_loc = hotel.find_element_by_xpath('//p[@title]').text\n item.hotel_dist = hotel.find_element_by_xpath('//span/i').text # 单位:公里\n struct_data.append(item)\n print(\"%s->抓取完毕\" % item.hotel_name)\n bro.quit() # 退出浏览器\n for item in struct_data:\n print(str(item))\n return struct_data\n\n def get_hotel_comments(self,hotel_urls):\n \"\"\"传递酒店详情页的url,从其中提取进店评论\"\"\"\n print(\"get_hotel_comments方法正在测试,请等候完善\")\n\n def get_image(self,img_urls):\n \"\"\"获取酒店的图片,并以酒店名为文件夹名\"\"\"\n print(\"get_image方法正在完善,请稍后\")\n\n def save_data(self, struct_data):\n \"\"\"将结构化数据写入CSV文件\"\"\"\n fileName = u'xiecheng.csv'\n \"\"\"编码异常,待解决\"\"\"\n with open(fileName, 'ab',encoding='gb2312' ) as fp:\n for item in struct_data:\n # fp.write('%s \\t %s \\t %s \\t %s \\t %s \\t %s \\t \\%s \\t %s \\r\\n'\n # % (item.hotel_name, item.hotel_price, item.hotel_user_recom_perc,\n # item.hotel_grade,item.hotel_loc,item.hotel_dist,item.house_style,\n # item.hotel_with_jingqu))\n fp.write(item.hotel_name+'\\t')\n print(r'酒店名为:<<%s>>的数据已成功存入文件\"%s\"...'\n % (item.hotel_name, fileName.decode('utf-8')))\n\n def save_comment(self,txt):\n \"\"\"将酒店评论写入txt文件\"\"\"\n with open(dir_path,'ab',encoding='gb2312',bewline='') as fp:\n fp.write(txt)\n\n def make_dir(self,folder_name):\n \"\"\" 新建文件夹并切换到该目录下 \"\"\"\n path = os.path.join(dir_path, folder_name)\n # 如果目录已经存在就不用再次爬取了,去重,提高效率。存在返回 False,否则反之\n if not os.path.exists(path):\n os.makedirs(path)\n print(path)\n os.chdir(path)\n return True\n print(\"Folder has existed!\")\n return None\n\n\nif __name__ == '__main__':\n GH = GetHotel()\n","sub_path":"src/spider/HotelSpider.py","file_name":"HotelSpider.py","file_ext":"py","file_size_in_byte":7723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"34902434","text":"#!/usr/bin/python3\n\"\"\" Deploys \"\"\"\nfrom fabric.api import *\nfrom datetime import datetime\nimport shlex\nimport os\n\n\nenv.hosts = ['35.237.42.19', '107.21.12.250']\nenv.user = \"ubuntu\"\n\n\ndef deploy():\n \"\"\" FUNCTION COMPLETE DEPLOY \"\"\"\n try:\n archive_path = do_pack()\n except:\n return False\n return do_deploy(archive_path)\n\n\ndef do_pack():\n try:\n if not os.path.exists(\"versions\"):\n local('mkdir versions')\n tm = datetime.now()\n stamp = \"%Y%m%d%H%M%S\"\n file_path = 'versions/web_static_{}.tgz'.format(tm.strftime(stamp))\n local('tar -cvzf {} web_static'.format(file_path))\n return file_path\n except:\n return None\n\n\ndef do_deploy(archive_path):\n \"\"\" Deploy \"\"\"\n if not os.path.exists(archive_path):\n return False\n try:\n n = archive_path.replace('/', ' ')\n n = shlex.split(n)\n n = n[-1]\n w = n.replace('.', ' ')\n w = shlex.split(w)\n w = w[0]\n release = \"/data/web_static/releases/{}/\".format(w)\n tmp = \"/tmp/{}\".format(n)\n put(archive_path, \"/tmp/\")\n run(\"mkdir -p {}\".format(release))\n run(\"tar -xzf {} -C {}\".format(tmp, release))\n run(\"rm {}\".format(tmp))\n run(\"mv {}web_static/* {}\".format(release, release))\n run(\"rm -rf {}web_static\".format(release))\n run(\"rm -rf /data/web_static/current\")\n run(\"ln -s {} /data/web_static/current\".format(release))\n print(\"New version deployed!\")\n return True\n except:\n return False\n","sub_path":"3-deploy_web_static.py","file_name":"3-deploy_web_static.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"133842767","text":"from keras.applications.vgg16 import VGG16\r\nfrom keras.utils.vis_utils import plot_model\r\nfrom keras import models\r\nfrom keras import layers\r\nfrom keras import optimizers\r\nimport glob\r\nimport os\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nimport numpy as np\r\nimport keras\r\nimport pickle\r\nfrom funkcije import writeResToExcel, saveROC\r\nimport pydot\r\nimport pydot_ng\r\nimport graphviz\r\nfrom keras.utils.vis_utils import plot_model\r\n\r\nEXP_NP_FILE_NAME = ['4slices_1dim_Gauss_sag', '4slices_1dim_Gauss_cor',\r\n '4slices_1dim_Gauss_ax', '4slices_3dim_Gauss']\r\nEXP_modalitete = [['T1W','T2W','FLAIR','OTHER'], ['T1W','T2W','FLAIR','OTHER','T1W_CONTRAST'],['T1W', 'T1W_CONTRAST']]\r\n\r\nfor i_NP_FILE_NAME in EXP_NP_FILE_NAME:\r\n for i_modalitete in EXP_modalitete:\r\n\r\n SEED = 49\r\n NP_FILE_NAME = i_NP_FILE_NAME\r\n NUM_EPOCHS = 50\r\n LR = 1e-4\r\n\r\n ####### PODATKI ZA VPIS V EXCEL TABELO ###################\r\n # OPIS SLIK e.g. 4 rezine na sliko, samo sagitalni prerezi\r\n opis_slik = NP_FILE_NAME\r\n\r\n # IZBIRA REZIN e.g. Gauss, mean=dim/2, std=dim/4\r\n izbira_rezin = 'Gauss, mean=dim/2, std=dim/4'\r\n\r\n # MODALITETE ['T1W','T2W','FLAIR','OTHER'], 'T1W_CONTRAST'\r\n modalitete = i_modalitete\r\n if all((m == 'T1W' or m == 'T1W_CONTRAST') for m in modalitete):\r\n DELETE_IF_NOT_IN_MODALITETE = 1\r\n else:\r\n DELETE_IF_NOT_IN_MODALITETE = 0\r\n\r\n # NASTAVITVE e.g. VGG16, 50 epochs, RMSprop(lr=1e-4)\r\n nastavitve_CNN = 'VGG16, {} epochs, RMSprop(lr={}), seed={}'.format(NUM_EPOCHS, LR, SEED)\r\n excel_name = 'Rezultati_CNN_VGG16_round2'\r\n\r\n save_results = True\r\n\r\n\r\n base_path = r'/home/jovyan/shared/InteliRad-gasper'\r\n\r\n\r\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! UPLOAD BEFORE RUNNING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n\r\n\r\n image_size = 128\r\n\r\n vgg_conv = VGG16(weights='imagenet', include_top=False, input_shape=(image_size, image_size, 3))\r\n\r\n # Freeze the layers except the last 4 layers\r\n for layer in vgg_conv.layers[:-4]:\r\n layer.trainable = False\r\n\r\n # Check the trainable status of the individual layers\r\n for layer in vgg_conv.layers:\r\n print(layer, layer.trainable)\r\n\r\n vgg_conv.summary()\r\n\r\n # Create the model\r\n model = models.Sequential()\r\n\r\n # Add the vgg convolutional base model\r\n model.add(vgg_conv)\r\n\r\n # Add new layers\r\n model.add(layers.Flatten())\r\n model.add(layers.Dense(1024, activation='relu'))\r\n model.add(layers.Dropout(0.5))\r\n model.add(layers.Dense(len(modalitete), activation='softmax'))\r\n\r\n # Show a summary of the model. Check the number of trainable parameters\r\n model.summary()\r\n # plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)\r\n\r\n os.chdir(os.path.join(base_path, 'PREPARED_IMAGES'))\r\n X = np.load(NP_FILE_NAME + '.npy')\r\n X = np.stack((X,)*3, axis=-1)\r\n\r\n with open (NP_FILE_NAME + '_ref.txt', 'rb') as fp:\r\n y_raw = pickle.load(fp)\r\n\r\n y_modality = [i[:-1] for i in y_raw]\r\n y_contrast = [i[-1] for i in y_raw]\r\n\r\n X_prep = np.ones_like(X)\r\n\r\n y = []\r\n idx_stay = 0\r\n for i, mdl in enumerate(y_modality):\r\n if mdl == 'T1W' and y_contrast[i] == '1' and 'T1W_CONTRAST' in modalitete:\r\n y.append('T1W_CONTRAST')\r\n if DELETE_IF_NOT_IN_MODALITETE:\r\n X_prep[idx_stay,:,:,:] = X[i,:,:,:]\r\n idx_stay += 1\r\n elif mdl not in modalitete:\r\n if DELETE_IF_NOT_IN_MODALITETE:\r\n pass\r\n else:\r\n y.append('OTHER')\r\n else:\r\n y.append(mdl)\r\n if DELETE_IF_NOT_IN_MODALITETE:\r\n X_prep[idx_stay,:,:,:] = X[i,:,:,:]\r\n idx_stay += 1\r\n\r\n y = pd.DataFrame({'ref': y})\r\n if DELETE_IF_NOT_IN_MODALITETE:\r\n X_prep = X_prep[:idx_stay]\r\n else:\r\n X_prep = X\r\n\r\n # y = y.replace(['?', 'SPINE_OTHER', 'SPINE_T1W', 'SPINE_T2W', 'SPINE_FLAIR'], 'OTHER')\r\n\r\n\r\n\r\n y = y.astype('category', categories=modalitete)\r\n y = pd.get_dummies(y)\r\n y_np = y.values\r\n\r\n X_train, X_test, y_train, y_test = train_test_split(X_prep,y_np, random_state=SEED)\r\n\r\n\r\n model.compile(loss='categorical_crossentropy',\r\n optimizer=optimizers.RMSprop(lr=LR),\r\n metrics=['acc'])\r\n\r\n model.fit(X_train, y_train,\r\n epochs=NUM_EPOCHS,\r\n validation_data=(X_test, y_test))\r\n\r\n score_train = model.evaluate(X_train, y_train, verbose=0)\r\n score_test = model.evaluate(X_test, y_test, verbose=0)\r\n\r\n y_pred = model.predict(X_test)\r\n\r\n\r\n roc_micro, roc_macro = saveROC(y_test, y_pred, save_results)\r\n\r\n if save_results:\r\n results = {'Input': opis_slik,\r\n 'Input_opis': izbira_rezin,\r\n 'Modalitete': ', '.join(modalitete),\r\n 'Nastavitve': nastavitve_CNN,\r\n 'Train_acc': score_train[1],\r\n 'Test_acc': score_test[1],\r\n 'Train_loss': score_train[0],\r\n 'Test_loss': score_test[0],\r\n 'ROC_micro': roc_micro,\r\n 'ROC_macro': roc_macro}\r\n\r\n writeResToExcel(excel_name, results)\r\n\r\n\r\n print('Test loss:', score_test[0])\r\n print('Test accuracy:', score_test[1])\r\n\r\n# tensorflow version 1.4.0 and keras version 2.0.8.\r\n# CUDA 8.0\r\n# cudnn 6.0","sub_path":"Scripts/CNN_VGG16.py","file_name":"CNN_VGG16.py","file_ext":"py","file_size_in_byte":5782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"489370179","text":"import cv2\nimport mul_images\nimport numpy as np\nimport import_images as ii\n\n\ndef shapes():\n white_image = np.ones((512, 512, 3)) # 1->white and 0->black\n # shapes\n color = (0, 0, 0) # bgr in opencv\n cv2.rectangle(white_image, (0, 0), (512, 512), color, 5)\n cv2.circle(white_image, (256, 256), 100, (255, 0, 0), 5)\n cv2.circle(white_image, (256, 256), 50, (255, 0, 0), -1) # if thickness is -1 then it will the color\n cv2.line(white_image, (156, 256), (356, 256), (0, 0, 255), 5)\n polygon_points = np.array([(0, 256), (256, 156), (512, 256), (256, 356)],\n np.int32) # these are vertices of the polygon and these must be in form of int32\n polygon_points = polygon_points.reshape(\n (-1, 1, 2)) # after change the shape into ROWS*1*2 and in reshape(-1)->flattening of array\n cv2.polylines(white_image, [polygon_points], True, color, 5) # true is for ->isClosed argument\n\n # text\n cv2.putText(white_image, 'madhav', (125, 400), cv2.FONT_ITALIC, 2, (0, 255, 0), 3)\n\n cv2.imshow('white', white_image)\n cv2.waitKey(0)\n\n'''\ncv2.namedWindow('blackwindow',cv2.WINDOW_NORMAL)# there are totally 6 flages normal,auto_size,gui_normal,gui_expanded,fullscreen,keepratio,freeratio,opengl\n cv2.resizeWindow('blackwindow',512,512)#to resize the window\n'''\n\ndef empty(x):\n pass\n\ndef trackbar():\n cv2.namedWindow('trackbars')#window to hold trackbars\n #creating trcakbars\n cv2.createTrackbar('blue','trackbars',0,255,empty)\n cv2.createTrackbar('green', 'trackbars', 0, 255, empty)\n cv2.createTrackbar('red', 'trackbars', 0, 255, empty)\n\n black = np.zeros((512, 512, 3), np.uint8)\n while True:\n\n cv2.imshow('trackbars', black)\n if cv2.waitKey(1) & 0xFF == ord('s'):\n break\n # here b,g,r has the value of trackbars at instant\n b = cv2.getTrackbarPos('blue', 'trackbars')\n g = cv2.getTrackbarPos('green', 'trackbars')\n r = cv2.getTrackbarPos('red', 'trackbars')\n black[:] = [b,g,r]\n\n\n cv2.destroyAllWindows()\n\nimg = cv2.imread('imageSources/black_ball.jpg')\nimage = cv2.resize(img,(512,512))\n\ndef click_mouse(event,x,y,flags,param):\n points = []\n if event == cv2.EVENT_LBUTTONDBLCLK:\n print('x and y coordinates')\n print('x =',x,'y =',y)\n print('bgr values at'+'('+str(x)+','+str(y)+')','=',image[x,y])\n cv2.circle(image,(x,y),2,(0,0,255),-1)\n points.append((x,y))\n if event == cv2.EVENT_RBUTTONDBLCLK and len(points)>2:\n poly_points = np.array(points,np.int32)\n poly_points = poly_points.reshape((-1,1,2))\n cv2.polylines(image,poly_points,True,(0,255,0),2)\n\ndef paint_brush():\n\n '''\n print([i for i in dir(cv2) if 'EVENT' in i])\n ['EVENT_FLAG_ALTKEY', 'EVENT_FLAG_CTRLKEY', 'EVENT_FLAG_LBUTTON', 'EVENT_FLAG_MBUTTON', 'EVENT_FLAG_RBUTTON',\n 'EVENT_FLAG_SHIFTKEY', 'EVENT_LBUTTONDBLCLK', 'EVENT_LBUTTONDOWN', 'EVENT_LBUTTONUP', 'EVENT_MBUTTONDBLCLK', 'EVENT_MBUTTONDOWN',\n 'EVENT_MBUTTONUP', 'EVENT_MOUSEHWHEEL', 'EVENT_MOUSEMOVE', 'EVENT_MOUSEWHEEL', 'EVENT_RBUTTONDBLCLK', 'EVENT_RBUTTONDOWN', 'EVENT_RBUTTONUP']\n '''\n#learning mouse events in opencv. Possible through setMouseCallback() method\n\n cv2.namedWindow('paint_brush_window')\n cv2.setMouseCallback('paint_brush_window',click_mouse)\n\n while True:\n cv2.imshow('paint_brush_window',image)\n if cv2.waitKey(1) & 0xFF == ord('s'):\n break\n cv2.destroyAllWindows()\n\n#paint_brush()\n\n\n\n\n\ndef finding_bgr_single_image(image,winName):\n def bgr(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDBLCLK:\n #cv2.circle(image, (x, y), 2, (0, 0, 255), -1)\n print(image.shape)\n print(winName+'[' + str(x) + ',' + str(y) + ']', image[y,x])\n points.append((x, y))\n\n points =[]\n cv2.namedWindow(winName)\n cv2.setMouseCallback(winName,bgr)\n image = cv2.resize(image,(512,512))\n cv2.imshow(winName,image)\n return points\n\ndef finding_bgr(image,winName):\n def bgr(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDBLCLK:\n #cv2.circle(image, (x, y), 2, (0, 0, 255), -1)\n\n print(winName+'[' + str(x) + ',' + str(y) + ']', image[y,x])\n points.append((x, y))\n\n points =[]\n cv2.namedWindow(winName)\n cv2.setMouseCallback(winName,bgr)\n # print(image.shape)\n\n cv2.imshow(winName , image)\n if cv2.waitKey(0) & 0xff == 's':\n cv2.destroyAllWindows()\n return points\n\n","sub_path":"OPENCV BEGGINNER LEVEL/code/gui_features.py","file_name":"gui_features.py","file_ext":"py","file_size_in_byte":4525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"385040583","text":"# Software License Agreement (BSD License)\n#\n# Copyright (c) 2008, Thibault Kruse\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n'functions to detect source files, tests and documentation'\n\nfrom __future__ import absolute_import, print_function, unicode_literals\nimport os\nfrom unilint.unilint_plugin import UnilintPlugin\nfrom unilint.common import is_script\n\n__pychecker__ = '--unusednames=cls,options,subdirs'\n\nCOMMON_SOURCE = 'common_source'\n\n\ndef splitpath(path):\n '''Lists all folders in a path'''\n result = []\n if not path:\n return result\n restpath = os.path.normpath(path)\n (_, restpath) = os.path.splitdrive(path)\n dirname = None\n while True:\n (dirname, basename) = os.path.split(restpath)\n if basename:\n result.insert(0, basename)\n if dirname == restpath:\n break\n restpath = dirname\n return result\n\n\nclass CommonSourcePlugin(UnilintPlugin):\n \"\"\"Identifies files and folders with scripts, documentation, tests\"\"\"\n\n def __init__(self, shell_function):\n super(CommonSourcePlugin, self).__init__(shell_function)\n\n @classmethod\n def get_id(cls):\n return COMMON_SOURCE\n\n def categorize_type(self, options, path, subdirs, files):\n result = {}\n if files is not None:\n if os.path.basename(path) in ['bin', 'scripts']:\n for filename in files:\n fullname = os.path.join(path, filename)\n if is_script(fullname):\n result[fullname] = ['script']\n else:\n if is_script(path):\n result[path] = ['script']\n\n path_elts = splitpath(path)\n if 'doc' in path_elts or 'doc-pak' in path_elts:\n if path not in result:\n result[path] = ['doc']\n else:\n result[path].append('doc')\n\n # only categorize actual test folder as tests, so pointing at\n # resource below works without -t option\n if path_elts[-1] in ['test', 'tests']:\n if path not in result:\n result[path] = ['test']\n else:\n result[path].append('test')\n\n if not files:\n files = [path]\n\n for filepath in files:\n if os.path.islink(path) and \\\n not os.path.exists(os.readlink(filepath)):\n result[fullname] = ['broken']\n filename = os.path.basename(filepath)\n\n def _categorize(path, filepath, category):\n 'assigns hidden and backup category'\n if filepath != path:\n filepath = os.path.join(path, filepath)\n result[filepath] = [category]\n\n for prefix in ['.', '#']:\n if filename.startswith(prefix):\n _categorize(path, filepath, 'hidden')\n break\n for suffix in ['~', '.orig', '.bak']:\n if filename.endswith(suffix):\n _categorize(path, filepath, 'backup')\n break\n for infix in ['.BACKUP.', '.BASE.', '.LOCAL.', '.REMOTE.']:\n if infix in filename:\n _categorize(path, filepath, 'backup')\n break\n return result\n","sub_path":"src/unilint/common_source_plugin.py","file_name":"common_source_plugin.py","file_ext":"py","file_size_in_byte":4542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"167524531","text":"from flask import Blueprint, flash, render_template, request\nfrom sqlalchemy import exc\nfrom app import db\nfrom app.forms import AddInstrumentForm, AddMusicForm, AddOriginalAuthorForm, AddStyleForm\nfrom app.models import Instrument, Music, Style, OriginalAuthor\n\nbp = Blueprint('admin', __name__)\n\n@bp.route('/admin/instrument/', methods=['GET', 'POST'])\ndef add_instrument():\n \"\"\"Renders the page for adding an instrument, as well as handling the\n addition of an instrument into the database.\"\"\"\n error = False\n status = None\n form = AddInstrumentForm()\n\n if form.validate_on_submit():\n try:\n name = form.name.data\n info = form.info.data\n range = form.range.data\n image = form.image.data\n instrument = Instrument(name=name, info=info, range=range, image=image)\n db.session.add(instrument)\n db.session.commit()\n flash(\"Instrument added successfully.\")\n except exc.IntegrityError as err:\n error = True\n print('/admin/instrument/:', err)\n flash(\"Something went wrong with adding the instrument. Please try again.\")\n except Exception as err:\n error = True\n print(\"Unexpected error:\", err)\n flash(\"Something went wrong with adding the instrument. Please try again.\")\n return render_template('admin_instrument.html', title=\"Admin\", error=error, form=form)\n\n@bp.route('/admin/style/', methods=['GET', 'POST'])\ndef add_style():\n \"\"\"Renders the page for adding a style/genre, as well as handling the\n addition of a style into the database.\"\"\"\n error = False\n form = AddStyleForm()\n if form.validate_on_submit():\n try:\n style = Style(\n style=form.name.data,\n description=form.description.data,\n )\n db.session.add(style)\n db.session.commit()\n flash(\"Style added successfully.\")\n except exc.IntegrityError as err:\n # Raised by database itself\n error = True\n print('/admin/style/:', err)\n flash(\"Something went wrong with adding the style. Please try again.\")\n except Exception as err:\n # Any weird errors, time to debug\n error = True\n print(\"Unexpected error:\", err)\n flash(\"Something went wrong with adding the style. Please try again.\")\n return render_template('admin_style.html', title=\"Admin\", error=error, form=form)\n\n@bp.route('/admin/author/', methods=['GET', 'POST'])\ndef add_originalauthor():\n # Converts date in format 2010-12-25 to UNIX timestamp\n # int(time.mktime(datetime.datetime.strptime(s, \"%Y-%m-%d\").timetuple()))\n error = False\n status = None\n form = AddOriginalAuthorForm()\n\n if form.validate_on_submit():\n try:\n author = OriginalAuthor(name=form.name.data, country=form.country.data, dob=form.dob.data)\n db.session.add(author)\n db.session.commit()\n flash(\"Author added successfully.\")\n except exc.IntegrityError as err:\n error = True\n print('/admin/author/:', err)\n flash(\"Something went wrong with adding the author. Please try again.\")\n except Exception as err:\n error = True\n print(\"Unexpected error:\", err)\n flash(\"Something went wrong with adding the author. Please try again.\")\n return render_template('admin_originalauthor.html', title=\"Admin\", error=error, form=form)\n\n@bp.route('/admin/music/', methods=['GET', 'POST'])\ndef add_music():\n \"\"\"Renders the page for adding music, as well as handling the addition of a\n piece of music into the database.\"\"\"\n error = False\n status = None\n form = AddMusicForm()\n styles = Style.query.all()\n authors = OriginalAuthor.query.all()\n # [('', '')] is default - None\n form.style.choices = [('', '')] + [(i.style, i.style) for i in Style.query.all()]\n # TODO: see if there's a way to have ('', '') as an option\n # despite coerce=int\n form.original_author.choices = [(i.id, i.name) for i in OriginalAuthor.query.all()]\n form.instruments.choices = [(i.id, i.name) for i in Instrument.query.order_by('name')]\n if form.validate_on_submit():\n try:\n # Turn list of instrument IDs into list of instrument objects to\n # make flask happy\n instruments = [Instrument.query.get(i) for i in form.instruments.data]\n music = Music(\n name=form.name.data,\n year=form.year.data,\n url=form.url.data,\n sheet_url=form.sheet_url.data,\n style_id=form.style.data,\n original_author_id=form.original_author.data,\n instruments=instruments,\n )\n db.session.add(music)\n db.session.commit()\n flash(\"Music added successfully.\")\n except exc.IntegrityError as err:\n error = True\n print('/admin/music/:', err)\n flash(\"Something went wrong with adding the music. Please try again.\")\n except Exception as err:\n error = True\n print(\"Unexpected error:\", err)\n flash(\"Something went wrong with adding the music. Please try again.\")\n return render_template('admin_music.html', title=\"Admin\", error=error, form=form, styles=styles)\n","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"9679676","text":"# Krzysztof Kubicki & Robert Jeżewski\r\n# Firma\r\n\r\n\r\n\r\nimport datetime\r\n\r\n\r\nclass Firma():\r\n\r\n def menu(self):\r\n\r\n print (\" ***** MENU ******\")\r\n print ((self.nazwa).center(20))\r\n print(\" 1 - listuj pracownikow\")\r\n print(\" 2 - zmien stanowisko pracownika\")\r\n print(\" 3 - Dodaj pracownika\")\r\n print(\" 4 - Podaj staz pracownika\")\r\n print(\" 5 - Wyswietl / Zmień szefa\")\r\n print(\" 6 - Wyswietl / Zmień dział\")\r\n print((self.nazwa).center(20))\r\n\r\n wybor = input (str(\" Wybierz 1 - 4 \"))\r\n if wybor.isdecimal() != True:\r\n print(\" Wybierz cyfre 1 - 4\")\r\n\r\n if wybor == '1':\r\n self.listuj_pracownikow()\r\n self.menu()\r\n elif wybor == '2':\r\n naz = input(str(\"Podaj nazwisko\"))\r\n self.awansuj_pracownika(naz)\r\n self.menu()\r\n elif wybor == '3':\r\n self.dodaj_pracownika()\r\n self.menu()\r\n\r\n elif wybor == '4':\r\n naz = input(str(\"Podaj nazwisko pracownika, dla ktorego chcesz wyswietlic staz\"))\r\n for i in self.lista_pracownikow:\r\n if i.nazwisko == naz:\r\n print(\"Staz pracownika o nazwisku\", naz)\r\n print(datetime.datetime.now() - i.start)\r\n self.menu()\r\n elif wybor == '5':\r\n print(\"Wybierz pracownika, dla ktorego chcesz zmienic szefa\")\r\n pracownik = self.listuj_i_zwroc_pracownika()\r\n print(\"Wybierz szefa\")\r\n nowy_szef = self.listuj_i_zwroc_pracownika()\r\n pracownik.szef = nowy_szef.nazwisko\r\n self.menu()\r\n\r\n elif wybor == '6':\r\n print(\"Wybierz pracownika, dla ktorego chcesz zmienic dzial\")\r\n pracownik = self.listuj_i_zwroc_pracownika()\r\n print(\"Wybierz dzial\")\r\n nowy_dzial = self.listuj_i_zwroc_pracownika()\r\n pracownik.dzial = nowy_dzial.dzial\r\n self.menu()\r\n\r\n\r\n def __init__(self, nazwa):\r\n self.nazwa = nazwa\r\n self.lista_pracownikow = []\r\n\r\n def add_dummy_data(self):\r\n ''' Dodanie testowych danych'''\r\n p1 = Pracownik(\"Krzysztof\", \"Kubicki\", \"blabla\", \"dzial1\", \"Stefan\")\r\n p2 = Pracownik(\"Robert\", \"Jeżewski\", \"inzynier\", \"dzial2\", \"Maciek\")\r\n p3 = Pracownik(\"Johny\", \"Rambo\", \"masakrator\", \"dzial666\", \"Bog\")\r\n self.lista_pracownikow.extend([p1, p2, p3])\r\n\r\n def listuj_i_zwroc_pracownika(self):\r\n ''' Listuje liste pracownikow i zwraca wybrany obiekt (Obiekt --- a nie index obiektu)))'''\r\n self.listuj_pracownikow()\r\n print(\"Wybierz od 0 do \" + str((len(self.lista_pracownikow))) + \"pracownika, którego chcesz wybrać\")\r\n index_na_liscie_pracownikow = input(\"Podaj index z listy\")\r\n #print()\r\n return self.lista_pracownikow[int(index_na_liscie_pracownikow)]\r\n\r\n def dodaj_pracownika(self):\r\n ''' Dodawanie pracownika'''\r\n imie = input (str(\" Podaj imie pracowniks\"))\r\n nazwisko = input(str( \" Podaj nazwisko pracownika\"))\r\n stawisko = input(str( \" Podaj stanowisko\"))\r\n dzial = input(str( \" Podaj dzial\"))\r\n szef = input (str(\" Podaj kto jest szefem pracownika\"))\r\n pracownik = Pracownik(imie, nazwisko, stawisko, dzial, szef)\r\n self.lista_pracownikow.append(pracownik)\r\n\r\n def listuj_pracownikow(self):\r\n ''' Listowanie'''\r\n for i in self.lista_pracownikow:\r\n print (self.lista_pracownikow.index(i), i.imie, i.nazwisko, \"Data rozpoczecia\", i.start, i.stanowisko, i.dzial, i.szef)\r\n\r\n def awansuj_pracownika(self, nazwisko):\r\n self.listuj_pracownikow()\r\n for i in self.lista_pracownikow:\r\n if i.nazwisko == nazwisko:\r\n i.nazwisko = input(str(\" Podaj nowe stanowisko\"))\r\n self.listuj_pracownikow()\r\n\r\nclass Osoba():\r\n def __init__(self, imie, nazwisko):\r\n self.imie = imie\r\n self.nazwisko = nazwisko\r\n\r\nclass Pracownik(Osoba):\r\n\r\n def __init__(self, imie, nazwisko, stanowisko, dzial, szef):\r\n Osoba.__init__(self, imie = imie, nazwisko = nazwisko)\r\n self.stanowisko = stanowisko\r\n self.start = datetime.datetime.now()\r\n self.dzial = dzial\r\n self.szef = szef\r\n\r\n def wyswietla_pracownika(self):\r\n print(self.imie, self.nazwisko, self.stanowisko, self.start, self.dzial, self.szef)\r\n\r\n#p1 = Pracownik(\"Krzysztof\", \"Kubicki\").costam()\r\n#p2 = Pracownik(\"Krzysiek\").costam()\r\n#p3 = Pracownik(\"Krzysztof\", \"Kubicki\", \"blabla\", \"wtorek\", \"dzial1\", \"Stefan\" ).costam()\r\n\r\n\r\nf = Firma(\" Super Firma\")\r\nf.add_dummy_data()\r\nf.menu()\r\n\r\n#f.dodaj_pracownika()\r\n#f.listuj_pracownikow()\r\n#f.awansuj_pracownika(\"Kubicki\")\r\n","sub_path":"Firma.py","file_name":"Firma.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"160982000","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nHold individual inspection functions that may be called on by the config.json being used.\n\"\"\"\n\n# Imports\n\n\n# Local Imports\nfrom sharedFunctionLib import *\nfrom errors import simpleErrors\nimport requests\n\nerrors = simpleErrors()\n\n# ###################################################################################\n# Confirm that all columns specified as mandatory are present in the column headers\n\ndef confirmExpectedColumns(df, warnings, args):\n\n cols = parseArgs(\"cols\", args)\n\n missing = []\n for col in cols:\n if col not in df.columns.values:\n missing.append(col)\n\n if len(missing) > 0:\n errors.unexpectedColumns(missing)\n\n return warnings\n\n\n# ###################################################################################\n# Check PER_ROW that AT_LEAST-ONE of the columns in this group has a value\n# example: you might need to have either an observation or a datamarker\ndef confirmAtLeastOnePopulated(df, warnings, args):\n\n # Get columns\n cols = prepareColumnHeaders(df, args)\n\n # Create a sample frame with just the columns we are looking at merged into one\n # if there's only one columns - skip most of this\n sampleFrame = concatenateIntoFirstColumn(df, cols)\n\n # Return row indexes where the \"cell\" is still blank\n resultsList = sampleFrame[cols[0]][sampleFrame[cols[0]].astype(str) == \"\"]\n\n # Add one to row numbers, as headers are not indexed\n # i.e in pandas, row 1 of a spreadsheet is row 0\n resultsList = [x+1 for x in resultsList.index.values]\n totalResults = len(resultsList)\n\n # Limit result rows\n if len(resultsList) > 10:\n resultsList = resultsList[:10]\n\n if len(resultsList) > 0:\n errorText = \"At least one of these columns '{cols}' should always have a value. The following rows (showing {a} out of {b}) do not: \".format(a=len(resultsList), b=totalResults,cols=\",\".join(cols)) + \".\".join(cols)\n errors.missingItems(errorText)\n\n return warnings\n\n\n# ###################################################################################\n# Conpares a column of data to a trusted source\ndef compareItemsToSource(df, warnings, args):\n\n supportedTypes = [\"json-api\"]\n\n # Get type\n type = parseArgs(\"type\", args)\n if type not in supportedTypes:\n errors.typeNotSupported(type)\n\n if type == \"json-api\":\n uri = parseArgs(\"uri\", args)\n pattern = parseArgs(\"pattern\", args)\n\n r = requests.get(uri)\n if r.status_code != 200:\n errors.cannotRequestJson(uri)\n\n data = r.json()\n\n iterationCounts = {\"i\":None, \"j\":None}\n iteratorList = [\"i\", \"j\"]\n\n steps = \"data\"\n correctItems = []\n for step in pattern.split(\">\"):\n\n if \"EACH#\" in step:\n it = iteratorList.pop(0)\n item = step[5:]\n iterationCounts[it] = len(eval(steps + '[\"' + item + '\"]'))\n steps = steps + '[\"' + item + '\"]' + \"[\" + it + \"]\"\n\n else:\n steps = steps + \"['\" + step + \"']\"\n\n if iterationCounts[\"i\"] != None and iterationCounts[\"j\"] != None:\n\n for i in range(0, iterationCounts[\"i\"]):\n for j in iterationCounts[\"j\"]:\n correctItems.append(eval(steps))\n\n elif iterationCounts[\"i\"] != None:\n\n for i in range(0, iterationCounts[\"i\"]):\n correctItems.append(eval(steps))\n\n targetCol = type = parseArgs(\"target_col\", args)\n col = df.columns.values[targetCol]\n itemsWeHave = df[col].unique()\n\n notFoundList = []\n for item in itemsWeHave:\n\n if item not in correctItems:\n notFoundList.append(item)\n\n if len(notFoundList) > 0:\n errors.incorrectItems(notFoundList, uri)\n\n return warnings\n\n\n# ###################################################################################\n# Check whether the level of sparsity in the dataset is enough to trigger a warning or error\ndef confirmAcceptableSparsity(df, warnings, args):\n\n warningLevel = parseArgs(\"warning_level\", args)\n errorLevel = parseArgs(\"error_level\", args)\n cols = parseArgs(\"cols\", args)\n\n # Calculate sparsity\n rowCount = len(df)\n\n debug = []\n expected = 1\n for i in cols:\n dfCol = df.columns.values[i]\n expected = expected * len(df[dfCol].unique())\n debug.append(len(df[dfCol].unique()))\n\n sparsityAsZeroToOne = 1 - ((1 / rowCount) * expected)\n\n if sparsityAsZeroToOne > errorLevel:\n errors.sparsityError(sparsityAsZeroToOne)\n elif sparsityAsZeroToOne > warningLevel:\n warnings.update({\"Sparsity is above the warning level\":\"Warning: {w}. Actual: {a}\".format(w=warningLevel,a=sparsityAsZeroToOne)})\n\n return warnings\n\n\n# Controller\n# ==========\n# A function controller, that calls functions based on name-as-string\ndef funcController(wantedFunc, df, resultsDict, args):\n\n funcLookup = {\n \"confirmExpectedColumns\": confirmExpectedColumns,\n \"confirmAtLeastOnePopulated\": confirmAtLeastOnePopulated,\n \"confirmAcceptableSparsity\": confirmAcceptableSparsity,\n \"compareItemsToSource\": compareItemsToSource\n }\n return funcLookup[wantedFunc](df, resultsDict, args)\n\n\n\n\n\n\n\n\n\n","sub_path":"csvInspector/inspectFunctionLib.py","file_name":"inspectFunctionLib.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"476344234","text":"class Decrypt(object):\r\n def __init__(self,Encrypted_word):\r\n self.Encrypted_word = Encrypted_word\r\n self.DecryptedWords = {}\r\n def Decrypt_Word(self):\r\n for i in range(0,27):\r\n string = ''\r\n for x in self.Encrypted_word:\r\n pos=((ord(x)-ord('a'))-i)%26+ord(\"a\")\r\n string += chr(pos)\r\n self.DecryptedWords[i]=string\r\n return self.DecryptedWords\r\n \r\n\r\n def checkWord(self):\r\n f = open('words.txt','r')\r\n for line in f:\r\n x=line.split(' ')\r\n for word in x:\r\n if word in self.DecryptedWords.values():\r\n return \"The decryption of the word is %s\"%(word) \r\n\r\n \r\n \r\n\r\ntrial =Decrypt('fhei')\r\nprint(trial.Decrypt_Word(),'\\n')\r\nprint(trial.checkWord())","sub_path":"Decrypt.py","file_name":"Decrypt.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"312443241","text":"import pickle\nimport pandas as pd\n\nwith open('classification_model.pkl', 'rb') as f:\n reg = pickle.load(f)\n\nInp_Arr=[]\n\nfor elem in [\"Cycle#\", 11, 9, 12, 4]:\n if elem == \"Cycle#\":\n print(\"Enter \" + str(elem))\n cycle_num = input()\n Inp_Arr.append(int(cycle_num))\n else:\n print(\"Enter Value for Sensor_\" + str(elem))\n sensor_val = input()\n Inp_Arr.append(float(sensor_val))\n\ndata_f = pd.DataFrame(columns = [\"Cycle#\", 'Sensor_11', 'Sensor_9', 'Sensor_12', 'Sensor_4'])\ndata_f.loc[len(data_f)] = Inp_Arr\nprediction = reg.predict(data_f)\n\nif prediction == 0:\n cond = 'Healthy'\nelse:\n cond = 'Faulty'\n\nprint(\"Engine Condition is {}\".format(cond))\n\n","sub_path":"QuAMs/QuAM_Classification.py","file_name":"QuAM_Classification.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"513726323","text":"\"\"\"\nCode for fitness functions comparisons experiment: n seed sets are randomly sampled, each fitness function is evaluated\nand the pearson correlation of the resulting values is computed\n\"\"\"\n\nimport networkx as nx\nimport argparse\nimport pandas as pd\nfrom functools import partial\nimport random\nimport numpy as np\nimport time\n\nfrom utils import add_weights_WC, add_weights_IC, dict2csv\nfrom load import read_graph\nfrom spread.two_hop import two_hop_spread\nfrom spread.monte_carlo_max_hop import MonteCarlo_simulation as monte_carlo_max_hop\nfrom spread.monte_carlo import MonteCarlo_simulation as monte_carlo\n\nif __name__ == \"__main__\":\n\n\tparser = argparse.ArgumentParser(description='Spread functions computation')\n\tparser.add_argument('--k', type=int, default=5, help='seed set size')\n\tparser.add_argument('--p', type=float, default=0.01, help='probability of influence spread in IC model')\n\tparser.add_argument('--n', type=int, default=100, help='number of seed set extractions')\n\tparser.add_argument('--max_hop', type=int, default=2, help='number of simulations for spread calculation'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t' when montecarlo mehtod is used')\n\tparser.add_argument('--model', default=\"IC\", choices=['IC', 'WC'], help='type of influence propagation model')\n\tparser.add_argument('--g_nodes', type=int, default=1000, help='number of nodes in the graph')\n\tparser.add_argument('--g_new_edges', type=int, default=2, help='number of new edges in barabasi-albert graphs')\n\tparser.add_argument('--g_type', default='barabasi_albert', choices=['barabasi_albert', 'wiki', 'amazon', 'epinions',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'twitter', 'facebook', 'CA-GrQc'], help='graph type')\n\tparser.add_argument('--g_seed', type=int, default=0, help='random seed of the graph')\n\tparser.add_argument('--g_file', default=None, help='location of graph file')\n\tparser.add_argument('--random_seed', type=int, default=42, help='seed to initialize the pseudo-random number '\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'generation')\n\tparser.add_argument('--no_simulations', type=int, default=100, help='number of simulations for spread calculation'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t' when montecarlo mehtod is used')\n\tparser.add_argument('--out_dir', default=\".\", help='location of the output directory in case if outfile is preferred'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t' to have default name')\n\targs = parser.parse_args()\n\n\t# create / load graph\n\tif args.g_file is None:\n\t\tif args.g_type == \"barabasi_albert\":\n\t\t\tG = nx.generators.barabasi_albert_graph(args.g_nodes, args.g_new_edges, seed=args.g_seed)\n\t\telif args.g_type == \"wiki\":\n\t\t\tG = read_graph(\"../experiments/datasets/wiki-Vote.txt\", directed=True)\n\t\t\targs.g_nodes = len(G.nodes())\n\t\telif args.g_type == \"amazon\":\n\t\t\tG = read_graph(\"../experiments/datasets/amazon0302.txt\", directed=True)\n\t\t\targs.g_nodes = len(G.nodes())\n\t\telif args.g_type == \"twitter\":\n\t\t\tG = read_graph(\"../experiments/datasets/twitter_combined.txt\", directed=True)\n\t\t\targs.g_nodes = len(G.nodes())\n\t\telif args.g_type == \"facebook\":\n\t\t\tG = read_graph(\"../experiments/datasets/facebook_combined.txt\", directed=False)\n\t\t\targs.g_nodes = len(G.nodes())\n\t\telif args.g_type == \"CA-GrQc\":\n\t\t\tG = read_graph(\"../experiments/datasets/CA-GrQc.txt\", directed=True)\n\t\t\targs.g_nodes = len(G.nodes())\n\t\telif args.g_type == \"epinions\":\n\t\t\tG = read_graph(\"../experiments/datasets/soc-Epinions1.txt\", directed=True)\n\t\t\targs.g_nodes = len(G.nodes())\n\n\t# extract n seed sets\n\tseed_sets = []\n\tprng = random.Random(args.random_seed)\n\tfor _ in range(args.n):\n\t\tseed_set = []\n\t\tfor _ in range(args.k):\n\t\t\tseed_set.append(prng.randint(0, args.g_nodes-1))\n\t\tseed_sets.append(seed_set)\n\n\t# initialize fitness functions\n\tmonte_carlo_mh = partial(monte_carlo_max_hop, G=G, p=args.p, max_hop=args.max_hop, random_generator=prng,\n\t\t\t\t\t\t\t no_simulations=args.no_simulations, model=args.model)\n\tmonte_carlo_ = partial(monte_carlo, G=G, random_generator=prng, p=args.p, no_simulations=args.no_simulations, model=args.model)\n\ttwo_hop = partial(two_hop_spread, G=G, model=args.model, p=args.p)\n\n\t# output file\n\toutfile_name = args.out_dir + \"/\" + \"results.csv\"\n\tf = open(outfile_name, \"w\")\n\n\tout_cols = [\"n{}\".format(i) for i in range(args.k)]\n\n\tfor col in [\"monte_carlo\", \"monte_carlo_max_hop\", \"two_hop\"]:\n\t\tout_cols.append(col)\n\tf.write(\",\".join(out_cols))\n\n\tG_nodes = np.array(G.nodes())\n\n\t# logging computation time\n\tcomp_time_mc = np.zeros(len(seed_sets))\n\tcomp_time_mh = np.zeros(len(seed_sets))\n\tcomp_time_th = np.zeros(len(seed_sets))\n\n\tfor i, S in enumerate(seed_sets):\n\t\tf.write(\"\\n\")\n\t\tA = G_nodes[S]\n\t\tnow = time.time()\n\t\tmc, _ = monte_carlo_(A=A)\n\t\tcomp_time_mc[i] = time.time() - now\n\t\tprint(\"Monte carlo comp.time: {}\".format(comp_time_mc[i]))\n\t\tnow = time.time()\n\t\tmc_mh, _ = monte_carlo_mh(A=A)\n\t\tcomp_time_mh[i] = time.time() - now\n\t\tprint(\"Monte carlo max hop comp.time: {}\".format(comp_time_mh[i]))\n\t\tnow = time.time()\n\t\tth = two_hop(A=A)\n\t\tcomp_time_th[i] = time.time() - now\n\t\tprint(\"Two hop comp.time: {}\".format(comp_time_th[i]))\n\t\tf.write(\",\".join(map(str, S)) + \",\")\n\t\tf.write(\",\".join(map(str, [mc, mc_mh, th])))\n\n\tf.close()\n\n\t# calculate correlation among results\n\tdf = pd.read_csv(outfile_name)\n\tmc_th_corr = df[\"monte_carlo\"].corr(df[\"two_hop\"], method='pearson')\n\tmc_mcmh_corr = df[\"monte_carlo\"].corr(df[\"monte_carlo_max_hop\"], method='pearson')\n\tstd = df[\"monte_carlo\"].std()\n\tprint(mc_mcmh_corr)\n\tprint(mc_th_corr)\n\tprint(std)\n\tmc_min = df[\"monte_carlo\"].min()\n\tmc_max = df[\"monte_carlo\"].max()\n\n\t# write log file\n\tlog_data = args.__dict__\n\tlog_data[\"mc_th_corr\"] = mc_th_corr\n\tlog_data[\"mc_mcmh_corr\"] = mc_mcmh_corr\n\tlog_data[\"mc_std\"] = std\n\tlog_data[\"mc_min\"] = mc_min\n\tlog_data[\"mc_max\"] = mc_max\n\tlog_data[\"exec_time_mc_mean\"] = comp_time_mc.mean()\n\tlog_data[\"exec_time_mc_std\"] = comp_time_mc.std()\n\tlog_data[\"exec_time_mh_mean\"] = comp_time_mh.mean()\n\tlog_data[\"exec_time_mh_std\"] = comp_time_mh.std()\n\tlog_data[\"exec_time_th_mean\"] = comp_time_th.mean()\n\tlog_data[\"exec_time_th_std\"] = comp_time_th.std()\n\n\t# write average degree and standard deviation, max, min\n\tdegrees = np.array(list(dict(G.degree()).values()))\n\tlog_data[\"degree_mean\"] = degrees.mean()\n\tlog_data[\"degree_std\"] = degrees.std()\n\tlog_data[\"degree_min\"] = degrees.min()\n\tlog_data[\"degree_max\"] = degrees.max()\n\tlog_data[\"degree_median\"] = np.median(degrees)\n\n\tlogfile_name = args.out_dir + \"/\" + \"log.csv\"\n\tdict2csv(log_data, logfile_name)\n","sub_path":"src/additional_experimental_scripts/spread_computation.py","file_name":"spread_computation.py","file_ext":"py","file_size_in_byte":6338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"252676706","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 17 11:37:10 2017\nAssignment 2 MATH6103\n@author: chengxue\n\"\"\"\n\nimport matplotlib.pyplot as plt, numpy as np\nimport scipy.fftpack\nfrom scipy.io import wavfile\nfs, data = wavfile.read('/Users/chengxue/Github/ANU/Semester2_2017/MATH6103/Week4 Tutorial/Discrete Fourier Transform Tutorial-20170815/oboe.wav') # load the data\nfreq = scipy.fftpack.fftfreq(fs,1/fs)\nt = np.linspace(0,1,fs)\nind = np.arange(0,int(fs/2))\n\nafterFFT = scipy.fftpack.fft(data)\nafterFFT = afterFFT/fs # normalise\n\n\n\nfig = plt.figure(figsize=(8,10))\nax = fig.add_subplot(211)\nplt.title(\"Original Signal\")\nax.plot(t,data,\"k,\",label = \"Orginal Signal\")\nplt.xlabel(\"Time\")\n\n#If I want Parseval’s relation to still hold I have to multiply \n#all the positive frequencies which normally also occur as \n#negative frequencies by a factor of 2. This is because I have \n#essentially “lost” half my power by omitting the negative \n#frequencies. \n\n# \n# f, Pxx = signal.periodogram(data,fs)\n# plt.plot(f,Pxx)\n\npsd = abs(afterFFT[ind])**2 \npsd[1:] = 2*psd[1:] # don't scale the DC and Nyquist\n\n\nax = fig.add_subplot(212)\nax.plot(freq[ind],psd,'b-')\nplt.title(\"Power Spectrume Density\")\nplt.xlabel(\"Frequency\")\nplt.ylabel(\"Power\")\nplt.show()\n\n\n#question d\n\n#according to the graph, the first pick is just below 0.2 * 10^7 so lets take all of the value greater than 0.2 * 10^7 \n\nmain_freq_ind = np.where(psd > 0.2e7)\n#the fundamental and the 3 harmonics frequency are 415, 829, 1244, 1659\nfreq[main_freq_ind]\n#the fundamental and the 3 harmonics power are 2693824, 28683478, 34492550, 10942770\npsd[main_freq_ind]\n\n#question e\n#choose only the notes listed above, remove others\n\nmain_freq_ind = np.ravel(main_freq_ind)[[0,1,3,5]]\n\nprocessed_FFT = np.zeros_like(afterFFT)\nprocessed_FFT[main_freq_ind] = afterFFT[main_freq_ind]\nprocessed_FFT[-main_freq_ind] = afterFFT[main_freq_ind]\n\nprocessed = scipy.ifft(processed_FFT) #normalise\nprocessed = processed.real\n\n#question f\n\nfig = plt.figure(figsize=(8,10))\nax = fig.add_subplot(211)\nplt.title(\"Processed Signal\")\nax.plot(t,processed,\"r,\" ,label = \"Processed Signal\")\n#ax.plot(t,data,\"k,\" ,label = \"Original Signal\")\nplt.xlabel(\"Time\")\n\n\n\npsd = 2 * abs(processed_FFT[ind])**2 #normlised\nax = fig.add_subplot(212)\nax.plot(freq[ind],psd,'b-')\nplt.title(\"Processed Power Spectrume Density\")\nplt.xlabel(\"Frequency\")\nplt.ylabel(\"Power\")\n\nplt.show()\n\n\n#question g\n#save it as a music file\n\nwavfile.write(\"Assignment 2.wav\",fs,processed)\n\n","sub_path":"Semester2_2017/MATH6103/Assignment 2/Assignment2.py","file_name":"Assignment2.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"534822261","text":"import os, csv, util.getParameter as gp\nfrom pyecharts import Pie, Grid, Polar, Bar\n\nname = \"rose_pie\"\npathHtml = gp.html_path + name + \".html\"\npathData = gp.data_path + \"roseData.csv\"\npathImage = gp.img_path + name + \".png\"\nAttr, Name, Data = [], [], []\n\n\ndef readData(PathData):\n with open(PathData, encoding='utf-8-sig') as file:\n global Attr, Name, Data\n reader_row = csv.reader(file)\n for i, rows in enumerate(reader_row):\n row = rows\n row.remove(row[0])\n Data.append(row)\n Attr = Data[0]\n Data.remove(Data[0])\n with open(PathData, encoding='utf-8-sig') as file:\n reader_column = csv.reader(file)\n column = [row[0] for row in reader_column]\n column.remove(column[0])\n Name = column\n\n\ndef drawBar():\n bar = Bar()\n bar.add(\n \"\",\n Attr,\n Data[0]\n )\n grid.add(bar)\n\n\ndef drawRose(name, data, position):\n pie = Pie()\n pie.add(\n name=name,\n attr=Attr,\n value=data,\n radius=[0, 80],\n center=position,\n rosetype=\"area\",\n is_legend_show=False,\n is_label_show=False,\n is_toolbox_show=False,\n )\n grid.add(pie)\n\n\ndef drawPloar():\n polar = Polar(\"\")\n polar.add(\n \"\",\n [0 for _ in range(10)],\n angle_data=Attr,\n type=\"barAngle\",\n is_angleaxis_show=False,\n is_radiusaxis_show=True,\n boundary_gap=False,\n axis_range=[100, 100],\n angleaxis_label_interval=0,\n is_toolbox_show=False\n )\n grid.add(polar)\n\n\ndef drawLable(pie, data, position):\n pie.add(\n '',\n Attr,\n data,\n center=position,\n radius=[38, 38],\n label_pos='inside',\n rosetype=\"area\",\n is_label_show=True,\n is_legend_show=False,\n label_formatter=\"{b}\\n{c}\",\n label_text_color=\"#363636\",\n label_text_size=8\n )\n\n\nif __name__ == '__main__':\n readData(pathData)\n grid = Grid(height=200, width=200)\n drawBar()\n drawRose('', Data[0], [])\n grid.render(pathHtml)\n","sub_path":"python/pyecharts/rosepie.py","file_name":"rosepie.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"514644398","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 29 13:52:48 2019\n\n@author: usuario\n\"\"\"\n\n\nimport gym #cargar libreria de gym\n\nenvironment = gym.make(\"Qbert-v0\") \nMAX_NUM_EPISODES = 10\nMAX_STEPS_PER_EPISODE = 500\n\nfor episode in range(MAX_NUM_EPISODES):\n obs = environment.resert()\n for step in range(MAX_STEPS_PER_EPISODE):\n environment.render()\n action = environment.action_space.sample()#Decisión aleatoria\n next_state, reward, done, info = environment.step(action)\n obs = next_state\n \n if done is True:\n print(\"\\n Episodio #{} terminado en {} steps.\".format(episode, step+1))\n break\nenvironment.close()\n","sub_path":"Sección 5/03_gym_steps.py","file_name":"03_gym_steps.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"131771861","text":"import scrapy\n\n\nclass NewsSpider(scrapy.Spider):\n name = \"news\"\n start_urls = [\n 'https://readhub.me/',\n ]\n\n def parse(self, response):\n for news in response.css('div.topicItem___3YVLI'):\n title = news.xpath('h2/span/text()').extract_first()\n text = news.xpath('div/div/text()').extract_first()\n yield {\n 'title': title,\n 'text': text\n }\n","sub_path":"scraper/readhub.py","file_name":"readhub.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"378954586","text":"import openpyxl\nimport string\n\nfrom collections import OrderedDict\nfrom openpyxl.cell import get_column_letter\n\n# ------------------------------------------------------------------------------\n\n# dict_from_xlsx.py\n\n# Returns a dictionary {'rows': data_dict, 'columns': column_dict}\n# data_dict - Dictionary keys - Accession Number, values - dictionary\n# column_dict - Dictionary keys - Excel column letter, values - Column name\n\n# ------------------------------------------------------------------------------\n\nEXCEL_PATH = '/Users/SimonJung/Desktop/proteomics/RT_1FDR_1.xlsx'\nID_COLUMN = 'Accession Number'\n\n\ndef dict_from_xlsx(xlsx_path):\n wb = openpyxl.load_workbook(xlsx_path)\n sheet = wb.active\n\n column_names = [x.value for x in sheet.rows[0] if x.value]\n id_column = get_column_letter(column_names.index(ID_COLUMN) + 1)\n column_dict = OrderedDict(zip(string.ascii_uppercase, column_names))\n\n data_dict = dict()\n for row in xrange(2, sheet.max_row + 1):\n value_dict = {}\n for column in column_dict.keys():\n value_dict[column_dict[column]] = sheet[column+str(row)].value\n data_dict[sheet[id_column+str(row)].value] = value_dict\n return {'rows': data_dict, 'columns': column_dict}\n\nif __name__ == '__main__':\n data = dict_from_xlsx(EXCEL_PATH)\n","sub_path":"dict_from_xlsx.py","file_name":"dict_from_xlsx.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"139847595","text":"from web.Pipelines.BasicPipeline import BasicPipeline\nfrom scrapy.exporters import CsvItemExporter\n\n\nclass CsvWriterPipeline(BasicPipeline):\n def spider_opened(self, spider):\n file = open('%s_items.csv' % spider.name, 'wb')\n self.files[spider] = file\n self.exporter = CsvItemExporter(file)\n self.exporter.start_exporting()\n","sub_path":"web/Pipelines/CsvItemExporter.py","file_name":"CsvItemExporter.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"582354174","text":"from contextlib import contextmanager\n\nfrom django.http import QueryDict\nfrom django_filters import compat\nfrom django_filters.rest_framework import backends\nfrom rest_framework.exceptions import ValidationError\n\nfrom .complex_ops import combine_complex_queryset, decode_complex_ops\nfrom .filterset import FilterSet\n\n\n@contextmanager\ndef noop(self):\n yield\n\n\nclass RestFrameworkFilterBackend(backends.DjangoFilterBackend):\n default_filter_set = FilterSet\n\n @property\n def template(self):\n if compat.is_crispy():\n return 'rest_framework_filters/crispy_form.html'\n return 'rest_framework_filters/form.html'\n\n @contextmanager\n def patch_for_rendering(self, request):\n \"\"\"\n Patch `get_filter_class()` so the resulting filterset does not perform\n filter expansion during form rendering.\n \"\"\"\n original = self.get_filter_class\n\n def get_filter_class(view, queryset=None):\n filter_class = original(view, queryset)\n filter_class.override_filters = noop\n\n return filter_class\n\n self.get_filter_class = get_filter_class\n yield\n self.get_filter_class = original\n\n def to_html(self, request, queryset, view):\n # patching the behavior of `get_filter_class()` in this method allows\n # us to avoid maintenance issues with code duplication.\n with self.patch_for_rendering(request):\n return super(RestFrameworkFilterBackend, self).to_html(request, queryset, view)\n\n\nclass ComplexFilterBackend(RestFrameworkFilterBackend):\n complex_filter_param = 'filters'\n operators = None\n negation = True\n\n def filter_queryset(self, request, queryset, view):\n if self.complex_filter_param not in request.query_params:\n return super(ComplexFilterBackend, self).filter_queryset(request, queryset, view)\n\n # Decode the set of complex operations\n encoded_querystring = request.query_params[self.complex_filter_param]\n try:\n complex_ops = decode_complex_ops(encoded_querystring, self.operators, self.negation)\n except ValidationError as exc:\n raise ValidationError({self.complex_filter_param: exc.detail})\n\n # Collect the individual filtered querysets\n querystrings = [op.querystring for op in complex_ops]\n try:\n querysets = self.get_filtered_querysets(querystrings, request, queryset, view)\n except ValidationError as exc:\n raise ValidationError({self.complex_filter_param: exc.detail})\n\n return combine_complex_queryset(querysets, complex_ops)\n\n def get_filtered_querysets(self, querystrings, request, queryset, view):\n parent = super(ComplexFilterBackend, self)\n original_GET = request._request.GET\n\n querysets, errors = [], {}\n for qs in querystrings:\n request._request.GET = QueryDict(qs)\n try:\n result = parent.filter_queryset(request, queryset, view)\n querysets.append(result)\n except ValidationError as exc:\n errors[qs] = exc.detail\n finally:\n request._request.GET = original_GET\n\n if errors:\n raise ValidationError(errors)\n return querysets\n","sub_path":"rest_framework_filters/backends.py","file_name":"backends.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"100615874","text":"# -*- coding:utf-8 -*-\nfrom flask import Flask\n\nfrom settings import Config\n\napp = Flask(__name__,\n static_folder='static')\n\n\"\"\"\n调试模式\n1,自动重启服务器(鼠标离开或保存py文件)\n2,控制台会打印error\n\"\"\"\n# 方式1,属性\n# app.debug = True\n\n# 方式2\n# config,是一个存储app所有配置的字典,Key都是大写\n# app.config['DEBUG']= True\n\n# 方式3 加载文件,完整文件名\n# app.config.from_pyfile('settings.py')\n\n# 方式4 , 加载对象(更为推荐)\napp.config.from_object(Config)\n\n@app.route('/')\ndef hello_world():\n return 'Hello World!'\n\nif __name__ == '__main__':\n # app的一些参数\n # 默认 port:5000 host:'127.0.0.1'\n # app.run(debug=True,port=5001,host='192.168.44.129 ')\n\n # 全零地址:本机/局域网/公网都可访问\n app.run(debug=True,host='0.0.0.0')","sub_path":"flask1-5/flask_01/demo02_setting.py","file_name":"demo02_setting.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"617140140","text":"import numpy as np\r\nfrom spike_swarm_sim.register import actuator_registry\r\nfrom spike_swarm_sim.utils import softmax\r\n\r\n@actuator_registry(name='wireless_transmitter')\r\nclass CommunicationTransmitter:\r\n \"\"\" Communication transmitter actuator. It isotropically transmits a \r\n frame with a message and its context. The propagation simulation is \r\n implemented at the receiver side, this class only updates the transmitted \r\n frame of each robot. \r\n =========================================================================\r\n - Params:\r\n range [float] : maximum distance of message reception, in centimeters.\r\n msg_length [int] : number of components of the message.\r\n quantize [bool] : whether to quantize the message to a set of possible \r\n symbols or not.\r\n \"\"\"\r\n def __init__(self, range=120, msg_length=1, quantize=True):\r\n self.channel = 0\r\n self.msg_length = msg_length\r\n self.range = range\r\n self.quantize = quantize\r\n if self.quantize:\r\n self.clusters = [centroid for centroid in \\\r\n zip(*map(lambda v: v.flatten(),\\\r\n np.meshgrid(*[np.linspace(0, 1, 4) for _ in np.arange(self.msg_length)])))]\r\n self.clusters = np.array(self.clusters)\r\n self.frame = None\r\n self.reset()\r\n \r\n def step(self, action):\r\n #* Select cluster using softmax on distances to clusters\r\n if self.quantize:\r\n dists = np.linalg.norm(action['msg'] - self.clusters, axis=1)\r\n # Max. dist in hypercube is sqrt(dim(x))\r\n max_distance = np.sqrt(len(action['msg']))\r\n probs = softmax(1 - dists / max_distance, tau=1e-2)\r\n cluster = np.random.choice(range(len(self.clusters)), p=probs)\r\n action['msg'] = self.clusters[cluster]\r\n self.frame['msg'] = action['msg']\r\n self.frame['priority'] = action['priority']\r\n self.frame['sender'] = action['sender']\r\n self.frame['destination'] = action['destination'] \\\r\n if 'destination' in action.keys() else 0\r\n self.frame['enabled'] = action['enabled']\\\r\n if 'enabled' in action.keys() else True\r\n self.frame['n_hops'] = action['n_hops']\r\n self.frame['state'] = action['state']\r\n self.frame['sending_direction'] = action['sending_direction']\r\n\r\n def reset(self):\r\n self.frame = {\r\n 'msg' : [0 for _ in range(self.msg_length)],\r\n 'enabled' : True,\r\n 'state' : 1,\r\n 'n_hops' : 1,\r\n 'sender' : -1,\r\n 'destination' : 0,\r\n 'source' : 0,\r\n 'priority' : 0,\r\n 'sending_direction' : 0,\r\n }","sub_path":"spike_swarm_sim/actuators/communication_transmitter.py","file_name":"communication_transmitter.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"153083833","text":"import dockhand\nimport mock\nimport pytest\n\nZOOKEEPER_3_4_6 = (\"jplock/zookeeper\", \"3.4.6\")\nCASSANDRA_2_1_2_2 = (\"cn-docker.adtran.com:5000/cassandradb\", \"2.1.2-2\", \"/opt/apache-cassandra-2.1.2/bin/nodetool\")\nDNSMASQ_2_75_1 = (\"cn-docker.adtran.com:5000/dnsmasq\", \"2.75-1\")\n\n@pytest.fixture(scope=\"module\", autouse=True)\ndef mockclients():\n dockhand.zookeeper.docker.Client = mock.MagicMock()\n dockhand.cassandradb.docker.Client = mock.MagicMock()\n\ndef test_get_zookeeper_manager():\n zookeeper_manager = dockhand.get_zookeeper_manager('zookeeper', ZOOKEEPER_3_4_6)\n assert zookeeper_manager.name == 'zookeeper'\n assert zookeeper_manager.version == '3.4.6'\n\ndef test_get_cassandra_manager():\n cassandra_manager = dockhand.get_cassandra_manager('cassandra', CASSANDRA_2_1_2_2)\n assert cassandra_manager.name == 'cassandra'\n assert cassandra_manager.version == '2.1.2-2'\n\ndef test_get_dnsmasq_manager():\n zookeeper_manager = dockhand.get_dnsmasq_manager('dnsmasq', DNSMASQ_2_75_1, 1)\n assert zookeeper_manager.name == 'dnsmasq'\n assert zookeeper_manager.version == '2.75-1'\n\n","sub_path":"test/unit/test_top_level.py","file_name":"test_top_level.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"160149026","text":"import requests\nfrom common import monitor\nimport datetime\nimport os\n\nHOST = os.environ.get('SEREPOK_HOST') if os.environ.get('SEREPOK_HOST') else 'serepok-api'\nPORT = os.environ.get('SEREPOK_PORT') if os.environ.get('SEREPOK_PORT') else '80'\nROUTE = 'api/serepok/token_manager'\nURL = 'http://' + HOST + \":\" + PORT + \"/\" + ROUTE\n\ndef get_tokens(pool_name):\n assert pool_name\n \n payload = {\n 'where': '{\"death_time\":null,\"is_delete\":{\"$ne\":true}, \"pool_name\": \"%s\"}' % pool_name,\n 'max_results': 10000\n }\n\n responses = requests.get(url=URL, params=payload)\n items = responses.json()['_items']\n monitor.add('TOTAL_ACCESS_TOKENS', int_value=len(items), message=pool_name)\n return items\n\n\ndef invalidate_token(token):\n if token is not None:\n token_ids = get_token_id(token)\n if not token_ids:\n return False\n\n payload = {\n 'death_time': datetime.datetime.now().strftime(\"%a, %d %b %Y %H:%M:%S GMT\"),\n }\n for token_id in token_ids:\n reponses = requests.patch(url=URL + \"/\" + token_id, data=payload)\n if reponses.json()['_status'] != 'OK':\n return False\n\n return True\n return False\n\ndef get_token_id(token):\n payload = {\n 'where': \"access_token==\\\"\" + token + \"\\\"\",\n }\n responses = requests.get(url=URL, params=payload)\n items = responses.json()['_items']\n\n if not items:\n return None\n\n return [item['_id'] for item in items]\n\n","sub_path":"Thanos/token_manager/main/app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"138606281","text":"# encoding: utf-8\n\"\"\"\n@author: xingyu liao\n@contact: sherlockliao01@gmail.com\n\"\"\"\n\nimport argparse\nimport logging\nimport sys\nimport os\nimport pickle\nimport numpy as np\nimport torch\nimport tqdm\nfrom torch.backends import cudnn\n\n\nsys.path.append('.')\n\nfrom fastreid.evaluation import evaluate_rank\nfrom fastreid.config import get_cfg\nfrom fastreid.utils.logger import setup_logger\nfrom fastreid.data import build_reid_test_loader\nfrom predictor import FeatureExtractionDemo\nfrom fastreid.utils.visualizer import Visualizer\n\n\ncudnn.benchmark = True\nlogger = logging.getLogger('fastreid.visualize_result')\n\n\ndef setup_cfg(args):\n # load config from file and command-line arguments\n cfg = get_cfg()\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n return cfg\n\ndef get_parser():\n parser = argparse.ArgumentParser(description=\"Feature extraction with reid models\")\n parser.add_argument(\n \"--config-file\",\n metavar=\"FILE\",\n help=\"path to config file\",\n )\n parser.add_argument(\n '--parallel',\n action='store_true',\n help='if use multiprocess for feature extraction.'\n )\n parser.add_argument(\n \"--dataset-name\",\n # default='VesselReid',\n default='Market1501',\n help=\"a test dataset name for visualizing ranking list.\"\n )\n parser.add_argument(\n \"--output\",\n default=\"./vis_rank_list\",\n help=\"a file or directory to save rankling list result.\",\n\n )\n parser.add_argument(\n \"--vis-label\",\n action='store_true',\n help=\"if visualize label of query instance\"\n )\n parser.add_argument(\n \"--num-vis\",\n type=int,\n default=10,\n help=\"number of query images to be visualized\",\n )\n parser.add_argument(\n \"--rank-sort\",\n default=\"ascending\",\n help=\"rank order of visualization images by AP metric\",\n )\n parser.add_argument(\n \"--label-sort\",\n default=\"ascending\",\n help=\"label order of visualization images by cosine similarity metric\",\n )\n parser.add_argument(\n \"--max-rank\",\n type=int,\n default=10,\n help=\"maximum number of rank list to be visualized\",\n )\n parser.add_argument(\n \"--opts\",\n help=\"Modify config options using the command-line 'KEY VALUE' pairs\",\n default=[],\n nargs=argparse.REMAINDER,\n )\n return parser\n\ndef save_features(output, feats, pids, camids):\n if not os.path.exists(output):\n os.makedirs(output)\n features = {\n \"feats\": np.asarray(feats),\n \"pids\": np.asarray(pids),\n \"camids\": np.asarray(camids),\n }\n with open(os.path.join(output, \"features.pickle\"), \"wb\") as handle:\n pickle.dump(features, handle, protocol=pickle.HIGHEST_PROTOCOL)\ndef load_features(path):\n with open(path, 'rb') as handle: res = pickle.load(handle)\n return res\n\nif __name__ == '__main__':\n args = get_parser().parse_args()\n logger = setup_logger()\n cfg = setup_cfg(args)\n test_loader, num_query = build_reid_test_loader(cfg, args.dataset_name)\n demo = FeatureExtractionDemo(cfg, parallel=args.parallel)\n if(os.path.exists(os.path.join(args.output, \"features.pickle\"))):\n features = load_features(os.path.join(args.output, \"features.pickle\"))\n logger.info(\"features load at \" + args.output,)\n feats = features['feats']\n pids = features['pids']\n camids = features['camids']\n feats = torch.from_numpy(feats)\n else:\n logger.info(\"Start extracting image features\")# 10min\n feats = []\n pids = []\n camids = []\n for (feat, pid, camid) in tqdm.tqdm(demo.run_on_loader(test_loader), total=len(test_loader)):\n feats.append(feat)\n pids.extend(pid)\n camids.extend(camid)\n\n feats = torch.cat(feats, dim=0)\n save_features(args.output, feats, pids, camids)\n print(\"features saved at \" + args.output,)\n \n q_feat = feats[:num_query]\n g_feat = feats[num_query:]\n q_pids = np.asarray(pids[:num_query]).astype(np.int32)\n g_pids = np.asarray(pids[num_query:]).astype(np.int32)\n q_camids = np.asarray(camids[:num_query]).astype(np.int8)\n g_camids = np.asarray(camids[num_query:]).astype(np.int8)\n\n # compute cosine distance\n distmat = 1 - torch.mm(q_feat, g_feat.t())\n distmat = distmat.numpy()\n\n logger.info(\"Computing APs for all query images ...\")# 10min\n # cmc, all_ap, all_inp = evaluate_rank(distmat, q_feat, g_feat, q_pids, g_pids, q_camids, g_camids)\n cmc, all_ap, all_inp = evaluate_rank(distmat, q_pids, g_pids, q_camids, g_camids) #修改为\n visualizer = Visualizer(test_loader.dataset)\n visualizer.get_model_output(all_ap, distmat, q_pids, g_pids, q_camids, g_camids)\n logger.info(\"Saving ROC curve and distribution...\")\n visualizer.save_roc_curve(args.output)\n # fpr, tpr, pos, neg = visualizer.vis_roc_curve(args.output)\n # visualizer.save_roc_info(args.output, fpr, tpr, pos, neg)\n\n \n\n logger.info(\"Saving rank list result ...\")\n query_indices = visualizer.vis_rank_list(args.output, args.vis_label, args.num_vis,\n args.rank_sort, args.label_sort, args.max_rank)\n","sub_path":"demo/visualize_and_save_result.py","file_name":"visualize_and_save_result.py","file_ext":"py","file_size_in_byte":5302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"148618824","text":"from selenium import webdriver\n\n\n#Driver Intialization\n\n\ndriver=webdriver.Chrome(executable_path=\"D:\\SeleniumPython\\drivers\\chromedriver.exe\")\ndriver.maximize_window()\n\ndriver.get(\"http://testautomationpractice.blogspot.com/\") # Launch Browser\ndriver.implicitly_wait(10)\ndriver.maximize_window()\n\n\n#Scroll down the Page by pixel\n#driver.execute_script(\"window.scrollBy(0,500)\",\"\")\n\n#Scroll down the Page till element found\n# ele=driver.find_element_by_xpath(\"//select[@name='skills']\")\n# driver.execute_script(\"arguments[0].scrollIntoView();\",ele)\n\n#Scroll to end of the page\ndriver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n","sub_path":"SeleniumPython/Scrolling.py","file_name":"Scrolling.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"616107856","text":"from gpiozero import LED\nfrom time import sleep\n\npower_down = LED(26)\ndirection = LED(19)\npower_up = LED(13)\n\n\ndef panels_up():\n power_down.off()\n power_up.on()\n direction.off()\n\n\ndef panels_down():\n power_down.on()\n power_up.off()\n direction.on()\n\n\ndef panels_stop():\n power_down.off()\n power_up.off()\n direction.off()\n\n\nif __name__ == '__main__':\n delay = 20\n while True:\n panels_up()\n print(\"Up...\")\n sleep(delay)\n\n panels_stop()\n print(\"Stop\")\n sleep(delay)\n\n panels_down()\n print(\"Down...\")\n sleep(delay)\n\n panels_stop()\n print(\"Stop\")\n sleep(delay)\n","sub_path":"Raspberry-Pi/unit_tests/test_panel_control.py","file_name":"test_panel_control.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"302586590","text":"# -*- coding: utf-8 -*-\n\n\nfrom flask import url_for, redirect, render_template, request\nfrom . import map\nfrom app.decorators import login_required\nfrom .forms import RelationshipForm, CityForm\nfrom app.models.maps import MapCity, MapRelationship\n\n\n@map.route(\"/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef home(page):\n form = RelationshipForm()\n if form.validate_on_submit():\n MapRelationship(city_from_name=form.city_from.data, city_to_name=form.city_to.data)\n return redirect(url_for(\"map.home\", page=1))\n headings = (\"identify\", \"city_from\", \"city_to\", \"date\")\n pagination = MapRelationship.query.order_by(MapRelationship.date.desc()).paginate(page=page, per_page=20, error_out=False)\n contents = pagination.items\n citys = {city.identify: city.name for city in MapCity.query.all()}\n return render_template(\"map/home.html\", form=form, headings=headings, contents=contents, pagination=pagination, citys=citys)\n\n\n@map.route(\"/city/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef city(page):\n form = CityForm()\n if form.validate_on_submit():\n MapCity(name=form.city.data)\n return redirect(url_for(\"map.city\", page=1))\n headings = (\"identify\", \"name\", \"lng\", \"lat\", \"level\", \"date\", \"publish\")\n pagination = MapCity.query.order_by(MapCity.date.desc()).paginate(page=page, per_page=20, error_out=False)\n contents = pagination.items\n return render_template(\"map/city.html\", form=form, headings=headings, contents=contents, pagination=pagination)\n\n\n@map.route(\"/city/delete\", methods=[\"POST\"])\n@login_required\ndef city_delete():\n identify = request.form[\"identify\"]\n tmp_map_city = MapCity.query.filter_by(identify=identify).first()\n tmp_map_city.delete()\n return redirect(url_for(\"map.city\", page=1))\n\n\n@map.route(\"/relationship/delete\", methods=[\"POST\"])\n@login_required\ndef relationship_delete():\n identify = request.form[\"identify\"]\n tmp_map_relationship = MapRelationship.query.filter_by(identify=identify).first()\n tmp_map_relationship.delete()\n return redirect(url_for(\"map.home\", page=1))\n","sub_path":"app/map/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"497698538","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- import rospy\n\nimport rospy\nimport time\n#import math, time, sys\nimport threading\n#import csv, time\n#import rospy, threading, math\n#import numpy as np\n#from std_msgs.msg import Header\n#from geometry_msgs.msg import Twist \n#from geometry_msgs.msg import PoseWithCovarianceStamped\n#from geometry_msgs.msg import Pose2D\nfrom geometry_msgs.msg import Twist\n\nimport KvaserCANLib as kcl\n\n\nDEBUG = False\n\nclass ROS2Vehicle:\n\n velocity_limit = 0\n senced_distance = 0\n steering = 0\n disabled = 0\n alive = True\n\n def __init__(self):\n rospy.init_node('velocity_supressor')\n self.disabled = 0\n self.timer = time.time()\n\n def start_subscribe(self):\n rospy.Subscriber(\"/cmd_vel\", Twist, self.twist_cb)\n\n def twist_cb(self, dat):\n self.timer = time.time()\n self.disabled = 0\n\n a = rospy.get_param(\"~asvev1_velocity_limitter\", 16.0)\n self.velocity_limit = min( dat.linear.x, a )\n self.senced_distance = dat.linear.y\n # self.steering = dat.angular.z \n \n def sendThread(self,can):\n # start send thread\n th1 = threading.Thread(name='cansend', target=self.cansend, args=(can,))\n th1.setDaemon(True)\n th1.start()\n return th1\n\n def cansend(self, can):\n _id = 0x6a1\n freerun = 0\n\n rate = rospy.Rate(10)\n while not rospy.is_shutdown(): #self.Alive:\n freerun += 1\n if freerun > 255:\n freerun = 0\n msg = can.hosuu2inv(int(self.velocity_limit*10))+can.hosuu2inv(int(self.steering*10))+(0,0,self.disabled,freerun)\n can.send(_id,msg)\n # print _id,msg\n # time.sleep(0.2)\n rate.sleep()\n\n\ndef main():\n channel = rospy.get_param(\"canif_channel\", 0)\n can = kcl.KvaserCANLib(channel)\n\n th1 = can.receiveThread()\n r2v = ROS2Vehicle()\n r2v.start_subscribe()\n th2 = r2v.sendThread(can)\n # v2r.calculate_and_publish()\n\n rate = rospy.Rate(20)\n while th1.isAlive and th2.isAlive:\n # no ROS message timeout\n if time.time() - r2v.timer > 10:\n pass\n r2v.disabled = 1\n # DEBUG\n # print r2v.velocity, r2v.steering, r2v.disabled\n rate.sleep()\n\n r2v.alive = False\n\n\nif __name__ == '__main__':\n\n main()\n\n","sub_path":"node/asvev1/src/velocity_supressor.py","file_name":"velocity_supressor.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"478042007","text":"from datetime import datetime, timedelta\n\nimport dateutil\nfrom flask import (\n render_template,\n url_for,\n session,\n jsonify,\n current_app,\n request,\n abort\n)\nfrom flask_login import login_required\n\nfrom app.main import main\nfrom app import (\n job_api_client,\n service_api_client,\n template_statistics_client\n)\nfrom app.statistics_utils import get_formatted_percentage, add_rate_to_job\nfrom app.utils import user_has_permissions\n\n\n# This is a placeholder view method to be replaced\n# when product team makes decision about how/what/when\n# to view history\n@main.route(\"/services//history\")\n@login_required\ndef temp_service_history(service_id):\n data = service_api_client.get_service_history(service_id)['data']\n return render_template('views/temp-history.html',\n services=data['service_history'],\n api_keys=data['api_key_history'],\n events=data['events'])\n\n\n@main.route(\"/services//dashboard\")\n@login_required\n@user_has_permissions('view_activity', admin_override=True)\ndef service_dashboard(service_id):\n\n if session.get('invited_user'):\n session.pop('invited_user', None)\n session['service_id'] = service_id\n\n return render_template(\n 'views/dashboard/dashboard.html',\n updates_url=url_for(\".service_dashboard_updates\", service_id=service_id),\n templates=service_api_client.get_service_templates(service_id)['data'],\n partials=get_dashboard_partials(service_id)\n )\n\n\n@main.route(\"/services//dashboard.json\")\n@user_has_permissions('view_activity', admin_override=True)\ndef service_dashboard_updates(service_id):\n return jsonify(**get_dashboard_partials(service_id))\n\n\n@main.route(\"/services//template-activity\")\n@login_required\n@user_has_permissions('view_activity', admin_override=True)\ndef template_history(service_id):\n template_statistics = aggregate_usage(\n template_statistics_client.get_template_statistics_for_service(service_id)\n )\n\n return render_template(\n 'views/dashboard/all-template-statistics.html',\n template_statistics=template_statistics,\n most_used_template_count=max(\n [row['count'] for row in template_statistics] or [0]\n )\n )\n\n\n@main.route(\"/services//usage\")\n@login_required\n@user_has_permissions('manage_settings', admin_override=True)\ndef usage(service_id):\n try:\n year = int(request.args.get('year', 2016))\n except ValueError:\n abort(404)\n return render_template(\n 'views/usage.html',\n months=get_free_paid_breakdown_for_billable_units(\n year, service_api_client.get_billable_units(service_id, year)\n ),\n year=year,\n **calculate_usage(service_api_client.get_service_usage(service_id)['data'])\n )\n\n\n@main.route(\"/services//weekly\")\n@login_required\n@user_has_permissions('manage_settings', admin_override=True)\ndef weekly(service_id):\n stats = service_api_client.get_weekly_notification_stats(service_id)['data']\n return render_template(\n 'views/weekly.html',\n days=format_weekly_stats_to_list(stats),\n now=datetime.utcnow()\n )\n\n\ndef aggregate_usage(template_statistics):\n return sorted(\n template_statistics,\n key=lambda template_statistic: template_statistic['count'],\n reverse=True\n )\n\n\ndef get_dashboard_partials(service_id):\n # all but scheduled and cancelled\n statuses_to_display = job_api_client.JOB_STATUSES - {'scheduled', 'cancelled'}\n\n template_statistics = aggregate_usage(\n template_statistics_client.get_template_statistics_for_service(service_id, limit_days=7)\n )\n\n scheduled_jobs = sorted(\n job_api_client.get_jobs(service_id, statuses=['scheduled'])['data'],\n key=lambda job: job['scheduled_for']\n )\n immediate_jobs = [\n add_rate_to_job(job)\n for job in job_api_client.get_jobs(service_id, limit_days=7, statuses=statuses_to_display)['data']\n ]\n service = service_api_client.get_detailed_service(service_id)\n\n return {\n 'upcoming': render_template(\n 'views/dashboard/_upcoming.html',\n scheduled_jobs=scheduled_jobs\n ),\n 'totals': render_template(\n 'views/dashboard/_totals.html',\n service_id=service_id,\n statistics=get_dashboard_totals(service['data']['statistics'])\n ),\n 'template-statistics': render_template(\n 'views/dashboard/template-statistics.html',\n template_statistics=template_statistics,\n most_used_template_count=max(\n [row['count'] for row in template_statistics] or [0]\n ),\n ),\n 'has_template_statistics': bool(template_statistics),\n 'jobs': render_template(\n 'views/dashboard/_jobs.html',\n jobs=immediate_jobs\n ),\n 'has_jobs': bool(immediate_jobs),\n 'usage': render_template(\n 'views/dashboard/_usage.html',\n **calculate_usage(service_api_client.get_service_usage(service_id)['data'])\n ),\n }\n\n\ndef get_dashboard_totals(statistics):\n for msg_type in statistics.values():\n msg_type['failed_percentage'] = get_formatted_percentage(msg_type['failed'], msg_type['requested'])\n msg_type['show_warning'] = float(msg_type['failed_percentage']) > 3\n return statistics\n\n\ndef calculate_usage(usage):\n # TODO: Don't hardcode these - get em from the API\n sms_free_allowance = 250000\n sms_rate = 0.0165\n\n sms_sent = usage.get('sms_count', 0)\n emails_sent = usage.get('email_count', 0)\n\n return {\n 'emails_sent': emails_sent,\n 'sms_free_allowance': sms_free_allowance,\n 'sms_sent': sms_sent,\n 'sms_allowance_remaining': max(0, (sms_free_allowance - sms_sent)),\n 'sms_chargeable': max(0, sms_sent - sms_free_allowance),\n 'sms_rate': sms_rate\n }\n\n\ndef format_weekly_stats_to_list(historical_stats):\n out = []\n for week, weekly_stats in historical_stats.items():\n for stats in weekly_stats.values():\n stats['failure_rate'] = get_formatted_percentage(stats['failed'], stats['requested'])\n\n week_start = dateutil.parser.parse(week)\n week_end = week_start + timedelta(days=6)\n weekly_stats.update({\n 'week_start': week,\n 'week_end': week_end.date().isoformat(),\n 'week_end_datetime': week_end,\n })\n out.append(weekly_stats)\n\n return sorted(out, key=lambda x: x['week_start'], reverse=True)\n\n\ndef get_months_for_financial_year(year):\n return [\n month.strftime('%B')\n for month in (\n get_months_for_year(4, 13, year) +\n get_months_for_year(1, 4, year + 1)\n )\n if month < datetime.now()\n ]\n\n\ndef get_months_for_year(start, end, year):\n return [datetime(year, month, 1) for month in range(start, end)]\n\n\ndef get_free_paid_breakdown_for_billable_units(year, billable_units):\n cumulative = 0\n for month in get_months_for_financial_year(year):\n previous_cumulative = cumulative\n monthly_usage = billable_units.get(month, 0)\n cumulative += monthly_usage\n breakdown = get_free_paid_breakdown_for_month(\n cumulative, previous_cumulative, monthly_usage\n )\n yield {\n 'name': month,\n 'paid': breakdown['paid'],\n 'free': breakdown['free']\n }\n\n\ndef get_free_paid_breakdown_for_month(\n cumulative,\n previous_cumulative,\n monthly_usage\n):\n allowance = 250000\n\n if cumulative < allowance:\n return {\n 'paid': 0,\n 'free': monthly_usage,\n }\n elif previous_cumulative < allowance:\n return {\n 'paid': monthly_usage - (allowance - previous_cumulative),\n 'free': allowance - previous_cumulative\n }\n else:\n return {\n 'paid': monthly_usage,\n 'free': 0\n }\n","sub_path":"app/main/views/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":8067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"654258332","text":"######################imports######################\n\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport pandas as pd\nimport plotly.graph_objs as go\nimport pathlib\nfrom app import app\nimport dash_table\nimport plotly.express as px\nfrom apps import reusableFunctions\n\n\n\n\n######################data_import######################\n######################data_import######################\n######################data_import######################\n######################data_import######################\n\n\nPATH = pathlib.Path(__file__).parent\nDATA_PATH = PATH.joinpath(\"../datasets\").resolve()\n\n\ndf = pd.read_excel(DATA_PATH.joinpath(r'minaUtgifter.xlsx'))\n\n\n###################### datum ######################\n###################### datum ######################\n###################### datum ######################\n###################### datum ######################\n\ndf['datum'] = pd.to_datetime(df['datum'])\ndf['short_date'] = df.datum.dt.strftime('%y-%m')\ndf['year'] = df.datum.dt.strftime('%y')\n\n\nmonth = df.short_date\nmonth = month.drop_duplicates().sort_values(ascending=True)\nmonth_dict = {k:v for k,v in enumerate(month)}\n\n###################### group main DF ######################\n###################### group main DF ######################\n###################### group main DF ######################\n###################### group main DF ######################\n\ndf_group = df.groupby(['year', 'short_date', 'kategori']).sum()\ndf_group = df_group.reset_index(['year', 'short_date', 'kategori'])\n\n\n################ define monthly DFs ################\n################ define monthly DFs ################\n################ define monthly DFs ################\n################ define monthly DFs ################\n\n\nmonthly_resultat = df_group[-df_group['kategori'].isin(['Spara'])].groupby(['short_date']).sum('summa').reset_index(['short_date'])\nmonthly_resultat['kategori'] = 'Result'\nmonthly_exp = df_group[-df_group['kategori'].isin(['Spara','Lön'])].groupby(['short_date']).sum('summa').reset_index(['short_date'])\nmonthly_exp['summa'] = monthly_exp['summa']*-1\nmonthly_exp['kategori'] = 'Expenses'\nmonthly_salary = df_group[df_group['kategori'].isin(['Lön'])].groupby(['short_date']).sum('summa').reset_index(['short_date'])\nmonthly_salary['kategori'] = 'Salary'\n\n#append\nmonthly_summary = pd.DataFrame()\nmonthly_summary = monthly_summary.append([monthly_resultat,monthly_exp,monthly_salary])\n\n\n################ define yearly DF ################\n################ define yearly DF ################\n################ define yearly DF ################\n################ define yearly DF ################\n\n\nyearly_res = df_group[-df_group['kategori'].isin(['Spara'])].groupby(['year']).sum('summa').reset_index(['year'])\n\n\n######################app_dash######################\n######################app_dash######################\n######################app_dash######################\n######################app_dash######################\n\n\nlayout = html.Div(style = {}, children=[\n reusableFunctions.get_header(),\n reusableFunctions.get_navbar(),\n html.Div([\n html.Div([], className='col-2'),\n html.Div(dcc.Graph(id='summary'), className='col-8'),\n html.Div([], className='col-2')\n ],\n className='row',\n style={'background-color' : reusableFunctions.corporate_colors['dark-green']}),\n html.Div([\n html.Div([], className='col-2'),\n html.Div(dcc.RangeSlider('summary_slider',\n min=0,\n max=len(month)-1,\n step=None,\n marks=month_dict,\n value=[0,0]), className='col-8'),\n html.Div([], className='col-2'),\n ], className='row',\n style={'background-color' : reusableFunctions.corporate_colors['dark-green']}),\n html.Div([\n html.Div([], className='col-2'),\n html.Div(dcc.Graph(id='result'), className='col-8'),\n html.Div([], className='col-2')\n ], className='row',\n style={'background-color' : reusableFunctions.corporate_colors['dark-green']})\n\n])\n\n\n\n@app.callback(\n Output(component_id='summary', component_property='figure'),\n Output(component_id='result', component_property='figure'),\n Input(component_id='summary_slider', component_property='value')\n)\n\ndef slider_chart(value):\n\n first = value[0]\n last = value[1]+1\n\n dates = [month_dict[x] for x in list(range(first,last))]\n\n summary_temp = monthly_summary[monthly_summary['short_date'].isin(dates)]\n summary_temp['summa'] = round(summary_temp['summa'], 0)\n summary_temp = summary_temp.groupby('kategori')\n\n\n\n fig_summary_mm = go.Figure(\n data=[\n go.Bar(name=kategori, x=group.short_date, y=group.summa) for kategori, group in summary_temp\n ], layout=reusableFunctions.graph_layout\n )\n fig_summary_mm.update_layout(barmode='group', xaxis= {'tickvals': dates, 'title': 'Month'},\n yaxis={'title': 'SEK'}, title= {'text': 'Monthly Result in SEK'})\n\n\n\n fig_yearly = go.Figure(go.Bar(x = yearly_res['year'],\n y = yearly_res['summa'],\n width=0.1), layout=reusableFunctions.graph_layout)\n fig_yearly.update_layout(xaxis= {'title': 'År', 'tickvals': yearly_res.drop_duplicates(['year'])['year']},\n yaxis= {'title': 'Årligt resultat'}, title={'text': 'Yearly Result'})\n\n return [fig_summary_mm, fig_yearly]","sub_path":"apps/summary.py","file_name":"summary.py","file_ext":"py","file_size_in_byte":5505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"499747626","text":"from Medical_Dataset import *\n\n\ndef folder_name_gen(prefix, kind, dye, mag):\n subtype_folder = prefix + kind + \"/\" + dye\n subtype_folder_content = os.listdir(subtype_folder)\n\n dir_list = []\n for i in range(0, len(subtype_folder_content)):\n current_index_folder = subtype_folder + \"/\" + subtype_folder_content[i]\n current_index_folder_content = os.listdir(current_index_folder)\n\n for j in range(0, len(current_index_folder_content)):\n current_mag_folder = current_index_folder + \"/\" + current_index_folder_content[j]\n image_folder = current_mag_folder + \"/\" + mag + \"/\"\n dir_list.append(image_folder)\n\n return dir_list\n\n\nmagnification = \"400X\"\ndye = \"SOB\"\nmain_path = \"../Datasets/BreaKHis_v1/histology_slides/breast/\"\nimg_type = \"png\"\n\narea_size = 64\nbatch_size = 128\ntraining_rate = 0.7\n\nread_from_saved = bool(int(sys.argv[1]))\nresize_rate = float(sys.argv[2])\nload_list = bool(int(sys.argv[3]))\ninitial_learning_rate = float(sys.argv[4])\nif_aug = bool(int(sys.argv[5]))\nif_ten_crop = bool(int(sys.argv[6]))\n\nif read_from_saved:\n benign_x = np.load(\"benign_box_\" + magnification + \".npy\")\n malignant_x = np.load(\"malignant_box_\" + magnification + \".npy\")\nelse:\n benign_folder_list = folder_name_gen(main_path, \"benign\", dye, magnification)\n malignant_folder_list = folder_name_gen(main_path, \"malignant\", dye, magnification)\n\n benign_x = process_and_concat(read_img_dirlist(benign_folder_list, img_type),\n process_op=size_filter)\n malignant_x = process_and_concat(read_img_dirlist(malignant_folder_list,\n img_type), process_op=size_filter)\n\n # save for future use\n np.save(\"benign_box_\" + magnification + \".npy\", benign_x)\n np.save(\"malignant_box_\" + magnification + \".npy\", malignant_x)\n\n# resize\nbenign_x = resize_img_mat(benign_x, resize_rate, whether_readable=True)\nmalignant_x = resize_img_mat(malignant_x, resize_rate, whether_readable=True)\n\nlength = benign_x.shape[1]\nwidth = benign_x.shape[2]\nchannels = benign_x.shape[3]\n\nprint(benign_x.shape)\nprint(malignant_x.shape)\n\ntotal_p, train_p, total_n, train_n = list_size_calc(malignant_x, benign_x, training_rate)\n\nprint(train_n)\nprint(train_p)\n\ntrain_list_p, test_list_p, train_list_n, test_list_n = get_balanced_load_list(load_list, train_p, total_p, train_n, total_n)\n\ntrain_image_p = malignant_x[train_list_p]\ntrain_image_n = benign_x[train_list_n]\ntest_image_p = malignant_x[test_list_p]\ntest_image_n = benign_x[test_list_n]\n\nprint(train_image_p.shape)\nprint(train_image_n.shape)\nprint(test_image_p.shape)\nprint(test_image_n.shape)\n\ntrain_label_p = np.ones(len(train_image_p), dtype=int)\ntrain_label_n = np.zeros(len(train_image_n), dtype=int)\ntest_label_p = np.ones(len(test_image_p), dtype=int)\ntest_label_n = np.zeros(len(test_image_n), dtype=int)\n\ntrain_image = common_concat([train_image_p, train_image_n])\ntest_image = common_concat([test_image_p, test_image_n])\n\ntrain_label = common_concat([train_label_p, train_label_n])\ntest_label = common_concat([test_label_p, test_label_n])\n\nresize_dim = (int(length * resize_rate), int(width * resize_rate))\n\n# set up transformations according to the setting\nif if_ten_crop:\n tran_test_set = [#transforms.Resize(resize_dim, interpolation=Image.ANTIALIAS),\n transforms.TenCrop(area_size)]\n if if_aug:\n tran_test_set.append(transforms.Lambda(lambda crops:\n torch.stack([transforms.Normalize((0.4914, 0.4822, 0.4465),\n (0.2023, 0.1994, 0.2010))\n (transforms.ToTensor()(crop)) for crop in crops])))\n else:\n tran_test_set.append(transforms.Lambda(lambda crops:\n torch.stack([transforms.Normalize((0.5, 0.5, 0.5),\n (0.5, 0.5, 0.5))\n (transforms.ToTensor()(crop)) for crop in crops])))\nelse:\n tran_test_set = [#transforms.Resize(resize_dim, interpolation=Image.ANTIALIAS),\n transforms.CenterCrop(area_size)]\n if if_aug:\n tran_test_set.extend([transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465),\n (0.2023, 0.1994, 0.2010))])\n else:\n tran_test_set.extend([transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5),\n (0.5, 0.5, 0.5))])\n\nif if_aug:\n tran_train_set = [#transforms.Resize(resize_dim, interpolation=Image.ANTIALIAS),\n transforms.RandomCrop(area_size, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465),\n (0.2023, 0.1994, 0.2010))]\nelse:\n tran_train_set = [#transforms.Resize(resize_dim, interpolation=Image.ANTIALIAS),\n transforms.CenterCrop(area_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5),\n (0.5, 0.5, 0.5))]\n\ntransform_train = transforms.Compose(tran_train_set)\ntransform_test = transforms.Compose(tran_test_set)\n\ntrainset = MedicalImages(data=train_image, labels=train_label, transform=transform_train)\ntestset = MedicalImages(data=test_image, labels=test_label, transform=transform_test)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False)\n\nnet = torch.load('pytorch_model.pt')\nprint(net)\n\nget_acc(net, testloader, if_ten_crop, 'gpu', set_name=\"test\")\n","sub_path":"pytorch_images/Histology_Inference.py","file_name":"Histology_Inference.py","file_ext":"py","file_size_in_byte":5883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"562908889","text":"import threading\nimport time\n\ndef threadWorker():\n print (\"Thread in running state\")\n time.sleep(10)\n print (\"Terminating\")\n \nmyThread = threading.Thread(target=threadWorker)\n\nmyThread.start()\n\nmyThread.join()\n\nprint(\"Thread enters dead state\")","sub_path":"Threading/threadlifecyle.py","file_name":"threadlifecyle.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"596502756","text":"from ndlib.models.actions.Action import Action\nimport numpy as np\nimport networkx as nx\n\n__author__ = 'Giulio Rossetti'\n__license__ = \"BSD-2-Clause\"\n__email__ = \"giulio.rossetti@gmail.com\"\n\n\nclass AddNode(Action):\n\n def __init__(self, probability=1, copy_attributes=False, number_of_edges=0, model='random',\n initial_status=None, **kwargs):\n super(self.__class__, self).__init__(kwargs)\n self.probability = probability\n self.copy_attributes = copy_attributes\n self.initial_status = initial_status\n self.number_of_edges = number_of_edges\n self.model = model\n\n def execute(self, graph=None, status=None, status_map=None, *args, **kwargs):\n\n p = np.random.random_sample()\n\n # Node creation check\n if p <= self.probability:\n attr = None\n if self.copy_attributes:\n # randomly select a graph node\n ncd = np.random.choice(list(graph.nodes()))\n # create a copy of the node attribute\n attr = graph.nodes[ncd]\n\n nid = graph.number_of_nodes()+1\n graph.add_node(nid, attr=attr)\n for key in attr.keys():\n nx.set_node_attributes(graph, name=key, values={nid: key})\n\n status[nid] = status_map[self.initial_status]\n\n # Edge creation phase\n if self.number_of_edges > 0:\n # Preferential Attachment\n if self.model == 'PA':\n total_edges = graph.number_of_edges()\n if isinstance(graph, nx.Graph):\n total_edges *= 2\n probs = [float(graph.degree(n))/total_edges for n in graph.nodes()]\n # Random selection\n else:\n probs = None\n\n if self.number_of_edges > graph.number_of_nodes():\n self.number_of_edges = graph.number_of_nodes()\n\n targets = np.random.choice(list(graph.nodes()), self.number_of_edges, replace=False, p=probs)\n for tr in targets:\n graph.add_edge(nid, tr)\n\n return self.compose(graph, node_id=nid, **kwargs)\n\n return True\n","sub_path":"ndlib/models/actions/AddNode.py","file_name":"AddNode.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"295602982","text":"import numpy as np\nimport numpy.ma as ma\nimport matplotlib.pyplot as plt\nfrom division_data import *\nfrom matplotlib.figure import Figure\nfrom re import sub\nfrom pydap.client import open_url\nfrom mpl_toolkits.basemap import Basemap\nfrom matplotlib import cm, colors, colorbar\nfrom matplotlib.patches import Polygon\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.patches import PathPatch\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nimport os\nfrom os import environ as EV\n\ndef USbasemap(fig = None, ax = None):\n\n\tif fig == None:\n\t\tfig = plt.figure()\n\t\tax = fig.add_subplot(111)\n\n\tm = Basemap(ax = ax, projection = 'merc', llcrnrlon=-130, llcrnrlat = 25, \\\n\t\t\t\turcrnrlon = -60, urcrnrlat=50, resolution = 'i')\n\tm.drawmapboundary(fill_color='gray')\n\tm.drawcoastlines(linewidth = 0.25)\n\tm.drawcountries()\n\tm.fillcontinents(color='gray',lake_color='aqua')\n\tfp = EV['SHPFILES']+'/CONUS_CLIMATE_DIVISIONS/GIS_OFFICIAL_CLIM_DIVISIONS'\n\tm.readshapefile(fp, 'divs', drawbounds = False)\n\treturn fig, ax, m\n\ndef valueMap(data, fig = None, ax = None):\n\t#data should be a dataframe with divnames as the indices\n\tfig, ax, m = USbasemap(fig = fig, ax = ax)\n\tminima = min(data.values)\n\tmaxima = max(data.values)\n\n\tcmap = cm.RdBu\n\tnorm = colors.Normalize(vmin = minima, vmax = maxima, clip = True)\n\tmapper = cm.ScalarMappable(norm = norm, cmap = cmap)\n\n\tcodes = reverseStates(importStates())\n\n\tfor name in data.index:\n\t\tdivcode = codes[name[:-3]]+name[-2:]\n\t\tcolor = mapper.to_rgba(data.loc[name])\n\t\tpatches = []\n\t\tfor info, shape in zip(m.divs_info, m.divs):\n\t\t\tif info['CLIMDIV']==int(divcode):\n\t\t\t\tpatches.append(Polygon(np.array(shape),True))\n\t\tax.add_collection(PatchCollection(patches, facecolor = color, \\\n\t\t\tedgecolor='k', linewidths=1., zorder=2))\n\tcax = fig.add_axes([.925, .3, .025, .4])\n\tcb = colorbar.ColorbarBase(cax, cmap = cmap, norm = norm, spacing = 'proportional')\n\treturn fig, ax\n\t\"\"\"\n\tNOTES:\n\tColorbar info obtained from here\n\thttp://stackoverflow.com/questions/25505674/python-matplotlib-add-colorbar\n\t\"\"\"\n\ndef sstMap(nipaPhase, phase = 'allyears', field = 'sst', fig = None, ax = None, monte = False):\n\tfrom numpy import linspace\n\tif fig == None:\n\t\tfig = plt.figure()\n\t\tax = fig.add_subplot(111)\n\tm = Basemap(ax = ax, projection = 'robin', lon_0 = 270, resolution = 'i')\n\tm.drawmapboundary(fill_color='aqua')\n\tm.drawcoastlines(linewidth = 0.25)\n\tm.drawcountries()\n\tm.fillcontinents(color='green',lake_color='aqua')\n\tparallels = np.linspace(m.llcrnrlat, m.urcrnrlat, 4)\n\tmeridians = np.linspace(m.llcrnrlon, m.urcrnrlon, 4)\n\tm.drawparallels(parallels, linewidth = 1, labels = [0,0,0,0])\n\tm.drawmeridians(meridians, linewidth = 1, labels = [0,0,0,0])\n\n\tlons = nipaPhase.lon[field]\n\tlats = nipaPhase.lat[field]\n\tif monte:\n\t\tdata = nipaPhase.monte_grid[phase]\n\t\tlevels = linspace(0, data.max(), data.max())\n\t\tcmap = cm.Reds\n\telse:\n\t\tdata = nipaPhase.corr_grid[field][phase]\n\t\tlevels = linspace(-0.8,0.8,9)\n\t\tcmap = cm.RdBu\n\tlons, lats = np.meshgrid(lons,lats)\n\tim1 = m.pcolormesh(lons,lats,data, vmin = np.min(levels), \\\n\t\tvmax=np.max(levels), cmap = cmap, latlon=True)\n\tcb = m.colorbar(im1,'bottom', size=\"5%\", pad=\"2%\")\n\tax.set_title('%s, %s' % (phase, field))\n\treturn fig, ax, m\n","sub_path":"modules/mapFuncts.py","file_name":"mapFuncts.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"384433195","text":"import streamlit as st\r\nimport cv2 as cv\r\nfrom PIL import Image,ImageEnhance\r\nimport numpy as np\r\nimport os\r\nimport PIL\r\nimport numpy\r\n\r\n\r\ndef detect(image):\r\n '''\r\n Function to detect circles\r\n '''\r\n pil_image = image.convert('RGB') \r\n img = numpy.array(pil_image) \r\n # Convert RGB to BGR \r\n img = img[:, :, ::-1].copy()\r\n \r\n output = img.copy()\r\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\r\n gray = cv.medianBlur(gray, 5)\r\n \r\n\r\n\r\n circles = cv.HoughCircles(gray, cv.HOUGH_GRADIENT, 0.5, 1,\r\n param1=50, param2=30, minRadius=10, maxRadius=20)\r\n detected_circles = np.uint16(np.around(circles))\r\n for (x, y ,r) in detected_circles[0, :]:\r\n cv.circle(output, (x, y), r+5, (0, 0, 0), -1)\r\n #cv.circle(output, (x, y), 2, (0, 255, 255), 3)\r\n cv.imwrite('0.png',output)\r\n \r\n \r\n img=cv.imread('0.png')\r\n output = img.copy()\r\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\r\n gray = cv.medianBlur(gray, 9)\r\n\r\n \r\n circles = cv.HoughCircles(gray, cv.HOUGH_GRADIENT, 0.5, 1,\r\n param1=50, param2=30, minRadius=min_rad, maxRadius=20)\r\n detected_circles = np.uint16(np.around(circles))\r\n for (x, y ,r) in detected_circles[0, :]:\r\n cv.circle(output, (x, y), r+5, (0, 0, 0), -1)\r\n #cv.circle(output, (x, y), 2, (0, 255, 255), 3)\r\n cv.imwrite('1.png',output)\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n \r\n \r\n return output\r\n \r\n \r\n\r\n\r\n\r\ndef about():\r\n st.write(\r\n '''\r\n contact email - tanbinhasnat04@gmail.com\r\n ''')\r\n\r\n\r\ndef main():\r\n st.title(\"circle Detection App :sunglasses: \")\r\n st.write(\"**Using the Haar cascade Classifiers**\")\r\n\r\n activities = [\"Home\", \"About\"]\r\n choice = st.sidebar.selectbox(\"Pick something fun\", activities)\r\n\r\n if choice == \"Home\":\r\n\r\n st.write(\"Go to the About section from the sidebar to learn more about it.\")\r\n \r\n # You can specify more file types below if you want\r\n image_file = st.file_uploader(\"Upload image\", type=['jpeg', 'png', 'jpg', 'webp'])\r\n print(type(image_file))\r\n global min_rad\r\n min_rad=st.slider('mir radius : ',value=5)\r\n st.write('min radius ',min_rad)\r\n\r\n br=st.slider('Brightness : ',value=1.4,min_value=1.0,max_value=4.0,step=0.1)\r\n st.write('Brightness ',br)\r\n\r\n con=st.slider('contrast : ',value=1.5,min_value=1.0,max_value=4.0,step=0.1)\r\n st.write('contrast ',con)\r\n\r\n sh=st.slider('sharpness : ',value=1.0,min_value=1.0,max_value=4.0,step=0.1)\r\n st.write('sharpness ',sh)\r\n\r\n\r\n if image_file is not None:\r\n\r\n image = Image.open(image_file)\r\n\r\n \r\n enhencer=ImageEnhance.Brightness(image)\r\n image=enhencer.enhance(br)\r\n enhencer=ImageEnhance.Contrast(image)\r\n image=enhencer.enhance(con)\r\n enhencer=ImageEnhance.Sharpness(image)\r\n image=enhencer.enhance(sh)\r\n\r\n \r\n\r\n\r\n if st.button(\"Process\"):\r\n\r\n \r\n # result_img is the image with rectangle drawn on it (in case there are faces detected)\r\n # result_faces is the array with co-ordinates of bounding box(es)\r\n result_img = detect(image=image)\r\n st.image(result_img, use_column_width = True)\r\n\r\n elif choice == \"About\":\r\n about()\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"544523183","text":"from flask import jsonify, request\n\nfrom .app import app, db\nfrom .models import User, Project\nfrom .wrappers import userRequiredJson\n\n@app.route(\"/projects\", methods=['GET'])\n@userRequiredJson()\ndef getProjects(user):\n userId = user[\"id\"]\n user = User.query.filter_by(id=userId).first()\n projects = [p.as_dict() for p in user.projects]\n print(projects)\n return jsonify({\"projects\": projects}), 200\n\n@app.route(\"/projects/\", methods=['DELETE'])\n@userRequiredJson()\ndef deleteProject(user, projectId):\n userId = user[\"id\"]\n project = Project.query.filter_by(id=projectId).first()\n if (project.user_id != userId):\n return jsonify({\"err\": \"you can't delete others projects\"}), 401\n Project.query.filter_by(id=projectId).delete()\n db.session.commit()\n return jsonify({\"project\": project.as_dict()}), 200\n\n@app.route(\"/projects/\", methods=['PUT'])\n@userRequiredJson()\ndef editProject(user, projectId):\n userId = user[\"id\"]\n project = Project.query.filter_by(id=projectId).first()\n if (project.user_id != userId):\n return jsonify({\"err\": \"you can't edit others projects\"}), 401\n data_json = request.get_json()\n print(data_json)\n project.description = data_json[\"desc\"]\n project.title = data_json[\"title\"]\n db.session.add(project)\n db.session.commit()\n return jsonify({\"project\": project.as_dict()}), 200\n\n@app.route(\"/projects\", methods=['POST'])\n@userRequiredJson()\ndef addProject(user):\n userId = user[\"id\"]\n data_json = request.get_json()\n newProject = Project(title=data_json[\"title\"], description=data_json[\"desc\"], user_id=userId)\n db.session.add(newProject)\n db.session.commit()\n return jsonify({\"project\": newProject.as_dict()}), 200\n","sub_path":"app/projects.py","file_name":"projects.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"369322762","text":"\"\"\"\n************************************************************************************************************************\nAuthor: Rahul Ambati (GET Mercedes Benz R&D India)\nCo-Authors: None Yet\nTool Description: A labelling/annotation Tool for SVS Images\n************************************************************************************************************************\n\"\"\"\n\nimport json\nimport os.path\nimport datetime\n\n\nfrom base64 import b64encode, b64decode\n\nclass LabelFileError(Exception):\n pass\n\nclass LabelFile(object):\n suffix = '.json'\n\n def __init__(self, filename=None):\n self.shapes = ()\n\n if filename is not None:\n self.load(filename)\n\n #iLabelTool Format\n def load(self, filename):\n shapes = []\n with open(filename, 'r') as f:\n data = json.load(f)\n for s in data[\"shapes\"]:\n shapes.append([s['label'], s['points'],s['attributes'], s[\"z_value\"], s['instance_id']])\n return shapes, data\n\n def format_shape(self, s):\n return dict(label=str(s.label_name),\n z_value=s.z_value,\n points=[(p.pos().x(), p.pos().y()) for p in s.handle_list],\n attributes=s.attributes,\n instance_id=s.instance_id)\n\n def save(self, filename, img_name, directory, height, width, shapes, finalize, version):\n\n shapes = [self.format_shape(shape) for shape in shapes]\n\n with open(filename, 'w') as f:\n json.dump(dict(\n version=version,\n seqdir=directory,\n imagename=img_name,\n height=height,\n width=width,\n finalized=finalize,\n shapes=shapes,\n imagePath=filename),\n f, ensure_ascii=True, indent=4)\n\n @staticmethod\n def isLabelFile(filename):\n if os.path.splitext(filename)[1].lower() == '.json':\n return True\n else:\n return False\n\n","sub_path":"Legacy_Stuff/iLabel_Qt_Aug28/file_management.py","file_name":"file_management.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"355918853","text":"# -*- coding: utf-8 -*-\n\nimport boto3\nimport botocore\n\n# This is where we write the entry. Note that we use the CHECKSUM as a primary keyu\n# Registration WILL fail if the same file exists\n# NOTE: Should we tie the index to account as well?\ndef writeEntry(DOC):\n dynamodb = boto3.resource('dynamodb')\n table = dynamodb.Table('Assets')\n \n try:\n table.put_item(\n Item = DOC,\n ConditionExpression = 'attribute_not_exists(Checksum)'\n )\n except botocore.exceptions.ClientError as err:\n result = { \n 'reason' : 'REG-0001_Duplicate file entry: The file with ID %s already exists' %(DOC['Checksum']),\n 'detail' : str(err)\n }\n else:\n result = { \n 'Checksum' : DOC['Checksum'] \n }\n\n return result\n\n# Database updates expect:\n# Primary Key [Dictionary] of the file\n# The update expression\n# The update values\n# Return Values [Optional]\n# Note: We should add in a parameter to fail if the primary key is not found\ndef updateEntry(key, updateExpression, expressionValue, returnValues='NONE'):\n dynamodb = boto3.resource('dynamodb')\n table = dynamodb.Table('Assets')\n #print key, updateExpression, expressionValue, returnValues\n response = table.update_item(\n Key = key,\n UpdateExpression = updateExpression,\n ExpressionAttributeValues = expressionValue,\n ReturnValues = returnValues\n )\n \n return response\n \n \ndef deleteEntry(key):\n \n dynamodb = boto3.resource('dynamodb')\n table = dynamodb.Table('Assets')\n \n response = table.delete_item(\n Key = key,\n )\n \n return response\n ","sub_path":"EC2-Backup/Deprecated Code/Assets/sharedLibraries/databaseHelper.py","file_name":"databaseHelper.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"325674883","text":"from sqlalchemy import desc\nfrom src.models import Track, Stem\nfrom src.queries.query_helpers import create_save_repost_count_subquery, \\\n populate_track_metadata, add_users_to_tracks, decayed_score\nfrom src.utils.db_session import get_db_read_replica\nfrom src.utils import helpers\n\ndef get_remixable_tracks(args):\n \"\"\"Gets a list of remixable tracks\"\"\"\n db = get_db_read_replica()\n limit = args.get(\"limit\", 25)\n current_user_id = args.get(\"current_user_id\", None)\n\n with db.scoped_session() as session:\n # Subquery to get current tracks that have stems\n remixable_tracks_subquery = (\n session.query(Track)\n .join(Stem, Stem.parent_track_id == Track.track_id)\n .filter(\n Track.is_current == True,\n Track.is_unlisted == False,\n Track.is_delete == False\n )\n .subquery()\n )\n\n count_subquery = create_save_repost_count_subquery(session, \"track\")\n\n query = (\n session.query(\n remixable_tracks_subquery,\n count_subquery.c[\"count\"],\n decayed_score(\n count_subquery.c[\"count\"],\n remixable_tracks_subquery.c.created_at\n ).label(\"score\")\n )\n .select_from(remixable_tracks_subquery)\n .join(\n count_subquery,\n count_subquery.c[\"id\"] == remixable_tracks_subquery.c.track_id\n )\n .order_by(\n desc(\"score\"),\n desc(remixable_tracks_subquery.c.track_id)\n )\n .limit(limit)\n )\n\n tracks = helpers.query_result_to_list(query.all())\n track_ids = list(map(lambda track: track[\"track_id\"], tracks))\n\n # Get user specific data for tracks\n tracks = populate_track_metadata(session, track_ids, tracks, current_user_id)\n\n if args.get(\"with_users\", False):\n add_users_to_tracks(session, tracks, current_user_id)\n\n return tracks\n","sub_path":"discovery-provider/src/queries/get_remixable_tracks.py","file_name":"get_remixable_tracks.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"582647788","text":"from django.test import TestCase\nfrom code.models import Person\nfrom code.mutantes import *\nfrom django.test import RequestFactory, TestCase\nfrom code.views import mutantView\nimport json\n\nclass PersonTestCase(TestCase):\n def setUp(self):\n Person.objects.create(dna =\"[ATGCGA,CAGTGC,TTATGT,AGAAGG,CCCCTA,TCACTG]\", mutant = True,dna_hash = 1234)\n \n def test_get_dnsHash(self):\n \n person = Person.objects.get(dna_hash = 1234)\n \n self.assertEqual(person.getDnaHash(), 1234)\n \n def test_get_Mutant(self):\n person = Person.objects.get(dna_hash = 1234)\n self.assertEqual(person.getMutant(), True)\n\n def test_get_dna(self):\n person = Person.objects.get(dna_hash = 1234)\n self.assertEqual(person.getDna(), \"[ATGCGA,CAGTGC,TTATGT,AGAAGG,CCCCTA,TCACTG]\")\n \nclass MuntantDectectorCase(TestCase):\n \n def test_isMutant_True(self):\n \n dna_mutant =[\"ATGCGA\",\n \"CAGTGC\",\n \"TTATGT\",\n \"AGAAGG\",\n \"CCCCTA\",\n \"TCACTG\"]\n\n mutantDectector = MutantDetector()\n\n self.assertTrue(mutantDectector.isMutant(dna_mutant))\n\n def test_isMutant_False(self):\n \n dna_human =[\"ATGCGA\",\n \"CCGTTC\",\n \"TTATGT\",\n \"AGAAGG\",\n \"CCCCTA\",\n \"TCACTG\"]\n \n mutantDectector = MutantDetector()\n\n self.assertTrue( not mutantDectector.isMutant(dna_human))\n\n def test_isMutant_True_Diagonales(self):\n \n dna_mutant =[\"ATGCGA\",\n \"CAGTAC\",\n \"TTAAGT\",\n \"CTAAGG\",\n \"CCTCTA\",\n \"TCACTG\"]\n \n mutantDectector = MutantDetector()\n\n self.assertTrue(mutantDectector.isMutant(dna_mutant))\n\n def test_isMutant_True_Horizontales(self):\n dna_mutant =[\"TTAAAA\",\n \"CAGTCC\",\n \"TTAAGT\",\n \"CTAAGG\",\n \"CCTCTA\",\n \"TTTTCC\"]\n \n mutantDectector = MutantDetector()\n\n self.assertTrue(mutantDectector.isMutant(dna_mutant))\n\n def test_isMutant_True_Verticales(self):\n dna_mutant =[\"TTACAA\",\n \"TAGTCC\",\n \"TTAAGA\",\n \"TTAAGA\",\n \"CCTCTA\",\n \"TTTACA\"]\n \n mutantDectector = MutantDetector()\n\n self.assertTrue(mutantDectector.isMutant(dna_mutant))\n\nclass MutantApi(TestCase):\n def setUp(self):\n \n self.factory = RequestFactory()\n \n def test_isMutant_True(self):\n \n request = self.factory.post('/mutant/', data = { \"dna\":[\"ATGCGA\",\n \"CAGTGC\",\n \"TTATGT\",\n \"AGAAGG\",\n \"CCCCTA\",\n \"TCACTG\"]}, content_type='application/json')\n\n response = mutantView.as_view()(request)\n self.assertEqual(response.status_code, 200)\n\n def test_isMutant_False(self):\n \n request = self.factory.post('/mutant/', data = { \"dna\":[\"TTGCGA\",\n \"CAGTTC\",\n \"TTAAGT\",\n \"ATAAGG\",\n \"CCCCTA\",\n \"TCACTG\"]}, content_type='application/json')\n\n response = mutantView.as_view()(request)\n self.assertEqual(response.status_code, 403)\n \n def test_isMutant_false_1000dnas(self):\n testBoolean = True\n dnas = jsonfileToDic(\"code/data/dnasHuman.json\")\n \n for dna in dnas.values():\n request = self.factory.post('/mutant/', data = { \"dna\":dna}, content_type='application/json')\n\n response = mutantView.as_view()(request)\n\n if(response.status_code != 403):\n testBoolean = False\n\n for dna in dnas.values():\n request = self.factory.post('/mutant/', data = { \"dna\":dna}, content_type='application/json')\n\n response = mutantView.as_view()(request)\n\n if(response.status_code != 403):\n testBoolean = False\n \n self.assertTrue(testBoolean)\n\ndef jsonfileToDic(filename):\n with open(filename,'r') as f_in:\n return(json.load(f_in))","sub_path":"Mutants/code/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"586041520","text":"#Drill 0\r\n# Remember, you will use the same model, only with the test set data. Don't fit a new model by mist\r\nX_test_lsa = lsa.transform(X_test_tfidf)\r\n\r\nparas_by_component=pd.DataFrame(X_test_lsa,index=X_test)\r\nfor i in range(5):\r\n print('Component {}:'.format(i))\r\n print(paras_by_component.loc[:,i].sort_values(ascending=False)[0:10])\r\n\r\n\r\n#Drill 1\r\nimport spacy\r\n#Tweaks Go Here\r\nnlp = spacy.load('en')\r\nemma_raw = gutenberg.raw('austen-emma.txt')\r\nemma_doc = nlp(emma_raw)\r\nemma_sentences = list(emma_doc.sents)\r\n\r\nemma_sentences_text = []\r\nfor span in emma_sentences:\r\n emma_sentences_text.append(span.text)\r\n\r\nX_train, X_test = train_test_split(emma_sentences_text, test_size=0.4, random_state=0)\r\n\r\nvectorizer = TfidfVectorizer(max_df=0.4, # drop words that occur in more than half the paragraphs\r\n min_df=10, # only use words that appear at least twice\r\n stop_words='english', \r\n lowercase=True, #convert everything to lower case (since Alice in Wonderland has the HABIT of CAPITALIZING WORDS for EMPHASIS)\r\n use_idf=True,#we definitely want to use inverse document frequencies in our weighting\r\n norm=u'l2', #Applies a correction factor so that longer paragraphs and shorter paragraphs get treated equally\r\n smooth_idf=True #Adds 1 to all document frequencies, as if an extra document existed that used every word once. Prevents divide-by-zero errors\r\n )\r\n\r\n#Applying the vectorizer\r\nemma_sents_tfidf=vectorizer.fit_transform(emma_sentences_text)\r\nprint(\"Number of features: %d\" % emma_sents_tfidf.get_shape()[1])\r\n\r\n#splitting into training and test sets\r\nX_train_tfidf, X_test_tfidf= train_test_split(emma_sents_tfidf, test_size=0.4, random_state=0)\r\n\r\n\r\n#Reshapes the vectorizer output into something people can read\r\nX_train_tfidf_csr = X_train_tfidf.tocsr()\r\n\r\n#number of paragraphs\r\nn = X_train_tfidf_csr.shape[0]\r\n#A list of dictionaries, one per paragraph\r\ntfidf_bypara = [{} for _ in range(0,n)]\r\n#List of features\r\nterms = vectorizer.get_feature_names()\r\n#for each paragraph, lists the feature words and their tf-idf scores\r\nfor i, j in zip(*X_train_tfidf_csr.nonzero()):\r\n tfidf_bypara[i][terms[j]] = X_train_tfidf_csr[i, j]\r\n\r\n#Keep in mind that the log base 2 of 1 is 0, so a tf-idf score of 0 indicates that the word was present once in that sentence.\r\nprint('Original sentence:', X_train[2])\r\nprint('Tf_idf vector:', tfidf_bypara[2])\r\n\r\nsvd= TruncatedSVD(130)\r\nlsa = make_pipeline(svd, Normalizer(copy=False))\r\n# Run SVD on the training data, then project the training data.\r\nX_train_lsa = lsa.fit_transform(X_train_tfidf)\r\n\r\nvariance_explained=svd.explained_variance_ratio_\r\ntotal_variance = variance_explained.sum()\r\nprint(\"Percent variance captured by all components:\",total_variance*100)\r\n\r\n#Looking at what sorts of paragraphs our solution considers similar, for the first five identified topics\r\nparas_by_component=pd.DataFrame(X_train_lsa,index=X_train)\r\nfor i in range(5):\r\n print('Component {}:'.format(i))\r\n print(paras_by_component.loc[:,i].sort_values(ascending=False)[0:10])","sub_path":"Lasso R2.py","file_name":"Lasso R2.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"532486151","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\n\ndef read_synaptic_weight(file_path):\n return np.loadtxt(file_path)\n\n\ndef plot_results(pf_tan_weight, ctx_msn_weight):\n plt.plot(pf_tan_weight, 'k--', label='CM/Pf-TAN')\n plt.plot(ctx_msn_weight, 'k-', label='Sensory Cortex-MSN')\n plt.legend(loc=0)\n plt.ylabel('Synaptic Strength')\n plt.axvline(pf_tan_weight.size/3, color='k', alpha=0.5)\n plt.axvline(pf_tan_weight.size * 2/3, color='k', alpha=0.5)\n plt.xlabel('Trial')\n plt.axis([0, pf_tan_weight.size, 0, 1.1])\n plt.show()\n\n\ndef main():\n if (len(sys.argv) == 1):\n print(\"Please enter a command.\")\n elif (sys.argv[1] == \"default\"):\n pf_tan_weight = read_synaptic_weight('./results/w_pf_tan')\n ctx_msn_weight = read_synaptic_weight('./results/w_ctx_msn')\n plot_results(pf_tan_weight, ctx_msn_weight)\n elif (sys.argv[1] == \"pso\"):\n pf_tan_weight = read_synaptic_weight('./pso_simulation/w_pf_tan')\n ctx_msn_weight = read_synaptic_weight('./pso_simulation/w_ctx_msn')\n plot_results(pf_tan_weight, ctx_msn_weight)\n else:\n print(\"Unknown argument.\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"plot_fast_reacquisition.py","file_name":"plot_fast_reacquisition.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"315358035","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.datasets import make_classification\nfrom sklearn.decomposition import PCA\nfrom imblearn.under_sampling import RandomUnderSampler\n\n# Generate the dataset\nX, y = make_classification(n_classes=2, class_sep=2, weights=[0.15, 0.95], n_informative=3, n_redundant=1, flip_y=0,\n n_features=20, n_clusters_per_class=2, n_samples=1000, random_state=10)\npca = PCA(n_components=3)\nX_vis = pca.fit_transform(X)\n\n# Apply the random under-sampling\nrus = RandomUnderSampler(return_indices=True)\nX_resampled, y_resampled, idx_resampled = rus.fit_resample(X, y)\nX_res_vis = pca.transform(X_resampled)\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\nidx_samples_removed = np.setdiff1d(np.arange(X_vis.shape[0]), idx_resampled)\nidx_class_0 = y_resampled == 0\n\n# make plot\nplt.scatter(X_res_vis[idx_class_0, 0], X_res_vis[idx_class_0, 1], alpha=.8, label='Class #0')\nplt.scatter(X_res_vis[~idx_class_0, 0], X_res_vis[~idx_class_0, 1], alpha=.8, label='Class #1')\nplt.scatter(X_vis[idx_samples_removed, 0], X_vis[idx_samples_removed, 1], alpha=.8, label='Removed samples')\n\nax.spines['top'].set_visible(False)\nax.spines['right'].set_visible(False)\nax.get_xaxis().tick_bottom()\nax.get_yaxis().tick_left()\nax.spines['left'].set_position(('outward', 10))\nax.spines['bottom'].set_position(('outward', 10))\nax.set_xlim([-6, 6])\nax.set_ylim([-6, 6])\n\nplt.title('Under-sampling using ramdom under-sampling')\nplt.legend()\nplt.tight_layout()\nplt.show()\n","sub_path":"data_balancing.py","file_name":"data_balancing.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"165850972","text":"import abdbeam as ab\n\nsc = ab.Section()\n# Create a materials dictionary:\nmts = dict()\nmts[1] = ab.Laminate()\nmts[1].ply_materials[1] = ab.PlyMaterial(0.0001, 148e9, 9.65e9, 4.55e9,\n 0.3)\nmts[1].ply_materials[2] = ab.PlyMaterial(0.0002, 16.39e9, 16.39e9,\n 38.19e9, 0.801)\nmts[1].plies = [[0,1]]*10 + [[45,1]]*10\nmts[1].symmetry = 'T'\n# Create a points dictionary based on Y and Z point coordinates:\npts = dict()\npts[1] = ab.Point(-0.025, -0.035)\npts[2] = ab.Point(0.025, -0.035)\npts[3] = ab.Point(0.025, 0.035)\npts[4] = ab.Point(-0.025, 0.035)\n# Create a segments dictionary referencing point and material ids:\nsgs = dict()\nsgs[1] = ab.Segment(1,2,1)\nsgs[2] = ab.Segment(2,3,1)\nsgs[3] = ab.Segment(3,4,1)\nsgs[4] = ab.Segment(4,1,1)\n# Point the dictionaries to the section\nsc.materials = mts\nsc.points = pts\nsc.segments = sgs\n# Calculate and output section properties\nsc.calculate_properties()\nsc.summary()\nab.plot_section(sc, segment_coord=True, figsize=(6.4*0.8, 4.8*0.8))\n# Create a single load case and calculate its internal loads\nsc.loads[1] = ab.Load(Px=200, Mz=10, Vz_s=-100)\nsc.calculate_internal_loads()\n# Plot internal loads\nab.plot_section_loads(sc, 1, int_load_list=['Nx', 'Nxy'],\n title_list=['Abdbeam - Nx (N/m)',\n 'Abdbeam - Nxy (N/m)'], figsize=(6.4*0.8, 4.8*0.8))","sub_path":"abdbeam/examples/example_kollar_springer_single_cell.py","file_name":"example_kollar_springer_single_cell.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"546240668","text":"import wqi\n# import vis\nimport tkinter as tk\nfrom tkinter import ttk \nfrom tkinter import * \nfrom tkinter.ttk import *\nfrom tkinter import filedialog\nimport pandas as pd\nimport homepage\nimport numpy as np\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\nfrom matplotlib.backend_bases import key_press_handler\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure\nimport matplotlib.image as mpimg\nfrom geopy.geocoders import Nominatim\nimport time\n\nroot = tk.Tk()\nroot.wm_title(\"Water Quality Index Estimation Tool\")\nroot.geometry(\"900x600\")\ntabControl = ttk.Notebook(root) \n\n\nhome = ttk.Frame(tabControl)\ntab1 = ttk.Frame(tabControl) \ntab2 = ttk.Frame(tabControl) \ntab3 = ttk.Frame(tabControl) \ntab4 = ttk.Frame(tabControl) \ntabControl.add(home, text ='HOME') \ntabControl.add(tab1, text ='TASK 1') \ntabControl.add(tab2, text ='TASK 2') \ntabControl.add(tab3, text ='TASK 3') \ntabControl.add(tab4, text ='VIZ') \n\ntabControl.pack(expand = 1, fill =\"both\") \n\ncsv =None\ncsv_q2 = None\ncsv_q3 = None\ndf_q3 = None\n\ndef add_tab1(tab1, tab4):\n\thead = tk.Label(tab1, text=\"TASK 1\", font=(\"Verdana\", 20))\n\thead.place(x=400,y=10)\n\n\tattrs = [\"pH\", \"Temperature\",\" Turbidity\",\"TDS\",\"Nitrates\",\"Fecal Coliform\"]\n\tlabs = []\n\tets = []\n\tfor i in range(len(attrs)):\n\t\tlabs.append(tk.Label(tab1, text=attrs[i]))\n\t\tets.append(tk.Entry(tab1))\n\t\tlabs[i].place(x = 200, y = 50 + (50 * i))\n\t\tets[i].place(x = 450, y = 50 + (50 * i))\n\n\tdef open_file():\n\t\tfile = filedialog.askopenfilename(title = \"choose your file\",filetypes =[('csv files','*.csv')])\n\t\tglobal csv \n\t\tcsv = pd.read_csv(file)\n\n\tbtn = Button(tab1, text ='Choose file', command = lambda:open_file()) \n\t# btn.grid(row=6,column=1)\n\tbtn.place(x=420, y=400)\n\tout_name = tk.Label(tab1, text=\"Output File Name\")\n\tout_name.place(x=200, y=450)\n\tets.append(tk.Entry(tab1))\n\tets[-1].place(x=450, y=450)\n\n\tclasses = [\"Very Bad\", \"Bad\", \"Medium\", \"Good\", \"Excellent\"]\n\tdef show_entry_fields():\n\t\tqual_ind_vec = []\n\t\tqual_cls_vec = []\n\t\tif csv is not None:\n\t\t\tfor i in range(len(csv)) : \n\t\t\t\t# print(csv.iloc[i, 0], csv.iloc[i, 2]) \n\t\t\t\tif 'NIT' not in csv:\n\t\t\t\t\tcsv['NIT'] = 0.5\n\t\t\t\tif 'FEC' not in csv:\n\t\t\t\t\tcsv['FEC'] = 0\n\t\t\t\t# print(csv.iloc[i, 6],csv.iloc[i, 3],csv.iloc[i, 11],csv.iloc[i, 5],csv.iloc[i, 18],csv.iloc[i, 19])\n\t\t\t\tqual_ind = wqi.q1_main(csv.iloc[i, 6],csv.iloc[i, 3],csv.iloc[i, 11],csv.iloc[i, 5],csv.iloc[i, 18],csv.iloc[i, 19])\n\t\t\t\t# tk.Label(tab1,text=qual_ind).grid(row=i,column=7)\n\t\t\t\tif qual_ind>=0 and qual_ind<25:\n\t\t\t\t\twq_clss = classes[0]\n\t\t\t\telif qual_ind>=25 and qual_ind<50:\n\t\t\t\t\twq_clss = classes[1]\n\t\t\t\telif qual_ind>=50 and qual_ind<70:\n\t\t\t\t\twq_clss = classes[2]\n\t\t\t\telif qual_ind>=70 and qual_ind<90:\n\t\t\t\t\twq_clss = classes[3]\n\t\t\t\telse:\n\t\t\t\t\twq_clss = classes[4]\n\t\t\t\tqual_ind_vec.append(qual_ind)\n\t\t\t\tqual_cls_vec.append(wq_clss)\n\t\t\n\t\t\tcsv[\"WQI\"] = qual_ind_vec\n\t\t\tcsv[\"WQC\"] = qual_cls_vec\n\t\t\toutputfname = ets[-1].get()\n\n\t\t\tif not outputfname:\n\t\t\t\toutputfname = \"out.csv\"\n\t\t\tcsv.to_csv(outputfname, index=False)\n\t\t\t# vis.q1(csv)\n\t\telse:\n\t\t\tevals = [float(et.get()) for et in ets[:-1]]\n\t\t\tqual_ind = wqi.q1_main(evals[0],evals[1],evals[2],evals[3],evals[4],evals[5])\n\t\t\tif qual_ind>=0 and qual_ind<25:\n\t\t\t\twq_clss = classes[0]\n\t\t\telif qual_ind>=25 and qual_ind<50:\n\t\t\t\twq_clss = classes[1]\n\t\t\telif qual_ind>=50 and qual_ind<70:\n\t\t\t\twq_clss = classes[2]\n\t\t\telif qual_ind>=70 and qual_ind<90:\n\t\t\t\twq_clss = classes[3]\n\t\t\telse:\n\t\t\t\twq_clss = classes[4]\n\t\t\t\t\n\t\t\t\t\t\n\t\t\twq = tk.Label(tab1,text=qual_ind, font=(\"Verdana\",15))\n\t\t\twq_lab = tk.Label(tab1,text=\"WQI\", font=(\"Verdana\",20))\n\t\t\twq_class = tk.Label(tab1,text=\"WQC\", font=(\"Verdana\",20))\n\t\t\twq_class_val = tk.Label(tab1,text=wq_clss, font=(\"Verdana\",15))\n\t\t\twq.place(x=700, y=300)\n\t\t\twq_lab.place(x=700, y=250)\n\t\t\twq_class.place(x=700, y=350)\n\t\t\twq_class_val.place(x=700, y=400)\n\t\n\tdef show_entry_fields1():\n\t\tqual_ind_vec = []\n\t\tqual_cls_vec = []\n\t\t\n\t\tevals = [float(et.get()) for et in ets[:-1]]\n\t\tqual_ind = wqi.q1_main(evals[0],evals[1],evals[2],evals[3],evals[4],evals[5])\n\t\tif qual_ind>=0 and qual_ind<25:\n\t\t\twq_clss = classes[0]\n\t\telif qual_ind>=25 and qual_ind<50:\n\t\t\twq_clss = classes[1]\n\t\telif qual_ind>=50 and qual_ind<70:\n\t\t\twq_clss = classes[2]\n\t\telif qual_ind>=70 and qual_ind<90:\n\t\t\twq_clss = classes[3]\n\t\telse:\n\t\t\twq_clss = classes[4]\n\t\t\t\n\t\t\t\t\n\t\twq = tk.Label(tab1,text=qual_ind, font=(\"Verdana\",15))\n\t\twq_lab = tk.Label(tab1,text=\"WQI\", font=(\"Verdana\",20))\n\t\twq_class = tk.Label(tab1,text=\"WQC\", font=(\"Verdana\",20))\n\t\twq_class_val = tk.Label(tab1,text=wq_clss, font=(\"Verdana\",15))\n\t\twq.place(x=700, y=300)\n\t\twq_lab.place(x=700, y=250)\n\t\twq_class.place(x=700, y=350)\n\t\twq_class_val.place(x=700, y=400)\n\n\tqt = tk.Button(tab1, text='QUIT', command=tab1.quit)\n\tqt.place(x=500, y=500)\n\tcalc = tk.Button(tab1, text='CALCULATE', command=show_entry_fields)\n\tcalc.place(x=350, y=500)\n\tcalc1 = tk.Button(tab1, text='CALCULATE', command=show_entry_fields1)\n\tcalc1.place(x=350, y=350)\n\tviz = tk.Button(tab1, text='VISUALIZE', command=lambda:get_vis(tab4, csv))\n\tviz.place(x=600, y=500)\n\n\ndef add_tab2(tab2, tab4):\n\thead = tk.Label(tab2, text=\"TASK 2\", font=(\"Verdana\", 20))\n\thead.place(x=400,y=10)\n\tatts = [\"Turbidity\", \"pH\",\"Color\",\"DO\", \"BOD\",\"TDS\", \"Hardness\",\"Cl\",\"No3\",\"So4\",\"Coliform\",\"As\",\"F\"]\n\tclasses2 = [\"Heavily polluted\", \"Polluted\", \"Slightly polluted\", \"Acceptable\", \"Excellent\"]\n\tlabs = []\n\tets= []\n\tfor i in range(0, len(atts)):\n\t\tlabs.append(tk.Label(tab2, text=atts[i]))\n\t\tets.append(tk.Entry(tab2))\n\t\tlabs[i].place(x = 200, y = 50 + (30 * i))\n\t\tets[i].place(x = 450, y = 50 + (30 * i))\n\n\tdef open_file():\n\t\tfile = filedialog.askopenfilename(title = \"choose your file\",filetypes =[('csv files','*.csv')])\n\t\tglobal csv_q2\n\t\tcsv_q2 = pd.read_csv(file)\n\n\tbtn = Button(tab2, text ='Choose file', command = lambda:open_file()) \n\tbtn.place(x=420, y=450)\n\tout_name = tk.Label(tab2, text=\"Output File Name\")\n\tout_name.place(x=200, y=500)\n\tets.append(tk.Entry(tab2))\n\tets[-1].place(x=450, y=500)\n\n\tdef show_entry_fields():\n\t\tqual_ind_vec = []\n\t\tqual_cls_vec = []\n\t\tif csv_q2 is not None:\n\t\t\tfor i in range(len(csv_q2)) : \n\t\t\t\t# print(csv_q2.iloc[i, 0], csv_q2.iloc[i, 2]) \n\t\t\t\tpars = [csv_q2.iloc[i,j] for j in range(4, 17)]\n\t\t\t\tqual_ind = wqi.q2_main(pars)\n\t\t\t\t# print(qual_ind)\n\t\t\t\tif qual_ind>=0 and qual_ind<=1:\n\t\t\t\t\twq_clss = classes2[4]\n\t\t\t\telif qual_ind>1 and qual_ind<=2:\n\t\t\t\t\twq_clss = classes2[3]\n\t\t\t\telif qual_ind>2 and qual_ind<=4:\n\t\t\t\t\twq_clss = classes2[2]\n\t\t\t\telif qual_ind>4 and qual_ind<=8:\n\t\t\t\t\twq_clss = classes2[1]\n\t\t\t\telif qual_ind>8:\n\t\t\t\t\twq_clss = classes2[0]\n\t\t\t\tqual_ind_vec.append(qual_ind)\n\t\t\t\tqual_cls_vec.append(wq_clss)\n\t\t\t\t# tk.Label(tab1,text=qual_ind).grid(row=i,column=7)\n\t\t\n\t\t\tcsv_q2[\"OIP\"] = qual_ind_vec\n\t\t\tcsv_q2[\"WQC\"] = qual_cls_vec\n\t\t\toutputfname = ets[-1].get()\n\t\t\tif not outputfname:\n\t\t\t\toutputfname = \"out.csv\"\n\t\t\tcsv_q2.to_csv(outputfname, index=False)\n\n\t\t\t# vis.q2(csv_q2)\n\t\telse:\n\t\t\tevals = [float(et.get()) for et in ets[:-1]]\n\t\t\tqual_ind = wqi.q2_main(evals)\n\t\t\t# print(qual_ind)\n\t\t\tif qual_ind>=0 and qual_ind<=1:\n\t\t\t\twq_clss = classes2[4]\n\t\t\telif qual_ind>1 and qual_ind<=2:\n\t\t\t\twq_clss = classes2[3]\n\t\t\telif qual_ind>2 and qual_ind<=4:\n\t\t\t\twq_clss = classes2[2]\n\t\t\telif qual_ind>4 and qual_ind<=8:\n\t\t\t\twq_clss = classes2[1]\n\t\t\telif qual_ind>8:\n\t\t\t\twq_clss = classes2[0]\n\t\t\t\t\n\t\t\t\t\t\n\t\t\twq = tk.Label(tab2,text=qual_ind, font=(\"Verdana\",15))\n\t\t\twq_lab = tk.Label(tab2,text=\"OIP\", font=(\"Verdana\",20))\n\t\t\twq_class = tk.Label(tab2,text=\"WQC\", font=(\"Verdana\",20))\n\t\t\twq_class_val = tk.Label(tab2,text=wq_clss, font=(\"Verdana\",15))\n\t\t\twq.place(x=700, y=300)\n\t\t\twq_lab.place(x=700, y=250)\n\t\t\twq_class.place(x=700, y=350)\n\t\t\twq_class_val.place(x=700, y=400)\n\t\n\tdef show_entry_fields1():\n\n\t\tevals = [float(et.get()) for et in ets[:-1]]\n\t\tqual_ind = wqi.q2_main(evals)\n\t\t# print(qual_ind)\n\t\tif qual_ind>=0 and qual_ind<=1:\n\t\t\twq_clss = classes2[4]\n\t\telif qual_ind>1 and qual_ind<=2:\n\t\t\twq_clss = classes2[3]\n\t\telif qual_ind>2 and qual_ind<=4:\n\t\t\twq_clss = classes2[2]\n\t\telif qual_ind>4 and qual_ind<=8:\n\t\t\twq_clss = classes2[1]\n\t\telif qual_ind>8:\n\t\t\twq_clss = classes2[0]\n\t\t\t\n\t\t\t\t\n\t\twq = tk.Label(tab2,text=qual_ind, font=(\"Verdana\",15))\n\t\twq_lab = tk.Label(tab2,text=\"OIP\", font=(\"Verdana\",20))\n\t\twq_class = tk.Label(tab2,text=\"WQC\", font=(\"Verdana\",20))\n\t\twq_class_val = tk.Label(tab2,text=wq_clss, font=(\"Verdana\",15))\n\t\twq.place(x=700, y=300)\n\t\twq_lab.place(x=700, y=250)\n\t\twq_class.place(x=700, y=350)\n\t\twq_class_val.place(x=700, y=400)\n\n\tqt = tk.Button(tab2, text='QUIT', command=tab2.quit)\n\tqt.place(x=500, y=540)\n\tcalc = tk.Button(tab2, text='CALCULATE', command=show_entry_fields)\n\tcalc.place(x=350, y=540)\n\tcalc1 = tk.Button(tab2, text='CALCULATE', command=show_entry_fields1)\n\tcalc1.place(x=650, y=150)\n\tviz = tk.Button(tab2, text='VISUALIZE', command=lambda:get_vis_q2(tab4, csv_q2))\n\tviz.place(x=600, y=540)\n\ndef add_tab3(tab3, tab4):\n\thead = tk.Label(tab3, text=\"TASK 3\", font=(\"Verdana\", 20))\n\thead.place(x=400,y=10)\n\n\tdef open_file():\n\t\tfile = filedialog.askopenfilename(title = \"choose your file\",filetypes =[('csv files','*.csv')])\n\t\tglobal csv_q3\n\t\tcsv_q3 = pd.read_csv(file)\n\n\tbtn = Button(tab3, text ='Choose file', command = lambda:open_file()) \n\tbtn.place(x=420, y=320)\n\tout_name = tk.Label(tab3, text=\"Output File Name\")\n\tout_name.place(x=200, y=420)\n\tent = tk.Entry(tab3)\n\tent.place(x=450, y=420) \n\n\t# df = pd.DataFrame()\n\t# if csv_q3 is not None:\n\t# \tdf = wqi.q3_main(csv_q3)\n\t# global csv_q3\n\tdf_train = pd.read_csv('./timeseries_train.csv')\n\tdf_name = df_train.groupby('Name').mean().reset_index()\n\n\tn = tk.StringVar() \n\t\n\tst_name = tk.Label(tab3, text=\"Station Name\")\n\tst = ttk.Combobox(tab3, text = \"Station\", width = 40, textvariable = n) \n\tst_name.place(x = 200, y = 200)\n\tst.place(x=350, y=200)\n\n\t# # Adding combobox drop down list \n\tst['values'] = df_name['Name'].tolist()\n\n\tdef ok():\n\t\tval = n.get()\n\t\tdfC = df_train[df_train['Name'] == val]\n\t\tdf_q3 = wqi.q3_main(dfC, df_train)\n\n\t\treturn df_q3\n\n\n\n\tdef show_entry_fields():\n\t\tglobal df_q3\n\t\tif csv_q3 is not None:\n\t\t\tdf_q3 = wqi.q3_main(csv_q3, df_train)\n\t\t\tdf_q3.to_csv(ent.get(),index=False)\n\t\telse:\n\t\t\tdf_q3 = ok()\n\t\t\n\tqt = tk.Button(tab3, text='QUIT', command=tab3.quit)\n\tqt.place(x=450, y=500)\n\tcalc = tk.Button(tab3, text='CALCULATE', command=show_entry_fields)\n\tcalc.place(x=300, y=500)\n\tviz = tk.Button(tab3, text='VISUALIZE', command=lambda:get_vis_q3(tab4, df_q3))\n\tviz.place(x=550, y=500)\n\ndef get_vis(tab4, df):\n\t# print(\"hi\")\n\tfig = plt.figure(figsize=(10,10))\n\n\t# tabControl.select(tab4)\n\tdf_new = df[['Name', 'lat', 'long', 'WQI', 'WQC']]\n\t# print(df_new)\n\t# print(df.loc)\n\t# df_final = df.loc[df.groupby([\"Name\"])[\"WQI\"].idxmin()]\n\tdf_add = df.loc[df.groupby([\"Name\"])[\"WQI\"].idxmin()]\n\tdf_final = df_new.append(df_add)\n\t# df_final = df_new.groupby(['Name'])['WQI'].idxmax().reset_index()\n\n\t# print(df_final)\n\t# fig, ax = plt.subplots()\n\tind_img = mpimg.imread('./india-rivers-map.jpg')\n\tplt.imshow(ind_img,extent=[68.7, 96.25, 7.4, 37.6], alpha=0.75)\n\tcolors = {'Excellent':'blue','Good':'c','Medium':'purple','Bad':'violet','Very Bad':'red'}\n\tclasses = [\"Very Bad\", \"Bad\", \"Medium\", \"Good\", \"Excellent\"]\n\tlabs=[]\n\tfor clsa in df_final[\"WQC\"]:\n\t\tlabs.append(classes.index(clsa))\n\tlatitudes = df['lat'].to_numpy()\n\tlongitudes = df['long'].to_numpy()\n\twqis = df['WQI'].to_numpy()\n\twqc = df['WQC'].to_numpy()\n\t# for longi,lat in zip(df_final[\"long\"], df_final[\"lat\"]):\n\t# \tplt.scatter(longi, lat) \n\t\n\tfor i in range(int(len(wqis)/4)):\n\t\t# print(i)\n\t\tplt.scatter(longitudes[i],latitudes[i], color=colors[wqc[i]],s=100, alpha=0.75)\n\tplt.legend(title=\"WQI\", loc=\"lower right\")\n\tplt.show()\n\t# scatter = ax.scatter(df_final[\"long\"], df_final[\"lat\"],c=labs,s=10)\n\t# print(*scatter.legend_elements()[0])\n\t# legend1 = ax.legend(*scatter.legend_elements(),\n # loc=\"lower left\", title=\"Classes\")\n\t# ax.add_artist(legend1)\n\n\n\t# canvas = FigureCanvasTkAgg(fig, master=tab4)\n\t# canvas.draw()\n\t# canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)\n\n\t# toolbar = NavigationToolbar2Tk(canvas, tab4)\n\t# toolbar.update()\n\t# canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)\n\ndef get_vis_q2(tab5, df):\n\t# tabControl.select(tab5)\n\n fig = plt.figure(figsize=(10,10))\n title = \"Plot based on water quality\"\n # plt.title(title)\n ind_img = mpimg.imread('./india-rivers-map.jpg')\n plt.imshow(ind_img,extent=[68.7, 96.25, 7.4, 37.6], alpha=0.75)\n latitudes = df['lats'].to_numpy()\n longitudes = df['longs'].to_numpy()\n station = df['STATION'].to_numpy()\n wqis = df['OIP'].to_numpy()\n wqc = df['WQC'].to_numpy()\n colors = {'Excellent':'blue','Acceptable':'c','Slightly polluted':'purple','Polluted':'violet','Heavily polluted':'red'}\n #colors = sb.heatmap(normalised)\n for i in range(len(wqis)):\n plt.scatter(longitudes[i],latitudes[i], color=colors[wqc[i]],s=100, alpha=0.75, label=station[i]+\":\"+str(wqc[i]))\n plt.legend(title=\"WQI\", loc=\"lower right\")\n plt.show()\n\ndef get_vis_q3(tab4, df):\n\t\n\t# print(df)\n\tfig = plt.figure(figsize=(10,10))\n\tdf_new = df[['Station', 'Sample Date', 'WQI']]\n\n\tdf_new['Sample Date'] = df_new['Sample Date'].str.split(\"-\", n = 1, expand = True)[0]\n\n\tfinal = df_new.groupby('Sample Date').max().reset_index()\n\n\t# print(final)\n\t# ax = final.plot.bar(x=\"Sample Date\", y=\"WQI\", rot=0, figsize = (15, 15))\n\tplt.bar(x=final[\"Sample Date\"],height=final[\"WQI\"])\n\tplt.show()\n\t\n\nhomepage.add_home(home)\nadd_tab1(tab1,tab4)\nadd_tab2(tab2,tab4)\nadd_tab3(tab3,tab4)\n# get_vis(tab4)\nroot.mainloop()","sub_path":"Assign2/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":13531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"321165897","text":"from django.conf.urls import url, include\n\nfrom jobs.views import ManagerIndex, ManagerDataView, ManagerCreateReport, populate, JobReport\n\nfrom .views import PickCenterView, EngineeringIndexView, EngineeringDetailView, EngineeringPickOperationView, EngineeringDataView, engineering_save_data, engineering_edit_data, engineering_add_field, engineering_delete_field, PickEngineeringProcessView, set_process_template, release_to_operator, go_to_detail_or_picker\n\n\napp_name = 'workcenters'\nurlpatterns = [\n url(r'^manager/(?P[0-9a-zA-Z-]+)/create_report/$', ManagerCreateReport.as_view(), name='create_report'),\n url(r'^manager/(?P[0-9a-zA-Z-]+)/populate/$', populate, name='populate_report'),\n url(r'^manager/(?P[0-9a-zA-Z-]+)/report/$', JobReport.as_view(), name='job_report'),\n url(r'^manager/(?P[0-9a-zA-Z-]+)/$', ManagerDataView.as_view(), name='manager_data_view'),\n url(r'^manager/$', ManagerIndex.as_view(), name='manager_index'),\n url(r'^engineering/(?P[0-9a-zA-Z-]+)/pick_operation/$', EngineeringPickOperationView.as_view(), name='engineering_pick_operation'),\n url(r'^engineering/(?P[0-9a-fA-F-]+)/data/$', EngineeringDataView.as_view(), name='engineering_data_view'),\n url(r'^engineering/(?P[0-9a-fA-F-]+)/save/$', engineering_save_data, name='engineering_save_data'),\n url(r'^engineering/(?P[0-9a-fA-F-]+)/decide/$', go_to_detail_or_picker, name='go_to_detail_or_picker'),\n url(r'^engineering/(?P[0-9a-fA-F-]+)/edit/$', engineering_edit_data, name='engineering_edit_data'),\n url(r'^engineering/(?P[0-9a-fA-F-]+)/add/$', engineering_add_field, name='engineering_add_field'),\n url(r'^engineering/(?P[0-9a-fA-F-]+)/delete/$', engineering_delete_field, name='engineering_delete_field'),\n url(r'^engineering/(?P[0-9a-fA-F-]+)/pick_process/$', PickEngineeringProcessView.as_view(), name='pick_process_template'),\n url(r'^engineering/(?P[0-9a-fA-F-]+)/set/(?P[0-9]+)/$', set_process_template, name='set_process_template'),\n url(r'^engineering/(?P[0-9a-fA-F-]+)/release_to_operator/$', release_to_operator, name='release_to_operator'),\n url(r'^engineering/(?P[0-9a-fA-F-]+)/$', EngineeringDetailView.as_view(), name='engineering_detail'),\n url(r'^engineering/$', EngineeringIndexView.as_view(), name='engineering_index'),\n url(r'^', PickCenterView.as_view(), name='pick_center'),\n]\n","sub_path":"frost/workcenters/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"392233207","text":"import torch\nimport db\nfrom torch import nn as nn\nfrom pytorch_transformers.modeling_bert import ( \n BertConfig, BertEncoder, BertPooler, BertLayerNorm)\n\nclass SelfAttn(nn.Module):\n def __init__(self, config):\n super(SelfAttn, self).__init__()\n self.config = config\n self.hsize=64\n self.atom_emb = nn.Embedding(5, 64)\n self.type_emb = nn.Embedding(15, 64)\n self.pos_emb = nn.Linear(3, 256, bias=False)\n self.dist_emb = nn.Linear(1, 64, bias=False) \n self.mu_emb = nn.Linear(1, 32, bias=False) # dipole_moment \n \n self.attn = BertEncoder(config)\n def get_reg_layer(output_size):\n return nn.Sequential(\n nn.Linear(config.hidden_size, config.hidden_size),\n nn.LayerNorm(config.hidden_size), \n nn.LeakyReLU(),\n nn.Dropout(config.hidden_dropout_prob),\n nn.Linear(config.hidden_size, config.hidden_size),\n nn.LayerNorm(config.hidden_size), \n nn.LeakyReLU(),\n nn.Dropout(config.hidden_dropout_prob),\n nn.Linear(config.hidden_size, output_size),\n )\n self.reg_layers4 = nn.ModuleList([get_reg_layer(4) for _ in range(9)])\n self.reg_layers1 = nn.ModuleList([get_reg_layer(1) for _ in range(9)])\n # not currently used.\n self.reg_aux = None\n \n #self.apply(self.init_weights)\n \n def init_weights(self, module):\n \"\"\" Initialize the weights.\n \"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n elif isinstance(module, BertLayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n def forward(self, atom0, atom1, typ, xyz0, xyz1, mu0, mu1, mask):\n atom0_emb = self.atom_emb(atom0)\n atom1_emb = self.atom_emb(atom1)\n type_emb = self.type_emb(typ)\n xyz0_emb = self.pos_emb(xyz0)\n xyz1_emb = self.pos_emb(xyz1)\n dist_emb = self.dist_emb((xyz0-xyz1).norm(dim=2, keepdim=True))\n mu0_emb = self.mu_emb(mu0)\n mu1_emb = self.mu_emb(mu1)\n \n \n atom_pairs = torch.cat([atom0_emb, atom1_emb, type_emb, \n xyz0_emb, xyz1_emb, dist_emb, mu0_emb, mu1_emb], 2)\n \n extended_attention_mask = mask.unsqueeze(1).unsqueeze(2)\n extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n head_mask = [None] * self.config.num_hidden_layers\n \n encoded_layers = self.attn(atom_pairs, extended_attention_mask, head_mask=head_mask)\n sequence_output = encoded_layers[-1]\n \n batch_size = typ.size(0)\n typ = typ.view(-1)\n sequence_output = sequence_output.view(-1, sequence_output.size(-1))\n \n org_indices = []\n type_output1 = []\n type_output4 = []\n for i in range(15):\n typ_bool = (typ == i)\n if typ_bool.sum() == 0: continue \n org_indices.append(typ_bool.nonzero().view(-1))\n \n if i > 8:\n i = 8 \n type_output4.append( self.reg_layers4[i](sequence_output[typ_bool] ) ) \n type_output1.append( self.reg_layers1[i](sequence_output[typ_bool] ) )\n org_indices = torch.cat(org_indices)\n _, rev_indices = org_indices.sort()\n type_output1 = torch.cat(type_output1)\n type_output4 = torch.cat(type_output4)\n type_output1 = type_output1[rev_indices]\n type_output4 = type_output4[rev_indices]\n \n #res_indices = torch.cuda.LongTensor(org_indices)[rev_indices]\n pred4 = type_output4.view(batch_size, -1, type_output4.size(-1))\n pred1 = type_output1.view(batch_size, -1, type_output1.size(-1))\n pred5 = torch.cat([pred1, pred4], -1)\n return pred1, pred5\n \n\n\n\n\n","sub_path":"solutions/3/code/BERT-based/transformer_v25_3/cust_model.py","file_name":"cust_model.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"11286669","text":"# ------------------- Librerias -------------------\nimport re\n\n\n# ------------------- Variables de comprobación --------------\nopcion_inv = str(\"\\n-------------------\"\n \"\\n| Opción inválida |\"\n \"\\n-------------------\\n\")\n\n\ndatos_inco = str(\"\\n------------------------------------\"\n \"\\n| Usted ha digitado datos erroneos |\"\n \"\\n------------------------------------\\n\")\n\n\n# -------------------- Clases ----------------------\nclass Persona:\n def __init__(self,Nombre, Apellido, Cedula, Correo,Edad):\n self.Nombre = Nombre\n self.Apellido = Apellido\n self.Cedula = Cedula\n self.Correo = Correo\n self.Edad = Edad\n\n\nclass Estudiante(Persona):\n def Matricular(self):\n print(\"matriculó\")\n\n def Pagar(self):\n print(\"pagó\",)\n\n\nclass Profesor(Persona):\n def Matricular(self):\n print(\"matriculó\")\n\n def Pagar(self):\n print(\"pagó,\")\n\n\nclass Materia:\n def __init__(self, Nombre, Precio, Grado):\n self.Nombre = Nombre\n self.Precio = Precio\n self.Grado = Grado\n\n\n# ------------------ Objetos ------------------------\nMatematicas = Materia(\"Matemáticas\",12000,\"Bachillerato\")\nCiencias = Materia(\"Ciencias\",12000,\"Bachillerato\")\nFisica = Materia(\"Física Cuántica\",12000,\"Licenciatura\")\nBiotec = Materia(\"Biotecnología\",12000,\"Licenciatura\")\n\nAstro = Materia(\"Astrofísica\",12000,\"Maestría\")\nTermod = Materia(\"Termodinámica\",12000,\"Maestría\")\n\nMateriaagre = Materia\n\nEstudiante1 = Estudiante\n\nProfe1 = Profesor\n\n\n# ------------------ Listas -------------------\nlista_materias = [Matematicas,Ciencias,Fisica,Biotec,Astro,Termod]\nmateria_matriculada = []\nmateria_matriculada_prof = []\npagar = []\npagar_prof = []\n\n\n# ------------------ Funciones --------------------------\ndef Matricular_Est():\n while True:\n try:\n nombre = input(\"Digite su nombre: \")\n apellido = input((\"Digite su apellido: \"))\n nombre.isalpha()\n apellido.isalpha()\n if nombre.isalpha() and apellido.isalpha() == True:\n edad = int(input(\"Digite su edad: \"))\n cedula = int(input(\"Digite su cédula: \"))\n correo = str(input(\"Digite su correo: \"))\n if re.match('^[(a-z0-9\\_\\-\\.)]+@[(a-z0-9\\_\\-\\.)]+\\.[(a-z)]{2,15}$', correo.lower()):\n Estudiante1.Nombre = nombre\n Estudiante1.Apellido = apellido\n Estudiante1.Cedula = cedula\n Estudiante1.Correo = correo\n Estudiante1.Edad = edad\n print(\n \"\\nElija laa materias que desea matricular...\\n1) Matemáticas\\n2) Ciencias\\n3) Fisica\\n4) Biotecnología\")\n print(\n \"\\n* NOTA *\\nComo estudiante regular solo tiene acceso a materias de Bachillerato o Licenciatura\")\n seleccion = int(input(\"\\nElije: \"))\n if seleccion == 1:\n print(\"Está seguro que desea matricular\",Matematicas.Nombre,\"por un pecio de ¢\",Matematicas.Precio,\n \"\\n1) Si.\\n2) No.\")\n eleccion = int(input(\"Elija: \"))\n if eleccion == 1:\n materia_matriculada.append(Matematicas)\n pagar.append(Matematicas.Precio)\n print(Estudiante1.Nombre, \"matriculó y pagó\", Matematicas.Nombre, \"por un valor de\",\n Matematicas.Precio)\n Est_Regular()\n elif eleccion == 2:\n print(\"Haz rechazado el trámite...\\nVolviendo al menú pricipal de Estudiante Regular\")\n input(\"Presiona 'enter' para continuar...\")\n Est_Regular()\n elif seleccion == 2:\n print(\"Está seguro que desea matricular\", Ciencias.Nombre, \"por un pecio de ¢\",Ciencias.Precio,\n \"\\n1) Si.\\n2) No.\")\n eleccion = int(input(\"Elija: \"))\n if eleccion == 1:\n materia_matriculada.append(Ciencias)\n pagar.append(Ciencias.Precio)\n print(Estudiante1.Nombre, \"matriculó y pagó\", Ciencias.Nombre, \"por un valor de ¢\",\n Ciencias.Precio)\n Est_Regular()\n elif eleccion == 2:\n print(\"Haz rechazado el trámite...\\nVolviendo al menú pricipal de Estudiante Regular\")\n input(\"Presiona 'enter' para continuar...\")\n Est_Regular()\n elif seleccion == 3:\n print(\"Está seguro que desea matricular\", Fisica.Nombre, \"por un pecio de ¢\",Fisica.Precio,\n \"\\n1) Si.\\n2) No.\")\n eleccion = int(input(\"Elija: \"))\n if eleccion == 1:\n materia_matriculada.append(Fisica)\n pagar.append(Fisica.Precio)\n print(Estudiante1.Nombre, \"matriculó y pagó\", Fisica.Nombre, \"por un valor de\",\n Fisica.Precio)\n Est_Regular()\n elif eleccion == 2:\n print(\"Haz rechazado el trámite...\\nVolviendo al menú pricipal de Estudiante Regular\")\n input(\"Presiona 'enter' para continuar...\")\n Est_Regular()\n elif seleccion == 4:\n print(\"Está seguro que desea matricular\", Biotec.Nombre, \"por un pecio de ¢\", Biotec.Precio,\n \"\\n1) Si.\\n2) No.\")\n eleccion = int(input(\"Elija: \"))\n if eleccion == 1:\n materia_matriculada.append(Biotec)\n pagar.append(Biotec.Precio)\n print(Estudiante1.Nombre, \"matriculó y pagó\", Biotec.Nombre, \"por un valor de\",\n Biotec.Precio)\n Est_Regular()\n elif eleccion == 2:\n print(\"Haz rechazado el trámite...\\nVolviendo al menú pricipal de Estudiante Regular\")\n input(\"Presiona 'enter' para continuar...\")\n Est_Regular()\n elif seleccion != 1 or 2 or 3 or 4:\n print(opcion_inv)\n else:\n print(\"\\n| El correo no es válido |\\n\")\n else:\n print(\"\\nNombre y Apellido no puede contener dígitos...\\n\")\n except:\n print(datos_inco)\n\n\ndef Matricular_Prof():\n while True:\n try:\n nombre = input(\"Digite su nombre: \")\n apellido = input(\"Digite su apellido: \")\n if nombre.isalpha() and apellido.isalpha() == True:\n edad = int(input(\"Digite su edad: \"))\n cedula = int(input(\"Digite su cédula: \"))\n correo = str(input(\"Digite su correo: \"))\n if re.match('^[(a-z0-9\\_\\-\\.)]+@[(a-z0-9\\_\\-\\.)]+\\.[(a-z)]{2,15}$', correo.lower()):\n Profe1.Nombre = nombre\n Profe1.Apellido = apellido\n Profe1.Cedula = cedula\n Profe1.Correo = correo\n Profe1.Edad = edad\n print(\"\\nElija laa materias que desea matricular...\\n1) AstroFísica\\n2) Termodinámica\")\n print(\"\\n* NOTA *\\nComo profesor o aspirante de maestría solo tiene acceso a materias de Maestría\")\n seleccion = int(input(\"\\nElije: \"))\n if seleccion == 1:\n print(\"Está seguro que desea matricular\", Astro.Nombre, \"por un pecio de ¢\", Astro.Precio,\n \"\\n1) Si.\\n2) No.\")\n eleccion = int(input(\"Elija: \"))\n if eleccion == 1:\n materia_matriculada_prof.append(Astro)\n pagar_prof.append(Fisica.Precio)\n print(Profe1.Nombre, \"matriculó y pagó\", Astro.Nombre, \"por un valor de\",\n Astro.Precio)\n Profe()\n elif eleccion == 2:\n print(\"Haz rechazado el trámite...\\nVolviendo al menú pricipal de Estudiante Regular\")\n input(\"Presiona 'enter' para continuar...\")\n Profe()\n elif seleccion == 2:\n print(\"Está seguro que desea matricular\", Termod.Nombre, \"por un pecio de ¢\", Termod.Precio,\n \"\\n1) Si.\\n2) No.\")\n eleccion = int(input(\"Elija: \"))\n if eleccion == 1:\n materia_matriculada_prof.append(Termod)\n pagar_prof.append(Fisica.Precio)\n print(Profe1.Nombre, \"matriculó y pagó\", Termod.Nombre, \"por un valor de\",\n Termod.Precio)\n Profe()\n elif eleccion == 2:\n print(\"Haz rechazado el trámite...\\nVolviendo al menú pricipal de Estudiante Regular\")\n input(\"Presiona 'enter' para continuar...\")\n Profe()\n elif seleccion != 1 or 2:\n print(opcion_inv)\n else:\n print(\"\\n--------------------------\"\n \"\\n| El correo no es válido |\"\n \"\\n--------------------------\\n\")\n else:\n print(\"\\nNombre y Apellido no puede contener dígitos...\\n\")\n except:\n print(datos_inco)\n\n\ndef Est_Regular():\n while True:\n try:\n print(\"\\nEstas son las opciones que tiene como Estudiante...\"\n \"\\n1) Ver lista de todas las materias.\"\n \"\\n2) Matricular (Bachillerato - Licenciatura)\"\n \"\\n3) Ver detalles de matrícula (Bachillerato - Licenciatura)\"\n \"\\n4) Menú Principal\"\n \"\\n\\n5) Resgistrar Materias\")\n Opc = int(input(\"\\nElija que desea hacer: \"))\n if Opc == 1:\n Ver_materias()\n elif Opc == 2:\n Matricular_Est()\n elif Opc == 3:\n print(Estudiante1.Nombre,Estudiante1.Apellido,\"cédula\",Estudiante1.Cedula,\"correo\",Estudiante1.Correo,\n \"edad\",Estudiante1.Edad,\",matriculó:\")\n for j in materia_matriculada:\n print(\"\\nMateria:\", j.Nombre, \"\\nValor:\", j.Precio, \"\\nGrado:\", j.Grado)\n print(\"\\nPor un valor total de ¢\",(12000*len(pagar)))\n elif Opc == 4:\n print(\"\\nVolviendo al Menú Inicial...\")\n input(\"Presiona 'Enter' para contiar...\")\n Menu()\n elif Opc == 5:\n nombreagre = str(input(\"\\nNombre de la materia a agregar: \"))\n valoragre = int(input(\"Valor de la materia por agregar: \"))\n gradoagre = str(input(\"Grado de la materia por agregar: \"))\n Materiaagre.Nombre = nombreagre\n Materiaagre.Precio = valoragre\n Materiaagre.Grado = gradoagre\n lista_materias.append(Materiaagre)\n print(\"Se añadió la matería...\")\n Est_Regular()\n elif Opc != 1 or 2 or 3 or 4 or 5:\n print(opcion_inv)\n except:\n print(datos_inco)\n\n\ndef Profe():\n while True:\n try:\n print(\"\\nEstas son las opciones que tiene como Profesor o Aspirante a Maestría...\"\n \"\\n1) Ver lista de todas las materias.\"\n \"\\n2) Matricular (Maestría)\"\n \"\\n3) Ver detalles de matícula (Maestría)\"\n \"\\n4) Menú Principal\"\n \"\\n\\n5) Registrar materia\")\n Opc = int(input(\"\\nElija que desea hacer: \"))\n if Opc == 1:\n Ver_materias()\n elif Opc == 2:\n Matricular_Prof()\n elif Opc == 3:\n print(Profe1.Nombre, Profe1.Apellido, \"cédula\", Profe1.Cedula, \"correo\",\n Profe1.Correo,\"edad\", Profe1.Edad,\",matriculó:\")\n for h in materia_matriculada_prof:\n print(\"\\nMateria:\", h.Nombre, \"\\nValor:\", h.Precio, \"\\nGrado:\", h.Grado)\n print(\"\\nPor un valor total de ¢\", (12000 * len(pagar_prof)))\n elif Opc == 4:\n print(\"\\nVolviendo al Menú Inicial...\")\n input(\"Presiona 'Enter' para contiar...\")\n Menu()\n elif Opc == 5:\n nombreagre = str(input(\"\\nNombre de la materia a agregar: \"))\n valoragre = int(input(\"Valor de la materia por agregar: \"))\n gradoagre = str(input(\"Grado de la materia por agregar: \"))\n Materiaagre.Nombre = nombreagre\n Materiaagre.Precio = valoragre\n Materiaagre.Grado = gradoagre\n lista_materias.append(Materiaagre)\n print(\"Se añadió la matería...\")\n Profe()\n elif Opc != 1 or 2 or 3 or 4 or 5:\n print(opcion_inv)\n except:\n print(datos_inco)\n\n\ndef Ver_materias():\n for i in lista_materias:\n print(\"------------------\", \"\\nMateria:\", i.Nombre, \"\\nValor:\",i.Precio,\"\\nGrado:\",i.Grado)\n\n\n# ------------------ Menus Principales -------------------\ndef Menu():\n while True:\n try:\n print(\"\\n ******************\"\n \"\\n * SISTEMA AVATAR *\"\n \"\\n ******************\"\n \"\\n\\n1) Profesor o Aspirante a Maestría.\\n2) Estudiante (Bachillerato - Licenciatura).\\n3) Salir\")\n opcion = int(input(\"\\nElija la opcion que le corresponde para matricula: \"))\n if opcion == 1:\n Profe()\n elif opcion == 2:\n Est_Regular()\n elif opcion == 3:\n print(\"\\nGracias por visitar la UTN!! <3\")\n break\n elif opcion != 1 or 2 or 3:\n print(opcion_inv)\n except:\n print(datos_inco)\n\nMenu()","sub_path":"Lab6/Programa de matrícula.py","file_name":"Programa de matrícula.py","file_ext":"py","file_size_in_byte":14748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"510785006","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom bson import ObjectId\nfrom base_app.classes.debug import Debug\nfrom base_app.models.mongodb.base_model import MongodbModel, BaseModel\n\n__author__ = 'Morteza'\n\n\nclass UserSearchPatternModel(BaseModel):\n def __init__(self, _id=None, name=None, user=None):\n BaseModel.__init__(self)\n self.id = _id\n self.name = name\n self.user = user\n self.result = {'value': {}, 'status': False}\n\n def insert(self, **body):\n try:\n __body = {\n \"name\": body['name'],\n \"user\": self.user,\n \"tags\": body['tags'],\n \"all_words\": body['all_words'],\n \"without_words\": body['without_words'],\n \"each_words\": body['each_words'],\n \"exactly_word\": body['exactly_word'],\n \"period\": body['period'],\n \"start\": body['start'],\n \"end\": body['end'],\n \"agency\": body['agency']\n }\n\n self.result['value'] = MongodbModel(collection='user_search_pattern', body=__body).insert()\n self.result['status'] = True\n\n return self.result\n except:\n Debug.get_exception(sub_system='admin', severity='error', tags='mongodb > save_search_pattern', data='collection > user_search_pattern')\n return self.result\n\n def get_all(self):\n try:\n __body = {\n \"user\": self.user,\n }\n\n r = MongodbModel(collection='user_search_pattern', body=__body).get_all()\n ls = []\n if r:\n for i in r:\n ls.append({\n \"name\": i['name'],\n \"tags\": i['tags'],\n \"all_words\": i['all_words'],\n \"without_words\": i['without_words'],\n \"each_words\": i['each_words'],\n \"exactly_word\": i['exactly_word'],\n \"period\": i['period'],\n \"start\": i['start'],\n \"end\": i['end'],\n \"agency\": i['agency']\n })\n self.result['value'] = ls\n self.result['status'] = True\n\n return self.result\n except:\n Debug.get_exception(sub_system='admin', severity='error', tags='mongodb > get_all', data='collection > user_search_pattern')\n return self.result","sub_path":"base_app/models/mongodb/user/user_search_pattern/user_search_pattern.py","file_name":"user_search_pattern.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"590029768","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 19 15:01:30 2019\n\n@author: LaurencT\n\"\"\"\n\nimport re\nimport pandas as pd\n\ndef lists_to_dict(list_keys, list_values):\n \"\"\"two ordered lists to a dict where list_keys are the keys and list_values \n are the values\n Inputs:\n list_keys - a list of n unique elements, where n = 0, 1 or many\n list_values - a list of n elements\n Returns:\n a dict of length n\n \"\"\"\n if len(list_keys) > len(set(list_keys)):\n raise ValueError('The list of keys is not unique')\n elif len(list_keys) != len(list_values):\n raise ValueError('The lists are not the same length')\n else:\n return {k:v for k,v in zip(list_keys, list_values)}\n\ndef deterministic_lists(analysis_type, param_user):\n \"\"\"Defines the different LTLI scenarios and which list of parameters should\n be used for each of them\n Inputs:\n analysis_type - the dictionary summarising what type of analysis is \n being undertaken, must contain the key 'run_deterministic'\n param_user - dict - keys: id_codes, values: series of parameters\n Returns:\n A dict - keys: scenario names, values - the list of parameters to\n be called for the corresponding scenario. Example:\n {'base': [burden_mean,\n ...,\n coverage_mean],\n '....': [...],\n 'burden_lower': [burden_lower,\n ...,\n coverage_mean]}\n \"\"\"\n # Create scenario names based on parameter names\n # This takes a random series from the dictionary's values to get the indexes\n # this is fine as all the values have the same indexes\n param_names = list(param_user.values())[0].index.tolist()\n scenario_names = [name for name in param_names if re.search('upper|lower', name)]\n \n # Exclude disease proportions because they vary with disease burden\n scenario_names = [name for name in scenario_names if not re.search('disease.*prop', name)]\n \n # Add in the base case and placeholders for burden scenarios\n scenario_names = ['base'] + scenario_names + ['burden_upper', 'burden_lower']\n \n # Create a list of parameter series indexes to select the right paramters \n # for each of the scenarios\n columns_to_select = [column for column in param_names \n if not re.search('lower|upper|SD', column)]\n\n # Create a dictionary keys: scenario names, values: lists of relevant column names\n dict_of_columns = {}\n for scenario in scenario_names:\n # Don't change anything in the base case\n if scenario == 'base':\n new_columns = columns_to_select.copy()\n # Burden scenarios influence strain proportion, will use GBD ranges - \n # not assumed ones so no adjustment factor for burden estimates yet\n elif re.search('burden', scenario):\n scenario_type = scenario[scenario.rindex('_')+1:]\n new_columns = [re.sub('mean', scenario_type, column) \n if re.search('disease.*prop', column) else column \n for column in columns_to_select]\n # All others replace the column index for mean with upper or lower\n else:\n scenario_focus = scenario[:scenario.rindex('_')] \n column_name_to_replace = scenario_focus + '_mean'\n new_columns = [scenario \n if column == column_name_to_replace \n else column \n for column in columns_to_select]\n dict_of_columns[scenario] = new_columns.copy()\n return dict_of_columns\n\ndef scenario_param(param_user, param_list, id_code):\n \"\"\"Subsets a series of parameters based on which are required for this \n scenario, and renames the parameters to standard names (not upper, lower\n or mean anymore)\n Inputs:\n param_list: a list of parameter indexes required for this scenario\n param_user - dict - keys: id_codes, values: series of parameters\n id_code: a string used to index to get data on the right project\n Returns:\n param: a series that has been indexed and renamed\n \"\"\"\n param = param_user[id_code]\n # Series to get the relevant parameters for the scenario\n param = param.reindex(param_list)\n # Get the names of those parameters and replace them with standard ones so \n # all the parameters have standard names (no upper, lower, mean)\n param_indexes = param.index.values.tolist()\n param_indexes_new = [re.sub('_mean|_lower|_upper', '', x) \n if re.search('mean|lower|upper', x) else x \n for x in param_indexes]\n # Generate mapping of old indexes to new indexes and use that to rename\n indexes_dict = lists_to_dict(param_indexes, param_indexes_new)\n param = param.rename(indexes_dict)\n # Return the relevant parameters with standardised names\n return param \n\ndef get_deterministic_params(analysis_type, param_user):\n \"\"\"Turns param_user dict into a set of parameters for each of the \n deterministic analyses\n Inputs:\n analysis_type - the dictionary summarising what type of analysis is \n being undertaken, must contain the keys 'run_deterministic' and\n 'num_trials'\n param_user - dict - keys: id_codes, values: series of parameters\n Returns:\n param_dict - a dict- keys: id_codes, values dfs of parameters for \n each of the deterministic scenarios\n \"\"\"\n id_codes = list(param_user.keys())\n # Generate a dictionary of which parameters are relevant for each scenario\n scenarios_dict = deterministic_lists(analysis_type, param_user)\n # Create a dictionary where id_codes are the keys, and the values are dfs\n # of the parameter values for each scenario\n param_dict = {}\n for code in id_codes:\n # Create a list to be filled with series, where each series is a set\n # of parameters for a scenario\n scenario_params = []\n for scenario in scenarios_dict.keys():\n param_list = scenarios_dict[scenario]\n param = scenario_param(param_user, param_list, code)\n param = param.rename(scenario)\n scenario_params.append(param)\n # Concatenate the series and transpose\n param_df = pd.concat(scenario_params, axis = 1, \n join_axes=[scenario_params[0].index])\n param_df = param_df.transpose()\n # populate the dictionary\n param_dict[code] = param_df\n return param_dict","sub_path":"generate_deterministic_params.py","file_name":"generate_deterministic_params.py","file_ext":"py","file_size_in_byte":6750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"331521070","text":"from __future__ import print_function\nimport os\nimport re\nimport sys\nimport shlex\nimport subprocess\nimport json\nimport threading\nimport functools\nimport base64\nfrom getpass import getpass\n\nfrom future.moves.urllib.request import urlopen, Request\n\nfrom invoke import run, task\nimport invoke.runners\nimport invoke.exceptions\n\ntry:\n from blessings import Terminal\nexcept:\n # Cannot do normal import as setup.py may not have been run yet.\n exec(open(os.path.join(\n os.path.dirname(__file__),\n 'tng/util/dummy_term.py')).read())\n\n\nterminal = Terminal()\n\nthis_directory = os.path.dirname(os.path.abspath(__file__))\n\ncoverage_options = (\n '-qq', '--cov=tng_sl', '--cov=test', '--junit-xml=results.xml',\n '--cov-report=html')\ncoverage_tool = 'py.test'\n\nif sys.platform.startswith('win'):\n pip = '{}\\\\Scripts\\\\pip.exe'.format(sys.exec_prefix)\n py_test = '{}\\\\Scripts\\\\py.test.exe'.format(sys.exec_prefix)\n if not os.path.exists(py_test):\n py_test = '{0}\\python.exe {0}\\\\Scripts\\\\pytest'.format(\n sys.exec_prefix)\nelse:\n # FIXME: on Fedora, pip is pip-python\n pip = 'pip'\n py_test = 'py.test'\n\ntest_runner = py_test\n\ntry: # py2 and py3 compatible terminal input\n input = raw_input\nexcept NameError:\n pass\n\n\ndef command(command):\n run(command, echo=True)\n\n\ndef command_output(command):\n result = run(command, echo=False, hide=True)\n return result.stdout\n\n\ndef return_capturer(func, dest):\n '''\n Returns a callable which runs func and captures the return value or\n exception in dest.\n '''\n @functools.wraps(func)\n def worker(*a, **k):\n dest[func] = func(*a, **k)\n return worker\n\n\ndef quit(code):\n ' Fail hard with a custom exit code '\n # There doesn't seem to be a sane way of failing a task?\n raise invoke.exceptions.Failure(\n invoke.runners.Result(\n command=None, stdout=None, stderr=None, exited=code, pty=None))\n\n\n@task\ndef install_hooks(ctx):\n '''creates .git/hooks/pre-commit that will run invoke test on every commit\n '''\n githooks = os.path.join(this_directory, '.git', 'hooks')\n pre_commit = os.path.join(githooks, 'pre-commit')\n if os.path.exists(pre_commit):\n return\n print(\"Installing git pre-commit hook\")\n if not os.path.exists(githooks):\n # honor umask\n os.system(\"mkdir -p '{}'\".format(githooks))\n with open(pre_commit, \"wb\") as fh:\n fh.write('#!/bin/bash -e\\ninvoke test\\n')\n os.chmod(pre_commit, 0o755)\n\n\n@task(install_hooks)\ndef cleanpyc(ctx):\n print(terminal.bold_yellow('Cleaning pyc files (and others)'))\n print('Number of .pyc files we found was: %s' % command_output(\n \"find . -iname '*.pyc' | wc -l\").rstrip())\n command(\"find . -iname '*.pyc' -delete\")\n command(\"find . -type d -name '__pycache__' -prune -exec rm -r '{}' \\;\")\n command(\"find . -type d -name 'tnglogs' -prune -exec rm -r '{}' \\;\")\n command(\"find . -type d -name '_trial_temp' -prune -exec rm -r '{}' \\;\")\n\n\n@task\ndef cleanboring(ctx):\n print(\"Number of ~ files we found was: %s\" % command_output(\n \"find . -iname '*~' | wc -l\"))\n command(\"find . -iname '*~' -delete\")\n\n\n@task\ndef install(ctx, extras=None, quiet=False):\n target = '.'\n pip_args = []\n if extras:\n target = '{}[{}]'.format(target, extras)\n if quiet:\n pip_args += ['--quiet']\n\n cmd = ' '.join([pip, 'install'] + pip_args + ['--editable', target])\n command(cmd)\n\n\n@task\ndef distclean(ctx):\n '''Intended to clean up artifacts from installing TNG as root'''\n blacklist = [\n 'docs',\n 'examples',\n 'build',\n 'TNG.egg-info',\n 'TODO',\n 'DEV_INSTALL']\n for item in blacklist:\n command('sudo rm -rf %s' % item)\n\n\n@task\ndef pdf(ctx):\n usage_folder = os.path.join(this_directory, 'docs', 'usage')\n command('cd %s; pdflatex usage.tex' % usage_folder)\n print(\"PDF Created: %s/usage.pdf\" % usage_folder)\n\n\n@task(cleanpyc)\ndef sphinx(ctx):\n sphinx_dir = os.path.join(this_directory, 'docs', 'sphinx')\n try:\n command('cd %s; make html' % sphinx_dir)\n except Exception:\n if ignore_sphinx_build_errors:\n print(terminal.bold_red('Ignoring Sphinx build error'))\n else:\n raise\n else:\n link = \"file://\" + os.path.join(\n sphinx_dir, '_build', 'html', 'index.html')\n print(\"Sphinx docs created: %s\" % link)\n\n\n@task\ndef cleansphinx(ctx):\n sphinx_dir = os.path.join(this_directory, 'docs', 'sphinx')\n command('cd %s; make clean' % sphinx_dir)\n\n\ndef _pep8():\n blacklist = ['.git', 'build', 'config', 'data']\n subdirs, files = next(os.walk(this_directory))[1:]\n things_to_pep8 = [\n x for x in subdirs if not (x.startswith('.') or x in blacklist)]\n things_to_pep8 += [\n x for x in files if (x.endswith('.py') and x not in blacklist)]\n things_to_pep8.sort()\n\n pep8 = subprocess.Popen(\n ['python', 'pep8_tng.py', '--config=pep8_config'] + things_to_pep8,\n cwd=this_directory,\n env=dict(os.environ),\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n stdout = pep8.stdout.read()\n code = pep8.wait()\n output = terminal.red(stdout.decode(sys.getdefaultencoding()))\n return code, output\n\n\n@task\ndef pep8(ctx):\n code, output = _pep8()\n if code:\n print(output)\n quit(code)\n\n\nif sys.version_info.major == 2:\n ignore_sphinx_build_errors = False\n tests = (\"test\", )\nelse:\n ignore_sphinx_build_errors = True\n all_test_files = set()\n for dirpath, dirnames, filenames in os.walk('test'):\n for filename in filenames:\n if filename.startswith('test') and filename.endswith('.py'):\n all_test_files.add(os.path.join(dirpath, filename))\n exclude_tests = {}\n tests = tuple(sorted(all_test_files - exclude_tests))\n\n\ndef _unittests(coverage=False, extra_opts=''):\n print(terminal.bold_yellow('Running tests'))\n env = dict(os.environ)\n cmd_line = (test_runner, ) + tests + tuple(shlex.split(extra_opts))\n if coverage:\n cmd_line += coverage_options\n p = subprocess.Popen(cmd_line, cwd=this_directory, env=env)\n code = p.wait()\n return code\n\n\n@task(cleanpyc)\ndef unittests(ctx, coverage=False, extra_opts=''):\n code = _unittests(coverage=coverage, extra_opts=extra_opts)\n if code:\n quit(code=code)\n\n\n@task(cleanpyc)\ndef test(ctx, coverage=False, extra_opts=''):\n results = {}\n unittests = threading.Thread(\n target=return_capturer(_unittests, results),\n kwargs={'coverage': coverage, 'extra_opts': extra_opts})\n pep8 = threading.Thread(target=return_capturer(_pep8, results))\n unittests.start()\n pep8.start()\n unittests.join()\n pep8.join()\n\n unittests_ec = results[_unittests]\n pep8_ec, pep8_output = results[_pep8]\n if pep8_ec:\n print(' PEP8 '.center(80, '-'))\n print(pep8_output)\n print('-' * 80)\n if any((unittests_ec, pep8_ec)):\n pass_ = terminal.green('Pass')\n fail_ = terminal.red('Fail')\n\n test_str = pass_ if not unittests_ec else fail_\n pep8_str = pass_ if not pep8_ec else fail_\n print(\"\\nTests: {}\\nPEP8: {}\".format(test_str, pep8_str))\n quit(code=1)\n\n\n@task\ndef tox_test(ctx):\n '''Run tests in tox environment which should also ensure setup.py works\n '''\n command('tox --recreate')\n\n\n@task\ndef coverage(ctx):\n command('rm -f .coverage')\n command('rm -rf htmlcov')\n command('rm -f coverage.xml')\n command(\"{0} {1} test\".format(coverage_tool, ' '.join(coverage_options)))\n\n\n@task\ndef publish(ctx, server_url='http://rusc01-pypi.rusclabs.cisco.com/'):\n command(\n 'python setup.py register -r \"{server_url}\" sdist upload '\n '-r \"{server_url}\"'.format(server_url=server_url))\n\n\n@task\ndef whatsnew(ctx):\n command(\"git fetch\")\n\n locallog = command_output(\n \"git log --abbrev-commit\"\n \" --format='%Cgreen* %C(yellow)%h %Cblue%aN %Cgreen%ar %Creset%s'\"\n \" FETCH_HEAD..\")\n remotelog = command_output(\n \"git log --abbrev-commit\"\n \" --format='%Cred* %C(yellow)%h %Cblue%aN %Cgreen%ar %Creset%s'\"\n \" ..FETCH_HEAD\")\n\n if locallog:\n print()\n print(\"YOUR CHANGES:\")\n print(\"-------------\")\n print(locallog)\n if remotelog:\n print()\n print(\"REMOTE CHANGES:\")\n print(\"---------------\")\n print(remotelog)\n if not (locallog or remotelog):\n print()\n print(\"No changes. You're up to date!\")\n\n\nBITBUCKET_API_PULL_URL = (\n 'https://bitbucket-eng-gpk1.cisco.com/bitbucket/rest/api/1.0/projects/'\n 'TNG/repos/tng/pull-requests/{num:d}/')\n\n\ndef get_pull_request_title(number, username, password):\n req = Request(BITBUCKET_API_PULL_URL.format(num=number))\n base64_auth_string = base64.encodestring(\n '{}:{}'.format(username, password).encode())[:-1]\n req.add_header('Authorization', b'Basic ' + base64_auth_string)\n response = urlopen(req)\n info = json.loads(response.read().decode())\n return info['title']\n\n\n@task\ndef make_tag_message(ctx):\n '''This helper expects the following merge commit message pattern:\n\n Merged branch 'merge_requests/1234'\n\n One-line title/summary from gitorious merge request\n\n Followed by a multiline text with the complete merge request description,\n which we ignore in this tool.\n '''\n output = []\n tag = command_output('git describe')\n prev_tag = '-'.join(tag.split('-')[:-2])\n merge_re = re.compile(\n r'Merge pull request #(?P\\d+).+from (?P[~\\w:_\\-/]+)')\n changes = command_output(\n 'git log --pretty=\"%s\" --merges {tag}..HEAD'.format(tag=prev_tag))\n changes = tuple(\n change.strip() for change in changes.splitlines() if change.strip())\n username = input('CEC Username: ')\n password = getpass('CEC Password: ')\n for change in changes:\n merge_request = merge_re.search(change)\n if merge_request:\n info = merge_request.groupdict()\n title = get_pull_request_title(\n int(info['number']), username, password)\n output.append('Pull request #{}: {}'.format(info['number'], title))\n else:\n print('Failed to parse this commit: %s' % change)\n with open('tag_commit.txt', 'w') as fp:\n fp.write('CHANGES\\n-------\\n\\n')\n fp.write('\\n'.join(output))\n print()\n print('ALL DONE: to actually create the tag run:')\n print()\n print(\n 'git tag -a -F tag_commit.txt '\n '&& git push ')\n","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":10625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"96858691","text":"from face_detector import DLIB\nimport tensorflow as tf\nfrom tensorflow.keras.models import load_model\nimport numpy as np\nimport imutils\nimport cv2\n\nclass CameraStreamDetection:\n def __init__(self):\n self.dlib = DLIB() # face detector\n self.classifier = load_model('models/cnn_batch32_adam_91.837.h5')\n self.cam = cv2.VideoCapture(0) # init camera\n self.OHE = {'AF': [1, 0, 0, 0, 0, 0, 0], 'AN': [0, 1, 0, 0, 0, 0, 0], 'DI': [0, 0, 1, 0, 0, 0, 0],\n 'HA': [0, 0, 0, 1, 0, 0, 0], 'NE': [0, 0, 0, 0, 1, 0, 0], 'SA': [0, 0, 0, 0, 0, 1, 0],\n 'SU': [0, 0, 0, 0, 0, 0, 1], } # classes one hot encoding\n self.OHE_c = {0: 'AFRAID', 1: 'ANGRY', 2: 'DISGUSTED', 3: 'HAPPY',\n 4: 'NEUTRAL', 5: 'SAD', 6: 'SURPRISED'}\n\n def __show_img(self, img):\n cv2.imshow('img', np.uint8(img))\n cv2.waitKey(1)\n\n def __show_faces(self, faces):\n for i in range(len(faces)):\n cv2.imshow('{}'.format(i), np.uint8(faces[i]))\n cv2.waitKey(1)\n\n def streamDLIB(self):\n eternity = True\n while eternity:\n ret, img = self.cam.read() # capture image\n img = imutils.resize(img, width=800) # resize image\n self.dlib.detect(img) # detect faces\n detected_faces = self.dlib.faces\n\n for face in detected_faces: # for each face use classifier\n face = np.expand_dims(face, axis=0)\n face = np.expand_dims(face, axis=3)\n face = tf.convert_to_tensor(face)\n prediction = np.asarray(self.classifier.predict(face))\n print(np.round(prediction,2), self.OHE_c[np.argmax(prediction)])\n self.__show_img(img) # print camera capture\n self.__show_faces(detected_faces) # print detected faces\n\n self.cam.release()\n cv2.destroyAllWindows()","sub_path":"camera_stream.py","file_name":"camera_stream.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"546447573","text":"#-*- coding:utf-8 -*-\n\n\"\"\"Development settings and globals.\"\"\"\n\nfrom os.path import join, normpath\n\nfrom common import *\n\n\n########## DEBUG CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug\nDEBUG = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug\nTEMPLATE_DEBUG = DEBUG\n########## END DEBUG CONFIGURATION\n\n########## EMAIL CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n########## END EMAIL CONFIGURATION\n\n\n########## DATABASE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': normpath(join(DJANGO_ROOT, 'default.db')),\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n }\n}\n########## END DATABASE CONFIGURATION\n\n########## LOGGING CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'console': {\n '()': 'colorlog.ColoredFormatter',\n 'format': '[%(log_color)s%(levelname)s%(reset)s] %(module)s.%(funcName)s:%(lineno)s: %(message)s',\n 'log_colors': {\n 'DEBUG': 'cyan',\n 'INFO': 'reset',\n 'WARNING': 'yellow',\n 'ERROR': 'red',\n 'CRITICAL': 'bold_red',\n },\n },\n },\n 'handlers': {\n 'console':{\n 'level':'DEBUG',\n 'class':'logging.StreamHandler',\n 'formatter': 'console',\n },\n },\n 'loggers': {\n 'apps': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n },\n }\n}\n########## END LOGGING CONFIGURATION\n\n########## CACHE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',\n }\n}\n########## END CACHE CONFIGURATION\n\n\n########## CELERY CONFIGURATION\n# See: http://docs.celeryq.org/en/latest/configuration.html#celery-always-eager\nCELERY_ALWAYS_EAGER = True\n\n# See: http://docs.celeryproject.org/en/latest/configuration.html#celery-eager-propagates-exceptions\nCELERY_EAGER_PROPAGATES_EXCEPTIONS = True\n########## END CELERY CONFIGURATION\n\n\n########## TOOLBAR CONFIGURATION\n# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation\nINSTALLED_APPS += (\n 'debug_toolbar',\n)\n\n# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation\nINTERNAL_IPS = ('127.0.0.1',)\n\n# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation\nMIDDLEWARE_CLASSES += (\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n)\n########## END TOOLBAR CONFIGURATION\n\n########## PASSWORD HASHERS\n# See: https://docs.djangoproject.com/en/1.4/topics/testing/#speeding-up-the-tests\nPASSWORD_HASHERS = (\n 'django.contrib.auth.hashers.MD5PasswordHasher',\n)\n########## END PASSWORD HASHERS\n\n","sub_path":"project_name/settings/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"423194145","text":"from bs4 import BeautifulSoup\nfrom dataclasses import dataclass\nfrom typing import List\nimport re\nimport requests\n\n# Adding \"real user\" header in requests should prevent Bing from spotting us, allegedly.\nheaders_get = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip, deflate',\n 'DNT': '1',\n 'Connection': 'keep-alive',\n 'Upgrade-Insecure-Requests': '1'\n}\n\n\n@dataclass\nclass SearchResult:\n title: str = 'Untitled'\n url: str = 'No URL'\n caption: str = 'No caption'\n category: str = 'other'\n\n def domain(self) -> str:\n pattern = r'(http.?://)?(.*?)(/.*|$)'\n match = re.search(pattern, self.url)\n return match.group(2) if match else ''\n\n\n def __str__(self):\n return '[{}][{}] {} || {} (@ {})\\n'.format(self.category.upper(), self.domain(), self.title, self.caption, self.url)\n\n\ndef bing_search(query: str) -> List[SearchResult]:\n \"\"\"\n Gets bing search results as a list of SearchResult list\n :param query: bing search query, accepts \"Google\" Dorks\n :return: list of bing search results\n \"\"\"\n session = requests.Session()\n url = 'http://www.bing.com/search?q={}&qs=n&form=QBRE&sp=-1'.format(query)\n response = session.get(url, headers=headers_get)\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n output: List[SearchResult] = []\n results = soup.find_all('li', {'class': 'b_algo'})\n for result in results:\n title = result.find('h2').text.lower()\n url = result.find('div', {'class': 'b_attribution'}).text.lower()\n caption = result.find('p').text.lower()\n output.append(SearchResult(title=title, url=url, caption=caption))\n session.close()\n return output\n\n","sub_path":"bing_search/bing_search.py","file_name":"bing_search.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"345612231","text":"#!/usr/bin/env bash\n\"\"\"\nReformat a JSON fixture file, making it easier to view in a text editor.\n\nThis is cosmetic only. It puts one JSON object on each line, and squeezes out\nsome of the extra spaces, but it doesn't/shouldn't change content.\n\nUsage:\n> python name-of-fixture-file > name-of-formatted-fixture-file\n\nCopyright (c) 2014, The Regents of the University of California, Department\nof Energy contract-operators of the Lawrence Berkeley National Laboratory.\nAll rights reserved.\n\n1. Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n (a) Redistributions of source code must retain the copyright notice, this\n list of conditions and the following disclaimer.\n\n (b) Redistributions in binary form must reproduce the copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n (c) Neither the name of the University of California, Lawrence Berkeley\n National Laboratory, U.S. Dept. of Energy nor the names of its contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\n2. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n3. You are under no obligation whatsoever to provide any bug fixes, patches,\n or upgrades to the features, functionality or performance of the source code\n (\"Enhancements\") to anyone; however, if you choose to make your Enhancements\n available either publicly, or directly to Lawrence Berkeley National\n Laboratory, without imposing a separate written license agreement for such\n Enhancements, then you hereby grant the following license: a non-exclusive,\n royalty-free perpetual license to install, use, modify, prepare derivative\n works, incorporate into other computer software, distribute, and sublicense\n such enhancements or derivative works thereof, in binary and source code\n form.\n\nNOTE: This license corresponds to the \"revised BSD\" or \"3-clause BSD\" license\nand includes the following modification: Paragraph 3. has been added.\n\"\"\"\n\n\nimport json\nimport sys\n\n\n#--- Read the fixture file into a Python data structure.\n#\n# This maps:\n# - JSON array to Python list\n# - JSON object to Python dict\n# - JSON string to Python str\n# - JSON true to Python True\n# - etc.\nwith open(sys.argv[1]) as fixtureFile:\n fixtureDat = json.load(fixtureFile)\n\n# The fixture should be a JSON array of objects (so a Python list of dictionaries).\nassert( type(fixtureDat) == list )\n\n\n#--- Write the JSON back out.\n\n# Start the JSON array.\nsys.stdout.write('[\\n')\n\n# Write every Python dictionary as a JSON object, one per line.\nendPrevLine = False\nfor item in fixtureDat:\n assert( type(item) == dict )\n\n jsonStr = json.dumps(item, separators=(', ', ':'))\n assert( jsonStr[0] == '{' )\n\n # Put \"model\" keyword first, if it occurs as a keyword in {item}.\n # Note \"model\" may appear as a keyword in a sub-dictionary of {item},\n # so it's dangerous to just pull it out using a grep search of {jsonStr}.\n if 'model' in item:\n modelType = item['model']\n modelStr = ', \"model\":\"' + modelType + '\"'\n leftIdx = jsonStr.find(modelStr)\n if( leftIdx>1 and jsonStr.rfind(modelStr)==leftIdx ):\n # Here, <<, \"model\":\"{modelType}\">> appears exactly once in {jsonStr}.\n # Move the \"model\":\"{modelType}\" part to beginning of {jsonStr}.\n parts = jsonStr[1:].split(modelStr)\n jsonStr = ''.join([\n '{\"model\":\"',\n modelType,\n '\", ',\n ''.join(parts)\n ])\n\n # Write the JSON object.\n if( endPrevLine ):\n sys.stdout.write(',\\n')\n else:\n endPrevLine = True\n sys.stdout.write(jsonStr)\n\n# End the JSON array.\nsys.stdout.write('\\n]')\n","sub_path":"openeis/applications/utest_applications/format-fixture-file.py","file_name":"format-fixture-file.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"523880082","text":"from eth_utils import keccak\n\nfrom config.constant import EventConstant, EventInputConstant\n\n\ndef get_topic_filter(event_abi):\n input_string = event_abi.get(\"name\") + \"(\"\n for input in event_abi.get(\"inputs\"):\n input_string += input.get(\"type\") + \",\"\n input_string = input_string[:-1] + \")\"\n hash = keccak(text=input_string)\n return '0x' + hash.hex()\n\n\ndef get_list_params_in_order(event_abi):\n indexed = []\n non_indexed = []\n for input in event_abi.get(EventConstant.inputs):\n if input.get(EventInputConstant.indexed):\n indexed.append(input)\n else:\n non_indexed.append(input)\n return indexed + non_indexed\n\n\ndef get_all_address_name_field(event_abi):\n address_name_field = []\n for input in event_abi.get(EventConstant.inputs):\n if input.get(EventInputConstant.type) == EventInputConstant.address:\n address_name_field.append(input.get(EventInputConstant.name))\n return address_name_field\n\n\nclass EventSubscriber:\n def __init__(self, topic_hash, name, list_params_in_order):\n self.topic_hash = topic_hash\n self.name = name\n self.list_params_in_order = list_params_in_order\n\n\nclass EthEvent(object):\n def __init__(self):\n self.contract_address = None\n self.transaction_hash = None\n self.log_index = None\n self.block_number = None\n self.params = {}\n self.event_type = None\n","sub_path":"ethereumetl/service/eth_event_service.py","file_name":"eth_event_service.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"316507074","text":"import tensorflow as tf\n\nx = tf.constant([0.9, 0.85], shape=[1, 2])\n\n# 使用随机正态分布函数声明w1和w2两个变量,其中w1是2x3的矩阵,w2是3x1的矩阵\n# 这里使用了随机种子参数seed,这样可以保证每次运行得到的结果是一样的\nw1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1), name=\"w1\")\nw2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1), name=\"w2\")\n\n# 将biase(偏置项)参数b1设置为初始值全为0的1x3矩阵,b2是初始值全为1的1x1矩阵\nb1 = tf.Variable(tf.zeros([1, 3]))\nb2 = tf.Variable(tf.ones([1]))\n\ninit_op = tf.global_variables_initializer()\n\na = tf.matmul(x, w1) + b1\ny = tf.matmul(a, w2) + b2\nwith tf.Session() as sess:\n sess.run(init_op)\n print(sess.run(y))\n # 输出[[5.4224963]]","sub_path":"tensorflow/TensorFlow-book-code/第4章/4-2.py","file_name":"4-2.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"482261068","text":"import init\ninit.main()\nimport time\nimport save_load\nimport ingame_menu\nimport new_game\nimport sys\nimport os\nimport pickle\nfrom pathlib import Path\n\n\ndef main():\n print('Welcome to ProjectCALC')\n print('Version: Alpha 1')\n answer = input('What would you like to do? (1.New Game, 2.Load Game or 3.Exit) ')\n if answer == '1':\n my_file = Path(\"savefile.pkl\")\n if my_file.is_file():\n deleteSave = input('You already have a safefile. Are you sure you want to delete it and make a new one? (1.Yes or 2.No) ')\n if deleteSave == '1':\n os.remove(\"savefile.pkl\")\n os.remove(\"inventory.pkl\")\n os.remove('temp.pkl')\n os.remove('enemies.pkl')\n print(\"Savefile deleted!\")\n time.sleep(2)\n new_game.main()\n temp = open('temp.pkl', 'wb')\n init_list = ['fn', 'ln', 'gen', 'age', 'inv', 'mag', 'wea', '1', '0', '1', '0', '0', '0', '0','20']\n pickle.dump(init_list, temp)\n temp.close()\n temp = pickle.load(open('temp.pkl', 'rb'))\n new_temp = temp\n temp = open('temp.pkl', 'wb')\n del new_temp[7]\n del new_temp[7]\n del new_temp[7]\n del new_temp[7]\n level = '1'\n old_level = '0'\n magic_level = '1'\n xp = '0'\n new_temp.insert(7, level)\n new_temp.insert(8, old_level)\n new_temp.insert(9, magic_level)\n new_temp.insert(10, xp)\n print(new_temp)\n pickle.dump(new_temp, temp)\n temp.close()\n save_load.save()\n ingame_menu.main()\n elif deleteSave == '2':\n print(\"Savefile not deleted.\")\n main()\n else:\n new_game.main()\n temp = open('temp.pkl', 'wb')\n init_list = ['fn', 'ln', 'gen', 'age', 'inv', 'mag', 'wea', '1', '0', '1', '0', '0', '0', '0','20']\n pickle.dump(init_list, temp)\n temp.close()\n temp = pickle.load(open('temp.pkl','rb'))\n new_temp = temp\n temp = open('temp.pkl','wb')\n del new_temp[7]\n del new_temp[7]\n del new_temp[7]\n del new_temp[7]\n level = '1'\n old_level = '0'\n magic_level = '1'\n xp = '0'\n new_temp.insert(7, level)\n new_temp.insert(8, old_level)\n new_temp.insert(9, magic_level)\n new_temp.insert(10, xp)\n print(new_temp)\n pickle.dump(new_temp, temp)\n temp.close()\n save_load.save()\n ingame_menu.main()\n\n elif answer == '2':\n try:\n save_load.load()\n ingame_menu.main()\n print('')\n print('')\n print('')\n except FileNotFoundError:\n print('You do not have a savefile. Please create a new game.')\n print('')\n print('')\n print('')\n main()\n elif answer == '3':\n sys.exit()\n while answer not in ['1','2','3']:\n print('Please enter a valid answer')\n answer = input('What would you like to do? (1.New Game, 2.Load Game or 3.Exit) ')\nmain()\n","sub_path":"Alpha 1/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"462599652","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn import metrics as mt\n\n\ndef print_classification_details(actual, predicted, verbose=False):\n # print the accuracy and confusion matrix\n cm = mt.confusion_matrix(actual, predicted)\n cr = mt.classification_report(actual, predicted)\n\n print(\"confusion matrix\\n\", cm)\n print(cr)\n\n if (verbose is True):\n plot_classification_report(cr)\n\n\ndef plot_classification_report(cr, title=None, cmap='RdBu'):\n \"\"\"\n Adapted from\n https://medium.com/district-data-labs/visual-diagnostics-for-more-informed-machine-learning-7ec92960c96b\n \"\"\"\n title = title or 'Classification report'\n lines = cr.split('\\n')\n classes = []\n matrix = []\n\n for line in lines[2:(len(lines)-5)]:\n s = line.split()\n classes.append(s[0])\n value = [float(x) for x in s[1: len(s) - 1]]\n matrix.append(value)\n\n fig, ax = plt.subplots(1)\n\n for column in range(len(matrix)+1):\n for row in range(len(classes)):\n txt = matrix[row][column]\n # ax.text(column,row,matrix[row][column],va='center',ha='center')\n ax.text(column, row, txt, va='center', ha='center',\n size=\"x-large\", bbox=dict(facecolor='white', alpha=0.5))\n\n fig = plt.imshow(matrix, interpolation='nearest',\n cmap=cmap, vmin=0, vmax=1)\n plt.title(title)\n plt.colorbar()\n x_tick_marks = np.arange(len(classes)+1)\n y_tick_marks = np.arange(len(classes))\n plt.xticks(x_tick_marks, ['Precision', 'Recall', 'F1-score'], rotation=45)\n plt.yticks(y_tick_marks, classes)\n plt.ylabel('Classes')\n plt.xlabel('Measures')\n plt.show()\n","sub_path":"more/scikit_helper/plot_classification.py","file_name":"plot_classification.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"560513418","text":"\"\"\"Parsing the file\"\"\"\n\nimport json\nimport yaml\nfrom pathlib import Path\n\n\ndef get_dict_from_file(path_file):\n \"\"\"Parse the file and return dict\"\"\"\n file_extension = Path(path_file).suffix\n return open_file(path_file, file_extension)\n\n\ndef open_file(path_file, file_extension):\n if file_extension.lower() == '.json':\n with open(path_file) as f:\n return json.load(f)\n elif file_extension.lower() == '.yml' or file_extension.lower() == '.yaml':\n with open(path_file) as f:\n return yaml.safe_load(f)\n","sub_path":"gendiff/tools/parse_file.py","file_name":"parse_file.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"513870554","text":"from math import cos\nfrom math import sqrt\nfrom math import pi\nfrom .image_analysis import get_cam_to_object_distance\nfrom .image_analysis import get_angle\n\nCONST_CAM_ANGLE = pi/2 #Our camera is supposedly 90 degrees or pi/2, but I'm not sure about this. \n#CONST_CAM_ANGLE: angle of the horizontal field of view of the camera in RADIANS\nCONST_AVG_FACE_BREADTH = 0.20 #Average is roughly 15cm or 0.15m (https://en.wikipedia.org/wiki/Human_head#Average_head_sizes), but the rectangles around detected faces are usually too big, so I will increase it a bit to account for this\n#CONST_AVG_FACE_BREADTH: the average face width/breadth of adult humans in METERS\n\n#Point class is not really necessary\nclass Point():\n x = 0\n y = 0\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def print_point(self):\n print(str(self.x) + \", \" + str(self.y))\n\n\n#get_distance returns the HORIZONTAL distance between the center of two faces (rectangles) in an image using ratios and the law of cosines.\n\n#parameters\n#(x1,y1): top left corner of face 1's \"rectangle\", (x2,y2): bottom right corner of face 1 \n#(x3,y3): is top left corner of face 2, (x4,y4): bottom right corner of face 2\n#imagePixelWidth: width of the image in pixels\n\ndef get_distance(x1, y1, x2, y2, x3, y3, x4, y4, imagePixelWidth): \n face1Center = Point((x1+x2)/2, (y1+y2)/2)\n # print(\"f1:\")\n # face1Center.print_point()\n face2Center = Point((x3+x4)/2, (y3+y4)/2)\n # print(\"f2:\")\n # face2Center.print_point()\n face1Dist = get_cam_to_object_distance(CONST_AVG_FACE_BREADTH, get_angle(x1, x2, imagePixelWidth, CONST_CAM_ANGLE))\n face2Dist = get_cam_to_object_distance(CONST_AVG_FACE_BREADTH, get_angle(x3, x4, imagePixelWidth, CONST_CAM_ANGLE))\n theta = get_angle(face1Center.x, face2Center.x, imagePixelWidth, CONST_CAM_ANGLE)\n # print(\"theta: \" + str(theta))\n \n #rest is trig (law of cosines)\n distanceSquared = face1Dist*face1Dist + face2Dist*face2Dist - 2*face1Dist*face2Dist*cos(theta)\n # print(\"cos(theta): \" + str(cost(theta)))\n # print(\"distance squared: \" + str(distanceSquared))\n return sqrt(distanceSquared)\n\nif __name__ == \"__main__\":\n test = get_distance(0,0,50,0,50,0,100,0,100)\n print(test)\n\n\n","sub_path":"Social_Distancing_Detection/image_handling/distance_calculations/distance_calculation.py","file_name":"distance_calculation.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"77724068","text":"import json\nfrom django.db.models import Q\nfrom django.views import View\nfrom django.http import HttpResponse, JsonResponse\nfrom django.db import IntegrityError\n\nfrom account.views import login_required\nfrom company.models import Company\nfrom job.models import (\n MainCategory, \n SubCategory, \n Job,\n Like,\n Bookmark,\n Apply\n)\n\nfrom account.models import Account\n\n\nclass CategoryView(View):\n def get(self, request):\n main_categories = MainCategory.objects.all().order_by('id')\n\n data = [{\n 'id' : main_category.id,\n 'name' : main_category.name,\n 'background_image' : main_category.image_url,\n 'sub_category' : [{\n 'id' : sub_category.id,\n 'name' : sub_category.name,\n 'background_image' : sub_category.image_url\n } for sub_category in main_category.subcategory_set.all()]\n\n } for main_category in main_categories]\n\n return JsonResponse({'data' : data}, status=200)\n\n\nclass CategoryTabView(View):\n def get(self, request, main_category_id):\n \n try:\n main_category = MainCategory.objects.get(id = main_category_id)\n\n data = [{\n 'id' : main_category.id,\n 'name' : main_category.name,\n 'sub_category' : [{\n 'id' : sub_category.id,\n 'name' : sub_category.name,\n 'background_image' : sub_category.image_url\n } for sub_category in main_category.subcategory_set.all()]\n }]\n\n return JsonResponse({'data' : data}, status=200)\n\n except MainCategory.DoesNotExist:\n return JsonResponse({'message' : \"INVALID_MAIN_CATEGORY\"}, status=400)\n\n\nclass JobListView(View):\n def get(self, request):\n jobs = Job.objects.all().order_by('id')\n \n offset = int(request.GET.get('offset', 0)) # 맨 처음 20개만 보이도록 pagination 처리 / 쿼리스트링 offset 필요 \n limit = offset + 20\n\n data = [{\n 'id' : job.id,\n 'name' : job.name,\n 'company' : job.company.name,\n 'region' : job.company.region.name,\n 'country' : job.company.country.name,\n 'reward_amount' : job.reward_amount,\n 'thumbnail' : job.company.thumbnail_url,\n 'likes' : job.like_set.filter(is_like = True).count()\n } for job in jobs]\n\n return JsonResponse({'data' : data[offset:limit]}, status=200)\n\n\nclass JobListCategoryView(View):\n def get(self, request, sub_category_id):\n if SubCategory.objects.filter(id = sub_category_id).exists():\n jobs = Job.objects.filter(sub_category_id = sub_category_id)\n\n data = [{\n 'id' : job.id,\n 'name' : job.name,\n 'company' : job.company.name,\n 'region' : job.company.region.name,\n 'country' : job.company.country.name,\n 'reward_amount' : job.reward_amount,\n 'thumbnail' : job.company.thumbnail_url,\n 'likes' : job.like_set.filter(is_like = True).count()\n } for job in jobs]\n\n return JsonResponse({'data' : data}, status=200)\n \n return JsonResponse({'message' : \"INVALID_SUBCATEGORY\"}, status=400)\n\n\nclass JobDetailView(View):\n def get(self, request, job_id):\n \n try:\n job = Job.objects.get(id = job_id)\n reward_amount = job.reward_amount / 2\n\n data = [{\n 'id' : job.id,\n 'sub_category_id' : job.sub_category.id,\n 'name' : job.name,\n 'company_id' : job.company.id,\n 'company' : job.company.name,\n 'region' : job.company.region.name,\n 'country' : job.company.country.name,\n 'referer_amount' : reward_amount,\n 'fereree_amount' : reward_amount,\n 'likes' : job.like_set.filter(is_like = True).count(),\n 'article' : job.article,\n 'deadline' : job.deadline,\n 'location' : job.company.location,\n 'lat' : job.company.latitude,\n 'lng' : job.company.longitude,\n 'logo_url' : job.company.logo_url,\n 'images' : [{\n 'name' : photo.name,\n 'url' : photo.url\n } for photo in job.company.photo_set.all()]\n }]\n\n return JsonResponse({'data' : data}, status=200)\n except Job.DoesNotExist:\n return JsonResponse({'message' : \"INVALID_JOB\"}, status=400)\n\n\nclass LikeView(View):\n \n @login_required\n def post(self, request):\n try:\n account_id = request.user.id\n job_id = request.GET.get('job_id', None)\n\n if Like.objects.filter(Q(account_id = account_id)&Q(job_id = job_id)).exists():\n like = Like.objects.get(Q(account_id = account_id)&Q(job_id = job_id))\n \n like.is_like = False if like.is_like else True \n like.save()\n \n else:\n Like.objects.create(\n account_id = account_id,\n job_id = job_id,\n is_like = True\n )\n\n return HttpResponse(status = 200)\n except IntegrityError:\n return JsonResponse({'message':'Invalid Account or Job'}, status=400)\n except KeyError:\n return HttpResponse(status = 400)\n \n @login_required\n def get(self, request):\n try:\n account_id = request.user.id\n job_id = request.GET.get('job_id', None)\n\n if Like.objects.filter(Q(account_id = account_id)&Q(job_id = job_id)).exists():\n like = Like.objects.get(Q(account_id = account_id)&Q(job_id = job_id))\n return JsonResponse({'is_like' : like.is_like}, status = 200)\n \n return JsonResponse({'message' : \"Invalid Like\"}, status = 400)\n\n except KeyError:\n return HttpResponse(status = 400)\n\n\nclass BookmarkView(View):\n @login_required\n def post(self, request): \n try:\n account_id = request.user.id\n job_id = request.GET.get('job_id', None)\n\n if Bookmark.objects.filter(Q(account_id = account_id)&Q(job_id = job_id)).exists():\n bookmark = Bookmark.objects.get(Q(account_id = account_id)&Q(job_id = job_id))\n \n bookmark.is_bookmark = False if bookmark.is_bookmark else True \n bookmark.save()\n \n else:\n Bookmark.objects.create(\n account_id = account_id,\n job_id = job_id,\n is_bookmark = True\n )\n\n return HttpResponse(status = 200)\n except IntegrityError:\n return JsonResponse({'message':'Invalid Account or Job'}, status=400)\n except KeyError:\n return HttpResponse(status = 400)\n \n @login_required\n def get(self, request):\n try:\n account_id = request.user.id\n #account_id = request.GET.get('account_id', None)\n job_id = request.GET.get('job_id', None)\n\n if Bookmark.objects.filter(Q(account_id = account_id)&Q(job_id = job_id)).exists():\n bookmark = Bookmark.objects.get(Q(account_id = account_id)&Q(job_id = job_id))\n return JsonResponse({'is_bookmark' : bookmark.is_bookmark}, status = 200)\n \n return JsonResponse({'message' : \"Invalid Bookmark\"}, status = 400)\n\n except KeyError:\n return HttpResponse(status = 400)\n\nclass ApplyView(View):\n @login_required\n def get(self, request): \n try:\n account_id = request.user.id\n account = Account.objects.get(id = account_id)\n\n data = {\n 'name' : account.username,\n 'email' : account.email,\n 'phone' : account.phone,\n 'resume' : [{\n 'id' : resume.id,\n 'title' : resume.title,\n 'updated_at' : resume.updated_at\n } for resume in account.resume_set.all()]\n }\n return JsonResponse({'data' : data}, status=200)\n \n except KeyError:\n return HttpResponse(status = 400)\n \n @login_required\n def post(self, request): \n try:\n account_id = request.user.id\n job_id = request.GET.get('job_id', None)\n resume_id = request.GET.get('resume_id', None)\n\n Apply.objects.create(\n account_id = account_id,\n job_id = job_id,\n resume_id = resume_id,\n is_apply = True\n )\n\n return HttpResponse(status = 200)\n except KeyError:\n return HttpResponse(status = 400)","sub_path":"job/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"634356160","text":"import asyncio\nimport random\nimport time\n\nimport idom\nfrom idom.widgets.html import Input\n\n\nvictory = idom.install(\"victory\", fallback=\"loading...\")\n\n\n@idom.component\ndef RandomWalk():\n mu = idom.hooks.use_ref(0)\n sigma = idom.hooks.use_ref(1)\n\n return idom.html.div(\n RandomWalkGraph(mu, sigma),\n idom.html.style(\n \"\"\"\n .number-input-container {margin-bottom: 20px}\n .number-input-container input {width: 48%;float: left}\n .number-input-container input + input {margin-left: 4%}\n \"\"\"\n ),\n NumberInput(\n \"Mean\",\n mu.current,\n mu.set_current,\n (-1, 1, 0.01),\n ),\n NumberInput(\n \"Standard Deviation\",\n sigma.current,\n sigma.set_current,\n (0, 1, 0.01),\n ),\n )\n\n\n@idom.component\ndef RandomWalkGraph(mu, sigma):\n interval = use_interval(0.5)\n data, set_data = idom.hooks.use_state([{\"x\": 0, \"y\": 0}] * 50)\n\n @idom.hooks.use_effect\n async def animate():\n await interval\n last_data_point = data[-1]\n next_data_point = {\n \"x\": last_data_point[\"x\"] + 1,\n \"y\": last_data_point[\"y\"] + random.gauss(mu.current, sigma.current),\n }\n set_data(data[1:] + [next_data_point])\n\n return victory.VictoryLine(\n {\n \"data\": data,\n \"style\": {\n \"parent\": {\"width\": \"500px\"},\n \"data\": {\"stroke\": \"royalblue\"},\n },\n }\n )\n\n\n@idom.component\ndef NumberInput(label, value, set_value_callback, domain):\n minimum, maximum, step = domain\n attrs = {\"min\": minimum, \"max\": maximum, \"step\": step}\n\n value, set_value = idom.hooks.use_state(value)\n\n def update_value(value):\n set_value(value)\n set_value_callback(value)\n\n return idom.html.fieldset(\n {\"class\": \"number-input-container\"},\n [idom.html.legend({\"style\": {\"font-size\": \"medium\"}}, label)],\n Input(update_value, \"number\", value, attributes=attrs, cast=float),\n Input(update_value, \"range\", value, attributes=attrs, cast=float),\n )\n\n\ndef use_interval(rate):\n usage_time = idom.hooks.use_ref(time.time())\n\n async def interval() -> None:\n await asyncio.sleep(rate - (time.time() - usage_time.current))\n usage_time.current = time.time()\n\n return asyncio.ensure_future(interval())\n\n\nidom.run(RandomWalk)\n","sub_path":"docs/source/examples/simple_dashboard.py","file_name":"simple_dashboard.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"196524668","text":"\"\"\"\n셀러리 Task chain\n\nTask 여러개를 연결하는 방법의 예시.\nadd의 결과가 multiply 1번쨰 인자로 들어감\n\"\"\"\n\n\nimport celery\n\napp = celery.Celery('05_celery-chain',\n broker='redis://localhost',\n backend='redis://localhost'\n)\n\n@app.task\ndef add(x, y):\n return x+y\n\n@app.task\ndef multiply(x, y):\n print('first-args', x)\n return x*y\n\nif __name__ == \"__main__\":\n chain = celery.chain(add.s(4, 7), multiply.s(10))\n print(\"Chain %s\" % chain)\n result = chain()\n print(\"Task state: %s\" % result.state)\n print(\"Result: %s\" % result.get())\n print(\"Task state: %s\" % result.state)\n","sub_path":"daily-programming/2019/11/ch-05-distribution-using-queue/05_celery-chain.py","file_name":"05_celery-chain.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"372032198","text":"import math\n\nwith open('input.txt') as file:\n joltage = [int(x) for x in file.read().splitlines()]\n\njoltage.append(0)\njoltage.append(max(joltage) + 3)\njoltage.sort()\n\nprint(joltage)\n\n\ndef find_variants(joltages: list) -> int:\n result = 1\n i = 0\n while i < len(joltages) - 1:\n block_size = 1\n while joltage[i + 1] - joltage[i] == 1:\n block_size += 1\n i += 1\n if block_size in (3, 4):\n result *= math.pow(2, block_size-2)\n if block_size == 5:\n result *= 7\n i += 1\n return int(result)\n\n\nanswer = find_variants(joltage)\nprint(answer)\n","sub_path":"day10/day10-2-linear.py","file_name":"day10-2-linear.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"183342566","text":"import time\n\nlocalTime = time.localtime(time.time())\n\nyear = localTime.tm_year\nmonth = localTime.tm_mon\nday = localTime.tm_mday\nhour = localTime.tm_hour\nminute = localTime.tm_min\nsecond = localTime.tm_sec\n\n\n\"\"\"The date / time string has to be escaped so that it can be put into a URL.\nSo, for instance,\n\n 2001-01-01 10:32:35\n\n becomes\n\n 2000-01-01+10%3A32%3A35\n\n See http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol\n\n\"\"\"\ndateTimeString = \"%d-%02d-%02d+%02d%s%02d%s%02d\" % (year, month, day, hour,\n \"%3A\", minute, \"%3A\", second)\n\nprint(\"The date-time string is\", dateTimeString)\n","sub_path":"sandbox/time experiments.py","file_name":"time experiments.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"337727692","text":"\nclass Tape:\n\n def __init__(self,\n tape_string = \"\",\n blank_symbol =\" \"):\n self.tape = dict((enumerate(tape_string)))\n self.blank_symbol = blank_symbol\n\n def __str__(self):\n return ''.join(self.tape.values())\n\n def __getitem__(self,index):\n if index in self.tape:\n return self.tape[index]\n else:\n return self.blank_symbol\n\n def __setitem__(self, pos, char):\n self.tape[pos] = char\n\n\nclass TuringMachine:\n\n def __init__(self,\n tape = \"\",\n blank_symbol = \" \",\n initial_state = \"\",\n final_states = None,\n transition_function = None):\n self.tape = Tape(tape_string=tape, blank_symbol=blank_symbol)\n self.head_position = 0\n self.current_state = initial_state\n self.transition_function = transition_function or {}\n self.final_states = set(final_states) or set()\n\n def get_tape(self):\n return str(self.tape)\n\n def step(self):\n char_under_head = self.tape[self.head_position]\n x = (self.current_state, char_under_head)\n if x in self.transition_function:\n y = self.transition_function[x]\n self.tape[self.head_position] = y[1]\n if y[2] == \"R\":\n self.head_position += 1\n elif y[2] == \"L\":\n self.head_position -= 1\n self.current_state = y[0]\n\n def final(self):\n if self.current_state in self.final_states:\n return True\n else:\n return False\n\n def run(self):\n while not self.final():\n self.step()\n\n\nif __name__ == \"__main__\":\n tape = \"||| \"\n initial_state = \"init\"\n accepting_states = [\"final\"]\n transition_function = {\n (\"init\", \"|\"):(\"init\", \"|\", \"R\"),\n (\"init\", \" \"):(\"pre-final\", \" \", \"L\"),\n (\"pre-final\", \"|\"):(\"final\", \" \", \"R\")\n }\n final_states = {\"final\"}\n\n t = TuringMachine(\n tape=tape,\n initial_state=initial_state,\n final_states=final_states,\n transition_function=transition_function\n )\n\n print(\"Input on Tape:\")\n print(t.get_tape())\n\n t.run()\n\n print(\"Result:\")\n print(t.get_tape())\n","sub_path":"LR-4/turing_machine.py","file_name":"turing_machine.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"478073712","text":"\"\"\"This function replaces missing spots.\n\nGiven a spot that disappears for some frames, this function takes its coordinate\njust before and just after disappearing and interpolates its position(s) in the\nmissing frame(s). Than takes the value of the green raw data in these points,\ninterpolating the supposed volume too, and replaces the missing information in\nthis way.\n\"\"\"\n\n\nimport numpy as np\nfrom skimage.morphology import label\nfrom skimage.measure import regionprops\n# import pyqtgraph as pg\n\nimport SpotsBuilder\n\n\nclass InterpolatMissingSpots:\n def __init__(self, green4D, spots_tracked_3D, spots_3D, ref_point, numb_zrs):\n \n steps = spots_tracked_3D.shape[0] \n prof_int = (spots_3D.spots_ints * (spots_tracked_3D == ref_point)).sum(2).sum(1) # intensity time series of the spot\n prof_int2 = (spots_3D.spots_ints * (spots_tracked_3D == ref_point)).sum(2).sum(1) # intensity time series of the spot\n prof_bin = np.sign((spots_tracked_3D == ref_point).sum(2).sum(1)) # binary time series of the spots presence (1 it is there, 0 it is not)\n prof_lbls = label(1 - prof_bin) # labels of the zeros; time series ending with ..., 1, 0, 0 give problems, so we check that the last label is not at the end of the trace. the '-1' compensate for the fact that the first index is 0 \n\n if np.where(prof_lbls == prof_lbls.max())[0][-1] == steps - 1: \n prof_lbls *= (1 - (prof_lbls == prof_lbls.max()))\n\n\n frms2work = []\n\n for l in range(1, prof_lbls.max() + 1):\n if np.sum(prof_lbls == l) <= numb_zrs: # select zeros segments smaller than a threshold (numb_zrs)\n frms2work.append(np.where(prof_lbls == l)) # time coordinates of these points\n\n for k in range(len(frms2work)): # segment by segment\n bfr_tzxy = np.zeros((4), dtype=np.int)\n aft_tzxy = np.zeros((4), dtype=np.int)\n bfr_tzxy[0] = (frms2work[k][0].min() - 1).astype(np.int) # time before disappearing\n aft_tzxy[0] = (frms2work[k][0].max() + 1).astype(np.int) # time after disappearing (when it just reappear)\n\n bfr_rgp = regionprops((spots_tracked_3D[bfr_tzxy[0], :, :] == ref_point).astype(np.int))\n aft_rgp = regionprops((spots_tracked_3D[aft_tzxy[0], :, :] == ref_point).astype(np.int))\n\n bfr_tzxy[2:] = np.round(bfr_rgp[0]['centroid']) # txy coordinate of the spot before disappearing\n aft_tzxy[2:] = np.round(aft_rgp[0]['centroid']) # txy coordinate of the spot after disappearing\n\n bfr_loc = np.argmin(((spots_3D.spots_tzxy[:, np.array([0, 2, 3])] - bfr_tzxy[np.array([0, 2, 3])])**2).sum(1)) # locate in tzxy coordinate matrix\n aft_loc = np.argmin(((spots_3D.spots_tzxy[:, np.array([0, 2, 3])] - aft_tzxy[np.array([0, 2, 3])])**2).sum(1)) # for some reason there is not perfect matching between the xy-coordinate of center of mass detected in 3D and the xy-coordinates of the same object projected in xy\n\n bfr_tzxy[1] = spots_3D.spots_tzxy[bfr_loc, 1] # z coordinate\n aft_tzxy[1] = spots_3D.spots_tzxy[aft_loc, 1] # z coordinate\n\n z_new = np.round(np.linspace(bfr_tzxy[1], aft_tzxy[1], 2 + frms2work[k][0].size)).astype(np.int) # interpolation over the z, x, y positions the built spot will have\n z_new = z_new[1:-1] # interpolations are linear\n\n x_new = np.round(np.linspace(bfr_tzxy[2], aft_tzxy[2], 2 + frms2work[k][0].size)).astype(np.int)\n x_new = x_new[1:-1]\n\n y_new = np.round(np.linspace(bfr_tzxy[3], aft_tzxy[3], 2 + frms2work[k][0].size)).astype(np.int)\n y_new = y_new[1:-1]\n\n bfr_vol = (spots_3D.spots_vol[bfr_tzxy[0], :, :] * (spots_tracked_3D[bfr_tzxy[0], :, :] == ref_point)).sum()\n aft_vol = (spots_3D.spots_vol[aft_tzxy[0], :, :] * (spots_tracked_3D[aft_tzxy[0], :, :] == ref_point)).sum()\n vol_new = np.round(np.linspace(bfr_vol, aft_vol, 2 + frms2work[k][0].size)).astype(np.int) # volume interpolation\n vol_new = vol_new[1:-1]\n\n sp_rel_coord = SpotsBuilder.SpotsBuilder(vol_new).sp_rel_coord # generation of the coordinates of picels of the built spot\n\n for i in range(len(sp_rel_coord)):\n # ant[frms2work[k][0][i], z_new[i], x_new[i], y_new[i]] = 2\n prof_int[frms2work[k][0][i]] += green4D[frms2work[k][0][i], z_new[i], x_new[i], y_new[i]].sum() # the time series of the spot is filled in the missing steps with the values of the raw data in the pixels of the built pixels\n for j in range(sp_rel_coord[i].shape[0]):\n zz = z_new[i] + sp_rel_coord[i][j, 0]\n xx = x_new[i] + sp_rel_coord[i][j, 1]\n yy = y_new[i] + sp_rel_coord[i][j, 2]\n # print(xx, zz, yy, frms2work[0][0][i], i)\n # ant[frms2work[k][0][i], zz, xx, yy] = 2\n try: # built spots can go out of the matrix (very rare). In this case we juts skip the pixel that goes out\n prof_int[frms2work[k][0][i]] += green4D[frms2work[k][0][i], zz, xx, yy].sum()\n spots_tracked_3D[frms2work[k][0][i], xx, yy] = ref_point\n except IndexError:\n pass\n\n self.corrected_trace = prof_int \n self.original_trace = prof_int2\n self.spots_tracked_3D = spots_tracked_3D\n\n \n # w = pg.plot(prof_int2, symbol='o')\n # w.plot(prof_int, symbol='x', pen='r')\n # pg.plot(prof_int, symbol='x', pen='r')\n","sub_path":"autocorrelation/spot-analysis/InterpolatMissingSpots.py","file_name":"InterpolatMissingSpots.py","file_ext":"py","file_size_in_byte":7380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"476652116","text":"# coding=utf-8\nfrom __future__ import unicode_literals\n\ndefault_env = [\"LANG=en_US.UTF-8\", \"LANGUAGE=en_US:en\", \"LC_ALL=en_US.UTF-8\"]\n\n\nc_lang_config = {\n \"compile\": {\n \"suffix\": \".c\",\n \"compile_command\": \"/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}\",\n },\n \"run\": {\n \"command\": \"{exe_path}\",\n \"seccomp_rule\": \"c_cpp\",\n \"env\": default_env\n }\n}\n\ncpp_lang_config = {\n \"compile\": {\n \"suffix\": \".cpp\",\n \"compile_command\": \"/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++11 {src_path} -lm -o {exe_path}\",\n },\n \"run\": {\n \"command\": \"{exe_path}\",\n \"seccomp_rule\": \"c_cpp\",\n \"env\": default_env\n }\n}\n\n","sub_path":"app/languages.py","file_name":"languages.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"421239878","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/2/7 15:55\n# @Author : Yajun Yin\n# @Note : modified based on Programming Collective Intelligence pp. 142\nfrom collections import defaultdict\nfrom PIL import Image, ImageDraw\n\nimport sys\n\nmy_data = [['slashdot', 'USA', 'yes', 18, 'None'],\n ['google', 'France', 'yes', 23, 'Premium'],\n ['digg', 'USA', 'yes', 24, 'Basic'],\n ['kiwitobes', 'France', 'yes', 23, 'Basic'],\n ['google', 'UK', 'no', 21, 'Premium'],\n ['(direct)', 'New Zealand', 'no', 12, 'None'],\n ['(direct)', 'UK', 'no', 21, 'Basic'],\n ['google', 'USA', 'no', 24, 'Premium'],\n ['slashdot', 'France', 'yes', 19, 'None'],\n ['digg', 'USA', 'no', 18, 'None'],\n ['google', 'UK', 'no', 18, 'None'],\n ['kiwitobes', 'UK', 'no', 19, 'None'],\n ['digg', 'New Zealand', 'yes', 12, 'Basic'],\n ['slashdot', 'UK', 'no', 21, 'None'],\n ['google', 'UK', 'yes', 18, 'Basic'],\n ['kiwitobes', 'France', 'yes', 19, 'Basic']]\n\n\nclass DecisionNode(object):\n def __init__(self, col=-1, value=None, results=None, tb=None, fb=None):\n \"\"\"\n Each node in a tree.\n :param col:待检验的判断条件所对应的列索引值\n :param value:判断条件的阈值\n :param results:针对当前分支的结果,它是一个字典,除了叶子节点以外,在其他节点上该值都为None\n :param tb:tb也是decisionnode,对应于结果为true时,树上相对于当前节点的子树上的节点\n :param fb:fb也是decisionnode,对 应于结果为false时,树上相对于当前节点的子树上的节点\n \"\"\"\n self.col = col\n self.value = value\n self.results = results\n self.tb = tb\n self.fb = fb\n\n\ndef divide_set(rows, column, value):\n \"\"\"\n 对某一个column上的数据拆分,既能够处理数值型数据,也能够处理离散型数据。\n :param rows:所有的数据行\n :param column:数据的某一列\n :param value:判断条件的阈值\n :return:返回split_function判断为真和假的两个集合\n \"\"\"\n # split_function = None\n if isinstance(value, int) or isinstance(value, float):\n split_function = lambda row: row[column] >= value\n else:\n split_function = lambda row: row[column] == value\n set1 = [row for row in rows if split_function(row)]\n set2 = [row for row in rows if not split_function(row)]\n return set1, set2\n\n\n# >>> d = treepredict.DecisionNode()\n# >>> d\n# \n# >>> d.divide_set(treepredict.my_data,2,'yes')\n# ([['slashdot', 'USA', 'yes', 18, 'None'], ['google', 'France', 'yes', 23, 'Premium'], ['digg', 'USA', 'yes'\n# , 24, 'Basic'], ['kiwitobes', 'France', 'yes', 23, 'Basic'], ['slashdot', 'France', 'yes', 19, 'None'], ['d\n# igg', 'New Zealand', 'yes', 12, 'Basic'], ['google', 'UK', 'yes', 18, 'Basic'], ['kiwitobes', 'France', 'ye\n# s', 19, 'Basic']], [['google', 'UK', 'no', 21, 'Premium'], ['(direct)', 'New Zealand', 'no', 12, 'None'], [\n# '(direct)', 'UK', 'no', 21, 'Basic'], ['google', 'USA', 'no', 24, 'Premium'], ['digg', 'USA', 'no', 18, 'No\n# ne'], ['google', 'UK', 'no', 18, 'None'], ['kiwitobes', 'UK', 'no', 19, 'None'], ['slashdot', 'UK', 'no', 2\n# 1, 'None']])\n# 随便的拆分方法并不理想,观察两个set的最终订阅情况,两边都混杂了各种情况,并不能说明问题。\ndef unique_counts(rows):\n \"\"\"\n 每行的最后一列就是最终的订阅情况,将集合内各种订阅情况计数到字典中\n :param rows:\n :return:\n \"\"\"\n results = defaultdict(int)\n for row in rows:\n r = row[len(row) - 1]\n results[r] += 1\n return results\n\n\ndef gini_impurity1(rows):\n total = len(rows)\n counts = unique_counts(rows)\n imp = 0\n for k1 in counts:\n p1 = float(counts[k1]) / total\n for k2 in counts:\n if k1 == k2:\n continue\n p2 = float(counts[k2]) / total\n imp += p1 * p2\n return imp\n\n\ndef gini_impurity2(rows):\n total = len(rows)\n counts = unique_counts(rows)\n tmp = 0\n for k in counts:\n p = float(counts[k]) / total\n tmp += p * p\n imp = 1 - tmp\n return imp\n\n\ndef gini_impurity3(rows):\n total = len(rows)\n counts = unique_counts(rows)\n imp = 0\n for k in counts:\n p = float(counts[k]) / total\n imp += p * (1 - p)\n return imp\n\n\ndef entropy(rows):\n from math import log\n log2 = lambda x: log(x) / log(2)\n results = unique_counts(rows)\n ent = 0.0\n for r in results:\n p = float(results[r]) / len(rows)\n ent += (-p * log2(p))\n return ent\n\n\n# gini和entropy的区别:归一化后的entropy是gini的上界,说明熵的“惩罚”更大一点;entropy的变化相对于gini稍微缓慢一点。\n# 为了衡量一个特征的好坏:好的特征能够使信息增益大\n# 信息增益:原数据集上的熵E1,分区后的平均熵E2,Gain=E1-E2;意思是使数据集的混乱程度降低最多,意味着分区后的数据集更一致。\n\ndef build_tree(rows, split='entropy'):\n if len(rows) == 0:\n return DecisionNode()\n split_func = {'entropy': entropy, 'gini': gini_impurity2, 'var': variance}\n try:\n current_score = split_func.get(split)(rows)\n except TypeError:\n print(\"Input correct split type: 'entropy' or 'gini' or 'var', default:'entropy'\")\n # sys.exit(1)\n\n # set up some variables to record best split scores\n best_gain = 0.0\n best_criteria = None\n best_sets = None\n\n column_count = len(rows[0]) - 1\n for col in range(column_count):\n column_values = set()\n for row in rows:\n column_values.add(row[col])\n for value in column_values:\n set1, set2 = divide_set(rows, col, value)\n\n # calculate the entropy of set1 and set2 and their average entropy\n # the ratio of set1\n p = len(set1) / len(rows)\n gain = current_score - p * split_func.get(split)(set1) - (1 - p) * split_func.get(split)(set2)\n # 节点不能为空:这点很重要;因为节点为空,相当于不用划分,这样best_gain还是0\n if gain > best_gain and len(set1) > 0 and len(set2) > 0:\n best_gain = gain\n best_criteria = (col, value)\n best_sets = (set1, set2)\n\n # create sub-tree\n # best_gain=0有两种情况:1.gain=0 2.不用划分了,就是整个set的result都一样,best_gain=0就是递归的退出条件\n if best_gain > 0:\n trueBranch = build_tree(best_sets[0])\n falseBranch = build_tree(best_sets[1])\n return DecisionNode(col=best_criteria[0], value=best_criteria[1], tb=trueBranch, fb=falseBranch)\n else:\n return DecisionNode(results=unique_counts(rows))\n\n\ndef print_tree(tree, indent=' '):\n # 前序遍历\n # it is a leaf\n if tree.results is not None:\n print('Leaf***', dict(tree.results))\n else:\n # print judge col and value\n print('feature' + str(tree.col) + ':' + str(tree.value) + '?')\n\n # print branch\n print(indent + 'T:-->', end=\"\")\n print_tree(tree.tb, indent + ' ')\n print(indent + 'F:-->', end=\"\")\n print_tree(tree.fb, indent + ' ')\n\n\ndef get_width(tree):\n if tree.results is not None:\n return 1\n else:\n return get_width(tree.tb) + get_width(tree.fb)\n\n\ndef get_depth(tree):\n if tree.results is not None:\n return 0\n else:\n return max(get_depth(tree.tb), get_depth(tree.fb)) + 1\n\n\ndef draw_tree(tree, filename=\"decision_tree.jpeg\"):\n \"\"\"\n 合理的尺寸画布,将画布和根节点传递给draw_node\n :param tree:\n :param filename:\n :return:\n \"\"\"\n w = get_width(tree) * 100\n h = get_depth(tree) * 100 + 120\n\n img = Image.new('RGB', (w, h), (255, 255, 255))\n draw = ImageDraw.Draw(img)\n\n draw_node(draw, tree, w / 2, 20)\n img.save(filename, 'JPEG')\n\n\ndef draw_node(draw, tree, x, y):\n \"\"\"\n 实际绘制决策树的节点,递归工作\n :param draw:\n :param tree:\n :param x:\n :param y:\n :return:\n \"\"\"\n if tree.results is None:\n w1 = get_width(tree.tb) * 100\n w2 = get_width(tree.fb) * 100\n\n left = x - (w1 + w2) / 2\n right = x + (w1 + w2) / 2\n\n draw.text((x - 20, y - 10), ('feature' + str(tree.col) + ':' + str(tree.value)), fill=(0, 0, 0))\n # print('feature' + str(tree.col) + ':' + str(tree.value))\n\n # 分支的连线\n draw.line((x, y, left + w1 / 2, y + 100), fill=(255, 0, 0))\n draw.line((x, y, right - w2 / 2, y + 100), fill=(255, 0, 0))\n\n draw_node(draw, tree.tb, left + w1 / 2, y + 100)\n draw_node(draw, tree.fb, right - w2 / 2, y + 100)\n else:\n txt = u' \\n'.join(['%s: %d' % v for v in tree.results.items()])\n # print(txt)\n draw.text((x - 20, y), txt, fill=(0, 0, 0))\n\n\ndef predict(observation, tree):\n # 每个observation有条确定路径,相当于链表\n if tree.results is not None:\n print(dict(tree.results))\n # 这种方法求dict中最大value的key太麻烦\n # return list(tree.results.keys())[list(tree.results.values()).index(max(tree.results.values()))]\n return max(tree.results.items(), key=lambda x: x[1])[0]\n else:\n v = observation[tree.col]\n # 判断这个特征是数值型还是离散型\n if isinstance(v, int) or isinstance(v, float):\n if v >= tree.value:\n branch = tree.tb\n else:\n branch = tree.fb\n else:\n if v == tree.value:\n branch = tree.tb\n else:\n branch = tree.fb\n return predict(observation, branch)\n\n\n# 剪枝:目前的完全生成树只有当无法降低熵,就是best_gain==0时,才会停止创建分支。\n# 一种策略是,设置一个熵减少的阈值,就是信息增益的阈值,当小于这个阈值的时候,就不再分支。\n# 另一种策略是,先构建好整个完全生成树,然后再尝试消除多余节点,即剪枝。合并具有相同父节点的一组节点,合并后的熵增加\n# 是否小于指定阈值。\ndef prune(tree, min_gain):\n \"\"\"\n 剪枝,当信息增益小于min_gain时,不再分支\n :param tree:\n :param min_gain: 最小阈值\n :return:\n \"\"\"\n # 后序遍历\n # 判断左右分支是不是叶子节点\n # 左分支不是叶子节点,右分支不是叶子节点.\n # 这里的逻辑是(左存在 and 左不是叶子)or(右存在 and 右不是叶子)\n if tree.tb.results is None:\n prune(tree.tb, min_gain)\n elif tree.fb.results is None:\n prune(tree.fb, min_gain)\n # 左右都是叶子,看看是否需要合并叶子\n if tree.tb.results is not None and tree.fb.results is not None:\n tb, fb = [], []\n for v, c in tree.tb.results.items():\n tb += [[v]] * c\n for v, c in tree.fb.results.items():\n fb += [[v]] * c\n total = len(tb + fb)\n p = float(len(tb)) / total\n delta_gain = entropy(tb + fb) - p * entropy(tb) - (1 - p) * entropy(fb)\n if delta_gain < min_gain:\n tree.tb, tree.fb = None, None\n tree.results = unique_counts(tb + fb)\n\n\n# 处理缺失值\n# 缺失了某些数据,这些数据是确定分支走向所必需的,可以选择两个分支都走,加权平均。\n# 如果有特征缺失,则每个分支对应的结果都会计算一遍,最终结果乘以对应的权重\ndef md_predict(observation, tree):\n if tree.results is not None:\n # print('leaf',dict(tree.results))\n return dict(tree.results)\n else:\n v = observation[tree.col]\n # 如果v的值缺失\n if v is None:\n # print(tree.col, tree.value)\n tr, fr = md_predict(observation, tree.tb), md_predict(observation, tree.fb)\n # print('tr', tr)\n # print('fr', fr)\n tcount = sum(tr.values())\n fcount = sum(fr.values())\n tw = float(tcount) / (tcount + fcount)\n fw = float(fcount) / (tcount + fcount)\n result = {}\n for k, v in tr.items():\n result[k] = v * tw\n for k, v in fr.items():\n if k not in result:\n result[k] = 0\n result[k] += v * fw\n # print(result)\n return result\n else:\n if isinstance(v, int) or isinstance(v, float):\n if v >= tree.value:\n branch = tree.tb\n else:\n branch = tree.fb\n else:\n if v == tree.value:\n branch = tree.tb\n else:\n branch = tree.fb\n return md_predict(observation, branch)\n\n\ndef variance(rows):\n \"\"\"\n 高的方差说明结果分散,低的方差说明结果比较接近。对于回归,使用方差作为分裂判断的依据。\n :param rows:\n :return:\n \"\"\"\n if len(rows) == 0:\n return 0\n # data中的最后一列就是结果\n data = [float(row[len(row) - 1]) for row in rows]\n mean = sum(data) / len(data)\n var = sum([(d - mean) ** 2 for d in data]) / len(data)\n return var\n","sub_path":"Programming-Collective-Intelligence/chapter 7/treepredict.py","file_name":"treepredict.py","file_ext":"py","file_size_in_byte":13412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"540016023","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright 2016\n# Author: zhujianwei@ict.ac.cn (Jianwei Zhu)\n\nimport argparse\nimport os\nimport sys\nimport warnings\n\n# check biopython module\ntry:\n from Bio.PDB import PDBParser\nexcept ImportError:\n raise SystemExit('Install biopython module if you want to use %s' % sys.argv[0])\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description=\"Transform original PDB file to distance or contact matrix.\", usage='%(prog)s <-i input_pdb_file> [options]', add_help=False)\n\n input_args = parser.add_argument_group('Input arguments')\n input_args.add_argument('-i', '--input', metavar='', type=open, help='input original pdb file, e.g., 1col.pdb')\n\n output_args = parser.add_argument_group('Output arguments')\n output_args.add_argument('-o', '--output', metavar='', help='output matrix to a file, e.g., 1colA.cm')\n output_args.add_argument('-D', '--dist', action='store_true', help='output distance matrix, [default=False]')\n\n other_args = parser.add_argument_group('Other arguments')\n other_args.add_argument('-h', '--help', action='help', help='show this help message and exit')\n other_args.add_argument('--version', action='version', version='%(prog)s 1.0')\n\n return parser.parse_args()\n\ndef main(pdbfile, outfile, is_distance=False):\n # parse pdbfile\n p = PDBParser(PERMISSIVE=1)\n structure = p.get_structure('name', pdbfile)\n chain=structure[0].get_list()[0]\n\n dist = []\n for res1 in chain:\n c1 = res1['CB'] if 'CB' in res1 else res1['CA']\n tmp_dist = []\n for res2 in chain:\n c2 = res2['CB'] if 'CB' in res2 else res2['CA']\n tmp_dist.append(c1 - c2)\n dist.append(tmp_dist)\n \n fout = open(outfile, 'w') if outfile else sys.stdout\n if is_distance:\n for row in dist:\n for c in row:\n print('%6.3f' % c, end=' ', file=fout)\n print(file=fout)\n else:\n for row in dist:\n for c in row:\n c = 1 if c < 8 else 0\n print(c, end=' ', file=fout)\n print(file=fout)\n outfile and fout.close()\n\n\n\nif __name__ == '__main__':\n args = parse_arguments()\n print('Parsing Parameters...')\n # check input file\n if not args.input:\n sys.argv.append('-h')\n parse_arguments()\n pdbfile = args.input.name\n outfile = args.output if args.output else None\n is_distance = args.dist\n print('Parameters OK.')\n\n main(pdbfile, outfile, is_distance)\n","sub_path":"scripts/contact_map.py","file_name":"contact_map.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"165665217","text":"#!/usr/bin/python\n#\n#https://chromium.googlesource.com/chromiumos/platform/factory/+/stabilize-4701.B/py/system/bluetooth.py\n#\n# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\nimport argparse\nimport dbus\nimport factory_common # pylint: disable=W0611\nimport gobject\nimport logging\nimport os\nimport re\nimport threading\nimport uuid\nimport yaml\nfrom cros.factory.test.utils import Retry\nfrom cros.factory.utils.net_utils import PollForCondition\nfrom dbus.mainloop.glib import DBusGMainLoop\nfrom dbus import service # pylint: disable=W0611\nfrom dbus import DBusException\nBUS_NAME = 'org.bluez'\nSERVICE_NAME = 'org.bluez'\nADAPTER_INTERFACE = SERVICE_NAME + '.Adapter1'\nDEVICE_INTERFACE = SERVICE_NAME + '.Device1'\n_RE_NODE_NAME = re.compile(r'')\nclass BluetoothManagerException(Exception):\n pass\n#TODO(cychiang) Add unittest for this class.\nclass BluetoothManager(object):\n \"\"\"The class to handle bluetooth adapter and device through dbus interface.\n Properties:\n _main_loop: The object representing the main event loop of a PyGTK\n application. The main loop should be running when calling function with\n callback through dbus interface.\n _manager: The proxy for the org.freedesktoop.DBus.ObjectManager interface\n on ojbect path / on bus org.bluez.\n Raises:\n Raises BluetoothManagerException if org.bluez.Manager object is not\n available through dbus interface.\n \"\"\"\n def __init__(self):\n DBusGMainLoop(set_as_default=True)\n self._main_loop = gobject.MainLoop()\n self._manager = None\n bus = dbus.SystemBus()\n try:\n self._manager = dbus.Interface(bus.get_object(BUS_NAME, '/'),\n 'org.freedesktop.DBus.ObjectManager')\n except DBusException as e:\n raise BluetoothManagerException('DBus Exception in getting Manager'\n 'dbus Interface: %s.' % e)\n #TODO(cychiang). Migrate to bluez5.x api. Check crosbug.com/p/19276.\n def SetDeviceConnected(self, adapter, device_address, connect):\n \"\"\"Switches the device connection.\n Args:\n adapter: The adapter interface to control.\n device_address: The mac address of input device to control.\n connect: True/False to turn on/off the connection.\n Returns:\n Return True if succeed to turn on/off connection.\n Raises:\n Raises BluetoothManagerException if fail to find device or fail to switch\n connection.\n \"\"\"\n try:\n device = adapter.FindDevice(device_address)\n except DBusException as e:\n raise BluetoothManagerException('SetDeviceConnected: fail to find device'\n ' %s: %s' % (device_address, e))\n bus = dbus.SystemBus()\n input_interface = dbus.Interface(bus.get_object(BUS_NAME, device),\n 'org.bluez.Input')\n try:\n if connect:\n input_interface.Connect()\n else:\n input_interface.Disconnect()\n except DBusException as e:\n raise BluetoothManagerException('SetDeviceConnected: fail to switch'\n 'connection: %s' % e)\n else:\n return True\n #TODO(cychiang). Migrate to bluez5.x api. Check crosbug.com/p/19276.\n def RemovePairedDevice(self, adapter, device_address):\n \"\"\"Removes the paired device.\n Args:\n adapter: The adapter interface to control.\n device_address: The mac address of input device to control.\n Returns:\n Return True if succeed to remove paired device.\n Raises:\n Raises BluetoothManagerException if fail to remove paired device.\n \"\"\"\n try:\n device = adapter.FindDevice(device_address)\n adapter.RemoveDevice(device)\n except DBusException as e:\n raise BluetoothManagerException('RemovePairedDevice: fail to remove'\n ' device: %s.' % e)\n else:\n logging.info('succefully removed device.')\n return True\n #TODO(cychiang). Migrate to bluez5.x api. Check crosbug.com/p/19276.\n def CreatePairedDevice(self, adapter, device_address):\n \"\"\"Create paired device.\n Args:\n adapter: The adapter interface to control.\n device_address: The mac address of input device to control.\n Raises:\n Raises BluetoothManagerException if fails to create service agent or\n fails to create paired device.\n \"\"\"\n success = threading.Event()\n def _ReplyHandler(device):\n \"\"\"The callback to handle success of adapter.CreatePairedDevice.\"\"\"\n logging.info('Created device %s.', device)\n success.set()\n self._main_loop.quit()\n def _ErrorHandler(error):\n \"\"\"The callback to handle error of adapter.CreatePairedDevice.\"\"\"\n logging.error('Creating device failed: %s.', error)\n self._main_loop.quit()\n bus = dbus.SystemBus()\n # Exposes a service agent object at a unique path for this test.\n agent_id = str(uuid.uuid4()).replace('-', '')\n agent_path = os.path.join('/BluetoothTest', 'agent', agent_id)\n logging.info('CreatePairedDevice: Set agent path at %s.', agent_path)\n try:\n dbus.service.Object(bus, agent_path)\n except DBusException as e:\n if str(e).find('there is already a handler.'):\n logging.info('There is already an agent there, that is OK: %s.', e)\n else:\n logging.exception('Fail to create agent.')\n raise BluetoothManagerException('CreatePairedDevice:'\n 'Fail to create agent.')\n adapter.CreatePairedDevice(device_address, agent_path, 'DisplayYesNo',\n reply_handler=_ReplyHandler,\n error_handler=_ErrorHandler)\n self._main_loop.run()\n if success.isSet():\n return True\n else:\n raise BluetoothManagerException('CreatePairedDevice: reply_handler'\n ' did not get called.')\n def GetFirstAdapter(self):\n \"\"\"Returns the first adapter object found by bluetooth manager.\n An adapter is a proxy object which provides the interface of\n 'org.bluez.Adapter1'.\n Raises:\n Raises BluetoothManagerException if fails to get any adapter.\n \"\"\"\n adapters = self.GetAdapters()\n if len(adapters) > 0:\n return adapters[0]\n else:\n raise BluetoothManagerException('Fail to find any adapter.')\n def _GetAdapters(self):\n \"\"\"Gets a list of available bluetooth adapters.\n Returns:\n Returns a list of adapters. An adapter is a proxy object which provides\n the interface of 'org.bluez.Adapter1'.\n Raises:\n Raises BluetoothManagerException if fail to get adapter interface.\n \"\"\"\n objects = self._manager.GetManagedObjects()\n bus = dbus.SystemBus()\n adapters = []\n for path, interfaces in objects.iteritems():\n adapter = interfaces.get(ADAPTER_INTERFACE)\n if adapter is None:\n continue\n obj = bus.get_object(BUS_NAME, path)\n adapters.append(dbus.Interface(obj, ADAPTER_INTERFACE))\n return adapters\n def GetAdapters(self, max_retry_times=10, interval=2):\n \"\"\"Gets a list of available bluetooth adapters.\n Args:\n max_retry_times: The maximum retry times to find adapters.\n interval: The sleep interval between two trials in seconds.\n Returns:\n A list of adapters found. Each adapter is a proxy object which provides\n the interface of 'org.bluez.Adapter1'. Returns None if there is no\n available adapter.\n \"\"\"\n adapters = Retry(max_retry_times, interval, None,\n self._GetAdapters)\n if adapters is None:\n logging.error('BluetoothManager: Fail to get any adapter.')\n return None\n else:\n return adapters\n def _SwitchAdapterPower(self, adapter, on):\n \"\"\"Powers on adapter by setting the Powered property.\n This will bring up the adapter like 'hciconfig up' does.\n Args:\n adapter: The adapter proxy object.\n on: True/False for power on/off.\n \"\"\"\n bus = dbus.SystemBus()\n device_prop = dbus.Interface(bus.get_object(BUS_NAME, adapter.object_path),\n 'org.freedesktop.DBus.Properties')\n device_prop.Set(ADAPTER_INTERFACE, 'Powered', on)\n def _WaitUntilStartDiscovery(self, adapter, timeout_secs):\n \"\"\"Waits until adapter starts discovery mode.\n After calling adapter.StartDiscovery(), there is a delay before the adapter\n actually start scanning. This function blocks until it sees adapter property\n \"Discovering\" is True with a timeout timeout_secs.\n \"\"\"\n bus = dbus.SystemBus()\n device_prop = dbus.Interface(bus.get_object(BUS_NAME, adapter.object_path),\n 'org.freedesktop.DBus.Properties')\n _Condition = lambda: device_prop.Get(ADAPTER_INTERFACE, 'Discovering') == 1\n PollForCondition(_Condition, timeout_secs,\n condition_name=\"Wait for Discovering==1\")\n def RemoveDevices(self, adapter, paths):\n \"\"\"Lets adapter to remove devices in paths.\n Args:\n adapter: The adapter proxy object.\n paths: A list of device paths to be removed.\n \"\"\"\n logging.info('Removing devices...')\n for path in paths:\n try:\n adapter.RemoveDevice(path)\n except DBusException as e:\n if str(e).find('Does Not Exist'):\n logging.warning('Can not remove device %s because it is not present',\n path)\n def GetAllDevicePaths(self, adapter):\n \"\"\"Gets all device paths under the adapter\"\"\"\n introspect = dbus.Interface(adapter, 'org.freedesktop.DBus.Introspectable')\n node_names = _RE_NODE_NAME.findall(introspect.Introspect())\n logging.info('node names: %s', node_names)\n paths = [os.path.join(adapter.object_path, x) for x in node_names]\n logging.info('paths: %s', paths)\n return paths\n def ScanDevices(self, adapter, timeout_secs=10, remove_before_scan=True):\n \"\"\"Scans device around using adapter for timeout_secs.\n The returned value devices is a dict containing the properties of\n scanned devies. Keys are device mac addresses and values are device\n properties.\n For example: devices = {\n dbus.String(u'08:3E:8E:2A:90:24'): dbus.Dictionary(\n {dbus.String(u'Paired'): dbus.Boolean(False, variant_level=1),\n dbus.String(u'LegacyPairing'): dbus.Boolean(False,\n variant_level=1),\n dbus.String(u'Alias'): dbus.String(u'08-3E-8E-2A-90-24',\n variant_level=1),\n dbus.String(u'Address'): dbus.String(u'08:3E:8E:2A:90:24',\n variant_level=1),\n dbus.String(u'RSSI'): dbus.Int16(-79, variant_level=1),\n dbus.String(u'Class'): dbus.UInt32(0L, variant_level=1),\n dbus.String(u'Trusted'): dbus.Boolean(False, variant_level=1)},\n signature=dbus.Signature('sv'))\n dbus.String(u'00:07:61:FC:0B:E8'): dbus.Dictionary(\n {dbus.String(u'Name'):\n dbus.String(u'Logitech Bluetooth Mouse M555b',\n variant_level=1),\n dbus.String(u'Paired'): dbus.Boolean(False, variant_level=1),\n dbus.String(u'LegacyPairing'): dbus.Boolean(False,\n variant_level=1),\n dbus.String(u'Alias'):\n dbus.String(u'Logitech Bluetooth Mouse M555b',\n variant_level=1),\n dbus.String(u'Address'): dbus.String(u'00:07:61:FC:0B:E8',\n variant_level=1),\n dbus.String(u'RSSI'): dbus.Int16(-56, variant_level=1),\n dbus.String(u'Class'): dbus.UInt32(9600L, variant_level=1),\n dbus.String(u'Trusted'): dbus.Boolean(False, variant_level=1),\n dbus.String(u'Icon'): dbus.String(u'input-mouse',\n variant_level=1)},\n signature=dbus.Signature('sv'))}\n Args:\n adapter: The adapter interface to control.\n timeout_secs: The duration of scan.\n remove_before_scan: Remove devices under adapter before scanning.\n Returns:\n A dict containing the information of scanned devices. The dict maps\n devices mac addresses to device properties.\n \"\"\"\n logging.info('Controlling adapter %s', adapter)\n if remove_before_scan:\n logging.info('Remove old devices before scanning...')\n old_device_paths = self.GetAllDevicePaths(adapter)\n self.RemoveDevices(adapter, old_device_paths)\n # devices is a mapping from device path to device properties.\n devices = dict()\n self._SwitchAdapterPower(adapter, True)\n logging.info('Powered on adapter')\n def _ScanTimeout():\n \"\"\"The callback when scan duration is over.\n If adapter is still scanning, stop it and\n quit self._main_loop.\n Returns:\n False since we want this to be called at most once.\n \"\"\"\n logging.info('Device scan timed out.')\n adapter.StopDiscovery()\n logging.info('Stop Discovery')\n logging.info('Quit main loop without waiting for Discovery=1.')\n self._main_loop.quit()\n return False\n def _CallbackInterfacesAdded(path, interfaces):\n \"\"\"The callback when an interface is found.\n When the adapter finds a device, it will assign the device a path and add\n that device interface to dbus.\n Reads the properties of device through interfaces and add the mapping\n from device path to device properties into 'devices'.\n Args:\n path: The device path.\n interfaces: The interface types.\n \"\"\"\n logging.info('InterfacesAdded')\n if DEVICE_INTERFACE not in interfaces:\n return\n properties = interfaces[DEVICE_INTERFACE]\n for key, value in properties.iteritems():\n logging.debug('%s : %s', key, value)\n if path in devices:\n logging.info('replace old device properties with new device properties')\n devices[path] = properties\n address = (properties['Address'] if 'Address' in properties\n else '')\n logging.info('Bluetooth Device Found: %s.', address)\n if 'RSSI' in properties:\n logging.info('Address: %s, RSSI: %s', address, properties['RSSI'])\n # pylint: disable=W0613\n def _CallbackDevicePropertiesChanged(interface, changed, invalidated, path):\n \"\"\"The callback when device properties changed.\n This is mainly for debug usage since device is scanned when callback for\n InterfaceAdded is called.\n Args:\n interface: Interface name.\n changed: A dict of changed properties.\n invalidated: A list of properties changed but the value is\n not provided.\n path: The path of signal emitter.\n \"\"\"\n logging.debug('Device properties changed %s: %s at path %s',\n interface, changed, path)\n if interface != DEVICE_INTERFACE:\n logging.error('should not get called with interface %s', interface)\n return\n address = (devices[path]['Address']\n if path in devices and 'Address' in devices[path]\n else '')\n if 'RSSI' in changed:\n logging.info('Address: %s, new RSSI: %s', address, changed['RSSI'])\n bus = dbus.SystemBus()\n bus.add_signal_receiver(_CallbackInterfacesAdded,\n dbus_interface='org.freedesktop.DBus.ObjectManager',\n signal_name='InterfacesAdded')\n bus.add_signal_receiver(_CallbackDevicePropertiesChanged,\n dbus_interface='org.freedesktop.DBus.Properties',\n signal_name='PropertiesChanged',\n arg0=DEVICE_INTERFACE,\n path_keyword=\"path\")\n adapter.StartDiscovery()\n logging.info('Start discovery')\n # Normally it takes less than a second to start discovery.\n # Raises TimeoutError if it fails to start discovery within timeout.\n self._WaitUntilStartDiscovery(adapter, 3)\n logging.info('Device scan started.')\n # Scan for timeout_secs\n gobject.timeout_add(timeout_secs * 1000, _ScanTimeout)\n self._main_loop.run()\n bus.remove_signal_receiver(_CallbackInterfacesAdded,\n dbus_interface='org.freedesktop.DBus.ObjectManager',\n signal_name='InterfacesAdded')\n bus.remove_signal_receiver(_CallbackDevicePropertiesChanged,\n dbus_interface='org.freedesktop.DBus.Properties',\n signal_name='PropertiesChanged',\n arg0=DEVICE_INTERFACE,\n path_keyword=\"path\")\n logging.info('Transform the key from path to address...')\n devices_address_properties = dict(\n ((value['Address'], value) for value in devices.values()\n if 'Address' in value))\n return devices_address_properties\nUSAGE = \"\"\"\nControls bluetooth adapter to scan remote devices.\n\"\"\"\nclass BluetoothTest(object):\n \"\"\"A class to test bluetooth in command line.\"\"\"\n args = None\n manager = None\n adapter = None\n def Main(self):\n self.ParseArgs()\n self.Run()\n def ParseArgs(self):\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=USAGE)\n parser.add_argument(\n '--properties', dest='properties', action='store_true',\n help=\"Shows properties in the scanned results\")\n parser.add_argument(\n '--forever', dest='forever', action='store_true',\n help=\"Scans forever\")\n self.args = parser.parse_args()\n logging.basicConfig(level=logging.INFO)\n def Run(self):\n \"\"\"Controls the adapter to scan remote devices.\"\"\"\n self.manager = BluetoothManager()\n self.adapter = self.manager.GetFirstAdapter()\n logging.info('Using adapter: %s', self.adapter)\n if self.args.forever:\n while True:\n self._RunOnce()\n else:\n self._RunOnce()\n def _RunOnce(self):\n \"\"\"Scans once.\"\"\"\n result = self.manager.ScanDevices(self.adapter)\n if self.args.properties:\n logging.info(yaml.dump(result, default_flow_style=False))\nif __name__ == '__main__':\n BluetoothTest().Main()","sub_path":"bluetoothChromium/bluetooth_chromium.py","file_name":"bluetooth_chromium.py","file_ext":"py","file_size_in_byte":18053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"557560924","text":"# Copyright (c) 2021 Alethea Katherine Flowers.\n# Published under the standard MIT License.\n# Full text available at: https://opensource.org/licenses/MIT\n\n\"\"\"Logging helpers and such.\"\"\"\n\nimport atexit\nimport datetime\nimport sys\nimport traceback\nfrom pathlib import Path\n\nfrom wintertools import tui\n\nDEBUG_COLOR = (0.7, 0.7, 0.7)\nINFO_COLOR = (0.8, 0.8, 1.0)\nWARNING_COLOR = (1.0, 1.0, 0.4)\nERROR_COLOR = (1.0, 0.4, 0.4)\nSUCCESS_COLOR = (0.5, 1.0, 0.5)\n\n\n_log_file_path = Path(\"logs\", f\"{datetime.datetime.now().isoformat()}.log\")\n_log_file_path.parent.mkdir(parents=True, exist_ok=True)\n_log_file = _log_file_path.open(\"w\")\n\n\ndef _finish_up():\n _log_file.flush()\n _log_file.close()\n print(\n tui.rgb(SUCCESS_COLOR),\n tui.bold,\n f\"► full log at {_log_file_path}\",\n tui.reset,\n sep=\"\",\n )\n\n\natexit.register(_finish_up)\n\n\ndef _print_term(color, *args, sep=\" \", end=\"\\n\", **kwargs):\n args = sep.join(f\"{arg}\" for arg in args)\n print(tui.rgb(color), args, tui.reset, sep=\"\", end=end, **kwargs)\n\n\ndef _print_file(*args, sep=\" \", end=\"\\n\", **kwargs):\n print(*args, sep=sep, end=end, **kwargs, file=_log_file)\n\n\ndef debug(*args, **kwargs):\n # _print_term(DEBUG_COLOR, *args, **kwargs)\n _print_file(\"[debug] : \", *args, **kwargs)\n\n\ndef info(*args, **kwargs):\n _print_term(INFO_COLOR, *args, **kwargs)\n _print_file(\"[info] : \", *args, **kwargs)\n\n\ndef warning(*args, **kwargs):\n _print_term(WARNING_COLOR, *args, **kwargs)\n _print_file(\"[warning] : \", *args, **kwargs)\n\n\ndef error(text, *args, exc=None, quit=True, **kwargs):\n if exc is not None:\n _print_term(ERROR_COLOR, f\"{text}: {exc}\", *args, file=sys.__stdout__, **kwargs)\n _print_file(f\"[error] : {text}: {exc}\", *args, **kwargs)\n traceback.print_exc(file=_log_file)\n else:\n _print_term(ERROR_COLOR, text, *args, file=sys.__stdout__, **kwargs)\n _print_file(f\"[error] : {text}\", *args, **kwargs)\n\n if quit:\n sys.exit(-1)\n\n\ndef success(*args, **kwargs):\n _print_term(SUCCESS_COLOR, *args, **kwargs)\n _print_file(\"[success] : \", *args, **kwargs)\n\n\ndef section(name, depth=1, **kwargs):\n marker = \"►\" * depth\n output = f\"{tui.bold}{tui.underline}{marker} {name}\\n\"\n _print_term((0.5, 0.8, 1.0), output)\n marker = \"#\" * depth\n _print_file(f\"\\n{marker} {name}\\n\")\n","sub_path":"wintertools/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"353779116","text":"import pandas as pd\nimport numpy as np\nimport os\nfrom scipy.stats import norm, multivariate_normal\nimport matplotlib.pyplot as plt\nimport matplotlib\n\ndef computeRegretOneIter(df, truthPdf, X):\n optimalClickCount = df[\"n_exp\"].sum() * truthPdf(X).max()\n #print(\"optimalClickCount = \", optimalClickCount)\n realClickCount = df[\"output\"].sum()\n #print(\"realClickCount = \", realClickCount)\n return optimalClickCount - realClickCount\n\ndef computerRegret(df, truthPdf, X):\n lenX = X.shape[0] * X.shape[1] * X.shape[2]\n assert (df.shape[0] % lenX) == 0, \"result dataframe has an incorrect size\"\n curIndex = 0\n runningAvg = []\n while curIndex + lenX <= df.shape[0]:\n regret = computeRegretOneIter(df.iloc[curIndex: curIndex+lenX], truthPdf, X)\n curAvg = 0 if len(runningAvg)==0 else runningAvg[-1]\n N = len(runningAvg) + 1\n runningAvg.append(curAvg * (N-1) / N + regret / N)\n curIndex += lenX\n return runningAvg\n\ndef pdf(x):\n mean1 = [3, 3, 3]\n cov1 = np.eye(3) * 0.75\n mean2 = [-2, -2, -2]\n cov2 = np.eye(3) * 0.75\n mean3 = [1, 1, 1]\n cov3 = np.eye(3) * 1.0\n prob = multivariate_normal.pdf(x, mean=mean1, cov=cov1) + multivariate_normal.pdf(x, mean=mean2, cov=cov2) \\\n + multivariate_normal.pdf(x, mean=mean3, cov=cov3)\n return prob * 3\n\n\nnTrials = 4\nacFuncs = [\"ucb\", \"ts\", \"greedy\", \"ei\", \"pi\"]\n\nfont = {'weight' : 'bold',\n 'size' : 16}\n\nmatplotlib.rc('font', **font)\n\nif __name__ == '__main__':\n runningAvgRegret = {}\n colors = {\"ucb\":\"black\", \"pi\":\"brown\", \"ei\":\"blue\", \"ts\":\"red\", \"greedy\":\"green\"}\n labels = {\"ucb\":\"GP-UCB\", \"pi\":\"PI\", \"ei\":\"EI\", \"ts\":\"TS\", \"greedy\":\"EPS\"}\n x, y, z = np.array(np.meshgrid(*(np.arange(-5, 5.0, 2) for _ in range(3))))\n X = np.empty(x.shape + (3,))\n X[:, :, :, 0] = x; X[:, :, :, 1] = y; X[:, :, :, 2] = z\n \n for acFunc in acFuncs:\n listAvgRegretsAllTrials = []\n for i in range(nTrials):\n eval_csv_path = os.path.join(\"./eval\", \"gaussian_result_3dim_clicks_%s_trialCount_%d.csv\"%(acFunc, i))\n df = pd.DataFrame.from_csv(eval_csv_path, index_col=None)\n y = computerRegret(df, pdf, X)\n listAvgRegretsAllTrials.append(y)\n runningAvgRegret[acFunc] = np.array(listAvgRegretsAllTrials).mean(axis=0)\n\n handles = []\n plt.figure(figsize=(15, 10))\n for k, v in runningAvgRegret.items():\n handle, = plt.plot(v, color=colors[k], label=k)\n handles.append(handle)\n plt.yscale(\"log\")\n plt.xlabel(\"Iteration Count\")\n plt.ylabel(\"Average Regret\")\n plt.legend(handles, [labels[k] for k in acFuncs])\n plt.savefig(\"eval.eps\", format='eps')\n plt.close()\n\n \n \n \n \n \n \n \n \n \n","sub_path":"samples/three_dim_test_many_click_val/avgRegret.py","file_name":"avgRegret.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"154329167","text":"import numpy as np\nfrom EulerStep import EulerStep\n\ndef EulerSolve(f,y0,T,h):\n\n # Initialize variables\n N = int(np.ceil((T[1]-T[0])/h))# number of steps\n h = (T[1]-T[0])/N # adjust step size to fit interval length\n d = len(y0) # dimension of solution\n t = np.linspace(T[0],T[1],N+1) # time grid\n y = np.zeros((d,N+1)) # solution\n y[:,0] = y0 # set initial value\n \n # Compute solution\n for j in range(0,N):\n y[:,j+1] = EulerStep(f,y[:,j],t[j],h)\n \n return np.array([t,y])","sub_path":"Euler methods/EulerSolve.py","file_name":"EulerSolve.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"438613890","text":"import tkinter as tk\r\n\r\nclass mycalendar(tk.Frame):\r\n def __init__(self,master=None,cnf={},**kw):\r\n import datetime\r\n tk.Frame.__init__(self,master,cnf,**kw)\r\n now = datetime.datetime.now()\r\n self.year = now.year\r\n self.month = now.month\r\n\r\n frame_top = tk.Frame(self)\r\n frame_top.pack(pady=5)\r\n\r\n self.previous_month = tk.Label(frame_top, text = \"<\", font = (\"\",18))\r\n self.previous_month.pack(side = \"left\", padx = 10)\r\n self.previous_month.bind(\"<1>\", self.change_month)\r\n self.current_year = tk.Label(frame_top, text = self.year , font = (\"\",18))\r\n self.current_year.pack(side = \"left\")\r\n self.current_month = tk.Label(frame_top, text = self.month, font = (\"\",18))\r\n self.current_month.pack(side = \"left\")\r\n self.next_month = tk.Label(frame_top, text = \">\", font = (\"\",22))\r\n self.next_month.pack(side = \"left\", padx = 10)\r\n self.next_month.bind(\"<1>\", self.change_month)\r\n\r\n frame_week = tk.Frame(self)\r\n frame_week.pack()\r\n label_san = d_label(frame_week, text = \"Sun\", fg = \"red\")\r\n label_san.grid(column=0, row=0)\r\n label_mon = d_label(frame_week, text = \"Mon\")\r\n label_mon.grid(column=1, row=0)\r\n label_tue = d_label(frame_week, text = \"Tue\")\r\n label_tue.grid(column=2, row=0)\r\n label_wed = d_label(frame_week, text = \"Wed\")\r\n label_wed.grid(column=3, row=0)\r\n label_thu = d_label(frame_week, text = \"Thu\")\r\n label_thu.grid(column=4, row=0)\r\n label_fri = d_label(frame_week, text = \"Fri\", fg = \"gold\")\r\n label_fri.grid(column=5, row=0)\r\n label_sat = d_label(frame_week, text = \"Sat\", fg = \"blue\")\r\n label_sat.grid(column=6, row=0)\r\n\r\n self.frame_calendar = tk.Frame(self)\r\n self.frame_calendar.pack()\r\n self.create_calendar(self.year,self.month)\r\n\r\n def create_calendar(self,year,month):\r\n try:\r\n for key,item in self.day.items():\r\n item.destroy()\r\n except:\r\n pass\r\n import calendar\r\n cal = calendar.Calendar()\r\n days = cal.monthdayscalendar(year,month)\r\n self.day = {}\r\n\r\n for i in range(0,42):\r\n c = i - (7 * int(i/7))\r\n r = int(i/7)\r\n try:\r\n if days[r][c] != 0:\r\n self.day[i] = d_label(self.frame_calendar,text = days[r][c])\r\n self.day[i].grid(column=c,row=r)\r\n except:\r\n break\r\n\r\n def change_month(self,event):\r\n if event.widget[\"text\"] == \"<\":\r\n self.month -= 1\r\n else:\r\n self.month += 1\r\n\r\n if self.month == 0:\r\n self.year -= 1\r\n self.month = 12\r\n elif self.month == 13:\r\n self.year += 1\r\n self.month =1\r\n\r\n self.current_year[\"text\"] = self.year\r\n self.current_month[\"text\"] = self.month\r\n self.create_calendar(self.year,self.month)\r\n\r\nclass d_label(tk.Label):\r\n def __init__(self, master=None, cnf={}, **kw):\r\n tk.Label.__init__(self,master,cnf,**kw)\r\n self.configure(font=(\"\",18) ,height=2, width=4)\r\n\r\nroot = tk.Tk()\r\nroot.title(\"Calemdar App\")\r\nmycal = mycalendar(root)\r\nmycal.pack()\r\nroot.mainloop()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"75041899","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nfrom compas.datastructures import Network\nfrom compas.datastructures import network_polylines\n\nfrom compas_singular.rhino import RhinoSurface\nfrom compas_singular.rhino import RhinoCurve\n\nfrom compas.utilities import pairwise\n\ntry:\n\timport rhinoscriptsyntax as rs\n\nexcept ImportError:\n\timport compas\n\tcompas.raise_if_ironpython()\n\n\n__all__ = [\n\t'surface_discrete_mapping'\n]\n\ndef surface_discrete_mapping(srf_guid, discretisation, minimum_discretisation = 5, crv_guids = [], pt_guids = []):\n\t\"\"\"Map the boundaries of a Rhino NURBS surface to planar poylines dicretised within some discretisation using the surface UV parameterisation.\n\tCurve and point feautres on the surface can be included.\n\tParameters\n\t----------\n\tsrf_guid : guid\n\t\tA surface guid.\n\tcrv_guids : list\n\t\tList of guids of curves on the surface.\n\tpt_guids : list\n\t\tList of guids of points on the surface.\n\tdiscretisation : float\n\t\tThe discretisation of the surface boundaries.\n\tminimum_discretisation : int\n\t\tThe minimum discretisation of the surface boundaries.\n\tReturns\n\t-------\n\ttuple\n\t\tTuple of the mapped objects: outer boundary, inner boundaries, polyline_features, point_features.\n\t\"\"\"\n\n\tsrf = RhinoSurface.from_guid(srf_guid)\n\n\t# a boundary may be made of multiple boundary components and therefore checking for closeness and joining are necessary\n\tmapped_borders = []\n\n\tfor i in [1, 2]:\n\t\tmapped_border = []\n\n\t\tfor border_guid in srf.borders(type = i):\n\t\t\tpoints = [list(srf.point_xyz_to_uv(pt)) + [0.0] for pt in rs.DivideCurve(border_guid, max(int(rs.CurveLength(border_guid) / discretisation) + 1, minimum_discretisation))]\n\t\t\t\n\t\t\tif rs.IsCurveClosed(border_guid):\n\t\t\t\tpoints.append(points[0])\n\t\t\t\n\t\t\tmapped_border.append(points)\n\t\t\trs.DeleteObject(border_guid)\n\t\tmapped_borders.append(mapped_border)\n\n\touter_boundaries, inner_boundaries = [network_polylines(Network.from_lines([(u, v) for border in mapped_borders[i] for u, v in pairwise(border)])) for i in [0, 1]]\n\t\n\t# mapping of the curve features on the surface\n\tmapped_curves = []\n\n\tfor crv_guid in crv_guids:\n\n\t\tpoints = [list(srf.point_xyz_to_uv(pt)) + [0.0] for pt in rs.DivideCurve(crv_guid, max(int(rs.CurveLength(crv_guid) / discretisation) + 1, minimum_discretisation))]\n\t\t\n\t\tif rs.IsCurveClosed(crv_guid):\n\t\t\tpoints.append(points[0])\n\t\t\n\t\tmapped_curves.append(points)\n\n\tpolyline_features = network_polylines(Network.from_lines([(u, v) for curve in mapped_curves for u, v in pairwise(curve)]))\n\n\t# mapping of the point features onthe surface\n\tpoint_features = [list(srf.point_xyz_to_uv(rs.PointCoordinates(pt_guid))) + [0.0] for pt_guid in pt_guids]\n\n\treturn outer_boundaries[0], inner_boundaries, polyline_features, point_features\n\n\n# ==============================================================================\n# Main\n# ==============================================================================\n\nif __name__ == '__main__':\n\n\timport compas\n","sub_path":"src/compas_singular/algorithms/decomposition/mapping.py","file_name":"mapping.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"558014624","text":"import sys\nfrom collections import deque\n\nread = lambda :sys.stdin.readline().rstrip()\n\ntest_cases = int(read())\nfor _ in range(test_cases):\n arr = input()\n stack1 = []\n stack2 = []\n for char in arr:\n if char == '<':\n if stack1:\n temp = stack1.pop()\n stack2.append(temp)\n elif char == '>':\n if stack2:\n temp = stack2.pop()\n stack1.append(temp)\n elif char == '-':\n if stack1:\n stack1.pop()\n else:\n stack1.append(char)\n while stack2:\n temp = stack2.pop()\n stack1.append(temp)\n for char in stack1:\n print(char, end='')\n print()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# queue = deque([a for a in read()])\n# i = 0\n# j = 1\n# cur = 0\n# arr = []\n# while queue:\n# oper = queue.popleft()\n# if oper == '<':\n# if cur-1 > -1:\n# cur -= 1\n# elif oper == '>':\n# if cur+1 < j:\n# cur += 1\n# elif oper == '-':\n# if cur-1 > -1:\n# cur -= 1\n# arr.pop(cur)\n# j -= 1\n# else:\n# arr.insert(cur, oper)\n# cur += 1\n# j += 1\n# for item in arr:\n# print(item, end='')\n","sub_path":"Baekjoon,SWEA, etc/백준/5397.py","file_name":"5397.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"386273981","text":"from Parser.parse_html_to_postgres import parse_html_to_postgres\nfrom config import ingestion_settings as settings\n\nif __name__ == '__main__':\n input_folder = settings['input_folder']\n\n # intermediate folder location (will be auto-generated)\n merge_folder = settings['merge_folder']\n output_html = settings['output_html']\n output_words = settings['output_words']\n\n db_connect_str = settings['db_connect_str']\n\n strip_tags = settings['strip_tags']\n ignored_file_when_link = settings['ignored_file_when_link']\n\n parse_html_to_postgres(input_folder, output_html, merge_folder, output_html, db_connect_str, strip_tags, ignored_file_when_link)\n","sub_path":"cosmos/docs/run_examples/run_parser.py","file_name":"run_parser.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"494292381","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport time\nimport sys\n\nimport sys\n\ndef cli_progress_test(end_val, bar_length=20):\n for i in xrange(0, end_val):\n percent = float(i) / end_val\n hashes = '#' * int(round(percent * bar_length))\n spaces = ' ' * (bar_length - len(hashes))\n sys.stdout.write(\"\\rPercent: [{0}] {1}%\".format(hashes + spaces, int(round(percent * 100))))\n sys.stdout.flush()\n\n#for i in range(100):\n# time.sleep(1)\n# sys.stdout.write(\"\\r%d%%\" % i)\n# sys.stdout.flush()\n","sub_path":"pb.py","file_name":"pb.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"160943137","text":"d1 = {'python': 10, 'java': 3, 'c#': 8, 'javascript': 15}\nd2 = {'java': 10, 'c++': 10, 'c#': 4, 'go': 9, 'python': 6}\nd3 = {'erlang': 5, 'haskell': 2, 'python': 1, 'pascal': 1}\n\n\ndef merge(*dicts):\n unsorted = {}\n for d in dicts:\n for k, v in d.items():\n unsorted[k] = unsorted.get(k, 0) + v\n\n # create a dictionary sorted by value\n return dict(sorted(unsorted.items(), key=lambda e: e[1], reverse=True))\n\n\nmerged = merge(d1, d2, d3)\nfor k, v in merged.items():\n print(k, v)\n\nprint()\n\nmerged = merge(d1, d2)\nfor k, v in merged.items():\n print(k, v)\n","sub_path":"Section 4 Coding Exercises/Coding Exercises - Solution 3.py","file_name":"Coding Exercises - Solution 3.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"13068598","text":"class Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if not prices:\n return 0\n \n n = len(prices)\n buy = [0 for i in xrange(n+1)]\n sell = [0 for i in xrange(n+1)]\n buy[1] = -prices[0]\n sell[1] = 0\n\n for i in xrange(2, n+1):\n buy[i] = max(sell[i-2] - prices[i-1], buy[i-1])\n sell[i] = max(buy[i-1] + prices[i-1], sell[i-1])\n \n return sell[n]\n\n\nclass Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if not prices:\n return 0\n \n n = len(prices)\n buy = -prices[0]\n pre_sell = 0\n pre_buy = 0\n sell = 0\n\n for i in xrange(2, n+1):\n pre_buy = buy\n buy = max(pre_sell - prices[i-1], pre_buy)\n pre_sell = sell\n sell = max(pre_buy + prices[i-1], pre_sell)\n\n return sell","sub_path":"src/main/java/com/practice/python/best_time_to_buy_and_sell_stock_cooldown.py","file_name":"best_time_to_buy_and_sell_stock_cooldown.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"312469285","text":"# -*- coding: utf-8 -*-\r\nimport os\r\nfrom django.conf import settings\r\nfrom models.sys_material import SysMaterial\r\nfrom utils import sql_get_pgsql\r\nimport json\r\n\r\n\r\nclass Material(object):\r\n def __init__(self, model):\r\n super(Material, self).__init__()\r\n self.model = model\r\n self.node_dict = {}\r\n topic_text_obj = sql_get_pgsql(\"SELECT app_label,model FROM django_content_type WHERE model='topictext'\")\r\n TopicText = {\"app_label\": topic_text_obj[0][0], \"model\": topic_text_obj[0][1]}\r\n guide_title_obj = sql_get_pgsql(\"SELECT app_label,model FROM django_content_type WHERE model='guidetitle'\")\r\n GuideTitle = {\"app_label\": guide_title_obj[0][0], \"model\": guide_title_obj[0][1]}\r\n GuideTitle = json.dumps(GuideTitle)\r\n TopicText = json.dumps(TopicText)\r\n self.data = [\r\n {'key': 'user_default_icon_path',\r\n 'value': '/static/media/icon/sysicon/yangwangtiankong.jpg',\r\n 'note': u'默认的用户头像'\r\n },\r\n {'key': 'user_images_default',\r\n 'value': '/static/media/icon/sysicon/user_images_ default_160x160.jpg',\r\n 'note': u'评论页的默认用户头像'\r\n },\r\n {'key': 'user_home_img',\r\n 'value': '/static/media/images/sysimg/default_user_home_images.jpg',\r\n 'note': u'用户主页默认头像'\r\n },\r\n {\"key\": \"comm_page_size\", \"value\": \"10\", \"note\": u\"社区首页展示的帖子的条数\"},\r\n {\"key\": \"sort_page_size\", \"value\": \"10\", \"note\": u\"分类展示帖子的页数\"},\r\n {\"key\": \"image_path\", \"value\": \"static\", \"note\": u\"文件默认上传的路径\"},\r\n {\"key\": \"TopicText\", \"value\": TopicText, \"note\": u\"TopicText的app_label和model\"},\r\n {\"key\": \"GuideTitle\", \"value\": GuideTitle, \"note\": u\"GuideTitle的app_label和model\"},\r\n ]\r\n\r\n def write_data(self):\r\n data = {}\r\n for item in self.data:\r\n key = item.get('key')\r\n data['value'] = item.get('value')\r\n data['note'] = item.get('note')\r\n new_obj = self.model.objects.get_or_create(key=key, defaults=data)[0]\r\n new_obj.save()\r\n\r\n\r\ndef make_data():\r\n from models.sys_material import SysMaterial\r\n Material(SysMaterial).write_data()\r\n","sub_path":"base/create_records.py","file_name":"create_records.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"413831949","text":"#!/usr/bin/env python\r\nimport argparse\r\nimport os, sys\r\nimport shutil\r\nfrom pathlib import Path\r\n\r\nimport numpy as np\r\nimport pickle\r\nimport chainer\r\nfrom chainer import training, serializers\r\nfrom chainer.training import extensions\r\n\r\nfrom core import models\r\nfrom core.utils.config import Config\r\nfrom core.updater.StarGANupdater import StarGANUpdater\r\nfrom core.datasets.dataset import GestureDataset\r\n\r\n\r\ndef parse_args():\r\n parser = argparse.ArgumentParser(description='StarGAN')\r\n parser.add_argument('config', help='config file path')\r\n parser.add_argument('--gpu', '-g', type=int, default=0,\r\n help='GPU ID (negative value indicates CPU)')\r\n parser.add_argument('--resume', type=str, default=None)\r\n args = parser.parse_args()\r\n return args\r\n\r\n\r\ndef train():\r\n args = parse_args()\r\n cfg = Config.from_file(args.config)\r\n\r\n iteration = cfg.train.iterations\r\n batchsize = cfg.train.batchsize\r\n out = cfg.train.out\r\n\r\n print('GPU: {}'.format(args.gpu))\r\n print('# Minibatch-size: {}'.format(batchsize))\r\n print('# iteration: {}'.format(iteration))\r\n print('')\r\n\r\n ## Set up networks to train\r\n # number of gesture classes and users\r\n n_gesture = cfg.train.n_gesture\r\n n_user = len(cfg.train.dataset_dirs)\r\n if cfg.style == 'gesture':\r\n gen = getattr(models, cfg.train.generator.model)(cfg.train.generator, n_style=n_gesture) \r\n elif cfg.style == 'user':\r\n gen = getattr(models, cfg.train.generator.model)(cfg.train.generator, n_style=n_user)\r\n else:\r\n print(f'Invalid style: {cfg.style}')\r\n exit()\r\n dis = getattr(models, cfg.train.discriminator.model)(cfg.train.discriminator, n_gesture=n_gesture, n_user=n_user)\r\n \r\n ## Load resume checkpoint to restart. Load optimizer state later.\r\n if args.resume or cfg.resume:\r\n gen_resume = args.resume if args.resume else cfg.resume\r\n print(f'loading generator resume from {os.path.join(out, gen_resume)}')\r\n serializers.load_npz(os.path.join(out, gen_resume), gen)\r\n dis_resume = gen_resume.replace('gen', 'dis')\r\n print(f'loading discriminator resume from {os.path.join(out, dis_resume)}')\r\n serializers.load_npz(os.path.join(out, dis_resume), dis)\r\n \r\n ## Load resume checkpoint (only weight, not load optimizer state)\r\n if cfg.weight:\r\n gen_weight = cfg.weight\r\n print(f'loading generator weight from {gen_weight}')\r\n serializers.load_npz(gen_weight, gen)\r\n dis_weight = gen_weight.replace('gen', 'dis')\r\n print(f'loading discriminator weight from {dis_weight}')\r\n serializers.load_npz(dis_weight, dis)\r\n \r\n \r\n ## Setup an optimizer\r\n def make_optimizer(model, alpha=0.0002, beta1=0.5):\r\n optimizer = chainer.optimizers.Adam(alpha=alpha, beta1=beta1)\r\n optimizer.setup(model)\r\n return optimizer\r\n opt_gen = make_optimizer(gen, alpha=cfg.train.parameters.g_lr, beta1=0.5)\r\n opt_dis = make_optimizer(dis, alpha=cfg.train.parameters.d_lr, beta1=0.5)\r\n if args.resume or cfg.resume:\r\n opt_gen_resume = gen_resume.replace('gen', 'opt_gen')\r\n print(f'loading generator optimizer from {os.path.join(out, opt_gen_resume)}')\r\n serializers.load_npz(opt_gen_resume, opt_gen)\r\n opt_dis_resume = gen_resume.replace('gen', 'opt_dis')\r\n print(f'loading discriminator optimizer from {os.path.join(out, opt_dis_resume)}')\r\n serializers.load_npz(opt_dis_resume, opt_dis)\r\n\r\n ## Set GPU\r\n if args.gpu >= 0:\r\n # Make a specified GPU current\r\n chainer.backends.cuda.get_device_from_id(args.gpu).use()\r\n gen.to_gpu()\r\n dis.to_gpu()\r\n\r\n ## Set up dataset\r\n train = GestureDataset(cfg.train.dataset_dirs, style=cfg.style, equal=cfg.train.class_equal)\r\n for i in range(len(cfg.train.dataset_dirs)):\r\n print(f'{cfg.train.dataset_dirs[i]} contains {train.len_each()[i]} samples')\r\n\r\n train_iter = chainer.iterators.SerialIterator(train, batchsize)\r\n\r\n ## Set up a Trainer\r\n updater = StarGANUpdater(\r\n models = (gen, dis),\r\n iterator = train_iter,\r\n optimizer = {'gen': opt_gen, 'dis': opt_dis},\r\n cfg = cfg,\r\n out=out)\r\n trainer = training.Trainer(updater, (iteration, 'iteration'), out=out)\r\n\r\n ## Set invervals\r\n ## - display_interval : Interval iterations of print logs on display.\r\n ## - save_interval : Interval iterations of save models.\r\n display_interval = (cfg.train.display_interval, 'iteration')\r\n save_interval = (cfg.train.save_interval, 'iteration')\r\n trainer.extend(extensions.snapshot_object(gen, 'gen_iter_{.updater.iteration}.npz'), trigger=save_interval )\r\n trainer.extend(extensions.snapshot_object(dis, 'dis_iter_{.updater.iteration}.npz'), trigger=save_interval )\r\n trainer.extend(extensions.snapshot_object(opt_gen, 'opt_gen_iter_{.updater.iteration}.npz'), trigger=save_interval )\r\n trainer.extend(extensions.snapshot_object(opt_dis, 'opt_dis_iter_{.updater.iteration}.npz'), trigger=save_interval )\r\n trainer.extend(extensions.LogReport(trigger=display_interval))\r\n trainer.extend(extensions.PrintReport([\r\n 'epoch', 'iteration', 'lr', 'gen/loss_adv', 'gen/loss_eq', 'gen/loss_style', 'gen/loss_cont', 'gen/loss_rec', 'gen/loss_sm', 'dis/loss_adv', 'dis/loss_style', 'dis/loss_cont' \r\n ]), trigger=display_interval)\r\n trainer.extend(extensions.ProgressBar(update_interval=display_interval[0]))\r\n\r\n ## Save scripts and command to result directory. (To look back later.)\r\n if not os.path.exists(out):\r\n os.makedirs(out)\r\n shutil.copy(args.config, f'./{out}')\r\n shutil.copy('./core/models/StarGAN.py', f'./{out}')\r\n shutil.copy('./core/updater/StarGANupdater.py', f'./{out}')\r\n\r\n commands = sys.argv\r\n with open(f'./{out}/command.txt', 'w') as f:\r\n f.write(f'python {commands[0]} ')\r\n for command in commands[1:]:\r\n f.write(command + ' ')\r\n\r\n ## Run the training\r\n trainer.run()\r\n\r\n ## Once training finishid, save all models.\r\n modelname = f'./{out}/gen.npz'\r\n print('saving generator model to ' + modelname)\r\n serializers.save_npz(modelname, gen)\r\n\r\n modelname = f'./{out}/dis.npz'\r\n print('saving discriminator model to ' + modelname)\r\n serializers.save_npz(modelname, dis)\r\n\r\n optname = f'./{out}/opt_gen.npz'\r\n print( 'saving generator optimizer to ' + optname)\r\n serializers.save_npz(optname, opt_gen)\r\n\r\n optname = f'./{out}/opt_dis.npz'\r\n print( 'saving discriminator optimizer to ' + optname)\r\n serializers.save_npz(optname, opt_dis)\r\n\r\n\r\nif __name__ == '__main__':\r\n train()\r\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"217476063","text":"# ***********************************************\n# In God we trust\n# Crack the interview Scripts\n# Developed by: Servio Palacios\n# Ordering two color list in O(n)\n# There is another way, just counting how many\n# of each color, it is O(n) too\n# ***********************************************\n__author__ = 'Servio'\n\nstrColoredList = [\"R\", \"B\", \"R\", \"B\", \"B\", \"B\", \"R\", \"R\"]\nintStrLen = len(strColoredList)\nintLeftIndex = 0\nintRightIndex = intStrLen-1\nintRightElementToSwap = -1\nintLeftElementToSwap = -1\nintLeftIndexesArray = [-1,-1,-1,-1]\nintRightIndexesArray = [-1,-1,-1,-1]\nj = 0\nk = 0\n\nprint(strColoredList)\nfor i in range(0,intStrLen//2):\n if strColoredList[intRightIndex - i] == \"B\" and intRightElementToSwap == -1:\n intRightElementToSwap = intRightIndex - i\n intRightIndexesArray[j] = intRightElementToSwap\n j += 1\n intRightElementToSwap = -1\n\n if strColoredList[intLeftIndex + i] == \"R\" and intLeftElementToSwap == -1:\n intLeftElementToSwap = intLeftIndex + i\n intLeftIndexesArray[k] = intLeftElementToSwap\n k += 1\n intLeftElementToSwap = -1\n\nfor i in range(0,intStrLen//2):\n if intLeftIndexesArray[i] >= 0:\n strColoredList[intLeftIndexesArray[i]] = \"B\"\n if intRightIndexesArray[i] >= 0:\n strColoredList[intRightIndexesArray[i]] = \"R\"\n\nprint(strColoredList)\n","sub_path":"interviewpreparation/numbertheory/sortingcoloredlist.py","file_name":"sortingcoloredlist.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"650668916","text":"#coding:utf-8\n\nimport os\nimport sys\nimport argparse\n\nimport numpy as np\nimport numpy.linalg as LA\n\n\ndef L2_normalize_numpy(x, verbose=False):\n \"\"\"Row normalization\n Args:\n x: a numpy matrix of shape N*D\n Returns:\n x: L2 normalized x\n \"\"\"\n sqr_row_sum = LA.norm(x, axis=1, keepdims=True)\n if verbose:\n print('There are [{}] zero-padding feature(s).'.format(len((sqr_row_sum <= 1e-7).nonzero()[0])))\n sqr_row_sum[sqr_row_sum <= 1e-7] = 1\n return x / sqr_row_sum\n\n\ndef main(args):\n features = np.fromfile(args.feature_path, dtype=np.float32).reshape(-1, 256)\n\n features = L2_normalize_numpy(features)\n\n np.savetxt(\"py_feature.txt\", features, fmt=\"%lf\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='read feature test')\n parser.add_argument(\"--feature_path\", metavar=\"feature_path\", type=str, dest=\"feature_path\", \n required=True)\n \n args = parser.parse_args()\n \n main(args)","sub_path":"IO/read_feature.py","file_name":"read_feature.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"583042699","text":"import h5py\nimport torch\nimport numpy as np\nfrom pytorch_transformers import BertTokenizer\nimport time\n\nPAD = 0\nCLS = 101\nSEP = 102\n\n# Load pretrained tokenizer\ntokenizer = BertTokenizer.from_pretrained('/users3/ywsun/project/data2text/data/bert-base-cased-vocab.txt')\n\ndef add_tokens():\n print(len(tokenizer))\n with open('roto-ie.dict', 'r') as fr:\n roto_vocab = [line.strip().split()[0] for line in fr.readlines()]\n with open('data/bert-base-cased-vocab.txt', 'r') as fr:\n bert_vocab = [line.strip() for line in fr.readlines()]\n with open('data/bert-base-cased-vocab.txt', 'r') as fr:\n bert_vocab_ = {}\n for i, line in enumerate(fr.readlines()):\n w = line.strip()\n bert_vocab_[i] = w\n '''\n cnt = 0\n for w in list(set(roto_vocab) - set(bert_vocab)):\n if len(tokenizer.encode(w, add_special_tokens=False)) != 1:\n print(w, [bert_vocab_[t] for t in tokenizer.encode(w, add_special_tokens=False)])\n cnt += 1\n print('unknown cnt %d'%cnt)\n '''\n tokenizer.add_tokens(list(set(roto_vocab) - set(bert_vocab)))\n print(len(tokenizer))\n\ndef transfer2bert():\n with open('roto-ie.dict', 'r') as fr:\n roto_vocab = {}\n for line in fr.readlines():\n w, i = line.strip().split()\n roto_vocab[int(i)] = w\n with open('data/bert-base-cased-vocab.txt', 'r') as fr:\n bert_vocab = {}\n for i, line in enumerate(fr.readlines()):\n w = line.strip()\n bert_vocab[i] = w\n fr = open('roto-ie.h5', 'rb')\n h5fi = h5py.File(fr, 'r')\n for data_type in ['tr', 'val', 'test']:\n start = time.time()\n print(h5fi['%ssents'%data_type].shape)\n sents = h5fi['%ssents'%data_type]\n numdists = h5fi['%snumdists'%data_type]\n entdists = h5fi['%sentdists'%data_type]\n new_sents = [] \n new_nums = []\n new_ents = []\n new_lengths = []\n max_len = 0\n for sent, num, ent in zip(sents, numdists, entdists):\n new_sent_idxs = [CLS]\n new_num = [num[0] - 1]\n new_ent = [ent[0] - 1]\n ws = ' '.join([roto_vocab[w] for w in sent if w != -1])\n print(ws) \n print(tokenizer.encode(ws, add_special_tokens=False))\n for idx, num_dist, ent_dist in zip(sent, num, ent):\n if idx != -1:\n w = roto_vocab[idx]\n new_w = tokenizer.encode(w, add_special_tokens=False)\n new_sent_idxs.extend(new_w)\n print(w, [bert_vocab[i] for i in new_w])\n new_num.extend([num_dist for _ in new_w])\n new_ent.extend([ent_dist for _ in new_w])\n new_num.append(new_num[-1] + 1)\n new_ent.append(new_ent[-1] + 1)\n new_sent_idxs.append(SEP)\n print(new_sent_idxs)\n exit()\n if len(new_sent_idxs) > max_len:\n max_len = len(new_sent_idxs)\n new_sents.append(new_sent_idxs)\n new_nums.append(new_num)\n new_ents.append(new_ent)\n assert len(new_sent_idxs) == len(new_num) and len(new_num) == len(new_ent)\n new_lengths.append(len(new_sent_idxs))\n # add [PAD]\n for i in range(len(new_sents)):\n new_sents[i] += [0 for _ in range(max_len - len(new_sents[i]))]\n new_nums[i] += [new_nums[i][-1] + j + 1 for j in range(max_len - len(new_nums[i]))]\n new_ents[i] += [new_ents[i][-1] + j + 1 for j in range(max_len - len(new_ents[i]))]\n print(time.time() - start)\n print('%s is finished'%data_type)\n h5fi.close()\n\nif __name__ == '__main__':\n #w = \"Belinelli\"\n #print(tokenizer.encode(w, add_special_tokens=False))\n # add_tokens()\n #print(tokenizer.encode(w, add_special_tokens=False))\n transfer2bert()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"573402205","text":"import sys\ninput = sys.stdin.readline\n# 시작 1시 17분\n# 코드생각시간 1시 27분\n# 코드만드는시간 1시 ??분\n# 디버깅시간 1시 49분 \n# 한번더 풀때는 visited로 사용해볼것! 어떨진 모르겠음..\nNUMBER = 0\nCOMBIN = 0\n\n\ndef permutation(numbers, seq, count):\n global NUMBER\n global COMBIN\n if len(seq) == COMBIN:\n print(*seq)\n return\n for _ in range(1, len(numbers)+1):\n num = numbers.pop(0)\n seq.append(num)\n sorted_numbers = sorted(numbers)\n permutation(sorted_numbers, seq, count)\n numbers.append(num)\n seq.pop()\n\n\ndef main():\n global NUMBER\n global COMBIN\n NUMBER, COMBIN = map(int, input().strip().split())\n permutation(list(range(NUMBER+1))[1:], [], 0)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"solve/Backtracking/15649_NM_nPm.py","file_name":"15649_NM_nPm.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"187813165","text":"import sys\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtWebKit import *\r\n\r\nclass Browser(QMainWindow):\r\n def __init__(self):\r\n QMainWindow.__init__(self)\r\n\r\n # Create the QWebView\r\n self.view = QWebView(self)\r\n self.view.load(QUrl(\"http://www.example.com\"))\r\n self.setCentralWidget(self.view)\r\n\r\n # Add the \"Go Back\" button\r\n back_button = QPushButton(\"Go Back\", self)\r\n back_button.clicked.connect(self.go_back)\r\n back_button.setEnabled(False)\r\n\r\n # Add the \"Go Forward\" button\r\n forward_button = QPushButton(\"Go Forward\", self)\r\n forward_button.clicked.connect(self.go_forward)\r\n forward_button.setEnabled(False)\r\n\r\n # Add the URL bar\r\n self.url_bar = QLineEdit(self)\r\n self.url_bar.returnPressed.connect(self.load_url)\r\n\r\n # Add the Refresh button\r\n refresh_button = QPushButton(\"Refresh\", self)\r\n refresh_button.clicked.connect(self.refresh)\r\n\r\n # Add the buttons to a QToolBar\r\n tool_bar = QToolBar(self)\r\n tool_bar.addWidget(back_button)\r\n tool_bar.addWidget(forward_button)\r\n tool_bar.addWidget(self.url_bar)\r\n tool_bar.addWidget(refresh_button)\r\n\r\n # Add the tool bar to the main window\r\n self.addToolBar(tool_bar)\r\n\r\n # Connect the \"url_changed\" signal to the \"update_url_bar\" slot\r\n self.view.urlChanged.connect(self.update_url_bar)\r\n\r\n # Connect the \"title_changed\" signal to the \"update_title\" slot\r\n self.view.titleChanged.connect(self.update_title)\r\n\r\n # Connect the \"load_started\" signal to the \"load_started\" slot\r\n self.view.loadStarted.connect(self.load_started)\r\n\r\n # Connect the \"load_finished\" signal to the \"load_finished\" slot\r\n self.view.loadFinished.connect(self.load_finished)\r\n\r\n def go_back(self):\r\n self.view.back()\r\n\r\n def go_forward(self):\r\n self.view.forward()\r\n\r\n def load_url(self):\r\n url = self.url_bar.text()\r\n if not url.startswith(\"http://\") and not url.startswith(\"https://\"):\r\n url = \"http://\" + url\r\n self.view.load(QUrl)\r\n","sub_path":"MyBrowser.py","file_name":"MyBrowser.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"172580112","text":"#!/usr/bin/env python\n\n'''\nDISTRIBUTION STATEMENT A. Approved for public release: distribution unlimited.\n\nThis material is based upon work supported by the Assistant Secretary of Defense for\nResearch and Engineering under Air Force Contract No. FA8721-05-C-0002 and/or\nFA8702-15-D-0001. Any opinions, findings, conclusions or recommendations expressed in this\nmaterial are those of the author(s) and do not necessarily reflect the views of the\nAssistant Secretary of Defense for Research and Engineering.\n\nCopyright 2017 Massachusetts Institute of Technology.\n\nThe software/firmware is provided to you on an As-Is basis\n\nDelivered to the US Government with Unlimited Rights, as defined in DFARS Part\n252.227-7013 or 7014 (Feb 2014). Notwithstanding any copyright notice, U.S. Government\nrights in this work are defined by DFARS 252.227-7013 or DFARS 252.227-7014 as detailed\nabove. Use of this work other than as specifically authorized by the U.S. Government may\nviolate any copyrights that exist in this work.\n'''\n\nimport time\nimport os\nimport configparser\n\nimport keylime.tornado_requests as tornado_requests\nimport keylime.ca_util as ca_util\nimport keylime.secure_mount as secure_mount\nimport keylime.common as common\nimport keylime.keylime_logging as keylime_logging\n\n# read the config file\nconfig = configparser.RawConfigParser()\nconfig.read(common.CONFIG_FILE)\n\nlogger = keylime_logging.init_logging('update_crl')\n\ndef execute(json_revocation):\n if json_revocation['type']!='revocation':\n return\n\n secdir = secure_mount.mount()\n\n cert_path = config.get('cloud_agent','revocation_cert')\n if cert_path == \"default\":\n cert_path = '%s/unzipped/RevocationNotifier-cert.crt'%(secdir)\n else:\n # if it is a relative, convert to absolute in work_dir\n if cert_path[0]!='/':\n cert_path = os.path.abspath('%s/%s'%(common.WORK_DIR,cert_path))\n if not os.path.exists(cert_path):\n raise Exception(\"revocation_cert %s not found\"%(os.path.abspath(cert_path)))\n\n # get the updated CRL\n dist_path = ca_util.get_crl_distpoint(cert_path)\n\n\n with open(\"%s/unzipped/cacrl.der\"%(secdir),\"rb\") as f:\n oldcrl = f.read()\n\n updated = False\n for i in range(10):\n logger.debug(\"Getting updated CRL from %s\"%dist_path)\n response = tornado_requests.request(\"GET\", dist_path, None, None, None)\n if response.status_code !=200:\n logger.warn(\"Unable to get updated CRL from %s. Code %d\"%(dist_path,response.status_code))\n time.sleep(1)\n continue\n if response.body == oldcrl:\n logger.warn(\"CRL not yet updated, trying again in 1 second...\")\n time.sleep(1)\n continue\n\n # write out the updated CRL\n logger.debug(\"Updating CRL in %s/unzipped/cacrl.der\"%(secdir))\n with open(\"%s/unzipped/cacrl.der\"%(secdir),\"w\") as f:\n f.write(response.body)\n ca_util.convert_crl_to_pem(\"%s/unzipped/cacrl.der\"%(secdir), \"%s/unzipped/cacrl.pem\"%secdir)\n updated = True\n break\n\n if not updated:\n logger.error(\"Unable to load new CRL from %s after receiving notice of a revocation\"%dist_path)\n","sub_path":"keylime/revocation_actions/update_crl.py","file_name":"update_crl.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"384669325","text":"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.linear_model import LogisticRegression\r\nimport pickle\r\ndef data_split(heart, ratio):\r\n np.random.seed(42)\r\n shuffled = np.random.permutation(len(heart))\r\n test_set_size = int(len(heart) * ratio)\r\n test_indices = shuffled[:test_set_size]\r\n train_indices = shuffled[test_set_size:]\r\n return heart.iloc[train_indices], heart.iloc[test_indices]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n df = pd.read_csv('heart.csv')\r\n train, test = data_split(df, 0.3)\r\n X_train = train[['age','sex','cp','trestbps','chol','fbs','restecg','thalach','exang','oldpeak','slope','ca','thal']].to_numpy()\r\n X_test = test[['age','sex','cp','trestbps','chol','fbs','restecg','thalach','exang','oldpeak','slope','ca','thal']].to_numpy()\r\n Y_train = train[['target']].to_numpy().reshape(229 ,)\r\n Y_test = test[['target']].to_numpy().reshape(97 ,)\r\n clf = LogisticRegression(solver='liblinear')\r\n clf.fit(X_train, Y_train)\r\n file = open('model.pkl', 'wb')\r\n pickle.dump(clf, file)\r\n file.close()","sub_path":"myTraining.py","file_name":"myTraining.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"634057376","text":"import json\n\nimport requests\n\napi_key = \"46d6a53307e9d13813f5af71d1f8db3c\"\nurl = \"http://api.openweathermap.org/data/2.5/\" \"weather?units=metric&q={q}&appid={key}\"\n\na = str(input(\"県名(ローマ字)をいれてください:\"))\ncity = a\nurl1 = url.format(q=city, key=api_key)\nresponse = requests.get(url1)\ndata = response.json()\n\njsontext = json.dumps(data, indent=4)\n\nprint(jsontext)\n","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"309227554","text":"# This script is just the names conversion from spanish to english\nimport pandas as pd\n\ndf = pd.read_csv('../Lesson-01 - Intro to Python & Scraping example/deptos.csv')\n\ncols = {'Ambientes':'rooms', 'Antigüedad':'age', 'Baños':'bath', \n 'Departamentos por piso':'aparment_floor', \n 'Disposición':'view', 'Dormitorios':'bedrooms',\n 'Expensas':'expenses', \n 'Piso (unidad)':'floor', 'Pisos':'nbr_floors', \n 'Superficie cubierta':'covered area', \n 'Superficie total':'total_area',\n 'Tipo de departamento':'type', 'address':'address', \n 'price':'price', 'neighborhood':'neighborhood'}\n\ndf.rename(columns=cols, inplace=True)\n\ndf = df[['rooms', 'age', 'bath', 'neighborhood',\n 'aparment_floor', 'view', 'bedrooms', \n 'expenses', 'floor', 'nbr_floors',\n 'covered area', 'total_area', 'type', 'address', 'price']]\n\ndf.to_csv('deptos_eng.csv', index=False)\n","sub_path":"Lesson-03 - Data manipulation with Pandas /.ipynb_checkpoints/change_column_names-checkpoint.py","file_name":"change_column_names-checkpoint.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"521027308","text":"from django.contrib import admin\n\n# Register your models here.\n# vim: set fileencoding=utf-8 :\nfrom django.contrib import admin\n\nfrom . import models\n\n\nclass ClientAdmin(admin.ModelAdmin):\n\n list_display = (\n 'id',\n 'ip',\n 'pays',\n 'ville',\n 'continent',\n 'longitude',\n 'latitude',\n 'reseau',\n )\n list_filter = (\n 'id',\n 'ip',\n 'pays',\n 'ville',\n 'continent',\n 'longitude',\n 'latitude',\n 'reseau',\n )\n\n\ndef _register(model, admin_class):\n admin.site.register(model, admin_class)\n\n\n_register(models.Client, ClientAdmin)\n","sub_path":"feliciano/statictiques/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"94499794","text":"#!/bin/python\nimport os\nimport datetime\nfrom flask import Flask\n\napp = Flask(__name__)\napp.config.from_pyfile(\"config.cfg\")\n\nfor dirpath, dirnames, filenames in os.walk(os.path.curdir + \"/\" + app.config[\"DOCUMENT_FOLDER\"]):\n\tfor file in filenames:\n\t\tpath = os.path.join(dirpath, file)\n\n\t\t# Ignore symbolic links\n\t\tif os.path.islink(path):\n\t\t\tcontinue\n\n\t\tfile_modified = datetime.datetime.fromtimestamp(os.path.getmtime(path))\n\t\tif datetime.datetime.now() - file_modified > datetime.timedelta(seconds=app.config[\"EXPIRATION_PERIOD\"]):\n\t\t\tos.remove(path)","sub_path":"clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"407664604","text":"'''\n squeue.py 队列的顺序存储\n'''\n\n# 思路分析:\n# 1.基于列表完成数据的存储\n# 2.通过封装功能完成对队列的基本行为\n# 3.无论在那边作为队头或队尾 都会在操作中有内存移动\n\n#自定义异常\nclass QueueError(Exception):\n pass\n\n#队列操作\nclass SQueue:\n def __init__(self):\n self._elems = []\n\n #判断队列是否为空\n def is_emty(self):\n return self._elems == []\n\n #入队\n def enqueue(self,val):\n self._elems.append(val)\n\n #出队\n def dequeue(self):\n if self.is_emty():\n raise QueueError('Queue is empty')\n return self._elems.pop(0)\n\n\n#\nif __name__ == '__main__':\n sq = SQueue()\n sq.enqueue(10)\n sq.enqueue(20)\n sq.enqueue(30)\n while not sq.is_emty():\n print(sq.dequeue())\n\n","sub_path":"pytnon-month02/month02-class notes/day02_fanb/squeue.py","file_name":"squeue.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"258996387","text":"\"\"\"\n\n\"\"\"\nimport os\nimport dj_database_url\n\n\nDEBUG = False\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '+&gd3v557^(*6+q3me9&!qc5mc^5z2vslqsr)1cex-485u3fvc'\nALLOWED_HOSTS = ['wailing-trees.herokuapp.com', 'wailing-trees.s3.amazonaws.com', '*']\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.9/howto/static-files/\n\n\nSTATICFILES_DIRS = [\n\tos.path.join(BASE_DIR, 'wt/wt/static'),\n]\n################################################################\n# optional AWS S3 cache : COMMENT IT IF I HAVE [WinError 10054]\nAWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires\n\t'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',\n\t'Cache-Control': 'max-age=94608000',\n}\n\nAWS_STORAGE_BUCKET_NAME = 'wailing-trees'\nAWS_ACCESS_KEY_ID = 'AKIAI2MJLYGYK72HZIEQ'\nS3_REGION_NAME = 'eu-west-1'\nAWS_SECRET_ACCESS_KEY = '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'\nAWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME\nAWS_QUERYSTRING_AUTH = False # without this CKE upload/download does'nt work with S3\n\n# MEDIA_ROOT = os.path.join(BASE_DIR, 'wt/media/')\n# MEDIA_ROOT = os.path.join(BASE_DIR, 'wt/wt/media/')\nMEDIA_ROOT = 'media'\nSTATICFILES_LOCATION = 'static'\nMEDIAFILES_LOCATION = 'media'\nCKEDITOR_UPLOAD_LOCATION = 'uploads/'\n\nfrom django.conf import settings\nfrom storages.backends.s3boto import S3BotoStorage\n\nclass StaticStorage(S3BotoStorage):\n\tlocation = STATICFILES_LOCATION\n\nclass MediaStorage(S3BotoStorage):\n\tlocation = MEDIAFILES_LOCATION\n\n\nSTATICFILES_STORAGE = 'custom_storage.StaticStorage'\nDEFAULT_FILE_STORAGE = 'custom_storage.MediaStorage'\n# CKEDITOR_UPLOAD_PATH = 'custom_storage.CkeStorage'\n\nSTATIC_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)\nMEDIA_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)\n# CKEDITOR_UPLOAD_PATH = \"https://%s/%s/%s\" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION, CKEDITOR_UPLOAD_LOCATION)\n# DEFAULT_FILE_STORAGE = 'custom_storage.MediaStorage'\n\n\nCKEDITOR_UPLOAD_PATH = 'uploads'\nCKEDITOR_IMAGE_BACKEND = 'pillow'\nCKEDITOR_BROWSE_SHOW_DIRS = True\nCKEDITOR_CONFIGS = {\n\t'default': {\n\t\t'toolbar': [\n\t\t\t[\"Format\", \"Bold\", \"Italic\", \"Underline\", \"Strike\", \"SpellChecker\"],\n\t\t\t['NumberedList', 'BulletedList', \"Indent\", \"Outdent\", 'JustifyLeft',\n\t\t\t\t\t\t'JustifyCenter', 'JustifyRight', 'JustifyBlock'],\n\t\t\t[\"HorizontalRule\",],\n\t\t\t[\"Image\", \"Table\", \"Link\", \"Unlink\", \"Anchor\", \"SectionLink\",],\n\t\t\t['Undo', 'Redo'], [\"Source\"],\n\t\t\t[\"Maximize\"]],\n\t\t'extraAllowedContent': 'iframe[*]',\n\t\t# \"removePlugins\": \"stylesheetparser\",\n\t},\n}\nCKEDITOR_BROWSE_SHOW_DIRS = True","sub_path":"wt/settings/prod.py","file_name":"prod.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"95356998","text":"\"\"\"Utils for direct upload to AWS S3.\"\"\"\nfrom base64 import b64encode\nfrom datetime import timedelta\nimport hashlib\nimport hmac\nimport json\n\nfrom django.conf import settings\nfrom django.utils import timezone\n\nfrom ..defaults import AWS_UPLOAD_EXPIRATION_DELAY, VIDEO_SOURCE_MAX_SIZE\nfrom ..utils.time_utils import to_timestamp\n\n\ndef sign(key, message):\n \"\"\"Return a SHA256 hmac updated with the message.\n\n Parameters\n ----------\n key : string\n The starting key for the hash.\n message : string\n The message being hashed into the hmac object\n\n Returns\n -------\n string\n The hash value resulting from the SHA256 hash of the message.\n\n \"\"\"\n return hmac.new(key, message.encode(\"utf-8\"), hashlib.sha256).digest()\n\n\ndef get_signature_key(secret_key, date_stamp, region_name, service_name):\n \"\"\"AWS Signature v4 Key derivation function.\n\n We need an algorithm to generate a signing key to sign our policy document. In signature\n version 4, the signing key is derived from the secret access key, which improves the security\n of the secret access key.\n\n Parameters\n ----------\n secret_key : string\n The key to be signed\n date_stamp : string\n The date at which the policy is signed with a format \"%Y%m%d\"\n region_name : string\n The AWS region name\n service_name : string\n The AWS service name\n\n Returns\n -------\n string\n Hash value representing the AWS v4 signature.\n\n See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html\n\n \"\"\"\n k_date = sign((\"AWS4\" + secret_key).encode(\"utf-8\"), date_stamp)\n k_region = sign(k_date, region_name)\n k_service = sign(k_region, service_name)\n k_signing = sign(k_service, \"aws4_request\")\n return k_signing\n\n\ndef get_s3_policy(bucket, video):\n \"\"\"Build a S3 policy to allow uploading a video to our video source bucket.\n\n Parameters\n ----------\n bucket : string\n The name of the S3 bucket to which we want to upload a video.\n video : Type[models.Model]\n The video object for which we want to upload a video file.\n\n Returns\n -------\n Tuple[string, string]\n A tuple of the policy and its signature both encoded in b64.\n\n \"\"\"\n now = timezone.now()\n stamp = str(to_timestamp(now))\n key = video.get_source_s3_key(stamp=stamp)\n\n expires_at = now + timedelta(seconds=AWS_UPLOAD_EXPIRATION_DELAY)\n acl = \"private\"\n x_amz_algorithm = \"AWS4-HMAC-SHA256\"\n x_amz_credential = \"{key:s}/{date:%Y%m%d}/{region:s}/s3/aws4_request\".format(\n date=now, key=settings.AWS_ACCESS_KEY_ID, region=settings.AWS_DEFAULT_REGION\n )\n x_amz_date = now.strftime(\"%Y%m%dT%H%M%SZ\")\n\n policy = {\n \"expiration\": expires_at.strftime(\"%Y-%m-%dT%H:%M:%S.000Z\"),\n \"conditions\": [\n {\"bucket\": bucket},\n {\"key\": key},\n {\"acl\": acl},\n [\"starts-with\", \"$Content-Type\", \"video/\"],\n [\"content-length-range\", 0, VIDEO_SOURCE_MAX_SIZE],\n {\"x-amz-credential\": x_amz_credential},\n {\"x-amz-algorithm\": x_amz_algorithm},\n {\"x-amz-date\": x_amz_date},\n [\"starts-with\", \"$x-amz-meta-jwt\", \"\"],\n ],\n }\n\n policy_b64 = b64encode(\n json.dumps(policy).replace(\"\\n\", \"\").replace(\"\\r\", \"\").encode()\n )\n\n signature_key = get_signature_key(\n settings.AWS_SECRET_ACCESS_KEY,\n now.strftime(\"%Y%m%d\"),\n settings.AWS_DEFAULT_REGION,\n \"s3\",\n )\n\n signature = hmac.new(signature_key, policy_b64, hashlib.sha256).hexdigest()\n\n return {\n \"acl\": acl,\n \"bucket\": bucket,\n \"stamp\": stamp,\n \"key\": key,\n \"max_file_size\": VIDEO_SOURCE_MAX_SIZE,\n \"policy\": policy_b64,\n \"s3_endpoint\": get_s3_endpoint(settings.AWS_DEFAULT_REGION),\n \"x_amz_algorithm\": x_amz_algorithm,\n \"x_amz_credential\": x_amz_credential,\n \"x_amz_date\": x_amz_date,\n \"x_amz_expires\": AWS_UPLOAD_EXPIRATION_DELAY,\n \"x_amz_signature\": signature,\n }\n\n\ndef get_s3_endpoint(region):\n \"\"\"Return the S3 endpoint domain for the region.\n\n Parameters\n ----------\n region : string\n One of the regions among Amazon AWS hosting regions (e.g. \"us-east-1\").\n\n Returns\n -------\n string\n The full domain of the S3 endpoint for the region passed in argument.\n\n \"\"\"\n if region == \"us-east-1\":\n return \"s3.amazonaws.com\"\n return \"s3.{:s}.amazonaws.com\".format(region)\n","sub_path":"marsha/core/utils/s3_utils.py","file_name":"s3_utils.py","file_ext":"py","file_size_in_byte":4527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"184178663","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\nThe difference from HD36051_2set.py is to use P*100 for MCMC sampling \n'''\n\n#==============================================================================\n# Import data \n#==============================================================================\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nstar = 'HD36051'\nDIR = '/Volumes/DataSSD/OneDrive - UNSW/Hermite_Decomposition/ESO_HARPS/' + star\nMJD = np.loadtxt(DIR + '/MJD.dat')\nRV_HARPS= np.loadtxt(DIR + '/RV_HARPS.dat') * 1000\nRV_noise= np.loadtxt(DIR + '/RV_noise.dat')\n\n# convert to x, y, yerr\nx = MJD\ny = RV_HARPS - np.mean(RV_HARPS)\nyerr = RV_noise\n\nif 0:\n plt.figure()\n plt.errorbar(x, y, yerr=yerr, fmt=\".k\", capsize=0, alpha=0.5, label='HARPS RV')\n # plt.errorbar(x, jitter, yerr=yerr, fmt=\".r\", capsize=0, alpha=0.5, label='jitter')\n plt.ylabel(\"RV [m/s]\")\n plt.xlabel(\"MJD [days]\")\n plt.legend()\n plt.savefig('../../output/'+star+'/'+star+'-0-RV.png')\n plt.show()\n\n#==============================================================================\n# Periodogram\n#==============================================================================\nif 0:\n\n from astropy.stats import LombScargle\n\n min_f = 0.0001\n max_f = 5\n spp = 20 # spp=1000 will take a while; for quick results set spp = 10\n\n frequency0, power0 = LombScargle(x, y, yerr).autopower(minimum_frequency=min_f,\n maximum_frequency=max_f,\n samples_per_peak=spp)\n\n frequency1, power1 = LombScargle(x, jitter, yerr).autopower(minimum_frequency=min_f,\n maximum_frequency=max_f,\n samples_per_peak=spp)\n\n\n ax = plt.subplot(111)\n # ax.axvline(x=17, color='k', ls='-.')\n plt.plot(1/frequency0, power0, label='HARPS RV', ls='-', alpha=0.5)\n plt.plot(1/frequency1, power1, label='jitter', ls='--', alpha=0.5)\n plt.xlim(0, 1/min_f)\n plt.xlabel(\"Period\")\n plt.ylabel(\"Power\")\n plt.legend()\n plt.savefig('../../output/'+star+'/'+star+'-Periodogram.png')\n plt.show()\n\n#==============================================================================\n# Model\n#==============================================================================\n\nimport matplotlib.pyplot as plt\nfrom rv import solve_kep_eqn\nfrom celerite.modeling import Model\nimport math\n\n\nclass Model(Model):\n parameter_names = ('P', 'tau', 'k', 'w', 'e0', 'offset1', 'offset2')\n\n def get_value(self, t):\n M_anom = 2*np.pi/(self.P*100) * (t - self.tau)\n e_anom = solve_kep_eqn(M_anom, self.e0)\n f = 2*np.arctan( np.sqrt((1+self.e0)/(1-self.e0))*np.tan(e_anom*.5) )\n rv = self.k * (np.cos(f + self.w) + self.e0*np.cos(self.w))\n\n offset = np.zeros(len(t))\n for i in range(len(t)):\n if t[i]<57161:\n offset[i] = self.offset1\n else:\n offset[i] = self.offset2\n\n return rv + offset\n\n# The dict() constructor builds dictionaries directly from sequences of key-value pairs:\nP = 5.5/100\ntau = 3.\ne = 0.086\noffset1 = 0.\noffset2 = 0.\nk = 30\nw = 262 / 360 * 2 * np.pi\n\nguess = dict(P=P, tau=tau, k=k, w=w, e0=e, offset1=offset1, offset2=offset2)\n\n\n#==============================================================================\n# MCMC\n#==============================================================================\n# Define the posterior PDF\n# Reminder: post_pdf(theta, data) = likelihood(data, theta) * prior_pdf(theta)\n# We take the logarithm since emcee needs it.\n\n# As prior, we assume an 'uniform' prior (i.e. constant prob. density)\n\ndef lnprior(theta):\n P, tau, k, w, e0, offset1, offset2 = theta\n if (0 < P) and (0 < k) and (0 < w < 2*np.pi) and (0. < e0 < 0.8):\n return 0.0\n return -np.inf\n\n# As likelihood, we assume the chi-square. Note: we do not even need to normalize it.\ndef lnlike(theta, x, y, yerr):\n P, tau, k, w, e0, offset1, offset2 = theta\n fit_curve = Model(P=P, tau=tau, k=k, w=w, e0=e0, offset1=offset1, offset2=offset2)\n y_fit = fit_curve.get_value(np.array(x))\n return -0.5*(np.sum( ((y-y_fit)/yerr)**2. ))\n\ndef lnprob(theta, x, y, yerr):\n lp = lnprior(theta)\n if not np.isfinite(lp):\n return -np.inf\n return lp + lnlike(theta, x, y, yerr) \n\n\nimport emcee\nndim = len(guess)\nnwalkers = 32\nsampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(x, y, yerr), threads=14)\ninitial = [P, tau, k, w, e, offset1, offset2]\n\nimport time\ntime_start = time.time()\n\nprint(\"Running 1st burn-in...\")\np0 = initial + 1e-4 * np.random.randn(nwalkers, ndim)\np0, lp, _ = sampler.run_mcmc(p0, 2000)\n\nprint(\"Running 2nd burn-in...\")\np0 = p0[np.argmax(lp)] + 1e-4 * np.random.randn(nwalkers, ndim)\np0, _, _ = sampler.run_mcmc(p0, 2000)\n\nprint(\"Running 3rd burn-in...\")\np0 = p0[np.argmax(lp)] + 1e-4 * np.random.randn(nwalkers, ndim)\np0, _, _ = sampler.run_mcmc(p0, 2000)\n\nprint(\"Running 4th burn-in...\")\np0 = p0[np.argmax(lp)] + 1e-4 * np.random.randn(nwalkers, ndim)\np0, _, _ = sampler.run_mcmc(p0, 2000)\n\n# print(\"Running 5th burn-in...\")\n# p0 = p0[np.argmax(lp)] + 1e-4 * np.random.randn(nwalkers, ndim)\n# p0, _, _ = sampler.run_mcmc(p0, 2000)\n\nprint(\"Running production...\")\np0 = p0[np.argmax(lp)] + 1e-3 * np.random.randn(nwalkers, ndim)\nsampler.run_mcmc(p0, 500); \n\n\ntime_end = time.time()\nprint('\\nRuntime = %.2f seconds' %(time_end - time_start))\n\n\n\n\n#==============================================================================\n# Trace and corner plots \n#==============================================================================\n\nimport copy\nlog_samples = sampler.chain[:, 15000:, :].reshape((-1, ndim))\nreal_samples = copy.copy(log_samples)\nreal_samples[:,0] = 100*real_samples[:,0]\n\n\nfig, axes = plt.subplots(ndim, figsize=(10, 7), sharex=True)\nlabels_log=[r\"$P$\", r\"$T_{0}$\", r\"$K$\", r\"$\\omega$\", r\"$e$\", \n \"offset1\", \"offset2\"]\nfor i in range(ndim):\n ax = axes[i]\n ax.plot( np.rot90(sampler.chain[:, :, i], 3), \"k\", alpha=0.3)\n ax.set_xlim(0, sampler.chain.shape[1])\n ax.set_ylabel(labels_log[i])\n ax.yaxis.set_label_coords(-0.1, 0.5)\n\naxes[-1].set_xlabel(\"step number\");\nplt.savefig('../../output/HD36051/36051_MCMC_-Trace.png')\nplt.show()\n\n\nimport corner\nlabels=[r\"$P$\", r\"$T_{0}$\", r\"$K$\", r\"$\\omega$\", r\"$e$\", \"offset1\", \"offset2\"]\nfig = corner.corner(real_samples, labels=labels, quantiles=[0.16, 0.5, 0.84], show_titles=True)\nplt.savefig('../../output/HD36051/36051_MCMC-Corner.png')\nplt.show()\n\n\n#==============================================================================\n# Output\n#==============================================================================\n\na0, a1, a2, a3, a4, a5, a6 = map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]), zip(*np.percentile(real_samples, [16, 50, 84], axis=0)))\naa = np.zeros((len(guess),3))\naa[0,:] = [a0[i] for i in range(3)]\naa[1,:] = [a1[i] for i in range(3)]\naa[2,:] = [a2[i] for i in range(3)]\naa[3,:] = [a3[i] for i in range(3)]\naa[4,:] = [a4[i] for i in range(3)]\naa[5,:] = [a5[i] for i in range(3)]\naa[6,:] = [a6[i] for i in range(3)]\nnp.savetxt('../../output/HD36051/36051_MCMC_result.txt', aa, fmt='%.6f')\n\n\nP, tau, k, w, e0, offset1, offset2 = aa[:,0]\nfit_curve = Model(P=P/100, tau=tau, k=k, w=w, e0=e0, offset1=offset1, offset2=offset2)\ny_fit = fit_curve.get_value(np.array(x))\n\n\nplt.figure()\nplt.errorbar(x, y_fit, yerr=yerr, fmt=\".\", capsize=0, label='MCMC fit')\nplt.errorbar(x, y, yerr=yerr, fmt=\".\", capsize=0, label='HARPS')\nplt.ylabel(\"RV [m/s]\")\nplt.xlabel(\"MJD\")\nplt.legend(loc=\"upper center\")\nplt.savefig('../../output/HD36051/36051_MCMC_fit.png')\nplt.show()\n\ncompanion = fit_curve.get_value(np.array(x))\nresidual = np.array(y) - companion\nchi2 = sum(residual**2 / np.array(yerr)**2) / (len(x)-len(guess))\nrms = np.sqrt(np.mean(residual**2))\nwrms = np.sqrt(sum((residual/yerr)**2)/sum(1/yerr**2))\n\n\n\n# plot residuals \nplt.figure()\nplt.errorbar(x, residual, yerr=yerr, fmt=\".\", capsize=0, label='HARPS', alpha=0.5)\nplt.ylabel(\"Residual [m/s]\")\nplt.xlabel(\"MJD [day]\")\nplt.legend(loc=\"upper center\")\nplt.savefig('../../output/HD36051/36051_residual.png')\nplt.show()\n\n# np.savetxt('/Volumes/DataSSD/MATLAB_codes/0816-FT-multiple_stars/' + star + '/BI.txt', companion)\n\n\n","sub_path":"1002-multi_discoveries/code/HD36051/archived/HD36051_2set2.py","file_name":"HD36051_2set2.py","file_ext":"py","file_size_in_byte":8484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"169381338","text":"import numpy as np\nimport math\nimport pandas as pd\nimport sys\n\ndef get_split_index(A):\n i = len(A) - 1\n while i > 0:\n if A[i] < A[i - 1]:\n i -= 1\n else:\n break\n return i - 1\n\n\ndef get_change_index(A, i):\n j = len(A) - 1\n while j >= i:\n if A[j] > A[i]:\n break\n else:\n j -= 1\n return j\n\n\ndef swap(A, i, j):\n A[i], A[j] = (A[j], A[i])\n\n\ndef reverse(A, start):\n left = start\n right = len(A) - 1\n while left < right:\n swap(A, left, right)\n left += 1\n right -= 1\n\n\ndef next_permutation(A):\n split_index = get_split_index(A)\n # the Array is sorted in descreased order\n if split_index == -1:\n reverse(A, 0)\n else:\n change_index = get_change_index(A, split_index)\n swap(A, split_index, change_index)\n reverse(A, split_index + 1)\n\n\ndef factorial(n):\n ans = 1\n for i in range(2, n + 1):\n ans *= i\n return ans\n\n\ndef permutations(d):\n a = []\n for j in range(d):\n a.append(j + 1)\n perm = dict()\n perm[str(a)] = 0\n for j in range(factorial(d) - 1):\n next_permutation(a)\n perm[str(a)] = j + 1\n return perm\n\n\ndef s_max(d):\n return math.log(factorial(d))\n\n\ndef s_max_list(d):\n return [1 / factorial(d)] * factorial(d)\n\n\ndef pi(arr, d):\n pr = [0] * factorial(d)\n permutation_dict = permutations(d)\n for i in range(d - 1, len(arr)):\n curr = []\n curr_perm = []\n for j in range(i - d + 1, i + 1):\n curr.append([arr[j], len(curr) + 1])\n curr.sort()\n for k in curr:\n curr_perm.append(k[1])\n pr[permutation_dict[str(curr_perm)]] += 1\n for i in range(len(pr)):\n pr[i] /= len(arr) - d + 1\n return pr\n\n\ndef si(pr):\n entropy = 0\n for i in range(len(pr)):\n if pr[i] != 0:\n entropy -= pr[i] * math.log(pr[i])\n return entropy\n\ndef q_0_calculation(d):\n pr = [0] * factorial(d)\n pr[0] = 1\n b = s_max_list(d)\n b = [pr + b for pr, b in zip(pr, b)]\n b = [i * 0.5 for i in b]\n return 1 / (si(b) - si(pr) / 2 - s_max(d) / 2)\n\ndef q_j(arr, d):\n pr = pi(arr, d)\n b = s_max_list(d)\n b = [pr + b for pr, b in zip(pr, b)]\n b = [i * 0.5 for i in b]\n return q_0_calculation(d) * (si(b) - si(pr) / 2 - s_max(d) / 2)\n\ndef entropy_measure(arr, d):\n return si(pi(arr, d))/s_max(d)\n\ndef mpr_complexity(arr, entropy_measure, d):\n return q_j(arr, d) * entropy_measure\n\nfilename = sys.argv[1]\nxs = np.loadtxt(filename)\nentropy_measure = entropy_measure(xs, 4)\n\nprint(\"Entropy = \", entropy_measure)\nprint(\"Compleixty = \", mpr_complexity(xs, entropy_measure, 4))\n\n\n","sub_path":"calc_entropy.py","file_name":"calc_entropy.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"546324419","text":"import csv\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom keras.models import Sequential\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.layers import Flatten, Dense, Lambda, Cropping2D, Convolution2D, ELU, Dropout\n\n\ndef readCsv():\n lines = []\n \n with open('data/driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n lines.append(line)\n return lines\n\n\ndef flip(center_image, center_angle):\n return np.fliplr(center_image), -center_angle\n\n\ndef get_image_atAngle(filepath, center_angle, param):\n correction = 0.25\n new_image = mpimg.imread(filepath)\n # new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB)\n\n if param == 'right':\n new_angle = center_angle - correction\n else:\n new_angle = center_angle + correction\n\n return new_image, new_angle\n\n\ndef data_generator(samples, batch_size=32):\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset + batch_size]\n\n images = []\n angles = []\n for batch_sample in batch_samples:\n \n ######################ADD CENTER IMAGE FIRST #########################################\n \n center_img_path = './data/IMG/' + batch_sample[0].split('/')[-1]\n center_image = mpimg.imread(center_img_path)\n # center_image = cv2.cvtColor(center_image, cv2.COLOR_BGR2RGB)\n center_angle = float(batch_sample[3])\n images.append(center_image)\n angles.append(center_angle)\n \n #######################################################################################\n\n ###################### ADD OTHER CAMERA IMAGES ########################################\n \n left_img_path = './data/IMG/' + batch_sample[1].split('/')[-1]\n right_img_path = './data/IMG/' + batch_sample[2].split('/')[-1]\n \n left_image = mpimg.imread(left_img_path) \n left_image_angle = float(batch_sample[3]) + 0.25\n\n right_image = mpimg.imread(right_img_path) \n right_image_angle = float(batch_sample[3]) - 0.25\n \n #left_image,left_image_angle = get_image_atAngle(right_img_path,center_angle,'left')\n #right_image,right_image_angle = get_image_atAngle(right_img_path,center_angle,'right')\n \n images.append(left_image)\n angles.append(left_image_angle)\n\n images.append(right_image)\n angles.append(right_image_angle)\n \n ########################################################################################\n \n ###################### FLIP ALL 3 IMAGES(to remove left or right bias)##################\n \n # add center flipped images\n flipped_center_image, flipped_center_angle = flip(center_image, center_angle)\n images.append(flipped_center_image)\n angles.append(flipped_center_angle)\n\n # add left flipped images\n flipped_left_image, flipped_left_angle = flip(left_image, left_image_angle)\n images.append(flipped_left_image)\n angles.append(flipped_left_angle)\n\n # add right flipped images\n flipped_right_image, flipped_right_angle = flip(right_image, right_image_angle)\n images.append(flipped_right_image)\n angles.append(flipped_right_angle)\n \n ########################################################################################\n\n\n # convert to numpy array and save\n X_train = np.array(images)\n y_train = np.array(angles)\n\n shuffle(X_train, y_train)\n yield (X_train, y_train)\n\ndef get_nvidia_model(): #nvidia architecture used,only all activation functions changed to 'elu'\n \n model = Sequential()\n model.add(Cropping2D(cropping=((70, 25), (0, 0)), input_shape=(160, 320, 3)))\n model.add(Lambda(lambda x: x / 127.5 - 1.0))\n\n model.add(Convolution2D(24, 5, 5, subsample=(2, 2), activation='elu'))\n model.add(Convolution2D(36, 5, 5, subsample=(2, 2), activation='elu'))\n model.add(Convolution2D(48, 5, 5, subsample=(2, 2), activation='elu'))\n model.add(Convolution2D(64, 3, 3, activation='elu'))\n model.add(Convolution2D(64, 3, 3, activation='elu'))\n\n model.add(Flatten())\n model.add(Dense(100,activation='elu'))\n model.add(Dense(50,activation='elu'))\n model.add(Dense(10,activation='elu'))\n model.add(Dense(1))\n model.summary()\n model.compile(loss='mse', optimizer='adam')\n return model\n\ndef get_commaAI_model():\n \n #commaAI architecture used, influenced by \n #https://github.com/commaai/research/blob/master/train_steering_model.py\n \n model = Sequential()\n model.add(Lambda(lambda x: (x / 127.5) - 1., input_shape=(160, 320, 3)))\n model.add(Cropping2D(cropping=((70, 25), (0, 0)), input_shape=(160, 320, 3)))\n model.add(Convolution2D(16, 8, 8, subsample=(4, 4), border_mode=\"same\"))\n model.add(ELU())\n model.add(Convolution2D(32, 5, 5, subsample=(2, 2), border_mode=\"same\"))\n model.add(ELU())\n model.add(Convolution2D(64, 5, 5, subsample=(2, 2), border_mode=\"same\"))\n model.add(Flatten())\n model.add(Dropout(.2))\n model.add(ELU())\n model.add(Dense(512))\n model.add(Dropout(.5))\n model.add(ELU())\n model.add(Dense(1))\n\n model.summary()\n model.compile(optimizer=\"adam\", loss=\"mse\")\n return model\n\n\ndef main():\n \n BATCH_SIZE = 32\n EPOCHS = 2\n\n samples = readCsv()\n samples = samples[1:]\n training_samples, validation_samples = train_test_split(samples, test_size=0.2)\n\n train_generator = data_generator(training_samples, batch_size=32)\n validation_generator = data_generator(validation_samples, batch_size=32)\n \n model = get_nvidia_model()\n #model = get_commaAI_model()\n \n #filepath=\"anupam1.h5\"\n #checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')\n #callbacks_list = [checkpoint]\n \n model.fit_generator(train_generator,\n samples_per_epoch=6 * len(training_samples),\n validation_data=validation_generator,\n nb_val_samples=len(validation_samples),\n nb_epoch=EPOCHS,\n #callbacks =callbacks_list,\n verbose=1)\n\n model.save('nvidia_2epochs.h5')\n #model.save('commaAI_model.h5')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"166191008","text":"import bs4\nimport concurrent.futures as cf\nimport requests\n\nMAIN_URL = 'https://mycar.kz'\nPAGE_URL = f'{MAIN_URL}/cars/?page='\nANNOUNCEMENT_URL = f'{MAIN_URL}/announcement/'\nNUMBER_OF_PAGES = 10\nFIELDS = ['ИД', 'Марка', 'Модель', 'Год', 'Пробег', 'Двигатель', 'Коробка',\n 'Кузов', 'Привод', 'Цвет', 'Цена']\nMODEL_FIELDS = ['id', 'make', 'model', 'year', 'mileage', 'engine', 'transmission',\n 'body', 'drive', 'color', 'price']\n\n\ndef get_announcement_ids(url):\n html_content = requests.get(url).content\n soup = bs4.BeautifulSoup(html_content, 'html.parser')\n return {\n a['href'].split('/')[-2]\n for a in soup.find_all('a', href=True) if '/announcement/' in a['href']\n }\n\n\ndef get_car_dict(url, id_):\n html_content = requests.get(url).content\n soup = bs4.BeautifulSoup(html_content, 'html.parser')\n make, model = [\n a.strip()\n for breadcrumb in soup.find_all('div', {'class': 'breadcrumbs__link'})\n for a in breadcrumb.find('a', href=True)\n ][1:3]\n price = soup.find(\n 'div', {'class': 'right-side__price'}\n ).find('span').text.strip().replace('\"', '').replace(',', '')\n params_dict = {\n 'ИД': id_,\n 'Марка': make,\n 'Модель': model,\n 'Цена': price\n }\n for row in soup.find_all('div', {'class': 'params-row'}):\n name = row.find('div', {'class': 'params-row__name'}).text.strip()\n value = row.find('div', {'class': 'params-row__value'}).text.strip() \\\n .replace('\"', '').replace(',', '')\n if name == 'Пробег' and value.endswith(' км'):\n value = value[:-3]\n params_dict[name] = value\n return params_dict\n\n\ndef scrape(number_of_pages=NUMBER_OF_PAGES):\n announcement_ids = set()\n car_dicts = []\n with cf.ThreadPoolExecutor(max_workers=10) as executor:\n future_announcement_ids = {\n executor.submit(get_announcement_ids, f'{PAGE_URL}{i}')\n for i in range(1, number_of_pages + 1)\n }\n done, _ = cf.wait(future_announcement_ids, timeout=30)\n for future in done:\n try:\n announcement_ids.update(future.result())\n except cf.TimeoutError or cf.CancelledError:\n pass\n except RuntimeError as error:\n raise error\n future_car_dicts = {\n executor.submit(get_car_dict, f'{ANNOUNCEMENT_URL}{id__}', id__)\n for id__ in announcement_ids\n }\n done, _ = cf.wait(future_car_dicts, timeout=30)\n for future in done:\n try:\n car_dicts.append(future.result())\n except cf.TimeoutError or cf.CancelledError:\n pass\n except RuntimeError as error:\n raise error\n return car_dicts\n","sub_path":"cars/management/commands/_scraper.py","file_name":"_scraper.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"454908212","text":"#%%\nimport numpy as np\nimport bokeh.io\nimport bokeh.plotting\nfrom bokeh.models import * \nimport bokeh.layouts\nimport prot.estimate\nimport prot.viz \ncolors, palette = prot.viz.bokeh_theme()\nbokeh.io.output_file('model_explorer.html')\n\n\n# Define the data sources\nribosomes = np.logspace(2, np.log10(3.3E5), 200)\nelongation_rate = [0]\ndata_source = ColumnDataSource({'R': ribosomes, \n 'R_fa': ribosomes,\n 'R_cell': ribosomes,\n 'elongation_rate':np.zeros_like(ribosomes), \n 'elongation_rate_fa':np.zeros_like(ribosomes), \n 'lambda': np.zeros_like(ribosomes),\n 'leg': ['100% ribosomes active'],\n 'lambda_fa': np.zeros_like(ribosomes),\n 'supply': [1E5],\n 'consumed': elongation_rate,\n 'consumed_fa': elongation_rate,\n 'accum': [0],\n 'accum_fa':[0]})\n \n\n\n# Define the sliders. \nkd_slider = Slider(value=5, start=0.01, end=50, step=0.01, title='dissociation constant [mM]',\n width=300)\nr_aa = Slider(value=8, start=1, end=10, step=0.1, title='log\\u2081\\u2080 (amino acid supply rate [AA / s•µm\\u00b3])',\n width=300)\nfa_slider = Slider(value=0.75, start=0.001, end=1, step=0.001, title='active ribosome fraction',\n width=300)\n\n\n# Set up the figure canvases. \nelong_rate_plot = bokeh.plotting.figure(width=500, height=350, \n x_axis_label='ribosomes per µm\\u00b3',\n x_axis_type='log',\n y_axis_label='elongation rate [AA / sec]',\n x_range=[1E2, 5E5],\n y_range = [0, 17.5])\ngrowth_rate_plot = bokeh.plotting.figure(width=500, height=350, \n x_axis_label='ribosomes per cell',\n x_axis_type='log',\n y_axis_label='growth rate [hr^-1]',\n y_range=[0, 2])\n\n# conc_plot = bokeh.plotting.figure(width=500, height=350, \n# x_axis_label='ribosomes per µm\\u00b3',\n# x_axis_type='log',\n# y_axis_type='log',\n# y_axis_label='AA / (s • µm\\u00b3)',\n# x_range=[1E3, 5E5],\n# y_range=[1E0, 1E9])\n\n\n\n\n\n# Elongation Plot\nelong_rate_plot.line(x='R', y='elongation_rate_fa', line_color=colors['light_blue'],\n source=data_source, line_width=3, legend_field='leg')\n\nelong_rate_plot.line(x='R', y='elongation_rate', line_color=colors['blue'],\n source=data_source, line_width=3, legend_label='no ribosome regulation')\n\n# Growth Rate Plot\ngrowth_rate_plot.line(x='R_cell', y='lambda_fa', line_width=3,\n source=data_source, line_color=colors['light_blue'],\n legend_field='leg')\ngrowth_rate_plot.line(x='R_cell', y='lambda', line_width=3, legend_label='no ribosome regulation',\n source=data_source, line_color=colors['blue'])\n\nelong_rate_plot.legend.location = 'top_left'\ngrowth_rate_plot.legend.location = 'top_left'\n\n# # Concentration Plot\n# conc_plot.line(x='R', y='supply', line_width=3, legend_label='[AA] generated',\n# line_color='black', source=data_source)\n# conc_plot.line(x='R', y='consumed_fa', line_width=3, legend_label='[AA] consumed (with regulation)',\n# line_color=colors['light_red'], source=data_source)\n# conc_plot.line(x='R', y='consumed', line_width=3, legend_label='[AA] consumed (no regulation)',\n# line_color=colors['red'], source=data_source)\n# conc_plot.line(x='R', y='accum_fa', line_width=3, legend_label='[AA]_eff (with regulation)',\n# line_color=colors['light_purple'], source=data_source)\n# conc_plot.line(x='R', y='accum', line_width=3, legend_label='[AA]_eff (no regulation)',\n# line_color=colors['purple'], source=data_source)\n\n\n# Load the javascript. \nwith open('model_explorer.js') as f:\n js = f.read()\ncb = CustomJS(args={'source':data_source, 'kd_slider':kd_slider, 'raa_slider':r_aa, 'fa_slider': fa_slider},\n code=js)\n\n# Assign the callbacks\nkd_slider.js_on_change('value', cb)\nr_aa.js_on_change('value', cb)\nfa_slider.js_on_change('value', cb)\nkd_slider.callback = cb\nr_aa.callback = cb\nfa_slider.callback = cb\n\n# Define the layout\ncontrols = bokeh.layouts.row(kd_slider, r_aa, fa_slider)\nbottom_row = bokeh.layouts.row(elong_rate_plot, growth_rate_plot)\nlay = bokeh.layouts.column(controls, bottom_row)\nbokeh.io.save(lay)\n\n# %%\n","sub_path":"code/figures/js/model_explorer.py","file_name":"model_explorer.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"135396410","text":"from torch.autograd import Variable\nimport torch\nimport torch.nn as nn\nfrom torch.optim import lr_scheduler\n\nimport time\nfrom os import path\n\nfrom args import args\nimport utils\nfrom log import Logger\nfrom capsnet import CapsNet, Decoder\n\n# Constants\nlogger = Logger(args.batch_size, args.visdom)\nlogger.plain('Training CapsNet with the following settings:\\n{}'.format(args))\n\nif args.dataset == 'MNIST':\n N_CLASSES = 10\nelse:\n raise Exception('Invalid dataset')\n\nstart = time.strftime(\"%Y-%m-%d-%H:%M\")\n\n\ndef train(epoch, model, dataloader, optim, decoder, decoder_optim):\n model.train()\n\n decoder_criterion = nn.MSELoss()\n\n for ix, (X, y) in enumerate(dataloader):\n target = utils.one_hot(y, model.final_caps.n_unit)\n\n X, target = Variable(X), Variable(target)\n if args.use_gpu:\n X, target = X.cuda(), target.cuda()\n\n y_hat = model(X)\n loss = model.loss(y_hat, target)\n loss.backward()\n optim.step()\n optim.zero_grad()\n\n # train the decoder\n imgs = decoder(y_hat.detach())\n decoder_loss = decoder_criterion(imgs, X)\n decoder_loss.backward()\n decoder_optim.step()\n decoder_optim.zero_grad()\n\n if ix % args.log_interval == 0:\n preds = model.capsule_prediction(y_hat)\n acc = utils.categorical_accuracy(y.float(), preds.cpu().data)\n logger.log(epoch, ix, len(dataloader.dataset), start+'_TRAIN',\n loss=loss.data[0], acc=acc,\n decoder_loss=decoder_loss.data[0])\n\n logger.images('generated_fmnist', imgs.data.cpu())\n\n return loss.data[0]\n\n\ndef test(epoch, model, dataloader):\n model.eval()\n\n for i, (X, y) in enumerate(dataloader):\n target = utils.one_hot(y, model.final_caps.n_unit)\n\n X, target = Variable(X), Variable(target)\n if args.use_gpu:\n X, target = X.cuda(), target.cuda()\n\n y_hat = model(X)\n loss = model.loss(y_hat, target)\n\n preds = model.capsule_prediction(y_hat)\n acc = utils.categorical_accuracy(y.float(), preds.cpu().data)\n logger.log(epoch, i, len(dataloader.dataset), start+'_TEST',\n loss=loss.data[0], acc=acc)\n\n\ntrainloader, testloader = utils.mnist_dataloaders(args.data_path,\n args.batch_size,\n args.use_gpu)\n\nmodel = CapsNet(n_conv_channel=256,\n n_primary_caps=8,\n primary_cap_size=1152,\n output_unit_size=16,\n n_routing_iter=3)\n\n# load state from past runs\nif args.load_checkpoint != '':\n model.load_state_dict(torch.load(args.load_checkpoint))\n\n# move to GPU\nmodel = model.cuda() if args.use_gpu else model\noptimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\n\n# setup decoder for training\ndecoder = Decoder()\ndecoder = decoder.cuda() if args.use_gpu else decoder\ndecoder_optim = torch.optim.Adam(decoder.parameters(), lr=0.001)\n# use decaying learning rate\nscheduler = lr_scheduler.ExponentialLR(decoder_optim, 0.5)\n\n\nfor epoch in range(1, args.epochs+1):\n train(epoch, model, trainloader, optimizer, decoder, decoder_optim)\n test(epoch, model, testloader)\n\n scheduler.step()\n\n if args.checkpoint_interval > 0:\n if epoch % args.checkpoint_interval == 0:\n p = path.join(args.checkpoint_dir,\n 'capsnet_{}_{}.pth'.format(start, epoch))\n torch.save(model.state_dict(),\n p)\n\n p = path.join(args.checkpoint_dir,\n 'decoder_{}_{}.pth'.format(start, epoch))\n torch.save(decoder.state_dict(),\n p)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"192701047","text":"from enemy.enemy import Enemy\r\n\r\n\r\nclass EnemyStrong(Enemy):\r\n def __init__(self, enemyPropertiesFactory, canvas, path):\r\n Enemy.__init__(self, canvas, path)\r\n self._enemyPropertiesFactory = enemyPropertiesFactory\r\n\r\n def set_properties(self):\r\n self.set_move_behavior(self._enemyPropertiesFactory.create_move_behavior())\r\n self.color = \"black\"\r\n self.size = 7\r\n self.health = 100 # should be strong...\r\n\r\n def render(self):\r\n self._canvas.delete(self._id)\r\n self._id = self._canvas.create_oval(self._x - self.size, self._y - self.size,\r\n self._x + self.size, self._y + self.size,\r\n fill = self.color)\r\n","sub_path":"TowerDefense/enemy/enemyStrong.py","file_name":"enemyStrong.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"394575051","text":"def timespan_2_stops_during_timespan_1(\n timespan_1=None,\n timespan_2=None,\n hold=False,\n ):\n \"\"\"\n Makes time relation indicating that ``timespan_2`` stops\n during ``timespan_1``.\n\n .. container:: example\n\n >>> relation = abjad.timespans.timespan_2_stops_during_timespan_1()\n >>> abjad.f(relation)\n abjad.timespans.TimespanTimespanTimeRelation(\n inequality=abjad.timespans.CompoundInequality(\n [\n abjad.TimespanInequality('timespan_1.start_offset < timespan_2.stop_offset'),\n abjad.TimespanInequality('timespan_2.stop_offset <= timespan_1.stop_offset'),\n ],\n logical_operator='and',\n ),\n )\n\n Returns time relation or boolean.\n \"\"\"\n from abjad import timespans\n\n inequality = timespans.CompoundInequality([\n 'timespan_1.start_offset < timespan_2.stop_offset',\n 'timespan_2.stop_offset <= timespan_1.stop_offset'\n ])\n\n time_relation = timespans.TimespanTimespanTimeRelation(\n inequality,\n timespan_1=timespan_1,\n timespan_2=timespan_2,\n )\n\n if time_relation.is_fully_loaded and not hold:\n return time_relation()\n else:\n return time_relation\n","sub_path":"abjad_demo/env/lib/python3.6/site-packages/abjad/timespans/timespan_2_stops_during_timespan_1.py","file_name":"timespan_2_stops_during_timespan_1.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"41931360","text":"from tkinter import *\nimport pandas as pd\n\ndat = pd.read_csv(\"./2019_accident.csv\") # 파일 불러오기\n\n# 기능 추가\n# 제출 버튼을 클릭했을 때, 동작 가능.\ndef click():\n word = entry.get()\n\n textbox.delete(0.0, END)\n dtbox.delete(0.0, END)\n itbox.delete(0.0, END)\n\n try:\n def_word = dat.loc[dat['area'] == word, 'acd'].values[0]\n wow = dat.loc[dat['area'] == word, 'death'].values[0]\n wow2 = dat.loc[dat['area'] == word, 'injury'].values[0]\n\n except:\n def_word = \"결과를 찾을 수 없음\"\n wow = \"결과를 찾을 수 없음\"\n wow2 = \"결과를 찾을 수 없음\"\n\n textbox.insert(END, def_word)\n dtbox.insert(END, wow)\n itbox.insert(END, wow2)\n\n\nwindow = Tk()\nwindow.title(\"2019_accident_statistic\")\nwindow.geometry('500x500')\nwindow['bg'] = 'skyblue'\n\n# 01 입력 상자 설명 레이브\nlabel = Label(window, text=\"지역 입력 후, 버튼 누르기\",bg='skyblue', fg='white smoke',font=('현대하모니L',15,'bold'))\nlabel.place(x=40, y=20)\n\n# 02 텍스트 입력이 가능한 상자(Entry)\nentry = Entry(window,width=25, bg=\"light yellow\")\nentry.place(x=40, y=50, height=25)\n\n# 03 결과 버튼\nbtn = Button(window, width=7, text=\"조회\", bg=\"light green\", command=click)\nbtn.place(x=230, y=50)\n\n# 04 결과 레이블 - 발생건수\nmean = Label(window, text=\"발생건수\",bg='skyblue', fg='purple',font=('현대하모니L',15,'bold'))\nmean.place(x=35, y=100)\n\ntextbox = Text(window, width=11,height=2,wrap=WORD, bg=\"light yellow\")\ntextbox.place(x=40, y=130)\n\n# 05 결과 레이블 - 사망자수\nresult = Label(window, text=\"사망자수\", bg='skyblue', fg='purple',font=('현대하모니L',15,'bold') )\nresult.place(x=165, y=100)\n\ndtbox = Text(window, width=11,height=2,wrap=WORD, bg=\"light yellow\")\ndtbox.place(x=170, y=130)\n\n# 06 결과 레이블 - 부상자수\nresult2 = Label(window, text=\"부상자수\", bg='skyblue', fg='purple',font=('현대하모니L',15,'bold') )\nresult2.place(x=295, y=100)\n\nitbox = Text(window, width=11,height=2,wrap=WORD, bg=\"light yellow\")\nitbox.place(x=300, y=130)\n\ncaracd = PhotoImage(file=\"car.PNG\")\n\nhello = Label(window, image=caracd, width=350,height=250)\nhello.place(x=40, y=190)\n\n# 메인 반복문 실행\nwindow.mainloop()","sub_path":"week1/05_11day/01_11-1.py","file_name":"01_11-1.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"121254458","text":"#!/usr/bin/python3\n\"\"\"\nInitializes the console for the project\n\"\"\"\n\nimport models\nimport cmd\nimport shlex\nfrom models.base_model import BaseModel\nfrom models.amenity import Amenity\nfrom models.city import City\nfrom models.place import Place\nfrom models.review import Review\nfrom models.state import State\nfrom models.user import User\n\nclass_dict = {\n \"Amenity\": Amenity,\n \"BaseModel\": BaseModel,\n \"City\": City,\n \"Place\": Place,\n \"Review\": Review,\n \"State\": State,\n \"User\": User\n }\n\nintegers = [\n \"number_rooms\",\n \"number_bathrooms\",\n \"max_guest\",\n \"price_by_night\"\n ]\n\nfloats = [\"latitude\", \"longitude\"]\n\n\nclass HBNBCommand(cmd.Cmd):\n \"\"\"Class containing the console HBNB\"\"\"\n\n prompt = \"(hbnb) \"\n\n def emptyline(self):\n \"\"\"Method to override father method\"\"\"\n return False\n\n def do_EOF(self, arg):\n \"\"\"Exit the console\"\"\"\n return True\n\n def do_quit(self, arg):\n \"\"\"Quit the console\"\"\"\n return True\n\n def do_create(self, tmpname):\n \"\"\"Creates a new instance of a class\"\"\"\n instname = shlex.split(tmpname)\n if len(instname) == 0:\n print(\"** class name missing **\")\n return False\n if instname[0] in class_dict:\n new_instance = class_dict[instname[0]]()\n else:\n print(\"** class doesn't exist **\")\n return False\n print(new_instance.id)\n new_instance.save\n\n def do_show(self, clinfo):\n \"\"\"Prints the string representation of\n an instance based on the class name and id\"\"\"\n clinfostr = shlex.split(clinfo)\n if len(clinfostr) == 0:\n print(\"** class name missing **\")\n return False\n if clinfostr[0] in class_dict:\n if len(clinfostr) > 1:\n instanceinfo = clinfostr[0] + \".\" + clinfostr[1]\n if instanceinfo in models.storage.all():\n print(models.storage.all()[instanceinfo])\n else:\n print(\"** no instance found **\")\n else:\n print(\"** instance id missing **\")\n else:\n print(\"** class doesn't exist **\")\n\n def do_destroy(self, insinfo):\n \"Deletes an instance based on the class name and id\"\n instodel = shlex.split(insinfo)\n if len(instodel) == 0:\n print(\"** class name missing **\")\n return False\n if instodel[0] in class_dict:\n if len(instodel) > 1:\n instopop = instodel[0] + \".\" + instodel[1]\n if instopop in models.storage.all():\n models.storage.all().pop(instopop)\n models.storage.save()\n else:\n print(\"** no instance found **\")\n else:\n print(\"** instance id missing **\")\n else:\n print(\"** class doesn't exist **\")\n\n def do_all(self, clshow):\n \"\"\"Prints all string representation of all\n instances based or not on the class name\"\"\"\n toshow = shlex.split(clshow)\n showls = []\n if len(toshow) == 0:\n for value in models.storage.all().values():\n showls.append(str(value))\n print(\"[\", end=\"\")\n print(\", \".join(showls), end=\"\")\n print(\"]\")\n elif toshow[0] in class_dict:\n for clname in models.storage.all():\n if toshow[0] in clname:\n showls.append(str(models.storage.all()[clname]))\n print(\"[\", end=\"\")\n print(\", \".join(showls), end=\"\")\n print(\"]\")\n else:\n print(\"** class doesn't exist **\")\n\n def do_update(self, objtoupdate):\n \"\"\"Updates an instance based on the class\n name and id by adding or updating attribute\"\"\"\n updatelist = shlex.split(objtoupdate)\n if len(updatelist) == 0:\n print(\"** class name missing **\")\n elif updatelist[0] in class_dict:\n if len(updatelist) > 1:\n valuetofind = updatelist[0] + \".\" + updatelist[1]\n if valuetofind in models.storage.all():\n if len(updatelist) > 2:\n if len(updatelist) > 3:\n if updatelist[0] == \"Place\":\n if updatelist[2] in integers:\n try:\n updatelist[3] = int(updatelist[3])\n except:\n updatelist[3] = 0\n elif updatelist[2] in floats:\n try:\n updatelist[3] = float(updatelist[3])\n except:\n updatelist[3] = 0.0\n setattr(models.storage.all()[valuetofind],\n updatelist[2], updatelist[3])\n models.storage.all()[valuetofind].save()\n else:\n print(\"** value missing **\")\n else:\n print(\"** attribute name missing **\")\n else:\n print(\"** no instance found **\")\n else:\n print(\"** instance id missing **\")\n else:\n print(\"** class doesn't exist **\")\n\nif __name__ == '__main__':\n HBNBCommand().cmdloop()\n","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":5514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"451654966","text":"from hashlib import md5\n\nfrom aocd import data\n\n\ndef part_ab(data):\n data = data.strip().encode(\"ascii\")\n code1 = \"\"\n code2 = [None] * 8\n n = 0\n remaining = set(\"01234567\")\n while True:\n test = b\"%s%d\" % (data, n)\n hash_ = md5(test).hexdigest()\n n += 1\n if not hash_.startswith(\"0\" * 5):\n continue\n h5, h6 = hash_[5], hash_[6]\n code1 += h5\n if h5 in remaining:\n code2[int(h5)] = h6\n remaining.remove(h5)\n if not remaining:\n break\n code1 = code1[:8]\n code2 = \"\".join(code2)\n return code1, code2\n\n\nassert part_ab(\"abc\") == (\"18f47a30\", \"05ace8e3\")\n\na, b = part_ab(data)\nprint(\"part a:\", a)\nprint(\"part b:\", b)\n","sub_path":"aoc_wim/aoc2016/q05.py","file_name":"q05.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"32808766","text":"import torch\nimport torch.nn as nn\nfrom catvae.composition import closure\nfrom gneiss.cluster import random_linkage\nfrom gneiss.balances import sparse_balance_basis\nfrom torch.distributions import Multinomial, Normal\nfrom torch.distributions.kl import kl_divergence\nimport numpy as np\nimport geotorch\n\nLOG_2_PI = np.log(2.0 * np.pi)\n\n\ndef get_basis(input_dim, basis=None):\n if basis is None:\n tree = random_linkage(input_dim)\n basis = sparse_balance_basis(tree)[0].copy()\n indices = np.vstack((basis.row, basis.col))\n Psi = torch.sparse_coo_tensor(\n indices.copy(), basis.data.astype(np.float32).copy(),\n requires_grad=False).coalesce()\n return Psi\n\n\nclass ArcsineEmbed(nn.Module):\n def __init__(self, input_dim, hidden_dim, dropout=0):\n super(ArcsineEmbed, self).__init__()\n self.embed = nn.Parameter(\n torch.zeros(input_dim, hidden_dim))\n self.ffn = nn.Sequential(\n nn.Linear(hidden_dim, hidden_dim * 4, bias=True),\n nn.Softplus(),\n nn.Dropout(dropout),\n nn.Linear(hidden_dim * 4, 1, bias=True),\n )\n\n def forward(self, x, Psi):\n a = torch.arcsin(torch.sqrt(closure(x))) # B x D\n x_ = a[:, :, None] * self.embed # B x D x H\n fx = self.ffn(x_).squeeze()\n fx = (Psi @ fx.T).T # B x D-1\n return fx\n\n\nclass CLREmbed(nn.Module):\n def __init__(self, input_dim, hidden_dim, dropout=0):\n super(CLREmbed, self).__init__()\n self.embed = nn.Parameter(\n torch.zeros(input_dim, hidden_dim))\n self.ffn = nn.Sequential(\n nn.Linear(hidden_dim, hidden_dim * 4, bias=True),\n nn.Softplus(),\n nn.Dropout(dropout),\n nn.Linear(hidden_dim * 4, 1, bias=True),\n )\n\n def forward(self, x, Psi):\n a = torch.arcsin(torch.sqrt(closure(x))) # B x D\n a = torch.log(closure(x + 1))\n a = a - a.mean(axis=1).reshape(-1, 1) # center around mean\n x_ = a[:, :, None] * self.embed # B x D x H\n fx = self.ffn(x_).squeeze()\n fx = (Psi @ fx.T).T # B x D-1\n return fx\n\n\nclass Encoder(nn.Module):\n def __init__(self, input_dim: int,\n hidden_dim: int,\n latent_dim: int, bias: bool = False,\n dropout: float = 0, batch_norm: bool = True,\n depth: int = 1, init_scale: float = 0.001):\n super(Encoder, self).__init__()\n if depth > 1:\n first_encoder = nn.Linear(\n input_dim, hidden_dim, bias=bias)\n num_encoder_layers = depth\n layers = []\n layers.append(first_encoder)\n layers.append(nn.Softplus())\n layers.append(nn.Dropout(dropout))\n for layer_i in range(num_encoder_layers - 2):\n layers.append(\n nn.Linear(hidden_dim, hidden_dim, bias=bias))\n layers.append(nn.Softplus())\n layers.append(nn.Dropout(dropout))\n if batch_norm:\n layers.append(nn.BatchNorm1d(hidden_dim))\n layers.append(nn.Linear(hidden_dim, latent_dim, bias=bias))\n self.encoder = nn.Sequential(*layers)\n\n # initialize\n for encoder_layer in self.encoder:\n if isinstance(encoder_layer, nn.Linear):\n encoder_layer.weight.data.normal_(0.0, init_scale)\n elif depth == 2:\n layers = nn.Sequential(*[\n nn.Linear(input_dim, hidden_dim, bias=bias),\n nn.Softplus(),\n nn.Linear(hidden_dim, latent_dim, bias=bias)\n ])\n self.encoder = nn.Sequential(*layers)\n for encoder_layer in self.encoder:\n if isinstance(encoder_layer, nn.Linear):\n encoder_layer.weight.data.normal_(0.0, init_scale)\n elif depth == 1:\n self.encoder = nn.Linear(\n input_dim, latent_dim, bias=bias)\n self.encoder.weight.data.normal_(0.0, init_scale)\n else:\n raise ValueError(f'Depth of {depth} is not appropriate.')\n\n def forward(self, x):\n return self.encoder(x)\n\n\nclass LinearVAE(nn.Module):\n\n def __init__(self, input_dim, hidden_dim, latent_dim=None,\n init_scale=0.001, encoder_depth=1,\n basis=None, bias=True,\n transform='pseudocount', distribution='multinomial',\n dropout=0, batch_norm=False, grassmannian=True):\n super(LinearVAE, self).__init__()\n if latent_dim is None:\n latent_dim = hidden_dim\n self.bias = bias\n self.hidden_dim = hidden_dim\n Psi = get_basis(input_dim, basis).coalesce()\n # note this line corresponds to the true input dim\n self.input_dim = Psi.shape[0]\n self.register_buffer('Psi', Psi)\n self.encoder = Encoder(\n self.input_dim, hidden_dim, latent_dim,\n bias=bias, depth=encoder_depth, init_scale=init_scale,\n dropout=dropout, batch_norm=batch_norm)\n self.decoder = nn.Linear(\n latent_dim, self.input_dim, bias=self.bias)\n if grassmannian:\n geotorch.grassmannian(self.decoder, 'weight')\n self.variational_logvars = nn.Parameter(torch.zeros(latent_dim))\n self.transform = transform\n self.distribution = distribution\n if self.transform == 'arcsine':\n self.input_embed = ArcsineEmbed(self.input_dim + 1,\n hidden_dim, dropout)\n if self.transform == 'clr':\n self.input_embed = CLREmbed(self.input_dim + 1,\n hidden_dim, dropout)\n\n def gaussian_kl(self, z_mean, z_logvar):\n return 0.5 * (1 + z_logvar - z_mean * z_mean - torch.exp(z_logvar))\n\n def gaussian_kl2(self, m1, s1, m2, s2):\n x = Normal(m1, torch.exp(0.5 * s1))\n y = Normal(m2, torch.exp(0.5 * s2))\n return - kl_divergence(x, y)\n\n def recon_model_loglik(self, x_in, x_out):\n logp = (self.Psi.t() @ x_out.t()).t()\n if self.distribution == 'multinomial':\n dist_loss = Multinomial(\n logits=logp, validate_args=False # weird ...\n ).log_prob(x_in).mean()\n elif self.distribution == 'gaussian':\n # MSE loss based out on DeepMicro\n # https://www.nature.com/articles/s41598-020-63159-5\n dist_loss = Normal(\n loc=logp, scale=1, validate_args=False # weird ...\n ).log_prob(x_in).mean()\n else:\n raise ValueError(\n f'Distribution {self.distribution} is not supported.')\n return dist_loss\n\n def impute(self, x):\n if self.transform in {'arcsine', 'clr'}:\n hx = self.input_embed(x, self.Psi)\n elif self.transform == 'pseudocount':\n fx = torch.log(x + 1) # ILR transform for testing\n hx = (self.Psi @ fx.T).T # B x D-1\n elif self.transform == 'none':\n hx = x\n else:\n raise ValueError(f'Unrecognzied transform {self.transform}')\n return hx\n\n def sample(self, x, size=None):\n # obtain mean of latent distribution\n z_mean = self.encode(x)\n if size is None:\n eps = torch.normal(torch.zeros_like(z_mean), 1.0)\n else:\n eps = torch.normal(torch.zeros(size), 1.0)\n z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars)\n return z_sample\n\n def encode(self, x):\n hx = self.impute(x)\n z = self.encoder(hx)\n return z\n\n def forward(self, x):\n z_mean = self.encode(x)\n eps = torch.normal(torch.zeros_like(z_mean), 1.0)\n z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars)\n x_out = self.decoder(z_sample)\n kl_div = self.gaussian_kl(\n z_mean, self.variational_logvars).mean(0).sum()\n recon_loss = self.recon_model_loglik(x, x_out).mean(0).sum()\n elbo = kl_div + recon_loss\n loss = - elbo\n return loss\n\n def get_reconstruction_loss(self, x):\n z_mean = self.encode(x)\n eps = torch.normal(torch.zeros_like(z_mean), 1.0)\n z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars)\n x_out = self.decoder(z_sample)\n recon_loss = -self.recon_model_loglik(x, x_out)\n return recon_loss\n\n\nclass LinearDLRVAE(LinearVAE):\n\n def __init__(self, input_dim, hidden_dim, latent_dim=None,\n init_scale=0.001, encoder_depth=1,\n basis=None, bias=True,\n transform='pseudocount', distribution='multinomial',\n dropout=0, batch_norm=False, grassmannian=True):\n super(LinearDLRVAE, self).__init__(\n input_dim, hidden_dim, latent_dim,\n init_scale=init_scale, basis=basis,\n encoder_depth=encoder_depth,\n bias=bias, transform=transform, dropout=dropout,\n batch_norm=batch_norm, grassmannian=grassmannian)\n self.log_sigma_sq = nn.Parameter(torch.ones(input_dim - 1))\n\n def sample(self, x):\n z_mean = self.encode(x)\n eps = torch.normal(torch.zeros_like(z_mean), 1.0)\n z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars)\n return z_sample\n\n def forward(self, x):\n z_mean = self.encode(x)\n eps = torch.normal(torch.zeros_like(z_mean), 1.0)\n z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars)\n x_out = self.decoder(z_sample)\n delta = torch.normal(torch.zeros_like(x_out), 1.0)\n x_out += delta * torch.exp(0.5 * self.log_sigma_sq)\n kl_div = self.gaussian_kl(\n z_mean, self.variational_logvars).mean(0).sum()\n recon_loss = self.recon_model_loglik(x, x_out).mean(0).sum()\n elbo = kl_div + recon_loss\n loss = - elbo\n return loss\n\n def get_reconstruction_loss(self, x):\n z_sample = self.sample(x)\n x_out = self.decoder(z_sample)\n recon_loss = -self.recon_model_loglik(x, x_out)\n return recon_loss\n\n\nclass LinearBatchVAE(LinearVAE):\n def __init__(self, input_dim, hidden_dim, latent_dim,\n batch_dim, batch_prior,\n init_scale=0.001, encoder_depth=1,\n basis=None, bias=True,\n transform='pseudocount',\n distribution='multinomial',\n batch_norm=False, dropout=0,\n grassmannian=True):\n \"\"\" Account for batch effects.\n\n Parameters\n ----------\n input_dim : int\n Number of dimensions for input counts\n hidden_dim : int\n Number of hidden dimensions within encoder\n latent_dim : int\n Number of hidden dimensions within latent space\n batch_dim : int\n Number of batches (i.e. studies) to do batch correction\n batch_prior : np.array of float\n Normal variance priors for batch effects of shape D - 1.\n Note that these priors are assumed to be in ILR coordinates.\n transform : str\n Choice of input transform. Can choose from\n arcsine, pseudocount and rclr (TODO).\n \"\"\"\n super(LinearBatchVAE, self).__init__(\n input_dim, hidden_dim, latent_dim,\n init_scale=init_scale, basis=basis,\n encoder_depth=encoder_depth,\n bias=bias, transform=transform, dropout=dropout,\n batch_norm=batch_norm, grassmannian=grassmannian)\n self.batch_dim = batch_dim\n self.ilr_dim = input_dim - 1\n batch_prior = batch_prior\n self.register_buffer('batch_prior', batch_prior)\n self.batch_logvars = nn.Parameter(torch.zeros(self.ilr_dim))\n self.beta = nn.Embedding(batch_dim, self.ilr_dim)\n self.batch_embed = nn.Embedding(batch_dim, latent_dim)\n\n def encode(self, x, b):\n hx = self.impute(x)\n zb = self.batch_embed(b)\n z = self.encoder(hx) - zb\n return z\n\n def encode_marginalized(self, x, b):\n \"\"\" Marginalize over batch_effects given predictions\n\n This will compute the expected batch effect given the\n batch classification probabilities.\n\n Parameters\n ----------\n x : torch.Tensor\n Counts of interest (B x D)\n b : torch.Tensor\n Batch effect prediction log probabilities (B x K)\n\n Notes\n -----\n This assumes that the batch classifier is well-calibrated.\n \"\"\"\n # obtain expected batch effect\n beta_ = self.beta.weight\n m = nn.Softmax()\n batch_effects = b @ m(beta_)\n hx = self.impute(x)\n hx = hx - batch_effects\n z = self.encoder(hx)\n return z\n\n def sample(self, x, b, size=None):\n # obtain mean of latent distribution\n z_mean = self.encode(x, b)\n if size is None:\n eps = torch.normal(torch.zeros_like(z_mean), 1.0)\n else:\n eps = torch.normal(torch.zeros(size), 1.0)\n z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars)\n return z_sample\n\n def forward(self, x, b):\n z_mean = self.encode(x, b)\n batch_effects = self.beta(b)\n eps = torch.normal(torch.zeros_like(z_mean), 1.0)\n z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars)\n eps = torch.normal(torch.zeros_like(batch_effects), 1.0)\n b_sample = batch_effects + eps * torch.exp(0.5 * self.batch_logvars)\n x_out = self.decoder(z_sample) + b_sample\n kl_div_z = self.gaussian_kl(\n z_mean, self.variational_logvars).mean(0).sum()\n kl_div_b = self.gaussian_kl2(\n batch_effects, self.batch_logvars,\n torch.zeros_like(self.batch_prior), self.batch_prior\n ).mean(0).sum()\n recon_loss = self.recon_model_loglik(x, x_out).mean(0).sum()\n elbo = kl_div_z + kl_div_b + recon_loss\n loss = - elbo\n return loss, -recon_loss, -kl_div_z, -kl_div_b\n\n def get_reconstruction_loss(self, x, b):\n z_mean = self.encode(x, b)\n eps = torch.normal(torch.zeros_like(z_mean), 1.0)\n z_sample = z_mean + eps * torch.exp(0.5 * self.variational_logvars)\n batch_effects = self.beta(b)\n x_out = self.decoder(z_sample)\n x_out += batch_effects # Add batch effects back in\n recon_loss = -self.recon_model_loglik(x, x_out)\n return recon_loss\n","sub_path":"catvae/models/linear_vae.py","file_name":"linear_vae.py","file_ext":"py","file_size_in_byte":14611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"154671618","text":"# Lexical Analyser for Simple C Programs\r\nimport os\r\nimport sys\r\n\r\n\r\n# Method to check if a string is number or not\r\ndef is_number(s):\r\n try:\r\n float(s)\r\n return True\r\n except ValueError:\r\n pass\r\n try:\r\n import unicodedata\r\n unicodedata.numeric(s)\r\n return True\r\n except (TypeError, ValueError):\r\n pass\r\n return False\r\n\r\n\r\ntry:\r\n # Reading keywords into a list from keywords.txt file\r\n keyword_list = [line.rstrip('\\n') for line in open('keywords.txt')]\r\nexcept FileNotFoundError:\r\n print('\\nkeywords.txt not found.')\r\n sys.exit()\r\n# Other lists for arithmetic,relational and assignment operator\r\narith_op_list = ['+', '-', '*', '/']\r\nrel_op_list = ['<', '>']\r\nassign_op = '='\r\npunc_symbols = [';', ',', '(', ')', '{', '}']\r\nwhite_space = [' ', '\\n']\r\n# Number and Alphabet list\r\nnum_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\r\nalphabet = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'\r\n\r\nnum_buffer = ''\r\nword_buffer = ''\r\n\r\nnext_char = ''\r\nflag = 0\r\ninvalid_flag = 0\r\nrow = 1\r\ncolumn = 1\r\ntoken_no = 0\r\n\r\nin_filename = input('\\nEnter name of the C program: ')\r\ntry:\r\n input_file = open(in_filename, 'r')\r\nexcept FileNotFoundError:\r\n print('\\nFile not found :: ' + in_filename)\r\n sys.exit()\r\n\r\n# Slicing out only the filename, without extension\r\nout_filename = str(os.path.splitext(in_filename)[0]) + '.csv'\r\n# Opening the output file with extension CSV\r\ntry:\r\n output_file = open(out_filename, 'w')\r\n # Writing header to CSV file\r\n header = 'Token No.' + ',' + 'Token' + ',' + 'Token Type' + ',' + 'Row' + ',' + 'Column' + '\\n'\r\n output_file.write(header)\r\nexcept PermissionError:\r\n print('\\nPermission denied for ' + out_filename)\r\n print('\\nClose any other application using ' + out_filename)\r\n sys.exit()\r\n\r\nwhile True:\r\n # Reading 1 byte at a time\r\n if flag is 0:\r\n character = input_file.read(1)\r\n # Getting the next character if it is already read\r\n else:\r\n character = next_char\r\n if not character:\r\n print('\\n\\nLexical Analysis Complete.')\r\n break\r\n else:\r\n # If the current character is in white space list\r\n if character in white_space:\r\n flag = 0\r\n # If it is a new line, increment row, reinitialize column as 1\r\n if character is '\\n':\r\n row += 1\r\n column = 1\r\n # If it is only a space, increment column only\r\n elif character is ' ':\r\n column += 1\r\n # If the current character is in arithmetic operator list\r\n elif character in arith_op_list:\r\n # If it is a backslash, three possibilities are there\r\n if character is '/':\r\n flag = 1\r\n next_char = input_file.read(1)\r\n # If next character is also a backslash, then we have a single line comment\r\n if next_char is '/':\r\n while True:\r\n next_char = input_file.read(1)\r\n if next_char is not '\\n':\r\n continue\r\n else:\r\n break\r\n row += 1\r\n column = 1\r\n # If next character is a star, then we have a multi line comment\r\n elif next_char is '*':\r\n cur_char = input_file.read(1)\r\n later_char = input_file.read(1)\r\n # Loop and skip until multi line comment ends\r\n while True:\r\n # If we have */ combination at some point, multi-line comment ends\r\n if cur_char is '*' and later_char is '/':\r\n flag = 0\r\n break\r\n # If newline occurs, increment row and set column equal to 1\r\n elif later_char is '\\n':\r\n row += 1\r\n column = 1\r\n # If we have back to back 2 newlines, increment row by 2 and set column equal to 1\r\n elif cur_char is '\\n' and later_char is '\\n':\r\n row += 2\r\n column = 1\r\n cur_char = later_char\r\n later_char = input_file.read(1)\r\n # If the above doesn't occur, that means current character is arithmetic operator only\r\n else:\r\n column += 1\r\n token_no += 1\r\n output_file.write(\r\n str(token_no) + ',' + str(character) + ',' + 'Arithmetic Op' + ',' + str(row) + ',' + str(\r\n column) + '\\n')\r\n # This condition is for arithmetic operators other than divide or backslash\r\n else:\r\n flag = 0\r\n column += 1\r\n token_no += 1\r\n output_file.write(\r\n str(token_no) + ',' + str(character) + ',' + 'Arithmetic Op' + ',' + str(row) + ',' + str(\r\n column) + '\\n')\r\n # If the current character is in relational operator list\r\n elif character in rel_op_list:\r\n flag = 0\r\n column += 1\r\n token_no += 1\r\n output_file.write(str(token_no) + ',' + str(character) + ',' + 'Relational Op' + ',' + str(row) + ',' + str(\r\n column) + '\\n')\r\n # If the current character is assignment operator\r\n elif character is assign_op:\r\n flag = 0\r\n invalid_flag = 1 # This flag is for checking if a ID is on LHS or RHS of equal sign\r\n column += 1\r\n token_no += 1\r\n output_file.write(str(token_no) + ',' + str(character) + ',' + 'Assignment Op' + ',' + str(row) + ',' + str(\r\n column) + '\\n')\r\n # If the current character is in punctuation symbols list\r\n elif character in punc_symbols:\r\n if character is ';':\r\n invalid_flag = 0 # Semicolon resets the flag for ID position checking\r\n flag = 0\r\n column += 1\r\n token_no += 1\r\n if character is ',':\r\n output_file.write(\r\n str(token_no) + ',' + '\",\"' + ',' + 'Punctuation Symbol' + ',' + str(row) + ',' + str(\r\n column) + '\\n')\r\n else:\r\n output_file.write(\r\n str(token_no) + ',' + str(character) + ',' + 'Punctuation Symbol' + ',' + str(row) + ',' + str(\r\n column) + '\\n')\r\n # If the current character is in number list\r\n elif character in num_list:\r\n flag = 1\r\n num_buffer += character\r\n next_char = input_file.read(1)\r\n column += 1\r\n # Put character in number buffer until we have number or letter\r\n while next_char in num_list or next_char in alphabet:\r\n character = next_char\r\n num_buffer += character\r\n next_char = input_file.read(1)\r\n column += 1\r\n token_no += 1\r\n # If number buffer is a number then write type as number\r\n if is_number(\"\".join(num_buffer)):\r\n output_file.write(\r\n str(token_no) + ',' + str(num_buffer) + ',' + 'Number' + ',' + str(row) + ',' + str(column) + '\\n')\r\n # If its not a number then it may be a Invalid Number or Invalid Identifier according to the position\r\n # it has i.e. RHS or LHS with respect to assignment operator\r\n else:\r\n if invalid_flag is 1:\r\n output_file.write(\r\n str(token_no) + ',' + str(num_buffer) + ',' + 'Invalid Number' + ',' + str(row) + ',' + str(\r\n column) + '\\n')\r\n else:\r\n output_file.write(\r\n str(token_no) + ',' + str(num_buffer) + ',' + 'Invalid Identifier' + ',' + str(row) + ',' + str(\r\n column) + '\\n')\r\n num_buffer = ''\r\n # If the current character is in alphabet list\r\n elif character in alphabet:\r\n flag = 1\r\n word_buffer += character\r\n next_char = input_file.read(1)\r\n column += 1\r\n # Put character in word buffer until we have number or letter\r\n while next_char in alphabet or next_char in num_list:\r\n character = next_char\r\n word_buffer += character\r\n next_char = input_file.read(1)\r\n column += 1\r\n # Check if word buffer contains a keyword\r\n if word_buffer in keyword_list:\r\n token_no += 1\r\n # Write token details, type as Keyword\r\n output_file.write(str(token_no) + ',' + str(word_buffer) + ',' + 'Keyword' + ',' + str(row) + ',' + str(\r\n column) + '\\n')\r\n # If its not a keyword then its a identifier\r\n else:\r\n token_no += 1\r\n output_file.write(\r\n str(token_no) + ',' + str(word_buffer) + ',' + 'Identifier' + ',' + str(row) + ',' + str(\r\n column) + '\\n')\r\n word_buffer = ''\r\n# Close input and output files\r\ninput_file.close()\r\noutput_file.close()\r\n","sub_path":"3rd Year/2nd Semester/Labs/Compiler Design/1. Lexical Analyser/lexical_analyser.py","file_name":"lexical_analyser.py","file_ext":"py","file_size_in_byte":9482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"583180168","text":"import pandas as pd\nimport numpy as np\nimport sklearn.preprocessing\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nfrom scipy.interpolate import spline\nimport DisplayData\nimport LoadData\nfrom libs.detect_peaks import detect_peaks\nimport peakutils.peak\n\n\n# normtype={\"min-max\",\"Z-score\"}\ndef NormData(data, norm_type, ddof=0):\n if norm_type == \"Z-score\":\n df_norm = (data - data.mean()) / (data.std(ddof=ddof))\n elif norm_type == \"min-max\":\n df_norm = (data - data.min()) / (data.max() - data.min())\n else:\n return \"normtype={'min-max','Z-score'}\"\n return df_norm\n\n\n# change one column to enum type\n# pvname:col name\n# cur_ranges:divide range,[1,5,7]\n# right:default Ture,Indicates whether the bins include the rightmost edge or not. If right == True (the default), then the bins [1,2,3,4] indicate (1,2], (2,3], (3,4].\n# enumnames:array or boolean, default None. Used as labels for the resulting bins. Must be of the same length as the resulting bins. If False, return only integer indicators of the bins.\ndef EnumData(data, pvname, cut_ranges, right=True, enumnames=None):\n EnumPV = pd.cut(data[pvname], cut_ranges, right=right, labels=enumnames)\n print(EnumPV)\n data[pvname] = EnumPV\n return data\n\n\n# use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.\n# data[(data['pvname']>1000)&data['pvname']<20]\n\n# fillna_type:{'backfill', 'bfill', 'pad', 'ffill', None}, default pad\ndef fillempty(data, method='pad'):\n data.fillna(method=method)\n return data\n\n#detect burr(peak) in data\ndef detect_burr(data,pv,left=None,right=None,method=0,minimum_peak_distance=100):\n titles = data.columns\n titleList=titles.values.tolist()\n if pv in titleList:\n pvn=titleList.index(pv)\n sta = DisplayData.showStatistic(data)\n print(\"statistic data:\")\n print(sta)\n # use boxplot define threshold\n iqr = sta.loc['75%'][titles[pvn]] - sta.loc['25%'][titles[pvn]]\n if left is None:\n left = sta.loc['25%'][titles[pvn]] - 1.5 * iqr\n if right is None:\n right = sta.loc['75%'][titles[pvn]] + 1.5 * iqr\n print('min edge:', left, 'max edge:', right)\n burrdata = data[((data[titles[pvn]]) < left) | ((data[titles[pvn]]) > right)]\n LoadData.df2other(burrdata, 'csv','newfile.csv')\n y = data[titles[pvn]].values\n if method == 0:\n # find_peaks by scipy signal\n peaks, _ = signal.find_peaks(y, height=right)\n plt.plot(y,'b',lw=1)\n plt.plot(peaks, y[peaks], \"+\", mec='r',mew=2, ms=8)\n plt.plot(np.zeros_like(y)+right, \"--\", color=\"gray\")\n plt.title(\"find_peaks min_height:%7f\"%right)\n plt.show()\n if method==1:\n detect_peaks(y, mph=right, mpd=minimum_peak_distance, show=True)\n if method==2:\n print('Detect peaks with minimum height and distance filters.')\n # thres=right/max(y)\n indexes = peakutils.peak.indexes(np.array(y),\n thres=right / max(y), min_dist=minimum_peak_distance)\n print('Peaks are: %s' % (indexes))\n plt.plot(y,'b',lw=1)\n for i in indexes:\n plt.plot(i, y[i], \"+\", mec='r',mew=2, ms=8)\n plt.plot(np.zeros_like(y) + right, \"--\", color=\"gray\")\n plt.title(\"peakutils.peak thres:%f ,minimum_peak_distance:%d\" % (right ,minimum_peak_distance))\n plt.show()\n else:\n print(\"Wrong PV name, not in \",titleList)\n\n\n","sub_path":"CleanData.py","file_name":"CleanData.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"320722534","text":"#! /usr/bin/python\n#Input format: ID,value1,value2,value3,........\n\nimport os\nimport sys\nimport numpy as np\nimport string\n\ninput=sys.argv[1]\noutput=sys.argv[2]\n\nfin=open(input)\nfout=open(output,'w')\nnormalized_data=[]\nnormalized_mean=[]\n\ndef average(x,y,z):\n return (x+y+z)/3\n\nline_no = 0\nfor line in fin:\n line=line.strip()\n normalized_data.append([line.split(\",\")[0]])\n \n temp=np.array(line.split(\",\")[1:])\n \n array = temp.astype(np.float)\n \n min_val=min(array)\n max_val=max(array)\n# print min_val\n# print max_val\n # for each line, normalize the value between 0 and 1\n for i in range(0,len(array)):\n normalized_data[line_no].append((array[i]-min_val)/(max_val - min_val))\n\n #every 3 lines, calculate a mean list\n if line_no%3==2:\n normalized_mean.append([normalized_data[line_no][0]] + map(average,normalized_data[line_no-2][1:],normalized_data[line_no-1][1:],normalized_data[line_no][1:]))\n \n line_no = line_no +1\n \n \n\nfor ele in normalized_mean:\n print>>fout, ele\n\nfin.close()\nfout.close()\n","sub_path":"normalize_by_line.py","file_name":"normalize_by_line.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"149211020","text":"import tornado.websocket\n\nclass ChatHandler(tornado.websocket.WebSocketHandler):\n\n connections = set() #set for storing all current connections\n\n messages = [] #an array for storing the servers current messages\n\n def open(self):\n\n print(\"new Connection\")\n #add connection to the connection set\n self.connections.add(self)\n #send all the messages to the newly connected user\n for msg in self.messages:\n self.write_message(msg)\n\n def on_message(self, message):\n\n\n if message == \"user is typing...\":\n #now send the message to all connections\n for conn in self.connections:\n if conn is not self:\n conn.write_message(message)\n return\n\n for conn in self.connections:\n conn.write_message(message)\n #we have recieved a message therefore we'll add it to the list and send it to all users\n self.messages.append(message)\n\n\n\n def on_close(self):\n #remove this connection from the set\n self.connections.discard(self)\n return\n","sub_path":"application/handlers/ChatHandler.py","file_name":"ChatHandler.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"393175299","text":"import torch\nimport threading\nimport pickle\n\nfrom torch.utils.data import IterDataPipe, communication, MapDataPipe\n\n__all__ = [\n \"DataPipeToQueuesLoop\",\n \"SpawnProcessForDataPipeline\",\n \"SpawnThreadForDataPipeline\",\n]\n\ndef DataPipeToQueuesLoop(source_datapipe, req_queue, res_queue):\n if isinstance(source_datapipe, IterDataPipe):\n pipe_type = communication.iter\n protocol_type = communication.protocol.IterDataPipeQueueProtocolServer\n elif isinstance(source_datapipe, MapDataPipe):\n pipe_type = communication.map # type: ignore[misc]\n protocol_type = communication.protocol.MapDataPipeQueueProtocolServer # type: ignore[assignment]\n else:\n raise Exception('Only supports IterDataPipe or MapDataPipe, got', source_datapipe)\n\n torch.set_num_threads(1)\n for _ in pipe_type.DataPipeBehindQueues(source_datapipe, protocol_type(req_queue, res_queue),\n blocking_request_get=True):\n pass\n\n\ndef SpawnProcessForDataPipeline(multiprocessing_ctx, datapipe):\n req_queue = multiprocessing_ctx.Queue()\n res_queue = multiprocessing_ctx.Queue()\n process = multiprocessing_ctx.Process(\n target=DataPipeToQueuesLoop, args=(datapipe, req_queue, res_queue))\n return process, req_queue, res_queue\n\n\ndef SpawnThreadForDataPipeline(datapipe):\n r\"\"\"\n Given a DataPipe, creates a copy of the DataPipe, starts a new Thread with DataPipeToQueuesLoop as target,\n and return the process, req_queue, res_queue, thread_local_datapipe.\n \"\"\"\n req_queue = communication.queue.ThreadingQueue()\n res_queue = communication.queue.ThreadingQueue()\n\n try:\n new_datapipe = pickle.loads(pickle.dumps(datapipe))\n except Exception as e:\n raise Exception('Unable to pickle DataPipe to make thread local copy', e)\n\n process = threading.Thread(target=DataPipeToQueuesLoop, args=(\n new_datapipe, req_queue, res_queue), daemon=True)\n return process, req_queue, res_queue, new_datapipe\n","sub_path":"torch/utils/data/communication/eventloop.py","file_name":"eventloop.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"109067259","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 7 18:12:23 2017\n\n@author: davidmoran\n\"\"\"\nfrom investor import Investor\nfrom realtimedata import info, buy, sell\nfrom honchopool import pools\n\nclass Honcho(Investor):\n \"\"\"Represents a Honcho account\n \n This is only for certified Honcho accounts. I probably will later have\n a class for all accounts, and have this Honcho class inherit that.\n \"\"\"\n # Made-up betas to use for testing\n betasixmonth = {'GOOG': 1.23, 'AMZN': 1.1, 'MSTX': .43}\n #First number is ratio of gains kept, second number is ratio of losses covered\n rank_ratio = {1: (.15, .05), 2: (.14, .06), 3: (.13, .07), 4: (.12, .08), \n 5: (.11, .09), 6: (.1, .1)}\n rank_benchmarks = {1: 90, 2: 80, 3: 70, 4: 60, 5: 50, 6: 0}\n\n def __init__(self, username, industry, performance=100.0):\n \"\"\"Adds a new Honcho account\n \n :param hportfolio: Shares of each stock in portfolio\n :param hcash: Investable money from Honcho stipend\n :param hportfolio_avg_price: Average price of each stock in portfolio\n :param industry: Industry that Honcho has the most equity in\n :param performance: Performance score; 100.0 is max\n :param risk: Risk score; 1.0 is average\n :param rank: Rank of Honcho\n :param diverse: Diversification score; 1.0 is max\n :param lowrisk: Exempt from risk filter if True\n :param highdiverse: Exempt from diversification filter if True\n :param pool: HonchoPool object representing active pool\n \"\"\"\n Investor.__init__(self, username=username, honcho=True)\n self.hportfolio = {}\n self.hcash = 0.0\n self.hportfolio_avg_price = {}\n self.industry = industry\n self.performance = performance\n self.rank = self.update_performance()\n self.risk = 1.0\n self.diverse = 1.0\n self.low_risk = True\n self.high_diverse = True\n '''\n The next two lines are ostensibly very confusing - self.pool is a\n reference to a HonchoPool object. self.pool attribute honchos, which\n is a list of all Honchos that currently belong to this pool. So here\n we're initalizing all Honchos to a pool with low risk and high\n diversity. The industry is set as a parameter.\n '''\n self.pool = pools[self.industry][self.low_risk][self.high_diverse]\n self.pool.honchos.append(self)\n\n def honcho_buy(self, ticker, shares):\n \"\"\"Market buy with Honcho money\"\"\"\n equity = buy(ticker=ticker, shares=shares)\n pps = equity / shares\n\n if equity > self.hcash:\n return \"Insufficient funds. You have only $%s\" % self.cash\n\n self.hcash -= equity\n\n if ticker in self.hportfolio:\n oldshares = self.hportfolio[ticker]\n self.hportfolio[ticker] += shares\n old_weight = oldshares / self.hportfolio[ticker]\n new_weight = shares / self.hportfolio[ticker]\n self.hportfolio_avg_price[ticker] *= old_weight\n self.hportfolio_avg_price[ticker] += new_weight * pps\n else:\n self.hportfolio[ticker] = shares\n self.hportfolio_avg_price[ticker] = pps\n\n if ticker in self.pool.portfolio:\n self.pool.portfolio[ticker] += shares\n else:\n self.pool.portfolio[ticker] = shares\n\n def honcho_sell(self, ticker, shares):\n \"\"\"Market sell with Honcho money\"\"\"\n if self.hportfolio[ticker] < shares:\n return \"You can only sell a maximum of %s shares\" % self.portfolio[ticker]\n equity = sell(ticker=ticker, shares=shares)\n change = equity - self.hportfolio_avg_price[ticker] * shares\n\n if change >= 0:\n gain_ratio = self.rank_ratio[self.rank][0]\n honcho_reward = gain_ratio * change\n self.cash += honcho_reward\n self.hcash += equity - honcho_reward\n else:\n #Ratio of loss covered by Honcho\n cover_ratio = self.rank_ratio[self.rank][1]\n honcho_cover = cover_ratio * change\n self.portfolio -= honcho_cover\n self.pool.reservemoney += honcho_cover\n self.hcash += equity\n\n self.hportfolio[ticker] -= shares\n self.pool.portfolio[ticker] -= shares\n\n if self.hportfolio[ticker] == 0:\n self.hportfolio.pop(ticker)\n if self.pool.portfolio[ticke] == 0:\n self.pool.portfolio.pop(ticker)\n\n def get_honcho_equity(self, cash=True):\n \"\"\"Returns current portfolio information, adjusting for reward/cover\n\n :rtype portfolio_equity: dict\n :rtype total_equity: float\n \"\"\"\n portfolio_equity = {'cash': self.hcash} if cash else {}\n total_equity = self.hcash if cash else 0.0\n\n for ticker, shares in self.hportfolio.iteritems():\n stock_equity = info(ticker=ticker, shares=shares)\n change = stock_equity - self.hportfolio_avg_price[ticker] * shares\n #Gain\n if change >= 0:\n gain_ratio = self.rank_ratio[self.rank][0]\n honcho_reward = gain_ratio * change\n stock_equity -= honcho_reward\n #Loss\n else:\n cover_ratio = self.rank_ratio[self.rank][1]\n honcho_cover = cover_ratio * change\n stock_equity += honcho_cover\n portfolio_equity[ticker] = stock_equity\n total_equity += stock_equity\n\n return portfolio_equity, total_equity\n\n\n def get_weight(self):\n \"\"\"Returns dictionary of portfolio weights\"\"\"\n portfolio_weight = {}\n portfolio_equity, total_equity = self.get_honcho_equity()\n for ticker, eq in portfolio_equity.iteritems():\n # The equity weights should add up to 1.0\n portfolio_weight[ticker] = eq / total_equity\n return portfolio_weight\n\n def update_performance(self):\n \"\"\"Updates performance score and rank of Honcho (As of now this method does nothing)\n \n This will likely be called periodically, perhaps on market close\n \"\"\"\n changefactor = 1.0\n # Do something here to determine the changefactor\n self.performance *= changefactor\n for rank, benchmark in self.rank_benchmarks.iteritems():\n if self.performance >= benchmark:\n return rank\n\n def update_pool(self, newindustry=None):\n \"\"\"Updates industry, risk, and diverse scores, changing pools if necessary\"\"\"\n oldpool = self.pool\n self.update_industry(newindustry=newindustry)\n self.update_risk()\n self.update_diverse()\n self.pool = pools[self.industry][self.low_risk][self.high_diverse]\n\n if self.pool is not oldpool:\n oldpool.remove(self)\n self.pool.append(self)\n owed = self.hcash + self.get_honcho_equity()\n oldpool.reserve_money += owed\n newpool.reserve_money -= owed\n\n def update_industry(self, newindustry=None):\n if newindustry:\n self.industry = newindustry\n\n def update_risk(self, betadata=betasixmonth):\n \"\"\"Updates beta of Honcho\"\"\"\n portfolio_weight = self.get_weight()\n totalbeta = 0.0\n for ticker, weight in portfolio_weight.iteritems():\n totalbeta += weight * betadata[ticker]\n # Average the total beta for all stocks\n self.beta = totalbeta / len(portfolio_weight)\n self.low_risk = True if self.beta > .9 else False\n\n def update_diverse(self):\n \"\"\"Updates diversification score of Honcho\n \n The best diversification score one can get is 1.0 - this is unlike\n performance score and beta\n \"\"\"\n new_score = 1.0\n portfolio_weight = self.get_weight()\n # Subtract sum of squares for equity weights over .05 from 1.0\n for weight in portfolio_weight.itervalues():\n # Ignore weights under .05 - this way, a score of 1.0 is possible\n if weight > .05:\n new_score -= weight ** 2\n self.diverse = new_score\n self.high_diverse = True if self.diverse > .75 else False\n","sub_path":"Structure/honchorole.py","file_name":"honchorole.py","file_ext":"py","file_size_in_byte":8228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"258463479","text":"from art import logo\nfrom random import choice\ndef return_total(deck):\n total = 0\n for c in deck:\n total += c\n return total\ndef win_announce(a,b,c):\n if a == \"C\":\n print(f\"Winner is Computer, user card: {user_card}, Computer cards: {computer_card}\")\n elif a == \"U\":\n print(f\"Winner is User, user card: {user_card}, Computer cards: {computer_card}\")\n elif a== \"D\":\n print(f\"DRAW, user card: {user_card}, Computer cards: {computer_card}\")\n \ndef decide_winner(u_card,c_card):\n if return_total(u_card) > return_total(c_card):\n return \"U\"\n elif return_total(u_card) < return_total(c_card):\n return \"C\"\n else:\n return \"D\"\n\n\n############### Blackjack Project #####################\n\n#Difficulty Normal 😎: Use all Hints below to complete the project.\n#Difficulty Hard 🤔: Use only Hints 1, 2, 3 to complete the project.\n#Difficulty Extra Hard 😭: Only use Hints 1 & 2 to complete the project.\n#Difficulty Expert 🤯: Only use Hint 1 to complete the project.\n\n############### Our Blackjack House Rules #####################\n\n## The deck is unlimited in size. \n## There are no jokers. \n## The Jack/Queen/King all count as 10.\n## The the Ace can count as 11 or 1.\n## Use the following list as the deck of cards:\n\n## The cards in the list have equal probability of being drawn.\n## Cards are not removed from the deck as they are drawn.\n## The computer is the dealer.\n\n##################### Hints #####################\ncards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\nur_choice = input(\"Do you want to play a game of Blackjack? Type 'y' or 'n': \").lower()\nif ur_choice == \"y\":\n print(logo) \n user_card =[choice(cards), choice(cards)]\n computer_card = [choice(cards), choice(cards)]\n winner = \"\"\n print(f\"Your cards: {user_card}\")\n print(f\"Computer's first card: {computer_card}\")\n winner = \"\"\n if 11 in user_card and 10 in user_card:\n if 11 in computer_card and 10 in computer_card:\n print(\"Both having BLACKJACK...Draw...U: {user_card} and C: {computer_card}\")\n else:\n print(\"You having BLACKJACK...You win...U: {user_card} and C: {computer_card}\")\n elif 11 in computer_card and 10 in computer_card:\n print(\"Computer having BLACKJACK...Computer wins...U: {user_card} and C: {computer_card}\")\n else:\n print(\"Rest code goes here\")\n loop1 = True\n while loop1:\n if(return_total(user_card) > 21):\n print(f\"user card > 21: U : {user_card}\")\n if 11 in user_card:\n print(f\"11 in user card: U : {user_card}\")\n user_card[user_card.index(11)] = 1\n print(f\"User card after replacing11 with 1: U : {user_card}\")\n if (return_total(user_card) > 21):\n print(f\"User card after replacing11 with 1 > 21: u : {user_card}\")\n winner = \"C\"\n loop1 = False \n else:\n print(f\"User card after replacing11 with 1 < 21: u : {user_card}\")\n ch = input(\"'y' for Hit, 'n' for stand: \").lower()\n if ch == \"y\":\n loop1 = True\n user_card.append(choice(cards))\n print(f\"User card after adding new card 1 : u : {user_card}\")\n else:\n loop1 = False\n print(f\"User card : u : {user_card}\")\n else:\n winner = \"C\"\n loop1 = False \n else:\n ch = input(\"'y' for Hit, 'n' for stand: \").lower()\n if ch == \"y\":\n loop1 = True\n user_card.append(choice(cards))\n print(f\"User card after adding new card 2 : u : {user_card}\")\n else:\n loop1 = False\n print(f\"User card : u : {user_card}\")\n #callCompPLay for 17\n if winner != \"\":\n win_announce(winner,user_card,computer_card)\n else:\n loop2 = True\n while loop2:\n if return_total(computer_card) < 17:\n next_card = choice(cards)\n print(f\"NC:{next_card}\")\n if next_card == 11:\n if return_total(computer_card)+next_card > 21:\n computer_card.append(1)\n elif return_total(computer_card)+next_card == 21:\n computer_card.append(next_card)\n win_announce(\"C\",user_card,computer_card)\n loop2=False\n else:\n if return_total(computer_card)+next_card < 21:\n computer_card.append(next_card)\n else:\n computer_card.append(next_card)\n win_announce(\"U\",user_card,computer_card)\n loop2=False\n else:\n winner = decide_winner(user_card,computer_card)\n win_announce(winner,user_card,computer_card)\n loop2=False\n \n\nelse:\n print(\"Bye...\")\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"23356261","text":"import gym\nimport numpy as np\nimport torch\nimport argparse\nimport os\nimport time\nimport multiprocessing as mp\n\nimport utils_local\nimport DDPG\nimport TD3_SQIL\n\n# def load_model(model_name='TD3', original=False):\n# if model_name == TD3:\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--env_name\", default=\"Hopper-v2\") # OpenAI gym environment name\n parser.add_argument(\"--seed\", default=1, type=int) # Sets Gym, PyTorch and Numpy seeds\n parser.add_argument(\"--buffer_type\", default=\"Robust\") # Prepends name to filename.\n parser.add_argument(\"--eval_freq\", default=1e3, type=float) # How often (time steps) we evaluate\n parser.add_argument(\"--num_trajs\", default=5, type=int) # Number of expert trajectories to use\n parser.add_argument(\"--num_imitators\", default=5, type=int) # Number of BC imitators in the ensemble\n parser.add_argument(\"--max_timesteps\", default=1e5, type=float) # Max time steps to run environment for\n parser.add_argument(\"--good\", action='store_true', default=False) # Good or mixed expert trajectories\n parser.add_argument(\"--expl_noise\", default=0.1, type=float) # Std of Gaussian exploration noise\n\n parser.add_argument(\"--start_timesteps\", default=1e3, type=int)\n\n parser.add_argument('--log-std', type=float, default=-0.0, metavar='G',\n help='log std for the policy (default: -0.0)')\n parser.add_argument('--gamma', type=float, default=0.99, metavar='G',\n help='discount factor (default: 0.99)')\n parser.add_argument('--tau', type=float, default=0.95, metavar='G',\n help='gae (default: 0.95)')\n parser.add_argument('--l2-reg', type=float, default=1e-3, metavar='G',\n help='l2 regularization regression (default: 1e-3)')\n parser.add_argument('--learning-rate', type=float, default=3e-4, metavar='G',\n help='gae (default: 3e-4)')\n parser.add_argument('--clip-epsilon', type=float, default=0.2, metavar='N',\n help='clipping epsilon for PPO')\n\n args = parser.parse_args()\n\n expert_type = 'good'\n file_name = \"SQIL_TD3_%s_traj%s_seed%s_%s\" % (args.env_name, args.num_trajs, str(args.seed), expert_type)\n # buffer_name = \"%s_traj100_%s_%s\" % (args.buffer_type, args.env_name, str(args.seed))\n buffer_name = \"%s_traj100_%s_0\" % (args.buffer_type, args.env_name)\n\n expert_trajs = np.load(\"./buffers/\"+buffer_name+\".npy\", allow_pickle=True)\n expert_rewards = np.load(\"./buffers/\"+buffer_name+\"_rewards\" + \".npy\", allow_pickle=True)\n flat_expert_trajs = utils_local.collect_trajectories_rewards(expert_trajs, good=args.good)\n\n print(\"---------------------------------------\")\n print(\"Settings: \" + file_name)\n print(\"\")\n print(\"---------------------------------------\")\n\n if not os.path.exists(\"./results\"):\n os.makedirs(\"./results\")\n\n env = gym.make(args.env_name)\n\n env.seed(args.seed)\n torch.manual_seed(args.seed)\n np.random.seed(args.seed)\n\n state_dim = env.observation_space.shape[0]\n action_dim = env.action_space.shape[0]\n max_action = float(env.action_space.high[0])\n\n # Initialize policy and imitator ensemble\n policy = TD3_SQIL.TD3_SQIL(state_dim, action_dim, max_action)\n\n # Initialize buffers\n expert_buffer = utils_local.ReplayBuffer()\n expert_buffer.set_expert(flat_expert_trajs)\n\n replay_buffer = utils_local.ReplayBuffer()\n\n total_timesteps = 0\n episode_reward = 0\n episode_num = 0\n done = True\n\n expert_rewards = []\n expert_timesteps = []\n while total_timesteps < args.max_timesteps:\n\n if done:\n\n if total_timesteps != 0:\n print(\"Total T: %d Episode Num: %d Episode T: %d Reward: %f\" % (\n total_timesteps, episode_num, episode_timesteps, episode_reward))\n policy.train(expert_buffer, expert=True)\n policy.train(replay_buffer)\n\n # Save policy\n if total_timesteps % 1e5 == 0:\n np.save(\"./results/\" + file_name + '_rewards', expert_rewards)\n np.save(\"./results/\" + file_name + '_timesteps', expert_timesteps)\n policy.save(file_name, directory=\"./imitator_models\")\n\n expert_rewards.append(episode_reward)\n expert_timesteps.append(total_timesteps)\n\n # Reset environment\n obs = env.reset()\n done = False\n episode_reward = 0\n episode_timesteps = 0\n episode_num += 1\n\n # Select action randomly or according to policy\n if total_timesteps < args.start_timesteps:\n action = env.action_space.sample()\n else:\n action = policy.select_action(np.array(obs))\n if args.expl_noise != 0:\n action = (action + np.random.normal(0, args.expl_noise, size=env.action_space.shape[0])).clip(\n env.action_space.low, env.action_space.high)\n\n # Perform action\n new_obs, reward, done, _ = env.step(action)\n done_bool = 0 if episode_timesteps + 1 == env._max_episode_steps else float(done)\n episode_reward += reward\n\n # Store data in replay buffer\n replay_buffer.add((obs, new_obs, action, reward, done_bool))\n\n obs = new_obs\n\n episode_timesteps += 1\n total_timesteps += 1\n\n np.save(\"./results/\" + file_name + '_rewards', expert_rewards)\n np.save(\"./results/\" + file_name + '_timesteps', expert_timesteps)\n\n # Save final policy\n policy.save(\"%s\" % (file_name), directory=\"./imitator_models\")","sub_path":"train_td3_sqil.py","file_name":"train_td3_sqil.py","file_ext":"py","file_size_in_byte":5646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"289084758","text":"import pylinkedcmd\nimport pandas as pd\nfrom sqlalchemy import create_engine\nfrom joblib import Parallel, delayed\nimport tqdm\nfrom datetime import datetime\nimport dateutil\nimport os\n\ncmd_pw = pylinkedcmd.pylinkedcmd.Pw()\n\npw_api = \"https://pubs.er.usgs.gov/pubs-services/publication/\"\n\npg_user = os.environ[\"PG_USER\"]\npg_pass = os.environ[\"PG_PASS\"]\npg_host = os.environ[\"PG_HOST\"]\npg_port = os.environ[\"PG_PORT\"]\npg_db = os.environ[\"PG_DB\"]\n\npg_engine = create_engine(f'postgresql://{pg_user}:{pg_pass}@{pg_host}:{pg_port}/{pg_db}')\n\nlast_record = pd.read_sql_query(\n \"SELECT max(datemodified) AS lastrecord FROM assets WHERE url LIKE '%pubs.er.usgs.gov%'\",\n pg_engine\n)[\"lastrecord\"][0]\nlast_x_days = abs((datetime.now()-dateutil.parser.parse(last_record)).days)\n\nsummarization = {\n \"assets\": list(),\n \"sentences\": list(),\n \"contacts\": list(),\n \"claims\": list(),\n \"links\": list()\n}\n\n\ndef accumulator(pw_doc):\n item_data = cmd_pw.summarize_pw_record(pw_doc, parse_sentences=True)\n for k, v in item_data.items():\n if isinstance(v, list):\n summarization[k].extend(v)\n else:\n summarization[k].append(v)\n\n\nif last_x_days > 0:\n modified_records = cmd_pw.pw_modifications(last_x_days)\n\n if len(modified_records) > 0:\n Parallel(n_jobs=50, prefer=\"threads\")(\n delayed(accumulator)\n (\n pw_item\n ) for pw_item in tqdm.tqdm(modified_records)\n )\n\n for k, v in summarization.items():\n if len(v) > 0:\n urls_for_query = str(\n [\n i[\"url\"] for i in v\n ]).replace('\"', \"'\").replace(\"[\", \"(\").replace(\"]\", \")\")\n\n with pg_engine.connect() as con:\n rs = con.execute(f\"DELETE FROM {k} WHERE url in {urls_for_query}\")\n\n pd.DataFrame(v).to_sql(\n k,\n pg_engine,\n index=False,\n if_exists=\"append\",\n chunksize=1000\n )\n","sub_path":"examples/isaid_scripts/cache_pw_update.py","file_name":"cache_pw_update.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"564247588","text":"\"\"\"\nDevice tracker platform that adds support for OwnTracks over HTTP.\n\nFor more details about this platform, please refer to the documentation at\nhttps://home-assistant.io/components/device_tracker.owntracks_http/\n\"\"\"\nimport json\nimport logging\nimport re\n\nfrom aiohttp.web import Response\nimport voluptuous as vol\n\n# pylint: disable=unused-import\nfrom homeassistant.components.device_tracker.owntracks import ( # NOQA\n PLATFORM_SCHEMA, REQUIREMENTS, async_handle_message, context_from_config)\nfrom homeassistant.const import CONF_WEBHOOK_ID\nimport homeassistant.helpers.config_validation as cv\n\nDEPENDENCIES = ['webhook']\n\n_LOGGER = logging.getLogger(__name__)\n\nEVENT_RECEIVED = 'owntracks_http_webhook_received'\nEVENT_RESPONSE = 'owntracks_http_webhook_response_'\n\nDOMAIN = 'device_tracker.owntracks_http'\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_WEBHOOK_ID): cv.string\n})\n\n\nasync def async_setup_scanner(hass, config, async_see, discovery_info=None):\n \"\"\"Set up OwnTracks HTTP component.\"\"\"\n context = context_from_config(async_see, config)\n\n subscription = context.mqtt_topic\n topic = re.sub('/#$', '', subscription)\n\n async def handle_webhook(hass, webhook_id, request):\n \"\"\"Handle webhook callback.\"\"\"\n headers = request.headers\n data = dict()\n\n if 'X-Limit-U' in headers:\n data['user'] = headers['X-Limit-U']\n elif 'u' in request.query:\n data['user'] = request.query['u']\n else:\n return Response(\n body=json.dumps({'error': 'You need to supply username.'}),\n content_type=\"application/json\"\n )\n\n if 'X-Limit-D' in headers:\n data['device'] = headers['X-Limit-D']\n elif 'd' in request.query:\n data['device'] = request.query['d']\n else:\n return Response(\n body=json.dumps({'error': 'You need to supply device name.'}),\n content_type=\"application/json\"\n )\n\n message = await request.json()\n\n message['topic'] = '{}/{}/{}'.format(topic, data['user'],\n data['device'])\n\n try:\n await async_handle_message(hass, context, message)\n return Response(body=json.dumps([]), status=200,\n content_type=\"application/json\")\n except ValueError:\n _LOGGER.error(\"Received invalid JSON\")\n return None\n\n hass.components.webhook.async_register(\n 'owntracks', 'OwnTracks', config['webhook_id'], handle_webhook)\n\n return True\n","sub_path":"homeassistant/components/device_tracker/owntracks_http.py","file_name":"owntracks_http.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"89806069","text":"\n# coding: utf-8\n\n# \n# # Project: Investigate Dataset of Appointments Set for Nearby Hospitals\n# \n# ## Table of Contents\n# \n\n# \n# ## Introduction\n# \n# Libraries such as pandas, numpy, matplotlib and seaborn are imported.Data from 'noshoowappointments.csv' consisting of appointments set for a hospital is loaded.The data consists of patient Id, appoinment Id, gender of patient, the day when appointment was scheduled,appointment day,age,neighbourhood,whether scholarship was given, disease, whether SMS was recieved and whether they turned up for the appointment.\n\n# In[22]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[23]:\n\n\ndf=pd.read_csv('noshowappointments.csv')\ndf.head()\n\n\n# The number of rows,columns of the dataset along with datypes and statistics of each column are found out.\n\n# In[27]:\n\n\ndf.shape\n\n\n# In[48]:\n\n\npd.to_datetime(df['AppointmentDay'])\ndf['month']=df['AppointmentDay'].dt.month\ndf.head()\n\n\n# In[29]:\n\n\ndf.dtypes\n\n\n# In[30]:\n\n\ndf.describe()\n\n\n# From the statistics one can note that the mean age of the patient is around 37, majority of them are between 18 and 55.Fewer people got scholarship and most patients suffer from hipertension.\n\n# \n# ## Data Wrangling\n\n# An attempt was made to find out the null values and duplicates.The column 'SMS_recieved' is dropped since it is not going to be used in analyzing the data.\n\n# In[31]:\n\n\ndf.info()\n\n\n# In[32]:\n\n\ndf.nunique()\n\n\n# In[33]:\n\n\nsum(df.duplicated())\n\n\n# There are no null values and duplicate values.\n\n# In[49]:\n\n\ndf.drop(['SMS_received'],axis=1)\ndf.head()\n\n\n# \n# ## Exploratory Data Analysis & Conclusion\n\n# The overall dataframe has been plotted.\n\n# In[28]:\n\n\ndf.hist(figsize=(25,15))\n\n\n# \n# ### Research Question 1 (What is the number of people showing up for the appointment?)\n\n# In[9]:\n\n\ndf1=df['No-show'].value_counts().plot(kind='bar',figsize=(8,10),title='no.people showing up for appointment')\ndf1.set_xlabel('no-show')\ndf1.set_ylabel('count')\n\n\n# It has been found out that nearly 5 times the number of people were absent for the scheduled appointment compared to number of people who were present. \n\n# \n# ### Research Question 2 (What is the total number of patients suffering from Hipertension)\n\n# In[30]:\n\n\nHipertension_patient=df['Hipertension'].sum()\nHipertension_patient\n\n\n# 21801 people suffer from hipertention.\n\n# \n# ### Research Question 3 (What is the statistics of total number of scholarship given to patients from different neighbourhood?)\n# \n\n# In[42]:\n\n\ndf.groupby('Neighbourhood').sum().Scholarship.describe()\n\n\n# Each neighbourhood is granted an average of 100 scholorships\n\n# \n# ### Research Question 4 (What is the total number of each type of patients showing up for appointments?)\n\n# In[21]:\n\n\ndef app_y():\n if element in df[df['No-show']==\"Yes\"]:\n return df\napp_y().describe()\n\n\n# In[23]:\n\n\napp_y().iloc[:,8:12].sum()\n\n\n# Given that the patients show up for the appointment, the most number of patients suffer from hipertention and the least are handicapped.Patients who are granted scholarship have got higher probability of turning up for the appoitment \n\n# \n# ### Research Question 5 (Which neighbourhood has got maximum number of patients turning up for appointments?)\n\n# In[25]:\n\n\napp_y()['Neighbourhood'].max()\n\n\n# The maximum number of patients who turn up for the appointment are from 'VILA RUBIM' \n\n# \n# ### Research Question 6 (What is the total number of scholarships granted for people of different age sector?)\n\n# In[36]:\n\n\nbin_edges=[0,30,60,90,120]\nbin_names=['young','middle-aged','old','v.old']\ndf['Age seg']=pd.cut(df['Age'],bin_edges,labels=bin_names)\ndf.head()\n\n\n# In[37]:\n\n\nage_scholarship=df.groupby('Age seg').sum().Scholarship\nage_scholarship\n\n\n# In[38]:\n\n\ndf_plot_schol=age_scholarship.plot(kind='bar',title='Scholorship')\ndf_plot_schol.set_xlabel('Age seg')\ndf_plot_schol.set_ylabel('frequency')\n\n\n# Young patients have got the highest scholarships.\n\n# \n# ### Research Question 7 (What is the total number of diabetic patients of different age sector?)\n\n# In[39]:\n\n\nage_diab=df.groupby('Age seg').Diabetes.sum()\n\n\n# In[40]:\n\n\ndf_plot_diab=age_diab.plot(kind='bar', title='Age of diabetic patient')\ndf_plot_diab.set_xlabel('age seg')\ndf_plot_diab.set_ylabel('frequency')\n\n\n# Old patients between the age of 60 to 90 suffer from diabetes the most.\n\n# ### Research Question 8 (What is the correlation between various columns of dataset?)\n\n# In[20]:\n\n\ndf.corr()\n\n\n# In[18]:\n\n\n#cols=[4,5,6]\n#df=df[df.columns[cols]]\ncorr=df.corr()\nplt.figure(figsize=(10,60))\nplt.matshow(corr,fignum=1)\nplt.xticks(range(len(corr.columns)), corr.columns);\nplt.yticks(range(len(corr.columns)), corr.columns);\n\n\n# Age is positively correlated to all diseases(i.e. with increase in age there is higher chance of suffering from a disease).Age is negatively correlated to scholarship(i.e the yonger lot has higher chance of getting a scholarship)\n","sub_path":"Project.py","file_name":"Project.py","file_ext":"py","file_size_in_byte":5213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"470890270","text":"import argparse\nimport torch\nimport torch.nn\nfrom torch import nn\nimport torchvision\nimport os, sys\nfrom data_process import *\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.nn.functional as F\nfrom sklearn.utils.multiclass import type_of_target\n\n#### setting agrparse\nparser = argparse.ArgumentParser(description='Training')\n##### input\nparser.add_argument('--w2v_file', type=str, default='../data/w2v_200.txt', help='embedding file')\nparser.add_argument('--embedding_dim', type=int, default=200, help='dimension of word embedding')\nparser.add_argument('--embedding_dim_pos', type=int, default=50, help='dimension of position embedding')\nparser.add_argument('--max_sen_len', type=int, default=30, help='max number of tokens per sentence')\nparser.add_argument('--max_doc_len', type=int, default=75, help='max number of tokens per documents')\n##### model struct\nparser.add_argument('--n_hidden', type=int, default=100, help='number of hidden unit')\nparser.add_argument('--n_class', type=int, default=2, help='number of distinct class')\nparser.add_argument('--log_file_name', type=str, default='log', help='name of log file')\n##### traing\nparser.add_argument('--training_iter', type=int, default=15, help='number of train iterator')\nparser.add_argument('--scope', type=str, default='RNN', help='scope')\nparser.add_argument('--batch_size', type=int, default=32, help='number of example per batch')\nparser.add_argument('--learning_rate', type=float, default=0.005, help='learning rate')\n# parser.add_argument('--learning_rate', type=float, default=0.05, help='learning rate')\n\nparser.add_argument('--keep_prob1', type=float, default=0.8, help='word embedding training dropout keep prob')\nparser.add_argument('--keep_prob2', type=float, default=1.0, help='softmax layer dropout keep prob')\nparser.add_argument('--l2_reg', type=float, default=0.00001, help='l2 regularization')\nparser.add_argument('--cause', type=float, default=1.000, help='lambda1')\nparser.add_argument('--pos', type=float, default=1.00, help='lambda2')\nparser.add_argument('--usegpu', type=bool, default=True, help='gpu')\nopt = parser.parse_args()\nif opt.usegpu and torch.cuda.is_available():\n use_gpu = True\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"6,7\"\n\n\ndef print_training_info():\n print('\\n\\n>>>>>>>>>>>>>>>>>>>>TRAINING INFO:\\n')\n print('batch-{}, lr-{}, kb1-{}, kb2-{}, l2_reg-{}'.format(\n opt.batch_size, opt.learning_rate, opt.keep_prob1, opt.keep_prob2, opt.l2_reg))\n print('training_iter-{}, scope-{}\\n'.format(opt.training_iter, opt.scope))\n\n\nclass MyDataset(Dataset):\n def __init__(self, input_file, word_idx, batchsize=opt.batch_size, max_doc_len=75, max_sen_len=45, test=False,\n transforms=None):\n self.transforms = transforms # NLP中实际上没用到\n print('load data_file: {}'.format(input_file))\n self.y_pairs, self.doc_len, self.y_position, self.y_cause, self.x, self.sen_len = [], [], [], [], [], []\n self.doc_id = []\n self.test = test\n self.n_cut = 0\n self.batch_size = batchsize\n inputFile = open(input_file, 'r')\n while True:\n line = inputFile.readline()\n if line == '': break\n line = line.strip().split()\n self.doc_id.append(line[0])\n d_len = int(line[1])\n pairs = eval('[' + inputFile.readline().strip() + ']')\n self.doc_len.append(d_len)\n self.y_pairs.append(pairs)\n pos, cause = zip(*pairs)\n y_po, y_ca, sen_len_tmp, x_tmp = np.zeros((max_doc_len, 2)), np.zeros((max_doc_len, 2)), np.zeros(\n max_doc_len, dtype=np.int32), np.zeros((max_doc_len, max_sen_len), dtype=np.int32)\n for i in range(d_len):\n y_po[i][int(i + 1 in pos)] = 1\n y_ca[i][int(i + 1 in cause)] = 1 ####没有保留配对信息\n words = inputFile.readline().strip().split(',')[-1]\n sen_len_tmp[i] = min(len(words.split()), max_sen_len)\n for j, word in enumerate(words.split()):\n if j >= max_sen_len:\n self.n_cut = self.n_cut + 1\n break\n x_tmp[i][j] = int(word_idx[word])\n\n self.y_position.append(y_po)\n self.y_cause.append(y_ca)\n self.x.append(x_tmp)\n self.sen_len.append(sen_len_tmp)\n\n self.y_position, self.y_cause, self.x, self.sen_len, self.doc_len = map(np.array,\n [self.y_position, self.y_cause, self.x,\n self.sen_len, self.doc_len])\n for var in ['self.y_position', 'self.y_cause', 'self.x', 'self.sen_len', 'self.doc_len']:\n print('{}.shape {}'.format(var, eval(var).shape))\n print('n_cut {}'.format(self.n_cut))\n print('load data done!\\n')\n\n self.index = [i for i in range(len(self.y_cause))]\n\n def __getitem__(self, index):\n index = self.index[index]\n feed_list = [self.x[index], self.sen_len[index], self.doc_len[index], opt.keep_prob1, opt.keep_prob2,\n self.y_position[index],\n self.y_cause[index]]\n return feed_list\n\n def __len__(self):\n return len(self.x)\n\n\nclass attention(torch.nn.Module):\n def __init__(self, input_size, hidden_size):\n super(attention, self).__init__()\n self.bilstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, bidirectional=True, batch_first=True)\n self.sh2 = 2 * opt.n_hidden\n # self.linearlayer1 = nn.Linear(self.sh2,self.sh2).cuda()\n # self.linearlayer2 = nn.Linear(self.sh2,1,bias=False).cuda()\n self.w1 = get_weight_varible([self.sh2, self.sh2])\n self.w1.requires_grad = True\n self.b1 = get_weight_varible([self.sh2])\n self.b1.requires_grad = True\n self.w2 = get_weight_varible([self.sh2, 1])\n self.w2.requires_grad = True\n if use_gpu:\n self.w1 = self.w1.cuda()\n self.b1 = self.b1.cuda()\n self.w2 = self.w2.cuda()\n\n def forward(self, inputs, sen_len):\n r_out, (h_n, h_c) = self.bilstm(inputs)\n inputs = r_out\n self.sen_len = sen_len\n max_len, n_hidden = (inputs.shape[1], inputs.shape[2])\n tmp = torch.reshape(inputs, [-1, n_hidden])\n u = torch.tanh(torch.matmul(tmp, self.w1) + self.b1)\n alpha = torch.reshape(torch.matmul(u, self.w2), [-1, 1, max_len]) # 200->1\n alpha = softmax_by_length(alpha, self.sen_len, use_gpu)\n s = torch.reshape(torch.matmul(alpha, inputs), [-1, n_hidden])\n s = torch.reshape(s, [-1, opt.max_doc_len, 2 * opt.n_hidden])\n return s\n\n\nclass biLSTM(torch.nn.Module):\n def __init__(self, word_embedding, keep_prob1, keep_prob2, input_size=opt.n_hidden * 2, hidden_size=opt.n_hidden):\n super(biLSTM, self).__init__()\n\n self.causebilstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, bidirectional=True, batch_first=True)\n self.posbilstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, bidirectional=True, batch_first=True)\n self.attention = attention(input_size=input_size, hidden_size=hidden_size)\n self.keep_prob1 = keep_prob1\n self.keep_prob2 = keep_prob2\n self.word_embedding = word_embedding\n self.w1 = get_weight_varible([2 * opt.n_hidden, opt.n_class])\n self.w1.requires_grad = True\n self.b1 = get_weight_varible([opt.n_class])\n self.b1.requires_grad = True\n self.w2 = get_weight_varible([2 * opt.n_hidden, opt.n_class])\n self.w2.requires_grad = True\n self.b2 = get_weight_varible([opt.n_class])\n self.b2.requires_grad = True\n if use_gpu:\n self.w1 = self.w1.cuda()\n self.w2 = self.w2.cuda()\n self.b1 = self.b1.cuda()\n self.b2 = self.b2.cuda()\n\n # self.nnlayer_cause = nn.Linear(2 * opt.n_hidden, opt.n_class).cuda()\n # self.nnlayer_pos = nn.Linear(2 * opt.n_hidden, opt.n_class).cuda()\n\n def forward(self, x, sen_len, doc_len, keep_prob1, keep_prob2):\n self.keep_prob1 = keep_prob1\n self.keep_prob2 = keep_prob2\n self.sen_len = sen_len\n self.doc_len = doc_len\n x = x.long()\n x = torch.index_select(self.word_embedding, dim=0, index=torch.reshape(x, [-1]))\n if use_gpu:\n x = x.cuda()\n # x = x.float()\n # print('输出尺寸')\n # print(x.shape)\n # 输出尺寸\n # torch.Size([72000, 200])\n inputs = torch.reshape(x, [-1, opt.max_sen_len, opt.embedding_dim])\n inputs = torch.nn.Dropout(1.0 - self.keep_prob1)(inputs)\n sen_len = torch.reshape(self.sen_len, [-1])\n s = self.attention(inputs, sen_len)\n r_out, (h_n, h_c) = self.causebilstm(s)\n s = r_out\n s1 = torch.reshape(s, [-1, 2 * opt.n_hidden])\n s1 = torch.nn.Dropout(1.0 - self.keep_prob2)(s1)\n pred_cause = F.softmax(torch.matmul(s1, self.w1) + self.b1)\n pred_cause = torch.reshape(pred_cause, [-1, opt.max_doc_len, opt.n_class])\n\n ss = self.attention(inputs, sen_len)\n r_out, (h_n, h_c) = self.posbilstm(ss)\n ss = r_out\n ss1 = torch.reshape(ss, [-1, 2 * opt.n_hidden])\n ss1 = torch.nn.Dropout(1.0 - self.keep_prob2)(ss1)\n pred_pos = F.softmax(torch.matmul(ss1, self.w2) + self.b2)\n pred_pos = torch.reshape(pred_pos, [-1, opt.max_doc_len, opt.n_class])\n\n reg = torch.norm(self.w1) + torch.norm(self.b1)\n reg = reg + (torch.norm(self.w2) + torch.norm(self.b2))\n reg = reg / 2\n return pred_pos, pred_cause, reg\n\n\ndef print_training_info():\n print('\\n\\n>>>>>>>>>>>>>>>>>>>>TRAINING INFO:\\n')\n print('batch-{}, lr-{}, kb1-{}, kb2-{}, l2_reg-{}'.format(\n opt.batch_size, opt.learning_rate, opt.keep_prob1, opt.keep_prob2, opt.l2_reg))\n print('training_iter-{}, scope-{}\\n'.format(opt.training_iter, opt.scope))\n\n\ndef run():\n save_dir = 'pair_data/{}/'.format(opt.scope)\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n if opt.log_file_name:\n sys.stdout = open(save_dir + opt.log_file_name, 'w')\n print_time()\n\n # wordembedding\n word_idx_rev, word_id_mapping, word_embedding, pos_embedding = load_w2v(opt.embedding_dim, opt.embedding_dim_pos,\n 'data_combine/clause_keywords.csv',\n opt.w2v_file)\n word_embedding = torch.FloatTensor(word_embedding)\n pos_embedding = torch.FloatTensor(pos_embedding)\n\n # train\n print_training_info()\n acc_cause_list, p_cause_list, r_cause_list, f1_cause_list = [], [], [], []\n acc_pos_list, p_pos_list, r_pos_list, f1_pos_list = [], [], [], []\n p_pair_list, r_pair_list, f1_pair_list = [], [], []\n for fold in range(1, 11):\n # model\n print('build model..')\n model = biLSTM(word_embedding, opt.keep_prob1, opt.keep_prob2, opt.n_hidden * 2, opt.n_hidden)\n print('build model end...')\n if use_gpu:\n model = model.cuda()\n\n train_file_name = 'fold{}_train.txt'.format(fold)\n test_file_name = 'fold{}_test.txt'.format(fold)\n print('############# fold {} begin ###############'.format(fold))\n train = 'data_combine/' + train_file_name\n test = 'data_combine/' + test_file_name\n edict = {\"train\": train, \"test\": test}\n NLP_Dataset = {x: MyDataset(edict[x], word_id_mapping, batchsize=opt.batch_size\n , max_sen_len=opt.max_sen_len, max_doc_len=opt.max_doc_len\n , test=(x is 'test')) for x in ['train', 'test']}\n train_staticDataset = MyDataset(train, word_id_mapping, batchsize=opt.batch_size, max_sen_len=opt.max_sen_len,\n max_doc_len=opt.max_doc_len, test=True)\n trainloader = DataLoader(NLP_Dataset['train'], batch_size=opt.batch_size, shuffle=True, drop_last=True)\n testloader = DataLoader(NLP_Dataset['test'], batch_size=opt.batch_size, shuffle=False)\n train_staticloader = DataLoader(train_staticDataset, shuffle=False)\n\n max_f1_cause, max_f1_pos, max_f1_avg = [-1.] * 3\n for i in range(opt.training_iter):\n start_time, step = time.time(), 1\n for _, data in enumerate(trainloader):\n with torch.autograd.set_detect_anomaly(True):\n x, sen_len, doc_len, keep_prob1, keep_prob2, y_position, y_cause = data\n pred_pos, pred_cause, reg = model(x, sen_len, doc_len, opt.keep_prob1, opt.keep_prob2)\n pred_pos = pred_pos.cpu()\n pred_cause = pred_cause.cpu()\n reg = reg.cpu()\n # tensor([17., 13., 9., 18., 16., 10., 13., 7., 24., 13., 17., 13., 12., 14.,\n # 13., 14., 12., 11., 15., 10., 15., 20., 12., 25., 20., 18., 32., 10.,\n # 30., 15., 9., 20.])\n valid_num = torch.sum(doc_len)\n loss_pos = - torch.sum(y_position * torch.log(pred_pos).double()) / valid_num\n loss_cause = - torch.sum(y_cause * torch.log(pred_cause).double()) / valid_num\n loss_op = loss_cause * opt.cause + loss_pos * opt.pos + reg.double() * opt.l2_reg\n optimizer = torch.optim.Adam(model.parameters(), lr=opt.learning_rate)\n optimizer.zero_grad()\n if use_gpu:\n loss_op = loss_op.cuda()\n loss_op.backward()\n optimizer.step()\n\n true_y_cause_op = torch.argmax(y_cause, 2)\n pred_y_cause_op = torch.argmax(pred_cause, 2)\n true_y_pos_op = torch.argmax(y_position, 2)\n pred_y_pos_op = torch.argmax(pred_pos, 2)\n # print(y_cause.shape)\n if use_gpu:\n true_y_cause_op = true_y_cause_op.cpu()\n pred_y_cause_op = pred_y_cause_op.cpu()\n true_y_pos_op = true_y_pos_op.cpu()\n pred_y_pos_op = pred_y_pos_op.cpu()\n\n if step % 10 == 0:\n print('step {}: train loss {:.4f} '.format(step, loss_op))\n acc, p, r, f1 = acc_prf(pred_y_cause_op, true_y_cause_op, doc_len)\n print('cause_predict: train acc {:.4f} p {:.4f} r {:.4f} f1 {:.4f}'.format(acc, p, r, f1))\n acc, p, r, f1 = acc_prf(pred_y_pos_op, true_y_pos_op, doc_len)\n print('position_predict: train acc {:.4f} p {:.4f} r {:.4f} f1 {:.4f}'.format(acc, p, r, f1))\n step = step + 1\n testloss = 0\n testdatanum = 0\n alltestpred_pos = torch.tensor([])\n alltestpred_cause = torch.tensor([])\n alltesty_cause = torch.tensor([])\n alltesty_pos = torch.tensor([])\n alldoc_len = torch.tensor([])\n allsen_len = torch.tensor([])\n\n with torch.no_grad():\n for _, data in enumerate(testloader):\n x, sen_len, doc_len, keep_prob1, keep_prob2, y_position, y_cause = data\n pred_pos, pred_cause, reg = model(x, sen_len, doc_len, 1, 1)\n if use_gpu:\n pred_pos = pred_pos.cpu()\n pred_cause = pred_cause.cpu()\n reg = reg.cpu()\n alltestpred_cause = torch.cat((alltestpred_cause, pred_cause.float()), 0)\n alltestpred_pos = torch.cat((alltestpred_pos, pred_pos.float()), 0)\n alltesty_pos = torch.cat((alltesty_pos, y_position.float()), 0)\n alltesty_cause = torch.cat((alltesty_cause, y_cause.float()), 0)\n alldoc_len = torch.cat((alldoc_len, doc_len.float()), 0)\n allsen_len = torch.cat((allsen_len, sen_len.float()), 0)\n valid_num = torch.sum(doc_len).float()\n testdatanum = testdatanum + valid_num\n\n loss_pos = -torch.sum(alltesty_pos * torch.log(alltestpred_pos)) / testdatanum\n loss_cause = - torch.sum(alltesty_cause * torch.log(alltestpred_cause)) / testdatanum\n loss = loss_cause * opt.cause + loss_pos * opt.pos + reg * opt.l2_reg\n print('\\nepoch {}: test loss {:.4f} cost time: {:.1f}s\\n'.format(i, loss, time.time() - start_time))\n\n alltesty_cause_op = torch.argmax(alltesty_cause, 2)\n alltestpred_cause_op = torch.argmax(alltestpred_cause, 2)\n alltesty_pos_op = torch.argmax(alltesty_pos, 2)\n alltestpred_pos_op = torch.argmax(alltestpred_pos, 2)\n acc, p, r, f1 = acc_prf(alltestpred_cause_op.numpy(), alltesty_cause_op.numpy(),\n alldoc_len.int().numpy())\n result_avg_cause = [acc, p, r, f1]\n if f1 > max_f1_cause:\n max_acc_cause, max_p_cause, max_r_cause, max_f1_cause = acc, p, r, f1\n print('cause_predict: test acc {:.4f} p {:.4f} r {:.4f} f1 {:.4f}'.format(acc, p, r, f1))\n print('max_acc {:.4f} max_p {:.4f} max_r {:.4f} max_f1 {:.4f}\\n'.format(max_acc_cause, max_p_cause,\n max_r_cause, max_f1_cause))\n\n acc, p, r, f1 = acc_prf(alltestpred_pos_op.numpy(), alltesty_pos_op.numpy(), alldoc_len.int().numpy())\n result_avg_pos = [acc, p, r, f1]\n if f1 > max_f1_pos:\n max_acc_pos, max_p_pos, max_r_pos, max_f1_pos = acc, p, r, f1\n print('position_predict: test acc {:.4f} p {:.4f} r {:.4f} f1 {:.4f}'.format(acc, p, r, f1))\n print(\n 'max_acc {:.4f} max_p {:.4f} max_r {:.4f} max_f1 {:.4f}\\n'.format(max_acc_pos, max_p_pos, max_r_pos,\n max_f1_pos))\n\n if (result_avg_cause[-1] + result_avg_pos[-1]) / 2. > max_f1_avg:\n max_f1_avg = (result_avg_cause[-1] + result_avg_pos[-1]) / 2.\n result_avg_cause_max = result_avg_cause\n result_avg_pos_max = result_avg_pos\n\n te_pred_y_cause, te_pred_y_pos = alltestpred_cause_op, alltestpred_pos_op\n tr_pred_y_cause, tr_pred_y_pos = [], []\n for _, data in enumerate(train_staticloader):\n x, sen_len, doc_len, keep_prob1, keep_prob2, y_position, y_cause = data\n pred_pos, pred_cause, reg = model(x, sen_len, doc_len, 1, 1)\n if use_gpu:\n pred_pos = pred_pos.cpu()\n pred_cause = pred_cause.cpu()\n reg = reg.cpu()\n pred_cause = torch.argmax(pred_cause, 2)\n pred_pos = torch.argmax(pred_pos, 2)\n tr_pred_y_cause.extend(pred_cause.numpy())\n tr_pred_y_pos.extend(pred_pos.numpy())\n print('Average max cause: max_acc {:.4f} max_p {:.4f} max_r {:.4f} max_f1 {:.4f}'.format(\n result_avg_cause_max[0], result_avg_cause_max[1], result_avg_cause_max[2], result_avg_cause_max[3]))\n print('Average max pos: max_acc {:.4f} max_p {:.4f} max_r {:.4f} max_f1 {:.4f}\\n'.format(\n result_avg_pos_max[0], result_avg_pos_max[1], result_avg_pos_max[2], result_avg_pos_max[3]))\n\n def get_pair_data(file_name, doc_id, doc_len, y_pairs, pred_y_cause, pred_y_pos, x, sen_len, word_idx_rev):\n g = open(file_name, 'w')\n for i in range(len(doc_id)):\n g.write(doc_id[i] + ' ' + str(doc_len[i]) + '\\n')\n g.write(str(y_pairs[i]) + '\\n')\n for j in range(doc_len[i]):\n clause = ''\n for k in range(sen_len[i][j]):\n clause = clause + word_idx_rev[x[i][j][k]] + ' '\n g.write(str(j + 1) + ', ' + str(pred_y_pos[i][j]) + ', ' + str(\n pred_y_cause[i][j]) + ', ' + clause + '\\n')\n print('write {} done'.format(file_name))\n\n get_pair_data(save_dir + test_file_name, NLP_Dataset['test'].doc_id, NLP_Dataset['test'].doc_len,\n NLP_Dataset['test'].y_pairs, te_pred_y_cause.numpy(),\n te_pred_y_pos.numpy(), NLP_Dataset['test'].x, NLP_Dataset['test'].sen_len, word_idx_rev)\n get_pair_data(save_dir + train_file_name, train_staticDataset.doc_id, train_staticDataset.doc_len,\n train_staticDataset.y_pairs, tr_pred_y_cause,\n tr_pred_y_pos, train_staticDataset.x, train_staticDataset.sen_len, word_idx_rev)\n\n print('Optimization Finished!\\n')\n print('############# fold {} end ###############'.format(fold))\n # fold += 1\n acc_cause_list.append(result_avg_cause_max[0])\n p_cause_list.append(result_avg_cause_max[1])\n r_cause_list.append(result_avg_cause_max[2])\n f1_cause_list.append(result_avg_cause_max[3])\n acc_pos_list.append(result_avg_pos_max[0])\n p_pos_list.append(result_avg_pos_max[1])\n r_pos_list.append(result_avg_pos_max[2])\n f1_pos_list.append(result_avg_pos_max[3])\n\n print_training_info()\n all_results = [acc_cause_list, p_cause_list, r_cause_list, f1_cause_list, acc_pos_list, p_pos_list,\n r_pos_list, f1_pos_list]\n acc_cause, p_cause, r_cause, f1_cause, acc_pos, p_pos, r_pos, f1_pos = map(lambda x: np.array(x).mean(),\n all_results)\n print('\\ncause_predict: test f1 in 10 fold: {}'.format(np.array(f1_cause_list).reshape(-1, 1)))\n print('average : acc {:.4f} p {:.4f} r {:.4f} f1 {:.4f}\\n'.format(acc_cause, p_cause, r_cause, f1_cause))\n print('position_predict: test f1 in 10 fold: {}'.format(np.array(f1_pos_list).reshape(-1, 1)))\n print('average : acc {:.4f} p {:.4f} r {:.4f} f1 {:.4f}\\n'.format(acc_pos, p_pos, r_pos, f1_pos))\n print_time()\n\n\nif __name__ == '__main__':\n opt.scope = 'Ind_BiLSTM_1'\n\n run()\n","sub_path":"baseline-nonlinear.py","file_name":"baseline-nonlinear.py","file_ext":"py","file_size_in_byte":22730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"223737573","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport os\nimport pickle\nfrom conf import setting\nfrom core import modle\n\ndef is_exist(type,name):\n #判断关联的学校,班级,课程,老师是否存在,不存在返回真\n if type == 'school'and not os.path.exists(os.path.join(setting.SCHOOL_DIR, name)):\n print('输入的学校不存在')\n return True\n if type == 'classes'and not os.path.exists(os.path.join(setting.CLASSES_DIR, name)):\n print('输入的班级不存在')\n return True\n if type == 'course'and not os.path.exists(os.path.join(setting.COURSE_DIR, name)):\n print('输入的课程不存在')\n return True\n if type == 'teacher'and not os.path.exists(os.path.join(setting.TEACHER_DIR, name)):\n print('输入的老师不存在')\n return True\n\n\ndef show_action(list):\n n = 1\n for data in list:\n print('--------number:%s--------' % n)\n for key, value in data.__dict__.items():\n print('%s: %s' % (key, value))\n n += 1\n\n\ndef show_teacher():\n list = modle.Teacher.get_list()\n show_action(list)\n\n\ndef show_classes():\n list = modle.Classes.get_list()\n show_action(list)\n\n\ndef show_course():\n list = modle.Course.get_list()\n show_action(list)\n\n\ndef create_teacher():\n name = input('请输入姓名').strip()\n password = input('请输入密码').strip()\n sex = input('请输入性别').strip()\n age = input('请输入年龄').strip()\n school = input('请输入学校').strip()\n if not (name and password and sex and age and school):\n print('输入不能为空')\n return\n if is_exist('school',school):\n return\n file_name = os.path.join(setting.TEACHER_DIR, name)\n n=''\n count = 0\n while os.path.exists(file_name+n):\n count += 1\n n = str(count)\n name += n\n if n:print('由于输入的用户名已存在,系统自动将用户名更改为%s'%name)\n modle.Teacher(name,password,sex,age,school).save()\n print('创建成功')\n\n\ndef create_classes():\n name = input('请输入班级名').strip()\n course = input('请输入课程').strip()\n teacher = input('请输入老师').strip()\n school = input('请输入学校').strip()\n if not (name and course and teacher):\n print('输入不能为空')\n return\n file_name = os.path.join(setting.CLASSES_DIR, name)\n if os.path.exists(file_name):\n print('班级名已存在,请重新输入')\n return\n if is_exist('course',course) or is_exist('teacher',teacher) or is_exist('school',school):\n return\n modle.Classes(name,course,teacher,school).save()\n teacher_get = modle.Teacher.get_file(teacher)\n teacher_get.classes.append(name)\n teacher_get.save()\n print('创建成功')\n\ndef create_course():\n name = input('请输入课程名').strip()\n period = input('请输入周期').strip()\n price = input('请输入价格').strip()\n school = input('请输入学校').strip()\n if not (name and period and price and school):\n print('输入不能为空')\n return\n file_name = os.path.join(setting.COURSE_DIR, name)\n if os.path.exists(file_name):\n print('课程名已存在,请重新输入')\n return\n if is_exist('school',school):\n return\n modle.Course(name,price,price,school).save()\n\n\ndef main():\n #输入想要执行的操作\n choice = '''\n 1:查看讲师\n 2:查看班级\n 3:查看课程\n 4:创建讲师\n 5:创建班级\n 6:创建课程\n b:返回\n '''\n\n choice_dict = {'1': show_teacher,\n '2': show_classes,\n '3': show_course,\n '4':create_teacher,\n '5':create_classes,\n '6':create_course\n }\n\n while True:\n print(choice)\n choice_input = input('输入操作:')\n if choice_input == 'b': break\n if not choice_input in choice_dict:\n continue\n choice_dict[choice_input]()\n\ndef login():\n #用户登录\n name = input('输入用户名').strip()\n file_name = os.path.join(setting.ADMIN_DIR,name)\n if not name:return\n if not os.path.exists(file_name):\n print('用户名或密码错误')\n return\n password = input('输入密码').strip()\n with open(file_name, 'rb') as file:\n if not password == pickle.load(file).password:\n print('用户名或密码错误')\n return\n main()\n","sub_path":"core/role_admin.py","file_name":"role_admin.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"237189955","text":"import sys\n\n\nif __name__ == '__main__':\n candidates = set()\n facts = sys.argv[1]\n \n pre_lines = [line.rstrip('\\n') for line in open(facts)]\n for i,val in enumerate(pre_lines):\n candidates.add(val.replace(\" \",\"\"))\n\n f = open((\"Oracle.facts\"),'w')\n for i, val in enumerate(candidates):\n data = val + '\\n'\n f.write(data)\n f.close\n\n\n\n\n\n","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"204774907","text":"from bottle import post, run, response, request, route, hook\nfrom bs4 import BeautifulSoup\nimport urllib\nfrom datetime import timedelta, date\nimport time\nimport json\nimport collections\nimport urllib.request\n\n\ndef daterange(start_date, end_date):\n for n in range(int ((end_date - start_date).days)+1):\n yield start_date + timedelta(n)\n\n# yy/mm/dd\nfecha_inicial = date(int(time.strftime(\"%Y\")),int(time.strftime(\"%m\")), int(time.strftime(\"%d\")))\nfecha_final = date(int(time.strftime(\"%Y\")),int(time.strftime(\"%m\")), int(time.strftime(\"%d\")))\nurl_original = 'http://elcomercio.pe/archivo/todas/'\n\n\n\ntitulares_total = []\n\nfor fecha in daterange(fecha_inicial,fecha_final):\n fecha_string = fecha.strftime('%Y-%m-%d')\n \n url_fecha = url_original + fecha_string\n print(url_fecha)\n r = urllib.request.urlopen(url_fecha).read()\n\n soup = BeautifulSoup(r,\"lxml\")\n #print(soup)\n #main = soup.find_all(role=\"main\")\n letters = soup.find_all(\"a\", class_=\"story-item__title\")\n titulares = [None]*len(letters)\n i = 0\n for element in letters:\n titulares[i] = element.get_text()\n i=i+1\n\n for i in range(len(titulares)):\n titulares[i] = titulares[i].replace('\\n','')\n titulares[i] = titulares[i].strip(' ')\n \n for i in range(len(titulares)):\n #fuente = collections.OrderedDict()\n #fuente['id'] = \"El Comercio\"\n #fuente['name'] = \"El Comercio\"\n\n articulo = collections.OrderedDict()\n #articulo['source'] = fuente\n articulo['title'] = titulares[i]\n #print(json.dumps(articulo,ensure_ascii=False))\n #print(titulares[i])\n titulares_total.append(articulo)\n\nnoticias = collections.OrderedDict()\n#print(titulares_total)\nnoticias['articles'] = titulares_total\n\nprint(json.dumps(noticias,ensure_ascii=False))\n\n \n@route('/')\ndef infoComercio():\n dato_json = json.dumps(titulares_total,ensure_ascii=False)\n return dato_json\n\n\n@hook('after_request')\ndef enable_cors():\n response.headers['Access-Control-Allow-Origin'] = '*'\n response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'\n response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'\n\n@post('/cors')\ndef lvambience():\n response.headers['Content-Type'] = 'application/json'\n return \"[1]\"\n\nrun(host='localhost', port=3030, debug=True)","sub_path":"noticias.py","file_name":"noticias.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"256991841","text":"n=20\ndef factoriallity(n):\n fact = 1\n for num in range(2, n + 1):\n fact *= num\n return fact\nprint(factoriallity(n))\n\nfrom math import factorial\nprint(factorial(n))\n\ndef facto(n, total=1):\n while True:\n if n == 1:\n return total\n n, total = n - 1, total * n\nprint(facto(n))\n\ndef factori(n):\n if n < 2:\n return 1\n return n * factori(n - 1)\nprint(factori(n))","sub_path":"typed/b1.py","file_name":"b1.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"461124730","text":"# SPDX-License-Identifier: Apache-2.0\n\n\n\"\"\"\ntf2onnx.rewriter.conv_dilations_rewriter - Rewrites the patten used to represent dilations\npat = SpaceToBatchND->DepthwiseConv2dNative->BatchToSpaceND\n\"\"\"\n\nfrom tf2onnx.graph_matcher import OpTypePattern, GraphMatcher\n\n# pylint: disable=invalid-name,unused-argument,missing-docstring, unused-variable\n\n\ndef rewrite_conv_dilations(g, ops):\n pattern1 = \\\n OpTypePattern(\"BatchToSpaceND\", name=\"batch_to_space\", inputs=[\n OpTypePattern(\"DepthwiseConv2dNative|Conv2D|Conv3D\", name=\"conv\", inputs=[\n OpTypePattern(\"SpaceToBatchND\", name=\"space_to_batch\", inputs=[\n OpTypePattern(\"*\"),\n OpTypePattern(\"Const|ConstV2\"),\n OpTypePattern(\"Const|ConstV2\"),\n ]),\n OpTypePattern(\"*\"),\n ]),\n OpTypePattern(\"Const|ConstV2\"),\n OpTypePattern(\"Const|ConstV2\"),\n ])\n pattern2 = \\\n OpTypePattern(\"BatchToSpaceND\", name=\"batch_to_space\", inputs=[\n OpTypePattern(\"Squeeze\", name=\"squeeze\", inputs=[\n OpTypePattern(\"DepthwiseConv2dNative|Conv2D|Conv3D\", name=\"conv\", inputs=[\n OpTypePattern(\"ExpandDims\", name=\"expand\", inputs=[\n OpTypePattern(\"SpaceToBatchND\", name=\"space_to_batch\", inputs=[\n OpTypePattern(\"*\"),\n OpTypePattern(\"Const|ConstV2\"),\n OpTypePattern(\"Const|ConstV2\"),\n ]),\n OpTypePattern(\"Const|ConstV2\"),\n ]),\n OpTypePattern(\"*\"),\n ]),\n ]),\n OpTypePattern(\"Const|ConstV2\"),\n OpTypePattern(\"Const|ConstV2\"),\n ])\n\n for pattern in [pattern1, pattern2]:\n matcher = GraphMatcher(pattern, allow_reorder=False)\n match_results = list(matcher.match_ops(ops))\n for match_result in match_results:\n is_conv_1d = pattern is pattern2\n space_to_batch = match_result.get_op(\"space_to_batch\")\n conv = match_result.get_op(\"conv\")\n batch_to_space = match_result.get_op(\"batch_to_space\")\n if is_conv_1d:\n expand = match_result.get_op(\"expand\")\n expand_axis = expand.inputs[1].get_tensor_value(as_list=True)\n squeeze = match_result.get_op(\"squeeze\")\n squeeze_axes = squeeze.get_attr_value(\"squeeze_dims\")\n if expand_axis not in [1, -3] or squeeze_axes not in [[1], [-3]]:\n continue\n\n block_shape1 = space_to_batch.inputs[1].get_tensor_value(as_list=True)\n paddings = space_to_batch.inputs[2].get_tensor_value(as_list=True)\n block_shape2 = batch_to_space.inputs[1].get_tensor_value(as_list=True)\n crops = batch_to_space.inputs[2].get_tensor_value(as_list=True)\n\n if block_shape1 != block_shape2:\n continue\n ndims = 2 if is_conv_1d else len(block_shape1)\n data_format = b\"NHWC\" if ndims == 2 else b\"NDHWC\"\n ones = [1] * (ndims + 2)\n if conv.get_attr_value(\"dilations\", ones) != ones:\n continue\n if conv.get_attr_value(\"strides\", ones) != ones:\n continue\n if conv.get_attr_value(\"data_format\", data_format) != data_format:\n continue\n if conv.get_attr_value(\"padding\") != b\"VALID\":\n continue\n\n\n base_start_pad = [p[0] for p in paddings]\n if any(c[0] != 0 for c in crops):\n continue\n base_end_pad = [p[1] - c[1] for p, c in zip(paddings, crops)]\n if not all(0 <= p[1] - bp < bs for p, bp, bs in zip(paddings, base_end_pad, block_shape1)):\n continue\n\n if is_conv_1d:\n inp = space_to_batch.input[0]\n g.replace_inputs(expand, [inp, expand.input[1]])\n g.copy_shape(batch_to_space.output[0], squeeze.output[0])\n g.replace_all_inputs(batch_to_space.output[0], squeeze.output[0])\n squeeze_out_shape = g.get_shape(squeeze.output[0])\n g.set_shape(squeeze.input[0], squeeze_out_shape[:1] + [1] + squeeze_out_shape[1:])\n expand_inp_shape = g.get_shape(expand.input[0])\n g.set_shape(expand.output[0], expand_inp_shape[:1] + [1] + expand_inp_shape[1:])\n\n base_start_pad = [0] + base_start_pad\n base_end_pad = [0] + base_end_pad\n block_shape1 = [1] + block_shape1\n else:\n inp = space_to_batch.input[0]\n kernel = conv.input[1]\n g.replace_inputs(conv, [inp, kernel])\n g.copy_shape(batch_to_space.output[0], conv.output[0])\n g.replace_all_inputs(batch_to_space.output[0], conv.output[0])\n\n base_pad_flat = [0, 0] + [x for s, e in zip(base_start_pad, base_end_pad) for x in [s, e]] + [0, 0]\n conv.set_attr(\"dilations\", [1] + block_shape1 + [1])\n conv.set_attr(\"explicit_paddings\", base_pad_flat)\n conv.set_attr(\"padding\", \"EXPLICIT\")\n\n return g.get_nodes()\n","sub_path":"tf2onnx/rewriter/conv_dilations_rewriter.py","file_name":"conv_dilations_rewriter.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"373791470","text":"# -*- conding:utf-8 -*-\n# 导入模块 import tkinter\nfrom tkinter import * #此处有坑,tkinter必须小写\nimport tkinter.messagebox as messagebox\nimport weatherAPI\nimport time\n \nclass Application(Frame):\n \"\"\"生成图形架构\"\"\"\n def __init__(self,master = None):\n Frame.__init__(self,master)\n self.historyList = []\n self.grid()\n self.createWidgets()\n #Pack.config(self)\n\n\n def createWidgets(self):\n '''创建主窗体''' \n self.flavor = StringVar()\n self.flavor.set(\"c\")\n\n self.txtDisplay = Text(self,font='Monaco')\n self.txtDisplay.grid(row=0,column=0,columnspan = 4) #使用grid()可以按照网格排版,\n\n # self.Label = Label(self,text = '如不输入定时时长,可立即查询天气.',fg=\"red\")\n # self.Label.grid(row=1,column=0,columnspan = 2) #,sticky='nsew'\n\n\n \n # self.flavor = StringVar()\n # self.flavor.set(\"chocolate\")\n \n # self.radioframe = Frame(self)\n # self.radioframe.pack()\n self.radioframechoc = Radiobutton(self, text=\"°C 摄氏度\",variable=self.flavor, value=\"c\",anchor=W)\n self.radioframechoc.grid(row=1,column=0)\n\n self.radioframestraw = Radiobutton(self, text=\"°F 华氏度\",variable=self.flavor, value=\"f\",anchor=W)\n self.radioframestraw.grid(row=1,column=1)\n\n self.quitButton = Button(self, text=\"退 出\", font='Monaco',fg=\"red\", command=self.quit)\n self.quitButton.grid(row=1,column=3,sticky='nsew')\n\n\n self.timeLabel = Label(self,text = '城市名称中文或拼音')\n self.timeLabel.grid(row=2,column=0) #,sticky='nsew'\n\n self.nameInput = Entry(self,font='Monaco')\n self.nameInput.grid(row=2,column=1,sticky='nsew')\n\n self.massageButton = Button(self,text=\"查 询\",font='Monaco', fg=\"blue\", command=self.messageInfo)\n self.massageButton.grid(row=2,column=2,sticky='nsew')\n \n self.HisButton = Button(self, text=\"历史查询\", font='Monaco',fg=\"blue\", command=self.historyButt)\n self.HisButton.grid(row=2,column=3,sticky='nsew')\n\n self.timeLabel = Label(self,text = '定时时长(秒)')\n self.timeLabel.grid(row=3,column=0) #,sticky='nsew'\n\n self.timeInput = Entry(self,font='Monaco')\n self.timeInput.grid(row=3,column=1,sticky='nsew')\n\n self.massageButton = Button(self,text=\"定时查询\",font='Monaco', fg=\"blue\", command=self.timeMessageInfo)\n self.massageButton.grid(row=3,column=2,sticky='nsew')\n\n\n self.helpButton = Button(self, text=\"帮 助\",font='Monaco', fg=\"blue\", command=self.help)\n self.helpButton.grid(row=3,column=3,sticky='nsew')\n\n def messageInfo(self):\n '''创建元件,如何插入中文'''\n name = self.nameInput.get() # \n nowAPI = \"https://api.thinkpage.cn/v3/weather/now.json?key=\" \n key = \"cp3kmxnoxvklla8q\"\n COrF = self.flavor.get()\n result = weatherAPI.getAPI(nowAPI,key,COrF,name).APIInfo()\n self.historyList.append(result) \n #messagebox.showinfo('Message','{0}的天气情况:{1}'.format(name,result)) # Message弹出显示\n self.txtDisplay.insert('end',result) #文本打印显示\n\n def timeMessageInfo(self):\n name = self.nameInput.get() # \n inputTime = self.timeInput.get()\n messagebox.showinfo('提示','定时开始,请点击确认关闭本窗口!') # Message弹出显示 \n time.sleep(int(inputTime))\n nowAPI = \"https://api.thinkpage.cn/v3/weather/now.json?key=\" \n key = \"cp3kmxnoxvklla8q\"\n COrF = self.flavor.get()\n result = weatherAPI.getAPI(nowAPI,key,COrF,name).APIInfo()\n self.historyList.append(result) \n self.txtDisplay.insert('end',result) #文本打印显示\n\n def help(self):\n text = weatherAPI.getText('README.md')\n #messagebox.showinfo('help',text) \n self.txtDisplay.insert('end',text) \n\n def historyButt(self):\n text = ' '.join(self.historyList)\n #messagebox.showinfo('history',text)\n self.txtDisplay.insert('end',text) \n\n\n\n\nif __name__ == '__main__':\n\n \n app = Application()\n app.master.title('天气查询')\n app.mainloop() #进入窗体主循环\n","sub_path":"Chap3/project/weatherGUI.py","file_name":"weatherGUI.py","file_ext":"py","file_size_in_byte":4249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"26933511","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2016 Mag. Christian Tanzer All rights reserved\n# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at\n# #*** ************************************************************#\n# This module is part of the package TFL.\n#\n# This module is licensed under the terms of the BSD 3-Clause License\n# .\n# #*** ***********************************************************#\n#\n#++\n# Name\n# TFL.G8R\n#\n# Purpose\n# Support for reverse localization, i.e., globalization\n#\n# Revision Dates\n# 10-Feb-2016 (CT) Creation\n# 15-Feb-2016 (CT) Add `localized`, `map_r`, `replacer_r`, `G8R_Multi`\n# 30-Nov-2016 (CT) Add `words`\n# 30-Nov-2016 (CT) Add `LC`\n# 30-Nov-2016 (CT) Add `keys`, `words`, `globalized` to `G8R_Multi`\n# ««revision-date»»···\n#--\n\n\"\"\"Support for reverse localization, i.e., globalization.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom _TFL import TFL\nfrom _TFL.I18N import _T\nfrom _TFL.Regexp import Regexp, Dict_Replacer, Multi_Re_Replacer, re\nfrom _TFL.pyk import pyk\n\nimport _TFL._Meta.Object\nimport _TFL._Meta.Once_Property\nimport _TFL._Meta.Property\n\nfrom itertools import chain as ichain\n\nclass G8R (TFL.Meta.Object) :\n \"\"\"Globalizer for a specific set of words.\"\"\"\n\n _lowercase = False\n _re_head = r\"\\b\"\n _re_tail = r\"\\b\"\n _skip_language = \"en\"\n\n def __init__ (self, * word_lists, ** kw) :\n self._words = ws = tuple (ichain (* word_lists))\n self._keys = set (ws)\n self._maps = {}\n self._maps_r = {}\n self._replacers = {}\n self._replacers_r = {}\n self.pop_to_self \\\n ( kw\n , \"lowercase\", \"re_head\", \"re_tail\", \"skip_language\"\n , prefix = \"_\"\n )\n # end def __init__\n\n def __call__ (self, text, count = 0) :\n \"\"\"Globalize `text`, i.e., replace localized words in `text` with their\n primary — normally english — version.\n \"\"\"\n return self._transformed (text, count, self.replacer)\n # end def __call__\n\n @TFL.Meta.Once_Property\n def LC (self) :\n \"\"\"Globalizer enforcing lower case. \"\"\"\n if self._lowercase :\n return self\n else :\n return self.__class__ \\\n ( self._words\n , lowercase = True\n , re_head = self._re_head\n , re_tail = self._re_tail\n , skip_language = self._skip_language\n )\n # end def LC\n\n @property\n def keys (self) :\n \"\"\"Set of words globalized by this globalizer.\"\"\"\n return self._keys\n # end def keys\n\n @property\n def map (self) :\n \"\"\"Map of localized words to their globalized versions.\"\"\"\n lang = TFL.I18N.Config.choice [0]\n if lang and lang != self._skip_language :\n try :\n result = self._maps [lang]\n except KeyError :\n result = self._maps [lang] = {}\n lcase = self._lowercase\n sk = lambda k : (-len (k), k)\n for k in sorted (self._keys, key = sk) :\n l = _T (k)\n if lcase :\n l = l.lower ()\n k = k.lower ()\n if l != k or l in result :\n ### Don't map identical strings unless there is a\n ### translation already, e.g., english `Mon` and `Mo`\n ### both translate to german `Mo`: in this case we want\n ### to retain the shorter translation\n result [l] = k\n return result\n # end def map\n\n @property\n def map_r (self) :\n \"\"\"Map of globalized words to their localized versions.\"\"\"\n lang = TFL.I18N.Config.choice [0]\n if lang :\n try :\n result = self._maps_r [lang]\n except KeyError :\n map = self.map\n result = self._maps_r [lang] = \\\n {v:k for k, v in pyk.iteritems (map)}\n return result\n # end def map_r\n\n @property\n def replacer (self) :\n \"\"\"A Dict_Replacer that will replace any element of `maps`.\"\"\"\n map = self.map\n if map :\n lang = TFL.I18N.Config.choice [0]\n try :\n result = self._replacers [lang]\n except KeyError :\n result = self._replacers [lang] = Dict_Replacer \\\n (map, 0, self._re_head, self._re_tail)\n return result\n # end def replacer\n\n @property\n def replacer_r (self) :\n \"\"\"A Dict_Replacer that will replace any element of `maps`.\"\"\"\n map_r = self.map_r\n if map_r :\n lang = TFL.I18N.Config.choice [0]\n try :\n result = self._replacers_r [lang]\n except KeyError :\n result = self._replacers_r [lang] = Dict_Replacer \\\n (map_r, 0, self._re_head, self._re_tail)\n return result\n # end def replacer\n\n @property\n def words (self) :\n \"\"\"Words globalized by this globalizer.\"\"\"\n return self._words\n # end def words\n\n def globalized (self, text, count = 0) :\n \"\"\"Globalize `text`, i.e., replace localized words in `text` with their\n primary — normally english — version.\n \"\"\"\n return self._transformed (text, count, self.replacer)\n # end def globalized\n\n def localized (self, text, count = 0) :\n \"\"\"Localize `text`, i.e., replace globalized words in `text` with their\n localized version.\n \"\"\"\n return self._transformed (text, count, self.replacer_r)\n # end def localized\n\n def _transformed (self, text, count, replacer) :\n result = text.lower () if self._lowercase else text\n if replacer is not None :\n result = replacer (result, count)\n return result\n # end def _transformed\n\n# end class G8R\n\nclass G8R_Multi (Multi_Re_Replacer) :\n \"\"\"Wrap multiple `G8R` instances.\"\"\"\n\n _lowercase = False\n\n @TFL.Meta.Once_Property\n def LC (self) :\n \"\"\"Globalizer enforcing lower case.\"\"\"\n if self._lowercase :\n return self\n else :\n rereps_lc = tuple (g8r.LC for g8r in self.rereps)\n result = self.__class__ (* rereps_lc)\n result._lowercase = True\n return result\n # end def LC\n\n @TFL.Meta.Once_Property\n def keys (self) :\n return set (self.words)\n # end def keys\n\n @TFL.Meta.Once_Property\n def words (self) :\n return sorted (ichain (* (g8r.words for g8r in self.rereps)))\n # end def words\n\n def globalized (self, text, count = 0) :\n \"\"\"Globalize `text`, i.e., replace localized words in `text` with their\n primary — normally english — version.\n \"\"\"\n result = text\n for g8r in self.rereps :\n result = g8r.globalized (result, count)\n return result\n # end def globalized\n\n def localized (self, text, count = 0) :\n \"\"\"Localize `text`, i.e., replace globalized words in `text` with their\n localized version.\n \"\"\"\n result = text\n for g8r in self.rereps :\n result = g8r.localized (result, count)\n return result\n # end def localized\n\n# end class G8R_Multi\n\nif __name__ != \"__main__\" :\n TFL._Export (\"*\")\n### __END__ TFL.G8R\n","sub_path":"Functions/venv/lib/python3.6/site-packages/_TFL/G8R.py","file_name":"G8R.py","file_ext":"py","file_size_in_byte":7750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"268149673","text":"import datetime\nimport time\n\nimport requests\nfrom flask import render_template\nfrom flask_user import roles_required\nfrom sqlalchemy import and_\n\nfrom database import db_session, engine\nfrom database import init_db\nfrom root import lookdet_data # připojení složky sprava_kgj\nfrom root.models.m_ph_d_lookdet_data import PhDLookDetData\nfrom root.models.m_kgj_lookdet_config import VazbaKgjKonstLDMeasConf, KgjLookDetMeasConfig, KgjLookDetChannelConfig\nfrom root.models.model_kgj_zaklad import Kgj\nfrom root.models.m_eservis import Eservis_data_last, Eservis_data\n\n# provázání na sprava_kgj\\__init__.py\nlookdet_data_page = lookdet_data.lookdet_data_page\n\n\n@lookdet_data.lookdet_data_page.route(\"/look_det_request\", methods=['GET', 'POST'])\n@roles_required(['lookdet', 'admin'])\ndef lookdet_get_data():\n lookdet_send_request()\n # lookdet_akt_data()\n # load_mth_from_eservis()\n return render_template(\"homepage.html\")\n\n\ndef lookdet_akt_data():\n elVyroba = None\n cogen_units = Kgj.query.filter().all()\n for cogen_unit in cogen_units:\n measuring_config = cogen_unit.lookdet_conf_meas_data()\n id_channel_config = cogen_unit.lookdet_channel_config()\n id_channel = id_channel_config.id_channel\n if id_channel >= 0:\n try:\n if id_channel == 0:\n data = '{\"ch\":2}'\n else:\n data = '{\"ch\":' + str(id_channel) + '2}'\n url = 'http://172.27.1.123/lookdet/post.php?data={\"idLoc\":1,\"dataVer\":1,\"heslo\":\"6512jj\",\"data\":{\"get\":[' + data + ']}}'\n result = requests.get(url=url).json()\n if (cogen_unit.por_zdroje == 1 or cogen_unit.por_zdroje == 3):\n elVyroba = input_validation(result=result, conf_pos=measuring_config.Elm1_Vyr)\n if cogen_unit.por_zdroje == 2:\n elVyroba = input_validation(result=result, conf_pos=measuring_config.Elm2_Vyr)\n except:\n pass\n zaznam = Eservis_data_last.query.filter_by(jednotka_id=cogen_unit.id).first()\n if elVyroba > 0:\n if zaznam:\n zaznam.lookdet_kwh = elVyroba\n zaznam.lookdet_datum = int(datetime.datetime.now().timestamp())\n else:\n zaznam = Eservis_data_last(cogen_unit.id, None, None, None, None, None, None, None, elVyroba,\n int(datetime.datetime.now().timestamp()))\n db_session.add(zaznam)\n db_session.commit()\n print(\"LookDet zaznamenán \" + str(datetime.datetime.now()))\n\n\ndef lookdet_send_request():\n # Creating url\n cogen_units = Kgj.query.filter().all()\n for cogen_unit in cogen_units:\n measuring_config = cogen_unit.lookdet_conf_meas_data()\n id_channel_config = cogen_unit.lookdet_channel_config()\n id_channel = id_channel_config.id_channel\n if id_channel >= 0:\n try:\n if id_channel == 0:\n data = '{\"ch\":2}'\n else:\n data = '{\"ch\":' + str(id_channel) + '2}'\n url = 'http://172.27.1.123/lookdet/post.php?data={\"idLoc\":1,\"dataVer\":1,\"heslo\":\"6512jj\",\"data\":{\"get\":[' + data + ']}}'\n result = requests.get(url=url).json()\n ld_data_encode(cogen_unit, measuring_config, result, id_channel)\n\n except:\n pass\n\n\ndef ld_data_encode(cogen_unit, measure_config, result, id_channel):\n # Datetime parsing (move to function)\n ld_date_time = result['data']['get'][0]['time']\n year = ld_date_time[:4]\n month = ld_date_time[5:7]\n day = ld_date_time[8:10]\n date_record = time.mktime(datetime.date(int(year), int(month), int(day)).timetuple())\n\n # Finding actual record in DB\n actual_record = cogen_unit.lookdet_d_data(date_record=date_record)\n if actual_record is None:\n MT1_Teplo = input_validation(result=result, conf_pos=measure_config.MT1_Teplo)\n MT2_Teplo = input_validation(result=result, conf_pos=measure_config.MT2_Teplo)\n MT3_Teplo = input_validation(result=result, conf_pos=measure_config.MT3_Teplo)\n MT4_Teplo = input_validation(result=result, conf_pos=measure_config.MT4_Teplo)\n MT5_Teplo = input_validation(result=result, conf_pos=measure_config.MT5_Teplo)\n Elm1_Vyr = input_validation(result=result, conf_pos=measure_config.Elm1_Vyr)\n Elm1_Spo_Run = input_validation(result=result, conf_pos=measure_config.Elm1_Spo_Run)\n Elm1_Spo_Stop = input_validation(result=result, conf_pos=measure_config.Elm1_Spo_Stop)\n Elm2_Vyr = input_validation(result=result, conf_pos=measure_config.Elm2_Vyr)\n Elm2_Spo_Run = input_validation(result=result, conf_pos=measure_config.Elm2_Spo_Run)\n Elm2_Spo_Stop = input_validation(result=result, conf_pos=measure_config.Elm2_Spo_Stop)\n Plyn_All_VB = input_validation(result=result, conf_pos=measure_config.Plyn_All_VB)\n Plyn1_VB = input_validation(result=result, conf_pos=measure_config.Plyn1_VB)\n Plyn2_VB = input_validation(result=result, conf_pos=measure_config.Plyn2_VB)\n\n MTH_KG1 = load_mth_from_eservis(measure_config.MTH_KG1, cogen_unit.id)\n MTH_KG2 = load_mth_from_eservis(measure_config.MTH_KG2, cogen_unit.id)\n\n if (MTH_KG1 or MTH_KG2) is None:\n MTH_KG1 = input_validation(result=result, conf_pos=measure_config.MTH_KG1)\n MTH_KG2 = input_validation(result=result, conf_pos=measure_config.MTH_KG2)\n\n new_record = PhDLookDetData(date_record,\n MT1_Teplo, MT2_Teplo, MT3_Teplo, MT4_Teplo, MT5_Teplo,\n Elm1_Vyr, Elm1_Spo_Run, Elm1_Spo_Stop,\n Elm2_Vyr, Elm2_Spo_Run, Elm2_Spo_Stop,\n Plyn_All_VB, Plyn1_VB, Plyn2_VB, MTH_KG1, MTH_KG2, cogen_unit.id, 0,\n int(time.time()))\n\n db_session.add(new_record)\n db_session.commit()\n else:\n if id_channel >= 0:\n print(cogen_unit.nazev,\n load_mth_from_eservis(measure_config.MTH_KG1, cogen_unit.id),\n load_mth_from_eservis(measure_config.MTH_KG2, cogen_unit.id),\n input_validation(result=result, conf_pos=measure_config.MTH_KG1),\n input_validation(result=result, conf_pos=measure_config.MTH_KG2))\n\n\n# Function which validate record from LookDet request\ndef input_validation(result, conf_pos):\n if conf_pos == -32768:\n output = 0\n return output\n else:\n output = result['data']['get'][0]['val'][conf_pos]\n output = output[0]\n return output\n\n\ndef load_mth_from_eservis(conf_pos, kgj_id):\n if conf_pos == -32768:\n output = 0\n return output\n else:\n with engine.connect() as con:\n rs = con.execute(\"\"\"\n select ked.mth\n from energo_tools.kgj_eservis_data_last ked\n left join energo_tools.kgj_konstanty kk on ked.jednotka_id = kk.id \n where kk.id = %s\"\"\" % (kgj_id))\n mth = [row[0] for row in rs]\n return mth[0]\n","sub_path":"root/lookdet_data/ld_requests_sending.py","file_name":"ld_requests_sending.py","file_ext":"py","file_size_in_byte":7218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"391942575","text":"#################################################################################\n# Copyright (c) 2018-2021, Texas Instruments Incorporated - http://www.ti.com\n# All Rights Reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n#################################################################################\n# Some parts of the code are borrowed from: https://github.com/pytorch/vision\n# with the following license:\n#\n# BSD 3-Clause License\n#\n# Copyright (c) Soumith Chintala 2016,\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n#################################################################################\n\nimport torch\n\nfrom functools import partial\nfrom torch import nn, Tensor\nfrom torch.nn import functional as F\nfrom typing import Any, Callable, Dict, List, Optional, Sequence\n\nfrom .utils import load_state_dict_from_url\nfrom .mobilenetv2 import _make_divisible, ConvBNActivation\n\nfrom torchvision.edgeailite import xnn\n\n__all__ = [\"MobileNetV3\", \"mobilenet_v3_large\", \"mobilenet_v3_small\", \"MobileNetV3Lite\", \"mobilenet_v3_lite_large\", \"mobilenet_v3_lite_small\"]\n\n\nmodel_urls = {\n \"mobilenet_v3_large\": \"https://download.pytorch.org/models/mobilenet_v3_large-8738ca79.pth\",\n \"mobilenet_v3_small\": \"https://download.pytorch.org/models/mobilenet_v3_small-047dcff4.pth\",\n}\n\n\n###################################################\ndef get_config():\n model_config = xnn.utils.ConfigNode()\n model_config.input_channels = 3\n model_config.num_classes = 1000\n model_config.width_mult = 1.\n model_config.strides = None #(2,2,2,2,2)\n model_config.enable_fp16 = False\n return model_config\n\n\nclass SqueezeExcitation(nn.Module):\n # Implemented as described at Figure 4 of the MobileNetV3 paper\n def __init__(self, input_channels: int, squeeze_factor: int = 4):\n super().__init__()\n squeeze_channels = _make_divisible(input_channels // squeeze_factor, 8)\n self.fc1 = nn.Conv2d(input_channels, squeeze_channels, 1)\n self.relu = nn.ReLU(inplace=True)\n self.fc2 = nn.Conv2d(squeeze_channels, input_channels, 1)\n\n def _scale(self, input: Tensor, inplace: bool) -> Tensor:\n scale = F.adaptive_avg_pool2d(input, 1)\n scale = self.fc1(scale)\n scale = self.relu(scale)\n scale = self.fc2(scale)\n return F.hardsigmoid(scale, inplace=inplace)\n\n def forward(self, input: Tensor) -> Tensor:\n scale = self._scale(input, True)\n return scale * input\n\n\nclass InvertedResidualConfig:\n # Stores information listed at Tables 1 and 2 of the MobileNetV3 paper\n def __init__(self, input_channels: int, kernel: int, expanded_channels: int, out_channels: int, use_se: bool,\n activation: str, stride: int, dilation: int, width_mult: float):\n self.input_channels = self.adjust_channels(input_channels, width_mult)\n self.kernel = kernel\n self.expanded_channels = self.adjust_channels(expanded_channels, width_mult)\n self.out_channels = self.adjust_channels(out_channels, width_mult)\n self.use_se = use_se\n self.use_hs = activation == \"HS\"\n self.stride = stride\n self.dilation = dilation\n\n @staticmethod\n def adjust_channels(channels: int, width_mult: float):\n return _make_divisible(channels * width_mult, 8)\n\n\nclass InvertedResidual(nn.Module):\n # Implemented as described at section 5 of MobileNetV3 paper\n def __init__(self, cnf: InvertedResidualConfig, norm_layer: Callable[..., nn.Module],\n se_layer: Callable[..., nn.Module] = SqueezeExcitation):\n super().__init__()\n if not (1 <= cnf.stride <= 2):\n raise ValueError('illegal stride value')\n\n self.use_res_connect = cnf.stride == 1 and cnf.input_channels == cnf.out_channels\n\n layers: List[nn.Module] = []\n activation_layer = nn.Hardswish if cnf.use_hs else nn.ReLU\n\n # expand\n if cnf.expanded_channels != cnf.input_channels:\n layers.append(ConvBNActivation(cnf.input_channels, cnf.expanded_channels, kernel_size=1,\n norm_layer=norm_layer, activation_layer=activation_layer))\n\n # depthwise\n stride = 1 if cnf.dilation > 1 else cnf.stride\n layers.append(ConvBNActivation(cnf.expanded_channels, cnf.expanded_channels, kernel_size=cnf.kernel,\n stride=stride, dilation=cnf.dilation, groups=cnf.expanded_channels,\n norm_layer=norm_layer, activation_layer=activation_layer))\n if cnf.use_se:\n layers.append(se_layer(cnf.expanded_channels))\n\n # project\n layers.append(ConvBNActivation(cnf.expanded_channels, cnf.out_channels, kernel_size=1, norm_layer=norm_layer,\n activation_layer=nn.Identity))\n\n self.block = nn.Sequential(*layers)\n self.out_channels = cnf.out_channels\n self._is_cn = cnf.stride > 1\n\n def forward(self, input: Tensor) -> Tensor:\n result = self.block(input)\n if self.use_res_connect:\n result += input\n return result\n\n\nclass MobileNetV3(nn.Module):\n\n def __init__(\n self,\n inverted_residual_setting: List[InvertedResidualConfig],\n last_channel: int,\n #num_classes: int = 1000,\n block: Optional[Callable[..., nn.Module]] = None,\n norm_layer: Optional[Callable[..., nn.Module]] = None,\n activation_layer: Optional[Callable[..., nn.Module]] = nn.Hardswish,\n **kwargs: Dict\n ) -> None:\n \"\"\"\n MobileNet V3 main class\n\n Args:\n inverted_residual_setting (List[InvertedResidualConfig]): Network structure\n last_channel (int): The number of channels on the penultimate layer\n num_classes (int): Number of classes\n block (Optional[Callable[..., nn.Module]]): Module specifying inverted residual building block for mobilenet\n norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use\n \"\"\"\n model_config = get_config()\n if 'model_config' in list(kwargs.keys()):\n model_config = model_config.merge_from(kwargs['model_config'])\n #\n strides = model_config.strides if (model_config.strides is not None) else (2,2,2,2,2)\n super().__init__()\n self.num_classes = model_config.num_classes\n self.enable_fp16 = model_config.enable_fp16\n\n if not inverted_residual_setting:\n raise ValueError(\"The inverted_residual_setting should not be empty\")\n elif not (isinstance(inverted_residual_setting, Sequence) and\n all([isinstance(s, InvertedResidualConfig) for s in inverted_residual_setting])):\n raise TypeError(\"The inverted_residual_setting should be List[InvertedResidualConfig]\")\n\n if block is None:\n block = InvertedResidual\n\n if norm_layer is None:\n norm_layer = partial(nn.BatchNorm2d, eps=0.001, momentum=0.01)\n\n layers: List[nn.Module] = []\n\n # building first layer\n firstconv_output_channels = inverted_residual_setting[0].input_channels\n layers.append(ConvBNActivation(model_config.input_channels, firstconv_output_channels, kernel_size=3, stride=strides[0], norm_layer=norm_layer,\n activation_layer=activation_layer))\n\n # building inverted residual blocks\n for cnf in inverted_residual_setting:\n layers.append(block(cnf, norm_layer))\n\n # building last several layers\n lastconv_input_channels = inverted_residual_setting[-1].out_channels\n lastconv_output_channels = 6 * lastconv_input_channels\n layers.append(ConvBNActivation(lastconv_input_channels, lastconv_output_channels, kernel_size=1,\n norm_layer=norm_layer, activation_layer=activation_layer))\n\n self.features = nn.Sequential(*layers)\n self.avgpool = nn.AdaptiveAvgPool2d(1)\n self.classifier = nn.Sequential(\n nn.Linear(lastconv_output_channels, last_channel),\n activation_layer(inplace=False),\n nn.Dropout(p=0.2, inplace=True),\n nn.Linear(last_channel, model_config.num_classes),\n )\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out')\n if m.bias is not None:\n nn.init.zeros_(m.bias)\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.ones_(m.weight)\n nn.init.zeros_(m.bias)\n elif isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, 0, 0.01)\n nn.init.zeros_(m.bias)\n\n def _forward_impl(self, x: Tensor) -> Tensor:\n x = self.features(x)\n\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n\n x = self.classifier(x)\n\n return x\n\n @xnn.utils.auto_fp16\n def forward(self, x: Tensor) -> Tensor:\n return self._forward_impl(x)\n\n\ndef _mobilenet_v3_conf(arch: str, use_se: bool = True, hs_type: str='HS', **params: Dict[str, Any]):\n # non-public config parameters\n reduce_divider = 2 if params.pop('_reduced_tail', False) else 1\n dilation = 2 if params.pop('_dilated', False) else 1\n width_mult = params.pop('_width_mult', 1.0)\n\n model_config = get_config()\n if 'model_config' in list(params.keys()):\n model_config = model_config.merge_from(params['model_config'])\n width_mult = max(width_mult, model_config.width_mult)\n #\n strides = model_config.strides if (model_config.strides is not None) else (2,2,2,2,2)\n\n bneck_conf = partial(InvertedResidualConfig, width_mult=width_mult)\n adjust_channels = partial(InvertedResidualConfig.adjust_channels, width_mult=width_mult)\n\n if arch in (\"mobilenet_v3_large\", \"mobilenet_v3_lite_large\"):\n inverted_residual_setting = [\n bneck_conf(16, 3, 16, 16, False, \"RE\", 1, 1),\n bneck_conf(16, 3, 64, 24, False, \"RE\", strides[1], 1), # C1\n bneck_conf(24, 3, 72, 24, False, \"RE\", 1, 1),\n bneck_conf(24, 5, 72, 40, use_se, \"RE\", strides[2], 1), # C2\n bneck_conf(40, 5, 120, 40, use_se, \"RE\", 1, 1),\n bneck_conf(40, 5, 120, 40, use_se, \"RE\", 1, 1),\n bneck_conf(40, 3, 240, 80, False, hs_type, strides[3], 1), # C3\n bneck_conf(80, 3, 200, 80, False, hs_type, 1, 1),\n bneck_conf(80, 3, 184, 80, False, hs_type, 1, 1),\n bneck_conf(80, 3, 184, 80, False, hs_type, 1, 1),\n bneck_conf(80, 3, 480, 112, use_se, hs_type, 1, 1),\n bneck_conf(112, 3, 672, 112, use_se, hs_type, 1, 1),\n bneck_conf(112, 5, 672, 160 // reduce_divider, use_se, hs_type, strides[4], dilation), # C4\n bneck_conf(160 // reduce_divider, 5, 960 // reduce_divider, 160 // reduce_divider, use_se, hs_type, 1, dilation),\n bneck_conf(160 // reduce_divider, 5, 960 // reduce_divider, 160 // reduce_divider, use_se, hs_type, 1, dilation),\n ]\n last_channel = adjust_channels(1280 // reduce_divider) # C5\n elif arch in (\"mobilenet_v3_small\", \"mobilenet_v3_lite_small\"):\n inverted_residual_setting = [\n bneck_conf(16, 3, 16, 16, use_se, \"RE\", strides[1], 1), # C1\n bneck_conf(16, 3, 72, 24, False, \"RE\", strides[2], 1), # C2\n bneck_conf(24, 3, 88, 24, False, \"RE\", 1, 1),\n bneck_conf(24, 5, 96, 40, use_se, hs_type, strides[3], 1), # C3\n bneck_conf(40, 5, 240, 40, use_se, hs_type, 1, 1),\n bneck_conf(40, 5, 240, 40, use_se, hs_type, 1, 1),\n bneck_conf(40, 5, 120, 48, use_se, hs_type, 1, 1),\n bneck_conf(48, 5, 144, 48, use_se, hs_type, 1, 1),\n bneck_conf(48, 5, 288, 96 // reduce_divider, use_se, hs_type, strides[4], dilation), # C4\n bneck_conf(96 // reduce_divider, 5, 576 // reduce_divider, 96 // reduce_divider, use_se, hs_type, 1, dilation),\n bneck_conf(96 // reduce_divider, 5, 576 // reduce_divider, 96 // reduce_divider, use_se, hs_type, 1, dilation),\n ]\n last_channel = adjust_channels(1024 // reduce_divider) # C5\n else:\n raise ValueError(\"Unsupported model type {}\".format(arch))\n\n return inverted_residual_setting, last_channel\n\n\ndef _mobilenet_v3_model(\n arch: str,\n inverted_residual_setting: List[InvertedResidualConfig],\n last_channel: int,\n pretrained: bool,\n progress: bool,\n **kwargs: Any\n):\n model = MobileNetV3(inverted_residual_setting, last_channel, **kwargs)\n if pretrained is True:\n if model_urls.get(arch, None) is None:\n raise ValueError(\"No checkpoint is available for model type {}\".format(arch))\n state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)\n model.load_state_dict(state_dict)\n elif xnn.utils.is_url(pretrained):\n state_dict = load_state_dict_from_url(pretrained, progress=progress)\n model.load_state_dict(state_dict)\n elif isinstance(pretrained, str):\n state_dict = torch.load(pretrained)\n state_dict = state_dict['model'] if 'model' in state_dict else state_dict\n state_dict = state_dict['state_dict'] if 'state_dict' in state_dict else state_dict\n model.load_state_dict(state_dict)\n\n return model\n\n\ndef mobilenet_v3_large(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> MobileNetV3:\n \"\"\"\n Constructs a large MobileNetV3 architecture from\n `\"Searching for MobileNetV3\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n arch = \"mobilenet_v3_large\"\n inverted_residual_setting, last_channel = _mobilenet_v3_conf(arch, **kwargs)\n return _mobilenet_v3_model(arch, inverted_residual_setting, last_channel, pretrained, progress, **kwargs)\n\n\ndef mobilenet_v3_small(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> MobileNetV3:\n \"\"\"\n Constructs a small MobileNetV3 architecture from\n `\"Searching for MobileNetV3\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n arch = \"mobilenet_v3_small\"\n inverted_residual_setting, last_channel = _mobilenet_v3_conf(arch, **kwargs)\n return _mobilenet_v3_model(arch, inverted_residual_setting, last_channel, pretrained, progress, **kwargs)\n\n\n###################################################\nclass MobileNetV3Lite(MobileNetV3):\n def __init__(\n self,\n inverted_residual_setting: List[InvertedResidualConfig],\n last_channel: int,\n block: Optional[Callable[..., nn.Module]] = None,\n norm_layer: Optional[Callable[..., nn.Module]] = None,\n activation_layer: Optional[Callable[..., nn.Module]] = nn.ReLU,\n **kwargs\n ) -> None:\n kwargs['num_classes'] = kwargs.get('num_classes', 1000)\n super().__init__(inverted_residual_setting,\n last_channel=last_channel,\n block=block,\n norm_layer=norm_layer,\n activation_layer=activation_layer,\n **kwargs)\n\n\ndef _mobilenet_v3_lite_conf(arch: str, **params: Dict[str, Any]):\n return _mobilenet_v3_conf(arch, use_se=False, hs_type=\"RE\", **params)\n\n\ndef _mobilenet_v3_lite_model(\n arch: str,\n inverted_residual_setting: List[InvertedResidualConfig],\n last_channel: int,\n pretrained: bool,\n progress: bool,\n **kwargs: Any\n):\n model = MobileNetV3Lite(inverted_residual_setting, last_channel, **kwargs)\n if pretrained is True:\n if model_urls.get(arch, None) is None:\n raise ValueError(\"No checkpoint is available for model type {}\".format(arch))\n state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)\n model.load_state_dict(state_dict)\n elif xnn.utils.is_url(pretrained):\n state_dict = load_state_dict_from_url(pretrained, progress=progress)\n model.load_state_dict(state_dict)\n elif isinstance(pretrained, str):\n state_dict = torch.load(pretrained)\n state_dict = state_dict['model'] if 'model' in state_dict else state_dict\n state_dict = state_dict['state_dict'] if 'state_dict' in state_dict else state_dict\n model.load_state_dict(state_dict)\n\n return model\n\n\ndef mobilenet_v3_lite_large(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> MobileNetV3Lite:\n \"\"\"\n Constructs a large MobileNetV3 architecture from\n `\"Searching for MobileNetV3\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n arch = \"mobilenet_v3_lite_large\"\n inverted_residual_setting, last_channel = _mobilenet_v3_lite_conf(arch, **kwargs)\n return _mobilenet_v3_lite_model(arch, inverted_residual_setting, last_channel, pretrained, progress, **kwargs)\n\n\ndef mobilenet_v3_lite_small(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> MobileNetV3Lite:\n \"\"\"\n Constructs a small MobileNetV3 architecture from\n `\"Searching for MobileNetV3\" `_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n arch = \"mobilenet_v3_lite_small\"\n inverted_residual_setting, last_channel = _mobilenet_v3_lite_conf(arch, **kwargs)\n return _mobilenet_v3_lite_model(arch, inverted_residual_setting, last_channel, pretrained, progress, **kwargs)\n","sub_path":"torchvision/edgeailite/xvision/models/mobilenetv3.py","file_name":"mobilenetv3.py","file_ext":"py","file_size_in_byte":20943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"333174110","text":"import unittest\nimport os\nimport glob\nimport os.path\nimport plistlib\nimport subprocess\n\n\nclass autopkgTests(unittest.TestCase):\n autopkgPythonPath = \"/usr/local/bin/autopkg\"\n # installedModulels = (\"jcapiv1\", \"jdcapiv2\", \"boto3\")\n recipeRepo = \"https://github.com/autopkg/recipes\"\n \n def bash_command(self, cmd):\n sp = subprocess.run(['/bin/bash', '-c', cmd], stdout=subprocess.PIPE, text=True)\n return sp.stdout\n\n def testEnv(self):\n '''API Key should be set in autopkg preference file'''\n keypair = self.bash_command(\"defaults read ~/Library/Preferences/com.github.autopkg.plist JC_API\")\n repolist = self.bash_command(\"autopkg repo-list\")\n # check key pair\n self.assertIsNotNone(keypair)\n # check repo list for valid test parent repos\n self.assertTrue(self.recipeRepo in repolist)\n\n def testAutoPkgRun(self):\n '''Tests Firefox Recipe'''\n pwd = os.getcwd()\n print(\"pwd Path: \" + pwd)\n # parent = os.path.dirname(pwd)\n # print(\"parent Path: \" + parent)\n recipe = (\"{}/recipe_overrides/Firefox.jumpcloud.recipe\").format(pwd)\n print(\"Recipe Path: \" + recipe)\n # run the autopkg recipe\n self.bash_command((\"autopkg run {}\").format(recipe))\n # check for receipt\n recipeReceiptPath = '~/Library/AutoPkg/Cache/local.pkg.Firefox/receipts/*.plist'\n recipeReceiptPathExpanded = os.path.expanduser(recipeReceiptPath)\n print(recipeReceiptPathExpanded)\n recipeRecipts = glob.glob(recipeReceiptPathExpanded)\n print(recipeRecipts)\n latest_file = max(recipeRecipts, key=os.path.getctime)\n print(latest_file)\n\n with open(latest_file, 'rb') as fp:\n pl = plistlib.load(fp)\n\n for i in pl:\n if \"Processor\" in i:\n if i['Processor'] == \"JumpCloudImporter\":\n print(i['Input'])\n self.assertIsNotNone(i)\n if 'RecipeError' in i:\n print(i)\n self.assertIsNone(i)\n\n\nif __name__ == \"__main__\":\n # tests\n unittest.main()","sub_path":"tests/test_jcautopkgimporter.py","file_name":"test_jcautopkgimporter.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"381265840","text":"import os\nimport shutil\nimport tempfile\nimport subprocess\nfrom subprocess import PIPE\n\nMODE_BATCH = 0\nMODE_NON_STOP = 1\nMODE_SCROLL = 2\nMODE_ERROR_STOP = 3\nINTERACTION_MODES = ['batchmode', 'nonstopmode', 'scrollmode', 'errorstopmode']\n\nJINJA2_ENV = {'block_start_string': '\\BLOCK{',\n 'block_end_string': '}',\n 'variable_start_string': '\\VAR{',\n 'variable_end_string': '}',\n 'comment_start_string': '\\#{',\n 'comment_end_string': '}',\n 'line_statement_prefix': '%%',\n 'line_comment_prefix': '%#',\n 'trim_blocks': True,\n 'autoescape': False}\n\n\nclass PDFLaTeX:\n def __init__(self, latex_src, job_name: str):\n self.latex = latex_src\n self.job_name = job_name\n self.interaction_mode = INTERACTION_MODES[MODE_BATCH]\n self.dir = None\n self.pdf_filename = None\n self.params = dict()\n self.pdf = None\n self.log = None\n \n @classmethod\n def from_texfile(cls, filename):\n prefix = os.path.basename(filename)\n prefix = os.path.splitext(prefix)[0]\n with open(filename, 'rb') as f:\n return cls.from_binarystring(f.read(), prefix)\n\n @classmethod\n def from_binarystring(cls, binstr: str, jobname: str):\n return cls(binstr, jobname)\n\n @classmethod\n def from_jinja_template(cls, jinja2_template, jobname: str = None, **render_kwargs):\n tex_src = jinja2_template.render(**render_kwargs)\n fn = jinja2_template.filename\n \n if fn is None:\n fn = jobname\n if not fn:\n raise ValueError(\"PDFLaTeX: if jinja template does not have attribute 'filename' set, \"\n \"'jobname' must be provided\")\n return cls(tex_src, fn)\n\n def create_pdf(self, keep_pdf_file: bool = False, keep_log_file: bool = False, env: dict = None):\n if self.interaction_mode is not None:\n self.add_args({'-interaction-mode': self.interaction_mode})\n \n dir = self.params.get('-output-directory')\n filename = self.params.get('-jobname')\n \n if filename is None:\n filename = self.job_name\n if dir is None:\n dir = \"\"\n \n with tempfile.TemporaryDirectory() as td:\n self.set_output_directory(td)\n self.set_jobname('file')\n \n args = self.get_run_args()\n fp = subprocess.run(args, input=self.latex, env=env, timeout=15, stdout=PIPE, stderr=PIPE)\n with open(os.path.join(td, 'file.pdf'), 'rb') as f:\n self.pdf = f.read()\n with open(os.path.join(td, 'file.log'), 'rb') as f:\n self.log = f.read()\n if keep_log_file:\n shutil.move(os.path.join(td, 'file.log'), os.path.join(dir, filename + '.log'))\n if keep_pdf_file:\n shutil.move(os.path.join(td, 'file.pdf'), os.path.join(dir, filename + '.pdf'))\n \n return self.pdf, self.log, fp\n\n def get_run_args(self):\n a = [k+('='+v if v is not None else '') for k, v in self.params.items()]\n a.insert(0, 'pdflatex')\n return a\n \n def add_args(self, params: dict):\n for k in params:\n self.params[k] = params[k]\n \n def del_args(self, params):\n if isinstance(params, str):\n params = [params]\n\n if isinstance(params, dict) or isinstance(params, list):\n for k in params:\n if k in self.params.keys():\n del self.params[k]\n else:\n raise ValueError('PDFLaTeX: del_cmd_params: parameter must be str, dict or list.')\n \n def set_output_directory(self, dir: str = None):\n self.generic_param_set('-output-directory', dir)\n\n def set_jobname(self, jobname: str = None):\n self.generic_param_set('-jobname', jobname)\n\n def set_output_format(self, fmt: str = None):\n if fmt and fmt not in ['pdf', 'dvi']:\n raise ValueError(\"PDFLaTeX: Format must be either 'pdf' or 'dvi'.\")\n self.generic_param_set('-output-format', dir)\n \n def generic_param_set(self, param_name, value):\n if value is None:\n if param_name in self.params.keys():\n del self.params[param_name]\n else:\n self.params[param_name] = value\n \n def set_pdf_filename(self, pdf_filename: str = None):\n self.set_jobname(pdf_filename)\n \n def set_batchmode(self, on: bool = True):\n self.interaction_mode = INTERACTION_MODES[MODE_BATCH] if on else None\n\n def set_nonstopmode(self, on: bool =True):\n self.interaction_mode = INTERACTION_MODES[MODE_NON_STOP] if on else None\n\n def set_scrollmode(self, on: bool = True):\n self.interaction_mode = INTERACTION_MODES[MODE_SCROLL] if on else None\n\n def set_errorstopmode(self, on: bool = True):\n self.interaction_mode = INTERACTION_MODES[MODE_ERROR_STOP] if on else None\n\n def set_interaction_mode(self, mode: int = None):\n if mode is None:\n self.interaction_mode = None\n elif 0 <= mode <= 3:\n self.interaction_mode = INTERACTION_MODES[mode]\n else:\n raise ValueError('PDFLaTeX: Invalid interaction mode!')","sub_path":"venv/Lib/site-packages/pdflatex/pdflatex.py","file_name":"pdflatex.py","file_ext":"py","file_size_in_byte":5312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"49619035","text":"import random\nimport operator\nimport copy\nfrom prettytable import PrettyTable\n\nNUM_VOTERS = 10\n\nCANIDATE1 = \"ALEX\"\nCANIDATE2 = \"BART\"\nCANIDATE3 = \"CINDY\"\nCANIDATE4 = \"DAVID\"\nCANIDATE5 = \"ERIK\"\nCANIDATE6 = \"FRANK\"\nCANIDATE7 = \"GREG\"\n\nCANIDATES = [CANIDATE1, CANIDATE2, CANIDATE3, CANIDATE4, CANIDATE5, CANIDATE6, CANIDATE7]\n\n#Force all canidates to prefer one canidate over another\nFORCE_PREFERENCE = True\nPREFERENCE1 = CANIDATE4\nPREFERENCE2 = CANIDATE5\n\nclass Voter:\n def __init__(self, weight):\n self.weight = weight\n self.pref = list(CANIDATES)\n self.shuffle()\n if FORCE_PREFERENCE:\n i = self.pref.index(PREFERENCE1)\n j = self.pref.index(PREFERENCE2)\n if j < i:\n self.pref[i], self.pref[j] = self.pref[j], self.pref[i]\n \n\n def shuffle(self):\n random.shuffle(self.pref)\n\n def pairwise(self, canidate1, canidate2):\n for canidate in self.pref:\n if canidate == canidate1:\n return canidate1\n elif canidate == canidate2:\n return canidate2\n\nclass BallotBox:\n def __init__(self):\n self.set_canidates(CANIDATES)\n \n def set_canidates(self, canidates):\n self.counter = {}\n for canidate in canidates:\n self.counter[canidate] = 0\n \n def vote(self, canidate, votes):\n self.counter[canidate] += votes\n\n def results(self):\n #This sort returns a list sorted first by vote count. In case of ties it orders the canidate by name.\n return map(lambda x:x[0], sorted(sorted(self.counter.items(), key=lambda x:x[0]), key=lambda x:x[1], reverse=True))\n \n def clear(self):\n self.counter = {}\n\n#The following are functions for the varios voting methods\n\ndef plurality(voters):\n box = BallotBox()\n box.set_canidates(voters[0].pref)\n for voter in voters:\n box.vote(voter.pref[0], voter.weight)\n return box.results()\n\ndef borda(voters):\n box = BallotBox()\n for voter in voters:\n for i in range(len(CANIDATES)):\n box.vote(voter.pref[i], (len(CANIDATES) - i) * voter.weight)\n return box.results()\n\ndef bucklin(voters):\n box = BallotBox()\n \n #Calculate Majority Votes Required\n votes_needed = 0\n for voter in voters:\n votes_needed += voter.weight\n votes_needed /= 2\n votes_needed += 1\n\n #Increase k until majority is found.\n i = 0\n while box.counter[box.results()[0]] < votes_needed:\n for voter in voters:\n box.vote(voter.pref[i], voter.weight)\n i += 1\n\n return box.results()\n\ndef stv(voters):\n #Single Tranferable Vote\n voters = copy.deepcopy(voters)\n results = []\n while len(results) < len(CANIDATES):\n worst_canidate = plurality(voters)[-1]\n results.insert(0,worst_canidate)\n for voter in voters:\n voter.pref.remove(worst_canidate)\n return results\n \ndef copeland(voters):\n first_order_box = BallotBox()\n second_order_box = BallotBox()\n\n #Build our inital defeat graph\n defeats = {}\n for canidate in CANIDATES:\n defeats[canidate] = []\n\n #First order Copeland. Also make note of who defeats who for second order.\n for canidate1 in CANIDATES:\n for canidate2 in CANIDATES:\n if canidate1 != canidate2:\n #Do pairwise vote\n temp_box = BallotBox()\n for voter in voters:\n temp_box.vote(voter.pairwise(canidate1, canidate2), voter.weight)\n\n #Canidates tied pairwise\n if temp_box.counter[canidate1] == temp_box.counter[canidate2]:\n first_order_box.vote(canidate1, 1)\n first_order_box.vote(canidate2, 1)\n #Canidate 1 wins pairwise\n elif temp_box.counter[canidate1] > temp_box.counter[canidate2]:\n first_order_box.vote(canidate1, 2)\n defeats[canidate1].append(canidate2)\n #Canidate 2 wins pairwise\n else:\n first_order_box.vote(canidate2, 2)\n defeats[canidate2].append(canidate1)\n\n #Second order Copeland calculation\n for canidate in CANIDATES:\n copeland_sum = 0\n for defeated_canidate in defeats[canidate]:\n copeland_sum += first_order_box.counter[defeated_canidate]\n \n second_order_box.vote(canidate, copeland_sum)\n\n return second_order_box.results()\n\ndef main():\n #random.seed(665273) #Seeded with my a number\n voters = []\n\n #Randomly generate some voters\n for i in range(NUM_VOTERS):\n voters.append(Voter(random.randint(1, NUM_VOTERS)))\n\n \n #Print the Majority Graph \n vs = PrettyTable()\n for i in range(NUM_VOTERS):\n voter = voters[i]\n vs.add_column('Weight:' + str(voter.weight), voter.pref) \n print(\"Majority Graph:\")\n print(vs)\n\n #Vote!\n stv_results = stv(voters)\n borda_results = borda(voters)\n copeland_results = copeland(voters)\n bucklin_results = bucklin(voters)\n plurality_results = plurality(voters)\n\n #Display Results \n ts = PrettyTable()\n ts.add_column('Borda', borda_results)\n ts.add_column('Single Transferable Vote', stv_results)\n ts.add_column('Second Order Copeland', copeland_results)\n ts.add_column('Bucklin', bucklin_results)\n ts.add_column('Plurality', plurality_results)\n print(\"\\nResults\")\n print(ts) \n \n \nif __name__ == \"__main__\":\n main()\n","sub_path":"2015 Fall/CS6100 - Agents/Homework3/voting.py","file_name":"voting.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"37138166","text":"#!/usr/bin/env python\n\"\"\"\nMap plot\n\"\"\"\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pyproj\nfrom obspy.imaging import beachball\nimport cst\n\npath = os.path.join( 'run', 'mesh', '1000' )\nmeta = os.path.join( path, 'meta.py' )\nmeta = cst.util.load( meta )\nproj = pyproj.Proj( **meta.projection )\nextent = meta.extent\nbounds = meta.bounds\n\n#extent = (-118.75, -117.25), (33.5, 34.4)\n\n# setup plot\ninches = 6.4, 3.7\nlat = np.mean( extent[1] )\naspect = 1.0 / np.cos( lat / 180.0 * np.pi )\nplt.rc( 'font', size=8 )\nplt.rc( 'axes', linewidth=0.5 )\nplt.rc( 'lines', lw=1.5, solid_joinstyle='round', solid_capstyle='round' )\nfig = plt.figure( None, inches, 100, None )\nfig.clf()\nax = fig.add_axes( [0.01, 0.02, 0.98, 0.96] )\n\n# topography\nddeg = 0.5 / 60.0\nz, extent = cst.data.topo( extent )\nx, y = extent\nn = z.shape\nx = x[0] + ddeg * np.arange( n[0] )\ny = y[0] + ddeg * np.arange( n[1] )\ny, x = np.meshgrid( y, x )\nx, y = proj( x, y )\nv = 250, 1000\nv = 1000,\nax.contour( x, y, z, v, colors='k', linewidths=0.25 )\n\n# coastlines and boarders\nx, y = cst.data.mapdata( 'coastlines', 'high', extent, 10.0 )\nx, y = proj( x, y )\nax.plot( x-360.0, y, 'k-', lw=0.5 )\n\n# source\nmts = 'scsn-mts-14383980.py'\nmts = cst.util.load( mts )\nx = mts.longitude\ny = mts.latitude\nx, y = proj( x, y )\nif 0:\n ax.plot( x, y, 'k*', ms=12, mew=1.0, mec='k', mfc='none' )\nelse:\n m = mts.double_couple_clvd\n m = m['mzz'], m['mxx'], m['myy'], m['mxz'], -m['myz'], -m['mxy']\n b = beachball.Beach( m, xy=(x,y), width=8000, linewidth=0.5, facecolor='k' )\n ax.add_collection( b )\n\n# stations\nsta = np.loadtxt( 'station-list.txt', 'S8, f, f, f' )\nx, y = proj( sta['f2'], sta['f1'] )\nax.plot( x, y, 'k^', markersize=5 )\nfor s, y, x, z in sta:\n x, y = proj( x, y )\n ax.text( x, y-1800, s.split('.')[-1], ha='center', va='top' )\n\n# finish up\naxis = bounds[0] + bounds[1]\n#ax.set_aspect( aspect )\nax.set_xticks( [] )\nax.set_yticks( [] )\nax.axis( 'image' )\nax.axis( axis )\nfig.canvas.draw()\nfig.savefig( 'map.pdf' )\nfig.show()\n\n","sub_path":"scripts/chino/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"595386173","text":"import unittest\n\nfrom common import get_context\nimport moderngl\n\n\nclass TestCase(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.ctx = get_context()\n\n def test_program(self):\n program = self.ctx.program(\n vertex_shader='''\n #version 330\n\n uniform vec2 pos;\n uniform float scale;\n\n in vec2 vert;\n out vec2 v_vert;\n\n void main() {\n gl_Position = vec4(pos + vert * scale, 0.0, 1.0);\n v_vert = vert;\n }\n ''',\n fragment_shader='''\n #version 330\n\n in vec2 v_vert;\n out vec4 color;\n\n void main() {\n color = vec4(v_vert, 0.0, 1.0);\n }\n ''',\n )\n\n self.assertIn('vert', program)\n self.assertIn('pos', program)\n self.assertIn('scale', program)\n\n self.assertIsInstance(program['vert'], moderngl.Attribute)\n self.assertIsInstance(program['pos'], moderngl.Uniform)\n self.assertIsInstance(program['scale'], moderngl.Uniform)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_program.py","file_name":"test_program.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"120926895","text":"from .baseclasses import Node, Container, Iterator\n\n\nclass LinkedList(Container):\n def __init__(self):\n super().__init__()\n self.root = None\n\n def __iter__(self):\n return Iterator(self.root)\n\n def append(self, data):\n node = Node(data)\n node.next = self.root\n self.root = node\n self.increment()\n\n def append_to_tail(self, data):\n new_node = Node(data=data)\n if self.is_empty():\n self.root = new_node\n else:\n node = self.root\n while node.next is not None:\n node = node.next\n node.next = new_node\n self.increment()\n\n def remove(self, data):\n if self.is_empty():\n return False\n elif self.root.data == data:\n self.root = self.root.next\n self.decrement()\n return True\n else:\n node = self.root\n while 1:\n if node.next.data == data:\n break\n if node.next is None:\n return False\n node = node.next\n node.next = node.next.next\n return True\n\n def dump_as_list(self):\n node_list = []\n node = self.root\n while node is not None:\n node_list.append(node.data)\n node = node.next\n return node_list\n","sub_path":"python/src/main/datastructures/linkedlist.py","file_name":"linkedlist.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"422661629","text":"import docker\nimport logging\nfrom client import Client\nfrom time import sleep\n\nclass Services(Client):\n def __init__(self, client):\n self.client = client\n\n def get(self, filters=None):\n \"\"\"\n Get Docker services based on the filter provided, if no filter is passed then all the running services are returned\n \"\"\"\n if self.is_docker_running():\n logging.info(self.client.services.list(filters=filters))\n return self.client.services.list(filters=filters)\n return []\n\n def update(self, **kwargs):\n \"\"\"\n Update docker services \n\n Arguments:\n \n \"filters\": Filter services based on id, name, mode or label. Passed as dictionary.\n\n \"update_config\": Dictionary of service options updates\n \"\"\"\n service_list = []\n response = {}\n\n if 'filters' in kwargs:\n service_list = self.get(filters=kwargs['filters'])\n else:\n # Get all the services\n service_list = self.get()\n\n if len(service_list):\n logging.info('Updating services...')\n else:\n logging.info('No services to update')\n response['Error'] = 'No services to update'\n\n for service in service_list:\n response[service.name] = {}\n try:\n service.update(**kwargs['update_config'])\n response[service.name]['Status'] = \"updating\"\n response[service.name]['Message'] = \"Update has been initaited\"\n\n except docker.errors.APIError as e:\n logging.warn('Update failed for service %s : %s' %(service.name, e))\n response[service.name]['Message'] = 'Update failed with error \"%s\"' %(e)\n response[service.name]['Status'] = 'failed'\n\n return response\n\n def get_status(self, filters=None):\n \"\"\"\n Get last status of service updates\n \"\"\"\n service_list = self.get(filters=filters)\n response = {}\n for service in service_list:\n response[service.name] = {}\n updateStatus = service.attrs.get('UpdateStatus')\n if updateStatus:\n response[service.name]['Image'] = service.attrs.get('Spec')['TaskTemplate']['ContainerSpec']['Image']\n if 'Message' in updateStatus: response[service.name]['Message'] = updateStatus['Message']\n if 'State' in updateStatus: response[service.name]['Status'] = updateStatus['State']\n if 'StartedAt' in updateStatus:response[service.name]['StartedAt'] = updateStatus['StartedAt']\n\n return response\n\n","sub_path":"deku/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"357979733","text":"from rest_framework import serializers\n\nfrom post.models import (Post, Tag, Categoria, PostCategoria, PostTag)\n\n\nclass CategoriaSerializer(serializers.ModelSerializer):\n class Meta:\n model = Categoria\n fields = [\n 'nome', 'descricao',\n ]\n\n def create(self, validated_data):\n return Post.objects.create(**validated_data)\n\n\nclass TagSerializer(serializers.ModelSerializer):\n class Meta:\n model = Tag\n fields = [\n 'nome'\n ]\n\n def create(self, validated_data):\n return Post.objects.create(**validated_data)\n\n\nclass PostSerializer(serializers.ModelSerializer):\n categorias = CategoriaSerializer(\n required=False,\n many=True\n )\n tags = TagSerializer(\n required=False,\n many=True\n )\n\n class Meta:\n model = Post\n fields = [\n 'titulo', 'descricao',\n 'conteudo', 'categorias', 'tags'\n ]\n\n def create(self, validated_data):\n possui_tag = validated_data.pop('tags', None)\n possui_categoria = validated_data.pop('categorias', None)\n\n post = Post.objects.create(**validated_data)\n\n tags_objects = []\n tag_post = []\n if possui_tag:\n tags = Tag.objects.all()\n tags_nomes = tags.values_list('nome', flat=True)\n for tag in possui_tag:\n if tag['nome'] not in tags_nomes:\n tag_instance = Tag(\n nome=tag['nome']\n )\n tags_objects.append(tag_instance)\n else:\n tag_instance = tags.filter(\n nome=tag['nome']\n ).first()\n\n tag_post.append(\n PostTag(\n tag=tag_instance,\n post=post\n )\n )\n if tags_objects:\n Tag.objects.bulk_create(tags_objects)\n\n PostTag.objects.bulk_create(tag_post)\n\n return post\n","sub_path":"post/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"598060441","text":"import json\nfrom member import MemberNode\n\n\ndef get_pre_part():\n pre_part = \"\"\"\n \n \n \n \n Organization Chart Plugin\n \n \n \n \n \n \n \n
\n \n \n \n \n \n \n \"\"\"\n return post_part\n\n\ndef draw_tree(member_dict, first_member_id, file_name):\n pre_part = get_pre_part()\n data_part = get_data_part(member_dict, first_member_id)\n post_part = get_post_part()\n\n html_content = pre_part + data_part + post_part\n file = open(file_name, \"w\", encoding='UTF-8')\n file.write(html_content)\n file.close()\n","sub_path":"src/family_tree_orgcharts.py","file_name":"family_tree_orgcharts.py","file_ext":"py","file_size_in_byte":4243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"311580278","text":"\"\"\"\nContains a class to help build fixtures programmatically.\n\"\"\"\n\nfrom securesystemslib import formats, signer\nfrom tuf import repository_tool, roledb\n\nimport json\nimport os\nimport shutil\nfrom dirhash import dirhash\n\n\nclass FixtureBuilder:\n\n def __init__(self, name, tuf_arguments={ 'use_snapshot_length': False }):\n self.dir = os.path.join(os.path.dirname(__file__), name)\n\n # The index of the next key pair (in the keys/ directory) to use when initializing\n # a role.\n self._key_index = 0\n # The keychain, containing all public and private keys. The dictionary\n # keys are role names, and each item is a dictionary with 'public' and\n # 'private' members, which are lists of public and private keys.\n self._keys = {}\n # The directory of server-side metadata (and targets).\n self._server_dir = os.path.join(self.dir, 'server')\n\n # If a directory of server-side metadata already exists, remove it.\n if os.path.isdir(self._server_dir):\n shutil.rmtree(self._server_dir)\n\n self.repository = repository_tool.create_new_repository(self._server_dir, name, **tuf_arguments)\n self.repository.status()\n\n # Initialize the basic TUF roles.\n self.add_key('root')\n self.add_key('targets')\n self.add_key('snapshot')\n self.add_key('timestamp')\n\n self.repository.status()\n\n def __del__(self):\n # Create a hash for the generated fixture.\n with open(self.dir + \"/hash.txt\", \"w\") as hash_file:\n hash_file.write(dirhash(self.dir, 'sha256', ignore=[\"__init__.py\", \"client_versions.ini\", \"hash.txt\"]))\n\n def _role(self, name):\n \"\"\"Loads a role object for a specific role.\"\"\"\n try:\n return getattr(self.repository, name)\n except AttributeError:\n return self.repository.targets(name)\n\n def delegate(self, role_name, paths, parent='targets', path_hash_prefixes=None, terminating=False):\n \"\"\"Creates a delegated role.\"\"\"\n self._role(parent).delegate(role_name, [], paths, path_hash_prefixes=path_hash_prefixes, terminating=terminating)\n self.add_key(role_name)\n return self\n\n def add_key(self, role_name):\n \"\"\"Loads a key pair from disk and assigns it to a given role.\"\"\"\n (public_key, private_key) = self._import_key(role_name)\n\n role = self._role(role_name)\n role.add_verification_key(public_key)\n role.load_signing_key(private_key)\n\n if role_name not in self._keys:\n self._keys[role_name] = {'public': [], 'private': []}\n\n self._keys[role_name]['public'].append(public_key)\n self._keys[role_name]['private'].append(private_key)\n\n self._mark_dirty(role_name)\n\n return self\n\n def revoke_key(self, role_name, key_index=0):\n \"\"\"Revokes a key pair from a given role.\"\"\"\n public_key = self._keys[role_name]['public'].pop(key_index)\n self._role(role_name).remove_verification_key(public_key)\n self._keys[role_name]['private'].pop(key_index)\n\n self._mark_dirty(role_name)\n\n return self\n\n def _mark_dirty(self, role_name):\n \"\"\"Marks a role as dirty, along with its parent role.\"\"\"\n self.repository.mark_dirty([role_name])\n\n if role_name in roledb.TOP_LEVEL_ROLES:\n self.repository.mark_dirty(['root'])\n else:\n self.repository.mark_dirty(['targets'])\n\n def _import_key(self, role_name):\n \"\"\"Loads a key pair from the keys/ directory.\"\"\"\n keys_dir = os.path.join(os.path.dirname(__file__), 'keys')\n private_key = os.path.join(keys_dir, str(self._key_index)) + '_key'\n public_key = '{}.pub'.format(private_key)\n\n print(\"Using key\", self._key_index, \"for\", role_name)\n self._key_index = self._key_index + 1\n\n return (\n repository_tool.import_ed25519_publickey_from_file(public_key),\n repository_tool.import_ed25519_privatekey_from_file(private_key, password='pw')\n )\n\n def invalidate(self):\n \"\"\"Marks the four top-level TUF roles as dirty.\"\"\"\n self.repository.mark_dirty(roledb.TOP_LEVEL_ROLES)\n return self\n\n def add_target(self, filename, signing_role='targets'):\n \"\"\"Adds an existing target file and signs it.\"\"\"\n # @todo Just use add_target or add_targets consistently. This is only\n # here while fixtures are being ported to FixtureBuilder, to maintain\n # consistency with previously generated fixtures.\n if signing_role == 'targets':\n self._role('targets').add_targets([filename])\n else:\n self._role(signing_role).add_target(filename)\n self.repository.mark_dirty(['snapshot', 'targets', 'timestamp', signing_role])\n\n return self\n\n def create_target(self, filename, contents=None, signing_role='targets'):\n \"\"\"Creates a signed target file with arbitrary contents.\"\"\"\n if contents is None:\n contents = 'Contents: ' + filename\n\n path = os.path.join(self._server_dir, 'targets', filename)\n with open(path, 'w') as f:\n f.write(contents)\n\n self.add_target(filename, signing_role)\n\n return self\n\n def publish(self, with_client=False, consistent=True):\n \"\"\"Writes the TUF metadata to disk.\"\"\"\n self.repository.writeall(consistent_snapshot=consistent)\n\n staging_dir = os.path.join(self._server_dir, 'metadata.staged')\n live_dir = os.path.join(self._server_dir, 'metadata')\n shutil.copytree(staging_dir, live_dir, dirs_exist_ok=True)\n\n if with_client:\n client_dir = os.path.join(self.dir, 'client')\n # If a directory of client-side metadata already exists, remove it.\n if os.path.isdir(client_dir):\n shutil.rmtree(client_dir)\n\n repository_tool.create_tuf_client_directory(self._server_dir, client_dir)\n\n return self\n\n def read(self, filename):\n \"\"\"Returns the parsed contents of an existing metadata file.\"\"\"\n path = os.path.join(self._server_dir, 'metadata', filename)\n\n with open(path, 'r') as f:\n return json.load(f)\n\n def write(self, filename, data):\n path = os.path.join(self._server_dir, 'metadata', filename)\n\n with open(path, 'w') as f:\n json.dump(data, f, indent=1, separators=(',', ': '), sort_keys=True)\n\n def write_signed(self, filename, data, signing_role):\n \"\"\"Writes arbitrary metadata, signed with a given role's keys, to a file.\"\"\"\n self.write(filename, {\n 'signatures': self._sign(data, signing_role),\n 'signed': data\n })\n\n def _sign(self, data, signing_role):\n \"\"\"Signs arbitrary data using a given role's keys.\"\"\"\n signatures = []\n\n # Encode the data to canonical JSON, which is what we will actually sign.\n data = str.encode(formats.encode_canonical(data))\n\n # Loop through the signing role's private keys and use each one to sign\n # the canonical JSON representation of the data.\n for key in self._keys[signing_role]['private']:\n signature = signer.SSlibSigner(key).sign(data)\n signatures.append(signature.to_dict())\n\n return signatures\n\n\nclass ConsistencyVariantFixtureBuilder:\n\n def __init__(self, name, tuf_arguments={ 'use_snapshot_length': False }):\n self.fixtures = [\n FixtureBuilder(os.path.join(name, 'consistent'), tuf_arguments),\n FixtureBuilder(os.path.join(name, 'inconsistent'), tuf_arguments)\n ]\n\n def delegate(self, role_name, paths, parent='targets', path_hash_prefixes=None, terminating=False):\n for fixture in self.fixtures:\n fixture.delegate(role_name, paths, parent, path_hash_prefixes, terminating)\n return self\n\n def add_key(self, role_name):\n for fixture in self.fixtures:\n fixture.add_key(role_name)\n return self\n\n def revoke_key(self, role_name, key_index=0):\n for fixture in self.fixtures:\n fixture.revoke_key(role_name, key_index)\n return self\n\n def invalidate(self):\n for fixture in self.fixtures:\n fixture.invalidate()\n return self\n\n def add_target(self, filename, signing_role='targets'):\n for fixture in self.fixtures:\n fixture.add_target(filename, signing_role)\n return self\n\n def create_target(self, filename, contents=None, signing_role='targets'):\n for fixture in self.fixtures:\n fixture.create_target(filename, contents, signing_role)\n return self\n\n def publish(self, with_client=False):\n self.fixtures[0].publish(with_client, consistent=True)\n self.fixtures[1].publish(with_client, consistent=False)\n return self\n\n def read(self, filename):\n return [\n self.fixtures[0].read(filename),\n self.fixtures[1].read(filename)\n ]\n\n def write(self, filename, data):\n for fixture in self.fixtures:\n fixture.write(filename, data)\n\n def write_signed(self, filename, data, signing_role):\n for fixture in self.fixtures:\n fixture.write_signed(filename, data, signing_role)\n","sub_path":"fixtures/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":9283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"13067124","text":"import libpry\nfrom libqtile import confreader, manager\n\n\nclass uConfig(libpry.AutoTree):\n def test_syntaxerr(self):\n libpry.raises(\"invalid syntax\", confreader.File, \"configs/syntaxerr.py\")\n\n def test_basic(self):\n f = confreader.File(\"configs/basic.py\")\n assert f.keys\n assert f.themedir == \"configs/themes\"\n \n\ntests = [\n uConfig()\n]\n","sub_path":"test/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"412534283","text":"#String Count\ndef strcount(string):\n dict={i:string.count(i) for i in string}\n return dict\n\ndef wordcount(string):\n lst=string.split()\n max=0\n for i in lst:\n if(maxsize):\n size=len(str[i:j])\n set2.add(str[i:j])\n print(\"Palindrome:\",set2)\n \n newlist=[i for i in set2 if(len(i)==size)]\n print(\"\\nLongest:\",newlist)\n\n#Reverse\ndef rev(str2):\n list=str2.split()\n print(list)\n for i in list:\n print(i[::-1],end=\" \")\n\n\n\n#Remove Characters\ndef rm(str1,str2):\n for i in str1:\n if(i in str2):\n str2=str2.replace(i,'')\n print(\"String 1:\",str1)\n print(\"String 1:\",str2)\n\n#Date Validation\ndef date_validation(day, month, year):\n if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:\n max_day_value = 31\n elif month == 4 or month == 6 or month == 9 or month == 11:\n max_day_value = 30\n elif year % 4 == 0 and year % 100 != 0 or year % 400 == 0:\n max_day_value = 29\n else:\n max_day_value = 28\n if day in range(1,day > max_day_value+1):\n print(\"Date is invalid.\")\n else:\n print(\"Valid Date\")\n\n#Append at the end\ndef string_encode(str1):\n lst=str1.split()\n count2=[]\n for i in lst:\n count2.append(len(i))\n print(count2)\n str1=str1.replace('a','@')\n str1=str1.replace('e','e#')\n str1=str1.replace('m','m$')\n str1=str1.replace('t','t%')\n str1=str1.replace('i','i&')\n counti=0\n text1=\"\"\n for i in range(len(str1)):\n if(str1[i] == ' '):\n text1=text1+str(count2[counti])\n else:\n text1=text1+str1[i]\n print(text1)\n\n\ndef calcfrequency(str1):\n lst=[]\n lst.extend(str1)\n for i in str1:\n if(i!=\" \"):\n print(i,\":\",lst.count(i))","sub_path":"packages.py","file_name":"packages.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"549315975","text":"import Unit as u\nimport socket\n\n#Represente un joueur\nclass Player():\n def __init__(self, name, id ,civilization=None):\n self.name = name\n self.civilization = civilization\n self.selectedObjects = [] #Liste des unites selectionnes\n self.units = [] #Liste de toute les unites\n self.id = id #Numero du joueur dans la liste de joueur\n self.startPos = 0 #Position de depart du joueur (pour le mothership)\n self.units.append(u.Unit('Scout001',[0,0,0], moveSpeed=5.0))\n self.units.append(u.Unit('Scout002',[100,200,0], moveSpeed=5.0))\n self.spaceBuildings = [] #Liste de toute les building\n \n #Ajoute une camera au joueur seulement quand la partie commence \n def addCamera(self, position, galaxy):\n self.camera = Camera(position ,galaxy)\n#Represente la camera \nclass Camera():\n def __init__(self, defaultPos, galaxy):\n self.position = defaultPos\n self.screenCenter = (400,300)\n self.screenWidth = 800\n self.screenHeight = 600\n self.galaxy = galaxy #reference a la galaxie\n self.movingDirection = []\n #Pour calculer la distance entre la camera et un point\n def calcDistance(self, position):\n distX = position[0] - self.position[0]\n distY = position[1] - self.position[1]\n return [distX+self.screenCenter[0], distY+self.screenCenter[1]]\n #Pour calculer un point dans la galaxie a partir d'un point dans l'ecran\n def calcPointInWorld(self, x,y):\n dist = self.calcDistance([x,y])\n rX = self.position[0]-self.screenCenter[0]+x\n rY = self.position[1]-self.screenCenter[1]+y\n return [rX,rY,0]\n #Pour calculer un point sur la minimap a partir d'un point dans l'espace\n def calcPointOnMap(self, x, y):\n rX = x/200 * self.galaxy.width - self.galaxy.width/2\n rY = y/200 * self.galaxy.height - self.galaxy.height/2\n if rX < 0-self.galaxy.width/2+self.screenWidth/2:\n rX = 0-self.galaxy.width/2+self.screenWidth/2\n elif rX > self.galaxy.width/2-self.screenWidth/2:\n rX = self.galaxy.width/2-self.screenWidth/2\n \n if rY < 0-self.galaxy.height/2+self.screenHeight/2:\n rY = 0-self.galaxy.height/2+self.screenHeight/2\n elif rY > self.galaxy.height/2-self.screenHeight/2:\n rY = self.galaxy.height/2-self.screenHeight/2\n return [rX, rY]\n #Pour calculer un point dans la galaxie a partir d'un point dans la minimap\n def calcPointMinimap(self,x ,y ):\n rX = x/200 * self.galaxy.width - self.galaxy.width/2\n rY = y/200 * self.galaxy.height - self.galaxy.height/2\n return [rX, rY]\n #Retourne Vrai si la position est visible par la camera en ce moment\n def isInFOV(self, position):\n if position[0] > self.position[0]-self.screenWidth/2-20 and position[0] < self.position[0]+self.screenWidth/2+20:\n if position[1] > self.position[1]-self.screenHeight/2-20 and position[1] < self.position[1]+self.screenHeight/2+20:\n return True\n return False\n #Deplace la camera selon le contenu de la liste movingDirection\n def move(self):\n if 'LEFT' in self.movingDirection:\n if self.position[0] > (self.galaxy.width*-1)/2+self.screenCenter[0]:\n self.position[0]-=5\n elif 'RIGHT' in self.movingDirection:\n if self.position[0] < self.galaxy.width/2 - self.screenCenter[0]:\n self.position[0]+=5\n if 'UP' in self.movingDirection:\n if self.position[1] > (self.galaxy.height*-1)/2 + self.screenCenter[1]:\n self.position[1]-=5\n elif 'DOWN' in self.movingDirection:\n if self.position[1] < self.galaxy.height/2 - self.screenCenter[1]:\n self.position[1]+=5\n\n \n","sub_path":"src/Karim/Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"466759988","text":"# This is a master file for various versions of sorting algorithms implemented in Python\n\n# Version 1 of Merge Sort\ndef mergeSort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n left = arr[:mid]\n right = arr[mid:]\n\n # We will recursively call the mergeSort function\n # on both the left half and the right half of the \n # array until we reach the base cases (len(arr) = 1)\n mergeSort(left)\n mergeSort(right)\n\n # We initialize pointers for traversal of the left \n # and right half of the arrays as well as a third\n # pointer for inserting and sorting the values in\n # the original array\n i = 0\n j = 0\n k = 0\n\n # While the pointers haven't reached the end of\n # the arrays\n while i < len(left) and j < len(right):\n # if the value in the left array at position i\n # is less than the value at position j\n # in the right array\n if left[i] <= right[j]:\n arr[k] = left[i]\n # increase the left pointer by one\n i += 1\n \n else:\n arr[k] = right[j]\n j += 1\n k += 1\n\n # We'll create two other while loops just in case\n # one of the arrays rusn out of values to traverse\n while i < len(left):\n arr[k] = left[i]\n i += 1\n k += 1\n\n while j < len(right):\n arr[k] = right[j]\n j += 1\n k += 1\n\narr = [6, 2, 4, 1, 3, 7, 5, 8]\nmergeSort(arr)\nprint(arr)\n\n\n# Version 1 of Quick Sort\n# O(n^2) time\n\ndef quickSort(nums):\n\n # We'll create a helper function that recursively\n # sorts the array for everything below the pivot value\n # and verything above the pivot value\n quickSortHelper((nums, 0, len(nums) - 1))\n \n # Now we'll define the quickSortHelper function\n def quickSortHelper(nums, first, last):\n # if our \"first\" index pointer is less than our\n # \"last\" index pointer\n if first < last:\n # we'll use a partition function to find a pivot\n # value in the array and assign it to a variable\n # for easier access\n split = partition(nums, first, last)\n\n # Recursively call the helper function on values\n # below the pivot value and vlaues above the pivot\n quickSortHelper(nums, first, split - 1)\n quickSortHelper((nums, split + 1, last))\n\n def partition(nums, first, last):\n # The pivot value can be anything in the array really\n # but usually it can be the first value in the array\n pivot_value = nums[first]\n\n # create a left pointer and a right pointer\n # the left pointer has to be the value right after\n # \"pivot\" which is the first value specified\n left_point = first + 1\n right_point = last\n\n # Create a check point for the array being sorted/done\n done = False\n while not done:\n \n # This while loop checks that the left pointer index is less than\n # the right pointer index and that the value at the left pointer index\n # is less than the pivot value. If everything checks out then we increment\n # the left pointer\n while left_point <= right_point and nums[left_point] <= pivot_value:\n left_point = left_point + 1\n\n # This while loop checks that the right pointer index is greater than\n # the left pointer index and that the value at the right pointer index\n # is greater than the pivot value. If everything checks out then we decrement\n # the right pointer\n while right_point >= left_point and nums[right_point] >= pivot_value:\n right_point = right_point - 1\n\n # When the right pointer is pointing at an index\n # value less than the left pointer index then\n # we are done traversing the list\n if right_point < left_point:\n done = True\n # If none of the while loops check out and the \n # right pointer isn't at a value less than\n # the left pointer then we need to swap them\n # since they are in the wrong positions\n else:\n temp = nums[left_point]\n nums[left_point] = nums[right_point]\n nums[right_point] = temp\n\n temp = nums[first]\n nums[first] = nums[right_point]\n nums[right_point] = temp\n\n return right_point\nnums = [54, 26, 93, 17, 77, 31, 44, 55, 20]\nquickSort(nums)\nprint(nums)\n\n\n# Version 1 of Heap Sort\nfrom heapq import heappop, heappush\ndef heapSort(array):\n # create an empty array to store sorted elements\n heap = []\n\n # iterating over the array and pushing each element into the heap\n for element in array:\n # inserting using heap push\n heappush(heap, element)\n # empty list to store the sorted elements\n sorted_array = []\n while heap:\n # inserting into sorted_array until the heap is empty\n sorted_array.append(heappop(heap))\n # return the new sorted_array\n return sorted_array","sub_path":"Python/Sort/sorting.py","file_name":"sorting.py","file_ext":"py","file_size_in_byte":5249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"236514322","text":"#desafio JOGO DA VELHA\n\nfrom os import system\nfrom time import sleep\n\n\nvelha = [['2','2','2'],['2','2','2'],['2','2','2']]\n\n\ndef clear_velha (lista):\n for i in lista:\n for k in range (3):\n i[k] = '2'\n return lista\n\n\ndef show_velha (lista):\n system (\"cls\")\n divisor = 0\n print (\"\\n\")\n for i in velha:\n a = \" | \".join(i)\n a = a.replace ('2', ' ')\n a = a.replace ('0', 'O')\n a = a.replace ('-1', 'X')\n print (a)\n divisor += 1\n if divisor < 3:\n print ('— — —')\n \n\ndef check_local (lista, linha, coluna):\n l = 0\n for i in lista:\n if l == (linha - 1):\n if i[(coluna - 1)] != '2':\n return -5\n else:\n return 5\n else:\n l += 1\n \n\ndef check_diagonal_principal (lista):\n c = 0\n soma = 0\n for i in lista:\n soma += int(i[c])\n c += 1\n if soma == 0:\n return 0\n elif soma == -3:\n return 1\n else:\n return 2\n\n\ndef check_diagonal_secundaria (lista):\n c = 2\n soma = 0\n for i in lista:\n soma += int(i[c])\n c -= 1\n if soma == 0:\n return 0\n elif soma == -3:\n return 1\n else:\n return 2\n\n\ndef check_linha (lista):\n soma = 0\n for i in lista:\n for j in i:\n soma += int(j)\n if soma == 4:\n return 5\n else:\n if soma == 0:\n return 0\n elif soma == -3:\n return 1\n return -5\n\n\ndef check_coluna (lista):\n soma = 0\n c = 0\n while c < 2:\n for i in lista:\n soma += int(i[c])\n if soma == 0:\n return 0\n elif soma == -3:\n return 1\n else:\n soma = 0\n c += 1\n return -5\n\n\ndef check_empate (lista):\n if check_linha (lista) == -5 and check_coluna (lista) == -5 and check_diagonal_principal (lista) == 2 and check_diagonal_secundaria (lista) == 2:\n return 0\n else:\n return 1\n\n\ndef check_fim (lista, player1, player2):\n if check_linha (lista) == 0 or check_coluna (lista) == 0 or check_diagonal_principal (lista) == 0 or check_diagonal_secundaria (lista) == 0:\n system (\"cls\")\n print (\"\\n\\nEita poha, {} passou o rodo em {}\".format (player1, player2))\n print (\"\\n\\t\\t\\tPARABÉNS!! :)\")\n show_velha(lista)\n return 1\n elif check_linha (lista) == 1 or check_coluna (lista) == 1 or check_diagonal_principal (lista) == 1 or check_diagonal_secundaria (lista) == 1:\n system (\"cls\")\n print (\"\\n\\n{} se fudeu! {} passou a faca nele!\".format (player2, player1))\n print (\"\\n\\t\\tPARABÉNS para {} e meus pêsames para {}\".format (player2, player1))\n show_velha (velha)\n return 1\n elif check_empate (lista) == 0:\n system (\"cls\")\n print (\"Ihhhh, deu empate\")\n show_velha (velha)\n return 1\n\n\ndef jogada (lista, nome1, nome2, vez):\n while True:\n if vez % 2 != 0:\n print (\"\\nVez do(a) --->\", nome1)\n else:\n print (\"\\nVez do(a) --->\", nome2)\n linha = int (input (\"\\nLinha: \"))\n coluna = int (input (\"\\nColuna: \"))\n if check_local (velha, linha, coluna) == 5:\n l = 0\n for i in lista:\n if l == linha - 1:\n if vez % 2 != 0:\n i[(coluna - 1)] = \"0\"\n return lista\n else:\n i[(coluna - 1)] = \"-1\"\n return lista\n l += 1\n else:\n print (\"\\nShiii, posição ocupada.\\nTente outra.\")\n sleep (2)\n system (\"cls\")\n show_velha (velha)\n check_fim (lista, nome1, nome2)\n\n\ndef main ():\n vez = 9\n print(\"\\n\\n\\t\\t\\tJOGO DA VELHA\")\n player1 = input(\"\\n\\nQuem é o primeiro suicida a tentar esse jogo imortal?\\nSe acuse: \")\n player2 = input(\"\\nComo são dois doidos, se acuse também pro outro não ficar com vergonha: \")\n system (\"cls\")\n print (\"\\nAgora que sabemos quem são vocês, vamos iniciar a matança.\")\n print (\"\\n\\n\\t\\t\\tQUE COMEÇE O JOGO!!!!\")\n sleep (5)\n while True:\n #clear_velha (velha)\n show_velha (velha)\n jogada (velha, player1, player2, vez)\n vez -= 1\n\n\nif __name__ == \"__main__\":\n main ()","sub_path":"desafio_2.py","file_name":"desafio_2.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"397010217","text":"\"\"\"Test hook that runs shard splits continuously.\"\"\"\n\nimport copy\nimport random\nimport threading\nimport time\nimport uuid\n\nimport bson\nimport pymongo.errors\n\nfrom buildscripts.resmokelib import errors\nfrom buildscripts.resmokelib.testing.fixtures import interface as fixture_interface\nfrom buildscripts.resmokelib.testing.fixtures import shard_split\nfrom buildscripts.resmokelib.testing.fixtures.replicaset import ReplicaSetFixture\nfrom buildscripts.resmokelib.testing.hooks import interface\n\n\nclass ContinuousShardSplit(interface.Hook): # pylint: disable=too-many-instance-attributes\n \"\"\"Starts a shard split thread at the beginning of each test.\"\"\"\n\n DESCRIPTION = (\"Continuous shard split operations\")\n\n IS_BACKGROUND = True\n AWAIT_REPL_TIMEOUT_MINS = ReplicaSetFixture.AWAIT_REPL_TIMEOUT_MINS\n\n def __init__(self, hook_logger, fixture, shell_options):\n \"\"\"Initialize the ContinuousShardSplit.\n\n Args:\n hook_logger: the logger instance for this hook.\n fixture: the target ShardSplitFixture containing the donor replica set.\n shell_options: contains the global_vars which contains TestData.tenantIds to be used for\n shard splits.\n\n \"\"\"\n interface.Hook.__init__(self, hook_logger, fixture, ContinuousShardSplit.DESCRIPTION)\n\n if not isinstance(fixture, shard_split.ShardSplitFixture):\n raise ValueError(\"The ContinuousShardSplit hook requires a ShardSplitFixture\")\n self._shard_split_fixture = fixture\n self._shell_options = copy.deepcopy(shell_options)\n self._shard_split_thread = None\n\n def before_suite(self, test_report):\n \"\"\"Before suite.\"\"\"\n if not self._shard_split_fixture:\n raise ValueError(\"No ShardSplitFixture to run shard splits on\")\n self.logger.info(\"Starting the shard split thread.\")\n self._shard_split_thread = _ShardSplitThread(self.logger, self._shard_split_fixture,\n self._shell_options, test_report)\n self._shard_split_thread.start()\n\n def after_suite(self, test_report, teardown_flag=None):\n \"\"\"After suite.\"\"\"\n self.logger.info(\"Stopping the shard split thread.\")\n self._shard_split_thread.stop()\n self.logger.info(\"Stopped the shard split thread.\")\n\n def before_test(self, test, test_report):\n \"\"\"Before test.\"\"\"\n self.logger.info(\"Resuming the shard split thread.\")\n self._shard_split_thread.resume(test)\n\n def after_test(self, test, test_report):\n \"\"\"After test.\"\"\"\n self.logger.info(\"Pausing the shard split thread.\")\n self._shard_split_thread.pause()\n self.logger.info(\"Paused the shard split thread.\")\n\n\nclass ShardSplitLifeCycle(object):\n \"\"\"Class for managing the various states of the shard split thread.\n\n The job thread alternates between calling mark_test_started() and mark_test_finished(). The\n shard split thread is allowed to perform splits at any point between these two calls.\n Note that the job thread synchronizes with the shard split thread outside the context of\n this object to know it isn't in the process of running a split.\n \"\"\"\n\n _TEST_STARTED_STATE = \"start\"\n _TEST_FINISHED_STATE = \"finished\"\n\n def __init__(self):\n \"\"\"Initialize the ShardSplitLifeCycle instance.\"\"\"\n self.__lock = threading.Lock()\n self.__cond = threading.Condition(self.__lock)\n\n self.test_num = 0\n self.__test_state = self._TEST_FINISHED_STATE\n self.__should_stop = False\n\n def mark_test_started(self):\n \"\"\"Signal to the shard split thread that a new test has started.\n\n This function should be called during before_test(). Calling it causes the\n wait_for_shard_split_permitted() function to no longer block and to instead return\n true.\n \"\"\"\n with self.__lock:\n self.test_num += 1\n self.__test_state = self._TEST_STARTED_STATE\n self.__cond.notify_all()\n\n def mark_test_finished(self):\n \"\"\"Signal to the shard split thread that the current test has finished.\n\n This function should be called during after_test(). Calling it causes the\n wait_for_shard_split_permitted() function to block until mark_test_started() is called\n again.\n \"\"\"\n with self.__lock:\n self.__test_state = self._TEST_FINISHED_STATE\n self.__cond.notify_all()\n\n def is_test_finished(self):\n \"\"\"Return true if the current test has finished.\"\"\"\n with self.__lock:\n return self.__test_state == self._TEST_FINISHED_STATE\n\n def stop(self):\n \"\"\"Signal to the shard split thread that it should exit.\n\n This function should be called during after_suite(). Calling it causes the\n wait_for_shard_split_permitted() function to no longer block and to instead return\n false.\n \"\"\"\n with self.__lock:\n self.__should_stop = True\n self.__cond.notify_all()\n\n def wait_for_shard_split_permitted(self):\n \"\"\"Block until splits are permitted, or until stop() is called.\"\"\"\n with self.__lock:\n while not self.__should_stop:\n if self.__test_state == self._TEST_STARTED_STATE:\n return True\n\n self.__cond.wait()\n\n return False\n\n def wait_for_shard_split_interval(self, timeout):\n \"\"\"Block for 'timeout' seconds, or until stop() is called.\"\"\"\n with self.__lock:\n self.__cond.wait(timeout)\n\n def poll_for_idle_request(self): # noqa: D205,D400\n \"\"\"Return true if the shard split thread should continue running splits, or false\n if it should temporarily stop running splits.\n \"\"\"\n with self.__lock:\n return self.__test_state == self._TEST_FINISHED_STATE\n\n\nclass _ShardSplitOptions:\n def __init__( # pylint: disable=too-many-arguments\n self, logger, shard_split_fixture, tenant_ids, recipient_tag_name, recipient_set_name):\n self.logger = logger\n self.migration_id = uuid.uuid4()\n self.shard_split_fixture = shard_split_fixture\n self.tenant_ids = tenant_ids\n self.recipient_tag_name = recipient_tag_name\n self.recipient_set_name = recipient_set_name\n\n def get_migration_id_as_binary(self):\n \"\"\"Return the migration id as BSON Binary.\"\"\"\n return bson.Binary(self.migration_id.bytes, 4)\n\n def get_donor_rs(self):\n \"\"\"Return the current donor for the split fixture.\"\"\"\n return self.shard_split_fixture.get_donor_rs()\n\n def get_donor_name(self):\n \"\"\"Return the replica set name for the donor.\"\"\"\n return self.get_donor_rs().replset_name\n\n def get_donor_primary(self):\n \"\"\"Return a connection to the donor primary.\"\"\"\n return self.get_donor_rs().get_primary(timeout_secs=self.AWAIT_REPL_TIMEOUT_MINS)\n\n def get_donor_nodes(self):\n \"\"\"Return the nodes for the current shard split fixture donor.\"\"\"\n return self.get_donor_rs().nodes\n\n def get_recipient_nodes(self):\n \"\"\"Return the recipient nodes for the shard split fixture.\"\"\"\n return self.shard_split_fixture.get_recipient_nodes()\n\n def __str__(self):\n opts = {\n \"migration_id\": self.migration_id, \"tenant_ids\": self.tenant_ids,\n \"donor\": self.get_donor_name(), \"recipientSetName\": self.recipient_set_name,\n \"recipientTagName\": self.recipient_tag_name\n }\n return str(opts)\n\n\nclass _ShardSplitThread(threading.Thread): # pylint: disable=too-many-instance-attributes\n THREAD_NAME = \"ShardSplitThread\"\n\n WAIT_SECS_RANGES = [[0.05, 0.1], [0.1, 0.5], [1, 5], [5, 15]]\n POLL_INTERVAL_SECS = 0.1\n\n NO_SUCH_MIGRATION_ERR_CODE = 327\n INTERNAL_ERR_CODE = 1\n\n def __init__(self, logger, shard_split_fixture, shell_options, test_report):\n \"\"\"Initialize _ShardSplitThread.\"\"\"\n threading.Thread.__init__(self, name=self.THREAD_NAME)\n self.daemon = True\n self.logger = logger\n self._shard_split_fixture = shard_split_fixture\n self._tenant_ids = shell_options[\"global_vars\"][\"TestData\"][\"tenantIds\"]\n self._auth_options = shell_options[\"global_vars\"][\"TestData\"][\"authOptions\"]\n self._test = None\n self._test_report = test_report\n self._shell_options = shell_options\n\n self.__lifecycle = ShardSplitLifeCycle()\n # Event set when the thread has been stopped using the 'stop()' method.\n self._is_stopped_evt = threading.Event()\n # Event set when the thread is not performing shard splits.\n self._is_idle_evt = threading.Event()\n self._is_idle_evt.set()\n\n def run(self):\n \"\"\"Execute the thread.\"\"\"\n if not self._shard_split_fixture:\n self.logger.warning(\"No ShardSplitFixture to run shard splits on.\")\n return\n\n split_count = 0\n\n try:\n while True:\n self._is_idle_evt.set()\n\n permitted = self.__lifecycle.wait_for_shard_split_permitted()\n if not permitted:\n break\n\n if split_count >= 3: # TODO(SERVER-66045): Remove this check and run unbounded splits\n time.sleep(self.POLL_INTERVAL_SECS)\n continue\n\n self._is_idle_evt.clear()\n\n split_opts = self._create_split_opts(split_count)\n\n # Set up the donor for a split\n self._shard_split_fixture.add_recipient_nodes(split_opts.recipient_set_name)\n\n # Briefly wait to let the test run before starting the split operation, so that\n # the first split is more likely to have data to migrate.\n wait_secs = random.uniform(\n *self.WAIT_SECS_RANGES[split_count % len(self.WAIT_SECS_RANGES)])\n self.logger.info(f\"Waiting for {wait_secs} seconds before starting split.\")\n self.__lifecycle.wait_for_shard_split_interval(wait_secs)\n\n self.logger.info(f\"Starting shard split: {str(split_opts)}.\")\n start_time = time.time()\n is_committed = self._run_shard_split(split_opts)\n end_time = time.time()\n\n split_count += 1\n self.logger.info(\n f\"Completed shard split {str(split_opts)} in {(end_time - start_time) * 1000} ms.\"\n )\n\n # set up the fixture for the next split operation\n if is_committed:\n self._shard_split_fixture.replace_donor_with_recipient(\n split_opts.recipient_set_name)\n else:\n self._shard_split_fixture.remove_recipient_nodes()\n\n found_idle_request = self.__lifecycle.poll_for_idle_request()\n if found_idle_request:\n continue\n except Exception: # pylint: disable=W0703\n # Proactively log the exception when it happens so it will be flushed immediately.\n self.logger.exception(\"Shard split thread threw exception\")\n # The event should be signaled whenever the thread is not performing shard splits.\n self._is_idle_evt.set()\n\n def stop(self):\n \"\"\"Stop the thread when the suite finishes.\"\"\"\n self.__lifecycle.stop()\n self._is_stopped_evt.set()\n # Unpause to allow the thread to finish.\n self.resume(self._test)\n self.join()\n\n def pause(self):\n \"\"\"Pause the thread after test.\"\"\"\n self.__lifecycle.mark_test_finished()\n\n # Wait until we are no longer executing splits.\n self._is_idle_evt.wait()\n # Check if the thread is alive in case it has thrown an exception while running.\n self._check_thread()\n\n # Check that the fixture is still running.\n if not self._shard_split_fixture.is_running():\n raise errors.ServerFailure(\n f\"ShardSplitFixture with pids {self._shard_split_fixture.pids()} expected to be running in\"\n \" ContinuousShardSplit, but wasn't.\")\n\n def resume(self, test):\n \"\"\"Resume the thread before test.\"\"\"\n self._test = test\n self.__lifecycle.mark_test_started()\n\n def _wait(self, timeout):\n \"\"\"Wait until stop or timeout.\"\"\"\n self._is_stopped_evt.wait(timeout)\n\n def short_name(self):\n \"\"\"Return the name of the thread.\"\"\"\n return self.THREAD_NAME\n\n def _check_thread(self):\n \"\"\"Throw an error if the thread is not running.\"\"\"\n if not self.is_alive():\n msg = \"Shard split thread is not running.\"\n self.logger.error(msg)\n raise errors.ServerFailure(msg)\n\n def _is_fail_point_abort_reason(self, abort_reason):\n return abort_reason[\"code\"] == self.INTERNAL_ERR_CODE and abort_reason[\n \"errmsg\"] == \"simulate a shard split error\"\n\n def _create_split_opts(self, split_count):\n recipient_set_name = f\"rs{split_count+1}\"\n recipient_tag_name = \"recipientNode\"\n return _ShardSplitOptions(self.logger, self._shard_split_fixture, self._tenant_ids,\n recipient_tag_name, recipient_set_name)\n\n def _create_client(self, node):\n return fixture_interface.authenticate(node.mongo_client(), self._auth_options)\n\n def _run_shard_split(self, split_opts): # noqa: D205,D400\n try:\n donor_client = self._create_client(split_opts.get_donor_rs())\n res = self._commit_shard_split(donor_client, split_opts)\n is_committed = res[\"state\"] == \"committed\"\n\n # Garbage collect the split prior to throwing error to avoid conflicting operations\n # in the next test.\n if is_committed:\n # Wait for the donor/proxy to reroute at least one command before doing garbage\n # collection. Stop waiting when the test finishes.\n self._wait_for_reroute_or_test_completion(donor_client, split_opts)\n\n self._forget_shard_split(donor_client, split_opts)\n self._wait_for_garbage_collection(split_opts)\n\n if not res[\"ok\"]:\n raise errors.ServerFailure(\n f\"Shard split '{split_opts.migration_id}' on replica set \"\n f\"'{split_opts.get_donor_name()}' failed: {str(res)}\")\n\n if is_committed:\n return True\n\n abort_reason = res[\"abortReason\"]\n if self._is_fail_point_abort_reason(abort_reason):\n self.logger.info(\n f\"Shard split '{split_opts.migration_id}' on replica set \"\n f\"'{split_opts.get_donor_name()}' aborted due to failpoint: {str(res)}.\")\n return False\n raise errors.ServerFailure(\n f\"Shard split '{str(split_opts.migration_id)}' with donor replica set \"\n f\"'{split_opts.get_donor_name()}' aborted due to an error: {str(res)}\")\n except pymongo.errors.PyMongoError:\n self.logger.exception(\n f\"Error running shard split '{split_opts.migration_id}' with donor primary on \"\n f\"replica set '{split_opts.get_donor_name()}'.\")\n raise\n\n def _commit_shard_split(self, donor_client, split_opts): # noqa: D205,D400\n self.logger.info(f\"Starting shard split '{split_opts.migration_id}' on replica set \"\n f\"'{split_opts.get_donor_name()}'.\")\n\n while True:\n try:\n res = donor_client.admin.command({\n \"commitShardSplit\": 1, \"migrationId\": split_opts.get_migration_id_as_binary(),\n \"tenantIds\": split_opts.tenant_ids,\n \"recipientTagName\": split_opts.recipient_tag_name, \"recipientSetName\":\n split_opts.recipient_set_name\n }, bson.codec_options.CodecOptions(uuid_representation=bson.binary.UUID_SUBTYPE))\n\n if res[\"state\"] == \"committed\":\n self.logger.info(f\"Shard split '{split_opts.migration_id}' on replica set \"\n f\"'{split_opts.get_donor_name()}' has committed.\")\n return res\n if res[\"state\"] == \"aborted\":\n self.logger.info(f\"Shard split '{split_opts.migration_id}' on replica set \"\n f\"'{split_opts.get_donor_name()}' has aborted: {str(res)}.\")\n return res\n if not res[\"ok\"]:\n self.logger.info(f\"Shard split '{split_opts.migration_id}' on replica set \"\n f\"'{split_opts.get_donor_name()}' has failed: {str(res)}.\")\n return res\n except pymongo.errors.ConnectionFailure:\n self.logger.info(\n f\"Retrying shard split '{split_opts.migration_id}' against replica set \"\n f\"'{split_opts.get_donor_name()}'.\")\n\n def _forget_shard_split(self, donor_client, split_opts):\n self.logger.info(f\"Forgetting shard split '{split_opts.migration_id}' on replica set \"\n f\"'{split_opts.get_donor_name()}'.\")\n\n while True:\n try:\n donor_client.admin.command(\n {\"forgetShardSplit\": 1, \"migrationId\": split_opts.get_migration_id_as_binary()},\n bson.codec_options.CodecOptions(uuid_representation=bson.binary.UUID_SUBTYPE))\n return\n except pymongo.errors.ConnectionFailure:\n self.logger.info(\n f\"Retrying forget shard split '{split_opts.migration_id}' against replica \"\n f\"set '{split_opts.get_donor_name()}'.\")\n continue\n except pymongo.errors.OperationFailure as err:\n if err.code != self.NO_SUCH_MIGRATION_ERR_CODE:\n raise\n\n # The fixture was restarted.\n self.logger.info(\n f\"Could not find shard split '{split_opts.migration_id}' on donor primary on \"\n f\"replica set '{split_opts.get_donor_name()}': {str(err)}.\")\n return\n except pymongo.errors.PyMongoError:\n self.logger.exception(\n f\"Error forgetting shard split '{split_opts.migration_id}' on donor primary on \"\n f\"replica set '{split_opts.get_donor_name()}'.\")\n raise\n\n def _wait_for_garbage_collection(self, split_opts): # noqa: D205,D400\n try:\n donor_nodes = split_opts.get_donor_nodes()\n for donor_node in donor_nodes:\n self.logger.info(\n f\"Waiting for shard split '{split_opts.migration_id}' to be garbage collected on donor node on port {donor_node.port} of replica set '{split_opts.get_donor_name()}'.\"\n )\n\n donor_node_client = self._create_client(donor_node)\n while True:\n try:\n res = donor_node_client.config.command({\n \"count\": \"tenantSplitDonors\",\n \"query\": {\"tenantIds\": split_opts.tenant_ids}\n })\n if res[\"n\"] == 0:\n break\n except pymongo.errors.ConnectionFailure:\n self.logger.info(\n f\"Retrying waiting for shard split '{split_opts.migration_id}' to be garbage collected on donor node on port {donor_node.port} of replica set '{split_opts.get_donor_name()}'.\"\n )\n continue\n time.sleep(self.POLL_INTERVAL_SECS)\n\n recipient_nodes = split_opts.get_recipient_nodes()\n for recipient_node in recipient_nodes:\n self.logger.info(\n f\"Waiting for shard split '{split_opts.migration_id}' to be garbage collected on recipient node on port {recipient_node.port} of replica set '{split_opts.recipient_set_name}'.\"\n )\n\n recipient_node_client = self._create_client(recipient_node)\n while True:\n try:\n res = recipient_node_client.config.command({\n \"count\": \"tenantSplitDonors\",\n \"query\": {\"tenantIds\": split_opts.tenant_ids}\n })\n if res[\"n\"] == 0:\n break\n except pymongo.errors.ConnectionFailure:\n self.logger.info(\n f\"Retrying waiting for shard split '{split_opts.migration_id}' to be garbage collected on recipient node on port {recipient_node.port} of replica set '{split_opts.recipient_set_name}'.\"\n )\n continue\n time.sleep(self.POLL_INTERVAL_SECS)\n\n except pymongo.errors.PyMongoError:\n self.logger.exception(\n f\"Error waiting for shard split '{split_opts.migration_id}' from donor replica set '{split_opts.get_donor_name()} to recipient replica set '{split_opts.recipient_set_name}' to be garbage collected.\"\n )\n raise\n\n def _wait_for_reroute_or_test_completion(self, donor_client, split_opts):\n start_time = time.time()\n\n self.logger.info(\n f\"Waiting for donor primary of replica set '{split_opts.get_donor_name()}' for shard split '{split_opts.migration_id}' to reroute at least one conflicting command. Stop waiting when the test finishes.\"\n )\n\n while not self.__lifecycle.is_test_finished():\n try:\n # We are reusing the infrastructure originally developed for tenant migrations,\n # and aren't concerned about conflicts because we don't expect the tenant migration\n # and shard split hooks to run concurrently.\n doc = donor_client[\"testTenantMigration\"][\"rerouted\"].find_one(\n {\"_id\": split_opts.get_migration_id_as_binary()})\n if doc is not None:\n return\n except pymongo.errors.ConnectionFailure:\n self.logger.info(\n f\"Retrying waiting for donor primary of replica set '{split_opts.get_donor_name()}' for shard split '{split_opts.migration_id}' to reroute at least one conflicting command.\"\n )\n continue\n except pymongo.errors.PyMongoError:\n end_time = time.time()\n self.logger.exception(\n f\"Error running find command on donor primary replica set '{split_opts.get_donor_name()}' after waiting for reroute for {(end_time - start_time) * 1000} ms\"\n )\n raise\n\n time.sleep(self.POLL_INTERVAL_SECS)\n","sub_path":"buildscripts/resmokelib/testing/hooks/shard_split.py","file_name":"shard_split.py","file_ext":"py","file_size_in_byte":23090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"327206551","text":"#!/usr/bin/env python\n\"\"\"\nESTIMATE OCCLUSIONS.\n\nBackground:\n------------------------------------------------------------------------------\nFor a pixel (x,y) in frame I0, if back flow at location (x,y)+flow0 in frame I1\ndisagrees with flow in frame I0 by a given threshold, we mark it as occluded.\nNote that the same method was used for MIP Sintel flow dataset. We use a sightly\nhigher threshold of 0.5 pixels by default, because our resolution is higher.\n\nNote:\n------------------------------------------------------------------------------\nThis main function is not used for pipeline.sh, as occuslions are also computed\nin unpack_exr_main.py.\n\n\"\"\"\nimport argparse\nimport os\nfrom skimage.io import imsave\n\nimport flow_util\nimport io_util\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description='Computes occlusions by finding forward-back flow discrepancies '\n 'over the provided threshold.')\n parser.add_argument(\n '--flow_pattern', action='store', type=str, required=True)\n parser.add_argument(\n '--backflow_pattern', action='store', type=str, required=True)\n parser.add_argument(\n '--threshold', action='store', type=float, default=0.5)\n parser.add_argument(\n '--odir', action='store', type=str, required=True)\n parser.add_argument(\n '--frames', action='store', type=str, default='',\n help='CSV string of frame numbers to process; otherwise process all; e.g. '\n '--frames=\"1,5,7\".')\n args = parser.parse_args()\n\n data = {}\n io_util.parse_file_sequence(args.flow_pattern, data, 'flow')\n io_util.parse_file_sequence(args.backflow_pattern, data, 'backflow')\n\n legit_frames = [ k for k in data.keys() if\n ('flow' in data[k] and k+1 in data and 'backflow' in data[k+1]) ]\n if len(args.frames) > 0:\n frames = [ int(x) for x in args.frames.split(',') if int(x) in legit_frames ]\n print('Only processing frames %s out of %s' % (str(frames), str(legit_frames)))\n legit_frames = frames\n else:\n print('Processing frames %s' % str(legit_frames))\n legit_frames.sort()\n\n for f in legit_frames:\n flow = io_util.read_flow(data[f]['flow'])\n backflow = io_util.read_flow(data[f+1]['backflow'])\n occ_fname = os.path.join(args.odir, 'occlusions%06d.png' % f)\n occ = flow_util.get_occlusions_vec(flow, backflow,\n pixel_threshold=args.threshold)\n imsave(occ_fname, occ)\n","sub_path":"creativeflow/blender/compute_occlusions_main.py","file_name":"compute_occlusions_main.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"342368569","text":"#-*- coding:utf-8 -*-\nimport sys\nimport json\nimport time\nfrom weixin import DataMod\nfrom weixin.update import *\nfrom weixin.Delete import *\nfrom weixin.search import *\nfrom weixin.tuling import *\nfrom datetime import datetime\nfrom wechat_sdk import WechatExt\nfrom weixin.spider import *\nfrom django.http.response import HttpResponse, HttpResponseBadRequest\nfrom django.views.decorators.csrf import csrf_exempt\nfrom wechat_sdk import WechatConf\nfrom wechat_sdk import WechatBasic\nfrom wechat_sdk.exceptions import ParseError\nfrom wechat_sdk import WechatExt\nfrom wechat_sdk.messages import (TextMessage, VoiceMessage, ImageMessage, VideoMessage, LinkMessage, LocationMessage, EventMessage, ShortVideoMessage)\nconf = WechatConf(\n token='weixin',\n appid='wx2754bc14e0d446b8',\n appsecret='7fd629600a5dd033d502c866b22e0edd',\n encrypt_mode='normal',\n #encoding_aes_key='YOUR_AES_KEY'\n)\nnow = time.time()\nnow = time.gmtime(now)\nnow = time.strftime(\"%Y-%m-%d %H:%M:%S\")\nnowtime = \"出错,出错时间\"+str(now)\n@csrf_exempt\ndef wechat_home(request):\n\n signature = request.GET.get('signature') #提取signature\n timestamp = request.GET.get('timestamp') #提取timestamp\n nonce = request.GET.get('nonce') #提取nonce\n wechat_instance = WechatBasic(conf=conf)\n if not wechat_instance.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): #验证地址有效性\n return HttpResponseBadRequest('Verify Failed') #无效\n else:\n if request.method == 'GET':\n response = request.GET.get('echostr', 'error')\n else:\n try:\n wechat_instance.parse_data(request.body) #解析收到的XML消息\n message = wechat_instance.get_message() #获取解析好的微信请求信息\n if isinstance(message, VoiceMessage):\n return_text = '(\"▔□▔)/好难听的声音\")'\n elif isinstance(message, EventMessage):\n if message.type == 'subscribe':\n return_text = '欢迎关注机器人161班的微信号ε=ε=(ノ≧∇≦)ノ'\n elif message.type == 'unsubsrcibe':\n return_text = '你死定了,敢取关( ̄へ ̄)'\n elif message.type == 'scan':\n return_text = '没想到你竟然扫了我的二维码,我好开心( ̄▽ ̄)'\n elif message.type == 'click':\n key = message.key\n if key == 'score':\n try_again(1)\n text_key = return_socre()\n return_text = text_key\n elif key == 'community':\n return_text = '好气啊,还木有这个功能哦'\n elif key == 'exam':\n return_text = '我害怕考试(´;ω;`)'\n elif key == 'telephone':\n return_text = '别傻了,输姓名就可以查找了'\n elif key == 'new':\n responsed = wechat_instance.response_news([\n {\n 'title':'我们的第一个冬至',\n 'picurl':'http://wx.xuntu365.com/upload/kindeditor/image/20161225/20161225193951_52847.jpg',\n 'description':'那真是我们终生的回忆啊',\n 'url':'http://wx.xuntu365.com/gzzh/artview-1.html?wid=386674&rid=550109'\n }\n ])\n return HttpResponse(responsed, content_type=\"application/xml\")\n elif isinstance(message, ImageMessage):\n return_text = '和我斗图?(╬゚д゚)▄︻┻┳═一'\n elif isinstance(message, LinkMessage):\n return_text = '我是纯洁的←◡←'\n elif isinstance(message, LocationMessage):\n return_text = '为什么要发地址给我,难道你想要98逸'\n elif isinstance(message, VideoMessage):\n return_text = '口意⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄'\n elif isinstance(message, ShortVideoMessage):\n return_text = '这个视频和你**一样短⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄'\n elif isinstance(message, TextMessage):\n content = message.content.strip()\n chose = '第'\n u = Use()\n if content == '你好':\n return_text = 'hello!'\n elif content == '查询常规':\n return_text = '直接输入社团或常规即可查询'\n #elif content == '常规':\n # try:\n # try_again(1)\n # text = return_socre()\n # if text == None:\n # text = '暂无'\n # return_text = text\n # except:\n # return_text = \"哎呦,出错了,已联系管理员处理\"\n # wechat_instance.send_text_message('opL4ZwSzQPdCcefPKYo_LR0ImjhI', nowtime)\n #elif content == '如何使用':\n # return_text = '输入:全部常规,即可获取最近的常规;'\n elif '的操行分' in content:\n name = content[:3]\n return_text = Search(name)\n elif content == '常规':\n return_text = get_new_routine()\n elif content == '社团':\n date,url = get_new_association()\n responsed = wechat_instance.response_news([\n {\n 'title':'社团',\n 'picurl': 'http://source.pixiv.net/www/images/share/pictures.jpg',\n 'description':date,\n 'url': url\n }\n ])\n return HttpResponse(responsed, content_type=\"application/xml\")\n elif content == '更新':\n return_text = manual_update()\n elif '常规' in content:\n content = content[:5]\n try:\n if u.pop_all(content,'changgui') != None:\n return_text = u.pop_all(content,'changgui')\n else :\n return_text = '查询失败'\n except:\n return_text = '查询失败'\n elif '总评' in content:\n if u.pop_all(content,'week') != None:\n return_text = u.pop_all(content,'week')\n else:\n return_text = '查询失败'\n elif '社团' in content:\n content = content[:5]\n try:\n if u.pop_all(content,'shetuan') != None:\n date,url = u.pop_all(content,'shetuan')\n responsed = wechat_instance.response_news([\n {\n 'title':'社团',\n 'picurl': 'http://source.pixiv.net/www/images/share/pictures.jpg',\n 'description':date,\n 'url': url\n }\n ])\n return HttpResponse(responsed, content_type=\"application/xml\")\n else:\n return_text = '查询失败'\n except:\n return_text = '查询失败'\n\n\n\n\n\n #elif ',' in content :\n # message = content.split(',')\n # try:\n # name = message[0]\n # much = message[1]\n # ID = message[2]\n # result = message[3]\n # except:\n # raise\n # finally:\n # ret = update(name=name,much=much,ID=ID,result=result)\n # return_text = ret\n #elif '删除' in content:\n # del_str = content[2:]\n # a = delsql(del_str)\n # return_text = a\n #elif content == '全部常规':\n # try:\n # try_again(0)\n # page = return_all_socre()\n # if page == None:\n # page = '暂无'\n # return_text = page\n # except:\n # return_text = \"哎呀,出错了,已联系管理员处理\"\n # wechat_instance.send_text_message('opL4ZwSzQPdCcefPKYo_LR0ImjhI', nowtime)\n #elif content == '社团':\n # try:\n # image = return_image()\n # if image == '':\n # return_text = '暂无'\n # else :\n # responsed = wechat_instance.response_news([\n # {\n # 'title':'社团',\n # 'picurl':'http://www.zhyz.net.cn/service?wdApplication=xw&wdService=wenz_ck&wdToken=58629&wdOutputComponent=440163743&wdtest=false&wdComponentWebsite=4401421&wzid=6000503010237',\n # 'description':'社团情况',\n # 'url':str(image)\n # }\n # ])\n # return HttpResponse(responsed, content_type=\"application/xml\")\n # except:\n # return_text = \"哎呀,出错了,已联系管理员处理\"\n # wechat_instance.send_text_message('opL4ZwSzQPdCcefPKYo_LR0ImjhI', nowtime)\n #elif content == 'userlist':\n # return_text = wechat_instance.get_followers()\n #elif content == 'userinfo':\n # return_text = wechat_instance.get_user_info('opL4ZwSzQPdCcefPKYo_LR0ImjhI', lang='zh_CN')\n #elif content == 'sent':\n # wechat_instance.send_text_message('opL4ZwSzQPdCcefPKYo_LR0ImjhI', content)\n else :\n return_text = tuling_speak(content)\n response = wechat_instance.response_text(content = return_text)\n #wechat_instance.create_menu(menu_data = menu)\n except ParseError:\n return HttpResponseBadRequest('Invalid XML Data')\n return HttpResponse(response, content_type=\"application/xml\")\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"603679595","text":"#-------------------------------------------------------------------------------\r\n# Name: temperature_effects\r\n# Purpose:\r\n#\r\n# Author: Han\r\n#\r\n# Created: 10/05/2011\r\n# Copyright: (c) Han 2011\r\n# Licence: \r\n#-------------------------------------------------------------------------------\r\n#!/usr/bin/env python\r\n\r\nimport xlrd\r\n#xlrd is a module to extract data from M$ excel files, should be replaced by csv\r\nimport datetime\r\nfrom math import exp\r\nimport calendar\r\n\r\nclass Tp_date(object):\r\n def __init__(self, onset_year = 1994,\r\n optimal_temperature = 1.1,\r\n chilling_effect_interval = 20,\r\n chilling_effect_onset_month = 10,\r\n chilling_effect_onset_day = 30,\r\n chilling_quantity_required = 56,\r\n characteristic_temperature = 9.0,\r\n heat_sigmoidal = False,\r\n sigmoidal_slope = 6.0,\r\n heat_quantity_required = 83.58):\r\n\r\n self.onset_year = onset_year\r\n self.optimal_temperature = optimal_temperature\r\n self.chilling_effect_interval = chilling_effect_interval\r\n self.chilling_effect_onset_month = chilling_effect_onset_month\r\n self.chilling_effect_onset_day = chilling_effect_onset_day\r\n self.chilling_quantity_required = chilling_quantity_required\r\n self.characteristic_temperature = characteristic_temperature\r\n self.heat_sigmoidal = heat_sigmoidal\r\n self.sigmoidal_slope = sigmoidal_slope\r\n self.heat_quantity_required = heat_quantity_required\r\n\r\n self.temp_file = xlrd.open_workbook(\"../../share/data/temperature_data.xls\")\r\n self.temp_sheet = self.temp_file.sheet_by_name(\"moy\")\r\n\r\n self.chilling_accummulation = 0\r\n self.heat_accummulation = 0\r\n\r\n self.dormancy_break_date = None\r\n self.bud_break_date = None\r\n\r\n def bud_break(self):\r\n for i in range(1, self.temp_sheet.nrows):\r\n dt_tuple = xlrd.xldate_as_tuple(self.temp_sheet.cell(i,0).value, 0)\r\n dt = datetime.datetime(*dt_tuple)\r\n if dt.month == self.chilling_effect_onset_month and dt.day == self.chilling_effect_onset_day:\r\n r_onset = i\r\n break\r\n for j in range(1, self.temp_sheet.ncols):\r\n if self.temp_sheet.cell(0,j).value == self.onset_year:\r\n c_onset = j\r\n break\r\n for k in range(r_onset, self.temp_sheet.nrows):\r\n tp_k = self.temp_sheet.cell(k, c_onset).value\r\n if tp_k > self.optimal_temperature - self.chilling_effect_interval and tp_k < self.optimal_temperature + self.chilling_effect_interval:\r\n ce = 1 - abs(tp_k - self.optimal_temperature)/self.chilling_effect_interval\r\n \"\"\"\r\n if tp_k > self.optimal_temperature:\r\n ce = 1 - (tp_k - self.optimal_temperature)/self.chilling_effect_interval\r\n else:\r\n ce = 1 - (self.optimal_temperature - tp_k)/self.chilling_effect_interval\r\n \"\"\"\r\n else:\r\n ce = 0\r\n self.chilling_accummulation += ce\r\n #print self.chilling_accummulation, xlrd.xldate_as_tuple(self.temp_sheet.cell(k,0).value, 0)[1], xlrd.xldate_as_tuple(self.temp_sheet.cell(k,0).value, 0)[2]\r\n if self.chilling_accummulation >= self.chilling_quantity_required:\r\n r_dormancy_break = k\r\n #print \"dormancy_date: \", xlrd.xldate_as_tuple(self.temp_sheet.cell(r_dormancy_break,0).value, 0)[1], xlrd.xldate_as_tuple(self.temp_sheet.cell(r_dormancy_break,0).value, 0)[2]\r\n dbd_tuple = xlrd.xldate_as_tuple(self.temp_sheet.cell(r_dormancy_break,0).value, 0)\r\n dbd = datetime.datetime(*dbd_tuple)\r\n if dbd.month < self.chilling_effect_onset_month:\r\n if calendar.isleap(self.onset_year) and dbd.month > 2:\r\n self.dormancy_break_date = (self.onset_year, dbd.month, dbd.day-1, 0, 0)\r\n else:\r\n self.dormancy_break_date = (self.onset_year, dbd.month, dbd.day, 0, 0)\r\n else:\r\n self.dormancy_break_date = (self.onset_year-1, dbd.month, dbd.day, 0, 0)\r\n break\r\n\r\n for p in range(r_dormancy_break+1, self.temp_sheet.nrows):\r\n tp_p = self.temp_sheet.cell(p, c_onset).value\r\n if self.heat_sigmoidal == False:\r\n he = exp(tp_p/self.characteristic_temperature-1)\r\n else:\r\n he = 2 / (1 + exp((tp_p - self.characteristic_temperature) / self.sigmoidal_slope))\r\n self.heat_accummulation += he\r\n if self.heat_accummulation >= self.heat_quantity_required:\r\n r_bud_break = p\r\n break\r\n\r\n # Get the date for bud break\r\n br_tuple = xlrd.xldate_as_tuple(self.temp_sheet.cell(r_bud_break, 0).value, 0)\r\n br = datetime.datetime(*br_tuple)\r\n if br.month < self.chilling_effect_onset_month:\r\n if calendar.isleap(self.onset_year) and br.month > 2:\r\n self.bud_break_date = (self.onset_year, br.month, br.day-1, 0, 0)\r\n else:\r\n self.bud_break_date = (self.onset_year, br.month, br.day, 0, 0)\r\n return self.bud_break_date\r\n else:\r\n self.bud_break_date = (self.onset_year-1, br.month, br.day, 0, 0)\r\n return self.bud_break_date\r\n\r\nclass Test(object):\r\n def __init__(self, first_year=1963, last_year=2010):\r\n t = open(\"dates_test.csv\", \"w\")\r\n t.write(\"year, dormancy_break, bud_break\\n\")\r\n t.close()\r\n\r\n t = open(\"dates_test.csv\", \"a\")\r\n for y in range(first_year, last_year+1):\r\n tp_date = Tp_date(onset_year=y)\r\n dt = tp_date.bud_break()\r\n t.write(str(y) + \",\")\r\n t.write(str(tp_date.dormancy_break_date[2]) + \"/\" + str(tp_date.dormancy_break_date[1]) + \",\")\r\n t.write(str(tp_date.bud_break_date[2]) + \"/\" + str(tp_date.bud_break_date[1]) + \"\\n\")\r\n t.close()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"src/stocatree/temperature_effects.py","file_name":"temperature_effects.py","file_ext":"py","file_size_in_byte":6205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"280948054","text":"import os\n\n#grab folder where script is\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nDATABASE = 'flasktaskr.db'\nCSRF_ENABLED = True\nSECRET_KEY = 'my_precious'\n\n#define the full path for db\nDATABASE_PATH = os.path.join(basedir, DATABASE)\n\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH\n","sub_path":"project/_config.py","file_name":"_config.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"318937047","text":"#Uses python3\n\n\nfrom typing import Dict, List, Tuple\n\n\ndef transform_edges_to_adjacency(num_of_vertices: int, edges: List[Tuple[int, int]]) -> Dict[int, List[int]]:\n adjacency = {i: [] for i in range(num_of_vertices)}\n for (a, b) in edges:\n adjacency[a].append(b)\n adjacency[b].append(a)\n return adjacency\n\n\nclass ConnectedComponents:\n def __init__(self, adjacency: Dict[int, List[int]]):\n self.vertices = sorted(list(adjacency.keys()))\n self.adjacency = adjacency\n self.component_count = 0\n self.components = {v: None for v in self.vertices}\n self.visited_vertices = []\n\n def reset(self):\n self.component_count = 0\n self.visited_vertices = []\n\n def dfs(self):\n for vertex in self.vertices:\n if vertex not in self.visited_vertices:\n self.explore(vertex)\n self.component_count += 1\n\n def explore(self, vertex: int):\n self.visited_vertices.append(vertex)\n self.components[vertex] = self.component_count\n for connected_vertex in self.adjacency[vertex]:\n if connected_vertex not in self.visited_vertices:\n self.explore(connected_vertex)\n\n\ndef number_of_components(adjacency,):\n cc = ConnectedComponents(adjacency)\n cc.dfs()\n return cc.component_count\n\n\nif __name__ == '__main__':\n n, m = list(map(int, input().split()))\n edges_list = []\n for i in range(0, m):\n edges_list.append(list(map(int, input().split())))\n\n edges_list = [(a - 1, b - 1) for a, b in edges_list]\n adj = transform_edges_to_adjacency(n, edges_list)\n\n print(number_of_components(adj))\n","sub_path":"c3/w1/2_connected_components/connected_components.py","file_name":"connected_components.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"620880557","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 17 23:03:49 2019\n\n@author: ASUS\n\"\"\"\nimport csv\nfn=r'Post_All.csv'\nwith open(fn,encoding='UTF-8-sig') as csvFile:\n csvReader=csv.reader(csvFile)\n listReport=list(csvReader)\n col=listReport[0]\n print(col)\n col1=len(listReport)\n print(col1-1)\n x=[]\n y=[]\n post=[]\n sat=[]\n sun=[]\n taipost=[]\n otherpost=[]\n taisat=[]\n othersat=[]\n\n \n for i in range(1,col1):\n if listReport[i][14]!='':\n post+=[listReport[i]]\n if listReport[i][15]!='':\n sat+=[listReport[i]]\n if listReport[i][16]!='':\n sun+=[listReport[i]]\n \n postnum=len(post)\n satnum=len(sat)\n sunnum=len(sun)\n \n print('全台郵局總數:{},平日延時提供服務家數:{},周六提供服務家數:{},周日提供服務家數:{}'.format(col1-1,postnum,satnum,sunnum))\n\n \n for i in range(0,postnum):\n if post[i][8]=='臺北市':\n taipost+=[post[i]]\n else:\n otherpost+=[post[i]]\n \n for i in range(0,satnum):\n if sat[i][8]=='臺北市':\n taisat+=[sat[i]]\n else:\n othersat+=[sat[i]]\n \n taipostnum=len(taipost)\n otherpostnum=len(otherpost)\n taisatnum=len(taisat)\n othersatnum=len(othersat)\n \n print(\"臺北市平日延時服務家數:{},其它地區平日延時服務家數:{}\".format(taipostnum,otherpostnum))\n print(\"台北市周六營業家數:{},其它地區周六營業家數:{}\".format(taisatnum,othersatnum))\n\n\nimport matplotlib.pyplot as plt\n \nact=['全台家數','平日延時家數']\npienum=[col1-postnum,postnum]\ncolors=['lightgreen','lightblue']\nplt.pie(pienum,labels=act,colors=colors,shadow=True,explode=(0,0.1),autopct='%1.1f%%')\nplt.axis('equal')\nplt.show()\n\nact=['全台家數','周六營業家數']\npienum=[col1-satnum,satnum]\ncolors=['purple','grey']\nplt.pie(pienum,labels=act,colors=colors,shadow=True,explode=(0,0.1),autopct='%1.1f%%')\nplt.axis('equal')\nplt.show()\n\n\nact=['台北平日平日延時營業家數','其它地區平日��時營業家數']\npienum=[taipostnum,otherpostnum]\ncolors=['pink','brown']\nplt.pie(pienum,labels=act,colors=colors,shadow=True,explode=(0,0.1),autopct='%1.1f%%')\nplt.axis('equal')\nplt.show()\n\nact=['台北周六營業家數','其它周六營業家數']\npienum=[taisatnum,othersatnum]\ncolors=['red','yellow']\nplt.pie(pienum,labels=act,colors=colors,shadow=True,explode=(0,0.1),autopct='%1.1f%%')\nplt.axis('equal')\nplt.show()\n\n \n \n \n \n \n \n \n ","sub_path":"post-練習1.py","file_name":"post-練習1.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"401947182","text":"import logging\n\n\ndef test_logDemo():\n logger = logging.getLogger(__name__) # name is used to mention test case name in object\n\n filelocation = logging.FileHandler(\"loggingfile.txt\") # create an object to specify the location of file\n\n formatting = logging.Formatter(\"%(asctime)s :%(levelname)s : %(name)s :%(message)s\")\n filelocation.setFormatter(formatting)\n\n logger.addHandler(filelocation) # pass the location through created object\n logger.setLevel(logging.ERROR)\n logger.debug(\"Debug statement is printed\")\n logger.info(\"Information for this test case is printed\")\n logger.warning(\"Warning message is printed. But test case execution continues\")\n logger.error(\"Error occurred which is failing the test case\")\n logger.critical(\"Critical error is occurring\")\n","sub_path":"Pytest/test_Logging.py","file_name":"test_Logging.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"108950394","text":"\n#DO NOT CHANGE!\ndef read_train_file():\n '''\n HELPER function: reads the training files containing the words and corresponding tags.\n Output: A tuple containing 'sentences' and 'tags'\n 'sentences': It is a list of sentences where each sentence, in turn, is a list of words.\n For example - [['A','boy','is','running'],['Pick','the','red','cube'],['One','ring','to','rule','them','all']]\n 'tags': A nested list similar to above, just the corresponding tags instead of words.\n ''' \n f = open('train_data.txt','r')\n sentences = []\n tags = []\n sentence = []\n tag = []\n for line in f:\n s = line.rstrip('\\n')\n if s == '':\n sentences.append(sentence)\n tags.append(tag)\n sentence=[]\n tag=[]\n else:\n w,t = line.split()\n sentence.append(w)\n tag.append(t)\n sentences = sentences[1:]\n tags = tags[1:]\n assert len(sentences) == len(tags)\n f.close()\n return (sentences,tags)\n\n\n\n\n\n\n\n\n#NEEDS TO BE FILLED!\ndef store_emission_and_transition_probabilities(train_list_words, train_list_tags):\n \n '''\n This creates dictionaries storing the transition and emission probabilities - required for running Viterbi.\n INPUT: The nested list of words and corresponding nested list of tags from the TRAINING set. This passing of correct lists and calling the function\n has been done for you. You only need to write the code for filling in the below dictionaries. (created with bigram-HMM in mind)\n OUTPUT: The two dictionaries\n\n HINT: Keep in mind the boundary case of the starting POS tag. You may have to choose (and stick with) some starting POS tag to compute bigram probabilities\n for the first actual POS tag.\n '''\n\n \n tag_follow_tag = {};myTags= ['VERB','NOUN','PRON', 'ADJ','ADV','ADP','CONJ','DET','NUM','PRT','.','X', 'UNKNOWN']\n \n '''Nested dictionary to store the transition probabilities\n each tag X is a key of the outer dictionary with an inner dictionary as the corresponding value\n The inner dictionary's key is the tag Y following X\n and the corresponding value is the number of times Y follows X - convert this count to probabilities finally before returning\n for example - { X: {Y:0.33, Z:0.25}, A: {B:0.443, W:0.5, E:0.01}} (and so on) where X,Y,Z,A,B,W,E are all POS tags\n so the first key-dictionary pair can be interpreted as \"there is a probability of 0.33 that tag Y follows tag X, and 0.25 probability that Z follows X\"\n '''\n word_tag = {}\n \"\"\"Nested dictionary to store the emission probabilities.\n Each word W is a key of the outer dictionary with an inner dictionary as the corresponding value\n The inner dictionary's key is the tag X of the word W\n and the corresponding value is the number of times X is a tag of W - convert this count to probabilities finally before returning\n for example - { He: {A:0.33, N:0.15}, worked: {B:0.225, A:0.5}, hard: {A:0.1333, W:0.345, E:0.25}} (and so on) where A,N,B,W,E are all POS tags\n so the first key-dictionary pair can be interpreted as \"there is a probability of 0.33 that A is the POS tag for He, and 0.15 probability that N is the POS tag for He\"\n \"\"\"\n\n\n # *** WRITE YOUR CODE HERE *** \n \n \n ran1 = len(train_list_tags) #Emission matrix calculations\n for i in range(1, ran1+1):\n ran2= len(train_list_tags[i-1])\n for j in range(1, ran2+1):\n try:\n x = word_tag[train_list_tags[i-1][j-1]]\n except:\n word_tag[train_list_tags[i-1][j-1]]={}\n try:\n word_tag[(train_list_tags[i-1][j-1])][(train_list_words[i-1][j-1])]+=1\n except:\n word_tag[(train_list_tags[i-1][j-1])][(train_list_words[i-1][j-1])]=1\n\n \n count = 2**10\n for key, value in word_tag.items():\n \n for key2, val in word_tag[key].items():\n count+=word_tag[key][key2]\n for key2, val in word_tag[key].items():\n word_tag[key][key2]/=count\n \n \n for aTag in myTags:\n try:\n x = tag_follow_tag[aTag]\n except:\n tag_follow_tag[aTag]={}\n\n for key, value in tag_follow_tag.items(): #Transition matrix\n \n for i in range(1, ran1+1):\n ran2 = len(train_list_tags[i-1])\n train_list_words[i-1].insert(len(train_list_words[i-1])-1, 'EndOfSentence')\n\n for j in range(1, ran2):\n if train_list_tags[i-1][j-1] == (key):\n try:\n tag_follow_tag[key][(train_list_tags[i-1][j])]+=1\n except:\n tag_follow_tag[key][(train_list_tags[i-1][j])]=1\n \n \n \n for _ in range(1, ran1+1):\n try:\n tag_follow_tag['UNKNOWN'][(train_list_tags[_-1][0])]+=1\n except:\n tag_follow_tag['UNKNOWN'][(train_list_tags[_-1][0])]=1\n \n for key, value in tag_follow_tag.items():\n count =0 \n for key2, val in tag_follow_tag[key].items():\n count+=tag_follow_tag[key][key2]\n for key2, val in tag_follow_tag[key].items():\n tag_follow_tag[key][key2]/=count\n import pprint\n # pprint.pprint(word_tag, width =1)\n # END OF YOUR CODE \n return (tag_follow_tag, word_tag)\n\n\n\n#NEEDS TO BE FILLED!\ndef assign_POS_tags(test_words, tag_follow_tag, word_tag):\n\n '''\n This is where you write the actual code for Viterbi algorithm.\n INPUT: test_words - this is a nested list of words for the TEST set\n tag_follow_tag - the transition probabilities (bigram), filled in by YOUR code in the store_emission_and_transition_probabilities\n word_tag - the emission probabilities (bigram), filled in by YOUR code in the store_emission_and_transition_probabilities\n OUTPUT: a nested list of predicted tags corresponding to the input list test_words. This is the 'output_test_tags' list created below, and returned after your code\n ends.\n\n HINT: Keep in mind the boundary case of the starting POS tag. You will have to use the tag you created in the previous function here, to get the\n transition probabilities for the first tag of sentence...\n HINT: You need not apply sophisticated smoothing techniques for this particular assignment.\n If you cannot find a word in the test set with probabilities in the training set, simply tag it as 'NOUN'.\n So if you are unable to generate a tag for some word due to unavailibity of probabilities from the training set,\n just predict 'NOUN' for that word.\n\n '''\n \n myTags= ['VERB','NOUN','PRON', 'ADJ','ADV','ADP','CONJ','DET','NUM','PRT','.','X']\n\n\n output_test_tags = [] #list of list of predicted tags, corresponding to the list of list of words in Test set (test_words input to this function)\n\n\n # *** WRITE YOUR CODE HERE ***\n ran = len(test_words); count=0\n \n for i in range(1, ran+1):\n ls=[0]\n tempDict={}\n \n for aTag in myTags:\n try:\n x = tempDict[aTag]\n except:\n tempDict[aTag]=[]\n\n\n charas='NOUN'\n \n ls.clear()\n ran2 = len(test_words[i-1])\n for j in range(1, ran2+1):\n if j==1:\n for key, val in word_tag.items():\n fill = 0\n keyList = list(word_tag[key].keys())\n if test_words[i-1][j-1] in keyList:\n\n if key not in tag_follow_tag['UNKNOWN']:\n tempDict[key].insert(len(tempDict[key])-1, ('UNKNOWN',0))\n else: \n \n fill = tag_follow_tag['UNKNOWN'][key]\n fill*=word_tag[key][test_words[i-1][j-1]]\n tempDict[key].insert(len(tempDict[key])-1, ('UNKNOWN',fill))\n else:\n if key=='NOUN':\n fill = (1/1000000)\n tempDict[key].insert(len(tempDict[key])-1, ('UNKNOWN',fill))\n else:\n tempDict[key].insert(len(tempDict[key])-1, ('UNKNOWN',0))\n elif(j>1): \n for key1, val1 in word_tag.items():\n ma=0\n ch ='NOUN'\n for key, vall in word_tag.items():\n keyList = word_tag[key1].keys()\n if test_words[i-1][j-1] in keyList:\n if key1 in tag_follow_tag[key]:\n val=tempDict[key][j-2][1]\n val*=tag_follow_tag[key][key1]\n val*=word_tag[key1][test_words[i-1][j-1]]\n else:\n val = 0\n else:\n if key1 !='NOUN':\n val =0\n else:\n val =0.000000001\n val*=tempDict[key][j-2][1]\n val*=tag_follow_tag[key][key1]\n\n #print(val)\n if val>=ma:\n ma=val\n ch=key\n \n tempDict[key1].append((ch,ma))\n maxi=0\n\n for key, val in tempDict.items():\n if tempDict[key][len(test_words[i-1])-1][1]>=maxi:\n pos = len(test_words[i-1])-1\n maxi=tempDict[key][pos][1]\n charas = tempDict[key][pos][0]\n\n ls.insert(len(ls)-1 ,charas)\n rann = (len(test_words[i-1])-2)\n for tempy in range(rann,-1,-1):\n ls.append(charas)\n charas=tempDict[charas][tempy][0]\n\n reverseList = list(ls[::-1])\n output_test_tags.append(reverseList)\n \n \n\n # END OF YOUR CODE\n\n return output_test_tags\n\n# DO NOT CHANGE!\ndef public_test(predicted_tags):\n '''\n HELPER function: Takes in the nested list of predicted tags on test set (prodcuced by the assign_POS_tags function above)\n and computes accuracy on the public test set. Note that this accuracy is just for you to gauge the correctness of your code.\n Actual performance will be judged on the full test set by the TAs, using the output file generated when your code runs successfully.\n '''\n\n f = open('public_test_data.txt','r')\n sentences = []\n tags = []\n sentence = []\n tag = []\n for line in f:\n s = line.rstrip('\\n')\n if s == '':\n sentences.append(sentence)\n tags.append(tag)\n sentence=[]\n tag=[]\n else:\n w,t = line.split()\n sentence.append(w)\n tag.append(t)\n sentences = sentences[1:]\n tags = tags[1:]\n assert len(sentences) == len(tags)\n f.close()\n public_predictions = predicted_tags[:len(tags)]\n assert len(public_predictions)==len(tags)\n\n flattened_actual_tags = []\n flattened_pred_tags = []\n for i in range(len(tags)):\n x = tags[i]\n y = public_predictions[i]\n flattened_actual_tags+=x\n flattened_pred_tags+=y\n # print(len(flattened_actual_tags))\n # print(len(flattened_pred_tags))\n assert len(flattened_actual_tags)==len(flattened_pred_tags)\n\n correct = 0.0\n for i in range(len(flattened_pred_tags)):\n if flattened_pred_tags[i]==flattened_actual_tags[i]:\n correct+=1.0\n print('Accuracy on the Public set = '+str(correct/len(flattened_pred_tags)))\n\n\n\n# DO NOT CHANGE!\nif __name__ == \"__main__\":\n words_list_train = read_train_file()[0]\n tags_list_train = read_train_file()[1]\n\n dict2_tag_tag = store_emission_and_transition_probabilities(words_list_train,tags_list_train)[0]\n word_tag = store_emission_and_transition_probabilities(words_list_train,tags_list_train)[1]\n\n f = open('private_unlabelled_test_data.txt','r')\n\n words = []\n l=[]\n for line in f:\n w = line.rstrip('\\n')\n if w=='':\n words.append(l)\n l=[]\n else:\n l.append(w)\n f.close()\n words = words[1:]\n test_tags = assign_POS_tags(words, dict2_tag_tag, word_tag)\n assert len(words)==len(test_tags)\n\n public_test(test_tags)\n\n #create output file with all tag predictions on the full test set\n\n f = open('output.txt','w')\n for i in range(len(words)):\n sent = words[i]\n pred_tags = test_tags[i]\n for j in range(len(sent)):\n word = sent[j]\n pred_tag = pred_tags[j]\n f.write(word+' '+pred_tag)\n f.write('\\n')\n f.write('\\n')\n f.close()\n\n print('OUTPUT file has been created') \n\n\n","sub_path":"Assignment-5/Problem Statement/viterbi.py","file_name":"viterbi.py","file_ext":"py","file_size_in_byte":13169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"257561967","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef load_data():\n fh = open('./files/titanic.csv')\n df = pd.read_csv(fh)\n return df\n\ndef draw_plot(titanic):\n proportions = []\n for i in titanic.Sex.value_counts():\n proportions.append(i)\n plt.pie(proportions, labels=[\"Males\", \"Females\"], autopct='%1.1f%%', explode=(0, 0.125), shadow=True, startangle=90)\n plt.title(\"Sex Proportions\")\n plt.show()\n\ndef draw_historgram(titanic):\n fair_value = titanic.Fare.copy()\n fair_value.sort_values(inplace=True)\n fair_value.hist(bins=30)\n plt.xlabel('Fare')\n plt.ylabel('Frequency')\n plt.title('Fare Paid Histogram')\n plt.show()\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"164610514","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 6 14:15:26 2015\n\n@author: martin\n\"\"\"\nfrom Bio.Seq import Seq\nfrom Bio.Alphabet import IUPAC\n\ndef presentResultsSS(x,y,z,ldna,offset):\n final_DNA = Seq(\"\", IUPAC.unambiguous_dna)\n for a in ldna:\n final_DNA+=a\n \n xModified = final_DNA[offset:][:len(x)*3].translate()\n yModified = final_DNA[(offset+z):][:len(y)*3].translate()\n \n return (xModified, yModified, final_DNA)\n \n\n","sub_path":"src/presentResultsSS.py","file_name":"presentResultsSS.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"182671371","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n########################################################################################################################\n# Copyright © 2019-2020 Pi-Yueh Chuang and Lorena A. Barba.\n# All Rights Reserved.\n#\n# Contributors: Pi-Yueh Chuang \n#\n# Licensed under the BSD-3-Clause License (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: https://opensource.org/licenses/BSD-3-Clause\n#\n# BSD-3-Clause License:\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided\n# that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the\n# following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or\n# promote products derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n########################################################################################################################\n\n\"\"\"\nHelper functions for post-processing.\n\"\"\"\nimport os\nimport numpy\nfrom clawpack import pyclaw\n\n\ndef get_min_value(solution, field=0):\n \"\"\"\n Get the minimum value in a field in a solution.\n \"\"\"\n\n min_val = 1e38\n\n for state in solution.states:\n min_temp = state.q[field, :, :].min()\n if min_temp < min_val:\n min_val = min_temp\n\n return min_val\n\ndef get_max_value(solution, field=0):\n \"\"\"\n Get the maximum value in a field in a solution.\n \"\"\"\n\n max_val = 0.\n\n for state in solution.states:\n max_temp = state.q[field, :, :].max()\n if max_temp > max_val:\n max_val = max_temp\n\n return max_val\n\ndef get_max_AMR_level(solution):\n \"\"\"\n Get the max AMR level in a solution object.\n \"\"\"\n\n max_level = 1\n\n for state in solution.states:\n p = state.patch\n\n if p.level > max_level:\n max_level = p.level\n\n return max_level\n\ndef plot_at_axes(solution, ax, field=0, border=False,\n min_level=2, max_level=None, vmin=None, vmax=None,\n threshold=1e-4, cmap=\"viridis\"):\n \"\"\"Plot solution.\n\n Plot a field in the q array of a solution object.\n\n Args:\n solution [in]: pyClaw solution object.\n ax [inout]: matplotlib axes object.\n field [in]: target field to be plot:\n 0 - depth;\n 1 - hu conservative field;\n 2 - hv conservative field;\n 3 - eta (elevation + depth)\n border [in]: a boolean indicating whether to plot grid patch borders.\n min_levle [in]: the minimum level of AMR grid to be plotted.\n max_levle [in]: the maximum level of AMR grid to be plotted.\n vmin [in]: value of the minimum value of the colorbar.\n vmax [in]: value of the maximum value of the colorbar.\n threshold [in]: values below this threshold will be clipped off.\n cmap [in]: pyplot colorbar theme.\n\n Return:\n pyplot image object/handler, or None.\n \"\"\"\n\n if vmin is None:\n vmin = get_min_value(solution, field)\n\n if vmax is None:\n vmax = get_max_value(solution, field)\n\n for state in solution.states:\n p = state.patch\n\n if p.level < min_level:\n continue\n\n if max_level is not None and max_level < p.level:\n continue\n\n x, dx = numpy.linspace(p.lower_global[0], p.upper_global[0],\n p.num_cells_global[0]+1, retstep=True)\n y, dy = numpy.linspace(p.lower_global[1], p.upper_global[1],\n p.num_cells_global[1]+1, retstep=True)\n assert numpy.abs(dx-p.delta[0]) < 1e-6, \"{} {}\".format(dx, p.delta[0])\n assert numpy.abs(dy-p.delta[1]) < 1e-6, \"{} {}\".format(dy, p.delta[1])\n\n im = ax.pcolormesh(\n x, y, numpy.ma.masked_less(state.q[field, :, :], threshold).T,\n shading='flat', edgecolors='None',\n vmin=vmin, vmax=vmax, cmap=cmap)\n\n if border:\n ax.plot([x[0], x[-1], x[-1], x[0], x[0]],\n [y[0], y[0], y[-1], y[-1], y[0]], 'k-', lw=1)\n\n try:\n return im\n except UnboundLocalError:\n return None\n\ndef plot_topo(data, transform, res, topo_min=None, topo_max=None,\n shaded=True, colormap=\"terrain\"):\n \"\"\"Return a fig and ax object with topography.\"\"\"\n from matplotlib import colors\n from matplotlib import pyplot\n import rasterio.plot\n\n # a new figure\n fig = pyplot.figure(0, (13, 8), 90)\n\n # create an axes at 1, 3, 1\n ax_topo = fig.add_axes([0.1, 0.125, 0.65, 0.75])\n\n # light source\n ls = colors.LightSource(315, 45)\n\n # min and max\n if topo_min is None:\n topo_min = data.mean() - 2 * data.std()\n if topo_max is None:\n topo_max = data.mean() + 2 * data.std()\n\n if shaded:\n # get shaded RGBA data\n shaded = ls.shade(\n data, blend_mode=\"overlay\", vert_exag=3, dx=res[0], dy=res[1],\n vmin=topo_min, vmax=topo_max, cmap=pyplot.get_cmap(colormap))\n\n # convert from (row, column, band) to (band, row, column)\n shaded = rasterio.plot.reshape_as_raster(shaded)\n\n # show topography in cropped region\n rasterio.plot.show(shaded, ax=ax_topo, transform=transform, adjust=None)\n else:\n rasterio.plot.show(\n data[-1::-1, :], ax=ax_topo, transform=transform,\n vmin=topo_min, vmax=topo_max,\n origin=\"lower\", cmap=pyplot.get_cmap(colormap))\n\n # x, y labels\n ax_topo.set_xlabel(\"x coordinates (m)\")\n ax_topo.set_ylabel(\"y coordinates (m)\")\n\n # get x, y limit\n xlim = ax_topo.get_xlim()\n ylim = ax_topo.get_ylim()\n\n # plot colorbar in a new axes for topography\n cbarax = fig.add_axes([0.775, 0.125, 0.03, 0.75])\n im = ax_topo.imshow(\n data, cmap=colormap, vmin=topo_min, vmax=topo_max, origin='lower')\n im.remove()\n cbar = pyplot.colorbar(im, cax=cbarax, ax=ax_topo)\n cbar.set_label(\"Elevation (m)\")\n\n # reset the x, y lim\n ax_topo.set_xlim(xlim)\n ax_topo.set_ylim(ylim)\n\n return fig, ax_topo\n\ndef plot_depth(data, transform, res, solndir, fno, border=False, level=1,\n shaded=True, dry_tol=1e-5, vmin=None, vmax=None):\n \"\"\"Plot depth on topography.\"\"\"\n from matplotlib import pyplot\n\n # a new figure and topo ax\n fig, ax = plot_topo(data, transform, res, shaded=shaded)\n\n # empty solution object\n soln = pyclaw.Solution()\n\n # aux path\n auxpath = os.path.join(solndir, \"fort.a\"+\"{}\".format(fno).zfill(4))\n\n # read\n soln.read(fno, solndir, file_format=\"binary\", read_aux=os.path.isfile(auxpath))\n\n print(\"Plotting frame No. {}, T={} secs ({} mins)\".format(\n fno, soln.state.t, int(soln.state.t/60.)))\n\n # plot\n im = plot_at_axes(soln, ax, field=0, border=border,\n min_level=level, max_level=level,\n vmin=vmin, vmax=vmax,\n threshold=dry_tol)\n\n # plot colorbar in a new axes for depth\n cbarax = fig.add_axes([0.875, 0.125, 0.03, 0.75])\n if im is None:\n im = ax.pcolormesh([0, data.shape[1]], [0, data.shape[0]], [[0]])\n im.remove()\n cbar = pyplot.colorbar(im, cax=cbarax, ax=ax)\n cbar.ax.set_yticklabels([0]*len(cbar.ax.get_yticks()))\n else:\n cbar = pyplot.colorbar(im, cax=cbarax, ax=ax)\n cbar.set_label(\"Depth (m)\")\n\n # figure title\n fig.suptitle(\"Topography and depth near rupture point, \"\n \"T = {} (mins)\".format(int(soln.state.t/60.)),\n x=0.5, y=0.9, fontsize=16,\n horizontalalignment=\"center\",\n verticalalignment=\"bottom\")\n\n return fig, ax\n\ndef plot_soln_topo(topodata, extent, solndir, fno, color_lims=[None, None],\n border=False, level=1):\n \"\"\"Plot the topology from solution (instead of from topo file)\"\"\"\n from matplotlib import pyplot\n import rasterio.plot\n\n # empty solution object\n soln = pyclaw.Solution()\n\n # path\n auxpath = os.path.join(solndir, \"fort.a\"+\"{}\".format(fno).zfill(4))\n\n # read\n soln.read(fno, solndir, file_format=\"binary\", read_aux=os.path.isfile(auxpath))\n\n print(\"Plotting frame No. {}, T={} secs ({} mins)\".format(\n fno, soln.state.t, int(soln.state.t/60.)))\n\n # colormap min & max\n if color_lims[0] is None:\n color_lims[0] = topodata.mean() - 2 * topodata.std()\n\n if color_lims[1] is None:\n color_lims[1] = topodata.mean() + 2 * topodata.std()\n\n # a new figure\n fig = pyplot.figure(0, (11, 8), 90)\n\n # figure title\n fig.suptitle(\"Elevation data in AMR grid patches, \"\n \"T = {} (mins)\".format(int(soln.state.t/60.)),\n x=0.5, y=0.9, fontsize=16,\n horizontalalignment=\"center\",\n verticalalignment=\"bottom\")\n\n # create an axes at 1, 3, 1\n ax = fig.add_axes([0.1, 0.125, 0.75, 0.75])\n\n # coordinate limit\n ax.set_xlim(extent[0], extent[1])\n ax.set_ylim(extent[2], extent[3])\n\n # plot colorbar in a new axes for elevation\n cbarax = fig.add_axes([0.875, 0.125, 0.03, 0.75])\n im = ax.imshow(\n topodata, extent=extent, cmap=\"terrain\",\n vmin=color_lims[0], vmax=color_lims[1], origin='lower')\n im.remove()\n cbar = pyplot.colorbar(im, cax=cbarax, ax=ax)\n cbar.set_label(\"Elevation (m)\")\n\n # plot each patch on level 1\n for state in soln.states:\n plot_single_patch_topo(\n ax, state, 1, os.path.isfile(auxpath), color_lims,\n (level == 1 and border))\n\n # if the target level is one, exit the function now\n if level == 1:\n return fig, ax\n\n # plot each patch on target level\n for state in soln.states:\n plot_single_patch_topo(\n ax, state, level, os.path.isfile(auxpath), color_lims, border)\n\n return fig, ax\n\ndef plot_single_patch_topo(ax, state, level, aux, color_lims, border):\n \"\"\"Plot elevation data of a single AMR grid patch.\"\"\"\n import rasterio\n\n p = state.patch\n\n if p.level != level:\n return\n\n trans = rasterio.transform.from_origin(\n p.lower_global[0], p.upper_global[1], p.delta[0], p.delta[1])\n\n if aux:\n data = state.aux[0, :, :].T\n else:\n data = state.q[3, :, :].T - state.q[0, :, :].T\n\n rasterio.plot.show(\n data, ax=ax, transform=trans, adjust=None,\n vmin=color_lims[0], vmax=color_lims[1],\n origin=\"lower\", cmap=\"terrain\")\n\n if border:\n ax.plot(\n [p.lower_global[0], p.upper_global[0], p.upper_global[0],\n p.lower_global[0], p.lower_global[0]],\n [p.lower_global[1], p.lower_global[1], p.upper_global[1],\n p.upper_global[1], p.lower_global[1]],\n 'k-', lw=1)\n\n return ax\n\ndef get_bounding_box(solndir, bg, ed, level):\n \"\"\"\n Get the bounding box of the result at a specific level.\n\n Return:\n [xleft, xright, ybottom, ytop]\n \"\"\"\n\n xleft = None\n xright = None\n ybottom = None\n ytop = None\n\n for fno in range(bg, ed):\n\n # aux path\n auxpath = os.path.join(solndir, \"fort.a\"+\"{}\".format(fno).zfill(4))\n\n # solution\n soln = pyclaw.Solution()\n soln.read(fno, solndir, file_format=\"binary\", read_aux=os.path.isfile(auxpath))\n\n # search through AMR grid patched in this solution\n for state in soln.states:\n p = state.patch\n\n if p.level != level:\n continue\n\n if xleft is None or xleft > p.lower_global[0]:\n xleft = p.lower_global[0]\n\n if ybottom is None or ybottom > p.lower_global[1]:\n ybottom = p.lower_global[1]\n\n if xright is None or xright < p.upper_global[0]:\n xright = p.upper_global[0]\n\n if ytop is None or ytop < p.upper_global[1]:\n ytop = p.upper_global[1]\n\n # finally, return\n return [xleft, xright, ybottom, ytop]\n","sub_path":"utilities/pphelper.py","file_name":"pphelper.py","file_ext":"py","file_size_in_byte":13128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"608094190","text":"# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.\n# Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer.\n# Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd.\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\" BASISo\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 valve_of\n\nfrom ryu.lib import mac\nfrom ryu.ofproto import ofproto_v1_3 as ofp\n\n\nclass ValveFloodManager(object):\n\n def __init__(self, flood_table, flood_priority,\n valve_in_match, valve_flowmod):\n self.flood_table = flood_table\n self.flood_priority = flood_priority\n self.valve_in_match = valve_in_match\n self.valve_flowmod = valve_flowmod\n\n def _build_flood_rule_actions(self, vlan, exclude_unicast, exclude_ports=[]):\n flood_acts = []\n tagged_ports = vlan.tagged_flood_ports(exclude_unicast)\n untagged_ports = vlan.untagged_flood_ports(exclude_unicast)\n for port in tagged_ports:\n if port not in exclude_ports:\n flood_acts.append(valve_of.output_port(port.number))\n if untagged_ports:\n flood_acts.append(valve_of.pop_vlan())\n for port in untagged_ports:\n if port not in exclude_ports:\n flood_acts.append(valve_of.output_port(port.number))\n return flood_acts\n\n def build_flood_rules(self, vlan, modify=False):\n \"\"\"Add flows to flood packets to unknown destinations on a VLAN.\"\"\"\n # TODO: not all vendors implement groups well.\n # That means we need flood rules for each input port, outputting\n # to all ports except the input port. When all vendors implement\n # groups correctly we can use them.\n command = ofp.OFPFC_ADD\n if modify:\n command = ofp.OFPFC_MODIFY_STRICT\n flood_priority = self.flood_priority\n flood_eth_dst_matches = []\n if vlan.unicast_flood:\n flood_eth_dst_matches.extend([(None, None)])\n flood_eth_dst_matches.extend([\n ('01:80:C2:00:00:00', 'ff:ff:ff:00:00:00'), # 802.x\n ('01:00:5E:00:00:00', 'ff:ff:ff:00:00:00'), # IPv4 multicast\n ('33:33:00:00:00:00', 'ff:ff:00:00:00:00'), # IPv6 multicast\n (mac.BROADCAST_STR, None), # flood on ethernet broadcasts\n ])\n ofmsgs = []\n vlan_all_ports = vlan.flood_ports(vlan.get_ports(), False)\n mirrored_ports = vlan.mirrored_ports()\n for eth_dst, eth_dst_mask in flood_eth_dst_matches:\n for port in vlan_all_ports:\n if eth_dst is None:\n flood_acts = self._build_flood_rule_actions(\n vlan, False, exclude_ports=[port])\n else:\n flood_acts = self._build_flood_rule_actions(\n vlan, True, exclude_ports=[port])\n ofmsgs.append(self.valve_flowmod(\n self.flood_table,\n match=self.valve_in_match(\n self.flood_table, in_port=port.number, vlan=vlan,\n eth_dst=eth_dst, eth_dst_mask=eth_dst_mask),\n command=command,\n inst=[valve_of.apply_actions(flood_acts)],\n priority=flood_priority))\n flood_priority += 1\n for port in mirrored_ports:\n if eth_dst is None:\n flood_acts = self._build_flood_rule_actions(vlan, False)\n else:\n flood_acts = self._build_flood_rule_actions(vlan, True)\n mirror_acts = [\n valve_of.output_port(port.mirror)] + flood_acts\n ofmsgs.append(self.valve_flowmod(\n self.flood_table,\n match=self.valve_in_match(\n self.flood_table,\n vlan=vlan,\n in_port=port.number,\n eth_dst=eth_dst,\n eth_dst_mask=eth_dst_mask),\n command=command,\n inst=[valve_of.apply_actions(mirror_acts)],\n priority=flood_priority))\n flood_priority += 1\n return ofmsgs\n","sub_path":"src/ryu_faucet/org/onfsdn/faucet/valve_flood.py","file_name":"valve_flood.py","file_ext":"py","file_size_in_byte":4667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"429377097","text":"\"\"\"\nConsulate: A client library for Consul\n\n\"\"\"\n__version__ = '0.4.0'\n\n\nimport logging\ntry:\n from logging import NullHandler\nexcept ImportError:\n class NullHandler(logging.Handler):\n \"\"\"Python 2.6 does not have a NullHandler\"\"\"\n def emit(self, record):\n \"\"\"Emit a record\n :param record record: The record to emit\n \"\"\"\n pass\n\nlogging.getLogger('consulate').addHandler(NullHandler())\n\nfrom consulate import adapters\nfrom consulate import api\n\nDEFAULT_HOST = 'localhost'\nDEFAULT_PORT = 8500\nSCHEME = 'http'\nVERSION = 'v1'\n\n\nclass Consul(object):\n \"\"\"Access the Consul HTTP API via Python\n\n :param str host: The host name to connect to (Default: localhost)\n :param int port: The port to connect on (Default: 8500)\n :param str datacenter: Specify a specific data center\n :param str token: Specify a ACL token to use\n\n \"\"\"\n def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT,\n datacenter=None, token=None):\n \"\"\"Create a new instance of the Consul class\"\"\"\n base_uri = self._base_uri(host, port)\n self._adapter = adapters.Request()\n self._acl = api.ACL(base_uri, self._adapter, datacenter, token)\n self._agent = api.Agent(base_uri, self._adapter, datacenter, token)\n self._catalog = api.Catalog(base_uri, self._adapter, datacenter, token)\n self._event = api.Event(base_uri, self._adapter, datacenter, token)\n self._health = api.Health(base_uri, self._adapter, datacenter, token)\n self._kv = api.KV(base_uri, self._adapter, datacenter, token)\n self._session = api.Session(base_uri, self._adapter, datacenter, token)\n self._status = api.Status(base_uri, self._adapter, datacenter, token)\n\n @property\n def acl(self):\n \"\"\"Access the Consul\n `ACL `_ API\n\n :rtype: :py:class:`consulate.api.acl.ACL`\n\n \"\"\"\n return self._acl\n\n @property\n def agent(self):\n \"\"\"Access the Consul\n `Agent `_ API\n\n :rtype: :py:class:`consulate.api.agent.Agent`\n\n \"\"\"\n return self._agent\n\n @property\n def catalog(self):\n \"\"\"Access the Consul\n `Catalog `_ API\n\n :rtype: :py:class:`consulate.api.catalog.Catalog`\n\n \"\"\"\n return self._catalog\n\n @property\n def event(self):\n \"\"\"Access the Consul\n `Events `_ API\n\n :rtype: :py:class:`consulate.api.event.Event`\n\n \"\"\"\n return self._event\n\n @property\n def health(self):\n \"\"\"Access the Consul\n `Health `_ API\n\n :rtype: :py:class:`consulate.api.health.Health`\n\n \"\"\"\n return self._health\n\n @property\n def kv(self):\n \"\"\"Access the Consul\n `KV `_ API\n\n :rtype: :py:class:`consulate.api.kv.KV`\n\n \"\"\"\n return self._kv\n\n @property\n def session(self):\n \"\"\"Access the Consul\n `Session `_ API\n\n :rtype: :py:class:`consulate.api.session.Session`\n\n \"\"\"\n return self._session\n\n @property\n def status(self):\n \"\"\"Access the Consul\n `Status `_ API\n\n :rtype: :py:class:`consulate.api.status.Status`\n\n \"\"\"\n return self._status\n\n @staticmethod\n def _base_uri(host, port):\n \"\"\"Return the base URI to use for API requests\n\n :param str host: The host name to connect to (Default: localhost)\n :param int port: The port to connect on (Default: 8500)\n :rtype: str\n\n \"\"\"\n return '{0}://{1}:{2}/{3}'.format(SCHEME, host, port, VERSION)\n\n\n# Backwards compatibility with 0.3.0\nSession = Consul\n","sub_path":"consulate/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"621793886","text":"from Model.countryStatistics import countryStatistics\nfrom Model.userCountryStatistics import userCountryStatistics\nfrom Controller.countryStatisticsController import countryStatisticsController\nfrom Service.ipDatabase import geoipDatabase\nfrom Logger import log\nimport ipaddress\n\nclass ipToCountry:\n logger = log.get_logger(\"ipToCountry\")\n\n @classmethod\n def mapIpToCountry(self):\n # handler for ip databases\n ipDatabaseHandler = geoipDatabase()\n ipData = countryStatisticsController.getDataNotMapped()\n countryStatsList = []\n usercountryStatsList = []\n mappedItems = 0 \n for item in ipData:\n # get network address\n ipaddr = ipaddress.ip_network(item.ip).network_address\n # get country code/ name\n countryData = ipDatabaseHandler.getCountryFromIp(str(ipaddr), item.ipVersion)\n if(countryData[0] != None):\n mappedItems +=1\n else:\n countryData[0] = 'UN'\n countryData[1] = 'Unknown'\n self.logger.warning(\"ip {0} not found at database\".format(ipaddr))\n\n countryStatisticsItem = countryStatistics(None, item.accessed, item.sourceIdp, item.service, countryData[0], countryData[1], 1)\n countryStatsList.append(countryStatisticsItem)\n usercountryStatisticsItem = userCountryStatistics(None, item.accessed, item.userid, countryData[0], countryData[1], 1)\n usercountryStatsList.append(usercountryStatisticsItem)\n \n # save data to tables if any\n if countryStatsList:\n countryStatistics.saveAll(countryStatsList)\n userCountryStatistics.saveAll(usercountryStatsList)\n self.logger.info(\"{0} ips mapped to countries\".format(mappedItems))\n else:\n self.logger.info(\"No new data found\")\n \n\n#run script \nipToCountry.mapIpToCountry()\n \n","sub_path":"ipToCountry.py","file_name":"ipToCountry.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"203268108","text":"dominant_values = {\"A\": 11, \"K\": 4, \"Q\": 3,\n \"J\": 20, \"T\": 10, \"9\": 14, \"8\": 0, \"7\": 0}\nnondom_values = {\"A\": 11, \"K\": 4, \"Q\": 3,\n \"J\": 2, \"T\": 10, \"9\": 0, \"8\": 0, \"7\": 0}\nscore = 0\n\nn, b = input().split()\nfor i in range(int(n) * 4):\n card = input()\n if card[1] == b:\n score += dominant_values[card[0]]\n else:\n score += nondom_values[card[0]]\n\nprint(score)\n","sub_path":"solutions/bela.py","file_name":"bela.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"151574534","text":"from selenium.webdriver.common.keys import Keys\nfrom locators.main_page_locators import MainPageLocators\nfrom selenium.webdriver.support import expected_conditions\n\n\nclass MainPage:\n def __init__(self, driver, wait):\n self.driver = driver\n self.wait = wait\n self.driver.get(\"http://www.python.org\")\n self.title = self.driver.title\n self.locators = MainPageLocators()\n\n def search_without_locator_deps(self, search_string):\n elem = self.driver.find_element_by_name(\"q\")\n elem.clear()\n elem.send_keys(search_string)\n elem.send_keys(Keys.RETURN)\n\n def search_without_waits(self, search_string):\n elem = self.driver.find_element(*self.locators.SEARCH_INPUT)\n elem.clear()\n elem.send_keys(search_string)\n elem.send_keys(Keys.RETURN)\n\n def search(self, search_string):\n # elem = self.driver.find_element(*self.locators.SEARCH_INPUT)\n elem = self.wait.until(expected_conditions.presence_of_element_located(self.locators.SEARCH_INPUT))\n elem.clear()\n elem.send_keys(search_string)\n elem.send_keys(Keys.RETURN)\n\n def click_donate_button(self):\n element = self.wait.until(expected_conditions.presence_of_element_located(self.locators.DONATE_BUTTON))\n element.click()","sub_path":"pages/main_page.py","file_name":"main_page.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"158655767","text":"the_num = 600851475143\r\n\r\n\r\ndef solution1(n):\r\n i = 1\r\n while i < n:\r\n if n % i is 0:\r\n n //= i\r\n i += 2\r\n\r\n return i\r\n\r\n\r\ndef solution(n):\r\n i = int(n**0.5)\r\n for j in range(i, 2, -1):\r\n if n % j is 0 and is_prime(j):\r\n return j\r\n\r\n\r\ndef is_prime(n):\r\n for i in range(2, int(n**0.5)+1):\r\n if n % i is 0:\r\n return False\r\n return True\r\n\r\n\r\n# print(is_prime(6857))\r\nprint(solution(the_num))\r\nprint(is_prime(775121))\r\n","sub_path":"PE/p3_sol.py","file_name":"p3_sol.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"107999921","text":"#!/usr/bin/env python\n\nimport assignment1 as a1\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport designmatrix as dm\n\n(countries, features, values) = a1.load_unicef_data()\n\n## Select first column as the values\ntargets = values[:,1]\n## Select rest of the columns as the features\nx = values[:,7:]\nx = a1.normalize_data(x)\n\n## Cut off value for the train set\nN_TRAIN = 100;\n\n## Training Features (100x33 matrix)\n## Testing Features (95x33 matrix)\nx_train = x[0:N_TRAIN,:]\nx_test = x[N_TRAIN:,:]\n\n## Training values (Nx1 matrix) (100x1 matrix)\n## Testing values (Nx1 matrix) (95x1 mtrix)\nt_train = targets[0:N_TRAIN]\nt_test = targets[N_TRAIN:]\n\n## Polynomial Model Construction Limit\npDegree = 6\n\n## To store Root-Mean-Square error, created vector of dimension M, one for each polynomial error.\ntrainError = {}\ntestError = {}\n\n## Python range function doesn't include last specified number. Running loop from degree 1 to 6.\nfor i in range(1,pDegree+1):\n\ttrainMatrix = dm.calculateDesignMatrix(x_train,i,categ=\"Poly\")\n\ttestMatrix = dm.calculateDesignMatrix(x_test,i,categ=\"Poly\")\n\n\t## weights = pinv(trainMatrix'*trainMatrix)*trainMatrix'*targetValue;\n\tweights = np.linalg.pinv(trainMatrix)*t_train\n\n\ttrainError[i] = math.sqrt(np.sum(np.square(np.dot(trainMatrix,weights) - t_train))/np.shape(t_train)[0])\n\ttestError[i] = math.sqrt(np.sum(np.square(np.dot(testMatrix,weights) - t_test))/np.shape(t_test)[0])\n\n# Produce a plot of results.\nplt.plot(trainError.keys(), trainError.values())\nplt.plot(testError.keys(), testError.values())\nplt.ylabel('RMS')\nplt.legend(['Train error','Test error'])\nplt.title('Fit with polynomials with Normalized Data')\nplt.xlabel('Polynomial degree')\nplt.show()","sub_path":"normalized.py","file_name":"normalized.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"324000188","text":"# coding by 刘云飞\n# email: liuyunfei.1314@163.com\n# date: 2018-4-17\n\nimport cv2\nimport numpy as np\n\n# 读取名称为 p6.png的图片\nimg = cv2.imread(\"d:\\\\1.jpg\",1)\n\n# 高斯模糊\nblur = cv2.GaussianBlur(img,(3,3),0)\n\n# Canny提取边缘\nprocessed = cv2.Canny(blur,10,20)\n\n# 显示原图和处理后的图像\ncv2.imshow(\"org\",img)\ncv2.imshow(\"processed\",processed)\n\ncv2.waitKey(0)\n","sub_path":"python/opencv/cany.py","file_name":"cany.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"189166050","text":"\"\"\"twocaptcha.py - Synchronous Module for interacting\nwit the 2Captcha API.\n\"\"\"\nimport time\nimport json\nfrom requests.api import get, post\n\nimport solvecaptcha.errors as errors\n\n\n# Typing\nApiKey = str\nBase64Str = str\n\n# Constants\nBASE = \"https://2captcha.com\"\nSOFT_ID = \"2621\"\n\n\nclass TwoCaptchaBase:\n key = None\n\n def _in(self, method: str = None, **kwargs):\n params = {\"key\": self.key, \"method\": method, \"soft_id\": SOFT_ID}\n if not method:\n params.pop(\"method\")\n\n if kwargs:\n params = {**params, **kwargs}\n\n with post(f\"{BASE}/in.php\", data=params) as r:\n if \"ERROR\" in r.text:\n raise errors.TwoCaptchaInputError(r.text)\n return r.text.replace(\"OK|\", \"\")\n\n def _res(self, action: str, **kwargs):\n params = {\"key\": self.key, \"action\": action}\n if kwargs:\n params = {**params, **kwargs}\n\n with get(f\"{BASE}/res.php\", params=params) as r:\n if \"ERROR\" in r.text:\n raise errors.TwoCaptchaResponseError(r.text)\n return r.text.replace(\"OK|\", \"\")\n\n\nclass TwoCaptchaResponse(TwoCaptchaBase):\n __slots__ = (\"key\", \"request_id\", \"timeout\", \"solution\")\n\n def __init__(self, key: ApiKey, request_id: str, timeout: int = 300):\n super().__init__()\n\n self.key = key\n self.request_id = request_id\n self.timeout = timeout\n\n self.solution = None\n\n def get_solution(self):\n for _ in range(self.timeout // 5):\n r = self._res(\"get\", id=self.request_id)\n if \"CAPCHA_NOT_READY\" in r:\n time.sleep(5)\n continue\n self.solution = r\n return self\n\n raise errors.CaptchaTimeoutError(\"Did not recieve captcha solution in set time\")\n\n def report_good(self):\n self._res(\"reportgood\", id=self.request_id)\n\n def report_bad(self):\n self._res(\"reportbad\", id=self.request_id)\n\n def __repr__(self):\n return self.solution\n\n\nclass TwoCaptcha(TwoCaptchaBase):\n __slots__ = (\"key\", \"timeout\")\n\n def __init__(self, key: ApiKey, timeout: int = 300):\n \"\"\"\n Parameters\n ----------\n key : ApiKey\n 2Captcha api key\n timeout : int, optional\n Timeout for recieving Captcha solution, by default 300\n \"\"\"\n super().__init__()\n\n self.key = key\n self.timeout = timeout\n\n\n def captcha(self, encoded_string: Base64Str, textinstructions: str, wait: bool = True, **kwargs) -> TwoCaptchaResponse:\n \"\"\"Solve a regular captcha\n\n Parameters\n ----------\n encoded_string : Base64Str\n Base64 encoded Captcha image\n textinstructions : str\n Text instructions to be given to the worker\n\n Attributes\n ----------\n phrase : int\n Specifies if the captcha contain two or more words\n 0 - One word\n 1 - Two or more words\n regsense : int\n Specifies if the captcha case sensitive\n 0 - captcha in not case sensitive\n 1 - captcha is case sensitive\n numeric : int\n Specifies what characters the captcha contains\n 0 - not specified\n 1 - captcha contains only numbers\n 2 - captcha contains only letters\n 3 - captcha contains only numbers OR only letters\n 4 - captcha contains both numbers AND letters\n Full list of Attributes:\n https://2captcha.com/2captcha-api#solving_normal_captcha\n Returns\n -------\n TwoCaptchaResponse\n \"\"\"\n id = self._in(\"base64\", body=encoded_string, textinstructions=textinstructions, **kwargs)\n\n response = TwoCaptchaResponse(self.key, id, self.timeout)\n\n if wait:\n time.sleep(5)\n return response.get_solution()\n\n return response\n\n def textcaptcha(self, text: str, lang: str = \"en\", language: int = 0, wait: bool = True, **kwargs) -> TwoCaptchaResponse:\n \"\"\"Solve a Text Captcha.\n\n https://2captcha.com/2captcha-api#solving_text_captcha\n > Text Captcha is a type of captcha that is represented as text and doesn't contain images.\n > Usually you have to answer a question to pass the verification.\n\n Parameters\n ----------\n text : str\n The text captchas contents, e.g. \"What day is today?\"\n lang : str, optional\n Language code, availabe language codes: 2captcha.com/2captcha-api#language, by default \"en\"\n language : int, optional\n Alphabet in use, 0 - not specified,\n 1 - Cyrillic (Russian) captcha,\n 2 - Latin captchai\n by default 0\n time_limit : int, optional\n Time limit until response is recieved, in seconds, by default 300\n\n Returns\n -------\n TwoCaptchaResponse\n \"\"\"\n id = self._in(textcaptcha=text, language=language, **kwargs)\n\n response = TwoCaptchaResponse(self.key, id, self.timeout)\n\n if wait:\n time.sleep(5)\n return response.get_solution()\n\n return response\n\n def recaptcha_v2(self, googlekey: str, pageurl: str, wait: bool = True, **kwargs) -> TwoCaptchaResponse:\n \"\"\"Solve ReCaptcha V2\n\n Parameters\n ----------\n googlekey : str\n Value of k or data-sitekey parameter, example: 6LfP0CITAAAAAHq9FOgCo7v_fb0-pmmH9VW3ziFs\n pageurl : str\n Full URL of the page where the ReCaptcha is present\n time_limit : int, optional\n Time limit until response is recieved, in seconds, by default 300\n\n Returns\n -------\n TwoCaptchaResponse\n \"\"\"\n id = self._in(\"userrecaptcha\", googlekey=googlekey, pageurl=pageurl, **kwargs)\n\n response = TwoCaptchaResponse(self.key, id, self.timeout)\n\n if wait:\n time.sleep(20)\n return response.get_solution()\n\n return response\n\n def hcaptcha(self, sitekey: str, pageurl: str, wait: bool = True, **kwargs) -> TwoCaptchaResponse:\n id = self._in(\"hcaptcha\", sitekey=sitekey, pageurl=pageurl, **kwargs)\n\n response = TwoCaptchaResponse(self.key, id, self.timeout)\n\n if wait:\n time.sleep(20)\n return response.get_solution()\n\n return response\n\n def capy(self, captchakey: str, pageurl: str, apiserver: str, wait: bool = True, **kwargs) -> TwoCaptchaResponse:\n id = self._in(\"capy\", captchakey=captchakey, pageurl=pageurl, apiserver=apiserver, **kwargs)\n\n response = TwoCaptchaResponse(self.key, id, self.timeout)\n\n if wait:\n time.sleep(20)\n return response.get_solution()\n\n return response\n\n def _get_balance(self) -> float:\n r = self._res(\"getbalance\")\n return float(r)\n\n @property\n def balance(self) -> float:\n return self._get_balance()\n\n def __repr__(self):\n return f\"\"\n","sub_path":"solvecaptcha/twocaptcha.py","file_name":"twocaptcha.py","file_ext":"py","file_size_in_byte":7115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"276597028","text":"import asyncio\n\nimport lcddriver\nimport time\nimport RPi.GPIO as GPIO\n#import schedule\n\ndisplay = lcddriver.lcd()\nredLed = 4\nyellowLed = 17\n\nlcd_display_time = 60\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(redLed, GPIO.OUT)\nGPIO.setup(yellowLed, GPIO.OUT)\n\nmed1_line1 = \"Ibuprofen 200mg\"\nmed1_line2 = \"2 tablet Bin A\"\n\nasync def lightFlash():\n while True:\n GPIO.output(redLed, True)\n await asyncio.sleep(1)\n GPIO.output(redLed, False)\n await asyncio.sleep(1)\n\nasync def start():\n try:\n asyncio.create_task(lightFlash())\n display.lcd_backlight(0)\n # Reminder 16 character long sentences!\n GPIO.output(redLed, True)\n display.lcd_backlight(0)\n print(\"Writing to display\")\n display.lcd_display_string(med1_line1, 1)\n display.lcd_display_string(med1_line2, 2)\n await asyncio.sleep(lcd_display_time)\n\n GPIO.output(redLed, False)\n display.lcd_clear()\n display.lcd_backlight(0)\n\n except KeyboardInterrupt:\n print(\"Cleaning up!\")\n display.lcd_clear()\n display.lcd_backlight(0)\n GPIO.cleanup() \n \nasyncio.run(start())\n","sub_path":"med_reminder_main.py","file_name":"med_reminder_main.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"436196911","text":"#!/usr/bin/env python\nimport pygame\nimport os\n\nos.putenv('SDL_FBDEV', '/dev/fb1')\npygame.init()\npygame.mouse.set_visible(False)\nlcd = pygame.display.set_mode((320, 240))\nlcd.fill((0,0,0))\npygame.display.update()\n","sub_path":"utils/clean-tft.py","file_name":"clean-tft.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"97417529","text":"#### last layer is not sparse\n\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport time\n\nimport numpy as np\nimport theano\nimport theano.tensor as T\nimport lab\nimport lasagne\n\n\n'''\nprune 90% connections\n'''\n# Permute images\ndef permute_mnist(window_size, X_train, y_train, X_val, y_val, X_test, y_test):\n\tnum_permute = window_size*window_size\n\tshift = (X_train.shape[1] - num_permute)/2\n\tperm_inds = range(num_permute)\n\tnp.random.shuffle(perm_inds)\n\tperm_inds = np.array(perm_inds) + shift\n\t# import ipdb; ipdb.set_trace()\n\t\n\tdef permute_one(inds, X):\n\t\tX_new = np.array([X[:,c] for c in inds])\n\t\treturn X_new\n\n\tperm_inds = np.concatenate([np.arange(shift), perm_inds, np.arange(shift)+num_permute+shift])\n\tperm_inds = perm_inds.tolist()\n\n\n\tX_train_new = permute_one(perm_inds, X_train)\n\tX_val_new = permute_one(perm_inds, X_val)\n\tX_test_new = permute_one(perm_inds, X_test)\n\n\treturn X_train_new, y_train, X_val_new, y_val, X_test_new, y_test\n\n\n# Download and prepare the MNIST dataset\ndef load_dataset():\n\t# We first define a download function, supporting both Python 2 and 3.\n\tif sys.version_info[0] == 2:\n\t\tfrom urllib import urlretrieve\n\telse:\n\t\tfrom urllib.request import urlretrieve\n\n\tdef download(filename, source='http://yann.lecun.com/exdb/mnist/'):\n\t\tprint(\"Downloading %s\" % filename)\n\t\turlretrieve(source + filename, filename)\n\n\t# We then define functions for loading MNIST images and labels.\n\t# For convenience, they also download the requested files if needed.\n\timport gzip\n\n\tdef load_mnist_images(filename):\n\t\tif not os.path.exists(filename):\n\t\t\tdownload(filename)\n\t\twith gzip.open(filename, 'rb') as f:\n\t\t\tdata = np.frombuffer(f.read(), np.uint8, offset=16)\n\t\tdata = data.reshape(-1,784)\n\t\t# import ipdb; ipdb.set_trace()\n\t\t# data = data.reshape(-1, 1, 28, 28)\n\t\treturn data / np.float32(256)\n\n\tdef load_mnist_labels(filename):\n\t\tif not os.path.exists(filename):\n\t\t\tdownload(filename)\n\t\t# Read the labels in Yann LeCun's binary format.\n\t\twith gzip.open(filename, 'rb') as f:\n\t\t\tdata = np.frombuffer(f.read(), np.uint8, offset=8)\n\t\t# The labels are vectors of integers now, that's exactly what we want.\n\t\treturn data\n\n\t# We can now download and read the training and test set images and labels.\n\tX_train = load_mnist_images('train-images-idx3-ubyte.gz')\n\ty_train = load_mnist_labels('train-labels-idx1-ubyte.gz')\n\tX_test = load_mnist_images('t10k-images-idx3-ubyte.gz')\n\ty_test = load_mnist_labels('t10k-labels-idx1-ubyte.gz')\n\n\t# We reserve the last 10000 training examples for validation.\n\tX_train, X_val = X_train[:-10000], X_train[-10000:]\n\ty_train, y_val = y_train[:-10000], y_train[-10000:]\n\n\t# We just return all the arrays in order, as expected in main().\n\t# (It doesn't matter how we do this as long as we can read them again.)\n\treturn X_train, y_train, X_val, y_val, X_test, y_test\n\n\n# Build Network\ndef build_custom_mlp(input_var=None, depth=2, width=800, drop_input=.2,\n\t\t\t\t\t drop_hidden=.5):\n\n\tnetwork = lasagne.layers.InputLayer(shape=(None, 784),\n\t\t\t\t\t\t\t\t\t\tinput_var=input_var)\n\tif drop_input:\n\t\tnetwork = lasagne.layers.dropout(network, p=drop_input)\n\t# Hidden layers and dropout:\n\tnonlin = lasagne.nonlinearities.rectify\n\tfor _ in range(depth):\n\t\tnetwork = lasagne.layers.DenseLayer(\n\t\t\t\tnetwork, width, nonlinearity=nonlin)\n\t\tif drop_hidden:\n\t\t\tnetwork = lasagne.layers.dropout(network, p=drop_hidden)\n\t# Output layer:\n\tsoftmax = lasagne.nonlinearities.softmax\n\tnetwork = lasagne.layers.DenseLayer(network, 10, nonlinearity=softmax)\n\treturn network\n\n\n# Build Sparse Network\ndef build_sparse_mlp(mask, input_var=None, depth=2, width=800, drop_input=.2,\n\t\t\t\t\t drop_hidden=.5):\n\n\tnetwork = lasagne.layers.InputLayer(shape=(None, 784),\n\t\t\t\t\t\t\t\t\t\tinput_var=input_var)\n\tif drop_input:\n\t\tnetwork = lasagne.layers.dropout(network, p=drop_input)\n\t# Hidden layers and dropout:\n\tnonlin = lasagne.nonlinearities.rectify\n\ti=0\n\tfor _ in range(depth):\n\t\tnetwork = lab.DenseLayer(mask[i+i], network, width, nonlinearity=nonlin)\n\t\tif drop_hidden:\n\t\t\tnetwork = lasagne.layers.dropout(network, p=drop_hidden)\n\t\ti = i +1\n\t# Output layer:\n\tsoftmax = lasagne.nonlinearities.softmax\n\tnetwork = lab.DenseLayer(mask[i+i], network, 10, nonlinearity=softmax)\n\treturn network\n\n\n# Batch iterator\ndef iterate_minibatches(inputs, targets, batchsize, shuffle=True):\n\tassert len(inputs) == len(targets)\n\tif shuffle:\n\t\tindices = np.arange(len(inputs))\n\t\tnp.random.shuffle(indices)\n\tfor start_idx in range(0, len(inputs) - batchsize + 1, batchsize):\n\t\tif shuffle:\n\t\t\texcerpt = indices[start_idx:start_idx + batchsize]\n\t\telse:\n\t\t\texcerpt = slice(start_idx, start_idx + batchsize)\n\t\tyield inputs[excerpt], targets[excerpt]\n\n\n# Main program\ndef main(prune_fraction, model='fc', num_epochs=500):\n\t# Load the dataset\n\tprint(\"Loading data...\")\n\tX_train, y_train, X_val, y_val, X_test, y_test = load_dataset()\n\n\t# Prepare Theano variables for inputs and targets\n\t# input_var = T.tensor4('inputs')\n\tinput_var = T.fmatrix('inputs')\n\ttarget_var = T.ivector('targets')\n\n\t# Create neural network model (depending on first command line parameter)\n\n\tdepth, width, drop_in, drop_hid = model.split(':', 1)[1].split(',')\n\n\twith np.load('model/model_{0}_{1}.npz'.format(depth, width)) as f:\n\t\tparam_values = [f['arr_%d' % i] for i in range(len(f.files))]\n\n\t# thresholding the weights\n\tprune_fraction = prune_fraction\n\tthres = []\n\tmask = []\n\tfor i in range(len(param_values)):\n\t\tdata_current = np.abs(param_values[i])\n\t\tif len(param_values[i].shape)>1 : \n\t\t\tvec_data = data_current.flatten()\n\t\t\ta = int(prune_fraction*data_current.size)\n\t\t\tthres_current = np.sort(vec_data)[a]\n\t\telse:\n\t\t\tthres_current = np.float32(0.0) ### all the b and the last layer params are retrained\n\t\t# import ipd; ipdb.set_trace()\n\t\tmask_current = (data_current>thres_current).astype(int)\n\t\tparam_values[i] *= mask_current\n\n\t\tthres.append(thres_current)\n\t\tmask.append(mask_current)\n\n\tprint(thres)\n\n\t# rebuild sparse model\n\tnetwork_s = build_sparse_mlp(mask, input_var, int(depth), int(width),\n\t\t\t\t\t\t\t\t float(drop_in), float(drop_hid))\n\n\t# Create a loss expression for training\n\tprediction = lasagne.layers.get_output(network_s)\n\tloss = lasagne.objectives.categorical_crossentropy(prediction, target_var)\n\tloss = loss.mean()\n\n\t# Create update expressions for training\n\tparams = lasagne.layers.get_all_params(network_s, trainable=True)\n\tW_grads = lab.compute_grads1(loss, network_s, mask)\n\tupdates = lasagne.updates.nesterov_momentum(\n\t\t\tloss_or_grads=W_grads, params=params, learning_rate=0.01, momentum=0.9)\n\t# Create a loss expression for validation/testing.\n\ttest_prediction = lasagne.layers.get_output(network_s, deterministic=True)\n\ttest_loss = lasagne.objectives.categorical_crossentropy(test_prediction,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttarget_var)\n\ttest_loss = test_loss.mean()\n\ttest_acc = T.mean(T.eq(T.argmax(test_prediction, axis=1), target_var),\n\t\t\t\t\t dtype=theano.config.floatX)\n\n\n\ttrain_fn = theano.function([input_var, target_var], [loss, W_grads[0], W_grads[2], W_grads[4]], updates=updates)\n\tval_fn = theano.function([input_var, target_var], [test_loss, test_acc])\n\n\tlasagne.layers.set_all_param_values(network_s, param_values)\n\n\t# retraining\n\tprint(\"Starting retraining...\")\n\tbest_val_acc = 0\n\tbest_epoch = 0\n\t# We iterate over epochs:\n\tfor epoch in range(num_epochs):\n\t\t# In each epoch, we do a full pass over the training data:\n\t\ttrain_loss = 0\n\t\ttrain_batches = 0\n\t\tstart_time = time.time()\n\t\tfor batch in iterate_minibatches(X_train, y_train, 500, shuffle=True):\n\t\t\tinputs, targets = batch\n\t\t\ttmp, g1, g2, g3 = train_fn(inputs, targets)\n\t\t\ttrain_loss += tmp\n\t\t\ttrain_batches += 1\n\n\t\ttrain_loss = train_loss / train_batches\n\n\t\t# And a full pass over the validation data:\n\t\tval_loss = 0\n\t\tval_acc = 0\n\t\tval_batches = 0\n\t\tfor batch in iterate_minibatches(X_val, y_val, 500, shuffle=False):\n\t\t\tinputs, targets = batch\n\t\t\tloss, acc = val_fn(inputs, targets)\n\t\t\tval_loss += loss\n\t\t\tval_acc += acc\n\t\t\tval_batches += 1\n\n\t\tval_loss = val_loss / val_batches\n\t\tval_acc = val_acc / val_batches * 100\n\n\t\t# Then we print the results for this epoch:\n\t\tif val_acc > best_val_acc:\n\t\t\tbest_val_acc = val_acc\n\t\t\tbest_epoch = epoch\t\t\t\n\t\t\t# After training, we compute and print the test error:\n\t\t\ttest_loss = 0\n\t\t\ttest_acc = 0\n\t\t\ttest_batches = 0\n\t\t\tfor batch in iterate_minibatches(X_test, y_test, 500, shuffle=False):\n\t\t\t\tinputs, targets = batch\n\t\t\t\tloss, acc = val_fn(inputs, targets)\n\t\t\t\ttest_loss += loss\n\t\t\t\ttest_acc += acc\n\t\t\t\ttest_batches += 1\n\t\t\ttest_loss = test_loss / test_batches\n\t\t\ttest_acc = test_acc / test_batches * 100\n\n\t\t\tnp.savez('model/sparse_model_{0}_{1}_{2}.npz'.format(prune_fraction, depth, width),\n\t\t\t\t\t *lasagne.layers.get_all_param_values(network_s))\n\n\t\tprint(\"Epoch {} of {} took {:.3f}s\".format(\n\t\t\tepoch + 1, num_epochs, time.time() - start_time))\n\t\tprint(\" training loss:\\t\\t{:.6f}\".format(train_loss))\n\t\tprint(\" validation loss:\\t\\t{:.6f}\".format(val_loss))\n\t\tprint(\" validation accuracy:\\t\\t{:.2f} %\".format(val_acc))\n\t\tprint(\" test loss:\\t\\t\\t{:.6f}\".format(test_loss))\n\t\tprint(\" test accuracy:\\t\\t{:.2f} %\".format(test_acc))\n\t\t\n\t\twith open(\"model/sparse_{0}_{1}_{2}_{3}_{4}.txt\".format(prune_fraction, depth, width, drop_in, drop_hid), \"a\") as myfile:\n\t\t\tmyfile.write(\"{0} {1:.3f} {2:.3f} {3:.3f} {4:.3f} {5:.3f}\\n\".format(\n\t\t\t\tepoch, train_loss, val_loss, val_acc, test_loss, test_acc))\n\n\n\nif __name__ == '__main__':\n\tif ('--help' in sys.argv) or ('-h' in sys.argv):\n\t\tprint(\"Trains a neural network on MNIST using Lasagne.\")\n\t\tprint(\"Usage: %s [MODEL [EPOCHS]]\" % sys.argv[0])\n\t\tprint(\"EPOCHS: number of training epochs to perform (default: 500)\")\n\telse:\n\t\tkwargs = {}\n\t\tif len(sys.argv) > 1:\n\t\t\tkwargs['model'] = sys.argv[1]\n\t\tif len(sys.argv) > 2:\n\t\t\tkwargs['num_epochs'] = int(sys.argv[2])\n\t\tif len(sys.argv) >3:\n\t\t\tkwargs['prune_fraction'] = float(sys.argv[3])\n\t\tmain(**kwargs)\n","sub_path":"expt1/fc/mnist_sparse.py","file_name":"mnist_sparse.py","file_ext":"py","file_size_in_byte":9783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"86254528","text":"from pytest import fixture\n\nfrom code_resources import Connection\n\n\n@fixture\ndef connections(request):\n ports = getattr(request.module, \"ports\", [])\n connections = []\n for port in ports:\n connection = Connection(port)\n connection.connect()\n connections.append(connection)\n request.addfinalizer(connection.disconnect)\n return connections\n","sub_path":"testing_focus_session/01_unit_tests/03_pytest/02_fixtures/05_request_fixture/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"491887727","text":"from playtest.components.card import Card, BasicDeck as Deck\n\n\ndef test_card_deal():\n deck1 = Deck(all_cards=True, shuffle=False)\n deck2 = Deck([])\n\n deck1.deal(deck2, count=2)\n expected = Deck([Card(c) for c in [\"Kc\", \"Kd\"]]).to_data()\n assert deck2.to_data() == expected\n\n\ndef test_card_value():\n deck = Deck([Card(c) for c in [\"Tc\", \"Ac\"]])\n assert sum([c.number for c in deck]) == 11\n\n\ndef test_reset():\n deck = Deck(all_cards=True)\n assert len(deck) == 52\n deck.reset()\n assert len(deck) == 52\n\n deck = Deck([Card(c) for c in [\"Ad\", \"Qs\"]])\n assert len(deck) == 2\n deck.reset()\n assert deck[0] == Card(\"Ad\")\n","sub_path":"playtest/components/test_card.py","file_name":"test_card.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"627498502","text":"# -*- coding: utf-8 -*-\nfrom osv import osv, fields\n\n\nclass jmdextra(osv.Model):\n _name = \"ea.extra\"\n _inherit = \"mail.thread\"\n\n def autoriza(self, cr, uid, ids, context=None):\n print(\"Entrando\")\n for i in self.browse(cr, uid, ids, context):\n if i.autorizado:\n return\n print(\"En el for\")\n self.write(cr, uid, [i.id], {\n 'jefe': uid,\n 'autorizado': True,\n 'fecha_autorizacion': fields.datetime.now()})\n self.pool.get(\"hr.bonos\").create(cr, uid, {\n 'name': i.motivo,\n 'empleado': i.name.id,\n 'monto': i.monto,\n 'tipo': i.tipo,\n 'dias': i.dias,\n 'proyecto_id': i.proyecto_id.id,\n 'plaza': i.plaza_id.name,\n 'codigo_plaza': i.plaza_id.codigo,\n 'es_extra': True,\n 'fecha': i.fecha\n })\n\n _columns = {\n 'name': fields.many2one(\"hr.employee\", string=\"Solicitante\"),\n 'jefe': fields.many2one(\"res.users\", string=\"Jefe que autoriza\"),\n 'monto': fields.float(\"Monto\"),\n 'dias': fields.float(\"Días\"),\n 'motivo': fields.text(\"Motivo\", required=True),\n 'autorizado': fields.boolean(\"Autorizado\"),\n 'aceptado': fields.boolean(\"Aceptado\"),\n 'tipo': fields.selection([('monto', 'Monto'), ('dias', 'Días')],\n \"Tipo\"),\n \"proyecto_id\": fields.many2one(\"project.project\", string=\"Estudio\", required=True),\n 'nombre_corto': fields.related(\"proyecto_id\", \"nombre_corto\",\n type=\"char\", string=\"Nombre Corto\", readonly=True, store=True),\n 'plaza_id': fields.many2one(\"plaza\", string=\"Plaza\"),\n 'codigo_nomina': fields.related(\"plaza_id\", \"codigo\",\n type=\"char\", string=\"Código de Estudio\", readonly=True, store=True),\n \"fecha\": fields.date(\"Fecha en que se generó\"),\n \"fecha_autorizacion\": fields.datetime(\"Fecha y Hora de Autorización\"),\n }","sub_path":"ea/ea_jmd/extra.py","file_name":"extra.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"52145717","text":"from app.api.models.LXDModule import LXDModule\n\nclass LXCSnapshot(LXDModule):\n def __init__(self, input):\n self.data = {}\n if not input.get('remoteHost'):\n self.remoteHost = '127.0.0.1'\n else:\n self.remoteHost = input.get('remoteHost')\n\n if not input.get('name'):\n self.setSnapshot('')\n else:\n self.setSnapshot(input.get('name'))\n\n if input.get('container'):\n self.setContainer(input.get('container'))\n\n if input.get('newContainer'):\n self.setNewContainer(input.get('newContainer'))\n\n super(LXCSnapshot, self).__init__(remoteHost=self.remoteHost)\n\n\n def setSnapshot(self, input):\n self.data['name'] = input\n\n def setContainer(self, input):\n self.data['container'] = input\n\n def setNewContainer(self, input):\n self.data['newContainer'] = input\n\n\n def snapshotList(self):\n try:\n return self.client.api.containers[self.data.get('container')].snapshots.get().json()['metadata']\n except Exception as e:\n raise ValueError(e)\n\n def snapshotInfo(self):\n try:\n return self.client.api.containers[self.data.get('container')].snapshots[self.data.get('name')].get().json()['metadata']\n except Exception as e:\n raise ValueError(e)\n\n def snapshot(self):\n try:\n container = self.client.containers.get(self.data.get('container'))\n snapName = self.data.get('name')\n container.snapshots.create(snapName)\n return self.client.api.containers[self.data.get('container')].snapshots.get().json()['metadata']\n except Exception as e:\n raise ValueError(e)\n\n def snapshotDelete(self):\n try:\n container = self.client.containers.get(self.data.get('container'))\n container.snapshots.get(self.data.get('name')).delete()\n except Exception as e:\n raise ValueError(e)\n\n\n def snapshotRestore(self):\n try:\n return self.client.api.containers[self.data.get('container')].put(json={'restore': self.data.get('name')}).json()['metadata']\n except Exception as e:\n raise ValueError(e)\n\n def snapshotPublish(self):\n try:\n container = self.client.containers.get(self.data.get('container'))\n image = container.snapshots.get(self.data.get('name')).publish(wait=True)\n image.add_alias(self.data.get('name'), self.data.get('name'))\n return self.client.api.images[image.fingerprint].get().json()['metadata']\n except Exception as e:\n raise ValueError(e)\n\n def snapshotCreateContainer(self):\n try:\n container = self.client.containers.get(self.data.get('container'))\n image = container.snapshots.get(self.data.get('name')).publish(wait=True)\n image.add_alias(self.data.get('name'), self.data.get('name'))\n config = {'name': self.data.get('newContainer'), 'source': {'type': 'image', 'alias': self.data.get('name')}}\n self.client.containers.create(config, wait=True)\n\n newImage = self.client.images.get(image.fingerprint)\n newImage.delete(wait=True)\n\n except Exception as e:\n raise ValueError(e)\n","sub_path":"app/api/models/LXCSnapshot.py","file_name":"LXCSnapshot.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"214212026","text":"from Utils.Offsets import *\r\n\r\n\r\n\r\ndef GetPlayerVars(pm, client, engine, engine_pointer, player):\r\n player = pm.read_int( client + dwLocalPlayer )\r\n engine_pointer = pm.read_int( engine + dwClientState )\r\n glow_manager = pm.read_int( client + dwGlowObjectManager )\r\n crosshairID = pm.read_int( player + m_iCrosshairId )\r\n getcrosshairTarget = pm.read_int( client + dwEntityList + (crosshairID - 1) * 0x10 )\r\n immunitygunganme = pm.read_int( getcrosshairTarget + m_bGunGameImmunity )\r\n localTeam = pm.read_int( player + m_iTeamNum )\r\n crosshairTeam = pm.read_int( getcrosshairTarget + m_iTeamNum )\r\n y_angle = pm.read_float( engine_pointer + dwClientState_ViewAngles + 0x4 )\r\n\r\n return player, engine_pointer, glow_manager, crosshairID, getcrosshairTarget,immunitygunganme, localTeam, crosshairTeam, y_angle","sub_path":"Classes/PlayerVars.py","file_name":"PlayerVars.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"105478008","text":"import requests\nimport sys\nfrom bs4 import BeautifulSoup\nfrom textwrap import TextWrapper\n\nfrom news_scraper import NewsScraper\nfrom user_settings import settings, set_file_name, change_settings\n\nurl = sys.argv[1]\n\nchange_settings()\n\nfile_name = set_file_name(url)\nwrapper = TextWrapper(width=settings['max_symbols_in_line'])\n\npage = requests.get(url)\nsoup = BeautifulSoup(page.text, 'html.parser')\nheadlines = [soup.find_all('h' + str(num)) for num in range(1, 7)]\n\nheadline = NewsScraper.get_main_headline(headlines)\n# главный заголовок должен лежать под тегом

,\n# соответственно в списке\n# под нулевым индексом\nif headline is not None:\n headline = headline.text\n headline = wrapper.fill(headline)\n print(headline)\n print('\\n')\n with open(file_name, 'w+', encoding='utf-8') as file:\n file.write(headline + '\\n') # записать заголовок в файл\n\nbody = soup.find(itemprop='articleBody')\n\nif body is not None:\n\n body = NewsScraper.handle_article_body(body)\n\n for paragraph in body:\n body = wrapper.fill(paragraph)\n print('\\n' + body)\n with open(file_name, 'a+', encoding='utf-8') as file:\n file.write('\\n' + body + '\\n') # записать каждый абзац в файл\nelse:\n whitelist = [\n 'p'\n ]\n\n body = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]\n\n for paragraph in body:\n body = wrapper.fill(paragraph)\n body = body.replace(u'\\xa0', ' ') # escape  \n print('\\n' + body)\n with open(file_name, 'a+', encoding='utf-8') as file:\n file.write('\\n' + body + '\\n') # записать каждый абзац в файл\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"251407438","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# hello.py\n\ndef application(environ, start_response):\n start_response('200 OK', [('Content-Type', 'text/html')])\n query = environ['QUERY_STRING']\n name = query[query.find('=') + 1:]\n body = '

Hello, %s!

' % (name)\n return [body.encode('utf-8')]\n\n\n\n","sub_path":"SE-option-Distributed-Computing-master/Homework2/hello_wsgi.py","file_name":"hello_wsgi.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"23461516","text":"import random\nimport time\n\n# User interface\n\n\ndef Start():\n print(\"\\nWelcome to my program for finding a solution to the set partition problem with optimalisation\")\n Questions()\n print(\"\\nThank you for using my program!\")\n\n\ndef Questions():\n print(\"_________________________________\")\n withSave = AskWithSave()\n fileInput = AskFileInput()\n\n if fileInput:\n FileInput(withSave)\n else:\n TerminalInput(withSave)\n\n\ndef AskFileInput():\n print(\"\\nHow do you want to read the entry set? \\n1 - terminal input \\n2 - for reading form the file\")\n readMethod = input()\n if readMethod == '1':\n return False\n if readMethod == '2':\n return True\n\n print(\"\\nWrong input\")\n return AskFileInput()\n\n\ndef TerminalInput(withSave):\n print(\"\\nInput comma-seperated elements of the set. \\nIf you input single number, then that many elements will be randomly generated\")\n inputElems = input()\n if \",\" in inputElems:\n elems = [int(elem) for elem in inputElems.split(\",\")]\n else:\n noOfElems = int(inputElems)\n elems = [random.randint(0, 20) for ii in range(0, noOfElems)]\n\n print('\\nInto how many subsets do you want to partition the set?')\n n = int(input())\n useMyFit = ChooseFitFun()\n\n print('\\nWhich approach do you want to use?')\n print(\"h - heuristic\")\n print(\"o - optimal by bruteforce\")\n print('b - both heuristic and bruteforce')\n\n while True:\n approach = input()\n\n if approach == 'h':\n print(\"\\n________RESULTS________\\n\")\n start = time.time()\n h = Heuristic(elems, n, useMyFit)\n end = time.time()\n PresentResult(h, elems, 1, True, end-start,\n (\"2\" if useMyFit else \"1\"), withSave)\n print(\"\\nDo you want to use the bruteforce approach as well? (y or n)\")\n alsoBrute = input()\n if alsoBrute == \"y\":\n start = time.time()\n bf = BruteForce(elems, n, useMyFit)\n end = time.time()\n PresentResult(bf, elems, 2, False, end-start,\n (\"2\" if useMyFit else \"1\"), withSave)\n break\n\n if approach == 'o':\n print(\"\\n________RESULTS________\\n\")\n start = time.time()\n bf = BruteForce(elems, n, useMyFit)\n end = time.time()\n PresentResult(bf, elems, 1, False, end-start,\n (\"2\" if useMyFit else \"1\"), withSave)\n print(\"\\nDo you want to use the heuristic approach as well? (y or n)\")\n alsoHeur = input()\n if alsoHeur == \"y\":\n start = time.time()\n h = Heuristic(elems, n, useMyFit)\n end = time.time()\n PresentResult(h, elems, 2, True, end-start,\n (\"2\" if useMyFit else \"1\"), withSave)\n break\n\n if approach == 'b':\n print(\"\\n________RESULTS________\\n\")\n start = time.time()\n h = Heuristic(elems, n, useMyFit)\n end = time.time()\n PresentResult(h, elems, 1, True, end-start,\n (\"2\" if useMyFit else \"1\"), withSave)\n start = time.time()\n bf = BruteForce(elems, n, useMyFit)\n end = time.time()\n PresentResult(bf, elems, 2, False, end-start,\n (\"2\" if useMyFit else \"1\"), withSave)\n break\n\n print(\"\\nDo you want to compute another problem? (y or n)\")\n again = input()\n if again == 'y':\n Questions()\n\n\ndef AskWithSave():\n print(\"\\nWhich output method do you want use?\")\n print(\"1 - display in terminal window\")\n print(\"2 - display in terminal window and save to the file\")\n ans = input()\n if ans == \"1\":\n return False\n if ans == \"2\":\n return True\n print(\"Wrong input\")\n return AskWithSave()\n\n\ndef PresentResult(result, S, count, useHeur, time, ff, withSave):\n if useHeur:\n print(\"\\nPartition\", count, \" - heuristic approach\")\n else:\n print(\"\\nPartition\", count, \" - brute force approach\")\n\n print(\"Set:\", *S, sep=\" \")\n print(\"Partition:\", *result['bestPartition'], sep=\" \")\n print(\"Sum of weights:\", *[\n round(sum(ii), 2) for ii in result['bestPartition']], sep=\" \")\n print(\"Fitness function (\"+ff+\") value:\", int(round(result['bestVal'])))\n print(\"Calculated in:\", \"{0:.4g}\".format(time), \"s\")\n\n if withSave:\n if count == 1:\n f = open(\"output.txt\", \"w\")\n else:\n f = open(\"output.txt\", \"a\")\n\n if useHeur:\n f.write(\"Partition \" + str(count) + \" - heuristic approach\")\n else:\n f.write(\"Partition \" + str(count) + \" - brute force approach\")\n\n f.write(\"\\nSet: \" + \" \".join(str(item) for item in S))\n f.write(\"\\nPartition: \" + \" \".join(str(item)\n for item in result['bestPartition']))\n f.write(\"\\nSum of weights: \" +\n \" \".join([str(round(sum(ii), 2)) for ii in result['bestPartition']]))\n f.write(\"\\nFitness function (\"+ff+\") value: \" +\n str(int(round(result['bestVal']))))\n f.write(\"\\nCalculated in: \" + \"{0:.4g}\".format(time) + \" s\\n\\n\")\n\n\ndef ChooseFitFun():\n print(\"\\nWhich fitness function do you want to use? (1 or 2)\")\n print(\"The function that rewards a partition where the sum of weights for consecutive subsets\")\n print(\"1 - is the same\")\n print('2 - increaces in the linear manner')\n fit = input()\n if fit == '1':\n return False\n if fit == '2':\n return True\n print(\"\\nWrong input\")\n return ChooseFitFun()\n\n\ndef FileInput(withSave):\n f = open(\"input.txt\", \"r\")\n line1 = f.readline()\n count = 0\n while line1 != \"\":\n count += 1\n\n line2 = f.readline()\n line3 = f.readline()\n line4 = f.readline()\n\n subsets = int(line1)\n useHeur = line2[0] == 'h'\n myFit = line3[0] == '2'\n elems = [int(s) for s in line4.split(\",\")]\n\n if len(elems) == 1:\n noOfElems = elems[0]\n elems = [random.randint(1, 20) for ii in range(0, noOfElems)]\n\n if useHeur:\n start = time.time()\n result = Heuristic(elems, subsets, myFit)\n end = time.time()\n\n else:\n start = time.time()\n result = BruteForce(elems, subsets, myFit)\n end = time.time()\n\n PresentResult(result, elems, count, useHeur,\n end-start, line3[0], withSave)\n line1 = f.readline()\n f.close()\n\n\n# BruteForce\n\n\ndef generateStepN(S, n, part, info, useMyFitness, sumofidx):\n\n # full partition\n if len(part) == len(S):\n\n # eliminate empty subsets\n if not (all(any(elem == subsetIndex for elem in part)) for subsetIndex in range(0, n)):\n return\n\n # diff computation\n sums = [0]*n\n\n for ii in range(0, len(part)):\n sums[part[ii]] += S[ii]\n\n val = Fitness2(sums, sumofidx) if useMyFitness else Fitness1(sums)\n\n if val < info['bestVal']:\n info['bestVal'] = val\n info['bestPartition'] = part\n\n return\n\n # recursion\n for ii in range(0, n):\n generateStepN(S, n, part+[ii], info, useMyFitness, sumofidx)\n\n\ndef MapPartition(info, S, n):\n subsets = []\n for ii in range(0, n):\n subsets.append([S[jj] for jj in range(0, len(S))\n if info['bestPartition'][jj] == ii])\n info['bestPartition'] = subsets\n\n\ndef Fitness1(sums):\n return max(sums)-min(sums)\n\n\ndef Fitness2(sums, sumofidx):\n val = 0\n s = sum(sums)\n\n for ii in range(0, len(sums)):\n val += abs((ii+1)/sumofidx*s - sums[ii])\n return val\n\n\ndef BruteForce(S, n, useMyFitness=False):\n if n > 1 and n <= len(S):\n info = {'bestVal': float('inf'), 'bestPartition': []}\n sumofidx = 0\n for ii in range(1, n+1):\n sumofidx += ii\n generateStepN(S, n, [], info, useMyFitness, sumofidx)\n MapPartition(info, S, n)\n return info\n\n# Heuristic\n\n\ndef Heuristic(S, n, useMyFit):\n\n subsets = []\n for ii in range(0, n):\n subsets.append([])\n\n sortedS = sorted(S)\n\n ii = len(S)-1\n\n if useMyFit:\n s = sum(S)\n k = 0\n for jj in range(0, n):\n k += (jj+1)\n coeff = s/k\n\n while ii >= 0:\n smallestIndex = n-1\n\n smallestValue = Aux2(subsets[smallestIndex], smallestIndex,\n coeff) if useMyFit else Aux1(subsets[smallestIndex])\n for jj in range(0, n):\n val = Aux2(subsets[jj], jj, coeff) if useMyFit else Aux1(\n subsets[jj])\n if val < smallestValue:\n smallestValue = val\n smallestIndex = jj\n\n subsets[smallestIndex].append(sortedS[ii])\n ii -= 1\n if useMyFit:\n return {\"bestPartition\": subsets, \"bestVal\": sum(abs(sum(subsets[i])-coeff*(i+1)) for i in range(0, n))}\n else:\n return {\"bestPartition\": subsets, \"bestVal\": max([sum(subset) for subset in subsets])-min([sum(subset) for subset in subsets])}\n\n\ndef Aux1(subset):\n return sum(subset)\n\n\ndef Aux2(subset, i, coeff):\n return (sum(subset)-(i+1)*coeff)\n\n\nStart()\n","sub_path":"Program.py","file_name":"Program.py","file_ext":"py","file_size_in_byte":9325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"196281924","text":"# Copyright 2016 Mirantis, Inc.\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.\nimport datetime\nimport json\n\nfrom junit_xml import TestSuite, TestCase\n\nfrom tcp_tests import logger\nfrom tcp_tests import settings\n\n\nLOG = logger.logger\n\n\nclass RallyManager(object):\n \"\"\"docstring for RallyManager\"\"\"\n\n image_name = 'rallyforge/rally'\n image_version = '0.9.1'\n\n def __init__(self, underlay, admin_host):\n super(RallyManager, self).__init__()\n self._admin_host = admin_host\n self._underlay = underlay\n\n def prepare(self):\n content = \"\"\"\nsed -i 's|#swift_operator_role = Member|swift_operator_role=SwiftOperator|g' /etc/rally/rally.conf # noqa\nsource /home/rally/openrc\nrally-manage db recreate\nrally deployment create --fromenv --name=tempest\nrally verify create-verifier --type tempest --name tempest-verifier\nrally verify configure-verifier\nrally verify configure-verifier --show\n\"\"\"\n cmd = \"cat > {path} << EOF\\n{content}\\nEOF\".format(\n path='/root/rally/install_tempest.sh', content=content)\n cmd1 = \"chmod +x /root/rally/install_tempest.sh\"\n cmd2 = \"scp ctl01:/root/keystonercv3 /root/rally/openrc\"\n\n with self._underlay.remote(host=self._admin_host) as remote:\n LOG.info(\"Create rally workdir\")\n remote.check_call('mkdir -p /root/rally')\n LOG.info(\"Create install_tempest.sh\")\n remote.check_call(cmd)\n LOG.info(\"Chmod +x install_tempest.sh\")\n remote.check_call(cmd1)\n LOG.info(\"Copy openstackrc\")\n remote.check_call(cmd2)\n\n def pull_image(self, version=None):\n version = version or self.image_version\n image = self.image_name\n cmd = (\"apt-get -y install docker.io &&\"\n \" docker pull {image}:{version}\".format(image=image,\n version=version))\n with self._underlay.remote(host=self._admin_host) as remote:\n LOG.info(\"Pull {image}:{version}\".format(image=image,\n version=version))\n remote.check_call(cmd)\n\n with self._underlay.remote(host=self._admin_host) as remote:\n LOG.info(\"Getting image id\")\n cmd = \"docker images | grep {0}| awk '{print $3}'\".format(\n self.image_version)\n res = remote.check_call(cmd)\n self.image_id = res['stdout'][0].strip()\n LOG.info(\"Image ID is {}\".format(self.image_id))\n\n def run(self):\n with self._underlay.remote(host=self._admin_host) as remote:\n cmd = (\"docker run --net host -v /root/rally:/home/rally \"\n \"-tid -u root {image_id}\".format(image_id=self.image_id))\n LOG.info(\"Run Rally container\")\n remote.check_call(cmd)\n\n cmd = (\"docker ps | grep {image_id} | \"\n \"awk '{{print $1}}'| head -1\").format(\n image_id=self.image_id)\n LOG.info(\"Getting container id\")\n res = remote.check_call(cmd)\n self.docker_id = res['stdout'][0].strip()\n LOG.info(\"Container ID is {}\".format(self.docker_id))\n\n def run_tempest(self, test=''):\n docker_exec = ('docker exec -i {docker_id} bash -c \"{cmd}\"')\n commands = [\n docker_exec.format(cmd=\"./install_tempest.sh\",\n docker_id=self.docker_id),\n docker_exec.format(\n cmd=\"source /home/rally/openrc && \"\n \"rally verify start {test}\".format(test=test),\n docker_id=self.docker_id),\n docker_exec.format(\n cmd=\"rally verify report --type json --to result.json\",\n docker_id=self.docker_id),\n docker_exec.format(\n cmd=\"rally verify report --type html --to result.html\",\n docker_id=self.docker_id),\n ]\n with self._underlay.remote(host=self._admin_host) as remote:\n LOG.info(\"Run tempest inside Rally container\")\n for cmd in commands:\n remote.check_call(cmd, verbose=True)\n\n def get_results(self, store=True, store_file='tempest.xml'):\n LOG.info('Storing tests results...')\n res_file_name = 'result.json'\n file_prefix = 'results_' + datetime.datetime.now().strftime(\n '%Y%m%d_%H%M%S') + '_'\n file_dst = '{0}/{1}{2}'.format(\n settings.LOGS_DIR, file_prefix, res_file_name)\n with self._underlay.remote(host=self._admin_host) as remote:\n remote.download(\n '/root/rally/{0}'.format(res_file_name),\n file_dst)\n res = json.load(remote.open('/root/rally/result.json'))\n if not store:\n return res\n\n formatted_tc = []\n failed_cases = [res['test_cases'][case]\n for case in res['test_cases']\n if res['test_cases'][case]['status']\n in 'fail']\n for case in failed_cases:\n if case:\n tc = TestCase(case['name'])\n tc.add_failure_info(case['traceback'])\n formatted_tc.append(tc)\n\n skipped_cases = [res['test_cases'][case]\n for case in res['test_cases']\n if res['test_cases'][case]['status'] in 'skip']\n for case in skipped_cases:\n if case:\n tc = TestCase(case['name'])\n tc.add_skipped_info(case['reason'])\n formatted_tc.append(tc)\n\n error_cases = [res['test_cases'][case] for case in res['test_cases']\n if res['test_cases'][case]['status'] in 'error']\n\n for case in error_cases:\n if case:\n tc = TestCase(case['name'])\n tc.add_error_info(case['traceback'])\n formatted_tc.append(tc)\n\n success = [res['test_cases'][case] for case in res['test_cases']\n if res['test_cases'][case]['status'] in 'success']\n for case in success:\n if case:\n tc = TestCase(case['name'])\n formatted_tc.append(tc)\n\n ts = TestSuite(\"tempest\", formatted_tc)\n with open(store_file, 'w') as f:\n ts.to_file(f, [ts], prettyprint=False)\n\n return res\n","sub_path":"tcp_tests/managers/rallymanager.py","file_name":"rallymanager.py","file_ext":"py","file_size_in_byte":6901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"565746581","text":"#saves html from webpages using requests\r\n#written by Kelly Schmidt\r\n\r\n#import modules\r\nimport re\r\nimport requests\r\nimport pyinputplus as pyip\r\nimport pyperclip as pclip\r\n\r\n#compile out the DNS from the url for filename\r\nfilename_compile = re.compile(r'''(http://|https://)\r\n (www.)?\r\n ([a-zA-Z0-9_-]*)\r\n [.][a-zA-Z]*[/]\r\n ([a-zA-Z0-9_-]*)?''', re.VERBOSE)\r\n\r\n#if user has webpage copied to clipboard they can use that, otherwise manually enter the url\r\ndef ask_for_webpage():\r\n print(\"Would you like to pull the website url from the clipboard?(y/n): \")\r\n cut_and_paste = pyip.inputYesNo()\r\n if cut_and_paste == 'yes':\r\n user_request = pclip.paste()\r\n get_webpage(user_request)\r\n else:\r\n print('Please enter the URL you would like to get the HTML for: ')\r\n user_request = pyip.inputURL('Must start with http(s):// : ')\r\n get_webpage(user_request)\r\n\r\n#request content from url\r\ndef get_webpage(user_request):\r\n req = requests.get(user_request)\r\n req.raise_for_status()\r\n filename = filename_compile.search(user_request)\r\n \r\n#save webpage\r\n with open('web scraping progs/savedpages/{}.html'.format(filename.group(3) + filename.group(4)), 'wb') as webpage:\r\n for chunk in req.iter_content(chunk_size = 10_000):\r\n webpage.write(chunk)\r\n\r\nask_for_webpage()\r\n","sub_path":"webpagesaver.py","file_name":"webpagesaver.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"646553617","text":"T = int(input())\n\n# 리스트를 나누는 함수 merge_sort\ndef merge_sort(n_list):\n\n # 반씩 자르는 list의 길이가 1이 되면 끝내고(return 하고) 다시 합치기 시작\n if len(n_list) == 1:\n return n_list\n\n # n_list를 left, right로 나눔\n mid = len(n_list)//2\n left = n_list[:mid]\n right = n_list[mid:]\n\n # left, right가 1이 될 때 까지 계속 나눔\n left_1 = merge_sort(left)\n right_1 = merge_sort(right)\n\n # 왼쪽부터 오른쪽 순서대로 병합하는 merge함수\n return merge(left_1, right_1)\n\n\n# 왼쪽부터 오른쪽 순서대로 병합해주는 함수\ndef merge(left, right):\n\n # merge를 하는 순간에 left[-1]과 right[-1]을 비교한다\n global cnt\n if left[0] > right[0]:\n cnt += 1\n\n i = 0\n j = 0\n idx = 0\n result_list = [0] * (len(left) + len(right)) # 결과 리스트\n\n # left = i / right = j 로 왼쪽부터 훑어나가면서 i와 j 둘 중 하나가 끝에 도달할 때 까지\n while (i < len(left)) and (j < len(right)):\n \n # left, right를 비교하며 더 작은 값을 result에 더해준다\n if left[i] < right[j]:\n result_list[idx] = left[i]\n idx += 1\n i += 1\n else:\n result_list[idx] = right[j]\n idx += 1\n j += 1\n\n # 위 while이 끝날 때, 처음부터 left, right의 개수가 맞지 않거나, \n # left, right중 한 쪽만 작은 숫자가 있어서 한 쪽만 정렬되고 끝날 수 있음.\n while i < len(left):\n result_list[idx] = left[i]\n idx += 1\n i += 1\n\n while j < len(right):\n result_list[idx] = right[j]\n idx += 1\n j += 1\n\n return result_list\n\n\nfor t in range(1, T+1):\n N = int(input())\n n_list = list(map(int, input().split()))\n cnt = 0\n result = merge_sort(n_list)\n\n print(\"#{} {} {}\".format(t, result[N//2], cnt))\n\n \n","sub_path":"intermediate/ad_day0304/병합정렬.py","file_name":"병합정렬.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"577185797","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 30 16:48:32 2020\n\n@author: krypton\n\"\"\"\n\n\n#%% imports \nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#%% read_img car_plate.jpg\nimg = cv2.imread(\"../DATA/car_plate.jpg\")\n\n#%% display function\ndef display(img):\n fig = plt.figure(figsize=(12, 10))\n ax= fig.add_subplot(111)\n ax.imshow(img, cmap=\"gray\")\n \n#%% \ndisplay(img)\n\n#%% \nmodel = cv2.CascadeClassifier(\"../DATA/haarcascades/haarcascade_russian_plate_number.xml\")\n\n#%% def \ndef detect_plate(img):\n \n plate = img.copy()\n \n plate_rects = model.detectMultiScale(plate)\n \n for x, y, w, h in plate_rects:\n cv2.rectangle(plate, (x, y), (x+w, y+h), (255, 0, 0), 2)\n \n return plate\n\n#%%\n\nres = detect_plate(img)\n\ndisplay(res)\n\n","sub_path":"car_plate_detection_assesment.py","file_name":"car_plate_detection_assesment.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"598553349","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nfrom lxml import html,etree\r\nfrom requests.adapters import HTTPAdapter\r\nfrom requests.packages.urllib3.util.retry import Retry\r\nfrom datetime import datetime\r\nimport time\r\nname=[]\r\nprice=[]\r\nrate=[]\r\nurllist=[]\r\nreview=[]\r\nhotel_data=[]\r\n\r\ndef parse(page):\r\n #parsed into beautifulsoup\r\n parsed_html = BeautifulSoup(page.content, 'lxml')\r\n item=parsed_html.find(class_='hotellist_wrap tracked shorten_property_block')\r\n \r\n hotel_list = item.find_all('div',class_=\"sr_item sr_item_new sr_item_default sr_property_block sr_item_bs sr_flex_layout\")\r\n hotel_list.extend(item.find_all('div',class_=\"sr_item sr_item_new sr_item_default sr_property_block sr_flex_layout\"))\r\n # get data using html elements\r\n for i in hotel_list:\r\n name.append(i.find('span',class_=\"sr-hotel__name\").get_text().strip('\\n'))\r\n #review.append(i.find('div',class_=\"bui-review-score__text\").get_text().strip('\\n'))\r\n val=i.find('div',class_='price scarcity_color')\r\n val1=i.find('div',class_='bui-price-display__value prco-inline-block-maker-helper')\r\n val2=i.find('b',class_=\"sr_gs_price_total\")\r\n val3=i.find('strong',class_=\"price availprice no_rack_rate\")\r\n val4=i.find('strong',class_=\"price scarcity_color\")\r\n val5=i.find('div',class_=\"totalPrice totalPrice_no-rack-rate entire_row_clickable\")\r\n \r\n if val!=None:\r\n price.append(val.get_text().strip())\r\n elif val!=None:\r\n price.append(val1.get_text().strip())\r\n elif val2!=None:\r\n price.append(val2.get_text().strip())\r\n elif val3!=None:\r\n price.append(val3.get_text().strip())\r\n elif val4!=None:\r\n price.append(val4.get_text().strip())\r\n elif val5!=None:\r\n price.append(val5.get_text().strip())\r\n else:\r\n price.append(0)\r\n # get rating data\r\n rating=i.find('div',class_='bui-review-score__badge')\r\n if rating==None:\r\n rating=i.find('span',class_='review-score-badge')\r\n \r\n if rating!=None:\r\n \r\n rates=float(rating.get_text().strip())\r\n else:\r\n rates=0.0\r\n # format rating\r\n rate.append(round(rates)/2)\r\n # get hotel url\r\n hotelurl=i.find('a',class_=\"hotel_name_link url\").get('href').strip()\r\n urllist.append('https://www.booking.com/'+str(hotelurl))\r\n print (len(price),len(rate),len(urllist))\r\n \r\n # format data into the dictionary\r\n for i in range(len(hotel_list)):\r\n data={}\r\n data['Name']=name[i]\r\n data['rate']=rate[i]\r\n data['url']=urllist[i]\r\n data['price']=price[i]\r\n hotel_data.append(data)\r\n #print name[i]\r\n #print\"=====================\"\r\n \r\n return hotel_data \r\n#parse('Chennai','06/18/2019','06/19/2019')\r\n","sub_path":"py/booking.py","file_name":"booking.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"416225931","text":"import pygame\r\npygame.init()\r\nwin=pygame.display.set_mode((500,480))\r\npygame.display.set_caption('flappy bird')\r\n\r\n\r\n\r\nwalkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'), pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'), pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]\r\nwalkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'), pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'), pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]\r\nbg = pygame.image.load('bg.jpg')\r\nchar = pygame.image.load('standing.png')\r\n\r\n\r\nclock=pygame.time.Clock()\r\nclass player(object):\r\n def __init__(self,x,y,width,height):\r\n self.x = x\r\n self.y = y\r\n self.width = width\r\n self.height = height\r\n self.vel = 5\r\n self.isjump = False\r\n self.left = False\r\n self.right = False\r\n self.walkcount = 0\r\n self.jumpcount = 10\r\n self.standing=True\r\n self.hitbox=(self.x+17,self.y,25,60)\r\n def draw(self, win):\r\n if self.walkcount + 1 >= 27:\r\n self.walkcount = 0\r\n if not (self.standing):\r\n if self.left:\r\n win.blit(walkLeft[self.walkcount//3], (self.x,self.y))\r\n self.walkcount += 1\r\n elif self.right:\r\n win.blit(walkRight[self.walkcount//3], (self.x,self.y))\r\n self.walkcount +=1\r\n else:\r\n if self.left:\r\n win.blit(walkLeft[0], (self.x,self.y))\r\n else:\r\n win.blit(walkRight[0], (self.x,self.y))\r\n self.hitbox=(self.x+17,self.y,28,60)\r\n #pygame.draw.rect(win,(255,0,0),self.hitbox,2) hitbxo\r\n def hit(self):\r\n self.x = 60 # We are resetting the player position\r\n self.y = 410\r\n self.walkCount = 0\r\n font1 = pygame.font.SysFont('comicsans', 100)\r\n text = font1.render('-5', 1, (255,0,0))\r\n win.blit(text, (250 - (text.get_width()/2),200))\r\n pygame.display.update()\r\n i = 0\r\n while i < 300:\r\n pygame.time.delay(10)\r\n i += 1\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n i = 301\r\n pygame.quit()\r\n \r\n \r\nclass enemy(object):\r\n walkRight = [pygame.image.load('R1E.png'), pygame.image.load('R2E.png'), pygame.image.load('R3E.png'), pygame.image.load('R4E.png'), pygame.image.load('R5E.png'), pygame.image.load('R6E.png'), pygame.image.load('R7E.png'), pygame.image.load('R8E.png'), pygame.image.load('R9E.png'), pygame.image.load('R10E.png'), pygame.image.load('R11E.png')]\r\n walkLeft = [pygame.image.load('L1E.png'), pygame.image.load('L2E.png'), pygame.image.load('L3E.png'), pygame.image.load('L4E.png'), pygame.image.load('L5E.png'), pygame.image.load('L6E.png'), pygame.image.load('L7E.png'), pygame.image.load('L8E.png'), pygame.image.load('L9E.png'), pygame.image.load('L10E.png'), pygame.image.load('L11E.png')]\r\n \r\n def __init__(self, x, y, width, height, end):\r\n self.x = x\r\n self.y = y\r\n self.width = width\r\n self.height = height\r\n self.path = [x, end] # This will define where our enemy starts and finishes their path.\r\n self.walkCount = 0\r\n self.vel = 3\r\n self.hitbox=(self.x+20,self.y,15,60)\r\n self.health=10\r\n self.visible=True\r\n def draw(self, win):\r\n self.move()\r\n if self.visible:\r\n if self.walkCount + 1 >= 33: # Since we have 11 images for each animtion our upper bound is 33. \r\n # We will show each image for 3 frames. 3 x 11 = 33.\r\n self.walkCount = 0\r\n \r\n if self.vel > 0:\r\n win.blit(self.walkRight[self.walkCount//3], (self.x,self.y))\r\n self.walkCount += 1\r\n else: \r\n win.blit(self.walkLeft[self.walkCount//3], (self.x,self.y))\r\n self.walkCount += 1\r\n\r\n pygame.draw.rect(win,(255,0,0),(self.hitbox[0],self.hitbox[1]-20,50,10))\r\n pygame.draw.rect(win,(0,128,0),(self.hitbox[0],self.hitbox[1]-20,50-(5*(10-self.health)),10))\r\n self.hitbox=(self.x+17,self.y,31,57)\r\n else:\r\n self.hitbox=(0,0,0,0)\r\n #pygame.draw.rect(win,(255,0,0),self.hitbox,2) hitbox\r\n \r\n def move(self):\r\n if self.vel>0:\r\n if self.xself.path[0]-self.vel:\r\n self.x+=self.vel\r\n else:\r\n self.vel*=-1\r\n self.walkCount=0 #take images from list\r\n self.x+=self.vel\r\n def hit(self):\r\n hitSound.play() \r\n if self.health>0:\r\n self.health-=1\r\n else:\r\n self.visible=False\r\n print('hit')\r\n \r\n def __del__(self):\r\n print('dleted')\r\n \r\n \r\nscore=0\r\nbulletSound = pygame.mixer.Sound(\"bullet.wav\")\r\nhitSound = pygame.mixer.Sound(\"hit.wav\")\r\n\r\nmusic = pygame.mixer.music.load(\"music.mp3\")\r\npygame.mixer.music.play(-1)\r\n\r\n\r\nclass projectile(object):\r\n def __init__(self,x,y,radius,color,facing):\r\n self.x = x\r\n self.y = y\r\n self.radius = radius\r\n self.color = color\r\n self.facing = facing\r\n self.vel=8*facing\r\n def draws(self,win):\r\n pygame.draw.circle(win,self.color,(self.x,self.y),self.radius)\r\n\r\n\r\n\r\ndef redraw():\r\n #win.fill((0,0,0))\r\n win.blit(bg,(0,0))\r\n text=font.render('Score:'+ str(score), 1, (0,0,0))\r\n win.blit(text,(390,10))\r\n #pygame.draw.rect(win,(255,0,0),(x,y,width,height))\r\n man.draw(win)\r\n #goblin1.draw(win)\r\n goblin.draw(win)\r\n \r\n \r\n for bullet in bullets:\r\n bullet.draws(win)\r\n pygame.display.update()\r\n\r\nfont = pygame.font.SysFont('comicsans',20,True)\r\n\r\n\r\n\r\n\r\n\r\n\r\ngoblin = enemy(100, 410, 64, 64, 300)\r\n#goblin1=enemy\r\n(50,410,64,64,100)\r\nman = player(200, 410, 64,64)\r\nbullets=[]\r\nshoot=0\r\nrun=True\r\nwhile run:\r\n if man.hitbox[1] < goblin.hitbox[1] + goblin.hitbox[3] and man.hitbox[1] + man.hitbox[3] > goblin.hitbox[1]:\r\n if man.hitbox[0] + man.hitbox[2] > goblin.hitbox[0] and man.hitbox[0] < goblin.hitbox[0] + goblin.hitbox[2]:\r\n man.hit()\r\n score -= 5\r\n clock.tick(27)\r\n pygame.time.delay(27)\r\n if shoot>0:\r\n shoot+=1\r\n if shoot>5:\r\n shoot=0\r\n for event in pygame.event.get():\r\n if event.type== pygame.QUIT:\r\n run=False\r\n\r\n for bullet in bullets:\r\n if bullet.y-bullet.radiusgoblin.hitbox[1]:\r\n if bullet.x+bullet.radius>goblin.hitbox[0] and bullet.x-bullet.radius0:\r\n bullet.x+=bullet.vel\r\n else:\r\n bullets.pop(bullets.index(bullet))\r\n\r\n \r\n keys=pygame.key.get_pressed()\r\n\r\n\r\n if keys[pygame.K_SPACE] and shoot==0:\r\n bulletSound.play()\r\n if man.left:\r\n facing=-1\r\n else:\r\n facing=1\r\n if len(bullets)< 5:\r\n bullets.append(projectile(round(man.x+man.width//2),round(man.y+man.height//2),6,(0,0,0),facing))\r\n shoot=1\r\n if keys[pygame.K_LEFT] and man.x>man.vel:\r\n man.x -= man.vel\r\n man.left = True\r\n man.right = False\r\n man.standing=False\r\n elif keys[pygame.K_RIGHT] and man.x<500-man.vel-man.width:\r\n man.x += man.vel\r\n man.right = True\r\n man.left = False\r\n man.standing=False\r\n else:\r\n man.standing=True\r\n man.walkCount = 0\r\n if not(man.isjump):\r\n\r\n #if keys[pygame.K_SPACE]:\r\n if keys[pygame.K_UP]:\r\n man.isjump = True\r\n #man.right = False\r\n #man.left = False\r\n man.walkCount = 0\r\n else:\r\n if man.jumpcount>=-10:\r\n neg=1\r\n if man.jumpcount<0:\r\n neg=-1\r\n man.y-=man.jumpcount ** 2 * 0.5 *neg\r\n man.jumpcount-=1\r\n else:\r\n man.isjump=False\r\n man.jumpcount=10\r\n #pygame.display.update()\r\n redraw()\r\n \r\n\r\npygame.quit()\r\n\r\n\r\n\r\n'''\r\n\r\nimport pygame\r\npygame.init()\r\n\r\nwin = pygame.display.set_mode((500,480))\r\n\r\npygame.display.set_caption(\"First Game\")\r\n\r\nwalkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'), pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'), pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]\r\nwalkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'), pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'), pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]\r\nbg = pygame.image.load('bg.jpg')\r\nchar = pygame.image.load('standing.png')\r\n\r\nclock = pygame.time.Clock()\r\n\r\n\r\nclass player(object):\r\n def __init__(self,x,y,width,height):\r\n self.x = x\r\n self.y = y\r\n self.width = width\r\n self.height = height\r\n self.vel = 5\r\n self.isJump = False\r\n self.left = False\r\n self.right = False\r\n self.walkCount = 0\r\n self.jumpCount = 10\r\n self.standing = True\r\n\r\n def draw(self, win):\r\n if self.walkCount + 1 >= 27:\r\n self.walkCount = 0\r\n\r\n if not(self.standing):\r\n if self.left:\r\n win.blit(walkLeft[self.walkCount//3], (self.x,self.y))\r\n self.walkCount += 1\r\n elif self.right:\r\n win.blit(walkRight[self.walkCount//3], (self.x,self.y))\r\n self.walkCount +=1\r\n else:\r\n if self.right:\r\n win.blit(walkRight[0], (self.x, self.y))\r\n else:\r\n win.blit(walkLeft[0], (self.x, self.y))\r\n \r\n\r\n\r\nclass projectile(object):\r\n def __init__(self,x,y,radius,color,facing):\r\n self.x = x\r\n self.y = y\r\n self.radius = radius\r\n self.color = color\r\n self.facing = facing\r\n self.vel = 8 * facing\r\n\r\n def draw(self,win):\r\n pygame.draw.circle(win, self.color, (self.x,self.y), self.radius)\r\n\r\n\r\n\r\ndef redrawGameWindow():\r\n win.blit(bg, (0,0))\r\n man.draw(win)\r\n for bullet in bullets:\r\n bullet.draw(win)\r\n \r\n pygame.display.update()\r\n\r\n\r\n#mainloop\r\nman = player(200, 410, 64,64)\r\nbullets = []\r\nrun = True\r\nwhile run:\r\n clock.tick(27)\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n run = False\r\n \r\n for bullet in bullets:\r\n if bullet.x < 500 and bullet.x > 0:\r\n bullet.x += bullet.vel\r\n else:\r\n bullets.pop(bullets.index(bullet))\r\n\r\n keys = pygame.key.get_pressed()\r\n\r\n if keys[pygame.K_SPACE]:\r\n if man.left:\r\n facing = -1\r\n else:\r\n facing = 1\r\n \r\n if len(bullets) < 5:\r\n bullets.append(projectile(round(man.x + man.width //2), round(man.y + man.height//2), 6, (0,0,0), facing))\r\n\r\n if keys[pygame.K_LEFT] and man.x > man.vel:\r\n man.x -= man.vel\r\n man.left = True\r\n man.right = False\r\n man.standing = False\r\n elif keys[pygame.K_RIGHT] and man.x < 500 - man.width - man.vel:\r\n man.x += man.vel\r\n man.right = True\r\n man.left = False\r\n man.standing = False\r\n else:\r\n man.standing = True\r\n man.walkCount = 0\r\n \r\n if not(man.isJump):\r\n if keys[pygame.K_UP]:\r\n man.isJump = True\r\n man.right = False\r\n man.left = False\r\n man.walkCount = 0\r\n else:\r\n if man.jumpCount >= -10:\r\n neg = 1\r\n if man.jumpCount < 0:\r\n neg = -1\r\n man.y -= (man.jumpCount ** 2) * 0.5 * neg\r\n man.jumpCount -= 1\r\n else:\r\n man.isJump = False\r\n man.jumpCount = 10\r\n \r\n redrawGameWindow()\r\n\r\n'''\r\n","sub_path":"pygamesss.py","file_name":"pygamesss.py","file_ext":"py","file_size_in_byte":12587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"103193527","text":"import numpy as np, matplotlib\r\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\r\nfrom matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar\r\nfrom matplotlib.figure import Figure\r\nfrom matplotlib.pyplot import cm\r\nimport matplotlib.colors as colors\r\nfrom matplotlib.colors import ListedColormap\r\nimport generate_tabletext\r\n\r\n\r\ndef create_christmas_colormap():\r\n christmas_colormap = cm.get_cmap('viridis', 31)\r\n christmas_colormap.colors[0,0:-1] = [1,1,1]\r\n for i in range(1,29):\r\n christmas_colormap.colors[i,0:-1] = [0,0.9-i*0.02,0]\r\n christmas_colormap.colors[-2,0:-1] = [0.5,0,0]\r\n christmas_colormap.colors[-1,0:-1] = [1,0,0]\r\n return christmas_colormap\r\n\r\n\r\ndef gen_plot(qtapp, data_type='disk'):\r\n current_model = qtapp.curr_model\r\n mic_cutoffS = float(current_model.ycutoffS)\r\n mic_cutoffR = float(current_model.ycutoffR)\r\n try:\r\n #Some cutoffs and breakpoints are very unlikely to be encuontered in reality and these\r\n #limits are below.\r\n if float(current_model.ycutoffS) < 0.06 or float(current_model.ycutoffS) > 120:\r\n return \"You have entered an invalid MIC breakpoint (<0.06 or >120). Try again.\"\r\n if float(current_model.ycutoffR) < 0.06 or float(current_model.ycutoffR) > 120:\r\n return \"You have entered an invalid MIC breakpoint (<0.06 or >120). Try again.\"\r\n if float(current_model.xcutoffS) < 0.12 or float(current_model.xcutoffS) > 64:\r\n return \"You have entered an invalid disk cutoff(<0.12 or >64). Try again.\"\r\n if float(current_model.xcutoffR) < 0.12 or float(current_model.xcutoffR) > 64:\r\n return \"You have entered an invalid disk cutoff(<0.12 or >64). Try again.\"\r\n except:\r\n return \"You have entered a non-numeric MIC breakpoint or disk cutoff. Try again.\"\r\n #If user imported non-numeric values, as they sometimes may, return error message.\r\n try:\r\n yreal = np.log(np.clip(np.asarray(current_model.current_dataset['mics']), a_min=0.016, a_max = 256))\r\n if current_model.mic_vs_mic:\r\n x = np.log(np.clip(np.asarray(current_model.current_dataset['disks']), a_min=0.016, a_max=256))\r\n else:\r\n x = np.clip(np.asarray(current_model.current_dataset['disks']), a_min=5, a_max=50)\r\n except:\r\n return \"Your data could not be plotted. It probably contains non-numeric or negative values. Try again.\"\r\n #Update the error tables before plotting...\r\n error_code = current_model.update_error_tables(current_model.mic_vs_mic)\r\n if error_code != '0':\r\n return error_code\r\n cell_text = generate_tabletext.generate_celltext(current_model)\r\n #vertpoints will be used to fill in the vertical lines that mark cutoffs on the heatmap.\r\n vertpoints1 = np.arange(0.0161,255,0.5)\r\n\r\n\r\n #The .clf call here clears any existing figure, which prevents Matplotlib from stacking colorbars generated\r\n #when plotting a new dataset.\r\n qtapp.central_plot.clf()\r\n ax = qtapp.central_plot.add_subplot(121)\r\n ax2 = qtapp.central_plot.add_subplot(122)\r\n qtapp.central_plot.subplots_adjust(left=0.08, right=0.95, bottom=0.18)\r\n ax2.clear()\r\n ax.clear()\r\n #Since MIC data is on y, y-axis is always a log scale. The values shown below are standard reporting values\r\n #for MICs so they are convenient to use as bins.\r\n ybins = np.asarray([0.016,0.03,0.06,0.12,0.25,0.5,1,2,4,8,16,32,64,128,256])\r\n #For the susceptibility MIC breakpoint, we have to draw the line 1 category up because of the way the axis is set up.\r\n #Must round up to next highest mic bin.\r\n mic_cutoffS = float(current_model.ycutoffS)\r\n for i in range(0, len(ybins)-1):\r\n if mic_cutoffS >= ybins[i] and mic_cutoffS < ybins[i+1]:\r\n mic_cutoffS = ybins[i+1]\r\n break\r\n ybins = np.log(ybins)\r\n ax.set_yticks(ybins)\r\n ax.set_yticklabels([0.016,0.03,0.06,0.12,0.25,0.5,1,2,4,8,16,32,64,128,''])\r\n ax.set_ylabel('MIC (mg/L)')\r\n \r\n #If the user imported mic vs mic data, the x-axis will need to be a log scale as well, with the same bin\r\n #values as y.\r\n if current_model.mic_vs_mic:\r\n xbins = np.log(np.asarray([0.016,0.03,0.06,0.12,0.25,0.5,1,2,4,8,16,32,64,128,256]))\r\n horizpoints1 = np.log(np.asarray([0.016,0.03,0.06,0.12,0.25,0.5,1,2,4,8,16,32,64,128,256]))\r\n #If using MIC data on x-axis, will need to round the cutoffs to the nearest common MIC reporting\r\n #value (will do the same thing when we export final results)\r\n ax.set_xlabel('MIC, alternate method (mg/L)')\r\n ax.set_xticks(xbins)\r\n ax.set_xticklabels([0.016,0.03,0.06,0.12,0.25,0.5,1,2,4,8,16,32,64,128,''], rotation=90)\r\n ax.xaxis.tick_top()\r\n\r\n xbins = [0.016,0.03,0.06,0.12,0.25,0.5,1,2,4,8,16,32,64,128,256]\r\n if current_model.xcutoffS <= 128:\r\n rounded_cutoffS = xbins[xbins.index(current_model.xcutoffS)+1]\r\n else:\r\n rounded_cutoffS = 256\r\n ax.plot(np.full(vertpoints1.shape[0], np.log(rounded_cutoffS)),\r\n np.log(vertpoints1), color='k', linewidth=0.5)\r\n ax.plot(np.full(vertpoints1.shape[0], np.log(current_model.xcutoffR)), np.log(vertpoints1), color='k', linewidth=0.5)\r\n xbins = np.log(np.asarray(xbins))\r\n else:\r\n #If plotting MIC vs disk, the x-axis is much simpler -- no log scale required; disk values are in [5,50].\r\n xbins = np.arange(5,50,1)\r\n horizpoints1 = np.arange(5,50,1)\r\n ax.set_xlabel('Disk zone (mm)')\r\n ax.plot(np.full(vertpoints1.shape[0], current_model.xcutoffS), np.log(vertpoints1), color='k', linewidth=0.5)\r\n ax.plot(np.full(vertpoints1.shape[0], current_model.xcutoffR+1), np.log(vertpoints1), color='k', linewidth=0.5)\r\n\r\n\r\n #try:\r\n if current_model.colormap_type == 'christmas_colors':\r\n im = ax.hist2d(x, yreal, bins=[xbins, ybins], cmap=create_christmas_colormap(), norm=colors.PowerNorm(gamma=0.5))\r\n elif current_model.colormap_type == 'continuous_blue':\r\n im = ax.hist2d(x, yreal, bins=[xbins, ybins], cmap='Blues',norm=colors.PowerNorm(gamma=0.5))\r\n elif current_model.colormap_type == 'continuous_green':\r\n im = ax.hist2d(x, yreal, bins=[xbins, ybins], cmap='Greens',norm=colors.PowerNorm(gamma=0.5))\r\n qtapp.central_plot.colorbar(im[3], ax=ax)\r\n #We plot the MIC breakpoints and disk cutoffs as horizontal and vertical lines.\r\n ax.plot(horizpoints1, np.full(horizpoints1.shape[0], np.log(mic_cutoffS)), color='k', linewidth=0.5)\r\n ax.plot(horizpoints1, np.full(horizpoints1.shape[0], np.log(float(current_model.ycutoffR))), color='k', linewidth=0.5)\r\n\r\n #except:\r\n # return \"There was an unspecified error during plotting. The data plot & error count table have not been updated.\"\r\n table = ax2.table(cellText = cell_text,cellLoc='center',\r\n loc='center', colWidths=[0.4, 0.17, 0.17, 0.17, 0.17, 0.17])\r\n ax2.axis('off')\r\n generate_tabletext.fix_table(table, current_model.mic_vs_mic)\r\n qtapp.canvas.draw()\r\n return '0'\r\n","sub_path":"scripts/disk_plotting.py","file_name":"disk_plotting.py","file_ext":"py","file_size_in_byte":6791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"126893628","text":"class Index(object):\n\n def __init__(self, index_id, dimensions=None, metric=None):\n self.index_id = index_id\n if dimensions is None:\n self.dimensions = 300\n else:\n self.dimensions = dimensions\n if metric is None:\n self.metric = 'angular'\n else:\n self.metric = metric\n","sub_path":"api/Index.py","file_name":"Index.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"395549176","text":"import os\nimport sys\n\nCLI_CONFIG = {\n \"log_file\": {\"dyne\": \"__cli__\"},\n \"log_level\": {\"dyne\": \"__cli__\"},\n \"log_fmt_logfile\": {\"dyne\": \"__cli__\"},\n \"log_fmt_console\": {\"dyne\": \"__cli__\"},\n \"log_datefmt\": {\"dyne\": \"__cli__\"},\n \"log_plugin\": {\"dyne\": \"__cli__\"},\n}\n\nCONFIG = {\n \"log_file\": {\n \"dyne\": \"__cli__\",\n \"default\": f\"{os.path.splitext(os.path.split(sys.argv[0])[1])[0]}.log\",\n \"help\": \"The location of the log file\",\n \"group\": \"Logging Options\",\n },\n \"log_level\": {\n \"dyne\": \"__cli__\",\n \"default\": \"warning\",\n \"help\": \"Set the log level, either quiet, info, warning, or error\",\n \"group\": \"Logging Options\",\n },\n \"log_fmt_logfile\": {\n \"dyne\": \"__cli__\",\n \"default\": \"%(asctime)s,%(msecs)03d [%(name)-17s][%(levelname)-8s] %(message)s\",\n \"help\": \"The format to be given to log file messages\",\n \"group\": \"Logging Options\",\n },\n \"log_fmt_console\": {\n \"dyne\": \"__cli__\",\n \"default\": \"[%(levelname)-8s] %(message)s\",\n \"help\": \"The log formatting used in the console\",\n \"group\": \"Logging Options\",\n },\n \"log_datefmt\": {\n \"dyne\": \"__cli__\",\n \"default\": \"%H:%M:%S\",\n \"help\": \"The date format to display in the logs\",\n \"group\": \"Logging Options\",\n },\n \"log_plugin\": {\n \"dyne\": \"__cli__\",\n \"default\": \"basic\",\n \"help\": \"The logging plugin to use\",\n \"group\": \"Logging Options\",\n },\n}\nSUBCOMMANDS = {}\nDYNE = {\n \"config\": [\"config\"],\n \"log\": [\"log\"],\n}\n","sub_path":"python/web_pdf/project11/Lib/site-packages/pop_config/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"611699797","text":"import cv2\nimport time\nimport os\nperson_cascade = cv2.CascadeClassifier('/home/pi/peepdetect/haarcascade_fullbody.xml')\nub_cascade=cv2.CascadeClassifier('/home/pi/peepdetect/haarcascade_upperbody.xml')\nlb_cascade=cv2.CascadeClassifier('/home/pi/peepdetect/haarcascade_lowerbody.xml')\nif person_cascade.empty() or ub_cascade.empty() or lb_cascade.empty():\n\tprint('Empty classifier[s]')\n\ncap = cv2.VideoCapture(\"1.avi\")\nwhile True:\n r, frame = cap.read()\n if r:\n start_time = time.time()\n frame = cv2.resize(frame,(640,360)) # Downscale to improve frame rate\n gray_frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) # Haar-cascade classifier needs a grayscale image\n rects = person_cascade.detectMultiScale(gray_frame)\n rects2 = ub_cascade.detectMultiScale(gray_frame)\n rects3 = lb_cascade.detectMultiScale(gray_frame)\n end_time = time.time()\n #print(type(rects))\n #print(\"Elapsed Time:\",end_time-start_time)\n print(\"Number of people=\",len(rects)+len(rects2)+len(rects3))\n for (x, y, w, h) in rects:\n cv2.rectangle(frame, (x,y), (x+w,y+h),(0,255,0),2)\n for (x, y, w, h) in rects2:\n cv2.rectangle(frame, (x,y), (x+w,y+h),(0,255,0),2)\n for (x, y, w, h) in rects3:\n cv2.rectangle(frame, (x,y), (x+w,y+h),(0,255,0),2)\n frame=cv2.resize(frame,(320,180))\n cv2.imshow(\"preview\", frame)\n k = cv2.waitKey(1)\n if k & 0xFF == ord(\"q\"): # Exit condition\n break\n\n\n","sub_path":"Peopledetection/peepdetect/detect2.py","file_name":"detect2.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"486713204","text":"import requests\nimport math\nimport numpy as np\nfrom astroquery.jplhorizons import Horizons\nfrom astroquery.jplsbdb import SBDB\nfrom astropy.time import Time\nfrom astropy.table import QTable\nimport astropy.units as u\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport matplotlib.ticker as ticker\nfrom datetime import datetime\nfrom array import *\nimport re\nimport pandas as pd\n\n\"\"\"\n# This API provides access to the JPL/SSD small-body mission design suite. The following operation modes are available:\n# Mode A (accessible) - retrieves the list of accessible small bodies based on user-defined constraint.\n# Mode Q (query) - retrieves pre-computed mission options to a specific object. Both impulsive and low-thrust gravity-assist mission options are available.\n# Mode M (map) - an extension of mode Q for the impulsive case, returns the data required to render a porkchop plot with multiple parameters.\n# Mode T (mission extension) - retrieves the list of small bodies that come closest (or within a prescribed distance) to a user-defined orbit during a certain period of time. This is a crude filter for finding potential candidates for mission extensions.\n# This script emphazise the development of the following mode\n# Mode M - In addition to querying the database like in mode Q (ballistic), compute all ballistic mission options to the specified target within certain ranges of launch dates and times of flight.\n# In addition, the values of the x-y axes of the maps are also provided:\n# dep_date - departure dates from Earth (Modified Julian Date), corresponding to the x-axis.\n# tof - times of flight to the target (days), corresponding to the y-axis.\n# If dep_date has m elements and tof has n, then the 2D arrays are of dimension n x m.\n# vinf_dep\n# vinf_arr\n# Reference of the API construction, data input and output: https://ssd-api.jpl.nasa.gov/doc/mdesign.html\n\"\"\"\n\ndef get_mission_profiles(asteroid_name,mjd0,span,tof_min,tof_max,step):\n \"\"\"\n # asteroid_name: designation (provisional or IAU-number) of the desired object (e.g., 2015 AB or 141P or 433).\n # NOTE: when submitting a des containing a space in your query string, you must replace the space with %20, for example 2015%20AB\n # mjd0: first launch date to be explored (Modified Julian Date)\n # span: duration of the launch-date period to be explored (days)\n # tof-min: minimum time of flight to be considered (days)\n # tof-max: maximum time of flight to be considered (days)\n # step: time step used to advance both the launch date and the time of flight (days). \n \"\"\"\n\n # The size of the transfer map is limited to 1,500,000 points\n sim_lim_points = 1500000 #1.5 millions\n if int(span)/int(step) > sim_lim_points:\n print('outside of tool limits') # TODO return error\n \n # Construction of the HTTP request\n url_base = 'https://ssd-api.jpl.nasa.gov/mdesign.api'\n url = f'{url_base}?sstr={str(asteroid_name)}&mjd0={str(mjd0)}&span={str(span)}&tof-min={str(tof_min)}&tof-max={str(tof_max)}&step={str(step)}'\n r = requests.get(url)\n data = r.json()\n\n # Elaboration of data\n available_missions = len(data['selectedMissions'])\n mission_profiles={}\n mjd01Jan2021 = 59215\n mjd31Dec2028 = 62136\n mjd01Jan2048 = 69076\n j = 0\n for mission_id in range(available_missions):\n if (data[\"selectedMissions\"][mission_id][0] > mjd01Jan2021 and data[\"selectedMissions\"][mission_id][0] < mjd31Dec2028 and data[\"selectedMissions\"][mission_id][1] < mjd01Jan2048):\n sel_profile={\"fullname\": data[\"object\"][\"fullname\"],\n \"mjd0\": data[\"selectedMissions\"][mission_id][0],\n \"mjdf\": data[\"selectedMissions\"][mission_id][1],\n \"tof\": data[\"selectedMissions\"][mission_id][9],\n \"vinf_dep\": data[\"selectedMissions\"][mission_id][2],\n \"vinf_arr\": data[\"selectedMissions\"][mission_id][3],\n \"earth_dist\": data[\"selectedMissions\"][mission_id][5],\n \"phase_ang\": data[\"selectedMissions\"][mission_id][4], \n \"elong_arr\": data[\"selectedMissions\"][mission_id][6], \n \"decl_dep\": data[\"selectedMissions\"][mission_id][7],\n \"approach_ang\": data[\"selectedMissions\"][mission_id][8], \n }\n mission_profiles[str(j)]=sel_profile\n j = j+1\n \n # Find min dv mission profile\n mission_profile_min_dv = get_min_dv_mission_profile(mission_profiles) #mp_dv_plot removed\n \n # Porkchop data\n porkchop_dv, dep_date, tof = get_mission_porkchop(data) #pc_plot removed\n #return mission_profiles \n return mission_profiles, porkchop_dv, dep_date, tof, mission_profile_min_dv #pc_plot, , mp_dv_plot removed\n\ndef get_min_dv_mission_profile(mission_profiles):\n\n # Find the best Mission Profile\n dv = np.zeros(len(mission_profiles.keys()))\n for profile in range(len(mission_profiles)):\n dv[profile] = mission_profiles[str(profile)]['vinf_dep'] + mission_profiles[str(profile)]['vinf_arr']\n\n index = np.linspace(0,len(dv)-1,len(dv))\n mask = [dv == np.min(dv)]\n idx_min = index[tuple(mask)]\n if type(idx_min) == float:\n mission_profile_min_dv = mission_profiles[str(int(idx_min))]\n else:\n #val, idx_min = min((val, idx) for (idx, val) in enumerate(dv))\n mission_profile_min_dv = mission_profiles[str(int(idx_min[0]))] # NOTE: there could be more than one best solution, here i took arbitrarly the first\n \n # Plot of the mission profiles and highlight the best one\n # fig = plt.figure()\n # plt.plot(dv, \"*\");\n # fig.suptitle('Mission Profile dv Distribution for '+ mission_profile_min_dv[\"fullname\"])\n # plt.xlabel('$idx$ (-)')\n # plt.ylabel('$dv$ (km/s)')\n # plt.plot(int(idx_min[0]), dv[int(idx_min[0])], \"r+\");\n \n return mission_profile_min_dv#, fig\n\ndef get_mission_porkchop(data):\n\n # to pass mjd2000 to date format\n # dep_date=Time(data[\"dep_date\"], format='mjd').to_value('iso', 'date');\n dep_date=data[\"dep_date\"]\n tof=data[\"tof\"]\n \n # Elaboration of data\n m = len(dep_date)\n n = len(tof)\n porkchop_map = np.zeros([n,m]) # porkchop_map[i,j]\n for i in range(n):\n for j in range(m):\n porkchop_map[i,j]=abs(data[\"vinf_arr\"][i][j])+abs(data[\"vinf_dep\"][i][j])\n \n \"\"\"\n # Porchop Plot\n #fig, ax = plt.subplots()\n # fig = plt.figure()\n # plt.contour(dep_date, tof, porkchop_map, np.linspace(0,30,31), cmap=\"gnuplot\") # arbitrary max contour level at dv = 30 km/s\n # fig.suptitle('Porkchop Plot for '+ data[\"object\"][\"fullname\"])\n # plt.xlabel('$Date_{dep}$ (-)')\n # plt.ylabel('$ToF$ (d)') \n # plt.colorbar()\n \n # locator = mdates.MonthLocator()\n # plt.gca().xaxis.set_major_locator(locator)\n \n # plt.gcf().autofmt_xdate()\n\n # date as xtick \n # Major ticks every 6 months.\n # fmt_half_year = mdates.MonthLocator(interval=6)\n # ax.xaxis.set_major_locator(fmt_half_year)\n # Minor ticks every month.\n # fmt_month = mdates.MonthLocator()\n # ax.xaxis.set_minor_locator(fmt_month)\n # Text in the x axis will be displayed in 'YYYY-mm' format.\n #ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))\n # Rotates and right aligns the x labels, and moves the bottom of the axes up to make room for them.\n #fig.autofmt_xdate()\n \"\"\"\n\n return porkchop_map, dep_date, tof#, fig\n\n##### DO NOT RUN NOW, TO CHECK THE USE\n\"\"\"\n# Mode T - Request list of small bodies that come closest (or within a prescribed distance) to a user-specified heliocentric \n# orbit (assumes two-body dynamics). Proxy for easiest-to-reach targets for an extended mission phase.\n# example url\n# https://ssd-api.jpl.nasa.gov/mdesign.api?ec=0.2056408220896557&qr=0.3074958016246215&tp=2459067.6508400026&\n# om=48.30597718083336&w=29.18348714438387&in=7.003733902930839&jd0=2458849.5&jdf=2459132.5&maxout=100&maxdist=0.0010\n\"\"\"\n# MODE T\ndef get_close_approach_to_asteroid(orb_params,jd0,jdf,n_object_requested,distance_within):\n\n \"\"\"\n # orb_params: array containing the orbital parameters required to run the query\n # ec: eccentricity [>0]\n # qr: perihelion distance [>0]\n # tp: time of perihelion passage (JD)\n # OM: longitude of the ascending node (deg) [0,360]\n # om: argument of periapsis (deg) [0,360]\n # incl: inclination (deg) [0,180]\n # jd0: beginning of the requested time span (JD)\n # jdf: end of the requested time span (JD). Time span must not be longer than one year\n # n_object_requested: maximum number of records to be returned\n # distance_within: ignore objects with distance of closest approach greater than \"distance_within\" [>0, optional]\n \"\"\"\n\n # Extraction of inputs\n ec = orb_params[1]\n qr = orb_params[2]\n tp = orb_params[3]\n OM = orb_params[4]\n om = orb_params[5]\n incl = orb_params[6]\n \n # Construction of the HTTP request\n url_base = 'https://ssd-api.jpl.nasa.gov/mdesign.api'\n url = f'{url_base}?ec={str(ec)}&qr={str(qr)}&tp={str(tp)}&om={str(OM)}&w={str(om)}&in={str(incl)}&jd0={str(jd0)}&jdf={str(jdf)}&maxout={str(n_object_requested)}&maxdist={str(distance_within)}'\n r = requests.get(url)\n data = r.json()\n\n return data\n\n# MODE A\ndef get_accessible_sb(records_lim,optim_crit,years,sb_class,rdzvs,profile,ball_flag,lt_flag):\n\n \"\"\"\n # If ballistic missions are requested, the API expects crit to be defined. \n # If low-thrust missions are requested, the API expects profile and rdzvs to be defined.\n \n ## INPUT\n # lim: number of records to be retrieved form the SBDB\n # crit: optimality criterion for selecting ballistic missions: \n # 1) min. departure V-infinity, \n # 2) min. arrival V-infinity, \n # 3) min. total delta-V, \n # 4) min. tof + min. departure V-infinity, \n # 5) min. tof + min. arrival V-infinity, \n # 6) min. tof + min. total delta-V\n # year: launch year or list of launch years for which optimal missions are to be retrieved \n # from the SBDB [current year + [0, 20]]\n # rdzvs when requesting low-thrust missions, if rdzvs is true, only rendezvous missions are retrieved from the SBDB. \n # If false, flyby missions will be retrieved [boolean]\n # profile when requesting low-thrust missions, profile maps to the spacecraft configuration: \n # 1) Mid-size spacecraft, 2) smallsat\n \n ## OUTPUT BALLISTIC\n # name - small-body full name.\n # date0 - departure date (cal).\n # MJD0 - departure date (MJD).\n # datef - arrival date (cal).\n # MJDF - arrival date (MJD).\n # c3_dep - departure characteristic energy C3 (km^2/s^2).\n # vinf_dep - departure V-infinity (km/s).\n # vinf_arr - arrival V-infinity (km/s).\n # dv_tot - total delta-V (km/s).\n # tof - time of flight (d).\n # class - three-letter orbit class code.\n # H - absolute magnitude.\n # condition_code - orbit condition code.\n # neo - Near-Earth Object flag.\n # pha - Potentially-Hazardous Asteroid flag.\n # bin - binary flag.\n # pdes - designation.\n \n ## OUTPUT RENDEZ-VOUS\n # name - small-body full name.\n # date0 - departure date (cal).\n # MJD0 - departure date (MJD).\n # datef - arrival date (cal).\n # MJDF - arrival date (MJD).\n # c3_dep - departure characteristic energy C3 (km^2/s^2).\n # vinf_dep - departure V-infinity (km/s).\n # vinf_arr - arrival V-infinity (km/s).\n # mass_dep - departure mass.\n # mass_arr - arrival mass.\n # tof - time of flight (d).\n # nga - number of Earth gravity assists.\n # rdzvs - rendezvous flag.\n # class - three-letter orbit class code.\n # H - absolute magnitude.\n # condition_code - orbit condition code.\n # neo - Near-Earth Object flag.\n # pha - Potentially-Hazardous Asteroid flag.\n # bin - binary flag.\n # pdes - designation.\n \"\"\"\n\n url_base = 'https://ssd-api.jpl.nasa.gov/mdesign.api'\n \n if (ball_flag==1 and lt_flag == 0): # ballistic profile mission requested\n # https://ssd-api.jpl.nasa.gov/mdesign.api?lim=200&crit=1&year=2025,2026,2027,2028,2029&sb_group=neo\n # Construction of the HTTP request\n url = f'{url_base}?lim={str(records_lim)}&crit={str(optim_crit)}&year={str(years)}&sb_group={str(sb_class)}'\n elif (ball_flag == 0 and lt_flag == 1): # low thrust profile mission requested\n # https://ssd-api.jpl.nasa.gov/mdesign.api?lim=200&rdzvs=true&profile=1&year=2025,2026,2027,2028,2029&sb_class=TJN\n # Construction of the HTTP request\n url = f'{url_base}?lim={str(records_lim)}&rdzvs={str(rdzvs)}&profile={str(profile)}&year={str(years)}&sb_class={str(sb_class)}'\n \n r = requests.get(url)\n data = r.json()\n \n # Elaboration of data\n accessible_valid_sb={}\n # Definition of limit condition to consider valid small body among the accessible ones\n mjd31Dec2028 = 62136\n mjd01Jan2048 = 69076\n lim_magnitude = 28\n lim_OCC = 7\n lim_c3_dep = 15 # km^2/s^2\n \n if (ball_flag==1 and lt_flag == 0): # ballistic profile mission requested\n j = 0\n for accessible_sb in range(int(data['md_constraints']['lim'])):\n if (int(data['data'][accessible_sb][2]) < mjd31Dec2028 and int(data['data'][accessible_sb][4]) < mjd01Jan2048 and float(data['data'][accessible_sb][11]) < lim_magnitude and int(data['data'][accessible_sb][12]) < lim_OCC and float(data['data'][accessible_sb][5]) < lim_c3_dep):\n valid_sb={\"fullname\": data['data'][accessible_sb][0],\n \"mjd0\": data['data'][accessible_sb][2],\n \"mjdf\": data['data'][accessible_sb][4],\n \"c3_dep\": data['data'][accessible_sb][5],\n \"vinf_dep\": data['data'][accessible_sb][6],\n \"vinf_arr\": data['data'][accessible_sb][7],\n \"dv_tot\": data['data'][accessible_sb][8],\n \"tof\": data['data'][accessible_sb][9],\n \"class\": data['data'][accessible_sb][10],\n \"H\": data['data'][accessible_sb][11],\n \"condition_code\": data['data'][accessible_sb][12],\n }\n accessible_valid_sb[str(j)]=valid_sb\n j = j+1\n elif (ball_flag == 0 and lt_flag == 1): # low thrust profile mission requested\n j = 0\n for accessible_sb in range(int(data['md_constraints']['lim'])):\n if (int(data['data'][accessible_sb][2]) < mjd31Dec2028 and int(data['data'][accessible_sb][4]) < mjd01Jan2048 and float(data['data'][accessible_sb][14]) < lim_magnitude and int(data['data'][accessible_sb][15]) < lim_OCC and float(data['data'][accessible_sb][5]) < lim_c3_dep):\n valid_sb={\"fullname\": data['data'][accessible_sb][0],\n \"mjd0\": data['data'][accessible_sb][2],\n \"mjdf\": data['data'][accessible_sb][4],\n \"c3_dep\": data['data'][accessible_sb][5],\n \"vinf_dep\": data['data'][accessible_sb][6],\n \"vinf_arr\": data['data'][accessible_sb][7],\n \"mass_dep\": data['data'][accessible_sb][8],\n \"mass_arr\": data['data'][accessible_sb][9],\n \"tof\": data['data'][accessible_sb][10],\n \"nga\": data['data'][accessible_sb][11],\n \"rdzvs\": data['data'][accessible_sb][12],\n \"class\": data['data'][accessible_sb][13],\n \"H\": data['data'][accessible_sb][14],\n \"condition_code\": data['data'][accessible_sb][15],\n }\n accessible_valid_sb[str(j)]=valid_sb;\n j = j+1 \n\n return accessible_valid_sb\n\ndef get_min_dv_accessible_sb(accessible_valid_sb):\n\n # Find the best Mission Profile among the valid accessible small bodies\n dv = np.zeros(len(accessible_valid_sb.keys()))\n for profile in range(len(accessible_valid_sb)):\n dv[profile] = accessible_valid_sb[str(profile)]['dv_tot']\n\n index = np.linspace(0,len(dv)-1,len(dv))\n mask = [dv == np.min(dv)]\n idx_min = index[tuple(mask)]\n if type(idx_min) == float:\n accessible_sb_min_dv = accessible_valid_sb[str(int(idx_min))]\n else:\n #val, idx_min = min((val, idx) for (idx, val) in enumerate(dv))\n accessible_sb_min_dv = accessible_valid_sb[str(int(idx_min[0]))] # NOTE: there could be more than one best solution, here i took arbitrarly the first\n \n # Plot of the mission profiles and highlight the best one\n fig = plt.figure()\n plt.plot(dv, \"*\")\n fig.suptitle('Accessible Small Bodies Mission dv, and the minimum is ' + accessible_sb_min_dv[\"fullname\"])\n plt.xlabel('$idx$ (-)')\n plt.ylabel('$dv$ (km/s)')\n plt.plot(int(idx_min[0]), dv[int(idx_min[0])], \"r+\")\n \n return accessible_sb_min_dv, fig\n\n# JPL SBDB \ndef get_dict(name_list):\n\n \"\"\"\n # Return information for each bodies in name_list from JPL Small Body Database in form of dictionair\n # INPUT\n # name_list list [name1, name2, ..., nameN]\n # OUTPUT\n # dict_bodies dict with the following structure\n # str(name): \"fullname\"\n # \"our_id\" is the id inside the new dict, from 0 to N-1 where N is the name_list length\n # \"neo_flag\"\n # \"orbit_class\"\n # \"pha_flag\"\n # \"object_kind\"\n # \"moid\"\n # \"orbita_elements\"\n # \"condition_code\"\n # \"rms\"\n # \"orbit_comment\"\n # \"magn_radius_flag\" is \"H\" if the next parameter is the magnitude, is \"D\" if the next parameter is the diameter\n # \"H\" or \"D\"\n # \"spectral_category_flag\" T, S or 0\n # \"spectral_category\"\n # \"N_obs\" Number of observations\n # \"obs_span\" Time between first and last observation\n # \"impacts\": str(impact id): 'width' \n # 'energy'\n # 'stretch'\n # 'ip'\n # 'dt'\n # 'date'\n # 'sigma_lov'\n # 'h'\n # 'mass'\n # 'v_inf'\n # 'sigma_imp'\n # 'method'\n # 'ts'\n # 'diam'\n # 'dist'\n # 'v_imp'\n # 'ps'\n \"\"\"\n\n our_id=0\n dict_bodies={}\n\n for name in name_list:\n sbdb = SBDB.query(name, neo_only=True, full_precision=True, phys=True, virtual_impactor=True)\n if sbdb[\"object\"][\"kind\"]!='cn' or sbdb[\"object\"][\"kind\"]!='cu' :\n asteroid={\"fullname\": sbdb[\"object\"][\"fullname\"],# TODO vogliamo fare un check?\n \"our_id\":our_id,\n \"neo_flag\": sbdb[\"object\"][\"neo\"],\n \"orbit_class\":sbdb[\"object\"][\"orbit_class\"][\"code\"],\n \"pha_flag\":sbdb[\"object\"][\"pha\"],\n \"object_kind\":sbdb[\"object\"][\"kind\"], #an asteroid numbered au unbered asteroid (cn, cu for comet)\n \"moid\": sbdb[\"orbit\"][\"moid\"],\n \"orbital_elements\":sbdb[\"orbit\"]['elements'],\n \"condition_code\": sbdb[\"orbit\"][\"condition_code\"], #OCC\n \"rms\": sbdb[\"orbit\"][\"rms\"],\n \"orbit_comment\":sbdb[\"orbit\"][\"comment\"],\n }\n try:\n asteroid[\"magn_radius_flag\"]='H'\n asteroid[\"H\"]=sbdb['phys_par']['H']\n except:\n asteroid[\"magn_radius_flag\"]='D'\n asteroid[\"D\"]=sbdb['phys_par']['diameter']\n asteroid[\"N_obs\"]=sbdb['orbit']['n_obs_used']\n asteroid[\"obs_span\"]=sbdb['orbit']['data_arc']\n \n asteroid[\"impacts\"]={}\n flag_bool=1\n if 'phys_par' in sbdb.keys():\n spect_flag=0\n if 'spec_T' in sbdb['phys_par'].keys():\n asteroid[\"spectral_category_flag\"]='T'\n asteroid[\"spectral_category\"]=sbdb['phys_par']['spec_T']\n spect_flag=1\n if 'spec_B' in sbdb['phys_par'].keys():\n asteroid[\"spectral_category_flag\"]='B'\n asteroid[\"spectral_category\"]=sbdb['phys_par']['spec_B']\n spect_flag=1\n if spect_flag==0:\n asteroid[\"spectral_category_flag\"]='0'\n else:\n asteroid[\"spectral_category\"]='0'\n \n if 'ip' in sbdb[\"vi_data\"]:\n n_imp=len(sbdb[\"vi_data\"]['ip'])\n for key in sbdb[\"vi_data\"].keys():\n if flag_bool==1:\n for i in range(0,n_imp):\n asteroid[\"impacts\"][str(i)]={}\n flag_bool=0\n for i in range(0,n_imp): \n try:\n if isinstance(sbdb[\"vi_data\"][key],str):\n asteroid[\"impacts\"][str(i)][key]=sbdb[\"vi_data\"][key];\n else:\n asteroid[\"impacts\"][str(i)][key]=sbdb[\"vi_data\"][key][i];\n except:\n print(name+\" could raise error in importing virtual impact data\") #this exception is raised if only one impact is present\n dict_bodies[name]=asteroid\n our_id=our_id+1\n flag_bool=1\n del asteroid\n\n return dict_bodies\n \ndef extract_esa_name_from_file(file_name):\n\n f = open(file_name, \"r\")\n #f = open('NEO_API_py/' + file_name, \"r\")\n line=f.readline()\n line=f.readline()\n line=f.readline()\n line=f.readline()\n counter=0\n esa_names=[]\n for line in f:\n word=\"\"\n for c in line:\n if c==' ':\n break\n else:\n word=word+c\n esa_names.append(word); \n\n return esa_names\n\ndef get_sentry_risk_list():\n\n url = 'https://ssd-api.jpl.nasa.gov/sentry.api'\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}\n\n r = requests.get(url, headers=headers)\n data = r.json()\n sentry_risk_names=[]\n for i in range(0,len(data['data'])):\n name_=\"\"\n name=data['data'][i]['des']\n for c in name:\n if c==' ':\n a=0\n else:\n name_=name_+c\n sentry_risk_names.append(name_)\n\n return sentry_risk_names\n\ndef merge_risk_lists(esa,sentry):\n risk_list=sentry\n for risk_name in esa:\n if risk_name not in sentry:\n risk_list.append(risk_name)\n return risk_list\n\ndef refined_selection(dict_risk_list):\n\n # This function return a dictionair of asteroid satisfyng the requirements\n\n # MOID<=0.05au, H<=26 (if H is not available diameter>=200m)\n MOID_H_selected=[]\n for key in dict_risk_list.keys():\n if float(dict_risk_list[key]['moid'].scale)<=0.05: #MOID<=0.05 AU\n if (dict_risk_list[key][\"magn_radius_flag\"]=='H' and float(dict_risk_list[key][\"H\"])<=26) or (dict_risk_list[key][\"magn_radius_flag\"]=='D' and float(dict_risk_list[key][\"D\"])>=200):\n MOID_H_selected.append(key)\n\n # At least one impact 2026=-7\n date_selected=[]\n PS_date_selected=[]\n for key in dict_risk_list.keys():\n if '0' in dict_risk_list[key]['impacts'].keys():\n max_P=-100\n date_flag=0\n for imp_id in dict_risk_list[key]['impacts'].keys():\n word=''\n for c in dict_risk_list[key]['impacts'][imp_id]['date']:\n #pprint(c)\n if c=='-':\n break\n else:\n word=word+c\n if int(word)<2048 and int(word)>2026:\n date_flag=1\n if float(dict_risk_list[key]['impacts'][imp_id]['ps'])>max_P:\n max_P=float(dict_risk_list[key]['impacts'][imp_id]['ps']);\n if date_flag==1:\n date_selected.append(key)\n if max_P>=-7:\n PS_date_selected.append(key)\n dict_risk_list[key][\"PS\"]=max_P\n\n # Orbit Uncertantains filter (number of observation>=40)\n OU_selected=[]\n for key in dict_risk_list:\n if int(dict_risk_list[key]['N_obs'])>=40:\n OU_selected.append(key)\n #Intersection of filtered lists\n refined_selected=list(set(list(set(PS_date_selected) & set(MOID_H_selected))) & set(OU_selected))\n i=0\n refined_dict={}\n PS_list=[]\n for selected in refined_selected: \n PS_list.append(dict_risk_list[selected]['PS'])\n\n index_list=[i[0] for i in sorted(enumerate(PS_list), key=lambda x:x[1])]\n index_list.reverse()\n for ind in index_list:\n print(refined_selected[ind])\n print('Max Palermo Scale:' + str(PS_list[ind]))\n print('OCC:' + str(dict_risk_list[refined_selected[ind]]['condition_code']))\n refined_dict[refined_selected[ind]]={}\n refined_dict[refined_selected[ind]]=dict_risk_list[refined_selected[ind]]\n\n return(refined_dict, refined_selected)\n\ndef palermo_scale(dict_risk_list):\n # At least one impact 2026=-7\n date_selected=[]\n PS_date_selected=[]\n ps_vector=[]\n for key in dict_risk_list.keys():\n if '0' in dict_risk_list[key]['impacts'].keys():\n max_P=-100\n date_flag=0\n for imp_id in dict_risk_list[key]['impacts'].keys():\n word=''\n for c in dict_risk_list[key]['impacts'][imp_id]['date']:\n #pprint(c)\n if c=='-':\n break\n else:\n word=word+c\n if int(word)<3000 and int(word)>2021:\n date_flag=1\n if float(dict_risk_list[key]['impacts'][imp_id]['ps'])>max_P:\n max_P=float(dict_risk_list[key]['impacts'][imp_id]['ps']);\n dict_risk_list[key][\"PS\"]=max_P\n try:\n ps_vector.append(dict_risk_list[key][\"PS\"])\n except:\n print(key)\n\n return ps_vector\n\n# DB EXPLORATION TOOL\ndef MOID_H(dict_risk_list):\n\n #Earth minimum orbit instersection distance and magnitude plotting\n H_=[]\n MOID_=[]\n for key in dict_risk_list:\n try:\n H_.append(float(dict_risk_list[key]['H']))\n MOID_.append(float(dict_risk_list[key]['moid'].scale))\n except:\n print(key+' does not have magnitude info')\n x = MOID_\n y = H_\n\n \"\"\"\n # fig, ax = plt.subplots()\n # ax.plot(x,y, marker='o', linewidth=0)\n # start, end = ax.get_ylim()\n # ax.yaxis.set_ticks(np.arange(-14, 306, 20))\n # ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))\n # plt.show()\n \"\"\"\n\n return x,y\n\ndef H_OCC(dict_risk_list):\n\n #Magnitude and Orbital Condition Code plotting\n H_=[]\n OCC_=[]\n for key in dict_risk_list:\n try:\n H_.append(float(dict_risk_list[key]['H']))\n OCC_.append(int(dict_risk_list[key]['condition_code']))\n except:\n print(key+' does not have magnitude info')\n x = H_\n y = OCC_\n\n \"\"\"\n # fig, ax = plt.subplots()\n # ax.plot(x,y, marker='o', linewidth=0)\n # start, end = ax.get_ylim()\n # ax.yaxis.set_ticks(np.arange(-14, 306, 20))\n # ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))\n # plt.show()\n \"\"\"\n return x,y\n\ndef get_df_for_sbdb_visualization(dict_risk_list):\n moid=[]; occ=[]; H=[]; worse_impact_ps=[];\n idx = 0\n arbitrary_albedo = 0.14 #between 0.05 and 0.25, but most of the asteroids are on higher ranges\n for el in dict_risk_list:\n moid.append(float(dict_risk_list[str(el)]['moid'].scale))\n occ.append(int(dict_risk_list[str(el)]['condition_code']))\n try:\n H.append(float(dict_risk_list[str(el)]['H']))\n except:\n print(el +' does not have magnitude info')\n # http://www.physics.sfasu.edu/astro/asteroids/sizemagnitude.html\n H.append(float(-np.log10(dict_risk_list[str(el)]['D'].scale*np.sqrt(arbitrary_albedo)/1329)*5));\n\n #worse_impact_ps_lim = -999\n #worse_impact_ps.insert(idx, float(worse_impact_ps_lim))\n impact_ps_vect=[]\n #for i in range(len(dict_risk_list[str(el)]['impacts'])):\n # impact_ps_vect.append(float(dict_risk_list[str(el)]['impacts'][str(i)]['ps']))\n\n no_impact_detected=[]\n if len(dict_risk_list[str(el)]['impacts'])==0:\n no_impact_detected.append(str(el))\n\n #worse_impact_ps.append(max(impact_ps_vect)) \n\n idx = idx + 1\n\n #kinda_dict_physical_properties = {'moid': array(\"f\",moid), 'occ': array(\"i\",occ), \n # 'H': array(\"f\",H),'worse_impact_ps': array(\"f\",worse_impact_ps)}\n kinda_dict_physical_properties = {'moid': array(\"f\",moid), 'occ': array(\"i\",occ), \n 'H': array(\"f\",H)}\n df_physical_properties = pd.DataFrame(data=kinda_dict_physical_properties)\n\n physical_properties_name = kinda_dict_physical_properties.keys()\n\n return df_physical_properties, physical_properties_name, no_impact_detected\n\ndef bi_impulsive_mission(refined_selected, mjd0, duration, min_tof, max_tof, step_size):\n \n \"\"\"\n mjd0 MJD2000 of departure date\n duration\n min_tof minimum time of flight\n max_tof maximum time of flight\n step_size step size\n \"\"\"\n\n refined_selected_MD={}\n for name in refined_selected:\n refined_selected_MD[name]={}\n refined_selected_MD[name]['missions'], refined_selected_MD[name]['porkchop_dv'], refined_selected_MD[name]['dep_date'], refined_selected_MD[name]['tof'], refined_selected_MD[name]['mp_min_dv'] = \\\n get_mission_profiles(name,mjd0,duration,min_tof,max_tof,step_size) #removed refined_selected_MD[name]['pc_plot'], refined_selected_MD[name]['mp_dv_plot'] check order\n \n return refined_selected_MD\n\n# NASA JPL Horizons\ndef get_horizons_ephemerides(name,pov,epoch_start,epoch_stop,step_size,type_elements):\n \n # step: step size, [10m, 1d, 1y]\n \n if pov.lower() == 'sun':\n loc = '500@10' # position relative to the sun\n elif pov.lower() == 'goldstone':\n loc = '257' # from goldstone\n elif pov.lower() == 'maunakea':\n loc = '568' # maunakea\n else:\n print('Not Valid Location Point Of View')\n \n # Process to get homogeneity from main script full name '2012QD8' to a valid name for Horizon call '2012 QD8'\n if len(re.findall('([0-9])', name)) <= 4: # 4 is the min numbers in every name, the date year of discovery\n r = re.compile(\"([0-9]+)([a-zA-Z]+)\").match(name)\n k1 = r.group(1) # the date of the name\n k2 = r.group(2) # the code of the date\n valid_name = k1 + \" \" + k2 \n else:\n r = re.compile(\"([0-9]+)([a-zA-Z]+)([0-9]+)\").match(name)\n k1 = r.group(1) # the date of the name\n k2 = r.group(2) # the code of the date\n k3 = r.group(3) # id after the letters\n valid_name = k1 + \" \" + k2 + k3\n \n obj = Horizons(id=valid_name, \n location=loc, \n epochs={'start': epoch_start, 'stop':epoch_stop,\n 'step': step_size})\n \n if type_elements.lower() == 'vectors':\n data = obj.vectors() # vectorial elements\n \n len_rows = len(data)\n len_cols = 6 # 3 positions 'x','y','z', and 3 velocities 'vx', 'vy', 'vz'\n idx_x = 5 # 'x' is at position 5 in the table (starting from 0)\n adata = np.zeros([len_rows,len_cols]) \n for row in range(len_rows):\n for col in range(6): \n idx_col_in_table = idx_x + col # because the 'x' start at 6th col, going up till the 12th that is 'vz'\n adata[row,col] = data[row][idx_col_in_table]\n\n elif type_elements.lower() == 'elements':\n # refsystem = 'J2000', # Element reference system for geometric and astrometric quantities\n # refplane = 'ecliptic' #ecliptic and mean equinox of reference epoch\n data = obj.elements(refsystem = 'J2000',refplane = 'ecliptic')\n \n len_rows = len(data)\n len_cols = 6 # (a e i OM om theta)\n adata = np.zeros([len_rows,len_cols]) \n for row in range(len_rows):\n adata[row,0] = data[row][14] # 15th column of data -> semimajor axis\n adata[row,1] = data[row][5] # 6th column of data -> eccentricity\n adata[row,2] = data[row][7] # 8th column of data -> inclination\n adata[row,3] = data[row][8] # 9th column of data -> RAAN, (OMEGA)\n adata[row,4] = data[row][9] # 10th column of data -> argument of perigee, (omega)\n adata[row,5] = data[row][13] # 14th column of data -> True anomaly, (theta)\n \n return adata\n\ndef get_earth_ephemerides(epoch_start,epoch_stop,step_size,type_elements):\n \n # step: step size, [10m, 1d, 1y]\n\n obj = Horizons(id = 'Geocenter', \n location = '500@10', \n epochs = {'start': epoch_start, 'stop':epoch_stop,\n 'step': step_size},\n id_type = 'majorbody')\n \n if type_elements.lower() == 'vectors':\n data_output = obj.vectors() # vectorial elements\n elif type_elements.lower() == 'ephemerides':\n data_output = obj.ephemerides()\n \n len_rows = len(data_output)\n len_cols = 6 # 3 positions 'x','y','z', and 3 velocities 'vx', 'vy', 'vz'\n idx_x = 3 # 'x' is at position 3 in the table\n data = np.zeros([len_rows,len_cols]) \n for row in range(len_rows):\n for col in range(6): \n idx_col_in_table = idx_x + col # because the 'x' start at 3rd col, going up till the 9th that is 'vz'\n data[row,col] = data_output[row][idx_col_in_table]\n\n return data\n\n","sub_path":"Mission Analysis/TrajOptimisation/LowThrust/neo_api_function.py","file_name":"neo_api_function.py","file_ext":"py","file_size_in_byte":34995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"582603016","text":"\"\"\"\n3. 统计数字\n计算数字k在0到n中的出现的次数,k可能是0~9的一个值\n\n样例\n例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次 (1, 10, 11, 12)\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param: : An integer\n @param: : An integer\n @return: An integer denote the count of digit k in 1..n\n \"\"\"\n # time:1406 ms\n def digitCounts(self, k, n):\n # write your code here\n count = 0\n for i in range(n + 1):\n for j in str(i):\n if k == int(j):\n count += 1\n return count\n","sub_path":"算法 - 其他/枚举法/3.统计数字.py","file_name":"3.统计数字.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"595027925","text":"from util import *\n\n\n@apply\ndef apply(x_less_than_a, y_less_than_b):\n abs_x, a = x_less_than_a.of(Less)\n abs_y, b = y_less_than_b.of(Less)\n\n x = abs_x.of(Abs)\n y = abs_y.of(Abs)\n\n return Less(abs(x - y), a + b)\n\n\n@prove\ndef prove(Eq):\n from axiom import algebra\n x, y, a, b = Symbol(real=True)\n\n\n Eq << apply(abs(x) < a, abs(y) < b)\n\n Eq << algebra.lt_abs.given.et.apply(Eq[-1])\n\n Eq << algebra.lt.imply.et.split.abs.apply(Eq[0])\n\n Eq << algebra.lt.imply.et.split.abs.apply(Eq[1])\n\n Eq <<= Eq[-4] + (-Eq[-1]), Eq[-3] + (-Eq[-2])\n return\n\n\nif __name__ == '__main__':\n run()\n# created on 2020-01-07\n","sub_path":"axiom/algebra/lt/lt/imply/lt/abs/sub.py","file_name":"sub.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"246511118","text":"\n\nimport pickle\nimport numpy\nimport matplotlib.pyplot\nimport math\nimport sys\nsys.path.append(\"../tools/\")\nfrom feature_format import featureFormat, targetFeatureSplit\n\n\nwith open(\"final_project_dataset.pkl\", \"rb\") as f:\n enron_data = pickle.load(f)\n\n\n#########################################################################\n#\n# Data Exploration\n#\n#########################################################################\n\n\n### Counts of total data point and features\ntot_data_points = len(enron_data)\ntot_features = len(enron_data[\"SKILLING JEFFREY K\"])\n\n\nprint(\"Number of Data Points: \", str(tot_data_points))\nprint(\"Number of Features: \", str(tot_features))\n\n\n### Feature Lists by Data Types\nnumeric_features = ['salary', 'deferral_payments', 'total_payments', 'loan_advances', 'bonus', 'restricted_stock_deferred', 'deferred_income', 'total_stock_value', 'expenses', 'exercised_stock_options', 'other', 'long_term_incentive', 'restricted_stock', 'director_fees', 'to_messages', 'from_poi_to_this_person', 'from_messages', 'from_this_person_to_poi', 'shared_receipt_with_poi']\nbool_features = ['poi']\ntext_features = ['email_address']\norig_features = numeric_features + text_features\n\n\n### Function to count quantifiable values for feature, optional setting POI\ndef get_quantifiable_count(key, is_poi = None):\n count = 0\n for k, v in enron_data.items():\n if is_poi is not None:\n if v[key] != 'NaN' and v['poi'] == is_poi:\n count += 1\n else:\n if v[key] != 'NaN':\n count += 1\n return count\n\n### Count of POI and non-POI in data set\nint_poi_count = get_quantifiable_count('poi', True)\nint_non_poi_count = get_quantifiable_count('poi', False)\n\n\nprint(\"Number of POIs: \", str(int_poi_count))\nprint(\"Number of non-POIs: \", str(int_non_poi_count))\n\n\nquantifiable_poi = get_quantifiable_count('poi')\nquantifiable_email = get_quantifiable_count('email_address')\n\n### No missing data for POI feature - good\nprint(\"Non-NaN 'poi'\", str(quantifiable_poi))\nprint(\"Percentage of Non-NaN 'poi'\", str(float(quantifiable_poi)/float(tot_data_points)))\n\n### Some missing data for email_address feature\nprint(\"Non-NaN 'email_address'\", str(quantifiable_email))\nprint(\"Percentage of Non-NaN 'email_address'\", str(float(quantifiable_email)/float(tot_data_points)))\n\n\n### Build numpy array of count and density of non-NaN / quantifiable feature values for numeric features\norig_feature_quantifiable_count = []\norig_feature_quantifiable_density = []\norig_feature_poi_quantifiable_count = []\norig_feature_poi_quantifiable_density = []\norig_feature_non_poi_quantifiable_count = []\norig_feature_non_poi_quantifiable_density = []\n\nfor f in orig_features:\n orig_feature_quantifiable_count.append(get_quantifiable_count(f))\n orig_feature_quantifiable_density.append(round(float(get_quantifiable_count(f))/float(tot_data_points), 5))\n orig_feature_poi_quantifiable_count.append(get_quantifiable_count(f, True))\n orig_feature_poi_quantifiable_density.append(round(float(get_quantifiable_count(f, True))/float(int_poi_count), 4))\n orig_feature_non_poi_quantifiable_count.append(get_quantifiable_count(f, False))\n orig_feature_non_poi_quantifiable_density.append(round(float(get_quantifiable_count(f, False))/float(int_non_poi_count), 4))\n\norig_feature_count_density = numpy.array([\n[feature, count, density, poi_count, poi_density, non_poi_count, non_poi_density]\nfor feature, count, density, poi_count, poi_density, non_poi_count, non_poi_density in zip(orig_features, orig_feature_quantifiable_count, orig_feature_quantifiable_density, orig_feature_poi_quantifiable_count, orig_feature_poi_quantifiable_density, orig_feature_non_poi_quantifiable_count, orig_feature_non_poi_quantifiable_density)])\nprint(orig_feature_count_density)\n\n\n### Build sorted dictionary with highest number of missing data of features for each data point\n\nNaN_feature_count = {}\nfor k, v in enron_data.items():\n count = 0\n for subK, subV in v.items():\n if subV == 'NaN':\n count += 1\n if count > 16: ## if more than 16 missing examine the data point\n NaN_feature_count[k] = count\n# print(NaN_feature_count)\n\n### Sort dictionary NaN_feature_count\nsorted_NaN_feature_count = [(k, NaN_feature_count[k]) for k in sorted(NaN_feature_count, key=NaN_feature_count.get, reverse=True)]\n\nprint(\"%s got the highest count of missing data at %s\" % (max(NaN_feature_count, key=NaN_feature_count.get), str(max(NaN_feature_count.values()))))\nprint(sorted_NaN_feature_count)\n\n\n#########################################################################\n#\n# Examine and Remove Outliers by Visulization\n#\n#########################################################################\n### EDA Plotting function\ndef exploration_plot(dataset, x_feature, y_feature):\n explore_plot_features = [x_feature, y_feature]\n plt_data = featureFormat(dataset, explore_plot_features)\n\n fig = matplotlib.pyplot.figure()\n ax = fig.add_subplot(111)\n\n for point in plt_data:\n total_stock_value = point[0]\n total_payments = point[1]\n print(type(point))\n matplotlib.pyplot.scatter( total_stock_value, total_payments )\n ax.annotate('(%s, %s)' % (point[1], point[0]), xy=point, textcoords='data') # <--\n\n matplotlib.pyplot.xlabel(str(x_feature))\n matplotlib.pyplot.ylabel(str(y_feature))\n matplotlib.pyplot.show()\n\n# exploration_plot(enron_data, 'total_stock_value', 'total_payments')\n\n### Task 2: Remove outliers\nenron_data.pop(\"TOTAL\", 0) # Remove outlier predetermined from mini-project\nenron_data.pop('LOCKHART EUGENE E', 0) # has no data\nenron_data.pop('THE TRAVEL AGENCY IN THE PARK', 0) # Obviously travel agency has nothing to do with Enron\n\n# exploration_plot(enron_data, 'salary', 'other')\n# exploration_plot(enron_data, 'salary', 'bonus')\n# exploration_plot(enron_data, 'salary', 'expenses')\n# exploration_plot(enron_data, 'salary', 'exercised_stock_options')\n\n\n#########################################################################\n#\n# New Feature Creations\n#\n#########################################################################\n\n#### New Features I would like to add: ratio of total_stock_value to total_payments, ratio of exercised_stock_options to total_stock_value, ratio of from_poi_to_this_person to to_messages, ratio of from_this_person_to_poi to from_messages\n\n### Function to Compute Ratios\ndef computeRatio( numerator, denominator ):\n\n ### in case of numerator or denominator having \"NaN\" value, return 0.\n ratio = float(numerator)/float(denominator)\n ratio = ratio if not math.isnan(ratio) else 0\n return ratio\n\n\n### Task 3: Create new feature(s)\nnew_features = [\"ratio_from_poi\", \"ratio_to_poi\", \"ratio_tot_stock_value_tot_payments\", \"ratio_exercised_stock_tot_stock_value\"]\n\nfor name in enron_data:\n\n data_point = enron_data[name]\n\n from_poi_to_this_person = data_point[\"from_poi_to_this_person\"]\n to_messages = data_point[\"to_messages\"]\n from_this_person_to_poi = data_point[\"from_this_person_to_poi\"]\n from_messages = data_point[\"from_messages\"]\n\n total_stock_value = data_point[\"total_stock_value\"]\n total_payments = data_point[\"total_payments\"]\n exercised_stock_options = data_point[\"exercised_stock_options\"]\n\n ratio_from_poi = computeRatio( from_poi_to_this_person, to_messages )\n ratio_to_poi = computeRatio( from_this_person_to_poi, from_messages )\n ratio_tot_stock_value_tot_payments = computeRatio( total_stock_value, total_payments )\n ratio_exercised_stock_tot_stock_value = computeRatio( exercised_stock_options, total_stock_value )\n\n data_point[\"ratio_from_poi\"] = ratio_from_poi\n data_point[\"ratio_to_poi\"] = ratio_to_poi\n data_point[\"ratio_tot_stock_value_tot_payments\"] = ratio_tot_stock_value_tot_payments\n data_point[\"ratio_exercised_stock_tot_stock_value\"] = ratio_exercised_stock_tot_stock_value\n\nnew_feature_quantifiable_count = []\nnew_feature_quantifiable_density = []\nnew_feature_poi_quantifiable_count = []\nnew_feature_poi_quantifiable_density = []\nnew_feature_non_poi_quantifiable_count = []\nnew_feature_non_poi_quantifiable_density = []\n\nfor f in new_features:\n new_feature_quantifiable_count.append(get_quantifiable_count(f))\n new_feature_quantifiable_density.append(round(float(get_quantifiable_count(f))/float(tot_data_points), 5))\n new_feature_poi_quantifiable_count.append(get_quantifiable_count(f, True))\n new_feature_poi_quantifiable_density.append(round(float(get_quantifiable_count(f, True))/float(int_poi_count), 4))\n new_feature_non_poi_quantifiable_count.append(get_quantifiable_count(f, False))\n new_feature_non_poi_quantifiable_density.append(round(float(get_quantifiable_count(f, False))/float(int_non_poi_count), 4))\n\nnew_feature_count_density = numpy.array([\n[feature, count, density, poi_count, poi_density, non_poi_count, non_poi_density]\nfor feature, count, density, poi_count, poi_density, non_poi_count, non_poi_density in zip(new_features, new_feature_quantifiable_count, new_feature_quantifiable_density, new_feature_poi_quantifiable_count, new_feature_poi_quantifiable_density, new_feature_non_poi_quantifiable_count, new_feature_non_poi_quantifiable_density)])\nprint(new_feature_count_density)\n\n### New All Original and New Feature List\nall_features = bool_features + numeric_features + new_features\n\n### Store to my_dataset for easy export below.\nmy_dataset = enron_data\n\n\n### Extract features and labels from dataset for local testing\nprint('all_features :: ', all_features)\ndata = featureFormat(my_dataset, all_features, sort_keys = True)\nlabels, features = targetFeatureSplit(data)\n\n\n#########################################################################\n#\n# Estimators and Pipelines\n#\n#########################################################################\n\n\nfrom sklearn import preprocessing\nfrom sklearn import feature_selection\nfrom sklearn.feature_selection import chi2, f_classif, SelectKBest\nfrom sklearn.svm import SVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.decomposition import PCA\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.model_selection import GridSearchCV, train_test_split, StratifiedShuffleSplit\nfrom sklearn.metrics import classification_report, precision_score, recall_score, f1_score\nfrom pprint import pprint\nfrom time import time\n\n### Build Estimators for Pipeline\nf_minmaxscaler = preprocessing.MinMaxScaler()\nf_kbest = feature_selection.SelectKBest()\ndim_reduc = PCA(svd_solver='randomized', random_state=42)\nlnr_sv_clf = SVC(kernel=\"linear\", random_state=42)\nrbf_sv_clf = SVC(kernel=\"rbf\", random_state=42)\ndt_clf = DecisionTreeClassifier(random_state=42)\nnb_clf = GaussianNB()\nrf_clf = RandomForestClassifier(random_state=42)\nf_union = FeatureUnion([(\"kbest\", f_kbest), (\"pca\", dim_reduc)])\n\n\n### First I tried to perform quick fit and score for different order and combinations of estimators and classifiers with pipeline and feature_union.\n\n### Scaler, [pca then kbest / kbest then pca], linear svc\nest_pipe_lnr_sv = [('f_scaler', f_minmaxscaler), ('dim_reduc', dim_reduc), ('f_kbest', f_kbest), ('lnr_sv_clf', lnr_sv_clf)]\nest_pipe_lnr_sv = [('f_scaler', f_minmaxscaler), ('f_kbest', f_kbest), ('dim_reduc', dim_reduc), ('lnr_sv_clf', lnr_sv_clf)]\npipe_lnr_sv = Pipeline(est_pipe_lnr_sv)\n\n### Scaler, [pca then kbest / kbest then pca], rbf svc\nest_pipe_rbf_sv = [('f_scaler', f_minmaxscaler), ('dim_reduc', dim_reduc), ('f_kbest', f_kbest), ('rbf_sv_clf', rbf_sv_clf)]\n# est_pipe_rbf_sv = [('f_scaler', f_minmaxscaler), ('f_kbest', f_kbest), ('dim_reduc', dim_reduc), ('rbf_sv_clf', rbf_sv_clf)]\npipe_rbf_sv = Pipeline(est_pipe_rbf_sv)\n\n### Scaler, [pca then kbest / kbest then pca], decision tree classifier\nest_pipe_dt = [('f_scaler', f_minmaxscaler), ('dim_reduc', dim_reduc), ('f_kbest', f_kbest), ('dt_clf', dt_clf)]\n# est_pipe_dt = [('f_scaler', f_minmaxscaler), ('f_kbest', f_kbest), ('dim_reduc', dim_reduc), ('dt_clf', dt_clf)]\npipe_dt = Pipeline(est_pipe_dt)\n\n### Scaler, [pca then kbest / kbest then pca], gaussian naive bayes classifier\nest_pipe_nb = [('f_scaler', f_minmaxscaler), ('dim_reduc', dim_reduc), ('f_kbest', f_kbest), ('nb_clf', nb_clf)]\n# est_pipe_nb = [('f_scaler', f_minmaxscaler), ('f_kbest', f_kbest), ('dim_reduc', dim_reduc), ('nb_clf', nb_clf)]\npipe_nb = Pipeline(est_pipe_nb)\n\n### Scaler, [pca then kbest / kbest then pca], random forest classifier\nest_pipe_rf = [('f_scaler', f_minmaxscaler), ('dim_reduc', dim_reduc), ('f_kbest', f_kbest), ('rf_clf', rf_clf)]\n# est_pipe_rf = [('f_scaler', f_minmaxscaler), ('f_kbest', f_kbest), ('dim_reduc', dim_reduc), ('rf_clf', rf_clf)]\npipe_rf = Pipeline(est_pipe_rf)\n\n### Scaler, featureUnion[pca & kbest], linear svc\nest_funion_lnr_sv = [('f_scaler', f_minmaxscaler), ('f_union', f_union), ('lnr_sv_clf', lnr_sv_clf)]\nfunion_lnr_sv = Pipeline(est_funion_lnr_sv)\n\n### Scaler, featureUnion[pca & kbest], rbf svc\nest_funion_rbf_sv = [('f_scaler', f_minmaxscaler), ('f_union', f_union), ('rbf_sv_clf', rbf_sv_clf)]\nfunion_rbf_sv = Pipeline(est_funion_rbf_sv)\n\n### Scaler, featureUnion[pca & kbest], random forest classifier\nest_funion_rf = [('f_scaler', f_minmaxscaler), ('f_union', f_union), ('rf_clf', rf_clf)]\nfunion_rf = Pipeline(est_funion_rf)\n\nestimators = [est_pipe_lnr_sv, est_pipe_rbf_sv, est_pipe_dt, est_pipe_nb, est_pipe_rf, est_funion_lnr_sv, est_funion_rbf_sv, est_funion_rf]\npipes = [pipe_lnr_sv, pipe_rbf_sv, pipe_dt, pipe_nb, pipe_rf, funion_lnr_sv, funion_rbf_sv, funion_rf]\n\nfeatures_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.3, random_state=42)\n\n\n### Quick run with training set to roughly select the model with highest f1, precision and recall scores\nfor estimator, pipe in zip(estimators, pipes):\n print(\"\\n=================================================================\")\n for name, est in estimator:\n print(\"\\nParameters for \", name, \" :: \\n\", est.get_params().keys())\n\n\n pipe.fit(features_train, labels_train)\n labels_pred = pipe.predict(features_test)\n clf_reports = classification_report(labels_test, labels_pred)\n print(\"\\nClassification Report for \", name, \"\\n\", clf_reports)\n print(\"\\n=================================================================\")\n\n\n################################################################################\n# The 3 following gives the best scores (See attached text files):\n# 1) scaler, pca, kbest, random forest classifier (f1: 0.88, recall: 0.91, precision: 0.92)\n# 2) scales, kbest, pca, random forest classifier (f1: 0.88, recall: 0.88, precision: 0.87)\n# 3) scales, f_union(pca, kbest), linear svc (f1: 0.88, recall: 0.88, precision: 0.87)\n################################################################################\n\n### Scaler, pca, kbest, random forest classifier\nest_pipe_pca_kbest_rf = [('f_scaler', f_minmaxscaler), ('dim_reduc', dim_reduc), ('f_kbest', f_kbest), ('rf_clf', rf_clf)]\npipe_pca_kbest_rf = Pipeline(est_pipe_pca_kbest_rf)\n\n### Scaler, kbest, pca, random forest classifier\nest_pipe_kbest_pca_rf = [('f_scaler', f_minmaxscaler), ('f_kbest', f_kbest), ('dim_reduc', dim_reduc), ('rf_clf', rf_clf)]\npipe_kbest_pca_rf = Pipeline(est_pipe_kbest_pca_rf)\n\n### Scaler, featureUnion[pca & kbest], linear svc\nest_funion_lnr_sv = [('f_scaler', f_minmaxscaler), ('f_union', f_union), ('lnr_sv_clf', lnr_sv_clf)]\nfunion_lnr_sv = Pipeline(est_funion_lnr_sv)\n\n\n#### Setting Param_Grids for GridSearchCV ####\n#########\n# params_pipe_lnr_sv = dict(\n# dim_reduc__n_components = [3, 5, 7, 10, 13, 17],\n# f_kbest__k = [1, 3, 5, 10, 13],\n# f_kbest__score_func = [f_classif, chi2],\n# lnr_sv_clf__C = [0.01, 1, 10, 100]\n# )\n# params_pipe_rbf_sv = dict(\n# dim_reduc__n_components = [3, 5, 7, 10, 13, 17],\n# f_kbest__k = [1, 3, 5, 10, 13],\n# f_kbest__score_func = [f_classif, chi2],\n# rbf_sv_clf__C = [0.01, 1, 10, 100],\n# rbf_sv_clf__gamma = [0.001, 0.01, 0.1]\n# )\n# params_pipe_dt = dict(\n# dim_reduc__n_components = [3, 5, 7, 10, 13, 17],\n# f_kbest__k = [1, 3, 5, 10, 13],\n# f_kbest__score_func = [f_classif, chi2],\n# dt_clf__criterion = ['gini', 'entropy'],\n# dt_clf__max_depth = [10, 15, 20, 25, 30]\n# )\n# params_pipe_nb = dict(\n# dim_reduc__n_components = [3, 5, 7, 10, 13, 17],\n# f_kbest__k = [1, 3, 5, 10, 13],\n# f_kbest__score_func = [f_classif, chi2]\n# )\nparams_pipe_rf = dict(\ndim_reduc__n_components = [3, 5, 7, 10, 13, 17],\nf_kbest__k = ['all', 1, 3, 5, 10, 13],\nf_kbest__score_func = [f_classif, chi2],\nrf_clf__n_estimators = [2, 5, 7, 10],\nrf_clf__criterion = ['gini', 'entropy'],\nrf_clf__max_depth = [10, 15, 20, 25, 30]\n)\nparams_funion_lnr_sv = dict(\nf_union__pca__n_components = [3, 5, 7, 10, 13, 17],\nf_union__kbest__k = [1, 3, 5, 10, 13],\nf_union__kbest__score_func = [f_classif, chi2],\nlnr_sv_clf__C = [0.001]\n)\n# params_funion_rbf_sv = dict(\n# f_union__pca__n_components = [3, 5, 7, 10, 13, 17],\n# f_union__kbest__k = [1, 3, 5, 10, 13],\n# f_union__kbest__score_func = [f_classif, chi2],\n# rbf_sv_clf__C = [0.01, 1, 10, 100],\n# rbf_sv_clf__gamma = [0.001, 0.01, 0.1]\n# )\n# params_funion_rf = dict(\n# f_union__pca__n_components = [3, 5, 7, 10, 13, 17],\n# f_union__kbest__k = [1, 3, 5, 10, 13],\n# f_union__kbest__score_func = [f_classif, chi2],\n# rf_clf__n_estimators = [2, 5, 7, 10],\n# rf_clf__criterion = ['gini', 'entropy'],\n# rf_clf__max_depth = [10, 15, 20, 25, 30]\n# )\n\n# params = [params_pipe_lnr_sv, params_pipe_rbf_sv, params_pipe_dt, params_pipe_nb, params_pipe_rf, params_funion_lnr_sv, params_funion_rbf_sv, params_funion_rf]\n\ngrid_search_estimators = [est_pipe_pca_kbest_rf, est_pipe_kbest_pca_rf, est_funion_lnr_sv]\ngrid_search_pipes = [pipe_pca_kbest_rf, pipe_kbest_pca_rf, funion_lnr_sv]\ngrid_search_params = [params_pipe_rf, params_pipe_rf, params_funion_lnr_sv]\n\ncv = StratifiedShuffleSplit(n_splits=100, random_state=42, test_size=0.1)\n\nfor estimator, pipe, paramgrid in zip(grid_search_estimators, grid_search_pipes, grid_search_params):\n print(\"\\n=================================================================\")\n grid_search = GridSearchCV(pipe, param_grid=paramgrid, cv=cv, scoring='f1', verbose=10, n_jobs=-1, error_score=0)\n\n print(\"Performing grid search...\")\n print(\"pipeline:\", [name for name, _ in pipe.steps])\n print(\"parameters:\")\n pprint(paramgrid)\n t0 = time()\n grid_search.fit(features, labels)\n print(\"done in %0.3fs\" % (time() - t0))\n print()\n\n print(\"Best score: %0.3f\" % grid_search.best_score_)\n best_estimator = grid_search.best_estimator_\n print(\"Best estimator pipeline: \", best_estimator)\n print(\"Best parameters set:\")\n best_parameters = best_estimator.get_params()\n for param_name in sorted(paramgrid.keys()):\n print(\"\\t%s: %r\" % (param_name, best_parameters[param_name]))\n\n pred = grid_search.predict(features_test)\n print('Precision:', precision_score(labels_test, pred))\n print('Recall:', recall_score(labels_test, pred))\n print('F1 Score:', f1_score(labels_test, pred))\n print(\"\\n=================================================================\")\n # grid_search_best = grid_search.best_estimator_\n # features_selected=[all_features[i+1] for i in grid_search_best.named_steps['f_union__kbest'].get_support(indices=True)]\n\n\nexit()\n\ngrid_search = GridSearchCV(pipe_pca_kbest_rf, param_grid=params_pipe_rf, cv=cv, scoring='f1', verbose=10, error_score=0)\n\nprint(\"Performing grid search...\")\nprint(\"pipeline:\", [name for name, _ in pipe_pca_kbest_rf.steps])\nprint(\"parameters:\")\npprint(params_pipe_rf)\nt0 = time()\ngrid_search.fit(features, labels)\nprint(\"done in %0.3fs\" % (time() - t0))\nprint()\n\nprint(\"Best score: %0.3f\" % grid_search.best_score_)\nbest_estimator = grid_search.best_estimator_\nprint(\"Best estimator pipeline: \", best_estimator)\nprint(\"Best parameters set: \")\nbest_parameters = grid_search.best_estimator_.get_params()\nfor param_name in sorted(params_pipe_rf.keys()):\n print(\"\\t%s: %r\" % (param_name, best_parameters[param_name]))\n\npred = grid_search.predict(features_test)\nprint('Precision:', precision_score(labels_test, pred))\nprint('Recall:', recall_score(labels_test, pred))\nprint('F1 Score:', f1_score(labels_test, pred))\n\n\n\n# Access the SelectKBest features selected\n\n# create a new list that contains the features selected by SelectKBest\n# in the optimal model selected by GridSearchCV\nfeatures_selected=[all_features[i+1] for i in best_estimator.named_steps['f_kbest'].get_support(indices=True)]\n\n# Access the feature importances\n\n# The step in the pipeline for the Decision Tree Classifier is called 'DTC'\n# that step contains the feature importances\nimportances = best_estimator.named_steps['rf_clf'].feature_importances_\nindices = numpy.argsort(importances)[::-1]\n\n# Use features_selected, the features selected by SelectKBest, and not features_list\nprint('Feature Ranking: ')\nfor i in range(len(features_selected)):\n print(\"feature no. {}: {} ({})\".format(i+1,features_selected[indices[i]],importances[indices[i]]))\n\n# print(\"best_estimator_\", \"::\", grid_search.best_estimator_)\n# print(\"best_score_\", \"::\", grid_search.best_score_)\n# print(\"best_params_\", \"::\", grid_search.best_params_)\n\nmy_clf = best_estimator\nmy_feature_list = features_selected\n# from sklearn.svm import SVC\n# from sklearn.decomposition import PCA\n# estimators = [('reduce_dim', PCA()), ('clf', SVC())]\n# pipe = Pipeline(estimators)\n# pipe\n# Pipeline(steps=[('reduce_dim', PCA(copy=True, iterated_power='auto',\n# n_components=None, random_state=None, svd_solver='auto', tol=0.0,\n# whiten=False)), ('clf', SVC(C=1.0, cache_size=200, class_weight=None,\n# coef0=0.0, decision_function_shape=None, degree=3, gamma='auto',\n# kernel='rbf', max_iter=-1, probability=False, random_state=None,\n# shrinking=True, tol=0.001, verbose=False))])\n\n# ### Task 4: Try a varity of classifiers\n# ### Please name your classifier clf for easy export below.\n# ### Note that if you want to do PCA or other multi-stage operations,\n# ### you'll need to use Pipelines. For more info:\n# ### http://scikit-learn.org/stable/modules/pipeline.html\n#\n# # Provided to give you a starting point. Try a variety of classifiers.\n# from sklearn.naive_bayes import GaussianNB\n# clf = GaussianNB()\n\n### Task 5: Tune your classifier to achieve better than .3 precision and recall\n### using our testing script. Check the tester.py script in the final project\n### folder for details on the evaluation method, especially the test_classifier\n### function. Because of the small size of the dataset, the script uses\n### stratified shuffle split cross validation. For more info:\n### http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html\n\n# Example starting point. Try investigating other evaluation techniques!\n# from sklearn.cross_validation import train_test_split\n# from sklearn.model_selection import train_test_split\n# features_train, features_test, labels_train, labels_test = \\\n# train_test_split(features, labels, test_size=0.3, random_state=42)\n\n### Task 6: Dump your classifier, dataset, and features_list so anyone can\n### check your results. You do not need to change anything below, but make sure\n### that the version of poi_id.py that you submit can be run on its own and\n### generates the necessary .pkl files for validating your results.\nmy_clf = best_estimator\nmy_feature_list = features_selected\nfrom tester import dump_classifier_and_data\ndump_classifier_and_data(my_clf, my_dataset, my_feature_list)\n","sub_path":"final_project/poi_id0.py","file_name":"poi_id0.py","file_ext":"py","file_size_in_byte":23544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"441520818","text":"#!/usr/bin/env python3\n\"\"\"\nANDES, a power system simulation tool for research.\n\nCopyright 2015-2017 Hantao Cui\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport os\nimport glob\nimport io\nimport pstats\nimport cProfile\nfrom time import sleep\nfrom multiprocessing import Process\nfrom argparse import ArgumentParser\n\nfrom . import filters\nfrom .consts import *\nfrom .system import PowerSystem\nfrom .utils import elapsed\nfrom .variables import preamble\nfrom .routines import powerflow, timedomain\n\n\ndef cli_parse(writehelp=False, helpfile=None):\n \"\"\"command line input argument parser\"\"\"\n\n parser = ArgumentParser(prog='andes')\n parser.add_argument('casename', nargs='*', default=[], help='Case file name.')\n\n # program general options\n parser.add_argument('-x', '--exit', help='Exit before solving the power flow. Enable this option to '\n 'use andes ad a file format converter.', action='store_true')\n parser.add_argument('--no_preamble', action='store_true', help='Hide preamble')\n parser.add_argument('--license', action='store_true', help='Display MIT license and exit.')\n parser.add_argument('--version', action='store_true', help='Print current andes version and exit.')\n parser.add_argument('--warranty', action='store_true', help='Print warranty info and exit.')\n parser.add_argument('--what', action='store_true', help='Show me something and exit', default=None)\n parser.add_argument('-n', '--no_output', help='Force not to write any output, including log,'\n 'outputs and simulation dumps', action='store_true')\n parser.add_argument('--profile', action='store_true', help='Enable Python profiler.')\n\n parser.add_argument('-l', '--log', help='Specify the name of log file.')\n parser.add_argument('-d', '--dat', help='Specify the name of file to save simulation results.')\n parser.add_argument('-v', '--verbose', help='Program logging level, an integer from 1 to 5.'\n 'The level corresponding to TODO=0, DEBUG=10, INFO=20, WARNING=30,'\n 'ERROR=40, CRITICAL=50, ALWAYS=60. The default verbose level is 2.',\n type=int)\n\n # file and format related\n parser.add_argument('-c', '--clean', help='Clean output files and exit.', action='store_true')\n parser.add_argument('-K', '--cleanall', help='Clean all output and auxillary files.', action='store_true')\n parser.add_argument('-p', '--path', help='Path to case files', default='')\n parser.add_argument('-s', '--settings', help='Specify a setting file. This will take precedence of .andesrc '\n 'file in the home directory.')\n parser.add_argument('-i', '--input_format', help='Specify input case file format.')\n parser.add_argument('-o', '--output_format', help='Specify output case file format. For example txt, latex.')\n parser.add_argument('-O', '--output', help='Specify the output file name. For different routines the same name'\n 'as the case file with proper suffix and extension wil be given.')\n parser.add_argument('-a', '--addfile', help='Include additional files used by some formats.')\n parser.add_argument('-D', '--dynfile', help='Include an additional dynamic file in dm format.')\n parser.add_argument('-J', '--gis', help='JML format GIS file.')\n parser.add_argument('-m', '--map', help='Visualize power flow results on GIS. Neglected if no GIS file is given.')\n parser.add_argument('-e', '--dump_raw', help='Dump RAW format case file.') # consider being used as batch converter\n parser.add_argument('-Y', '--summary', help='Show summary and statistics of the data case.', action='store_true')\n\n # Solver Options\n parser.add_argument('-r', '--routine', help='Routine after power flow solution: t[TD], c[CPF], s[SS], o[OPF].')\n parser.add_argument('-j', '--checkjacs', help='Check analytical Jacobian using numerical differentation.')\n\n # helps and documentations\n parser.add_argument('-u', '--usage', help='Write command line usage', action='store_true')\n parser.add_argument('-C', '--category', help='Dump device names belonging to the specified category.')\n parser.add_argument('-L', '--dev_list', help='Dump the list of all supported devices.', action='store_true')\n parser.add_argument('-f', '--dev_format', help='Dump the format definition of all devices.', action='store_true')\n parser.add_argument('-W', '--dev_variables', help='Dump the variables of a specified device.')\n parser.add_argument('-G', '--group', help='Dump all the devices in the specified group.', action='store_true')\n parser.add_argument('-q', '--quick_help', help='Print a quick help of the device.')\n parser.add_argument('--help_option', help='Print a quick help of a setting parameter')\n parser.add_argument('--help_settings', help='Print a quick help of a given setting class. Use ALL'\n 'for all setting classes.')\n parser.add_argument('-S', '--search', help='Search devices that match the given expression.')\n\n if writehelp:\n try:\n usagefile = open(helpfile, 'w')\n usagefile.writelines('[ANDES] Command Line Usage Help\\n\\n')\n parser.print_help(file=usagefile)\n usagefile.close()\n print('--> Command line usage written to file.')\n except IOError:\n print('I/O exception while writing help file.')\n return\n else:\n args = parser.parse_args()\n return args\n\n\ndef dumphelp(usage=None, group=None, category=None, dev_list=None, dev_format=None, dev_variables=None,\n quick_help=None, help_option=None, help_settings=None, **kwargs):\n if usage:\n cli_parse(writehelp=True, helpfile='cli_help.txt')\n if category:\n pass\n if dev_list:\n pass\n if dev_format:\n pass\n if dev_variables:\n pass\n if group:\n pass\n if quick_help:\n pass\n if help_option:\n pass\n if help_settings:\n pass\n\n\ndef cleanup(clean=False, cleanall=False):\n \"\"\"Clean up function for generated files\"\"\"\n if not (clean or cleanall):\n return\n if clean:\n pass\n if cleanall:\n pass\n\n\ndef main():\n \"\"\"Entry function\"\"\"\n t0, s = elapsed()\n args = cli_parse()\n cases = []\n kwargs = {}\n\n # run clean-ups and exit\n if args.clean or args.cleanall:\n cleanup(args.clean, args.cleanall)\n return\n\n # extract case names\n for item in args.casename:\n cases += glob.glob(os.path.join(args.path, item))\n args.casename = None\n\n # extract all arguments\n for arg, val in vars(args).items():\n if val is not None:\n kwargs[arg] = val\n\n # dump help and exit\n if dumphelp(**kwargs):\n return\n\n # exit if no case specified\n if len(cases) == 0:\n print(preamble(args.no_preamble))\n print('--> No valid data file or action is defined.')\n return\n\n # single case study\n elif len(cases) == 1:\n run(cases[0], **kwargs)\n t1, s = elapsed(t0)\n print('--> Single process finished in {0:s}.'.format(s))\n return\n\n # multiple studies on multiple processors\n else:\n jobs = []\n kwargs['verbose'] = ERROR\n for idx, casename in enumerate(cases):\n kwargs['pid'] = idx\n job = Process(name='Process {0:d}'.format(idx), target=run, args=(casename,), kwargs=kwargs)\n jobs.append(job)\n job.start()\n\n sleep(0.1)\n for job in jobs:\n job.join()\n t0, s0 = elapsed(t0)\n print('--> Multiple processing finished in {0:s}.'.format(s0))\n return\n\n\ndef run(case, **kwargs):\n \"\"\"Run a single case study\"\"\"\n profile = kwargs.pop('profile', False)\n dump_raw = kwargs.pop('dump_raw', False)\n summary = kwargs.pop('summary', False)\n exitnow = kwargs.pop('exit', False)\n no_preamble = kwargs.pop('no_preamble', False)\n pid = kwargs.get('pid', -1)\n pr = cProfile.Profile()\n\n # enable profiler if requested\n if profile:\n pr.enable()\n\n # create a power system object\n system = PowerSystem(case, **kwargs)\n\n # print preamble\n if pid == -1:\n system.Log.info(preamble(no_preamble))\n\n t0, _ = elapsed()\n\n # parse input file\n if not filters.guess(system):\n system.Log.error('Unable to determine case format.')\n return\n if not filters.parse(system):\n system.Log.error('Parse input file failed.')\n return\n\n t1, s = elapsed(t0)\n system.Log.info('Case file {:s} parsed in {:s}.'.format(system.Files.fullname, s))\n\n # dump system as raw file if requested\n if dump_raw:\n if filters.dump_raw(system):\n t2, s = elapsed(t1)\n system.Log.info('Raw dump {:s} written in {:s}.'.format(system.Files.dump_raw, s))\n else:\n system.Log.error('Dump raw file failed.')\n\n # print summary only\n if summary:\n t2, s = elapsed(t1)\n system.Report.writey(content='summary')\n system.Log.info('Summary of written in {:s}'.format(s))\n return\n\n # exit without solving power flow\n if exitnow:\n system.Log.info('Exiting before solving power flow.')\n return\n\n # set up everything in system\n system.setup()\n\n # per-unitize parameters\n if system.Settings.base:\n system.base()\n\n # initialize power flow study\n system.init_pf()\n t2, s = elapsed(t1)\n system.Log.info('System models initialized in {:s}.\\n'.format(s))\n\n # check for bus islanding\n system.check_islands()\n\n if len(system.Bus.islanded_buses) == 0 and len(system.Bus.island_sets) == 0:\n system.Log.info('System is interconnected.\\n')\n else:\n system.Log.info('System contains {:d} islands and {:d} islanded buses.\\n'.format\n (len(system.Bus.island_sets), len(system.Bus.islanded_buses)))\n\n # Choose PF solver and run_pf\n if system.SPF.solver.lower() not in powerflow.solvers.keys():\n system.SPF.solver = 'NR'\n\n system.Log.info('Power Flow Analysis:')\n system.Log.info('Sparse Library: ' + system.Settings.sparselib.upper())\n system.Log.info('Solution Method: ' + system.SPF.solver.upper())\n system.Log.info('Flat-start: ' + ('Yes' if system.SPF.flatstart else 'No') + '\\n')\n\n powerflow.run(system)\n t3, s = elapsed(t2)\n if not system.SPF.solved:\n system.Log.info('Power flow failed to converge in {:s}.'.format(s))\n else:\n system.Log.info('Power flow converged in {:s}.'.format(s))\n system.td_init() # initialize variables for output even if not running TDS\n t4, s = elapsed(t3)\n if system.DAE.n:\n system.Log.info('Dynamic models initialized in {:s}.'.format(s))\n else:\n system.Log.info('No dynamic model loaded.')\n if not system.Files.no_output:\n system.Report.write(content='powerflow')\n t5, s = elapsed(t4)\n system.Log.info('Static report written in {:s}.'.format(s))\n\n # run more studies\n t0, s = elapsed()\n routine = kwargs.pop('routine', None)\n if not routine:\n pass\n elif routine.lower() in ['time', 'td', 't']:\n routine = 'td'\n elif routine.lower() in ['cpf', 'c']:\n routine = 'cpf'\n elif routine.lower() in ['small', 'ss', 'sssa', 's']:\n routine = 'sssa'\n if routine is 'td':\n t1, s = elapsed(t0)\n system.Log.info('')\n system.Log.info('Time Domain Simulation:')\n system.Log.info('Integration Method: {0}'.format(system.TDS.method))\n timedomain.run(system)\n t2, s = elapsed(t1)\n system.Log.info('Time domain simulation finished in {:s}.'.format(s))\n if not system.Files.no_output:\n system.VarOut.dump()\n t3, s = elapsed(t2)\n system.Log.info('Simulation data dumped in {:s}.'.format(s))\n\n # Disable profiler and output results\n if profile:\n pr.disable()\n if system.Files.no_output:\n s = io.StringIO()\n nlines = 20\n ps = pstats.Stats(pr, stream=s).sort_stats('time')\n ps.print_stats(nlines)\n print(s.getvalue())\n s.close()\n else:\n s = open(system.Files.prof, 'w')\n nlines = 50\n ps = pstats.Stats(pr, stream=s).sort_stats('time')\n ps.print_stats(nlines)\n s.close()\n system.Log.info('cProfile results for job{:s} written.'.format(' ' + str(pid) if pid >= 0 else ''))\n\n if pid >= 0:\n t3, s = elapsed(t0)\n system.Log.always('Process {:d} finished in {:s}.'.format(pid, s))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"andes/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"3900790","text":"from collections.abc import MutableSequence\nfrom typing import Any\n\nimport proto\n\nfrom google.ads.googleads.v12.common.types.audiences import (\n AudienceDimension,\n AudienceExclusionDimension,\n)\nfrom google.ads.googleads.v12.enums.types.audience_status import AudienceStatusEnum\n\nclass Audience(proto.Message):\n resource_name: str\n id: int\n status: AudienceStatusEnum.AudienceStatus\n name: str\n description: str\n dimensions: MutableSequence[AudienceDimension]\n exclusion_dimension: AudienceExclusionDimension\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n resource_name: str = ...,\n id: int = ...,\n status: AudienceStatusEnum.AudienceStatus = ...,\n name: str = ...,\n description: str = ...,\n dimensions: MutableSequence[AudienceDimension] = ...,\n exclusion_dimension: AudienceExclusionDimension = ...\n ) -> None: ...\n","sub_path":"google-stubs/ads/googleads/v12/resources/types/audience.pyi","file_name":"audience.pyi","file_ext":"pyi","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"253861876","text":"# -*- coding: utf-8 -*-\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nimport time\r\nimport pywinauto\r\nfrom pywinauto.keyboard import send_keys\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport os\r\nimport random\r\nfrom selenium.webdriver.remote import switch_to\r\nfrom selenium.webdriver.support.expected_conditions import frame_to_be_available_and_switch_to_it\r\nfrom test.test_ssl import handle_error\r\nimport pyodbc\r\n\r\n\r\ndef login():\r\n\t# Login\r\n\td.find_element_by_link_text('登陆').click()\r\n\ttime.sleep(3)\r\n\td.find_element_by_name('username').send_keys(\"tangren\")\r\n\t# time.sleep(3)\r\n\td.find_element_by_name('password').send_keys('jian1980_')\r\n\t# time.sleep(3)\r\n\td.find_element_by_name('loginsubmit').click()\r\n\r\n\r\n# # 随机验证码\r\n# def yzm(len=6):\r\n# code_list = []\r\n# for i in range(10): # 0-9数字\r\n# code_list.append(str(i))\r\n# for i in range(65, 91): # 对应从“A”到“Z”的ASCII码\r\n# code_list.append(chr(i))\r\n# for i in range(97, 123): # 对应从“a”到“z”的ASCII码\r\n# code_list.append(chr(i))\r\n# myslice = random.sample(code_list, len) # 从list中随机获取6个元素,作为一个片断返回\r\n# verification_code = ''.join(myslice) # list to string\r\n# return verification_code\r\n\r\n\r\ndef connect_db_read_post():\r\n\t#链接数据库\r\n\t#db_path是access文件的绝对路径\r\n\tdb_path = r'D:\\Download\\Database1.accdb'\r\n\tconn = pyodbc.connect(u'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+ db_path)\r\n\t#创建游标\r\n\tcursor = conn.cursor()\r\n\ttry:\r\n\t\tcur = cursor.execute(\"SELECT * FROM local_news_cn_table WHERE published = 0\")\r\n\t\t# 获取数据库中表的全部数据\r\n\t\tdata = cur.fetchall()\r\n\t\tif data:\r\n\t\t\td = open_Driver()\r\n\t\t\tfor row in data:\r\n\t\t\t\turl = row[0]\r\n\t\t\t\ttitle = row[1]\r\n\t\t\t\tdate_publish = row[2]\r\n\t\t\t\tsource = row[3]\r\n\t\t\t\toriginal_author = row[4]\r\n\t\t\t\tcontent = row[5]\r\n\t\t\t\ttry:\r\n\t\t\t\t\tpost(d, url, title, date_publish, source, original_author, content)\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tcursor.execute(\"UPDATE local_news_cn_table SET published = -1 WHERE url = '%s'\" % url)\r\n\t\t\t\t\t\tconn.commit()\r\n\t\t\t\t\t\tprint(url + \" 文章已经发表到网站且数据库已经更新发表状态\")\r\n\t\t\t\t\texcept Exception as ex:\r\n\t\t\t\t\t\tprint(\"出现如下异常: %s\" % ex)\r\n\t\t\t\t\t\tprint(url + \" 文章已经发表到网站但数据库更新发表状态失败\")\r\n\t\t\t\texcept Exception as ex:\r\n\t\t\t\t\tprint(\"出现如下异常: %s\" % ex)\r\n\t\t\t\t\tprint(url + \" 文章发表到网站失败\")\r\n\t\telse:\r\n\t\t\tprint(\"当前数据库表中所有文章均被发表\")\r\n\texcept Exception as ex:\r\n\t\tprint(\"出现如下异常: %s\" % ex)\r\n\t\tprint(\"Error: ubale to fetch data\")\r\n\tcursor.close()\r\n\tconn.close()\r\n\r\n\r\n\r\ndef windows_pop_up(file_name):\r\n\t#处理Windows窗口事件\r\n\tapp = pywinauto.Desktop()\r\n\tdlg = app['Open']\r\n\tdlg['File name:Edit'].type_keys(file_name)\r\n\tdlg['Open'].click()\r\n\ttime.sleep(8)\r\n\r\n\r\n\r\ndef post(d, url, title, date_publish, source, original_author, content):\r\n\tdirectory = r\"D:\\Desktop\\img_local_news\" + '\\\\' + url.split('/')[-2]\r\n\tc = 1\r\n\tcc = 1\r\n\t# d.get('http://tangren.co.nz/portal.php?mod=portalcp&ac=article&catid=5')\r\n\t# time.sleep(5)\r\n\t# d.maximize_window()\r\n\r\n\td.find_element_by_name('title').send_keys(title)\r\n\ttime.sleep(3)\r\n\td.find_element_by_name('from').send_keys(source)\r\n\ttime.sleep(3)\r\n\td.find_element_by_name('fromurl').send_keys(url)\r\n\ttime.sleep(3)\r\n\td.find_element_by_xpath('//*[@id=\"articleform\"]/div[4]/div[2]/dl/dd[3]/input').send_keys(original_author)\r\n\ttime.sleep(3)\r\n\td.find_element_by_name('dateline').send_keys(date_publish)\r\n\ttime.sleep(3)\r\n\r\n\tActionChains(d).move_to_element_with_offset(d.find_element_by_xpath('//*[@id=\"uchome-ifrHtmlEditor\"]'), 379.25, 14).click().perform()\r\n\ttime.sleep(3)\r\n\r\n\tif get_file_name(directory):\r\n\t\tfor file_name in get_file_name(directory):\r\n\t\t\tif cc < 5:\r\n\t\t\t\tActionChains(d).move_to_element(d.find_element_by_id('imgSpanButtonPlaceholder')).click().perform()\r\n\t\t\t\ttime.sleep(5)\r\n\t\t\t\twindows_pop_up(file_name)\r\n\t\t\telse:\r\n\t\t\t\tbreak\r\n\t\t\tcc += 1\r\n\t\tfor element in d.find_elements_by_xpath('//*[contains(@id, \"attach_list_\")]'):\r\n\t\t\tif c == 1:\r\n\t\t\t\telement.find_element_by_tag_name('img').click()\r\n\t\t\t\ttime.sleep(5)\r\n\t\t\t\telement.find_element_by_tag_name('input').click()\r\n\t\t\t\ttime.sleep(5)\r\n\t\t\t\tActionChains(d).move_to_element_with_offset(d.find_element_by_xpath('//*[@id=\"uchome-ifrHtmlEditor\"]'), 1000, 350).click().send_keys(Keys.ENTER).send_keys(content).send_keys(Keys.ENTER).perform()\r\n\t\t\t\ttime.sleep(5)\r\n\t\t\telse:\r\n\t\t\t\telement.find_element_by_tag_name('img').click()\r\n\t\t\t\ttime.sleep(5)\r\n\t\t\tc += 1\r\n\telse:\r\n\t\tActionChains(d).move_to_element_with_offset(d.find_element_by_xpath('//*[@id=\"uchome-ifrHtmlEditor\"]'), 1000, 350).click().send_keys(content).perform()\r\n\t\ttime.sleep(5)\r\n\r\n\td.find_element_by_xpath('//*[@id=\"issuance\"]/strong').click()\r\n\ttime.sleep(5)\r\n\td.find_element_by_link_text('继续发布新文章').click()\r\n\ttime.sleep(5)\r\n\r\n\r\n# def validateTitle(title):\r\n# \t\"\"\"替换字符串中不能用于文件名的字符\"\"\"\r\n# \trstr = r\"[\\/\\\\\\:\\*\\?\\\"\\<\\>\\|]\" # '/ \\ : * ? \" < > |'\r\n# \tnew_title = re.sub(rstr, \"_\", title) # 替换为下划线\r\n# \treturn new_title\r\n\r\n\r\ndef get_file_name(directory):\r\n\tfile_name_list = []\r\n\tif os.path.exists(directory):\r\n\t\tfiles = os.listdir(directory)\r\n\t\tfor file in files:\r\n\t\t\tfile_name = directory + '\\\\' + file\r\n\t\t\tfile_name_list.append(file_name)\r\n\treturn file_name_list\r\n\r\ndef open_Driver():\r\n\t# chrome_options = Options()\r\n\t# chrome_options.add_experimental_option(\"detach\", True)\r\n\td = webdriver.Chrome()\r\n\td.get('http://tangren.co.nz/portal.php?mod=portalcp&ac=article&catid=4')\r\n\td.maximize_window()\r\n\ttime.sleep(5)\r\n\td.find_element_by_xpath('//*[@id=\"toptb\"]/div/div[2]/div/div/div/ul/li[1]/a').click()\r\n\ttime.sleep(5)\r\n\td.find_element_by_name('username').send_keys(\"admin\")\r\n\ttime.sleep(3)\r\n\td.find_element_by_name('password').send_keys('jian1980_')\r\n\ttime.sleep(3)\r\n\td.find_element_by_name('loginsubmit').click()\r\n\ttime.sleep(5)\r\n\treturn d\r\n\r\n\r\n\r\ndef main():\r\n\t'''main function'''\r\n\tconnect_db_read_post()\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n\r\n\r\n\r\n\r\n","sub_path":"scrapy_local_news_post.py","file_name":"scrapy_local_news_post.py","file_ext":"py","file_size_in_byte":6195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"202586743","text":"from room import Room\nfrom player import Player\nfrom world import World\n\nimport random\nfrom ast import literal_eval\n\nclass Queue():\n def __init__(self):\n self.queue = []\n def enqueue(self, value):\n self.queue.append(value)\n def dequeue(self):\n if self.size() > 0:\n return self.queue.pop(0)\n else:\n return None\n def size(self):\n return len(self.queue)\n\nclass TraversalGraph:\n def __init__(self):\n self.rooms = {}\n \n def add_room(self, room):\n self.rooms[room.id] = {}\n for i in room.get_exits():\n self.rooms[room.id][i] = '?'\n\n def add_connection(self, room_1, room_2, direction):\n opp_direction = {'n': 's', 's': 'n', 'e': 'w', 'w': 'e'}\n self.rooms[room_1.id][direction] = room_2.id\n self.rooms[room_2.id][opp_direction[direction]] = room_1.id\n \n def get_neighbor_rooms(self, room_id):\n return self.rooms[room_id]\n\n def bfs(self, starting_room):\n q = Queue()\n path = [starting_room]\n q.enqueue(path)\n visited = set()\n while q.size() > 0:\n current_path = q.dequeue()\n current_room = current_path[-1]\n if current_room == '?':\n return current_path\n if current_room not in visited:\n visited.add(current_room)\n room_neighbors = self.get_neighbor_rooms(current_room).values()\n for room_neighbor in room_neighbors:\n path_copy = current_path[:]\n path_copy.append(room_neighbor)\n q.enqueue(path_copy)\n\n# Load world\nworld = World()\n\n\n# You may uncomment the smaller graphs for development and testing purposes.\n# map_file = \"C:/Users/nchib/DS5/Graphs/projects/adventure/maps/test_line.txt\"\n# map_file = \"C:/Users/nchib/DS5/Graphs/projects/adventure/maps/test_cross.txt\"\n# map_file = \"C:/Users/nchib/DS5/Graphs/projects/adventure/maps/test_loop.txt\"\n# map_file = \"C:/Users/nchib/DS5/Graphs/projects/adventure/maps/test_loop_fork.txt\"\nmap_file = \"C:/Users/nchib/DS5/Graphs/projects/adventure/maps/main_maze.txt\"\n\n# Loads the map into a dictionary\nroom_graph=literal_eval(open(map_file, \"r\").read())\nworld.load_graph(room_graph)\n\n# Print an ASCII map\nworld.print_rooms()\n\nplayer = Player(world.starting_room)\n\n# Fill this out with directions to walk\n# traversal_path = ['n', 'n']\ntraversal_path = []\ngraph = TraversalGraph()\ndirections = ['n','s','e','w']\n\nwhile len(graph.rooms) < 500:\n room_1 = player.current_room\n if room_1.id not in graph.rooms:\n graph.add_room(room_1)\n current_exits = player.current_room.get_exits()\n direction = random.choice(current_exits)\n while player.current_room.get_room_in_direction(direction).id in \\\n graph.rooms and '?' not in \\\n graph.get_neighbor_rooms(player.current_room.get_room_in_direction(direction).id).values():\n direction = random.choice(current_exits)\n player.travel(direction)\n room_2 = player.current_room\n if room_2.id not in graph.rooms:\n graph.add_room(room_2)\n traversal_path.append(direction)\n if room_2.id not in graph.get_neighbor_rooms(room_1.id).values():\n graph.add_connection(room_1, room_2, direction)\n if '?' not in graph.get_neighbor_rooms(room_2.id).values() and graph.bfs(room_2.id) is not None:\n path_nearest_room = graph.bfs(room_2.id)\n path_nearest_room = path_nearest_room[1:-1]\n for p in path_nearest_room:\n for d in directions:\n room_in_dir = player.current_room.get_room_in_direction(d)\n if room_in_dir and room_in_dir.id == p:\n traversal_path.append(d)\n player.travel(d)\n if player.current_room.id not in graph.rooms:\n graph.add_room(player.current_room)\n\n# TRAVERSAL TEST\nvisited_rooms = set()\nplayer.current_room = world.starting_room\nvisited_rooms.add(player.current_room)\n\nfor move in traversal_path:\n player.travel(move)\n visited_rooms.add(player.current_room)\n\nif len(visited_rooms) == len(room_graph):\n print(f\"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited\")\nelse:\n print(\"TESTS FAILED: INCOMPLETE TRAVERSAL\")\n print(f\"{len(room_graph) - len(visited_rooms)} unvisited rooms\")\n\n\n\n#######\n# UNCOMMENT TO WALK AROUND\n#######\n# player.current_room.print_room_description(player)\n# while True:\n# cmds = input(\"-> \").lower().split(\" \")\n# if cmds[0] in [\"n\", \"s\", \"e\", \"w\"]:\n# player.travel(cmds[0], True)\n# elif cmds[0] == \"q\":\n# break\n# else:\n# print(\"I did not understand that command.\")\n\n","sub_path":"adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":4703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"145089435","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.core.files.storage\nimport django.utils.timezone\nimport annoying.fields\nfrom django.conf import settings\nfrom decimal import Decimal\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('auth', '0006_require_contenttypes_0002'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Category',\n fields=[\n ('name', models.CharField(serialize=False, primary_key=True, max_length=512)),\n ('image', models.ImageField(upload_to='', default='images-1.jpg')),\n ],\n ),\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('post_text', models.CharField(max_length=512)),\n ('pub_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date published')),\n ],\n ),\n migrations.CreateModel(\n name='Contributor',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('post_count', models.IntegerField(default=0)),\n ],\n ),\n migrations.CreateModel(\n name='Map',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('title', models.CharField(max_length=100)),\n ('pub_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date published')),\n ('image', models.ImageField(upload_to='', storage=django.core.files.storage.FileSystemStorage(location='/Users/smwoods/Desktop/djangoREST/newproject/media'))),\n ('is_public', models.BooleanField(default=False)),\n ('google_place', models.CharField(blank=True, max_length=512)),\n ('custom_place', models.CharField(blank=True, max_length=512)),\n ('description', models.CharField(blank=True, max_length=512)),\n ('categories', models.ManyToManyField(related_name='maps', to='api.Category', blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='Marker',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('latitude', models.DecimalField(decimal_places=15, default=Decimal('125'), max_digits=18)),\n ('longitude', models.DecimalField(decimal_places=15, default=Decimal('10'), max_digits=18)),\n ('post_text', models.CharField(null=True, blank=True, max_length=512)),\n ('pub_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date published')),\n ('google_place_id', models.CharField(blank=True, max_length=512)),\n ('google_place_name', models.CharField(blank=True, max_length=512)),\n ('google_place_address', models.CharField(default='nowhere', blank=True, max_length=512)),\n ('custom_place', models.CharField(blank=True, max_length=512)),\n ('image', models.ImageField(upload_to='', storage=django.core.files.storage.FileSystemStorage(location='/Users/smwoods/Desktop/djangoREST/newproject/media'), blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='Place',\n fields=[\n ('name', models.CharField(serialize=False, primary_key=True, max_length=512)),\n ('image', models.ImageField(upload_to='', default='images-3.jpg')),\n ('google_place_id', models.CharField(blank=True, max_length=512)),\n ('nlat', models.DecimalField(decimal_places=15, null=True, max_digits=18)),\n ('slat', models.DecimalField(decimal_places=15, null=True, max_digits=18)),\n ('wlon', models.DecimalField(decimal_places=15, null=True, max_digits=18)),\n ('elon', models.DecimalField(decimal_places=15, null=True, max_digits=18)),\n ('markers', models.ManyToManyField(related_name='places', to='api.Marker', blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='Profile',\n fields=[\n ('user', annoying.fields.AutoOneToOneField(serialize=False, primary_key=True, related_name='profile', to=settings.AUTH_USER_MODEL)),\n ('image', models.ImageField(upload_to='', storage=django.core.files.storage.FileSystemStorage(location='/Users/smwoods/Desktop/djangoREST/newproject/media'), default='images-1.jpg', blank=True)),\n ('is_public', models.BooleanField(default=False)),\n ('follows_maps', models.ManyToManyField(related_name='followed_by_users', to='api.Map', blank=True)),\n ('follows_users', models.ManyToManyField(related_name='followed_by_users', to=settings.AUTH_USER_MODEL, blank=True)),\n ('my_maps', models.ManyToManyField(related_name='user_who_created', to='api.Map', blank=True)),\n ],\n ),\n migrations.AddField(\n model_name='marker',\n name='comments',\n field=models.ManyToManyField(related_name='commented_on_markers', to=settings.AUTH_USER_MODEL, blank=True),\n ),\n migrations.AddField(\n model_name='marker',\n name='likes',\n field=models.ManyToManyField(related_name='likes_markers', to=settings.AUTH_USER_MODEL, blank=True),\n ),\n migrations.AddField(\n model_name='marker',\n name='user',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='markers'),\n ),\n migrations.AddField(\n model_name='map',\n name='comments',\n field=models.ManyToManyField(related_name='commented_on_map', to=settings.AUTH_USER_MODEL, blank=True),\n ),\n migrations.AddField(\n model_name='map',\n name='contributors',\n field=models.ManyToManyField(related_name='contributor', to=settings.AUTH_USER_MODEL, through='api.Contributor'),\n ),\n migrations.AddField(\n model_name='map',\n name='creator',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='maps'),\n ),\n migrations.AddField(\n model_name='map',\n name='likes',\n field=models.ManyToManyField(related_name='likes_maps', to=settings.AUTH_USER_MODEL, blank=True),\n ),\n migrations.AddField(\n model_name='map',\n name='markers',\n field=models.ManyToManyField(to='api.Marker', blank=True),\n ),\n migrations.AddField(\n model_name='contributor',\n name='onMap',\n field=models.ForeignKey(to='api.Map', related_name='onmap'),\n ),\n migrations.AddField(\n model_name='contributor',\n name='user',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='contributions'),\n ),\n migrations.AddField(\n model_name='comment',\n name='likes',\n field=models.ManyToManyField(related_name='comment_likes', to=settings.AUTH_USER_MODEL, blank=True),\n ),\n migrations.AddField(\n model_name='comment',\n name='user',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='comments'),\n ),\n ]\n","sub_path":"back-end/newproject/api/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":7767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"223496048","text":"from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n@app.route('/', methods=[\"POST\",\"GET\"])\n@app.route('/index', methods=[\"POST\",\"GET\"])\ndef index():\n if request.method == \"POST\":\n cedula= request.form['cedula']\n usuario = request.form['usuario']\n return render_template('result.html', cedula=cedula, usuario=usuario)\n else:\n return render_template('index.html')\n\napp.run(debug=True, host=\"0.0.0.0\", port=8080)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"525735046","text":"from . import user\n\nimport collections as col\nimport pandas as pd\nimport tensorflow as tf\nimport numpy as np\nfrom numpy.linalg import norm\nimport heapq\n\n\n\nDEBUG = True\ndef n_most_freq(ser:pd.Series,n:int) -> list:\n d = col.defaultdict(lambda:0)\n for x in ser:\n for item in x:\n d[item] += 1\n return [x[0] for x in sorted(d.items(),key = lambda x:x[1])[-n:][::-1]]\n#print(n_most_freq(recipes['ingredients'],50))\ndef cosine_similarity(u:user, rec:np.array):\n if norm(u) == 0:\n raise ValueError('User has preference norm 0, invalid')\n if norm(rec) == 0:\n return 0\n return np.dot(u, rec)/(norm(u)*norm(rec))\n\n#linearly calculates all distances from the user to the recipes\ndef get_recommendations(u:user, df:pd.DataFrame, n:int) -> np.array:\n ratings = []\n relevant_ingredients = n_most_freq(df['ingredients'],50)\n ing_favor = u.get_favorability_array(relevant_ingredients,df)\n for r in df.iloc():\n one_hot_ingredients = []\n for x in relevant_ingredients:\n one_hot_ingredients.append(1 if x in r['ingredients'] else 0)\n ratings.append( (r['id'],cosine_similarity(ing_favor,one_hot_ingredients)) ) #tuple\n return heapq.nlargest(n,ratings,key = lambda x:x[1])\n","sub_path":"src/content_based_rec.py","file_name":"content_based_rec.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"437524210","text":"\n\nfrom xai.brain.wordbase.nouns._mast import _MAST\n\n#calss header\nclass _MASTS(_MAST, ):\n\tdef __init__(self,): \n\t\t_MAST.__init__(self)\n\t\tself.name = \"MASTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"mast\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_masts.py","file_name":"_masts.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"170079567","text":"\"\"\"empty message\n\nRevision ID: afd3edfe6b04\nRevises: be0b0bca6b78\nCreate Date: 2018-04-02 20:27:07.724430\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'afd3edfe6b04'\ndown_revision = 'be0b0bca6b78'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('bus_stops',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.Text(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('buses',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('number', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('routes',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.Text(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('bus-route',\n sa.Column('route_id', sa.Integer(), nullable=True),\n sa.Column('bus_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['bus_id'], ['buses.id'], ),\n sa.ForeignKeyConstraint(['route_id'], ['routes.id'], )\n )\n op.create_table('bus_stop-route',\n sa.Column('stop_id', sa.Integer(), nullable=True),\n sa.Column('route_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['route_id'], ['routes.id'], ),\n sa.ForeignKeyConstraint(['stop_id'], ['bus_stops.id'], )\n )\n op.create_table('students',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('first_name', sa.Text(), nullable=True),\n sa.Column('last_name', sa.Text(), nullable=True),\n sa.Column('home_stop_id', sa.Integer(), nullable=True),\n sa.Column('school_stop', sa.Text(), nullable=True),\n sa.Column('present', sa.Boolean(), nullable=True),\n sa.ForeignKeyConstraint(['home_stop_id'], ['bus_stops.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('trip_history',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('student_id', sa.Integer(), nullable=False),\n sa.Column('trip_start', sa.DateTime(), nullable=False),\n sa.Column('trip_end', sa.DateTime(), nullable=True),\n sa.Column('bus_stop', sa.Text(), nullable=True),\n sa.ForeignKeyConstraint(['student_id'], ['students.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('trip_history')\n op.drop_table('students')\n op.drop_table('bus_stop-route')\n op.drop_table('bus-route')\n op.drop_table('routes')\n op.drop_table('buses')\n op.drop_table('bus_stops')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/afd3edfe6b04_.py","file_name":"afd3edfe6b04_.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"53048130","text":"#-*- coding: utf-8 -*-\n__author__ = \"ialillo\"\n\n'''\nusage\n\nfrom command line\n\n$ python CTR_image_dataset_1000impr.py\n\nto create the image dataset. To load the data, from python execute:\n\n>>> import pickle\n>>> from CTR_base_dataset import *\n>>> DATA = pickle.load(open('DATASET_CTR_BASE_1000impr','rb))\n\nThe images wil be saved to \nTo access the data: DATA.data is a hash for DATA_item elements, accesed\nwith id number (integer). Each Data_item has a .data dictionary of element:value \npairs, and a .dataexist dictionary of element:| indicating\nif value exist in the dataser (some values use default values, but\nin GPI database are NULL).\n\nExample:\n\n# get id's of the items\nkeys = DATA.data.keys()\n\n# get the data values and existence for some item 1\nDATA.data[keys[0]].data\nDATA.data[keys[0]].dataexist\n\n# get the \"descripcion\" field for all data\nDESC = [DATA.data[k].data['descripcion'] for k in DATA.data.keys()]\n\n'''\n\nimport os\nimport sys\nimport pickle\nimport gzip\nimport numpy as np\nimport time\n\nfrom PIL import Image\nfrom leargist import color_gist as gist\n\ndef gist_from_file(strfile):\n im = Image.open(strfile).resize((224,224))\n return gist(im)\n\n\nsys.path.append('../sql_queries')\nfrom gpi_connection import GPI_DB\n\n\nclass Img_item:\n def __init__(self):\n \n # values of data\n self.data = { \"id\":0, \n \"count_img\":0,\\\n \"list_img\":[]}\n \n # booleans to save when data values exist in database\n self.dataexist = { \"id\":True, \n \"count_img\":False,\\\n \"list_img\":False }\n # booleans to save when data values exist in database\n \nclass Img_score_base:\n def __init__(self):\n self.data = {}\n self.datatype = {\"id\":\"INT\", \n \"count_img\":\"INT\",\\\n \"list_img\":\"ARRAY\"}\n \n # here, data_row is a dictionary from raw data\n \n def get_id(self, data_row):\n if not type(data_row) == dict:\n print(data_row)\n print(\"row is not a hash table (dictionary)\")\n return 0\n if not data_row.has_key('id'):\n print('row must contain \"id\" key')\n return 0\n return int(data_row['id'])\n \n \n def add_data(self, data_row):\n \n id = self.get_id(data_row)\n \n if not id:\n return\n \n if not self.data.has_key(id):\n # create new item for id\n self.data[id] = Img_item()\n self.data[id].data['id'] = id\n self.update_data(data_row,id)\n #print(\"Added data for tuple with id = \" + str(id))\n else:\n # update existing item\n self.update_data(data_row,id)\n #print(\"Updated data for tuple with id = \" + str(id))\n \n\n def update_data(self, data_row, id=None):\n init_id = True\n if id is None:\n init_id = False\n id = self.get_id(data_row)\n if not id:\n return\n # check data existence\n if not self.data.has_key(id):\n print(\"No record for id \"+str(id))\n return\n self.update_data_no_check(data_row, id)\n \n def update_data_no_check(self, data_row, id):\n item = self.data[id]\n #print data_row\n for d in data_row:\n if data_row[d] == '':\n # set existence as False, and use default value for data\n item.dataexist[d] = False\n else:\n # set existence as True and check value\n item.dataexist[d] = True\n if self.datatype[d] == 'INT':\n item.data[d] = int(data_row[d])\n elif self.datatype[d] == 'FLOAT':\n item.data[d] = float(data_row[d])\n else:\n item.data[d] = data_row[d]\n\ndef append_data(csv_file, data):\n M_data = csv.reader(open(csv_file),delimiter=';')\n i = 0\n for row in M_data:\n if i == 0:\n keys = list(row)\n else:\n data.add_data(dict(zip(keys,row)))\n i += 1\n\nif __name__ == \"__main__\":\n \n if not os.path.exists(\"../Datasets/Training_image_1000impr.pkl\") or not os.path.exists('../Datasets/DATASET_IMAGE.pkl') :\n if not os.path.exists('../Datasets/DATASET_IMAGE.pkl'):\n DATA = Img_score_base()\n import time\n t1 = time.time()\n \n print(\"Connecting to goplaceit database\")\n \n cur = GPI_DB('dev',logger='info')\n\n print(\"Querying database\")\n nrows = cur.query('../sql_queries/images_propiedades_all.sql')\n \n print(\"Building dataset\")\n \n keys = cur.get_keys()\n \n for i in range(nrows):\n row = cur.fetchone()\n #print row\n if row[2] != None:\n DATA.add_data(dict(zip(keys,row)))\n \n pickle.dump(DATA, open(\"../Datasets/DATASET_IMAGE.pkl\",\"wb\"))\n print(time.time() - t1)\n \n \n else:\n DATA = pickle.load(open(\"../Datasets/DATASET_IMAGE.pkl\",'rb'))\n print(\"Loaded data from ../Datasets/DATASET_IMAGE\")\n \n '''\n Data:\n num_img\n num_hab\n num_ban\n dim_prop\n dim_total (= dim_prop if omited)\n est (=1 if (omitted and type=1), 0 if (omitted and type!=1))\n num_zones (=0 if omitted)\n info_score\n precio_usd (=mean(precio_USD according to tipo, mod) if omitted)\n '''\n \n # for each property/image, save the image GIST descriptors\n keys_id = DATA.data.keys()\n import scipy.io as io\n \n for id in keys_id:\n item = DATA.data[id]\n if item.data['count_img'] > 0 and not item.data['count_img'] is None:\n gist_data = []\n for img_url in item.data['list_img']: \n print(\"Descargando %s/%s\"%(str(id),img_url))\n ret = os.system('wget -O temp.jpg -nv --max-redirect 0 %s'%img_url)\n if ret == 0:\n print(\"Calculando GIST\")\n desc = gist_from_file('temp.jpg')\n if len(desc):\n gist_data.append(desc)\n if len(gist_data):\n os.system('mkdir -p ../Datasets/GIST')\n #pickle.dump(gist_data,gzip.open('../Datasets/GIST/%s.pkl'%(str(id)),'wb'))\n io.savemat('../Datasets/GIST/%s.mat'%str(id),{'gist_data':gist_data},do_compression=True)\n \n\n","sub_path":"GPI_env/gpi_destacados/CTR_image_dataset_1000impr.py","file_name":"CTR_image_dataset_1000impr.py","file_ext":"py","file_size_in_byte":6798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"144847552","text":"import socket\r\nimport threading\r\nimport time\r\ns = socket.socket()\r\ns.bind((socket.gethostname(), 1234))\r\nprint(\"Socket is binded at 1234 port.\")\r\n\r\ns.listen()\r\nprint(\"Socket is listening...\")\r\n\r\n\r\ndef send(clientSocket, addr):\r\n while True:\r\n ip = input()\r\n if len(ip) != 0:\r\n clientSocket.send((\"\\t\\t\\t\\t\"+ip).encode())\r\n\r\n\r\ndef receive(clientSocket, addr):\r\n while clientSocket is not None:\r\n ip = clientSocket.recv(64).decode()\r\n print(ip+\" \"+time.ctime().split()[3][:5])\r\n\r\n\r\nwhile True:\r\n clientSocket, addr = s.accept()\r\n thread1 = threading.Thread(target=receive, args=(clientSocket, addr))\r\n thread2 = threading.Thread(target=send, args=(clientSocket, addr))\r\n thread1.start()\r\n thread2.start()\r\n","sub_path":"Day1/sockets_program/chat/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"557827970","text":"import numpy\nimport cv2\n\nimage = cv2.imread('opencv.png')\nhsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\ngreen = numpy.uint8([[[0, 255, 0]]])\nhsv_green = cv2.cvtColor(green, cv2.COLOR_BGR2HSV)\n\nlower_green = numpy.array([hsv_green[0][0][0] - 10, 100, 100])\nupper_green = numpy.array([hsv_green[0][0][0] + 10, 255, 255])\n\nmask_green = cv2.inRange(hsv_image, lower_green, upper_green)\n\nred = numpy.uint8([[[0, 0, 255]]])\nhsv_red = cv2.cvtColor(red, cv2.COLOR_BGR2HSV)\n\nlower_red = numpy.array([hsv_red[0][0][0] - 10, 100, 100])\nupper_red = numpy.array([hsv_red[0][0][0] + 10, 255, 255])\n\nmask_red = cv2.inRange(hsv_image, lower_red, upper_red)\n\nmask = mask_green + mask_red\n\nresult = cv2.bitwise_and(image, image, mask=mask)\n\ncv2.imshow('hsv', hsv_image)\ncv2.imshow('mask', mask)\ncv2.imshow('result', result)\n\ncv2.waitKey(0)\n","sub_path":"2. Image processing/1. Changing Colorspaces/object tracking.py","file_name":"object tracking.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"97646929","text":"# -*- coding: utf-8 -*-\nimport click\nimport logging\nfrom pathlib import Path\nfrom dotenv import find_dotenv, load_dotenv\nimport pandas as pd\nfrom catboost import CatBoostClassifier\n\n\ndef predict_model(inference_filepath, model_filepath, output_filepath):\n \"\"\" Runs modelling scripts to turn preprocessed data from (../processed) into\n to a model (../models)\n \"\"\"\n logger = logging.getLogger(__name__)\n\n logger.info(f'loading model {model_filepath}')\n model = CatBoostClassifier().load_model(str(Path.cwd().joinpath(model_filepath)))\n\n logger.info(f'loading inference data {inference_filepath}')\n df = pd.read_feather(Path.cwd().joinpath(inference_filepath))\n\n # Store the encounter ids, before removing them for training\n arr = df['encounter_id']\n\n logger.info(f'inference data has cols: {df.columns}')\n logger.info(f'masking inference data to cols: {model.feature_names_}')\n X = df[model.feature_names_]\n\n logger.info('making predictions')\n y_proba = model.predict_proba(X)\n y_proba_death = y_proba[:, 1]\n\n y = pd.DataFrame(y_proba_death, columns=['hospital_death']).astype('float32')\n\n logger.info('persisting predictions')\n # arr = scalers['encounter_id'].inverse_transform(X['encounter_id'])\n X_encounter_id = round(pd.DataFrame(arr, columns=['encounter_id'])) # round for numerical errs\n X_encounter_id = X_encounter_id.astype('int32')\n\n output_filename = Path.cwd().joinpath(inference_filepath).stem + '.csv'\n pd.concat([X_encounter_id, y], axis=1).to_csv(Path.cwd().joinpath(output_filepath).joinpath(output_filename), index=False)\n\n\n@click.command()\n@click.argument('inference_filepath', type=click.Path(exists=True), default='data/processed/unlabeled_encoded.feather')\n@click.argument('model_filepath', type=click.Path(exists=True), default='models/model.dump')\n@click.argument('output_filepath', type=click.Path(), default='data/predictions/')\ndef main(inference_filepath, model_filepath, output_filepath):\n predict_model(inference_filepath, model_filepath, output_filepath)\n\n\nif __name__ == '__main__':\n log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n\n # not used in this stub but often useful for finding various files\n project_dir = Path(__file__).resolve().parents[2]\n\n # find .env automagically by walking up directories until it's found, then\n # load up the .env entries as environment variables\n load_dotenv(find_dotenv())\n\n main()\n","sub_path":"wids-datathon-2020/wids_datathon_2020/models/predict_model.py","file_name":"predict_model.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"636337279","text":"import requests\nimport json\n\nurl = 'http://localhost:5000/order'\nheaders = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}\n\npayload = {\"instrument\": \"EUR/USD\", \"price\": 1.10, \"quantity\": 100, \"side\":\"buy\"}\nfor price in [1.10, 1.20, 1.30, 1.40, 1.50, 1.60]:\n payload['price'] = price\n r = requests.post(url, data=json.dumps(payload), headers=headers)\n print ('result: {}'.format(r))\n\nbtcPayload = {\"instrument\": \"BTC/USDT\", \"price\": 3800, \"quantity\": 1, \"side\":\"buy\"}\nfor price in [3800, 3900, 4000, 5000]:\n btcPayload['price'] = price\n r = requests.post(url, data=json.dumps(btcPayload), headers=headers)\n print ('result: {}'.format(r))","sub_path":"initOrders.py","file_name":"initOrders.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"32068851","text":"\ndef VerifySquenceOfBST(sequence):\n if len(sequence)==0:\n return False\n index=0\n for i in range(len(sequence)):\n if sequence[i]>sequence[-1]:\n index=i\n break\n for j in range(i, len(sequence)):\n if sequence[j] < sequence[-1]:\n return False\n left = True\n right = True\n if len(sequence[:index]) > 0:\n left = VerifySquenceOfBST(sequence[:index])\n if len(sequence[index:-1]) > 0:\n right = VerifySquenceOfBST(sequence[index:-1])\n return left and right\n\n\nsequence=[5,7,6,9,11,10,8]\nlength=len(sequence)\nres=VerifySquenceOfBST(sequence)\nprint(res)","sub_path":"jianzhioffer/p179_二叉搜索树的后序遍历序列.py","file_name":"p179_二叉搜索树的后序遍历序列.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"196814132","text":"\"\"\"\nЗадание 4.\nРеализуйте скрипт \"Кэширование веб-страниц\"\n\nФункция должна принимать url-адрес и проверять\nесть ли в кэше соответствующая страница, если нет, то вносит ее в кэш\n\nПодсказка: задачу решите обязательно с применением 'соленого' хеширования\nМожете условжнить задачу, реализовав ее через ООП\n\"\"\"\n\nimport uuid\nimport hashlib\nimport requests\n\n\nclass WebCache:\n\n def __init__(self, salt):\n self.__salt = salt\n self.__cached_pages = dict()\n\n def __get_hash(self, argstr):\n argstr_and_salt = self.__salt.encode(\"utf-8\") + argstr.encode(\"utf-8\")\n str_hash = hashlib.sha256(argstr_and_salt)\n str_hash_hex = str_hash.hexdigest()\n return str_hash_hex\n\n def get_url(self, url):\n url_hash = self.__get_hash(url)\n if self.__cached_pages.get(url_hash):\n print(\"Нашел в кэше\")\n return self.__cached_pages[url_hash]\n else:\n print(\"Закешировал\")\n response = requests.get(url)\n self.__cached_pages[url_hash] = response\n\n return self.__cached_pages[url_hash]\n\n\ndef get_data(web_cache, url):\n data = web_cache.get_url(url)\n print(f\"Первые 10 символов {data.content[0:10]}\")\n\n\ndef main():\n pass\n try:\n salt = uuid.uuid4().hex\n web_cache = WebCache(salt)\n url_list = [\"https://ya.ru/\", \"https://github.com/login\", \"https://ya.ru/\"]\n for url in url_list:\n get_data(web_cache, url)\n\n print(\"\\nПрограмма завершена!\")\n\n except Exception as ex:\n print(f\"Fatal error: {ex}\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Урок 3. Практическое задание/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"75785991","text":"import requests\nimport json\nimport lxml.html\nimport re\nimport os\n\n# 获取src\ndef get_src():\n url = 'https://www.instagram.com/baaaakuuuu'\n html = requests.get(url).content.decode()\n selector = lxml.html.fromstring(html)\n script = selector.xpath('/html/body/script[1]/text()')[0].strip()\n # print(script)\n # print(type(script)) #str\n # exit()\n # for script_in in script :\n # try:\n # script_dic = json.loads(script_in)\n # print(script_dic)\n src = re.findall(r'\"thumbnail_resources\":\\[(.*?)\\]',script,re.S)\n # print(src[0]) #str\n # print(type(src[0]))\n # exit()\n return src\n\n# 获取图片链接\ndef get_picurl():\n src = get_src()\n # print(src)\n # exit()\n pic_url_lst = []\n for src_ls in src : #\"config_height\":480},{ ... ,\"config_width\":640,\"config_height\":640}\n thumb = re.findall(r'\"config_height\":480},{(.*?),\"config_width\":640,\"config_height\":640}',src_ls)[0]\n thumb_json = '{' + thumb + '}'\n # print(thumb_json)\n # exit()\n thumb_py = json.loads(thumb_json)\n pic_url = thumb_py['src']\n # print(pic_url)\n # exit()\n pic_url_lst.append(pic_url)\n # print(pic_url_lst)\n # exit()\n return pic_url_lst\n\n\n# 将图片链接保存\ndef save_pic():\n pic_url_lst = get_picurl()\n i = 1\n # print(pic_url_lst)\n # exit()\n for pic_con in pic_url_lst:\n # print(pic_con)\n # exit()\n try:\n pic = requests.get(pic_con, timeout=10)\n main_path = 'E:/ins/'\n if not os.path.exists(main_path):\n os.makedirs(main_path)\n path = 'E:/ins/' + 'baku' + str(i) + '.jpg' \n with open(path,'wb') as f:\n f.write(pic.content)\n print(f'第{i}张已下载')\n i +=1\n except requests.exceptions.ConnectionError: #requests.exceptions.ConnectionError\n print('图片无法下载')\n continue\n return \n\nsave_pic()","sub_path":"ins/ins_spider.py","file_name":"ins_spider.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"85978744","text":"import sqlphile as sp \n\nwith sp.sqlite3(r'database.db') as db:\n q = (db.insert(\"users\")\n .data(_id=1, username=\"John\", email= \"johndoe@gmail.com\")\n .execute())\n\n q = (db.select(\"users\")\n .get(\"id\", \"name\", \"email\")\n .filter())\n\nfor row in q.fetchall():\n print(row)\n\n\n####### ---OR--- #######\n\nwith sp.sqlite3(\"database.db3\", dir=\"./sqlmap\") as db:\n rows = (db.file.get_stat.filter(id = 1, name__startswith = \"J\")\n .execute()\n .fetchall())\n","sub_path":"Research Notes/SQLPhile/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"213377507","text":"\"\"\"\nWrapper around the CoreNLP server (http://nlp.stanford.edu/software/corenlp.shtml)\n\nAssumes a CoreNLP server is listening at CORENLP_HOST (default localhost:9000)\nE.g. you can run:\ndocker run -dp 9000:9000 chilland/corenlp-docker\n\"\"\"\n\nfrom nlpipe.module import Module\nfrom urllib.parse import urlencode\nimport requests\nimport json\nimport os\nfrom io import StringIO\nimport csv\nimport logging\n\nfrom corenlp_xml.document import Document\n\nclass CoreNLPBase(Module):\n\n\n def __init__(self, server=None):\n if server is None:\n server = os.getenv('CORENLP_HOST', 'http://localhost:9000')\n self.server = server\n\n def check_status(self):\n res = requests.get(self.server)\n if \"http://nlp.stanford.edu/software/corenlp.shtml\" not in res.text:\n raise Exception(\"Unexpected answer at {self.server}\".format(**locals()))\n\n def process(self, text):\n query = urlencode({\"properties\": json.dumps(self.properties)})\n url = \"{self.server}/?{query}\".format(**locals())\n res = requests.post(url, data=text.encode(\"utf-8\"))\n if res.status_code != 200:\n raise Exception(\"Error calling corenlp at {url}: {res.status_code}\\n{res.content}\".format(**locals()))\n return res.content.decode(\"utf-8\")\n\nclass CoreNLPParser(CoreNLPBase):\n name = \"corenlp_parse\"\n properties = {\"annotators\": \"tokenize,ssplit,pos,lemma,ner,parse,dcoref\", \"outputFormat\": \"xml\"}\n\n def convert(self, id, result, format):\n assert format in [\"csv\"]\n try:\n doc = Document(result.encode(\"utf-8\"))\n except:\n logging.exception(\"Error on parsing xml\")\n raise\n\n s = StringIO()\n w = csv.writer(s)\n w.writerow([\"doc_id\", \"sentence\", \"token_id\", \"offset\", \"token\", \"lemma\", \"POS\", \"pos1\", \"NER\",\n \"relation\", \"parent\"])\n\n parents = {} # sentence, child.id : (rel, parent.id)\n for sent in doc.sentences:\n if sent.collapsed_ccprocessed_dependencies:\n for dep in sent.collapsed_ccprocessed_dependencies.links:\n if dep.type != 'root':\n parents[sent.id, dep.dependent.idx] = (dep.type, dep.governor.idx)\n\n for sent in doc.sentences:\n for t in sent.tokens:\n rel, parent = parents.get((sent.id, t.id), (None, None))\n w.writerow([id, sent.id, t.id, t.character_offset_begin, t.word, t.lemma,\n t.pos, POSMAP[t.pos], t.ner, rel, parent])\n\n return s.getvalue()\n\n\nclass CoreNLPLemmatizer(CoreNLPBase):\n name = \"corenlp_lemmatize\"\n properties = {\"annotators\": \"tokenize,ssplit,pos,lemma,ner\", \"outputFormat\": \"xml\"}\n\n def convert(self, id, result, format):\n assert format in [\"csv\"]\n try:\n doc = Document(result.encode(\"utf-8\"))\n except:\n logging.exception(\"Error on parsing xml\")\n raise\n\n s = StringIO()\n w = csv.writer(s)\n w.writerow([\"id\", \"sentence\", \"offset\", \"word\", \"lemma\", \"POS\", \"pos1\", \"ner\"])\n \n for sent in doc.sentences:\n for t in sent.tokens:\n w.writerow([id, sent.id, t.character_offset_begin, t.word, t.lemma,\n t.pos, POSMAP[t.pos], t.ner])\n return s.getvalue()\n \nCoreNLPLemmatizer.register()\nCoreNLPParser.register()\n\n\nPOSMAP = { # Penn treebank POS -> simple POS\n # P preposition\n 'IN': 'P',\n # G adjective\n 'JJ': 'G',\n 'JJR': 'G',\n 'JJS': 'G',\n 'WRB': 'G',\n # C conjunction\n 'LS': 'C',\n # V verb\n 'MD': 'V',\n 'VB': 'V',\n 'VBD': 'V',\n 'VBG': 'V',\n 'VBN': 'V',\n 'VBP': 'V',\n 'VBZ': 'V',\n # N noun\n 'NN': 'N',\n 'NNS': 'N',\n 'FW': 'N',\n # R proper noun \n 'NNP': 'R',\n 'NNPS': 'R',\n # D determiner\n 'PDT': 'D',\n 'DT': 'D',\n 'WDT': 'D',\n # A adverb\n 'RB': 'A',\n 'RBR': 'A',\n 'RBS': 'A',\n # O other\n 'CC': 'O',\n 'CD': 'O',\n 'POS': 'O',\n 'PRP': 'O',\n 'PRP$': 'O',\n 'EX': 'O',\n 'RP': 'O',\n 'SYM': 'O',\n 'TO': 'O',\n 'UH': 'O',\n 'WP': 'O',\n 'WP$': 'O',\n ',': 'O',\n '.': 'O',\n ':': 'O',\n '``': 'O',\n '$': 'O',\n \"''\": 'O',\n \"#\": 'O',\n '-LRB-': 'O',\n '-RRB-': 'O',\n}\n","sub_path":"nlpipe/modules/corenlp.py","file_name":"corenlp.py","file_ext":"py","file_size_in_byte":4293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"452874498","text":"#!/usr/bin/env python\n\nimport cv2\nimport sys\nimport rospy\nfrom sensor_msgs.msg import Image, CameraInfo\nfrom cv_bridge import CvBridge, CvBridgeError\nimport numpy as np\nfrom perception.msg import YoloObject\n\nglobal cv_image\n\nclass YoloMock():\n def __init__(self):\n self.pub = rospy.Publisher('/ibvs/perception/yolo_target',YoloObject)\n self.bridge = CvBridge()\n self.sub = rospy.Subscriber('/camera/color/image_rect_color',Image,self.callback)\n self.yolo = YoloObject()\n\n def callback(self,data):\n try:\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n cv2.imshow(\"Window\", cv_image)\n cv2.waitKey(10)\n r = cv2.selectROI(\"Window\",cv_image, False)\n print(r)\n self.yolo.tag = 'MockImage'\n self.yolo.score = 78.4325\n self.yolo.baseX = r[0]\n self.yolo.baseY = r[1]\n self.yolo.width = r[2]\n self.yolo.height = r[3]\n rospy.loginfo(self.yolo)\n self.pub.publish(self.yolo)\n\n except CvBridgeError as e:\n print(e)\n\n\n\ndef main(args):\n ic = YoloMock()\n rospy.init_node('YoloMock', anonymous=True)\n r = rospy.Rate(1)\n try:\n while not rospy.is_shutdown():\n r.sleep()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main(sys.argv)\n\n","sub_path":"perception/scripts/publishYoloRealsense.py","file_name":"publishYoloRealsense.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"299515584","text":"import discord\r\nimport os\r\nimport json\r\nfrom discord.ext import commands\r\n\r\n\r\nExpJson = os.path.join('data', 'sentence.json')\r\n\r\n\r\nclass ExpCog(commands.Cog):\r\n\r\n def __init__(self, bot):\r\n super().__init__()\r\n self.bot = bot\r\n\r\n async def reply(self, ctx):\r\n reply = \"\"\r\n\r\n if \"使い方\" in ctx.content:\r\n if \"ない\" in ctx.content or \"なく\" in ctx.content or \"なえ\" in ctx.content:\r\n reply = \"ふざけないで\"\r\n else:\r\n with open(ExpJson, encoding=\"utf_8\") as f:\r\n expj = json.load(f)\r\n\r\n head_exp = \"以下に各コマンドについての説明\"\r\n d100_exp = expj[\"expression\"][\"/d100\"]\r\n d20_exp = expj[\"expression\"][\"/d20\"]\r\n d_exp = expj[\"expression\"][\"/d\"]\r\n ww_exp = expj[\"expression\"][\"/ww\"]\r\n other_exp = expj[\"expression\"][\"other\"]\r\n rpj_exp = expj[\"expression\"][\"repoj\"]\r\n\r\n helper = discord.Embed(title=\"About DiceChan\", description=head_exp, color=0xadd8e6)\r\n helper.add_field(name=\"/d100\", value=d100_exp, inline=False)\r\n helper.add_field(name=\"/d20\", value=d20_exp, inline=False)\r\n helper.add_field(name=\"/d\", value=d_exp, inline=False)\r\n helper.add_field(name=\"/ww\", value=ww_exp, inline=False)\r\n helper.add_field(name=\"その他\", value=other_exp, inline=False)\r\n helper.add_field(name=\"レポジトリ\", value=rpj_exp, inline=False)\r\n else:\r\n reply = \"何か用?\"\r\n\r\n await ctx.channel.send(reply) if len(reply) > 0 else await ctx.channel.send(embed=helper)\r\n\r\n @commands.Cog.listener()\r\n async def on_message(self, message):\r\n if self.bot.user in message.mentions:\r\n await self.reply(message)\r\n\r\n\r\nasync def setup(bot):\r\n await bot.add_cog(ExpCog(bot))\r\n","sub_path":"cogs/expressioncog.py","file_name":"expressioncog.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"563339496","text":"import os\nimport xml.etree.ElementTree as ET\nimport numpy as np\nimport cv2\nimport pandas as pd\n\n\nlabels = [\"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\", \"dog\",\n \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\", \"sofa\", \"train\", \"tvmonitor\"]\n\ndef generate_batch_data(vocPath,imageNameFile,batch_size,sample_number):\n \"\"\"\n Args:\n vocPath: the path of pascal voc data\n imageNameFile: the path of the file of image names\n batchsize: batch size, sample_number should be divided by batchsize\n Funcs:\n A data generator generates training batch indefinitely\n \"\"\"\n class_num = 20\n #Read all the data once and dispatch them out as batches to save time\n TotalimageList = prepareBatch(0,sample_number,imageNameFile,vocPath)\n\n while 1:\n batches = sample_number // batch_size\n for i in range(batches):\n images = []\n boxes = []\n sample_index = np.random.choice(sample_number,batch_size,replace=True)\n #sample_index = [3]\n for ind in sample_index:\n image = TotalimageList[ind]\n #print image.imgPath\n # image_array = crop_detection(image.imgPath,new_width=448,new_height=448)\n #image_array = np.expand_dims(image_array,axis=0)\n\n y = []\n for i in range(7):\n for j in range(7):\n box = image.boxes[i][j]\n '''\n ############################################################\n #x,y,h,w,one_hot class label vector[0....0],objectness{0,1}#\n ############################################################\n '''\n if(box.has_obj):\n obj = box.objs[0]\n\n y.append(obj.x)\n y.append(obj.y)\n y.append(obj.h)\n y.append(obj.w)\n\n labels = [0]*20\n labels[obj.class_num] = 1\n y.extend(labels)\n y.append(1) #objectness\n else:\n y.extend([0]*25)\n y = np.asarray(y)\n #y = np.reshape(y,[1,y.shape[0]])\n\n images.append(image_array)\n boxes.append(y)\n #return np.asarray(images),np.asarray(boxes)\n yield np.asarray(images),np.asarray(boxes)\n\ndef prepareBatch(start,end,imageNameFile,vocPath):\n \"\"\"\n Args:\n start: the number of image to start\n end: the number of image to end\n imageNameFile: the path of the file that contains image names\n vocPath: the path of pascal voc dataset\n Funs:\n generate a batch of images from start~end\n Returns:\n A list of end-start+1 image objects\n \"\"\"\n HEIGHT=600\n WIDTH=1000\n CHANNEL=3\n label_dimension=5\n max_label_found=20\n batch_size = end - start\n Image_data = np.zeros((batch_size,HEIGHT,WIDTH,CHANNEL), dtype=np.float32)\n # labels = np.zeros( (0, label_dimension), dtype = np.float32 )\n boundingBX_labels = np.zeros((batch_size, max_label_found, label_dimension), dtype=np.float32)\n im_dims=np.zeros((batch_size,2), dtype=np.float32)\n imageList = []\n labels = [\"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\", \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\", \"sofa\", \"train\",\"tvmonitor\"]\n file = open(imageNameFile)\n imageNames = file.readlines()\n for i in range(start,end):\n imgName = imageNames[i].strip('\\n')\n #\n # I'm chaning something in this'\n imgName1=imgName.split(\" \")\n imgName=imgName1[0]\n # ____________________________\n imgPath = os.path.join(vocPath,'JPEGImages',imgName)+'.jpg'\n xmlPath = os.path.join(vocPath,'Annotations',imgName)+'.xml'\n\n\n img = cv2.imread(imgPath,1)\n image_scale = cv2.resize(img, dsize=(WIDTH,HEIGHT), interpolation=cv2.INTER_NEAREST)\n \n Image_data[i]=image_scale\n im_dims[i] = image_scale.shape[:2]\n #Remeber to change to different widht and height\n #labels=\n bblabel=parseXML(xmlPath,labels,HEIGHT,WIDTH)\n # imageList.append(img)\n bb=np.array(bblabel)\n boundingBX_labels[i,:len(bb),:]=bb\n\n return Image_data,boundingBX_labels,im_dims\n\ndef parseXML(xmlPath, labels,pixel_size_height,pixel_size_width):\n \"\"\"\n Args:\n xmlPath: The path of the xml file of this image\n labels: label names of pascal voc dataset\n side: an image is divided into side*side grid\n \"\"\"\n tree = ET.parse(xmlPath)\n root = tree.getroot()\n\n width = int(root.find('size').find('width').text)\n height = int(root.find('size').find('height').text)\n bblabel=[]\n for obj in root.iter('object'):\n class_num = labels.index(obj.find('name').text)#finding the index of label mention so as to store data into correct label\n object_name=obj.find('name').text\n bndbox = obj.find('bndbox')\n xmin = int(bndbox.find('xmin').text)\n ymin = int(bndbox.find('ymin').text)\n xmax = int(bndbox.find('xmax').text)\n ymax = int(bndbox.find('ymax').text)\n h = ymax - ymin\n w = xmax - xmin\n # which cell this obj falls into\n centerx = (xmax + xmin) / 2.0\n centery = (ymax + ymin) / 2.0\n #448 is size of the input image\n newx = (pixel_size_width / width) * centerx\n newy = (pixel_size_height / height) * centery\n\n h_new = h * (pixel_size_height / height)\n w_new = w * (pixel_size_width / width)\n\n new_xmin=int(newx-(w_new/2))\n new_xmax=int(newx+(w_new/2))\n new_ymin=int(newy-(h_new/2))\n new_ymax=int(newy+(h_new/2))\n\n coordinate = [new_xmin, new_ymin, new_xmax, new_ymax, class_num]\n result = [float(c) for c in coordinate]\n result = np.array(result, dtype=np.int32)\n bblabel.append(coordinate)\n return bblabel\n\ndef pascal_to_csv(xmlPath_input_folder):\n loop=0\n bblabel = []\n for root, _, filenames in os.walk(xmlPath_input_folder):\n if (len(filenames) == 0):\n print(\"Input folder is empty\")\n #return 1\n for filename in filenames:\n loop=loop+1\n print(loop)\n print(filename)\n #if loop>50:\n #break\n #root=str(root)\n filename=str(filename)\n xml_path=os.path.join(xmlPath_input_folder,filename)\n # xml_path=root+\"/\"+filename\n #xml_path=\"/home/mayank-s/PycharmProjects/Datasets/VOCdevkit/VOC2012/Annotations/2010_005250.xml\"\n tree = ET.parse(xml_path)\n root = tree.getroot()\n\n width = int(root.find('size').find('width').text)\n height = int(root.find('size').find('height').text)\n \n for obj in root.iter('object'):\n class_num = labels.index(obj.find('name').text) # finding the index of label mention so as to store data into correct label\n object_name = obj.find('name').text\n bndbox = obj.find('bndbox')\n xmin = int(bndbox.find('xmin').text)\n ymin = int(bndbox.find('ymin').text)\n xmax = int(bndbox.find('xmax').text)\n ymax = int(bndbox.find('ymax').text)\n image_name=filename.split(\".\")[0]+\".jpg\"\n coordinate = [image_name, width, height, object_name,xmin, ymin, xmax, ymax]\n #result = [float(c) for c in coordinate]\n #result = np.array(result, dtype=np.int32)\n bblabel.append(coordinate)\n return bblabel\n\ndata2=pascal_to_csv(\"/home/mayank-s/PycharmProjects/Datasets/VOCdevkit/VOC2012/Annotations\")\ndf=pd.DataFrame(data2)\ndf.to_csv('out.csv')\n\nimageNameFile = \"/home/mayank-s/PycharmProjects/Datasets/VOCdevkit/VOC2012/ImageSets/Main/aeroplane_train.txt\"\nvocPath = \"/home/mayank-s/PycharmProjects/Datasets/VOCdevkit/VOC2012\"\n\n\n#image_array,y = generate_batch_data(vocPath,imageNameFile,1,sample_number=200)\n\n\n#Image_data,boundingBX_labels,im_dims=prepareBatch(0,2,imageNameFile,vocPath)\n# print(Image_data,boundingBX_labels,im_dims)\n","sub_path":"Deep learning/Load Datasets/convert pascal_voc_into_csv.py","file_name":"convert pascal_voc_into_csv.py","file_ext":"py","file_size_in_byte":8447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"376933098","text":"#taken from article https://raspberrypi.stackexchange.com/questions/76667/debouncing-buttons-with-rpi-gpio-too-many-events-detected\n\nimport RPi.GPIO as GPIO\nimport threading\n\n\nLANE1_FOOT = 12\nLANE1_HAND = 13\nLANE2_FOOT = 21\nLANE2_HAND = 17\n\nclass ButtonHandler(threading.Thread):\n def __init__(self, pin, risingfunc, fallingfunc, edge='both', bouncetime=200):\n super().__init__(daemon=True)\n\n self.edge = edge\n self.risingfunc = risingfunc\n self.fallingfunc = fallingfunc\n self.pin = pin\n self.bouncetime = float(bouncetime)/1000\n\n self.lastpinval = GPIO.input(self.pin)\n self.lock = threading.Lock()\n\n def __call__(self, *args):\n if not self.lock.acquire(blocking=False):\n return\n\n t = threading.Timer(self.bouncetime, self.read, args=args)\n t.start()\n\n def read(self, *args):\n pinval = GPIO.input(self.pin)\n\n if (\n ((pinval == 0 and self.lastpinval == 1) and\n (self.edge in ['falling', 'both'])) or\n ((pinval == 1 and self.lastpinval == 0) and\n (self.edge in ['rising', 'both']))\n ):\n if ( (pinval == 1 and self.lastpinval == 0) ): # rising \n self.risingfunc(*args)\n else:\n self.fallingfunc(*args)\n\n self.lastpinval = pinval\n self.lock.release()\n\n\n# Usage\n\ndef hand_cb(channel):\n print(\"hand_cb called \" + str(channel) ) \n\ndef footoff_cb(channel):\n print(\"Footoff_cb called \" + str(channel) ) \n\ndef footon_cb(channel):\n print(\"Footon_cb called \" + str(channel) ) \n\ndef null_cb(channel):\n #no op callback\n print(\"null_cb\")\n\n\n# Use GPIO numbers not pin numbers\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(LANE1_HAND, GPIO.IN, pull_up_down=GPIO.PUD_UP)\ncb = ButtonHandler(LANE1_HAND, hand_cb, null_cb, edge='rising', bouncetime=1)\ncb.start()\nGPIO.add_event_detect(LANE1_HAND, GPIO.RISING, callback=cb)\n\n\nGPIO.setup(LANE1_FOOT, GPIO.IN, pull_up_down=GPIO.PUD_UP)\ncb2 = ButtonHandler(LANE1_FOOT, footon_cb, footoff_cb, edge='both', bouncetime=10)\ncb2.start()\nGPIO.add_event_detect(LANE1_FOOT, GPIO.RISING, callback=cb2)\n\n\nGPIO.setup(LANE2_HAND, GPIO.IN, pull_up_down=GPIO.PUD_UP)\ncb = ButtonHandler(LANE2_HAND, hand_cb, null_cb, edge='rising', bouncetime=1)\ncb.start()\nGPIO.add_event_detect(LANE2_HAND, GPIO.RISING, callback=cb)\n\n\nGPIO.setup(LANE2_FOOT, GPIO.IN, pull_up_down=GPIO.PUD_UP)\ncb2 = ButtonHandler(LANE2_FOOT, footon_cb, footoff_cb, edge='both', bouncetime=10)\ncb2.start()\nGPIO.add_event_detect(LANE2_FOOT, GPIO.BOTH, callback=cb2)\n\nmessage = input(\"Press enter to quit\\n\\n\") # Run until someone presses enter\n\n\n\n#another article https://www.raspberrypi.org/forums/viewtopic.php?t=137484\n#http://abyz.me.uk/rpi/pigpio/python.html#callback\n\n\n","sub_path":"buttontest.py","file_name":"buttontest.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"274710033","text":"\"\"\"\nCopyright 2020 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n__author__ = [\n 'davidharcombe@google.com (David Harcombe)'\n]\n\nimport json\nimport logging\nimport pprint\n\n# Class Imports\nfrom absl import app\nfrom absl import flags\nfrom contextlib import suppress\nfrom datetime import datetime\nfrom urllib.parse import unquote\n\nfrom classes.firestore import Firestore\nfrom classes.report_type import Type\nfrom classes.sa360_report_manager import SA360Manager\nfrom classes.scheduler import Scheduler\n\n\nlogging.basicConfig(\n filename=f'sa360_report_manager-{datetime.now().strftime(\"%Y-%m-%d-%H:%M:%S\")}.log', \n format='%(asctime)s %(message)s', \n datefmt='%Y-%m-%d %I:%M:%S %p',\n level=logging.DEBUG\n)\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_bool('list', False, 'List all defined reports.')\nflags.DEFINE_bool('show', False, 'Print the defintion of the named report.')\nflags.DEFINE_bool('add', False, 'Add a new report from an SA360 definition format JSON file.')\nflags.DEFINE_bool('delete', False, 'Remove a defined report. This will also disable any runners defined for this report.')\n\n# add\nflags.DEFINE_string('file', None, 'JSON file containing the report definition.')\n\n# add/delete/show\nflags.DEFINE_string('name', None, 'Name as which the report should be stored. Default is the file name minus extension.')\n\n# common\nflags.DEFINE_string('project', None, 'GCP Project act on. Default is the environment default.')\nflags.DEFINE_string('email', None, 'Report owner/user email.')\n\n\ndef main(unused_argv):\n if FLAGS.list: action = 'list'\n elif FLAGS.show: action = 'show'\n elif FLAGS.add: action = 'add'\n elif FLAGS.delete: action = 'delete'\n else: raise NotImplementedError()\n\n args = {\n 'action': action,\n '_print': True,\n **FLAGS.flag_values_dict()\n }\n SA360Manager().manage(**args)\n\n\nif __name__ == '__main__':\n with suppress(SystemExit):\n app.run(main)","sub_path":"sa360_report_manager.py","file_name":"sa360_report_manager.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"261637528","text":"\"\"\" isometric latitude, meridian distance \"\"\"\n\nfrom __future__ import annotations\nimport typing\n\ntry:\n from numpy import radians, degrees, cos, arctan2 as atan2, tan, pi, ndarray, atleast_1d\nexcept ImportError:\n from math import radians, degrees, cos, atan2, tan, pi # type: ignore\n\n ndarray = typing.Any # type: ignore\n\nimport typing\nfrom .ellipsoid import Ellipsoid\nfrom .rcurve import rcurve_parallel\nfrom .rsphere import rsphere_rectifying\nfrom .latitude import (\n geodetic2rectifying,\n rectifying2geodetic,\n geodetic2isometric,\n geodetic2authalic,\n authalic2geodetic,\n)\nfrom .utils import sph2cart, cart2sph\n\n__all__ = [\n \"loxodrome_inverse\",\n \"loxodrome_direct\",\n \"meridian_arc\",\n \"meridian_dist\",\n \"departure\",\n \"meanm\",\n]\n\n\ndef meridian_dist(lat: ndarray, ell: Ellipsoid = None, deg: bool = True) -> float:\n \"\"\"\n Computes the ground distance on an ellipsoid from the equator to the input latitude.\n\n Parameters\n ----------\n lat : float\n geodetic latitude\n ell : Ellipsoid, optional\n reference ellipsoid (default WGS84)\n deg : bool, optional\n degrees input/output (False: radians in/out)\n\n Results\n -------\n dist : float\n distance (meters)\n \"\"\"\n return meridian_arc(0.0, lat, ell, deg)\n\n\ndef meridian_arc(lat1, lat2: ndarray, ell: Ellipsoid = None, deg: bool = True) -> float:\n \"\"\"\n Computes the ground distance on an ellipsoid between two latitudes.\n\n Parameters\n ----------\n lat1, lat2 : float\n geodetic latitudes\n ell : Ellipsoid, optional\n reference ellipsoid (default WGS84)\n deg : bool, optional\n degrees input/output (False: radians in/out)\n\n Results\n -------\n dist : float\n distance (meters)\n \"\"\"\n\n if deg:\n lat1, lat2 = radians(lat1), radians(lat2)\n\n rlat1 = geodetic2rectifying(lat1, ell, deg=False)\n rlat2 = geodetic2rectifying(lat2, ell, deg=False)\n\n return rsphere_rectifying(ell) * abs(rlat2 - rlat1)\n\n\ndef loxodrome_inverse(\n lat1: ndarray,\n lon1: ndarray,\n lat2: ndarray,\n lon2: ndarray,\n ell: Ellipsoid = None,\n deg: bool = True,\n) -> tuple[float, float]:\n \"\"\"\n computes the arc length and azimuth of the loxodrome\n between two points on the surface of the reference ellipsoid\n\n like Matlab distance('rh',...) and azimuth('rh',...)\n\n Parameters\n ----------\n\n lat1 : float\n geodetic latitude of first point\n lon1 : float\n geodetic longitude of first point\n lat2 : float\n geodetic latitude of second point\n lon2 : float\n geodetic longitude of second point\n ell : Ellipsoid, optional\n reference ellipsoid (default WGS84)\n deg : bool, optional\n degrees input/output (False: radians in/out)\n\n Results\n -------\n\n lox_s : float\n distance along loxodrome\n az12 : float\n azimuth of loxodrome (degrees/radians)\n\n Based on Deakin, R.E., 2010, 'The Loxodrome on an Ellipsoid', Lecture Notes,\n School of Mathematical and Geospatial Sciences, RMIT University, January 2010\n\n [1] Bowring, B.R., 1985, 'The geometry of the loxodrome on the\n ellipsoid', The Canadian Surveyor, Vol. 39, No. 3, Autumn 1985,\n pp.223-230.\n [2] Snyder, J.P., 1987, Map Projections-A Working Manual. U.S.\n Geological Survey Professional Paper 1395. Washington, DC: U.S.\n Government Printing Office, pp.15-16 and pp. 44-45.\n [3] Thomas, P.D., 1952, Conformal Projections in Geodesy and\n Cartography, Special Publication No. 251, Coast and Geodetic\n Survey, U.S. Department of Commerce, Washington, DC: U.S.\n Government Printing Office, p. 66.\n \"\"\"\n\n if deg:\n lat1, lon1, lat2, lon2 = radians(lat1), radians(lon1), radians(lat2), radians(lon2)\n\n # compute changes in isometric latitude and longitude between points\n disolat = geodetic2isometric(lat2, deg=False, ell=ell) - geodetic2isometric(\n lat1, deg=False, ell=ell\n )\n dlon = lon2 - lon1\n\n # compute azimuth\n az12 = atan2(dlon, disolat)\n cosaz12 = cos(az12)\n\n # compute distance along loxodromic curve\n dist = meridian_arc(lat2, lat1, deg=False, ell=ell) / abs(cos(az12))\n try:\n if (abs(cosaz12) < 1e-9).any():\n dist[abs(cosaz12) < 1e-9] = departure(lon2, lon1, lat1, ell, deg=False)\n except (AttributeError, TypeError):\n if abs(cosaz12) < 1e-9: # straight east or west\n dist = departure(lon2, lon1, lat1, ell, deg=False)\n\n if deg:\n az12 = degrees(az12) % 360.0\n\n return dist, az12\n\n\ndef loxodrome_direct(\n lat1: ndarray,\n lon1: ndarray,\n rng: ndarray,\n a12: float,\n ell: Ellipsoid = None,\n deg: bool = True,\n) -> tuple[ndarray, ndarray]:\n \"\"\"\n Given starting lat, lon with arclength and azimuth, compute final lat, lon\n\n like Matlab reckon('rh', ...)\n\n Parameters\n ----------\n lat1 : float\n inital geodetic latitude (degrees)\n lon1 : float\n initial geodetic longitude (degrees)\n rng : float\n ground distance (meters)\n a12 : float\n azimuth (degrees) clockwide from north.\n ell : Ellipsoid, optional\n reference ellipsoid\n deg : bool, optional\n degrees input/output (False: radians in/out)\n\n Results\n -------\n lat2 : float\n final geodetic latitude (degrees)\n lon2 : float\n final geodetic longitude (degrees)\n \"\"\"\n\n if deg:\n lat1, lon1, a12 = radians(lat1), radians(lon1), radians(a12)\n\n try:\n lat1 = atleast_1d(lat1)\n rng = atleast_1d(rng)\n if (abs(lat1) > pi / 2).any():\n raise ValueError(\"-90 <= latitude <= 90\")\n if (rng < 0).any():\n raise ValueError(\"ground distance must be >= 0\")\n except NameError:\n if abs(lat1) > pi / 2:\n raise ValueError(\"-90 <= latitude <= 90\")\n if rng < 0:\n raise ValueError(\"ground distance must be >= 0\")\n\n # compute rectifying sphere latitude and radius\n reclat = geodetic2rectifying(lat1, ell, deg=False)\n\n # compute the new points\n cosaz = cos(a12)\n lat2 = reclat + (rng / rsphere_rectifying(ell)) * cosaz # compute rectifying latitude\n lat2 = rectifying2geodetic(lat2, ell, deg=False) # transform to geodetic latitude\n\n newiso = geodetic2isometric(lat2, ell, deg=False)\n iso = geodetic2isometric(lat1, ell, deg=False)\n\n dlon = tan(a12) * (newiso - iso)\n lon2 = lon1 + dlon\n\n if deg:\n lat2, lon2 = degrees(lat2), degrees(lon2)\n\n try:\n return lat2.squeeze()[()], lon2.squeeze()[()]\n except AttributeError:\n return lat2, lon2\n\n\ndef departure(\n lon1: ndarray, lon2: ndarray, lat: ndarray, ell: Ellipsoid = None, deg: bool = True\n) -> float:\n \"\"\"\n Computes the distance along a specific parallel between two meridians.\n\n like Matlab departure()\n\n Parameters\n ----------\n lon1, lon2 : float\n geodetic longitudes (degrees)\n lat : float\n geodetic latitude (degrees)\n ell : Ellipsoid, optional\n reference ellipsoid\n deg : bool, optional\n degrees input/output (False: radians in/out)\n\n Returns\n -------\n dist: float\n ground distance (meters)\n \"\"\"\n if deg:\n lon1, lon2, lat = radians(lon1), radians(lon2), radians(lat)\n\n return rcurve_parallel(lat, ell, deg=False) * ((lon2 - lon1) % pi)\n\n\ndef meanm(\n lat: ndarray, lon: ndarray, ell: Ellipsoid = None, deg: bool = True\n) -> tuple[float | ndarray, float | ndarray]:\n \"\"\"\n Computes geographic mean for geographic points on an ellipsoid\n\n like Matlab meanm()\n\n Parameters\n ----------\n lat : sequence of float\n geodetic latitude (degrees)\n lon : sequence of float\n geodetic longitude (degrees)\n ell : Ellipsoid, optional\n reference ellipsoid\n deg : bool, optional\n degrees input/output (False: radians in/out)\n\n Returns\n -------\n latbar, lonbar: float\n geographic mean latitude, longitude\n \"\"\"\n\n if deg:\n lat, lon = radians(lat), radians(lon)\n\n lat = geodetic2authalic(lat, ell, deg=False)\n assert isinstance(lat, ndarray)\n x, y, z = sph2cart(lon, lat, 1)\n lonbar, latbar, _ = cart2sph(x.sum(), y.sum(), z.sum())\n latbar = authalic2geodetic(latbar, ell, deg=False)\n\n if deg:\n latbar, lonbar = degrees(latbar), degrees(lonbar)\n return latbar, lonbar\n","sub_path":"src/pymap3d/lox.py","file_name":"lox.py","file_ext":"py","file_size_in_byte":8419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"198986286","text":"import random\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.patches import Rectangle\n\nimport ReadCatalog as rcal\nimport ReadQuery as rquer\nimport FetchData as fdata\nimport ParseSaved as pars\n\nfrom Config import config as cfg\n\n\ndef findPlotBorders(object_dict):\n \"\"\" Find the minimum and maximum RA and Dec from an object_dict dictionary. \"\"\"\n\n # Init heaps\n ra_arr = []\n dec_arr = []\n\n # Get all dictionary values\n values = object_dict.values()\n\n # Fill heaps\n for arr in values:\n ra_arr.extend(arr[1])\n dec_arr.extend(arr[2])\n\n # Find min and max of both RA and Dec\n ra_min, ra_max = min(ra_arr), max(ra_arr)\n dec_min, dec_max = min(dec_arr), max(dec_arr)\n\n # Averages\n ra_avg = np.average(ra_arr)\n dec_avg = np.average(dec_arr)\n\n # Find the maximum span\n span_max = max(ra_max - ra_min, dec_max - dec_min) * 1.2\n\n # Redo the min and max\n ra_min = ra_avg - span_max/2\n ra_max = ra_avg + span_max/2\n\n dec_min = dec_avg - span_max/2\n dec_max = dec_avg + span_max/2\n\n # Return the values\n return ra_min, ra_max, dec_min, dec_max\n\n\nclass PlanningTool(object):\n\n def __init__(self, cal_dir, cal_name, data_dir, data_name, query_dir, query_name, save_dir, save_name, \\\n x_span, y_span, lim_mag):\n\n # Form the query\n fdata.sData2Query(data_dir, data_name, query_dir, query_name)\n\n # Load the query\n self.object_dict = rquer.readQuery(query_dir, query_name)\n\n # Init parameters\n self.save_dir = save_dir\n self.save_name = save_name\n\n self.x_span = x_span\n self.y_span = y_span\n\n self.lim_mag = lim_mag\n\n # Find the plot limits\n self.ra_min, self.ra_max, self.dec_min, self.dec_max = findPlotBorders(self.object_dict)\n\n # Load the catalog\n self.star_catalog = rcal.loadGaiaCatalog(cal_dir, cal_name, lim_mag=self.lim_mag, ra_min=self.ra_min, \\\n ra_max=self.ra_max, dec_min=self.dec_min, dec_max=self.dec_max)\n\n # Construct color array\n color_arr = cm.nipy_spectral(np.linspace(0.2, 1, len(self.object_dict)))\n color_order = random.sample(range(len(color_arr)), len(color_arr))\n self.color_arr = color_arr[color_order]\n\n # Init plot\n self.fig = plt.figure()\n self.ax = self.fig.add_subplot(111)\n\n # Plot stars\n self.ax.scatter(self.star_catalog[:, 0], self.star_catalog[:, 1], \\\n s=(2.512**(-self.star_catalog[:, 2])*1500), color='black')\n\n\n # Plot asteroids\n for i, object_i in enumerate(self.object_dict):\n \n # Extract coordinates and data\n date_str_arr, ra_arr, dec_arr, pa_arr = self.object_dict[object_i]\n color = self.color_arr[i]\n\n for i, date_str, ra, dec in zip(range(len(date_str_arr)), date_str_arr, ra_arr, dec_arr):\n\n # Scatter plot, label only if this is the first object in the series \n if i == 0:\n self.ax.scatter(ra, dec, c=color, marker='x', label=object_i)\n elif i == 2:\n self.ax.scatter(ra, dec, c=color, marker='x')\n pa = np.deg2rad(pa_arr[i + 1])\n r = np.sqrt((ra - ra_arr[i+1])**2 + (dec-dec_arr[i+1])**2)\n self.ax.arrow(ra, dec, r*np.sin(pa), r*np.cos(pa), width=0.01)\n elif i == 1:\n self.ax.scatter(ra, dec, c=color, marker='x')\n if i != 3:\n self.ax.annotate(date_str, (ra, dec), xycoords='data', color='r')\n\n\n # Label axes\n self.ax.set_xlabel('RA [deg]')\n self.ax.set_ylabel('Dec [deg]')\n\n # Legend\n self.legend = self.ax.legend(loc='upper right', fontsize='x-small')\n\n # Save plot limits\n self.x_min, self.x_max = self.ax.get_xlim()\n self.y_min, self.y_max = self.ax.get_ylim()\n\n # Plot center\n self.x_center = (self.x_min + self.x_max) / 2\n self.y_center = (self.y_min + self.y_max) / 2\n\n # Offsets between the rectangle center and lower left corner\n self.x_off = self.x_span/2\n self.y_off = self.y_span/2\n\n # Init FOV rectangle\n self.fov_rect = Rectangle((self.x_center - self.x_off, self.y_center - self.y_off), self.x_span, self.y_span, \\\n fill=True, alpha=0.5, facecolor='blue', edgecolor='black', linewidth=1)\n\n # Coordinates to which the FOV rectangle is moved\n self.new_x = None\n self.new_y = None\n\n # Where the selected rectangle positions and names are saved\n self.name_arr = []\n self.x_arr = []\n self.y_arr = []\n\n self.ax.add_patch(self.fov_rect)\n\n # Register mouse/keyboard events\n self.ax.figure.canvas.mpl_connect('motion_notify_event', self.onMouseMotion)\n self.ax.figure.canvas.mpl_connect('button_press_event', self.onMousePress)\n \n # Set tight layout\n self.fig.tight_layout()\n self.ax.margins(0)\n self.ax.set_aspect('equal')\n self.ax.figure.canvas.draw()\n\n\n def onMouseMotion(self, event):\n ''' Evokes when the mouse is moved. Moves the rectangle. '''\n\n # Don't do anything is the mouse is not inside the plot\n if event.inaxes != self.fov_rect.axes: return\n\n # Read new cursor position\n self.new_x = event.xdata\n self.new_y = event.ydata\n\n # Clip the values so the rectangle is always inside the plot\n self.new_x = np.clip(self.new_x, self.x_min + self.x_off, self.x_max - self.x_off)\n self.new_y = np.clip(self.new_y, self.y_min + self.y_off, self.y_max - self.y_off)\n\n # Move the rectangle\n self.fov_rect.set_xy((self.new_x - self.x_off, self.new_y - self.y_off))\n\n # Update plot\n self.ax.figure.canvas.draw()\n\n\n def onMousePress(self, event):\n ''' Evokes when the mouse button is pressed. Saves the rectangle coordinates. '''\n\n # Don't do anything is the mouse is not inside the plot\n if event.inaxes != self.fov_rect.axes: return\n\n # Read cursor position\n x_sel = event.xdata\n y_sel = event.ydata\n\n # Save the position\n self.x_arr.append(x_sel)\n self.y_arr.append(y_sel)\n\n # Get the object name\n for i, object_i in enumerate(self.object_dict):\n val_arr = self.object_dict[object_i]\n ra_arr, dec_arr = val_arr[1], val_arr[2]\n ra_avg = np.average(ra_arr)\n dec_avg = np.average(dec_arr)\n\n if ra_avg > self.ra_min and ra_avg < self.ra_max and \\\n dec_avg > self.dec_min and dec_avg < self.dec_max:\n\n self.name_arr.append(object_i)\n break\n\n # Save the arrays\n np.savetxt(self.save_dir + self.save_name, np.c_[self.name_arr, self.x_arr, self.y_arr], \\\n fmt='%7.7s %9.9s %9.9s')\n\n # Draw selected rectangle\n rect = Rectangle((x_sel - self.x_off, y_sel - self.y_off), self.x_span, self.y_span, \\\n fill = True, alpha=0.5, facecolor='green', edgecolor='black', linewidth=1)\n\n self.ax.add_patch(rect) \n\n # Update plot\n self.ax.figure.canvas.draw()\n\n\nif __name__ == '__main__':\n\n # Create tool instance\n pln = PlanningTool(cfg.CAL_DIR, cfg.CAL_NAME, cfg.DATA_DIR, cfg.DATA_NAME, cfg.QUERY_DIR, cfg.QUERY_NAME, cfg.SAVE_DIR, cfg.SAVE_NAME, \\\n cfg.X_SPAN, cfg.Y_SPAN, cfg.LIM_MAG)\n\n # Show plot\n plt.show()\n\n # Convert raw coordinates to telescope format\n pars.parseRaw(cfg.SAVE_DIR, cfg.SAVE_NAME, cfg.FINAL_DIR, cfg.FINAL_NAME)","sub_path":"src/PlanningTool.py","file_name":"PlanningTool.py","file_ext":"py","file_size_in_byte":7686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"626611612","text":"\"\"\"\nY1 and sim analysis\n\nfor each --dataset\n--job:\n create\n run, --test_run\n log_statistics\n run\n log_statistics\n consolidate_run\n\n\nTODO: figure out why I'm not consolidating the highest z regions\nTODO: Did I make the exact randoms not span the full redshift range?\n\"\"\"\n# imports\nfrom __future__ import print_function, division\nimport numpy as np\nimport pandas as pd\nfrom os import path\nimport fitsio\n# from subprocess import call, check_output, STDOUT\nfrom subprocess import call, check_output\n# clusterz\nfrom clusterz.datasets import check_make, augment_df, determine_kmeans_centers, \\\n load_fits_file, dataset_dict, load_log_stats, load_h5_file\nfrom clusterz.paircounts import treecorr_correlation, treecorr_autocorrelation\nimport time\ntime0 = time.time()\n\ndef print_time(x):\n print(x, time.time() - time0)\n return\n\n###############################################################################\n# argparse interpretation\n###############################################################################\nimport argparse\nparser = argparse.ArgumentParser(description='run the jobs!')\nparser.add_argument('--job',\n action='store',\n dest='job',\n default='NONE',\n help='[run, rerun, corr, create]')\nparser.add_argument('--reference',\n action='store',\n dest='reference',\n default='NONE',\n help='[SDSS_SDSS, REDMAPPER_SDSS, REDMAGIC_SDSS]')\nparser.add_argument('--unknown',\n action='store',\n dest='unknown',\n default='NONE',\n help='[SDSS_SDSS, REDMAPPER_SDSS, REDMAGIC_SDSS]')\nparser.add_argument('--kmeans_region',\n action='store',\n dest='kmeans_region',\n default=-1,\n type=int,\n help='[-1] + [00-99]')\nparser.add_argument('--z_region_ith',\n action='store',\n dest='z_region_ith',\n default=-1,\n type=int,\n help='[00-99]')\nparser.add_argument('--dataset',\n action='store',\n dest='dataset',\n default='NONE',\n help='What dataset!')\nparser.add_argument('--tomo',\n action='store',\n dest='tomo',\n default=0,\n type=int,\n help='[[zmin,zmax], [0.3,0.55], [0.55,0.83]]')\nparser.add_argument('--test_run',\n action='store_true',\n dest='test_run',\n help='If doing run, test_run does smaller run')\nparser.add_argument('--check_fits',\n action='store_true',\n dest='check_fits',\n help='Instead of just saying \"file found\", load up the' +\n 'fits file and make sure it has enough elements.')\noptions = parser.parse_args()\nargs = vars(options)\nfrom sys import argv\ninput_command = 'python ' + ' '.join(argv)\nprint(input_command, time.time() - time0)\ndataset = args['dataset']\n\n###############################################################################\n# config params\n###############################################################################\nrun_name = 'run41'\ncode_path = '/nfs/slac/g/ki/ki18/cpd/Projects/cluster-z/code/batch_runs/' + \\\n '{0}.py'.format(run_name)\ndatasets = ['SV', 'Y1A1CCTFv2', 'SDSS']\nif args['job'] == 'NONE':\n print('*** Welcome to {0}'.format(run_name))\n print('*** The commands you want to run are:')\n for i in datasets:\n print('python {0} --dataset {1} --job create'.format(code_path, i))\n print('python {0} --dataset {1} --job run --test_run'.format(code_path,\n i))\n print('python {0} --dataset {1} --job log_statistics'.format(code_path,\n i))\n print('python {0} --dataset {1} --job run'.format(code_path, i))\n print('python {0} --dataset {1} --job log_statistics'.format(code_path,\n i))\n print('python {0} --dataset {1} --job consolidate_run'.format(\n code_path, i))\n raise Exception('Now choose a job!')\n\nif dataset == 'NONE':\n raise Exception('Please choose a dataset!')\n\nelif dataset == 'SV':\n # bsub requirements\n # this is really bad practice::\n memory_notbenchmark = 1500 # MB\n req_time_notbenchmark = 160 # minutes\n memory_benchmark = 8000 # MB\n req_time_benchmark = 1600 # minutes\n\n memory_benchmark_unknown_auto = memory_benchmark\n req_time_benchmark_unknown_auto = 1300\n memory_notbenchmark_unknown_auto = memory_notbenchmark\n req_time_notbenchmark_unknown_auto = 120\n\n memory = memory_benchmark\n req_time = req_time_benchmark\n\n memory_unknown_auto = memory_benchmark\n req_time_unknown_auto = req_time_benchmark\n\n memory_consolidate = memory\n req_time_consolidate = 15\n\n # kmeans regions\n kmeans_name = 'REDMAGIC_SV' # which randoms make the kmeans center\n n_clusters = 100\n all_datasets = ['REDMAGIC_SV', 'REDMAPPER_SV', 'BENCHMARK_SV']\n # reference unknown\n all_pairs = [['REDMAPPER_SV', 'BENCHMARK_SV'],\n ['REDMAGIC_SV', 'BENCHMARK_SV'],\n ['REDMAPPER_SV', 'REDMAPPER_SV'],\n ['REDMAPPER_SV', 'REDMAGIC_SV'],\n ['REDMAGIC_SV', 'REDMAPPER_SV'],\n ['REDMAGIC_SV', 'REDMAGIC_SV'],\n ['BENCHMARK_SV', 'BENCHMARK_SV']]\n\n # redshift\n zmin = 0.05\n zmax = 1.55\n dz = 0.02\n tomo = [[0, 10], [0.3, 0.55], [0.55, 0.83], [0.83, 1.3]]\n z_iter = 20\n data_name = 'data.h5'\n\nelif dataset == 'Y1A1':\n # TODO: Double check on memory requirements!!!\n # bsub requirements\n z_iter = 20 # do this many zbins per batch job\n\n\n # this is really bad practice::\n memory_notbenchmark = 6000 # MB\n req_time_notbenchmark = 200 # minutes\n memory_benchmark = 10000 # MB\n req_time_benchmark = 1600 # minutes\n\n memory_benchmark_unknown_auto = memory_benchmark\n req_time_benchmark_unknown_auto = 2000\n memory_notbenchmark_unknown_auto = memory_notbenchmark\n req_time_notbenchmark_unknown_auto = 400\n\n\n memory = memory_benchmark\n req_time = req_time_benchmark\n\n memory_unknown_auto = memory_benchmark\n req_time_unknown_auto = req_time_benchmark\n\n memory_consolidate = memory\n req_time_consolidate = 15\n\n\n # kmeans regions\n n_clusters = 20\n kmeans_name = 'REDMAGIC6411HIGHDENS_Y1A1' # which randoms make the kmeans center\n all_datasets = ['BENCHMARK_Y1A1', 'REDMAPPER6411_Y1A1',\n 'REDMAGIC6411HIGHLUM_Y1A1', 'REDMAGIC6411HIGHDENS_Y1A1']\n\n # reference unknown\n all_pairs = [\n # ['REDMAPPER6411_Y1A1', 'BENCHMARK_Y1A1'],\n # ['REDMAGIC6411HIGHLUM_Y1A1', 'BENCHMARK_Y1A1'],\n # ['REDMAGIC6411HIGHDENS_Y1A1', 'BENCHMARK_Y1A1'],\n ['REDMAPPER6411_Y1A1', 'REDMAPPER6411_Y1A1'],\n ['REDMAPPER6411_Y1A1', 'REDMAGIC6411HIGHLUM_Y1A1'],\n ['REDMAPPER6411_Y1A1', 'REDMAGIC6411HIGHDENS_Y1A1'],\n ['REDMAGIC6411HIGHLUM_Y1A1', 'REDMAPPER6411_Y1A1'],\n ['REDMAGIC6411HIGHLUM_Y1A1', 'REDMAGIC6411HIGHLUM_Y1A1'],\n ['REDMAGIC6411HIGHDENS_Y1A1', 'REDMAPPER6411_Y1A1'],\n ['REDMAGIC6411HIGHDENS_Y1A1', 'REDMAGIC6411HIGHDENS_Y1A1'],\n ]\n\n # redshift\n zmin = 0.05\n zmax = 1.05\n dz = 0.02\n # don't do whole tomo range since we run out of samples after 0.9ish\n tomo = [[0, 10], [0.6, 1.1],\n [0.2, 0.3], [0.3, 0.4], [0.4, 0.5], [0.5, 0.6],\n [0.6, 0.675], [0.675, 0.75], [0.75, 0.825], [0.825, 0.9], [0.9, 0.975]]\n data_name = 'data.h5'\n\nelif dataset == 'Y1A1CCTFv2':\n # bsub requirements\n memory = 10000 # MB\n req_time = 3000 # minutes\n memory_unknown_auto = memory\n req_time_unknown_auto = req_time\n memory_consolidate = memory\n req_time_consolidate = 15\n # kmeans regions\n n_clusters = 100\n kmeans_name = 'REDMAGIC_Y1A1CCTFv2' # which randoms make the kmeans center\n number_density_divisors = [1, 2, 4, 8, 16, 32]\n dzs = [0.02, 0.04, 0.06, 0.08, 0.1]\n all_datasets = []\n\n # add the different density and dz divisors\n for number_density_divisor in number_density_divisors:\n if number_density_divisor >= 4:\n iths = range(4)\n else:\n iths = range(number_density_divisor)\n for ith in iths:\n table_name = 'REDMAGICdens{0:02d}ith{1}_Y1A1CCTFv2'.format(\n number_density_divisor, ith)\n all_datasets.append(table_name)\n dataset_dict[table_name] = {'data_path': '/nfs/slac/g/ki/ki18/des/cpd/cluster-z/run41/data/redmagic_explore.h5',\n 'random_path': '/nfs/slac/g/ki/ki18/des/cpd/cluster-z/run41/data/redmagic_explore.h5',\n 'zkey': 'z',\n 'zkey_random': 'z',}\n for dzi, dz in enumerate(dzs):\n table_name = 'REDMAGICdz{0}_Y1A1CCTFv2'.format(dzi)\n all_datasets.append(table_name)\n dataset_dict[table_name] = {'data_path': '/nfs/slac/g/ki/ki18/des/cpd/cluster-z/run41/data/redmagic_explore.h5',\n 'random_path': '/nfs/slac/g/ki/ki18/des/cpd/cluster-z/run41/data/redmagic_explore.h5',\n 'zkey': 'z',\n 'zkey_random': 'z',}\n\n all_datasets.append('REDMAGICEXACT_Y1A1CCTFv2')\n\n\n # reference unknown\n unknowns = ['BRIGHTEXACT_Y1A1CCTFv2', 'BRIGHTGAUSS_Y1A1CCTFv2']\n all_pairs = []\n # add the brightworsegauss\n table_name = 'BRIGHTWORSEGAUSS_Y1A1CCTFv2'\n dataset_dict[table_name] = {'data_path': '/nfs/slac/g/ki/ki18/des/cpd/cluster-z/run41/data/redmagic_explore.h5',\n 'random_path': '/nfs/slac/g/ki/ki18/des/cpd/cluster-z/run41/data/redmagic_explore.h5',\n 'zkey': 'z',\n 'zkey_random': 'z',}\n unknowns.append(table_name)\n all_pairs.append(['REDMAGICEXACT_Y1A1CCTFv2', table_name])\n all_pairs.append(['REDMAGICdens01ith0_Y1A1CCTFv2', table_name])\n # add other sets\n for unknown in unknowns:\n for reference in all_datasets:\n if 'BRIGHT' in reference:\n continue\n pair = [reference, unknown]\n if pair not in all_pairs:\n all_pairs.append([reference, unknown])\n if unknown not in all_datasets:\n all_datasets.append(unknown)\n\n\n\n # redshift\n zmin = 0.05\n zmax = 1.05\n dz = 0.01\n tomo = [[0, 10], [0.3, 0.55], [0.55, 0.83], [0.83, 1.3]]\n z_iter = 20 # do this many zbins per batch job\n data_name = 'redmagic_explore.h5'\n\nelif dataset == 'SDSS':\n # bsub requirements\n memory = 15000 # MB\n req_time = 2500 # minutes\n memory_unknown_auto = memory\n req_time_unknown_auto = req_time\n memory_consolidate = memory\n req_time_consolidate = 15\n # kmeans regions\n kmeans_name = 'SDSS_SDSS' # which randoms make the kmeans centers\n n_clusters = 100\n all_datasets = ['SDSS_SDSS',\n 'REDMAPPER510_SDSS',\n 'REDMAPPER631_SDSS', 'REDMAGIC63120_SDSS']\n # reference unknown\n all_pairs = [['SDSS_SDSS', 'SDSS_SDSS'],\n ['REDMAPPER510_SDSS', 'SDSS_SDSS'],\n ['REDMAPPER631_SDSS', 'SDSS_SDSS'],\n ['REDMAGIC63120_SDSS', 'SDSS_SDSS'],\n ['SDSS_SDSS', 'REDMAPPER510_SDSS'],\n ['SDSS_SDSS', 'REDMAPPER631_SDSS'],\n ['SDSS_SDSS', 'REDMAGIC63120_SDSS'],\n ['REDMAPPER510_SDSS', 'REDMAPPER510_SDSS'],\n ['REDMAPPER510_SDSS', 'REDMAGIC63120_SDSS'],\n ['REDMAPPER631_SDSS', 'REDMAPPER631_SDSS'],\n ['REDMAPPER631_SDSS', 'REDMAGIC63120_SDSS'],\n ['REDMAGIC63120_SDSS', 'REDMAPPER510_SDSS'],\n ['REDMAGIC63120_SDSS', 'REDMAPPER631_SDSS'],\n ['REDMAGIC63120_SDSS', 'REDMAGIC63120_SDSS'],\n ]\n # redshift\n zmin = 0.05\n zmax = 1.05\n dz = 0.02\n tomo = [[0, 10], [0.3, 0.55], [0.55, 0.83], [0.83, 1.3]]\n z_iter = 20 # do this many zbins per batch job\n data_name = 'sdss.h5'\n\nrandom_cutsize = 1000000 # maximum number of randoms in random-random cross\nsample_num = 1000000 # number of points to use for kmeans center determination\nlabel_every = 10000 # batch the labeling because of some crazy memory problem\n# sample split into test / train samples\ntest_fraction = 0.2\n\n###############################################################################\n# start code\n###############################################################################\nzbins = np.arange(zmin, zmax + dz, dz)\nzcenters = 0.5 * (zbins[1:] + zbins[:-1])\n\n# check directories and make them\nrun_dir = '/nfs/slac/g/ki/ki18/des/cpd/cluster-z/' + run_name\ndata_dir = run_dir + '/data'\ncheck_make(data_dir)\npaircount_dir = run_dir + '/paircounts'\ncheck_make(paircount_dir)\nlog_dir = run_dir + '/logs'\ncheck_make(log_dir)\n# thing we used to make the kmeans centers\nkmeans_path = data_dir + '/kmeans_centers_{0}_RANDOMS.npy'.format(kmeans_name)\nzbins_path = data_dir + '/zbins_{0}.npy'.format(dataset)\n\nkmeans_region = args['kmeans_region']\nz_region_ith = args['z_region_ith']\ntomo_ith = args['tomo']\n\nreference_name = args['reference']\nreference_data_path = dataset_dict[reference_name]['data_path']\n# not used if make_randoms_reference = True\nreference_random_path = dataset_dict[reference_name]['random_path']\nreference_data_zkey = dataset_dict[reference_name]['zkey'] # if none: 'NONE'\nreference_random_zkey = dataset_dict[reference_name]['zkey_random']\n# make_randoms_reference = dataset_dict[reference_name]['make_randoms']\n\nunknown_name = args['unknown']\nunknown_data_path = dataset_dict[unknown_name]['data_path']\n# not used if make_randoms_unknown = True\nunknown_random_path = dataset_dict[unknown_name]['random_path']\nunknown_data_zkey = dataset_dict[unknown_name]['zkey'] # if none: 'NONE'\nunknown_random_zkey = dataset_dict[unknown_name]['zkey_random']\n# make_randoms_unknown = dataset_dict[unknown_name]['make_randoms']\n\n###############################################################################\n# Functions\n###############################################################################\n\n\ndef create_file_name(reference_name=reference_name, unknown_name=unknown_name,\n kmeans_region=kmeans_region, z_region_ith=z_region_ith,\n tomo_ith=tomo_ith, auto=False, consolidate=False):\n if auto:\n fits_file = paircount_dir + '/{0}__{1}__{2}__{3}__{4}.fits'.format(\n unknown_name, reference_name,\n kmeans_region, 'auto', tomo_ith)\n elif consolidate:\n fits_file = run_dir + '/consolidated/{0}__{1}__{2}__consolidated.fits'.format(\n unknown_name, reference_name, tomo_ith)\n else:\n fits_file = paircount_dir + '/{0}__{1}__{2}__{3}__{4}.fits'.format(\n unknown_name, reference_name,\n kmeans_region, z_region_ith, tomo_ith)\n return fits_file\n\n\nif args['job'] == 'create':\n for unknown_name in [kmeans_name] + all_datasets:\n unknown_data_path = dataset_dict[unknown_name]['data_path']\n unknown_random_path = dataset_dict[unknown_name]['random_path']\n unknown_data_zkey = dataset_dict[unknown_name]['zkey']\n unknown_random_zkey = dataset_dict[unknown_name]['zkey_random']\n make_randoms_unknown = dataset_dict[unknown_name]['make_randoms']\n # do any data creation steps here. ONLY takes in the unknown name\n # # load data\n column_dictionary_unknown_data = {'ra': 'RA', 'dec': 'DEC'}\n if unknown_data_zkey != 'NONE':\n column_dictionary_unknown_data['z'] = unknown_data_zkey\n if '.fits' in unknown_data_path:\n unknown_data = load_fits_file(unknown_data_path,\n column_dictionary_unknown_data)\n elif '.h5' in unknown_data_path:\n unknown_data = load_h5_file(unknown_data_path, unknown_name,\n column_dictionary_unknown_data)\n # # create randoms if needs be\n if make_randoms_unknown:\n raise NotImplementedError('make randoms still not in here')\n else:\n column_dictionary_unknown_random = {'ra': 'RA', 'dec': 'DEC'}\n if unknown_data_zkey != 'NONE':\n column_dictionary_unknown_random['z'] = unknown_random_zkey\n if '.fits' in unknown_random_path:\n unknown_random = load_fits_file(\n unknown_random_path,\n column_dictionary_unknown_random,\n sample_num=30000000,\n sample_mult=20, sample_mult_compare=len(unknown_data))\n elif '.h5' in unknown_random_path:\n unknown_random = load_h5_file(\n unknown_random_path, unknown_name + '_RANDOMS',\n column_dictionary_unknown_random,\n sample_num=30000000,\n sample_mult=20, sample_mult_compare=len(unknown_data))\n\n # # kmeans center creation\n # arbitrarily we'll use the ref random to get the centers\n if ((unknown_name == kmeans_name) &\n (not path.exists(kmeans_path))):\n unknown_random_ra = unknown_random['ra'].values\n unknown_random_dec = unknown_random['dec'].values\n kmeans_centers = determine_kmeans_centers(unknown_random_ra,\n unknown_random_dec,\n n_clusters=n_clusters,\n sample_num=sample_num)\n np.save(kmeans_path, kmeans_centers)\n # arbitrarily also save the zbins for records keeping\n np.save(zbins_path, zbins)\n else:\n kmeans_centers = np.load(kmeans_path)\n\n # # augment dfs\n unknown_data = augment_df(unknown_data, kmeans_centers,\n do_zbins='z' in unknown_data.columns,\n zbins=zbins, test_fraction=test_fraction,\n label_every=label_every)\n unknown_random = augment_df(unknown_random, kmeans_centers,\n do_zbins='z' in unknown_random.columns,\n zbins=zbins, test_fraction=test_fraction,\n label_every=label_every)\n\n # # save data\n unknown_data.to_hdf(data_dir + '/' + data_name,\n key=unknown_name,\n mode='a', format='table', append=False)\n unknown_random.to_hdf(data_dir + '/' + data_name,\n key=unknown_name + '_RANDOMS',\n mode='a', format='table', append=False)\n\n# iterate through sending jobs to do paircounts\nelif ((args['job'] == 'run') | (args['job'] == 'rerun')):\n kmeans_regions = [-1] + range(n_clusters)\n if args['test_run']:\n # take only a couple jobs to test speed\n kmeans_regions = [-1]\n tomos = [0]\n else:\n tomos = range(len(tomo))\n for kmeans_region in kmeans_regions:\n for tomo_ith in tomos:\n for unknown_name in all_datasets:\n hdf5_path = data_dir + '/' + data_name\n # load and check unknown data\n unknown_data = pd.read_hdf(hdf5_path, key=unknown_name)\n # cut unknown by tomo\n z_lower, z_upper = tomo[tomo_ith]\n unknown_data = unknown_data[(unknown_data['z'] >= z_lower) &\n (unknown_data['z'] <= z_upper)]\n unknown_data_conds = unknown_data['kmeans_region'] != kmeans_region\n # cut to ra and decs\n if sum(unknown_data_conds) == 0:\n continue\n for reference_name in all_datasets:\n if [reference_name, unknown_name] not in all_pairs:\n continue\n if reference_name == unknown_name:\n # 1 is smaller!!\n unknown_data_conds_split = unknown_data_conds & (unknown_data['split'] == 1)\n else:\n unknown_data_conds_split = unknown_data_conds\n # cut to ra and decs\n if sum(unknown_data_conds_split) == 0:\n continue\n\n # load reference data\n reference_data = pd.read_hdf(hdf5_path, key=reference_name)\n print('reference data loaded', time.time() - time0)\n # reference_random = pd.read_hdf(hdf5_path, key=reference_name +\n # '_RANDOMS')\n # print('reference randoms loaded', time.time() - time0)\n\n z_regions = sorted(reference_data['z_region'].unique())\n n_iter = int(np.ceil(len(z_regions) / z_iter))\n n_iters = range(n_iter)\n if args['test_run']:\n # take only a couple jobs to test speed\n kmeans_regions = [-1]\n z_regions = [z_regions[int(0.75 * len(z_regions))]]\n n_iters = [n_iters[int(0.75 * len(n_iters))]]\n for z_region_ith in n_iters:\n # check if there is nothing there\n indx_lower = z_region_ith * z_iter\n indx_upper = indx_lower + z_iter\n z_regions = sorted(reference_data['z_region'].unique())[\n indx_lower: indx_upper]\n reference_data_conds =\\\n reference_data['kmeans_region'] != kmeans_region\n # reference_random_conds =\\\n # reference_random['kmeans_region'] != kmeans_region\n reference_data_conds = reference_data_conds &\\\n (reference_data['z_region'].isin(z_regions))\n # reference_random_conds = reference_random_conds &\\\n # (reference_random['z_region'].isin(z_regions))\n if reference_name == unknown_name:\n reference_data_conds = reference_data_conds &\\\n (reference_data['split'] == 0)\n # reference_random_conds = reference_random_conds &\\\n # (reference_random['split'] == 0)\n reference_data_ra =\\\n reference_data[reference_data_conds]['ra'].values\n # reference_random_ra =\\\n # reference_random[reference_random_conds]['ra'].values\n if len(reference_data_ra) == 0:\n continue\n # elif len(reference_random_ra) == 0:\n # continue\n\n fits_file = create_file_name(reference_name=reference_name,\n unknown_name=unknown_name,\n kmeans_region=kmeans_region,\n z_region_ith=z_region_ith,\n tomo_ith=tomo_ith)\n jobname = fits_file.split('/')[-1].split('.fits')[0]\n jobname = '{0}__{1}'.format(run_name, jobname)\n if ((args['job'] == 'run') & path.exists(fits_file) &\n (not args['check_fits'])):\n print('file found', jobname)\n continue\n if args['check_fits']:\n # load up file\n loaded = fitsio.read(fits_file)\n check_fits_count = len(loaded['z_region'])\n else:\n # gotta define check_fits_count\n check_fits_count = z_iter\n if ((args['check_fits']) & (check_fits_count != z_iter)):\n print('{0} instead of {1} entries found, {2}'.format(\n check_fits_count, z_iter, jobname))\n\n # check if jobname currently runs\n jobcheck = check_output(['bjobs', '-wJ', jobname])\n if jobname in jobcheck:\n print(jobcheck)\n continue\n # jobcheck = check_output(['bjobs', '-J', jobname],\n # stderr=STDOUT)\n # if 'not found' not in jobcheck:\n # print(jobcheck)\n # continue\n logfile = '{0}/{1}.log'.format(log_dir, jobname)\n print('submitting', jobname, logfile)\n if (dataset == 'SV') | (dataset == 'Y1A1'):\n if 'BENCHMARK' in unknown_name:\n memory = memory_benchmark\n req_time = req_time_benchmark\n else:\n memory = memory_notbenchmark\n req_time = req_time_notbenchmark\n command = ['bsub',\n '-J', jobname,\n '-o', logfile,\n '-W', str(req_time),\n '-M', str(memory),\n '-R', '\"span[hosts=1] rusage[mem={0}]\"'.format(\n memory),\n '-n', str(2),\n 'python', code_path,\n '--job', 'corr',\n '--reference', reference_name,\n '--unknown', unknown_name,\n '--kmeans_region', str(kmeans_region),\n '--z_region_ith', str(z_region_ith),\n '--tomo', str(tomo_ith),\n '--dataset', str(dataset)]\n call(command)\n\n # do auto correlation call after we do all the rest of the calls\n for kmeans_region in kmeans_regions:\n for tomo_ith in tomos:\n for reference_name, unknown_name in all_pairs:\n hdf5_path = data_dir + '/' + data_name\n # load and check unknown data\n unknown_data = pd.read_hdf(hdf5_path, key=unknown_name)\n # cut unknown by tomo\n z_lower, z_upper = tomo[tomo_ith]\n unknown_data = unknown_data[(unknown_data['z'] >= z_lower) &\n (unknown_data['z'] <= z_upper)]\n unknown_data_conds = unknown_data['kmeans_region'] != kmeans_region\n if reference_name == unknown_name:\n # 1 is smaller!!\n unknown_data_conds = unknown_data_conds & (unknown_data['split'] == 1)\n # cut to ra and decs\n unknown_data_ra = unknown_data[unknown_data_conds]['ra'].values\n if len(unknown_data_ra) == 0:\n continue\n\n # load reference data\n reference_data = pd.read_hdf(hdf5_path, key=reference_name)\n print('reference data loaded', time.time() - time0)\n\n z_regions = sorted(reference_data['z_region'].unique())\n n_iter = int(np.ceil(len(z_regions) / z_iter))\n n_iters = range(n_iter)\n if args['test_run']:\n # take only a couple jobs to test speed\n kmeans_regions = [-1]\n z_regions = [z_regions[int(0.75 * len(z_regions))]]\n n_iters = [n_iters[int(0.75 * len(n_iters))]]\n fits_file = create_file_name(reference_name=reference_name,\n unknown_name=unknown_name,\n kmeans_region=kmeans_region,\n z_region_ith=z_region_ith,\n tomo_ith=tomo_ith, auto=True)\n jobname = fits_file.split('/')[-1].split('.fits')[0]\n jobname = '{0}__{1}'.format(run_name, jobname)\n if ((args['job'] == 'run') & path.exists(fits_file) &\n (not args['check_fits'])):\n print('file found', jobname)\n continue\n if args['check_fits']:\n # load up file\n loaded = fitsio.read(fits_file)\n check_fits_count = len(loaded['z_region'])\n else:\n # gotta define check_fits_count\n check_fits_count = z_iter\n if ((args['check_fits']) & (check_fits_count != z_iter)):\n print('{0} instead of {1} entries found, {2}'.format(\n check_fits_count, z_iter, jobname))\n\n # check if jobname currently runs\n jobcheck = check_output(['bjobs', '-wJ', jobname])\n if jobname in jobcheck:\n print(jobcheck)\n continue\n # jobcheck = check_output(['bjobs', '-J', jobname],\n # stderr=STDOUT)\n # if 'not found' not in jobcheck:\n # print(jobcheck)\n # continue\n logfile = '{0}/{1}.log'.format(log_dir, jobname)\n print('submitting', jobname, logfile)\n if (dataset == 'SV') | (dataset == 'Y1A1'):\n if 'BENCHMARK' in unknown_name:\n memory_unknown_auto = memory_benchmark_unknown_auto\n req_time_unknown_auto = req_time_benchmark_unknown_auto\n else:\n memory_unknown_auto = memory_notbenchmark_unknown_auto\n req_time_unknown_auto = req_time_notbenchmark_unknown_auto\n command = ['bsub',\n '-J', jobname,\n '-o', logfile,\n '-W', str(req_time_unknown_auto),\n '-M', str(memory_unknown_auto),\n '-R', '\"span[hosts=1] rusage[mem={0}]\"'.format(\n memory_unknown_auto),\n '-n', str(2),\n 'python', code_path,\n '--job', 'corr_unknown_auto',\n '--reference', reference_name,\n '--unknown', unknown_name,\n '--kmeans_region', str(kmeans_region),\n '--z_region_ith', str(z_region_ith),\n '--tomo', str(tomo_ith),\n '--dataset', str(dataset)]\n call(command)\n\n# iterate through sending jobs to do paircounts\nelif args['job'] == 'consolidate_bsub':\n tomos = range(len(tomo))\n for reference_name, unknown_name in all_pairs:\n for tomo_ith in tomos:\n consolidate_file = create_file_name(reference_name=reference_name,\n unknown_name=unknown_name,\n tomo_ith=tomo_ith,\n consolidate=True)\n jobname = consolidate_file.split('/')[-1].split('.fits')[0]\n jobname = '{0}__{1}'.format(run_name, jobname)\n if path.exists(consolidate_file):\n print('file found', jobname)\n continue\n # check if jobname currently runs\n jobcheck = check_output(['bjobs', '-wJ', jobname])\n if jobname in jobcheck:\n print(jobcheck)\n continue\n # jobcheck = check_output(['bjobs', '-J', jobname],\n # stderr=STDOUT)\n # if 'not found' not in jobcheck:\n # print(jobcheck)\n # continue\n logfile = '{0}/{1}.log'.format(log_dir, jobname)\n print('submitting', jobname, logfile)\n command = ['bsub',\n '-J', jobname,\n '-o', logfile,\n '-W', str(int(req_time_consolidate)),\n '-M', str(int(memory_consolidate)),\n '-R', '\"span[hosts=1] rusage[mem={0}]\"'.format(memory_consolidate),\n '-n', str(2),\n 'python', code_path,\n '--job', 'consolidate',\n '--reference', reference_name,\n '--unknown', unknown_name,\n '--tomo', str(tomo_ith),\n '--dataset', str(dataset)]\n call(command)\n\nelif args['job'] == 'consolidate_run':\n tomos = range(len(tomo))\n for reference_name, unknown_name in all_pairs:\n for tomo_ith in tomos:\n consolidate_file = create_file_name(reference_name=reference_name,\n unknown_name=unknown_name,\n tomo_ith=tomo_ith,\n consolidate=True)\n jobname = consolidate_file.split('/')[-1].split('.fits')[0]\n jobname = '{0}__{1}'.format(run_name, jobname)\n if path.exists(consolidate_file):\n print('file found', jobname)\n continue\n logfile = '{0}/{1}.log'.format(log_dir, jobname)\n print('running', jobname, logfile, time.time() - time0)\n command = ['python', code_path,\n '--job', 'consolidate',\n '--reference', reference_name,\n '--unknown', unknown_name,\n '--tomo', str(tomo_ith),\n '--dataset', str(dataset)]\n call(command)\n print('done', time.time() - time0)\n\nelif args['job'] == 'corr_unknown_auto':\n # calculate the autocorrelation of the unknown sample\n hdf5_path = data_dir + '/' + data_name\n unknown_data = pd.read_hdf(hdf5_path, key=unknown_name)\n unknown_random = pd.read_hdf(hdf5_path, key=unknown_name + '_RANDOMS')\n # cut unknown by tomo\n z_lower, z_upper = tomo[tomo_ith]\n unknown_data = unknown_data[(unknown_data['z'] >= z_lower) &\n (unknown_data['z'] <= z_upper)]\n unknown_random = unknown_random[(unknown_random['z'] >= z_lower) &\n (unknown_random['z'] <= z_upper)]\n\n print('data loaded', time.time() - time0)\n # we'll keep it for all just to keep track.\n columns = np.zeros(1, dtype=[('logr', '1000f8'),\n ('dudu', '1000f8'),\n ('dudu_tot', 'f8'),\n ('duru', '1000f8'),\n ('duru_tot', 'f8'),\n ('ruru', '1000f8'),\n ('ruru_tot', 'f8'),\n ])\n\n # cut unknowns and do unknown calculations\n # first by kmeans region. Jackknife so neq\n unknown_data_conds = unknown_data['kmeans_region'] != kmeans_region\n unknown_random_conds = unknown_random['kmeans_region'] != kmeans_region\n if reference_name == unknown_name:\n # 1 is smaller!!\n unknown_data_conds = unknown_data_conds & (unknown_data['split'] == 1)\n unknown_random_conds = unknown_random_conds &\\\n (unknown_random['split'] == 1)\n # cut to ra and decs\n unknown_data_ra = unknown_data[unknown_data_conds]['ra'].values\n unknown_data_dec = unknown_data[unknown_data_conds]['dec'].values\n unknown_random_ra = unknown_random[unknown_random_conds]['ra'].values\n unknown_random_dec = unknown_random[unknown_random_conds]['dec'].values\n print('du, ru', len(unknown_data_ra), len(unknown_random_ra),\n time.time() - time0)\n if len(unknown_data_ra) == 0:\n raise Exception('unknown data empty!!')\n elif len(unknown_random_ra) == 0:\n raise Exception('unknown randoms empty!!')\n\n # only bother doing the unknown unknown for the first z_region_ith\n print('dudu', time.time() - time0)\n dudu, dudu_n2 = treecorr_autocorrelation(unknown_data_ra,\n unknown_data_dec)\n print('duru', time.time() - time0)\n duru, duru_n2 = treecorr_correlation(unknown_data_ra,\n unknown_data_dec,\n unknown_random_ra,\n unknown_random_dec)\n print('ruru', time.time() - time0)\n ruru, ruru_n2 = treecorr_autocorrelation(unknown_random_ra,\n unknown_random_dec)\n columns[0]['logr'] = dudu['meanlogr']\n columns[0]['dudu'] = dudu['npairs']\n columns[0]['dudu_tot'] = dudu['tot']\n columns[0]['duru'] = duru['npairs']\n columns[0]['duru_tot'] = duru['tot']\n columns[0]['ruru'] = ruru['npairs']\n columns[0]['ruru_tot'] = ruru['tot']\n print('column {0} updated'.format('0 for just the u-u autos'), time.time() - time0)\n\n # save\n fits_file = create_file_name(reference_name=reference_name,\n unknown_name=unknown_name,\n kmeans_region=kmeans_region,\n z_region_ith=z_region_ith,\n tomo_ith=tomo_ith, auto=True)\n fits = fitsio.FITS(fits_file,\n mode='rw', clobber=True)\n fits.write(columns)\n fits.close()\n print(fits_file)\n\n# do paircounts of specific set given commandline\nelif args['job'] == 'corr':\n hdf5_path = data_dir + '/' + data_name\n unknown_data = pd.read_hdf(hdf5_path, key=unknown_name)\n unknown_random = pd.read_hdf(hdf5_path, key=unknown_name + '_RANDOMS')\n if unknown_name != reference_name:\n reference_data = pd.read_hdf(hdf5_path, key=reference_name)\n reference_random = pd.read_hdf(hdf5_path, key=reference_name +\n '_RANDOMS')\n else:\n reference_data = unknown_data.copy()\n reference_random = unknown_random.copy()\n # cut unknown by tomo\n z_lower, z_upper = tomo[tomo_ith]\n unknown_data = unknown_data[(unknown_data['z'] >= z_lower) &\n (unknown_data['z'] <= z_upper)]\n unknown_random = unknown_random[(unknown_random['z'] >= z_lower) &\n (unknown_random['z'] <= z_upper)]\n\n print('data loaded', time.time() - time0)\n # we'll keep it for all just to keep track.\n n_zrows = max(reference_data['z_region']) + 1\n columns = np.zeros(n_zrows, dtype=[('z_region', 'i8'),\n ('logr', '1000f8'),\n ('dudr', '1000f8'),\n ('dudr_tot', 'f8'),\n ('durr', '1000f8'),\n ('durr_tot', 'f8'),\n ('rudr', '1000f8'),\n ('rudr_tot', 'f8'),\n ('rurr', '1000f8'),\n ('rurr_tot', 'f8'),\n ('drdr', '1000f8'),\n ('drdr_tot', 'f8'),\n ('drrr', '1000f8'),\n ('drrr_tot', 'f8'),\n ('rrrr', '1000f8'),\n ('rrrr_tot', 'f8'),\n ])\n\n # corr will do select set of z regions\n indx_lower = z_region_ith * z_iter\n indx_upper = indx_lower + z_iter\n z_regions = sorted(reference_data['z_region'].unique())[\n indx_lower: indx_upper]\n print(z_regions)\n\n # cut unknowns and do unknown calculations\n # first by kmeans region. Jackknife so neq\n unknown_data_conds = unknown_data['kmeans_region'] != kmeans_region\n unknown_random_conds = unknown_random['kmeans_region'] != kmeans_region\n if reference_name == unknown_name:\n # 1 is smaller!!\n unknown_data_conds = unknown_data_conds & (unknown_data['split'] == 1)\n unknown_random_conds = unknown_random_conds &\\\n (unknown_random['split'] == 1)\n # cut to ra and decs\n unknown_data_ra = unknown_data[unknown_data_conds]['ra'].values\n unknown_data_dec = unknown_data[unknown_data_conds]['dec'].values\n unknown_random_ra = unknown_random[unknown_random_conds]['ra'].values\n unknown_random_dec = unknown_random[unknown_random_conds]['dec'].values\n print('du, ru', len(unknown_data_ra), len(unknown_random_ra),\n time.time() - time0)\n if len(unknown_data_ra) == 0:\n raise Exception('unknown data empty!!')\n elif len(unknown_random_ra) == 0:\n raise Exception('unknown randoms empty!!')\n\n for z_region in z_regions:\n print(z_region, time.time() - time0)\n\n # cut all catalogs\n # first by kmeans region. Jackknife so neq\n reference_data_conds = reference_data['kmeans_region'] != kmeans_region\n reference_random_conds =\\\n reference_random['kmeans_region'] != kmeans_region\n # and z region for reference objects ONLY\n reference_data_conds = reference_data_conds &\\\n (reference_data['z_region'] == z_region)\n reference_random_conds = reference_random_conds &\\\n (reference_random['z_region'] == z_region)\n # and also by split if reference_name == unknown_name\n if reference_name == unknown_name:\n # 1 is smaller!!\n reference_data_conds = reference_data_conds &\\\n (reference_data['split'] == 0)\n reference_random_conds = reference_random_conds &\\\n (reference_random['split'] == 0)\n\n # cut to ra and decs\n reference_data_ra = reference_data[reference_data_conds]['ra'].values\n reference_data_dec = reference_data[reference_data_conds]['dec'].values\n reference_random_ra =\\\n reference_random[reference_random_conds]['ra'].values\n reference_random_dec =\\\n reference_random[reference_random_conds]['dec'].values\n\n print('du, ru, dr, rr', len(unknown_data_ra), len(unknown_random_ra),\n len(reference_data_ra), len(reference_random_ra),\n time.time() - time0)\n if len(reference_data_ra) == 0:\n continue\n elif len(reference_random_ra) == 0:\n continue\n\n # do treecorrs for the combos\n # dudr\n print('dudr', time.time() - time0)\n dudr, dudr_n2 = treecorr_correlation(unknown_data_ra,\n unknown_data_dec,\n reference_data_ra,\n reference_data_dec)\n\n # durr\n print('durr', time.time() - time0)\n durr, durr_n2 = treecorr_correlation(unknown_data_ra,\n unknown_data_dec,\n reference_random_ra,\n reference_random_dec)\n\n # rudr\n print('rudr', time.time() - time0)\n rudr, rudr_n2 = treecorr_correlation(unknown_random_ra,\n unknown_random_dec,\n reference_data_ra,\n reference_data_dec)\n\n # rurr\n print('rurr', time.time() - time0)\n # if unknown randoms > 10x the reference randoms, cut down signal\n # if unknown_random_ra.size > random_cutsize:\n # print('Cutting unknown random size from {0} to {1}'.format(\n # unknown_random_ra.size, random_cutsize))\n # unknown_random_index = np.random.choice(unknown_random_ra.size,\n # random_cutsize, replace=False)\n # unknown_random_ra = unknown_random_ra[unknown_random_index]\n # unknown_random_dec = unknown_random_dec[unknown_random_index]\n # if reference_random_ra.size > random_cutsize:\n # print('Cutting reference random size from {0} to {1}'.format(\n # reference_random_ra.size, random_cutsize))\n # reference_random_index = np.random.choice(reference_random_ra.size,\n # random_cutsize, replace=False)\n # reference_random_ra = reference_random_ra[reference_random_index]\n # reference_random_dec = reference_random_dec[reference_random_index]\n rurr, rurr_n2 = treecorr_correlation(unknown_random_ra,\n unknown_random_dec,\n reference_random_ra,\n reference_random_dec)\n\n print('drdr', time.time() - time0)\n drdr, drdr_n2 = treecorr_autocorrelation(reference_data_ra,\n reference_data_dec)\n print('drrr', time.time() - time0)\n drrr, drrr_n2 = treecorr_correlation(reference_data_ra,\n reference_data_dec,\n reference_random_ra,\n reference_random_dec)\n print('rrrr', time.time() - time0)\n rrrr, rrrr_n2 = treecorr_autocorrelation(reference_random_ra,\n reference_random_dec)\n\n columns[z_region]['z_region'] = z_region\n columns[z_region]['logr'] = dudr['meanlogr']\n columns[z_region]['dudr'] = dudr['npairs']\n columns[z_region]['dudr_tot'] = dudr['tot']\n columns[z_region]['durr'] = durr['npairs']\n columns[z_region]['durr_tot'] = durr['tot']\n columns[z_region]['rudr'] = rudr['npairs']\n columns[z_region]['rudr_tot'] = rudr['tot']\n columns[z_region]['rurr'] = rurr['npairs']\n columns[z_region]['rurr_tot'] = rurr['tot']\n\n columns[z_region]['drdr'] = drdr['npairs']\n columns[z_region]['drdr_tot'] = drdr['tot']\n columns[z_region]['drrr'] = drrr['npairs']\n columns[z_region]['drrr_tot'] = drrr['tot']\n columns[z_region]['rrrr'] = rrrr['npairs']\n columns[z_region]['rrrr_tot'] = rrrr['tot']\n print('column {0} updated'.format(z_region), time.time() - time0)\n\n # save\n # fits_file = create_filename()\n # fits = fitsio.FITS(fits_file,\n # mode='rw', clobber=True)\n # fits_out_name = paircount_dir + '/{0}__{1}__{2}__{3}__{4}.fits'.format(\n # unknown_name, reference_name, kmeans_region, z_region_ith, tomo_ith)\n fits_file = create_file_name(reference_name=reference_name,\n unknown_name=unknown_name,\n kmeans_region=kmeans_region,\n z_region_ith=z_region_ith,\n tomo_ith=tomo_ith)\n fits = fitsio.FITS(fits_file,\n mode='rw', clobber=True)\n fits.write(columns)\n fits.close()\n print(fits_file)\n\n\n# consolidate paircounts\nelif args['job'] == 'consolidate':\n # consolidate_file = paircount_dir + \\\n # '/{0}__{1}__{2}__consolidated.fits'.format(\n # unknown_name, reference_name, tomo_ith)\n consolidate_file = create_file_name(reference_name=reference_name,\n unknown_name=unknown_name,\n tomo_ith=tomo_ith,\n consolidate=True)\n\n # augment zbins\n zbins = np.append(0, np.append(zbins, np.inf))\n zcenters = 0.5 * (zbins[1:] + zbins[:-1])\n # tomos = range(len(tomo))\n # for tomo_ith in tomos:\n # for reference_name, unknown_name in all_pairs:\n hdf5_path = data_dir + '/' + data_name\n reference_data = pd.read_hdf(hdf5_path, key=reference_name)\n print('reference data loaded', time.time() - time0)\n\n z_regions_unique = sorted(reference_data['z_region'].unique())\n n_iter = int(np.ceil(len(z_regions_unique) / z_iter))\n n_iters = range(n_iter)\n n_zrows = max(reference_data['z_region']) + 1\n kmeans_centers = np.load(kmeans_path)\n kmeans_regions = [-1] + range(n_clusters)\n # if args['test_run']:\n # # take only a couple jobs to test speed\n # kmeans_regions = [-1]\n # z_regions_unique = [z_regions_unique[int(0.75 *\n # len(z_regions_unique))]]\n # n_iters = [n_iters[int(0.75 * len(n_iters))]]\n\n i8_dtype = '{0}i8'.format(len(kmeans_regions))\n f81000_dtype = '({0},1000)f8'.format(len(kmeans_regions))\n f8_dtype = '{0}f8'.format(len(kmeans_regions))\n bool_dtype = '{0}bool'.format(len(kmeans_regions))\n # TODO: could make z_region ones just i8 and f8. same with logr\n dtype = [('z_region', i8_dtype),\n ('logr', f81000_dtype),\n ('z_region_center', f8_dtype),\n ('z_region_lower', f8_dtype),\n ('z_region_upper', f8_dtype),\n ('dudr', f81000_dtype),\n ('dudr_tot', f8_dtype),\n ('durr', f81000_dtype),\n ('durr_tot', f8_dtype),\n ('rudr', f81000_dtype),\n ('rudr_tot', f8_dtype),\n ('rurr', f81000_dtype),\n ('rurr_tot', f8_dtype),\n ('drdr', f81000_dtype),\n ('drdr_tot', f8_dtype),\n ('drrr', f81000_dtype),\n ('drrr_tot', f8_dtype),\n ('rrrr', f81000_dtype),\n ('rrrr_tot', f8_dtype),\n ('dudu', f81000_dtype),\n ('dudu_tot', f8_dtype),\n ('duru', f81000_dtype),\n ('duru_tot', f8_dtype),\n ('ruru', f81000_dtype),\n ('ruru_tot', f8_dtype),\n ('kmeans_region', i8_dtype),\n ('kmeans_ra', f8_dtype),\n ('kmeans_dec', f8_dtype),\n ('good', bool_dtype)]\n columns = np.zeros(n_zrows, dtype=dtype)\n keys = ['z_region',\n 'dudr_tot',\n 'durr_tot',\n 'rudr_tot',\n 'rurr_tot',\n 'drdr_tot',\n 'drrr_tot',\n 'rrrr_tot',\n ]\n keys_1000 = ['dudr', 'durr', 'rudr', 'rurr',\n 'drdr', 'drrr', 'rrrr',\n 'logr']\n keys_unknown = ['dudu_tot',\n 'duru_tot',\n 'ruru_tot',\n ]\n keys_1000_unknown = ['dudu', 'duru', 'ruru']\n for kmeans_region_i, kmeans_region in enumerate(kmeans_regions):\n print(reference_name, unknown_name, kmeans_region_i,\n tomo_ith, time.time() - time0)\n # load up the unknowns\n fits_file_unknown = create_file_name(kmeans_region=kmeans_region,\n unknown_name=unknown_name,\n reference_name=reference_name,\n tomo_ith=tomo_ith,\n auto=True)\n if path.exists(fits_file_unknown):\n print(reference_name, unknown_name, kmeans_region_i,\n 'auto', tomo_ith, time.time() - time0)\n data_unknown = fitsio.read(fits_file_unknown, ext=-1)\n\n zregiondict = {key[0]: [] for key in dtype}\n\n num_collected = 0\n for z_region_ith in n_iters:\n indx_lower = z_region_ith * z_iter\n indx_upper = indx_lower + z_iter\n # the specific ones here\n z_regions = np.array(z_regions_unique[indx_lower: indx_upper])\n # fits_file = paircount_dir + '/{0}__{1}__{2}__{3}__{4}.fits'.\n # format(\n # unknown_name, reference_name,\n # kmeans_region, z_region_ith, tomo_ith)\n fits_file = create_file_name(kmeans_region=kmeans_region,\n z_region_ith=z_region_ith,\n unknown_name=unknown_name,\n reference_name=reference_name,\n tomo_ith=tomo_ith)\n if path.exists(fits_file):\n num_collected += 1\n print(reference_name, unknown_name, kmeans_region_i,\n z_region_ith, tomo_ith, time.time() - time0)\n data = fitsio.read(fits_file, ext=-1)\n\n z_region_i = data['z_region'][z_regions]\n # print_time(989)\n # for key in keys + keys_1000:\n # columns[key][z_region_i, kmeans_region_i] = \\\n # data[key][z_regions]\n # # columns[keys][z_region_i, kmeans_region_i] =\\\n # # data[keys][z_regions]\n # # columns[keys_1000][z_region_i, kmeans_region_i] =\\\n # # data[keys_1000][z_regions]\n # columns['kmeans_region'][z_region_i, kmeans_region_i] = \\\n # kmeans_region\n # if kmeans_region >= 0:\n # columns['kmeans_ra'][z_region_i, kmeans_region_i] = \\\n # kmeans_centers[kmeans_region][0]\n # columns['kmeans_dec'][z_region_i, kmeans_region_i] = \\\n # kmeans_centers[kmeans_region][1]\n # columns['good'][z_region_i, kmeans_region_i] = \\\n # z_region_i == z_regions\n # if sum(z_region_i != z_regions) > 0:\n # print(len(z_regions), sum(z_region_i == z_regions))\n # print(z_regions[z_region_i != z_regions],\n # zcenters[z_regions[z_region_i != z_regions]],\n # kmeans_region)\n\n # # keep rewriting this one which shouldn't change\n # columns['z_region_center'][z_region_i, kmeans_region_i] = \\\n # zcenters[z_region_i]\n # columns['z_region_lower'][z_region_i, kmeans_region_i] = \\\n # zbins[z_region_i]\n # columns['z_region_upper'][z_region_i, kmeans_region_i] = \\\n # zbins[z_region_i + 1]\n\n # # put in the unknowns if it exists\n # if path.exists(fits_file_unknown):\n # for key in keys_unknown + keys_1000_unknown:\n # columns[key][z_region_i, kmeans_region_i] = \\\n # data_unknown[key][0]\n\n # test out the other method\n z_region_i = data['z_region'][z_regions]\n for key in keys + keys_1000:\n zregiondict[key].append(data[key][z_regions])\n zregiondict['kmeans_region'].append([kmeans_region] * len(z_regions))\n if kmeans_region >= 0:\n zregiondict['kmeans_ra'].append([kmeans_centers[kmeans_region][0]] * len(z_regions))\n zregiondict['kmeans_dec'].append([kmeans_centers[kmeans_region][1]] * len(z_regions))\n else:\n zregiondict['kmeans_ra'].append([0] * len(z_regions))\n zregiondict['kmeans_dec'].append([0] * len(z_regions))\n zregiondict['good'].append(z_region_i == z_regions)\n zregiondict['z_region_center'].append(zcenters[z_region_i])\n zregiondict['z_region_lower'].append(zbins[z_region_i])\n zregiondict['z_region_upper'].append(zbins[z_region_i + 1])\n\n # put in the unknowns if it exists\n for key in keys_unknown:\n if path.exists(fits_file_unknown):\n zregiondict[key].append([data_unknown[key][0]] * len(z_regions))\n else:\n zregiondict[key].append([0] * len(z_regions))\n for key in keys_1000_unknown:\n if path.exists(fits_file_unknown):\n zregiondict[key].append([data_unknown[key][0]] * len(z_regions))\n else:\n zregiondict[key].append([[0] * 1000] * len(z_regions))\n # bad news bears if none found!\n if num_collected == 0:\n continue\n z_region_assign = np.hstack(zregiondict['z_region'])\n for key, dtype_str in dtype:\n # determine whether to hstack or vstack\n if '1000' in dtype_str:\n assignment = np.vstack(zregiondict[key])\n else:\n assignment = np.hstack(zregiondict[key])\n columns[key][z_region_assign, kmeans_region_i] = assignment\n # print('assigned', key, time.time() - time0)\n # save!\n fits = fitsio.FITS(consolidate_file,\n mode='rw', clobber=True)\n fits.write(columns)\n fits.close()\n # at the end, load it all up, and save as numpy file, which is much faster\n data = fitsio.read(consolidate_file)\n np.save(consolidate_file.replace('.fits', '.npy'), data)\n\nelif args['job'] == 'log_statistics':\n df_list = []\n kmeans_regions = [-1] + range(n_clusters)\n tomos = range(len(tomo))\n for reference_name, unknown_name in all_pairs:\n hdf5_path = data_dir + '/' + data_name\n reference_data = pd.read_hdf(hdf5_path, key=reference_name)\n print('reference data loaded', unknown_name, reference_name,\n time.time() - time0)\n\n z_regions = sorted(reference_data['z_region'].unique())\n n_iter = int(np.ceil(len(z_regions) / z_iter))\n n_iters = range(n_iter)\n for tomo_ith in tomos:\n for kmeans_region in kmeans_regions:\n for z_region_ith in n_iters:\n fits_file = create_file_name(reference_name=reference_name,\n unknown_name=unknown_name,\n kmeans_region=kmeans_region,\n z_region_ith=z_region_ith,\n tomo_ith=tomo_ith)\n jobname = fits_file.split('/')[-1].split('.fits')[0]\n jobname = '{0}__{1}'.format(run_name, jobname)\n logfile = '{0}/{1}.log'.format(log_dir, jobname)\n if path.exists(logfile):\n d = load_log_stats(logfile)\n d['reference'] = reference_name\n d['unknown'] = unknown_name\n d['kmeans_region'] = float(kmeans_region)\n d['z_region_ith'] = float(z_region_ith)\n d['tomo_ith'] = float(tomo_ith)\n df_list.append(d)\n\n df = pd.DataFrame(df_list)\n df.to_csv(run_dir + '/{0}__{1}__fit_statistics.csv'.format(run_name,\n dataset))\n","sub_path":"code/batch_runs/run41.py","file_name":"run41.py","file_ext":"py","file_size_in_byte":60131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"466446525","text":"import os\nimport requests\nimport time\nfrom os.path import join as pjoin\nfrom splinter import Browser\nfrom splinter.exceptions import ElementDoesNotExist\nfrom CGUIBrowserProcess import CGUIBrowserProcess\n\ndef init_module(test_cases, args):\n \"\"\"Preprocesses test cases\n\n Returns: (2-tuple)\n =======\n base_cases Cases that can begin immediately\n wait_cases Cases that need one of the base cases to complete first\n \"\"\"\n base_cases = []\n wait_cases = {}\n for test_case in test_cases:\n if not 'solvator_tests' in test_case:\n base_cases.append(test_case)\n else:\n do_copy = args.copy\n cases = handle_solvator_tests(test_case, do_copy)\n\n if 'localhost' in args.base_url.lower() and do_copy:\n base_case = cases[0]\n base_cases.append(base_case)\n wait_cases[base_case['label']] = cases[1:]\n else:\n base_cases += cases\n return base_cases, wait_cases\n\ndef handle_solvator_tests(test_case, do_copy=False):\n if not 'solvator_tests' in test_case:\n raise ValueError(\"Missing 'solvator_tests'\")\n solvtor_tests = test_case[solvent_tests]\n\n placeholder = 'SOLVATOR_TEST_PLACEHOLDER'\n found = False\n index = None\n check_lists = 'presteps', 'poststeps'\n for step_num, step in enumerate(test_case['steps']):\n for check_list in check_lists:\n if check_list in step and placeholder in step[check_list]:\n found = True\n index = step[check_list].index(placeholder)\n break\n if found:\n break\n if not found:\n raise ValueError(\"Missing '\"+placeholder+\"'\")\n\n for num, case in enumerate(cases):\n case['case_id'] = num\n case['solvator_link'] = step_num\n\n if do_copy:\n copy_action = \"copy_dir(ncopy={})\".format(len(solvator_tests))\n cases[0]['steps'][step_num][check_list].insert(index, copy_action)\n\n return cases\n\nclass FEPBrowserProcess(CGUIBrowserProcess):\n def __init__(self, todo_q, done_q, **kwargs):\n self.jobid = None\n self.output = None # charmm-gui-jobid.tgz\n super(FEPBrowserProcess, self).__init__(todo_q, done_q, **kwargs)\n\n def select(self, name, value):\n self.browser.select(name, value)\n\n def fill(self, name, value):\n self.browser.fill(name, value)\n\n def xpath(self, element):\n self.browser.find_by_xpath(element).click()\n\n def click_by_name(self, name):\n self.browser.find_by_name(name).click()\n\n def init_system(self, test_case):\n url = self.base_url + test_case['url_ym']\n browser = self.browser\n browser.visit(url)\n\n # attach files for this test case\n browser.attach_file('files[]', pjoin(self.base, 'lig1.mol2'))\n browser.attach_file('files[]', pjoin(self.base, 'lig2.mol2'))\n browser.attach_file('files[]', pjoin(self.base, 'lig3.mol2'))\n\n self.go_next(test_case['steps'][0]['wait_text'])\n\n jobid = browser.find_by_css(\".jobid\").first.text.split()[-1]\n test_case['jobid'] = jobid\n self.jobid = jobid\n if 'output' in test_case:\n self.output = test_case['output']\n\n def download(self, saveas):\n url = \"{url}?doc=input/download&jobid={jobid}\".format(url=self.base_url, jobid=self.jobid)\n print(\"downloading %s to %s\" % (url, saveas))\n\n user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'\n headers = {'User-Agent': user_agent}\n\n user, password = 'testing', 'lammps'\n r = requests.get(url, headers=headers, auth=(user, password))\n open(saveas, \"wb\").write(r.content)\n fsize = float(os.stat(saveas).st_size) / (1024.0 * 1024.0)\n print(\"download complete, file size is %5.2f MB\" % fsize)\n\n def run(self):\n super(FEPBrowserProcess, self).run()\n if self.output:\n self.download(self.output + '.tgz')\n else:\n self.download('charmm-gui-%s.tgz' % str(self.jobid))\n","sub_path":"FEPBrowserProcess.py","file_name":"FEPBrowserProcess.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"477782547","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nfrom allennlp.modules.elmo import Elmo, batch_to_ids\nfrom utils import transport_1_0_2, transport_1_0_2_image, extract_image_features\nimport torch.nn.functional as F\nclass WordLevel(nn.Module): \n \n def __init__(self, word_hidden_size):\n super(WordLevel, self).__init__()\n options_file = \"https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_options.json\"\n weight_file = \"https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_weights.hdf5\"\n self.elmo = Elmo(options_file, weight_file, 1, dropout=0.2, requires_grad = False)\n self.lstm = nn.LSTM(1024, word_hidden_size, num_layers=1, \n bidirectional=True, dropout=0.2)\n\n def forward(self, input):\n sentences = input\n if torch.cuda.is_available():\n character_ids = batch_to_ids(sentences).cuda()\n else:\n character_ids = batch_to_ids(sentences)\n embeddings = self.elmo(character_ids)['elmo_representations'][0]\n embedded = embeddings.permute(1, 0 , 2)\n output, (hidden,_) = self.lstm(embedded)\n hidden_output = torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1)\n\n return output, hidden_output \n\n\nclass SentLevel(nn.Module):\n def __init__(self, sent_hidden_size=256, word_hidden_size=256):\n super(SentLevel, self).__init__()\n self.lstm = nn.LSTM(2 * word_hidden_size, sent_hidden_size, bidirectional=True)\n\n\n def forward(self, input):\n output, (hidden, _) = self.lstm(input)\n hidden_output = torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1)\n return output, hidden_output \n\nclass ChoiceNet(nn.Module):\n \n def __init__(self, word_hidden_size):\n super(ChoiceNet, self).__init__()\n options_file = \"https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_options.json\"\n weight_file = \"https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_weights.hdf5\"\n self.elmo = Elmo(options_file, weight_file, 1, dropout=0.2, requires_grad = False)\n self.lstm = nn.LSTM(1024, word_hidden_size, num_layers=1, \n bidirectional=True, dropout=0.2)\n\n def forward(self, input):\n sentences = input\n if torch.cuda.is_available():\n character_ids = batch_to_ids(sentences).cuda()\n else:\n character_ids = batch_to_ids(sentences)\n embeddings = self.elmo(character_ids)['elmo_representations'][0]\n embedded = embeddings.permute(1, 0, 2) \n output, (hidden,_) = self.lstm(embedded)\n hidden_output = torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1)\n\n return output, hidden_output\n\n\nclass Text_Net(nn.Module): \n def __init__(self, word_hidden_size, sent_hidden_size):\n super(Text_Net, self).__init__()\n self.step_net = WordLevel(word_hidden_size)\n self.text_net = SentLevel(sent_hidden_size, word_hidden_size)\n\n def forward(self, input_text): \n output_list = []\n for i in input_text: \n output, step_hidden_state = self.step_net(i)\n if torch.cuda.is_available():\n output_list.append(step_hidden_state.cpu().detach().numpy())\n else:\n output_list.append(step_hidden_state.detach().numpy())\n if torch.cuda.is_available():\n output_step = torch.FloatTensor(output_list).cuda()\n else:\n output_step = torch.FloatTensor(output_list)\n\n output, hidden_output = self.text_net(output_step)\n\n return output, hidden_output \n\n\nclass Question_Net(nn.Module): \n def __init__(self, word_hidden_size, sent_hidden_size):\n super(Question_Net, self).__init__()\n self.word_net = WordLevel(word_hidden_size)\n self.sen_net = SentLevel(sent_hidden_size, word_hidden_size)\n\n def forward(self, input_question):\n output_list = []\n for i in input_question: \n output, word_hidden_state = self.word_net(i)\n if torch.cuda.is_available():\n output_list.append(word_hidden_state.cpu().detach().numpy())\n else:\n output_list.append(word_hidden_state.detach().numpy())\n if torch.cuda.is_available():\n output_word = torch.FloatTensor(output_list).cuda()\n else:\n output_word = torch.FloatTensor(output_list)\n\n output, hidden_output = self.sen_net(output_word)\n\n return output, hidden_output\n\n\n\n\nclass Attention(nn.Module):\n def __init__(self, word_hidden_size, sent_hidden_size, batch_size):\n super(Attention, self).__init__() \n self.dim = word_hidden_size*2\n self.batch_size = batch_size\n self.fc1 = nn.Linear(2*self.dim, self.dim)\n self.fc2 = nn.Linear(self.dim, self.dim)\n self.linear_dm = nn.Linear(self.dim,self.dim)\n self.linear_ms = nn.Linear(self.dim, 1)\n self.linear_rm = nn.Linear(self.dim,self.dim)\n self.linear_qm = nn.Linear(self.dim,self.dim)\n self.linear_rr = nn.Linear(self.dim,self.dim)\n self.linear_rg = nn.Linear(self.dim,self.dim)\n self.linear_qg = nn.Linear(self.dim,self.dim) \n def forward(self, context_output, question_output, u, image_output): \n \n if torch.cuda.is_available(): \n r = torch.zeros(context_output.size()[1], 1, self.dim).cuda() \n else:\n r = torch.zeros(context_output.size()[1], 1, self.dim)\n \n\n #context_output = self.fc1(torch.cat((context_output.permute(1,0,2), image_output.permute(1,0,2)), dim=2))\n ####tanh\n context_output = context_output.permute(1,0,2) \n\n for i in question_output: \n output1 = self.linear_dm(context_output) #(seq_leng, batch, dim) -> (batch, seq, dim)\n output2 = self.linear_rm(r) # (batch, 1, dim)\n output3 = self.linear_qm(i.unsqueeze(1)) # (batch, 1, dim)\n m = torch.tanh(output1 + output2 + output3) \n s = F.softmax(self.linear_ms(m), dim=1).permute(0,2,1)\n r = torch.matmul(s, context_output) + torch.tanh(self.linear_rr(r))\n g = self.linear_rg(r).squeeze(1) + self.linear_qg(u) # g (batch, 1, 512)\n\n return g \n\n\nclass Impatient_Reader_Model(nn.Module): \n def __init__(self, word_hidden_size, sent_hidden_size, batch_size):\n super(Impatient_Reader_Model, self).__init__()\n self.text = Text_Net(word_hidden_size, sent_hidden_size)\n self.question = Question_Net(word_hidden_size, sent_hidden_size) \n self.attention = Attention(word_hidden_size, sent_hidden_size, batch_size)\n self.attention_image = Attention(word_hidden_size, sent_hidden_size, batch_size)\n self.choice = ChoiceNet(word_hidden_size)\n self.fc3 = nn.Linear(word_hidden_size*8, 512)\n self.dropout = nn.Dropout(p = 0.2)\n self.fc4 = nn.Linear(512, 1) \n self.fc5 = nn.Linear(word_hidden_size*8, 512)\n self.fc6 = nn.Linear(512, 1)\n self.images = nn.LSTM(1000, word_hidden_size, bidirectional=True) \n # self.weight = torch.tensor(0.9, requires_grad=True).cuda()\n # self.fc8 = nn.Linear(1,1)\n\n def exponent_neg_manhattan_distance(self, x1, x2):\n return torch.sum(torch.abs(x1 - x2), dim=1)\n def cosine_dot_distance(self, x1, x2):\n return torch.sum(torch.mul(x1, x2), dim=1)\n def Infersent(self, x1, x2):\n return torch.cat((x1, x2, torch.abs(x1 - x2), x1 * x2), 1)\n\n def forward(self, input_context, input_question, input_choice, input_images, image_path):\n input_context = transport_1_0_2(input_context)\n input_question = transport_1_0_2(input_question)\n input_choice = transport_1_0_2(input_choice) \n input_images = transport_1_0_2_image(input_images) \n\n input_images = extract_image_features(input_images, image_path)\n\n context_output, _ = self.text(input_context)\n question_output, final_question_hidden = self.question(input_question)\n image_output, _ = self.images(input_images) \n\n g = self.attention(context_output, question_output, final_question_hidden, image_output) \n g2 = self.attention_image(image_output, question_output, final_question_hidden, context_output)\n\n output_choice_list = [] \n for i in input_choice: \n output_choice, hidden_output_choice = self.choice(i)\n similarity_scores = self.Infersent(g, hidden_output_choice)\n similarity_scores = self.dropout(torch.tanh(self.fc3(similarity_scores)))\n similarity_scores = self.fc4(similarity_scores)\n \n similarity_scores_image = self.Infersent(g2, hidden_output_choice)\n similarity_scores_image = self.dropout(torch.tanh(self.fc5(similarity_scores_image)))\n similarity_scores_image = self.fc6(similarity_scores_image) \n\n #similarity_scores = self.exponent_neg_manhattan_distance(hidden_output_question,hidden_output_choice) \n # print(self.weight)\n # self.weight = torch.sigmoid(self.fc8(self.weight))\n # print(self.weight)\n similarity_scores = similarity_scores * 0.95 + similarity_scores_image * 0.05 \n output_choice_list.append(similarity_scores) \n \n return output_choice_list \n\n\n\n\n\n","sub_path":"impatient_reader_visual/impatient_reader_model_visual.py","file_name":"impatient_reader_model_visual.py","file_ext":"py","file_size_in_byte":9575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"621193890","text":"import codecs\nimport requests\nimport base64\nimport operator\nfrom collections import *\nimport re\nimport sys\nimport json\nfrom urllib.parse import unquote\n\nfrom pyfasttext import FastText\n\nfrom itertools import permutations\n\nimport hashlib\n\nimport datetime\nfrom multiprocessing.connection import Listener\nfrom array import array\n\nimport math\n\ndef clean_unicode(word,is_reverse =0):\n\trules = [\n\t ['REPLACE','ේ',['ෙ','්']],\n\t ['REPLACE','ෛ',['ෙ','ෙ']],\n\t ['REPLACE','ො',['ෙ','ා']],\n\t ['REPLACE','ෝ',['ෙ','ා','්']],\n\t ['REPLACE','ෝ',['ො','්']],\n\t ['REPLACE','ෞ',['ෙ','ෟ']],\n\t ['REPLACE','ෲ',['ෘ','ෘ']]\n\t ]\n\t \n\tdelete_rules = [\n\t ['IGNORE','\\u200d',['්','*','ය']],\n\t ['IGNORE','\\u200d',['්','*','ර']]\n\t ]\n\t \n\tadd_rules = [\n\t ['IGNORE','\\u200d',['ක','්','*','ය']],\n\t ['IGNORE','\\u200d',['බ','්','*','ය']],\n\t ['IGNORE','\\u200d',['ග','්','*','ය']],\n\t ['IGNORE','\\u200d',['ච','්','*','ය']],\n\t ['IGNORE','\\u200d',['ජ','්','*','ය']],\n\t ['IGNORE','\\u200d',['ට','්','*','ය']],\n\t ['IGNORE','\\u200d',['ඪ','්','*','ය']],\n\t ['IGNORE','\\u200d',['ණ','්','*','ය']],\n\t ['IGNORE','\\u200d',['ත','්','*','ය']],\n\t ['IGNORE','\\u200d',['ථ','්','*','ය']],\n\t ['IGNORE','\\u200d',['ද','්','*','ය']],\n\t ['IGNORE','\\u200d',['ධ','්','*','ය']],\n\t ['IGNORE','\\u200d',['න','්','*','ය']],\n\t ['IGNORE','\\u200d',['ප','්','*','ය']],\n\t ['IGNORE','\\u200d',['භ','්','*','ය']],\n\t ['IGNORE','\\u200d',['ම','්','*','ය']],\n\t ['IGNORE','\\u200d',['ය','්','*','ය']],\n\t ['IGNORE','\\u200d',['ල','්','*','ය']],\n\t ['IGNORE','\\u200d',['ව','්','*','ය']],\n\t ['IGNORE','\\u200d',['ශ','්','*','ය']],\n\t ['IGNORE','\\u200d',['ෂ','්','*','ය']],\n\t ['IGNORE','\\u200d',['ස','්','*','ය']],\n\t ['IGNORE','\\u200d',['හ','්','*','ය']],\n\t ['IGNORE','\\u200d',['ක','්','*','ර']],\n\t ['IGNORE','\\u200d',['ග','්','*','ර']],\n\t ['IGNORE','\\u200d',['ඝ','්','*','ර']],\n\t ['IGNORE','\\u200d',['ජ','්','*','ර']],\n\t ['IGNORE','\\u200d',['ත','්','*','ර']],\n\t ['IGNORE','\\u200d',['ද','්','*','ර']],\n\t ['IGNORE','\\u200d',['ප','්','*','ර']],\n\t ['IGNORE','\\u200d',['බ','්','*','ර']],\n\t ['IGNORE','\\u200d',['භ','්','*','ර']],\n\t ['IGNORE','\\u200d',['ම','්','*','ර']],\n\t ['IGNORE','\\u200d',['ව','්','*','ර']],\n\t ['IGNORE','\\u200d',['ශ','්','*','ර']],\n\t ['IGNORE','\\u200d',['ස','්','*','ර']],\n\t ['IGNORE','\\u200d',['හ','්','*','ර']]\n\t ] \n\t \n\tword_char_list = list(word)\n\tis_changed =0\n\t\n\t \n\tif(is_reverse ==1): \n\t\tfor x in range(len(rules)):\n\t\t\n\t\t\tif rules[x][0] ==\"REPLACE\":\n\t\t\t\t\n\t\t\t\twordtemp =\"\"\n\t\t\t\tfor y in range(len(word_char_list)):\n\t\t\t\t\tif len(rules[x][2])==2:\n\t\t\t\t\t\tif word_char_list[y] ==rules[x][2][0]:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif y=no_char_before and p 0:\n if array[0] == 'ු' or array[0] == 'ූ' or array[0] == '්' or array[0] == 'ා' or array[0] == 'ි' or array[0] == 'ී' or array[0] == 'ී' or array[0] == 'ෑ' or array[0] == 'ැ':\n return True\n else:\n return False\n else:\n return False\n\n\ndef is_joiner_missing_word(word1, word2):\n array = []\n for i in word2:\n array.append(i)\n for i in word1:\n if i in array:\n array.remove(i)\n\n if len(array) > 0:\n if array[0] == '\\u200d':\n return True\n else:\n return False\n else:\n return False\n\n\ndef split_check(words, word):\n first_word =[]\n last_word = []\n space_suggestion = {}\n# for i in words:\n# if i[0] != '' and word != '' and i[0][0] != '' and i[0][0] == word[0] and i[0] in word:\n# if get_hash(i[0]) in hashed_dic and get_hash_md5(i[0]) in spell_checking_dic:\n# first_word.append(i[0])\n# if i[0] != '' and word != '' and i[0][-1] != '' and i[0][-1] == word[-1] and i[0] in word:\n# if get_hash(i[0]) in hashed_dic and get_hash_md5(i[0]) in spell_checking_dic:\n# last_word.append(i[0])\n \n# for i in first_word:\n# for j in last_word:\n# if i+j == word:\n# s = i + ' ### ' + j\n# space_suggestion[s]=1\n dic_words = {}\n for i in words:\n dic_words[i[0]] = 0\n \n \n for i in range(1,len(word)):\n if get_hash_md5(word[:i]) in spell_checking_dic and get_hash_md5(word[i:]) in spell_checking_dic:\n if word[:i] in dic_words and word[i:] in dic_words:\n space_suggestion[word[:i] + ' 1' + word[i:]] = 1\n# elif word[:i] in dic_words:\n# space_suggestion[word[:i] + ' 2' + word[i:]] = 2\n# elif word[i:] in dic_words:\n# space_suggestion[word[:i] + '3 ' + word[i:]] = 3\n# else:\n# space_suggestion[word[:i] + ' 4' + word[i:]] = 4\n\n if word[-i:] in other_file and get_hash_md5(word[:-i]) in spell_checking_dic:\n space_suggestion[word[:-i] + '5 ' + word[-i:]] = 5 \n \n \n return space_suggestion\n\n\ndef get_modified_input_word(word):\n new_sin_word = word\n if '්යා' in word and 'ර්යා' not in word:\n new_sin_word = new_sin_word.replace('්යා', '්‍යා')\n if '්ය' in word and 'ර්ය' not in word:\n new_sin_word = new_sin_word.replace('්ය', '්‍ය')\n\n if 'බ්රිී' in word:\n new_sin_word = new_sin_word.replace('බ්රිී', 'බ්‍රි')\n if 'ක්රි' in word:\n new_sin_word = new_sin_word.replace('ක්රි', 'ක්‍රි')\n if 'ප්රි' in word:\n new_sin_word = new_sin_word.replace('ප්රි', 'ප්‍රි')\n if 'ග්රි' in word:\n new_sin_word = new_sin_word.replace('ග්රි', 'ග්‍රි')\n if 'ද්රි' in word:\n new_sin_word = new_sin_word.replace('ද්රි', 'ද්‍රි')\n\n if 'බ්රී' in word:\n new_sin_word = new_sin_word.replace('බ්රී', 'බ්‍රී')\n if 'ක්රී' in word:\n new_sin_word = new_sin_word.replace('ක්රී', 'ක්‍රී')\n if 'ප්රී' in word:\n new_sin_word = new_sin_word.replace('ප්රී', 'ප්‍රී')\n if 'ග්රී' in word:\n new_sin_word = new_sin_word.replace('ග්රී', 'ග්‍රී')\n if 'ද්රී' in word:\n new_sin_word = new_sin_word.replace('ද්රී', 'ද්‍රී')\n\n if 'බ්ර' in word:\n new_sin_word = new_sin_word.replace('බ්ර', 'බ්‍ර')\n if 'ප්ර' in word:\n new_sin_word = new_sin_word.replace('ප්ර', 'ප්‍ර')\n if 'ක්ර' in word:\n new_sin_word = new_sin_word.replace('ක්ර', 'ක්‍ර')\n if 'ග්ර' in word:\n new_sin_word = new_sin_word.replace('ග්ර', 'ග්‍ර')\n if 'ද්ර' in word:\n new_sin_word = new_sin_word.replace('ද්ර', 'ද්‍ර')\n\n return new_sin_word\n\n\ndef show_entry_fields(): # Display box function\n\n #print(suggestion_generator(e1.get()))\n msg = messagebox.showinfo(\"Hello_Python\", suggestion_generator(e1.get()))\n\n\ndef call_counter(func): # Part of the levenshtein minimum edit distance algorithm\n def helper(*args, **kwargs):\n helper.calls += 1\n return func(*args, **kwargs)\n\n helper.calls = 0\n helper.__name__ = func.__name__\n return helper\n\n\ndef memoize(func):\n mem = {}\n\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in mem:\n mem[key] = func(*args, **kwargs)\n return mem[key]\n\n return memoizer\n\n\n@call_counter\n@memoize\ndef levenshtein(s, t): # Minimum edit distance algorithm\n if s == \"\":\n return len(t)\n if t == \"\":\n return len(s)\n if s[-1] == t[-1]:\n cost = 0\n else:\n cost = 1\n\n res = min([levenshtein(s[:-1], t) + 1,\n levenshtein(s, t[:-1]) + 1,\n levenshtein(s[:-1], t[:-1]) + cost])\n return res\n\n\n# #print(levenshtein(\"ළකුණ\", \"ලකුණු\"))\n# #print(\"The function was called \" + str(levenshtein.calls) + \" times!\")\n\ndef get_permutations(word, changed_letters):\n all = changed_letters\n indices = []\n word_lst = []\n for i in word: # put all the letters in the word to a list\n word_lst.append(i)\n for i in range(len(word_lst)):\n if word_lst[i] in all: # get the index numbers of the Nana Lala letters of that particular word\n indices.append(i)\n final = []\n for i in range(1, len(indices) + 1):\n\n perm = permutations(indices, i) # Generate the permutations\n\n # Print the obtained permutations\n for i in list(perm):\n lst = []\n for j in i:\n lst.append(j)\n lst.sort()\n if lst not in final:\n final.append(lst)\n return word_lst, final\n\n\ndef get_Bindu_words(word):\n all = ['න', 'ං']\n permutated_words = []\n word_lst, final = get_permutations(word, all)\n #print(word_lst)\n #print(final)\n for i in final:\n per_word = ['']\n inside_once = False\n for j in range(len(i)):\n #print(i[j])\n #print(len(word_lst))\n if word_lst[i[j]] == 'න' and i[j] < len(word_lst)-2 and word_lst[i[j]+1] == '්':\n if inside_once == False:\n per_word = word_lst.copy()\n inside_once = True\n #print(\"LLLMMMM\")\n per_word[i[j]] = 'ං'\n per_word[i[j]+1] = ''\n\n concat = ''\n for k in per_word:\n concat += k\n hash_dig = get_hash(concat)\n if (hash_dig in hashed_dic) and (concat not in permutated_words):\n permutated_words.append(concat)\n return permutated_words\n # if word_lst[i[j]] == 'ං':\n # if j <= 0:\n # per_word = word_lst.copy()\n # per_word[i[j]] = 'න'\n # per_word[i[j] + 1] = '්'\n\n\ndef nana_lala(word): # function which generates permutations of a given word\n # Get all permutations of length 2\n # and length 2\n all = ['න', 'ණ', 'ල', 'ළ', 'ස', 'ශ', 'ෂ', 'ත', 'ථ', 'බ', 'භ', 'ද', 'ඳ', 'ධ', 'ග', 'ට', 'ඨ', 'ච', 'ඡ', 'ජ', 'ක', 'ඛ', 'ග', 'ඝ', 'ජ', 'ඣ', 'ප', 'ඵ', 'ඩ', 'ඪ']\n # simple = ['න', 'ල', 'ශ', 'ත', 'බ', 'ද']\n # capital = ['ණ', 'ළ', 'ෂ', 'ථ', 'භ', 'ධ']\n # indices = []\n # word_lst = []\n permutated_words = []\n # for i in word: # put all the letters in the word to a list\n # word_lst.append(i)\n # for i in range(len(word_lst)):\n # if word_lst[i] in all: # get the index numbers of the Nana Lala letters of that particular word\n # indices.append(i)\n # final = []\n # for i in range(1, len(indices) + 1):\n #\n # perm = permutations(indices, i) # Generate the permutations\n #\n # # Print the obtained permutations\n # for i in list(perm):\n # lst = []\n # for j in i:\n # lst.append(j)\n # lst.sort()\n # if lst not in final:\n # final.append(lst)\n word_lst, final = get_permutations(word, all)\n for i in final:\n per_word = ['']\n for j in range(len(i)):\n dha_word = False\n if word_lst[i[j]] == 'න':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ණ'\n per_word2[i[j]] = 'ණ'\n\n if word_lst[i[j]] == 'ණ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'න'\n per_word2[i[j]] = 'න'\n\n if word_lst[i[j]] == 'ල':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ළ'\n per_word2[i[j]] = 'ළ'\n\n if word_lst[i[j]] == 'ළ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ල'\n per_word2[i[j]] = 'ල'\n\n if word_lst[i[j]] == 'ශ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ෂ'\n per_word2[i[j]] = 'ස'\n dha_word = True\n\n if word_lst[i[j]] == 'ෂ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ශ'\n per_word2[i[j]] = 'ස'\n dha_word = True\n\n if word_lst[i[j]] == 'ස':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ශ'\n per_word2[i[j]] = 'ෂ'\n dha_word = True\n\n if word_lst[i[j]] == 'ත':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ථ'\n per_word2[i[j]] = 'ථ'\n\n if word_lst[i[j]] == 'ථ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ත'\n per_word2[i[j]] = 'ත'\n\n if word_lst[i[j]] == 'බ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'භ'\n per_word2[i[j]] = 'භ'\n\n if word_lst[i[j]] == 'භ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'බ'\n per_word2[i[j]] = 'බ'\n\n if word_lst[i[j]] == 'ද':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ධ'\n per_word2[i[j]] = 'ඳ'\n dha_word = True\n\n if word_lst[i[j]] == 'ධ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ද'\n per_word2[i[j]] = 'ඳ'\n dha_word = True\n \n if word_lst[i[j]] == 'ඳ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ද'\n per_word2[i[j]] = 'ධ'\n dha_word = True\n\n if word_lst[i[j]] == 'ග':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ඟ'\n per_word2[i[j]] = 'ඟ'\n\n # if word_lst[i[j]] == 'දු':\n # if j <= 0:\n # per_word = word_lst.copy()\n # per_word2 = word_lst.copy()\n # per_word[i[j]] = 'ඳු'\n #\n # if word_lst[i[j]] == 'ඳු':\n # if j <= 0:\n # per_word = word_lst.copy()\n # per_word2 = word_lst.copy()\n # per_word[i[j]] = 'දු'\n\n #if word_lst[i[j]] == 'ු':\n # if j <= 0:\n # per_word = word_lst.copy()\n # per_word2 = word_lst.copy()\n # per_word[i[j]] = 'ූ'\n # per_word2[i[j]] = 'ූ'\n\n #if word_lst[i[j]] == 'ූ':\n # if j <= 0:\n # per_word = word_lst.copy()\n # per_word2 = word_lst.copy()\n # per_word[i[j]] = 'ු'\n # per_word2[i[j]] = 'ු'\n\n if word_lst[i[j]] == 'ට':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ඨ'\n per_word2[i[j]] = 'ඨ'\n\n if word_lst[i[j]] == 'ඨ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ට'\n per_word2[i[j]] = 'ට'\n\n if word_lst[i[j]] == 'ඡ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ච'\n per_word2[i[j]] = 'ජ'\n dha_word = True\n\n if word_lst[i[j]] == 'ච':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ඡ'\n per_word2[i[j]] = 'ඡ'\n\n if word_lst[i[j]] == 'ජ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ඡ'\n per_word2[i[j]] = 'ඡ'\n \n if word_lst[i[j]] == 'ක':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ඛ'\n per_word2[i[j]] = 'ඛ'\n\n if word_lst[i[j]] == 'ඛ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ක'\n per_word2[i[j]] = 'ක'\n \n if word_lst[i[j]] == 'ග':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ඝ'\n per_word2[i[j]] = 'ඝ'\n\n if word_lst[i[j]] == 'ඝ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ග'\n per_word2[i[j]] = 'ග'\n \n if word_lst[i[j]] == 'ජ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ඣ'\n per_word2[i[j]] = 'ඣ'\n\n if word_lst[i[j]] == 'ඣ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ජ'\n per_word2[i[j]] = 'ජ'\n \n if word_lst[i[j]] == 'ප':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ඵ'\n per_word2[i[j]] = 'ඵ'\n\n if word_lst[i[j]] == 'ඵ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ප'\n per_word2[i[j]] = 'ප'\n \n if word_lst[i[j]] == 'ඩ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ඪ'\n per_word2[i[j]] = 'ඪ'\n\n if word_lst[i[j]] == 'ඪ':\n if j <= 0:\n per_word = word_lst.copy()\n per_word2 = word_lst.copy()\n per_word[i[j]] = 'ඩ'\n per_word2[i[j]] = 'ඩ'\n\n concat = ''\n for k in per_word:\n concat += k\n hash_dig = get_hash(concat)\n if hash_dig in hashed_dic:\n permutated_words.append(concat)\n modified_concat = get_modified_input_word(concat)\n hash_dig = get_hash(modified_concat)\n if hash_dig in hashed_dic:\n permutated_words.append(modified_concat)\n if dha_word:\n concat2 = ''\n for k in per_word2:\n concat2 += k\n\n hash_dig = get_hash(concat2)\n if hash_dig in hashed_dic:\n permutated_words.append(concat2)\n modified_concat2 = get_modified_input_word(concat2)\n hash_dig = get_hash(modified_concat2)\n if hash_dig in hashed_dic:\n permutated_words.append(modified_concat2)\n\n return permutated_words\n \ndef swapPositions(list, pos1, pos2): \n \n list[pos1], list[pos2] = list[pos2], list[pos1]\n str1=''\n for i in list:\n str1+=i\n\n return str1\n \ndef get_swapped_words(word):\n lst = []\n stuff1 = list(word)\n stuff2 = stuff1.copy()\n if '්' in stuff1:\n pos = word.index('්')\n str1=''\n str2=''\n if len(word)-2>=pos:\n str1 = swapPositions(stuff1, pos, pos+1)\n if pos>0:\n str2 = swapPositions(stuff2, pos, pos-1)\n if get_hash(str1) in hashed_dic and get_hash_md5(str1) in spell_checking_dic:\n lst.append(str1)\n if get_hash(str2) in hashed_dic and get_hash_md5(str2) in spell_checking_dic:\n lst.append(str2)\n \n return lst\n\n\ndef get_RU_replaced_words(word):\n lst=[]\n if 'රැ' in word:\n w1= word.replace('රැ','රු')\n if get_hash(w1) in hashed_dic and get_hash_md5(w1) in spell_checking_dic:\n lst.append(w1)\n if 'රු' in word:\n w2= word.replace('රු','රැ')\n if get_hash(w2) in hashed_dic and get_hash_md5(w2) in spell_checking_dic:\n lst.append(w2)\n if 'රෑ' in word:\n w3= word.replace('රෑ','රූ')\n if get_hash(w3) in hashed_dic and get_hash_md5(w3) in spell_checking_dic:\n lst.append(w3)\n if 'රූ' in word:\n w4= word.replace('රූ','රෑ')\n if get_hash(w4) in hashed_dic and get_hash_md5(w4) in spell_checking_dic:\n lst.append(w4)\n \n return lst\n \n \ndef suggestion_generator(sinhala_word):\n # model = FastText('sinhala_all2.bin')\n a = datetime.datetime.now()\n # #print(model.similarity('බල්ල', 'බල්ලා'))\n user_sin_word = sinhala_word\n sin_word = get_modified_input_word(sinhala_word)\n\n permutated_nana_lala_sin_word = nana_lala(sin_word)\n permutated_bindu_sin_word = get_Bindu_words(sin_word)\n\n permutated_sin_word = permutated_nana_lala_sin_word + permutated_bindu_sin_word\n words = model.nearest_neighbors(sin_word, k=2000)\n minnnnn = []\n min1 = {}\n min2 = {}\n min3 = {}\n min_other = {}\n min = 1000000000\n max_frequency = 0\n # #print(words)\n suggested_words = []\n space_suggestion = split_check(words, sin_word)\n swapped_words = get_swapped_words(sin_word)\n for i in swapped_words:\n words.append((i,1000))\n \n RU_replaced_words = get_RU_replaced_words(sin_word)\n for i in RU_replaced_words:\n words.append((i,1000))\n \n final_dic = {}\n for i in words:\n punc = [',','.','/','?']\n punctuation_free_word = ''\n for k in i[0]:\n if k not in punc:\n punctuation_free_word += k\n\n\n if get_hash(punctuation_free_word) in hashed_dic:\n #and get_hash_md5(punctuation_free_word) in spell_checking_dic\n minimum_edit_distance = levenshtein(punctuation_free_word, sin_word)\n final_dic[punctuation_free_word+str(hashed_dic[get_hash(punctuation_free_word)])] = i[1] *math.log((hashed_dic[get_hash(punctuation_free_word)]+1)) #add or remove the log\n\n if punctuation_free_word in permutated_sin_word:\n final_dic[punctuation_free_word+str(hashed_dic[get_hash(punctuation_free_word)])] *= 10**1.35\n print(punctuation_free_word+\"GGGGGGGGGGGGGGGGGGGGG\")\n\n if is_papili_missing_word(sin_word, punctuation_free_word) and minimum_edit_distance<=1:\n final_dic[punctuation_free_word+str(hashed_dic[get_hash(punctuation_free_word)])] *= 10**1.3\n print(punctuation_free_word+\"DDDDDDDDDDDDDDDDDD\")\n\n if is_joiner_missing_word(sin_word, punctuation_free_word):\n final_dic[punctuation_free_word+str(hashed_dic[get_hash(punctuation_free_word)])] *= 10**1.12\n print(punctuation_free_word+\"SSSSSSSSSSSSSSSSS\")\n\n minimum_edit_distance = levenshtein(punctuation_free_word, sin_word)\n\n if punctuation_free_word in permutated_sin_word:\n ##print(final_dic[punctuation_free_word])\n final_dic[punctuation_free_word+str(hashed_dic[get_hash(punctuation_free_word)])] /= 10*minimum_edit_distance\n ##print(\"LLLLLLLLLLLLLLLLLLLLLLLLLL\")\n ##print(punctuation_free_word)\n ##print(hashed_dic[get_hash('ළඟයි')])\n elif minimum_edit_distance<3:\n final_dic[punctuation_free_word+str(hashed_dic[get_hash(punctuation_free_word)])] /= 10**minimum_edit_distance\n print(punctuation_free_word+\"KKKKKKKKKKKKKKKKKK\")\n else:\n final_dic[punctuation_free_word+str(hashed_dic[get_hash(punctuation_free_word)])] /= 100**minimum_edit_distance\n\n\n sorted_final_dic2 = sorted(final_dic.items(), key=lambda kv: kv[1])[::-1]\n sorted_final_dic = []\n \n for i in sorted_final_dic2:\n sorted_final_dic.append((i[0]+' '+str(i[1]),i[1]))\n\n\n max_frequency = 0\n max_word = ''\n #print(permutated_sin_word)\n for i in permutated_sin_word:\n hex_dig = get_hash(i)\n if hex_dig in hashed_dic:\n if hashed_dic[hex_dig] / 10 ** levenshtein(i, sin_word) > max_frequency:\n max_frequency = hashed_dic[hex_dig] / 10 ** levenshtein(i, sin_word)\n max_word = i\n\n if max_word != '' and max_word not in final_dic:\n sorted_final_dic.insert(0, (max_word+str(hashed_dic[get_hash(max_word)])+' '+str(max_frequency), max_frequency))\n elif max_word != '' and max_word in final_dic and (max_word, final_dic[max_word]) not in sorted_final_dic[:5]:\n sorted_final_dic.insert(0, (max_word+str(hashed_dic[get_hash(max_word)])+' '+str(max_frequency), max_frequency))\n \n if sin_word != '' and get_hash_md5(sin_word) in spell_checking_dic and get_hash(sin_word) in hashed_dic and (sin_word, hashed_dic[get_hash(sin_word)]) not in sorted_final_dic[:5]:\n sorted_final_dic.insert(0, (sin_word+str(hashed_dic[get_hash(sin_word)])+' '+str(max_frequency)+'######', max_frequency))\n \n sorted_final_dic = sorted(space_suggestion.items(), key=lambda kv: kv[1]) + sorted_final_dic \n \n return sorted_final_dic\n\t\n\ndef sync_time():\n a1 = datetime.datetime.now()\n return a1\n\n\n\nif __name__ == \"__main__\":\n '''\n m1 =sync_time()\n model = FastText('/var/www/html/morphy/fasttext/sinhala_all2.bin')\n m2 =sync_time()\n # model = FastText('result/fil9.bin')\n d1=sync_time()\n hashed_dic = hashing_tagged_copus()\n spell_checking_dic = hashing_spell_checking_dic()\n other_file = reading_other_file()\n d2=sync_time()\n\t'''\n \n input_word = sys.argv[1]\n print(clean_unicode(input_word,0)[0])\n\n \n\t\t\n\t\n\n","sub_path":"Final source/morphy/fasttext/ser.py","file_name":"ser.py","file_ext":"py","file_size_in_byte":32242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"335460830","text":"# proszę to traktować jako dodatek\n# uwagi o kopiowaniu służyły tylko uświadomieniu Państwu możliwości zaistneinia takiego problemu\n\n# to ćwiczenie rózni się od tego co robiliśmy na zajęciach\n\n# stworz (dowolną) listę o długości 2 (składjąca się z 2 elemntów)\n# i przypisz ją do zmiennej x\nlista1 = [2,3]\nx = lista1\n# przypisz listę x na zmienną y na y[0] oraz y[1]\ny = [x,x]\n# dodaj element do listy x\nx.append(2)\n# sparwdz czy y[0] wskazuje na ten sam adres w pamięci komputera co y[1]\n# użyj funkcji id()\nprint(id(y[0])==id(y[1]))\n\n# przypisz listę x na zmienną z[0] i z[1] używajć metody copy() \nz = [x.copy(), x.copy()]\n# sparwdz czy z[0] wskazuje na ten sam adres w pamięci komputera co z[1]\nprint(id(z[0]) == id(z[1]))","sub_path":"socjologia/python1/pliki/cw03.py","file_name":"cw03.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"125492739","text":"#! /usr/bin/env python3\r\nimport gnureadline as readline\r\nimport os\r\nimport re\r\n\r\n\r\nclass Command:\r\n def __init__(self, name, desc, func, *usage):\r\n self.name = name\r\n self.desc = desc\r\n self.func = func\r\n self.usage = usage\r\n\r\n def __call__(self, *s):\r\n options = []\r\n for usage in range(len(self.usage)):\r\n if usage < len(s):\r\n (worked, res) = self.usage[usage](s[usage])\r\n if worked:\r\n options.append(res)\r\n else:\r\n if self.usage[usage].optional:\r\n break\r\n else:\r\n print(res)\r\n print(self)\r\n return False\r\n else:\r\n if self.usage[usage].optional:\r\n break\r\n else:\r\n print(self)\r\n return False\r\n\r\n self.func(*options)\r\n\r\n def __repr__(self, *args):\r\n return 'Usage: ' + self.name + ' ' + ' '.join(str(u) for u in self.usage)\r\n\r\n\r\nclass Usage:\r\n def __init__(self, func, usage, optional=False):\r\n self.func = func\r\n self.usage = usage\r\n self.optional = optional\r\n\r\n def __call__(self, args):\r\n return self.func(args) # ret tuple (bool success, ret val)\r\n\r\n def __repr__(self):\r\n return ''.join(['<' if not self.optional else '[', self.usage, '>' if not self.optional else ']'])\r\n\r\n\r\nclass Completer(object):\r\n \"\"\"\r\n This is an autocompleter to be used with the python readline class\r\n sample implementation and documentation is located at:\r\n http://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input\r\n \"\"\"\r\n def __init__(self, commands):\r\n self.commands = commands\r\n self.re_space = re.compile('.*\\s+$', re.M)\r\n\r\n def _listdir(self, root):\r\n res = []\r\n for name in os.listdir(root):\r\n path = os.path.join(root, name)\r\n if os.path.isdir(path):\r\n name += os.sep\r\n res.append(name)\r\n return res\r\n\r\n def _complete_path(self, path=None):\r\n if not path:\r\n return self._listdir('.')\r\n dirname, rest = os.path.split(path)\r\n tmp = dirname if dirname else '.'\r\n res = [os.path.join(dirname, p) for p in self._listdir(tmp) if p.startswith(rest)]\r\n # more than one match, or single match which does not exist (typo)\r\n if len(res) > 1 or not os.path.exists(path):\r\n return res\r\n # resolved to a single directory, so return list of files below it\r\n if os.path.isdir(path):\r\n return [os.path.join(path, p) for p in self._listdir(path)]\r\n # exact file match terminates this completion\r\n return [path + ' ']\r\n\r\n def complete_extra(self, args):\r\n if not args:\r\n return self._complete_path('.')\r\n # treat the last arg as a path and complete it\r\n return self._complete_path(args[-1])\r\n\r\n def complete(self, text, state):\r\n buffer = readline.get_line_buffer()\r\n line = readline.get_line_buffer().split()\r\n\r\n # show all commands\r\n if not line:\r\n return [c + ' ' for c in self.commands][state]\r\n # account for last argument ending in a space\r\n if self.re_space.match(buffer):\r\n line.append('')\r\n # resolve command to the implementation function\r\n cmd = line[0].strip()\r\n if cmd in self.commands:\r\n args = line[1:]\r\n if args:\r\n return (self.complete_extra(args) + [None])[state]\r\n return [cmd + ' '][state]\r\n results = [c + ' ' for c in self.commands if c.startswith(cmd)] + [None]\r\n return results[state]\r\n","sub_path":"launcher/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"553899696","text":"# -*- coding: utf-8 -*-\n# MLToolkit (mltoolkit)\n\n\"\"\"\nMLToolkit - a verstile helping library for machine learning\n===========================================================\n'MLToolkit' is a Python package providing a set of user-friendly functions to \nhelp building machine learning models in data science research or production \nfocused projects. It is compatible with and interoperate with popular data \nanalysis, manipulation and machine learning libraries Pandas, Sci-kit Learn, \nTensorflow, Statmodels, Catboost, XGboost, etc.\n\nMain Features\n-------------\n- Data Extraction (SQL, Flatfiles, etc.)\n- Exploratory data analysis (statistical summary, univariate analysis, etc.)\n- Feature Extraction and Engineering\n- Model performance analysis, Explain Predictions and comparison between models\n- Cross Validation and Hyper parameter tuning\n- JSON input script for executing model building and scoring tasks.\n- Model Building UI\n- Auto ML (automated machine learning)\n- Model Deploymet and Serving via RESTful API\n\n\nAuthor\n------\n- Sumudu Tennakoon\n\nLinks\n-----\nWebsite: http://sumudu.tennakoon.net/projects/MLToolkit\nGithub: https://mltoolkit.github.io/MLToolKit\n\nLicense\n-------\nApache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\"\"\"\n\n# IF QUERY HAS DROP TABLE, TRUNCATE TABLE, DELETE, UPDATE, CREATE, set a control flag on (safety)\n# Modify output timing to execute query + row count\n\nfrom datetime import datetime\nimport gc\nimport traceback\nimport gc\nimport os\nfrom timeit import default_timer as timer\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport re\nimport urllib\nimport sqlalchemy \nimport csv\n\ntry:\n import pyodbc\nexcept:\n print('pyodbc not found! Data base query fufnctions disabled.')\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom mltk.string import *\nfrom mltk.explore import *\n\ndef number_unit_example():\n edges_std = ['0', '1p', '1n', '1u', '1m', '1c', '1', '100', '500', \n '1K', '2K', '5K', '10K', '20K', '50K', '100K', '500K', \n '1M', '2M', '5M', '10M', '100M', '200M', '500M', \n '1G', '2G', '5G', '10G', '100G', '200G', '500G',\n '1T', '2T', '5T', '10T', '100T', '200T', '500T',\n '1P', '2P', '5P', '10P', '100P', '200P', '500P',\n '1E']\n print(edges_std)\n \ndef get_number_units(): \n units = {'p':0.000000000001,\n 'n':0.000000001,\n 'u':0.000001,\n 'm':0.001,\n 'c':0.01,\n 'd':0.1,\n '':1,\n 'D':10,\n 'H':100,\n 'K':1000,\n 'M':1000000,\n 'G':1000000000,\n 'T':1000000000000,\n 'P':1000000000000000,\n 'E':1000000000000000000,\n 'INF':np.inf \n }\n units = pd.DataFrame(data=units.items(), columns=['unit', 'multiplier'])\n print(units)\n return units\n\n###############################################################################\n##[ I/O FUNCTIONS]############################################################# \n###############################################################################\ndef read_data(connector, params=None):\n connector = {\n \"method\":\"sql\", #\"pickle\", \"csv\", \"excel\"\n \"source\":{\"dbms\":\"mssql\", \"server\":\"SQLSERVER1\", \"database\":\"SampleDB\", \"schema\":None},\n \"auth\":{'type':'user', 'user':'user1', 'pwd':'password123'},\n \"params\":{}\n }\n \n connector2 = {\n \"method\":\"sql\", #\"pickle\", \"csv\", \"excel\"\n \"source\":{\"dbms\":\"snowflake\", \"server\":\"SQLSERVER1\", \"database\":\"SampleDB\", \"schema\":None}, # account (server)\n \"auth\":{'type':'user', 'user':'user1', 'password':'password123', \"role\": None}, \n \"params\":{}\n }\n \n return None \n \ndef read_data_csv(file, separator=',', quoting= 'MINIMAL', compression='infer', encoding='utf-8'):\n \"\"\"\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html\n \n Parameters\n ---------- \n file : str\n separator : str\n index : bool\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n quoting : {'ALL', MINIMAL', 'NONNUMERIC', 'NONE'}, default 'MINIMAL'\n encoding : {'utf-8', 'utf-16'}, default 'utf-8'\n \n Returns\n -------\n DataFrame : pandas.DataFrame\n \"\"\"\n if quoting=='ALL':\n quoting = csv.QUOTE_ALL\n elif quoting=='MINIMAL':\n quoting = csv.QUOTE_MINIMAL \n elif quoting=='NONNUMERIC':\n quoting = csv.QUOTE_NONNUMERIC \n elif quoting=='NONE':\n quoting = csv.QUOTE_NONE \n \n try:\n start_time = timer() \n DataFrame = pd.read_csv(filepath_or_buffer=file, sep=separator, quoting=quoting, \n compression=compression, encoding=encoding) \n execute_time = timer() - start_time\n except:\n execute_time = 0\n DataFrame = pd.DataFrame()\n print(traceback.format_exc())\n \n \n \n print('{:,d} records were loaded. execute time = {} s'.format(len(DataFrame.index), execute_time))\n \n return DataFrame\n\ndef write_data_csv(DataFrame, file, separator=',', index=False, quoting='ALL', encoding='utf-8', compression='infer', chunksize=None):\n \"\"\"\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html\n \n Parameters\n ---------- \n DataFrame : pandas.DataFrame\n file : str\n separator : str\n index : bool\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n quoting : {'ALL', MINIMAL', 'NONNUMERIC', 'NONE'}, default 'MINIMAL'\n encoding : {'utf-8', 'utf-16'}, default 'utf-8'\n chunksize : int, default None\n \n Returns\n -------\n None\n \"\"\"\n \n if quoting=='ALL':\n quoting = csv.QUOTE_ALL\n elif quoting=='MINIMAL':\n quoting = csv.QUOTE_MINIMAL \n elif quoting=='NONNUMERIC':\n quoting = csv.QUOTE_NONNUMERIC \n elif quoting=='NONE':\n quoting = csv.QUOTE_NONE \n try:\n start_time = timer() \n DataFrame.to_csv(path_or_buf=file, sep=separator, encoding=encoding, index=index, \n quoting=quoting, compression=compression, chunksize=chunksize)\n execute_time = timer() - start_time\n except:\n execute_time = 0\n print(traceback.format_exc())\n \n print('{:,d} records were written. execute time = {} s'.format(len(DataFrame.index), execute_time))\n \n return None\n\ndef read_data_pickle(file, compression='infer'):\n \"\"\"\n https://docs.python.org/3/library/pickle.html\n \"Warning The pickle module is not secure against erroneous or maliciously constructed data. \n Never unpickle data received from an untrusted or unauthenticated source.\"\n \n Parameters\n ---------- \n file : str\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n \n Returns\n -------\n DataFrame : pandas.DataFrame\n \"\"\"\n try:\n start_time = timer() \n DataFrame = pd.read_pickle(path=file, compression=compression)\n execute_time = timer() - start_time\n except:\n execute_time = 0\n print(traceback.format_exc())\n DataFrame = pd.DataFrame()\n \n \n print('{:,d} records were loaded. execute time = {} s'.format(len(DataFrame.index), execute_time))\n \n return DataFrame\n\ndef write_data_pickle(DataFrame, file, compression='infer', protocol=3):\n \"\"\"\n https://docs.python.org/3/library/pickle.html\n \"Warning The pickle module is not secure against erroneous or maliciously constructed data. \n Never unpickle data received from an untrusted or unauthenticated source.\"\n \n Parameters\n ---------- \n DataFrame : pandas.DataFrame\n file : str\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n protocol : int {1, 2, 3, 4}\n 0 is human-readable/backwards compatible with earlier versions of Python\n read more at https://docs.python.org/3/library/pickle.html\n Returns\n -------\n None \n \"\"\"\n try:\n start_time = timer() \n DataFrame.to_pickle(path=file, compression=compression, protocol=protocol)\n execute_time = timer() - start_time\n except:\n execute_time = 0\n print(traceback.format_exc())\n \n print('{:,d} records were written. execute time = {} s'.format(len(DataFrame.index), execute_time))\n\ndef create_sql_connect_string(server=None, database=None, auth=None, dbms='mssql', autocommit = 'True'): \n if dbms=='mssql':\n # Download ODBC Driver https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server\n driver = 'ODBC Driver 13 for SQL Server' # 'SQL Server' # \n if auth['type']=='machine':\n connect_string = r'Driver={'+driver+'};SERVER='+server+';DATABASE='+database+';TRUSTED_CONNECTION=yes;autocommit='+autocommit+';'\n connect_string = urllib.parse.quote_plus(connect_string)\n elif auth['type']=='user':\n uid = auth['uid'] \n pwd = auth['pwd'] \n connect_string = r'Driver={'+driver+'};SERVER='+server+';DATABASE='+database+';UID='+uid+'r;PWD='+pwd+'; autocommit='+autocommit+';'\n connect_string = urllib.parse.quote_plus(connect_string)\n elif dbms=='mysql':\n connect_string = None\n elif dbms=='snowflake':\n connect_string = None\n else:\n raise Exception(\"Parameter dbms not provided. Accepted values are {'mssql', 'mysql', 'snowflake'}\")\n return connect_string\n\ndef read_data_sql(query=None, server=None, database=None, auth=None, dbms='mssql', params=None):\n \"\"\"\n Parameters\n ----------\n query : str\n SQL SELECT query\n server : str\n Database Server\n database : str\n Database\n auth : dict\n e.g. auth = {'type':'user', 'uid':'user', 'pwd':'password'} for username password authentication\n auth = {'type':'machine', 'uid':None, 'pwd':None} for machine authentication\n \n Returns\n -------\n DataFrame : pandas.DataFrame\n \"\"\" \n execute_time = 0\n \n if query!=None and server!=None and auth!=None: \n coerce_float=True\n index_col=None\n parse_dates=None\n \n try:\n if auth['type']=='machine':\n connect_string = r'Driver={SQL Server};SERVER='+server+';DATABASE='+database+';TRUSTED_CONNECTION=yes;'\n elif auth['type']=='user':\n uid = auth['uid'] \n pwd = auth['pwd'] \n connect_string = r'Driver={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+uid+'r;PWD='+pwd+'}'\n else:\n raise Exception('No db server authentication method provided!')\n connection = pyodbc.connect(connect_string) \n \n start_time = timer() \n DataFrame = pd.read_sql_query(sql=query, con=connection, coerce_float=coerce_float, index_col=index_col, parse_dates=parse_dates)\n execute_time = timer() - start_time\n \n connection.close() \n except:\n print('Database Query Fialed!:\\n{}\\n'.format(traceback.format_exc()))\n DataFrame=pd.DataFrame()\n else:\n print('No Query provided !')\n DataFrame=pd.DataFrame()\n \n print('{:,d} records were loaded. execute time = {} s'.format(len(DataFrame.index), execute_time))\n \n return DataFrame\n\ndef write_data_sql(DataFrame, server=None, database=None, schema=None, table=None, index=False, dtypes=None, if_exists='fail', auth=None, dbms='mssql', params=None):\n \"\"\"\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html\n \n Parameters\n ----------\n DataFrame : pandas.DataFrame\n DataFrame\n server : str\n Database Server\n database : str\n Database\n schema : str\n Database Schema\n table : str\n Table name\n if_exists : {'fail', 'replace', 'append'}, default 'fail'\n Action if the table already exists.\n auth : dict\n e.g. auth = {'type':'user', 'uid':'user', 'pwd':'password'} for username password authentication\n auth = {'type':'machine', 'uid':None, 'pwd':None} for machine authentication\n \n Returns\n -------\n None\n \"\"\" \n \n # Download ODBC Driver https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server\n driver = 'ODBC Driver 13 for SQL Server' # 'SQL Server' # \n autocommit = 'True'\n fast_executemany = True\n execute_time = 0\n \n if server!=None and database!=None and schema!=None and table!=None and auth!=None : \n try:\n if auth['type']=='machine':\n #connect_string = r'Driver={SQL Server};SERVER='+server+';DATABASE='+database+';TRUSTED_CONNECTION=yes;' #ODBC (slow)\n connect_string = r'Driver={'+driver+'};SERVER='+server+';DATABASE='+database+';TRUSTED_CONNECTION=yes;autocommit='+autocommit+';'\n connect_string = urllib.parse.quote_plus(connect_string)\n elif auth['type']=='user':\n uid = auth['uid'] \n pwd = auth['pwd'] \n #connect_string = r'Driver={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+uid+'r;PWD='+pwd+'}' #ODBC (slow)\n connect_string = r'Driver={'+driver+'};SERVER='+server+';DATABASE='+database+';UID='+uid+'r;PWD='+pwd+'; autocommit='+autocommit+';'\n connect_string = urllib.parse.quote_plus(connect_string)\n else:\n raise Exception('No db server authentication method provided !') \n \n #connection = pyodbc.connect(connect_string) #ODBC (slow)\n engine = sqlalchemy.create_engine(\"mssql+pyodbc:///?odbc_connect=\"+connect_string, fast_executemany=fast_executemany)\n connection = engine\n \n start_time = timer() \n if dtypes==None:\n DataFrame.to_sql(name=table, con=connection, schema=schema, index= index, if_exists=if_exists)\n else:\n DataFrame.to_sql(name=table, con=connection, schema=schema, index= index, dtype=dtypes, if_exists=if_exists)\n execute_time = timer() - start_time\n \n #connection.close() \n engine.dispose()\n rowcount = len(DataFrame.index)\n except:\n print('Database Query Failed! Check If ODBC driver installed. \\nIf not, Download ODBC Driver from https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-serve.:\\n{}\\n'.format(traceback.format_exc()))\n rowcount = 0\n else:\n print('Check the destiniation table path (server, database, schema, table, auth) !')\n rowcount = 0\n \n print('{:,d} records were written. execute time = {} s'.format(rowcount, execute_time))\n \n return rowcount\n\ndef execute_sql_query(query=None, server=None, database=None, auth=None, params=None, dbms='mssql', on_error='ignore'):\n \"\"\"\n Parameters\n ----------\n query : str\n SQL SELECT query\n server : str\n Database Server\n database : str\n Database\n auth : dict\n e.g. auth = {'type':'user', 'uid':'user', 'pwd':'password'} for username password authentication\n auth = {'type':'machine', 'uid':None, 'pwd':None} for machine authentication\n params : dict\n extra parameters (not implemented)\n \n Returns\n -------\n DataFrame : pandas.DataFrame\n \"\"\" \n # Download ODBC Driver https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server\n driver = 'ODBC Driver 13 for SQL Server' # 'SQL Server' # \n autocommit = 'True'\n fast_executemany = True\n \n if server!=None and database!=None and query!=None and auth!=None :\n try:\n if auth['type']=='machine':\n connect_string = r'Driver={'+driver+'};SERVER='+server+';DATABASE='+database+';TRUSTED_CONNECTION=yes;autocommit='+autocommit+';'\n connect_string = urllib.parse.quote_plus(connect_string)\n \n elif auth['type']=='user':\n uid = auth['uid'] \n pwd = auth['pwd'] \n connect_string = r'Driver={'+driver+'};SERVER='+server+';DATABASE='+database+';UID='+uid+'r;PWD='+pwd+'; autocommit='+autocommit+';'\n connect_string = urllib.parse.quote_plus(connect_string)\n else:\n raise Exception('No db server authentication method provided !')\n \n engine = sqlalchemy.create_engine(\"mssql+pyodbc:///?odbc_connect=\"+connect_string, fast_executemany=fast_executemany)\n \n # connection\n connection = engine.connect()\n \n #transaction\n trans = connection.begin()\n \n # execute\n start_time = timer() \n result = connection.execute(query)\n execute_time = timer() - start_time\n \n try:\n rowcount = result.rowcount\n print('{} rows affected. execute time = {} s'.format(rowcount,execute_time))\n except:\n rowcount = -1\n print('ERROR in fetching affected rows count. execute time = {} s'.format(execute_time))\n \n # commit\n trans.commit()\n \n # close connections, results set and dispose engine (moved to finally)\n #connection.close()\n #result.close()\n #engine.dispose()\n except:\n print(r'ERROR: Check If ODBC driver installed. \\nIf not, Download ODBC Driver from https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server:\\n{}\\n'.format(traceback.format_exc()))\n rowcount = 0\n finally:\n # close connections, results set and dispose engine\n try:\n connection.close()\n except:\n print('Failed to close connection !')\n try:\n result.close()\n except:\n print('Failed to close results !')\n try:\n engine.dispose()\n except:\n print('Failed to dispose engine !')\n \n return rowcount \n\ndef sql_server_database_list(server, auth=None, user_database_only=True, dbms='mssql'):\n \"\"\"\n Reference: https://docs.microsoft.com/en-us/sql/relational-databases/system-compatibility-views/sys-sysdatabases-transact-sql?view=sql-server-2017\n \"\"\"\n \n query = \"\"\"\n SELECT \n @@SERVERNAME AS [ServerName],\n NAME AS [DBName],\n STATUS AS [Status],\n CRDATE AS [CreateDate]\n FROM master.dbo.sysdatabases (NOLOCK)\n WHERE Name NOT IN ( 'master','tempdb','model' ,'msdb')\n \"\"\" \n DBList = read_data_sql(query=query, server=server, database='master', auth=auth, params=None)\n \n return DBList\n \ndef sql_server_database_usage_report(server, database, auth=None, schema=None, table=None, user_tables_only=True, dbms='mssql', unit='KB'):\n \"\"\"\n Reference: https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-tables-transact-sql?view=sql-server-2017\n \"\"\"\n \n if user_tables_only:\n user_tables_only_condition = \"AND table.is_ms_shipped = 0 \" # is_ms_shipped = 1 (indicates this object was shipped or created by Microsoft), 0 (indicates this object was created by a user)\n else:\n user_tables_only_condition = \"\"\n \n if schema != None:\n schema_condition = \"AND schema.NAME = '{}'\".format(schema)\n else:\n schema_condition = \"\"\n\n if table != None:\n table_condition = \"AND table.NAME = '{}'\".format(table)\n else:\n table_condition = \"\"\n\n #Unit conversion\n if unit == 'KB':\n multiplier = 1.0\n if unit == 'MB':\n multiplier = 1.0/1024.0\n if unit == 'GB':\n multiplier = 1.0/(1024.0*1024.0) \n if unit == 'TB':\n multiplier = 1.0/(1024.0*1024.0*1024.0) \n \n if dbms == 'mssql':\n query = \"\"\"\n SELECT\n @@SERVERNAME AS [Server],\n DB_Name() AS [DB],\n [schema].NAME AS [Schema],\n [table].NAME AS [Table],\n [table].CREATE_DATE AS [CreateDate],\n [table].MODIFY_DATE AS [ModifyDate],\t\t\n [part].ROWS AS [Rows],\n SUM(alloc.total_pages) * 8 AS [TotalSpaceKBx],\n SUM(alloc.used_pages) * 8 AS [UsedSpaceKBx],\n FROM\n sys.tables [table] (NOLOCK)\n INNER JOIN \n sys.indexes (NOLOCK) [ix] ON ([table].OBJECT_ID = [ix].OBJECT_ID)\n INNER JOIN\n sys.partitions (NOLOCK) [part] ON ([ix].OBJECT_ID = [part].OBJECT_ID AND ix.index_id = [part].index_id)\n INNER JOIN\n sys.allocation_units (NOLOCK) [alloc] ON ([part].PARTITION_ID = [alloc].container_id)\n LEFT OUTER JOIN\n sys.schemas [schema] (NOLOCK) ON ([table].SCHEMA_ID = [schema].SCHEMA_ID)\n WHERE\n [table].NAME IS NOT NULL\n {user_tables_only_condition}\n {table_condition}\n {schema_condition}\n GROUP BY\n [table].NAME, \n [table].CREATE_DATE, \n [table].MODIFY_DATE, \n [schema].NAME, part.ROWS\n \"\"\".format(schema_condition=schema_condition, table_condition=table_condition, user_tables_only_condition=user_tables_only_condition)\n \n DBUsageReport = read_data_sql(query=query, server=server, database=database, auth=auth, params=None)\n \n DBUsageReport['TotalSpaceKBx'] = DBUsageReport['TotalSpaceKBx'].fillna(0)\n DBUsageReport['UsedSpaceKBx'] = DBUsageReport['UsedSpaceKBx'].fillna(0)\n DBUsageReport['AvaiableSpaceKBx'] = DBUsageReport['TotalSpaceKBx'] - DBUsageReport['UsedSpaceKBx']\n \n DBUsageReport['TotalSpace{}'.format(unit)] = DBUsageReport['TotalSpaceKBx'] * multiplier\n DBUsageReport['UsedSpace{}'.format(unit)] = DBUsageReport['UsedSpaceKBx'] * multiplier\n DBUsageReport['AvaiableSpace{}'.format(unit)] = DBUsageReport['AvaiableSpaceKBx'] * multiplier\n \n DBUsageReport = DBUsageReport.drop(columns=['TotalSpaceKBx', 'UsedSpaceKBx', 'AvaiableSpaceKBx'])\n else:\n DBUsageReport = pd.DataFrame()\n print('This function currently supported for MSSQL server only')\n \n return DBUsageReport\n\n###############################################################################\n##[ VALIDATE FIELDS]########################################################## \n###############################################################################\n \ndef add_identity_column(DataFrame, id_label='ID', start=1, increment=1):\n if id_label in DataFrame.columns:\n print('Column {} exists in the DataFrame'.format(id_label))\n return DataFrame\n else:\n DataFrame.reset_index(drop=True, inplace=True)\n DataFrame.insert(0, id_label, start+DataFrame.index)\n return DataFrame\n \ndef remove_special_characters(str_val, replace=''):\n return re.sub('\\W+',replace, str_val)\n\ndef remove_special_characters_list(str_list, replace=''):\n return [remove_special_characters(str_val, replace=replace) for str_val in str_list]\n \ndef clean_column_names(DataFrame, replace=''): # Remove special charcters from column names\n \"\"\"\n Parameters\n ----------\n DataFrame : pandas.DataFrame\n DataFrame\n replace : str, dafault ''\n Character to replace special charaters with. \n \n Returns\n -------\n DataFrame : pandas.DataFrame\n \"\"\"\n try:\n columns = DataFrame.columns\n columns = remove_special_characters_list(columns, replace=replace)\n if check_list_values_unique(columns):\n DataFrame.columns = columns\n else:\n print('Duplicates values excists the column names after removing special characters!. Column names were rolled-back to initial values.') \n except:\n print('Error in removing special characters from column names:\\n{}\\n'.format(traceback.format_exc()))\n return DataFrame\n\ndef check_list_values_unique(values_list):\n if len(values_list) == len(set(values_list)):\n return True\n else:\n return False\n \ndef handle_duplicate_columns(DataFrame, action='rename'): #'drop'\n \"\"\"\n Parameters\n ----------\n DataFrame : pandas.DataFrame\n DataFrame\n action : {'rename', 'drop'}, dafault 'rename'\n Action to be taken on duplicate columns \n \n Returns\n -------\n DataFrame : pandas.DataFrame\n \"\"\"\n is_duplicate = DataFrame.columns.duplicated()\n columns = list(DataFrame.columns)\n if action=='rename':\n for i in range(len(columns)):\n if is_duplicate[i]:\n columns[i]=columns[i]+'_' \n DataFrame.columns = columns\n elif action=='drop':\n DataFrame = DataFrame.loc[:,~is_duplicate]\n else:\n print('No valid action (rename or drop) provided!')\n return DataFrame\n\ndef add_missing_feature_columns(DataFrame, expected_features, fill_value=0):\n # Blanck columns for non-existance variables\n feature_variables_to_add = list(set(expected_features) - set(DataFrame.columns)) # Find columns not found in the dataset\n for f in feature_variables_to_add:\n DataFrame[f]=fill_value\n print('Column [{}] does not exist in the dataset. Created new column and set to {}...'.format(f,fill_value))\n return DataFrame\n\ndef exclude_records(DataFrame, exclude_condition=None, action = 'flag', exclude_label='_EXCLUDE_'):\n N0 = len(DataFrame.index)\n if exclude_condition==None:\n print('No exclude condition...')\n return DataFrame\n \n try:\n if action=='drop': #Drop Excludes \n DataFrame = DataFrame.query('not ({})'.format(exclude_condition))\n elif action=='flag': #Create new flagged column\n DataFrame[exclude_label] = DataFrame.eval(exclude_condition).astype('int8')\n print('Records {} -> {}=1'.format(exclude_condition, exclude_label))\n except:\n print('Error in excluding records {}:\\n{}\\n'.format(exclude_condition, traceback.format_exc()))\n N1 = len(DataFrame.index) \n print('{} records were excluded'.format(N1-N0))\n return DataFrame\n\n###############################################################################\n##[ CREATING FEATURES - TARGET ]############################################### \n############################################################################### \n \ndef set_binary_target(DataFrame, to_variable='_TARGET_', condition_str=None, default=0, null=0, return_variable=False, return_script=False):\n if condition_str==None: \n return DataFrame\n \n DataFrame, to_variable = create_binary_variable(DataFrame, to_variable, condition_str, default=default, null=null, return_variable=True)\n\n parameters = {\n 'condition_str':condition_str,\n 'default':default,\n 'null':null\n } \n script_dict = generate_create_variable_task_script(type='target', out_type='bin', include=False, operation='condition', source=None, destination=to_variable, parameters=parameters)\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \n###############################################################################\n##[ CREATING FEATURES - TRANSFORMATIONS]####################################### \n############################################################################### \n\ndef create_normalized_variable(DataFrame, variable, method='maxscale', parameters=None, to_variable=None, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = variable\n \n if method=='minscale': #scale=max\n try:\n min_ = parameters[\"min\"]\n except:\n min_ = DataFrame[variable].min()\n parameters[\"min\"] = min_\n DataFrame[to_variable] = DataFrame[variable]/min_\n if method=='maxscale': #scale=max\n try:\n max_ = parameters[\"max\"]\n except:\n max_ = DataFrame[variable].max()\n parameters[\"max\"] = max_\n DataFrame[to_variable] = DataFrame[variable]/max_\n if method=='range': # range = abs(max-min)\n try:\n min_ = parameters[\"min\"]\n max_ = parameters[\"max\"]\n except:\n min_ = DataFrame[variable].min()\n max_ = DataFrame[variable].max() \n parameters[\"min\"] = min_\n parameters[\"max\"] = max_\n min_max = abs(min_-max_)\n DataFrame[to_variable] = DataFrame[variable]/min_max\n if method=='minmaxfs': # range = (value-min)/(max-min)\n try:\n min_ = parameters[\"min\"]\n max_ = parameters[\"max\"]\n except:\n min_ = DataFrame[variable].min()\n max_ = DataFrame[variable].max() \n parameters[\"min\"] = min_\n parameters[\"max\"] = max_\n min_max = abs(max_-min_)\n DataFrame[to_variable] = (DataFrame[variable]-min_)/min_max\n if method=='minmaxfs_m': # range = (value-min)/(max-min)\n try:\n min_ = parameters[\"min\"]\n max_ = parameters[\"max\"]\n mean_ = parameters[\"mean\"]\n except: \n min_=DataFrame[variable].min()\n max_=DataFrame[variable].max()\n mean_ = DataFrame[variable].mean()\n parameters[\"min\"] = min_\n parameters[\"max\"] = max_\n parameters[\"mean\"] = mean_\n min_max = abs(max_-min_)\n DataFrame[to_variable] = (DataFrame[variable]-mean_)/min_max\n if method=='mean':\n try:\n mean_ = parameters[\"mean\"]\n except: \n mean_ = DataFrame[variable].mean()\n parameters[\"mean\"] = mean_\n DataFrame[to_variable] = DataFrame[variable]/mean_\n if method=='median':\n try:\n median_ = parameters[\"median\"]\n except: \n median_ = DataFrame[variable].median()\n parameters[\"median\"] = median_\n DataFrame[to_variable] = DataFrame[variable]/median_\n if method=='zscore': \n try:\n std_ = parameters[\"std\"]\n mean_ = parameters[\"mean\"]\n except: \n std_ = DataFrame[variable].std()\n mean_ = DataFrame[variable].mean()\n parameters[\"mean\"] = mean_\n parameters[\"std\"] = std_\n DataFrame[to_variable] = (DataFrame[variable] - mean_)/std_ \n \n script_dict = generate_create_variable_task_script(type='transform', out_type='cnt', \n include=False, operation='normalize', \n source=variable, destination=to_variable, \n parameters=parameters)\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\ndef create_datepart_variable(DataFrame, variable, to_variable=None, part='date', return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = '{}{}'.format(variable,part)\n \n try:\n DataFrame[variable] = pd.to_datetime(DataFrame[variable])\n if part=='date':\n DataFrame[to_variable] = DataFrame[variable].dt.date\n elif part=='year':\n DataFrame[to_variable] = DataFrame[variable].dt.year\n elif part=='quarter':\n DataFrame[to_variable] = DataFrame[variable].dt.quarter\n elif part=='month':\n DataFrame[to_variable] = DataFrame[variable].dt.month\n elif part=='week':\n DataFrame[to_variable] = DataFrame[variable].dt.week\n elif part=='day':\n DataFrame[to_variable] = DataFrame[variable].dt.day \n elif part=='dayofweek':\n DataFrame[to_variable] = DataFrame[variable].dt.dayofweek\n elif part=='dayofyear':\n DataFrame[to_variable] = DataFrame[variable].dt.dayofyear\n elif part=='time':\n DataFrame[to_variable] = DataFrame[variable].dt.time\n elif part=='hour':\n DataFrame[to_variable] = DataFrame[variable].dt.hour\n elif part=='minute':\n DataFrame[to_variable] = DataFrame[variable].dt.minute\n elif part=='second':\n DataFrame[to_variable] = DataFrame[variable].dt.second\n elif part=='microsecond':\n DataFrame[to_variable] = DataFrame[variable].dt.microsecond\n elif part=='nanosecond':\n DataFrame[to_variable] = DataFrame[variable].dt.nanosecond\n else:\n DataFrame[to_variable] = variable\n except:\n DataFrame[to_variable] = variable\n\n parameters = {'part':part} \n script_dict = generate_create_variable_task_script(type='transform', out_type='dat', \n include=False, operation='datepart', \n source=variable, destination=to_variable, \n parameters=parameters)\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\ndef create_dateadd_variable(DataFrame, variable, to_variable=None, unit='years', value=0, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = '{}{}{}'.format(variable, value, unit)\n \n try:\n DataFrame[variable] = pd.to_datetime(DataFrame[variable])\n if part=='years':\n DataFrame[to_variable] = DataFrame[variable] + pd.DateOffset(year=value)\n elif part=='months':\n DataFrame[to_variable] = DataFrame[variable] + pd.DateOffset(months=value)\n elif part=='weeks':\n DataFrame[to_variable] = DataFrame[variable] + pd.DateOffset(weeks=value)\n elif part=='days':\n DataFrame[to_variable] = DataFrame[variable] + pd.DateOffset(days=value)\n elif part=='hours':\n DataFrame[to_variable] = DataFrame[variable] + pd.DateOffset(hours=value)\n elif part=='minutes':\n DataFrame[to_variable] = DataFrame[variable] + pd.DateOffset(minutes=value)\n elif part=='seconds':\n DataFrame[to_variable] = DataFrame[variable] + pd.DateOffset(seconds=value)\n elif part=='microseconds':\n DataFrame[to_variable] = DataFrame[variable] + pd.DateOffset(microseconds=value)\n elif part=='nanoseconds':\n DataFrame[to_variable] = DataFrame[variable] + pd.DateOffset(nanoseconds=value) \n except:\n DataFrame[to_variable] = variable\n\n parameters = {\n 'unit':unit, \n 'value':value\n } \n script_dict = generate_create_variable_task_script(type='transform', out_type='dat', \n include=False, operation='dateadd', \n source=variable, destination=to_variable, \n parameters=parameters)\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\ndef create_log_variable(DataFrame, variable, base='e', to_variable=None, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = 'LOG{}'.format(variable)\n \n if base=='e':\n DataFrame[to_variable] = np.log(DataFrame[variable])\n elif base=='10':\n DataFrame[to_variable] = np.log10(DataFrame[variable])\n elif base=='2':\n DataFrame[to_variable] = np.log2(DataFrame[variable])\n\n parameters = { 'base':base }\n script_dict = generate_create_variable_task_script(type='transform', out_type='cnt', \n include=False, operation='log', \n source=variable, destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \ndef create_exponent_variable(DataFrame, variable, base='e', to_variable=None, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = 'EXP{}'.format(variable)\n \n if base=='e':\n DataFrame[to_variable] = np.e**DataFrame[variable]\n elif base=='10':\n DataFrame[to_variable] = 10**DataFrame[variable]\n elif base=='2':\n DataFrame[to_variable] = 2**DataFrame[variable]\n\n parameters = { 'base':base }\n script_dict = generate_create_variable_task_script(type='transform', out_type='cnt', \n include=False, operation='exponent', \n source=variable, destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n\ndef create_segmented_variable(DataFrame, variable, a=None, b=None, to_variable=None, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = 'SEG{}'.format(variable) \n \n if a == None:\n a = -np.inf\n \n if b == None:\n b = np.inf\n \n DataFrame[to_variable] = DataFrame[variable]\n DataFrame.loc[DataFrame[to_variable]b, to_variable] = b\n\n parameters = { 'a':a, 'b':b }\n script_dict = generate_create_variable_task_script(type='transform', out_type='cnt', \n include=False, operation='segment', \n source=variable, destination=to_variable, \n parameters=parameters) \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n###############################################################################\n##[ CREATING FEATURES - STR TRANSFORM ]######################################## \n############################################################################### \n \ndef create_str_count_variable(DataFrame, variable, pattern='*', case_sensitive=True, to_variable=None, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = '{}CNT{}'.format(variable, remove_special_characters(pattern, replace=''))\n try:\n if pattern=='*':\n DataFrame[to_variable] = DataFrame[variable].str.len()\n else:\n DataFrame[to_variable] = DataFrame[variable].str.count(pattern) \n except:\n print('ERROR in create_str_count_variable:\\n{}'.format(traceback.format_exc()))\n DataFrame[to_variable] = DataFrame[variable]\n\n parameters = { 'pattern':pattern, 'case_sensitive':case_sensitive }\n script_dict = generate_create_variable_task_script(type='transform_str', out_type='cnt', \n include=False, operation='strcount', \n source=variable, destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \ndef create_str_normalized_variable(DataFrame, variable, to_case='lower', chars='keep', numbers='remove', spchar='remove', space='remove', to_variable=None, return_variable=False, return_script=False):\n\n if to_variable==None:\n to_variable = '{}'.format(variable)\n \n try: \n DataFrame[to_variable] = DataFrame[variable]\n \n if to_case=='lower':\n DataFrame[to_variable] = DataFrame[variable].str.lower()\n if to_case=='upper':\n DataFrame[to_variable] = DataFrame[variable].str.upper()\n if numbers=='remove':\n DataFrame[to_variable] = DataFrame[variable].str.replace('\\d','') \n if spchar=='remove':\n DataFrame[to_variable] = DataFrame[variable].str.replace('\\W','') \n if space=='remove':\n DataFrame[to_variable] = DataFrame[variable].str.replace('\\s','') \n if chars=='remove':\n DataFrame[to_variable] = DataFrame[variable].str.replace('\\w','') \n except:\n print('ERROR in create_str_normalized_variable:\\n{}'.format(traceback.format_exc()))\n DataFrame[to_variable] = DataFrame[variable]\n\n parameters = { \n 'to_case':to_case, \n 'chars':chars,\n 'numbers':numbers,\n 'spchar':spchar, \n 'space':space\n }\n script_dict = generate_create_variable_task_script(type='transform_str', out_type='str', \n include=False, operation='normalize', \n source=variable, destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\ndef create_str_extract_variable(DataFrame, variable, pattern='\\w+', case_sensitive=True, to_variable=None, return_variable=False, return_script=False): \n if to_variable==None:\n to_variable = 'variableEXT'.format(variable)\n try:\n if case_sensitive: \n DataFrame[to_variable] = DataFrame[variable].str.extract('({})'.format(pattern))\n else:\n DataFrame[to_variable] = DataFrame[variable].str.extract('({})'.format(pattern), flags=re.IGNORECASE)\n except:\n print('ERROR in create_str_extract_variable:\\n{}'.format(traceback.format_exc()))\n DataFrame[to_variable] = DataFrame[variable]\n\n parameters = { \n 'pattern':pattern, \n 'case_sensitive':case_sensitive\n }\n script_dict = generate_create_variable_task_script(type='transform_str', out_type='str', \n include=False, operation='extract', \n source=variable, destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n##[ CREATING FEATURES - MULTI VARIABLE ]####################################### \n############################################################################### \ndef create_operation_mult_variable(DataFrame, expression_str='0', to_variable=None, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = '{}'.format(expression_str)\n \n try:\n DataFrame[to_variable] = DataFrame.eval(expression_str)\n except:\n print('ERROR in create_operation_mult_variable:\\n{}'.format(traceback.format_exc()))\n\n parameters = { 'expression_str':expression_str}\n script_dict = generate_create_variable_task_script(type='operation_mult', out_type='cnt', \n include=False, operation='expression', \n source=None, destination=to_variable, \n parameters=parameters) \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n##[ CREATING FEATURES - SEQUENCE ORDER ]####################################### \n###############################################################################\ndef create_sequence_order_variable(DataFrame, variable1a, variable2a, variable1b, variable2b, output='binary', to_variable=None, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = '{}{}SEQ{}{}'.format(variable1a, variable2a, variable1b, variable2b)\n \n try:\n DataFrame[to_variable] = DataFrame[variable] ########### NEED UPDATE !!!!\n except:\n print('ERROR in create_sequence_order_variable:\\n{}'.format(traceback.format_exc()))\n DataFrame[to_variable] = DataFrame[variable]\n\n parameters = { 'output':output }\n script_dict = generate_create_variable_task_script(type='sequence', out_type='cnt', \n include=False, operation='seqorder', \n source=[variable1a, variable2a, variable1b, variable2b], \n destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \n###############################################################################\n##[ CREATING FEATURES - DIFFERENCES ]########################################## \n############################################################################### \ndef create_numeric_difference_variable(DataFrame, variable1, variable2, multiplier=1, onerror=None, to_variable=None, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = '{}DIFF{}'.format(variable1, variable2)\n \n try:\n DataFrame[variable1] = pd.to_numeric(DataFrame[variable1], errors='coerce')\n DataFrame[variable2] = pd.to_numeric(DataFrame[variable2], errors='coerce') \n DataFrame[to_variable] = multiplier*(DataFrame[variable1] - DataFrame[variable2])\n except:\n DataFrame[to_variable] = None\n print('Data Type Error in {}, {} : {} '.format(variable1, variable2, traceback.format_exc())) \n\n parameters = { \n 'multiplier':multiplier,\n 'onerror': onerror\n }\n script_dict = generate_create_variable_task_script(type='comparison', out_type='cnt', \n include=False, operation='numdiff', \n source=[variable1, variable2], \n destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\ndef create_numeric_ratio_variable(DataFrame, variable1, variable2, multiplier=1, onerror=None, to_variable=None, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = '{}DIV{}'.format(variable1, variable2)\n \n try:\n DataFrame[variable1] = pd.to_numeric(DataFrame[variable1], errors='coerce')\n DataFrame[variable2] = pd.to_numeric(DataFrame[variable2], errors='coerce') \n DataFrame[to_variable] = multiplier*(DataFrame[variable1]/DataFrame[variable2])\n except:\n DataFrame[to_variable] = None\n print('Data Type Error in {}, {} : {} '.format(variable1, variable2, traceback.format_exc())) \n\n parameters = { \n 'multiplier':multiplier,\n 'onerror': onerror\n }\n script_dict = generate_create_variable_task_script(type='comparison', out_type='cnt', \n include=False, operation='ratio', \n source=[variable1, variable2], \n destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \ndef create_date_difference_variable(DataFrame, variable1, variable2, to_variable=None, unit='day', onerror=None, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = '{}DIFF{}'.format(variable1,variable2)\n \n try:\n DataFrame[variable1] = pd.to_datetime(DataFrame[variable1])\n DataFrame[variable2] = pd.to_datetime(DataFrame[variable2]) \n DataFrame[to_variable] = DataFrame[variable2] - DataFrame[variable1]\n DataFrame[to_variable]=DataFrame[to_variable]/np.timedelta64(1,unit)\n except:\n DataFrame[to_variable] = None\n print('Date Type Error in {}, {} : {} '.format(variable1, variable2, traceback.format_exc())) \n\n parameters = { \n 'unit':unit,\n 'onerror': onerror\n }\n script_dict = generate_create_variable_task_script(type='comparison', out_type='cnt', \n include=False, operation='datediff', \n source=[variable1, variable2], \n destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\ndef create_row_min_variable(DataFrame, variable1, variable2, to_variable=None, return_variable=False, return_script=False):\n \n if to_variable==None:\n to_variable = '{}MIN{}'.format(variable1,variable2)\n \n try:\n DataFrame[to_variable] = DataFrame[[variable1,variable2]].min(axis=1)\n except:\n DataFrame[to_variable] = None\n print('Row min({}, {}) Error: {}'.format(variable1, variable2, traceback.format_exc())) \n\n parameters = { }\n script_dict = generate_create_variable_task_script(type='comparison', out_type='cnt', \n include=False, operation='rowmin', \n source=[variable1, variable2], \n destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \n \ndef create_row_max_variable(DataFrame, variable1, variable2, to_variable=None, return_variable=False, return_script=False):\n \n if to_variable==None:\n to_variable = '{}MAX{}'.format(variable1,variable2)\n \n try:\n DataFrame[to_variable] = DataFrame[[variable1,variable2]].max(axis=1)\n except:\n DataFrame[to_variable] = None\n print('Row max({}, {}) Error : {}'.format(variable1, variable2, traceback.format_exc())) \n\n parameters = { }\n script_dict = generate_create_variable_task_script(type='comparison', out_type='cnt', \n include=False, operation='rowmax', \n source=[variable1, variable2], \n destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \n###############################################################################\n##[ CREATING FEATURES - STR COMPARISON ]####################################### \n############################################################################### \ndef create_str_comparison_variable(DataFrame, variable1, variable2, to_variable=None, operation='levenshtein', parameters={}, return_variable=False, return_script=False): \n if to_variable==None:\n to_variable = '{}SIM{}'.format(variable1,variable2)\n \n try:\n case_sensitive = parameters['case_sensitive']\n except:\n case_sensitive = True\n \n if operation=='levenshtein':\n try:\n normalize = parameters['normalize']\n except:\n normalize = False\n DataFrame[to_variable] = np.vectorize(damerau_levenshtein_distance)(DataFrame[variable1], DataFrame[variable2], case_sensitive, normalize)\n\n elif operation=='jaccard':\n try:\n method=parameters['method']\n except:\n method='substring'\n try:\n min_length=parameters['min_length']\n except:\n min_length=1\n try:\n max_length=parameters['max_length']\n except: \n max_length=np.inf\n \n DataFrame[to_variable] = np.vectorize(jaccard_index)(DataFrame[variable1], DataFrame[variable2], method, case_sensitive, min_length, max_length)\n\n script_dict = generate_create_variable_task_script(type='comparison_str', out_type='cnt', \n include=False, operation=operation, \n source=[variable1, variable2], \n destination=to_variable, \n parameters=parameters)\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n##[ CREATING FEATURES - BINARY VARIABLES]###################################### \n############################################################################### \n \ndef create_binary_variable(DataFrame, to_variable, condition_str, default=0, null=0, return_variable=False, return_script=False):\n \n if to_variable==None:\n to_variable = '{}'.format(condition_str)\n\n try: \n DataFrame[to_variable] = DataFrame.eval(condition_str).astype('int8').fillna(null)\n DataFrame.loc[DataFrame[to_variable].isna(), to_variable] = default\n except:\n print('Error in creating the binary variable {}:\\n{}\\n'.format(condition_str, traceback.format_exc()))\n print('Check variable rule set !')\n\n parameters = { \n 'condition_str':condition_str,\n 'default': default,\n 'null': null\n }\n script_dict = generate_create_variable_task_script(type='condition', out_type='bin', \n include=False, operation='condition', \n source=None, \n destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \n###############################################################################\n##[ CREATING FEATURES - CATEGORY LABELS]####################################### \n############################################################################### \n \ndef num_label_to_value(num_label):\n units = {'p':0.000000000001,\n 'n':0.000000001,\n 'u':0.000001,\n 'm':0.001,\n 'c':0.01,\n 'd':0.1,\n '':1,\n 'D':10,\n 'H':100,\n 'K':1000,\n 'M':1000000,\n 'G':1000000000,\n 'T':1000000000000,\n 'P':1000000000000000,\n 'E':1000000000000000000,\n 'INF':np.inf \n }\n try:\n sign, inf, num, unit = re.findall('^([-]?)((\\d+)([pnumcdDHKMGTPE]?)|INF)$', num_label.rstrip().lstrip())[0]\n if inf=='INF':\n value = int('{}1'.format(sign))*np.inf\n else:\n value = int('{}1'.format(sign))*float(num)*units[unit]\n except:\n print('vnum_label_value failed !\\n{}'.format(traceback.format_exc()))\n value = None\n return value\n\ndef edge_labels_to_values(edge_labels, left_inclusive=False, right_inclusive=False):\n \"\"\"\n Parameters\n ----------\n edge_labels : str []\n Edge labels with number unit as postfix\n 'p':0.000000000001,\n 'n':0.000000001,\n 'u':0.000001,\n 'm':0.001,\n 'c':0.01,\n 'd':0.1,\n '':1,\n 'D':10,\n 'H':100,\n 'K':1000,\n 'M':1000000,\n 'G':1000000000,\n 'T':1000000000000,\n 'P':1000000000000000,\n 'INF':np.inf \n left_inclusive : bool, default False\n Include left edge\n right_inclusive : bool, default False\n Include right edge\n \n Returns\n -------\n edge_values : numeric []\n bin_labels : str []\n \"\"\" \n edge_values = []\n bin_labels = []\n n_bins = len(edge_labels)-1\n i=0\n for i in range(n_bins): \n l_bracket = '(' if (i==0 and edge_labels[i]=='-INF') or (not left_inclusive) else '['\n r_bracket = ')' if (i==n_bins-1 and edge_labels[i+1]=='INF') or (not right_inclusive) else ']'\n edge_values.append(num_label_to_value(edge_labels[i]))\n bin_labels.append('{}_{}{},{}{}'.format(i+1, l_bracket, edge_labels[i], edge_labels[i+1], r_bracket))\n edge_values.append(num_label_to_value(edge_labels[n_bins]))\n return edge_values,bin_labels\n\n###############################################################################\n##[ CREATING FEATURES - CATEGORY]############################################## \n############################################################################### \n \ndef create_categorical_variable(DataFrame, variable, to_variable, labels_str, right_inclusive=True, default='OTHER', null='NA', return_variable=False, return_script=False):\n \n if to_variable==None:\n to_variable = '{}GRP'.format(variable)\n \n try:\n default_ = '0_{}'.format(default)\n null_ = '0_{}'.format(null)\n except:\n default_ = '0_Other'\n null_ = '0_NA'\n\n edge_values, bin_labels = edge_labels_to_values(labels_str, left_inclusive=not right_inclusive, right_inclusive=right_inclusive)\n \n try: \n DataFrame[to_variable] = pd.cut(DataFrame[variable], bins=edge_values, labels=bin_labels, right=right_inclusive, include_lowest=True).astype('object')\n except:\n DataFrame[to_variable] = null_\n\n DataFrame.loc[DataFrame[variable].isna(), to_variable] = null_\n DataFrame.loc[DataFrame[to_variable].isna(), to_variable] = default_\n\n parameters = { \n 'labels_str':labels_str,\n 'right_inclusive': right_inclusive,\n 'default': default,\n 'null': null\n }\n script_dict = generate_create_variable_task_script(type='category', out_type='cat', \n include=False, operation='bucket', \n source=variable, \n destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\ndef merge_categories(DataFrame, variable, to_variable, values, group_value, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = variable\n \n try: \n DataFrame[to_variable] = DataFrame[variable].replace(to_replace=values, value=group_value)\n except:\n print('ERROR in creating the categorical variable merge {}:\\n{}\\n'.format(variable, traceback.format_exc()))\n print('Check variable rule set !')\n \n parameters = { \n 'group_value':group_value,\n 'values': values\n }\n script_dict = generate_create_variable_task_script(type='category_merge', out_type='cat', \n include=False, operation='catmerge', \n source=variable, \n destination=to_variable, \n parameters=parameters) \n\n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \n###############################################################################\n##[ CREATING FEATURES - ENTITY (DICTIONARY) ]################################## \n###############################################################################\ndef create_entity_variable(DataFrame, variable, to_variable, dictionary, match_type=None, default='OTHER', null='NA', return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = '{}GRP'.format(variable)\n \n if to_variable != variable:\n DataFrame[to_variable] = None\n \n for entity in reversed(dictionary): \n try:\n case=entity['case']\n except:\n case=True\n \n if (match_type=='values') or ('values' in entity.keys()):\n if case==True:\n DataFrame.loc[DataFrame[variable].isin(entity['values']), to_variable] = entity['entity']\n else:\n values = [x.lower() for x in entity['values']] \n DataFrame.loc[DataFrame[variable].str.lower().isin(values), to_variable] = entity['entity']\n elif (match_type=='pattern') or ('pattern' in entity.keys()):\n DataFrame.loc[DataFrame[variable].fillna('').str.contains(pat=entity['pattern'], case=case), to_variable] = entity['entity']\n else:\n print('Entity {} not created !'.format(entity))\n \n DataFrame.loc[DataFrame[variable].isna(), to_variable] = null\n DataFrame.loc[DataFrame[to_variable].isna(), to_variable] = default\n\n parameters = { \n 'match_type':match_type,\n 'dictionary': dictionary,\n 'default': default,\n 'null': null\n }\n script_dict = generate_create_variable_task_script(type='entity', out_type='cat', \n include=False, operation='dictionary', \n source=variable, \n destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\ndef create_value_pair_variable(DataFrame, variable1, variable2, to_variable, dictionary, match_type=None, default='OTHER', null='NA', return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = '{}GRP{}'.format(variable1, variable2)\n \n if to_variable != variable1 and to_variable != variable2 :\n DataFrame[to_variable] = None\n \n for entity in reversed(dictionary): \n try:\n case=entity['case']\n except:\n case=True\n \n try:\n opperator = entity['opperator']\n except:\n opperator='AND'\n \n if (match_type=='values') or ('values' in entity.keys()):\n if case==True:\n if opperator=='AND':\n DataFrame.loc[(DataFrame[variable1]==entity['values'][0]) & (DataFrame[variable2]==entity['values'][1]), to_variable] = entity['entity']\n elif opperator=='OR':\n DataFrame.loc[(DataFrame[variable1]==entity['values'][0]) | (DataFrame[variable2]==entity['values'][1]), to_variable] = entity['entity']\n elif opperator=='NOT':\n DataFrame.loc[(DataFrame[variable1]==entity['values'][0]) & (DataFrame[variable2]!=entity['values'][1]), to_variable] = entity['entity']\n elif opperator=='^NOT':\n DataFrame.loc[(DataFrame[variable1]!=entity['values'][0]) & (DataFrame[variable2]==entity['values'][1]), to_variable] = entity['entity']\n else:\n values = [x.lower() for x in entity['values']] \n if opperator=='AND':\n DataFrame.loc[(DataFrame[variable1].str.lower()==values[0]) & (DataFrame[variable2].str.lower()==values[1]), to_variable] = entity['entity']\n elif opperator=='OR':\n DataFrame.loc[(DataFrame[variable1].str.lower()==values[0]) | (DataFrame[variable2].str.lower()==values[1]), to_variable] = entity['entity']\n elif opperator=='NOT':\n DataFrame.loc[(DataFrame[variable1].str.lower()==values[0]) & (DataFrame[variable2].str.lower()!=values[1]), to_variable] = entity['entity']\n elif opperator=='^NOT':\n DataFrame.loc[(DataFrame[variable1].str.lower()!=values[0]) & (DataFrame[variable2].str.lower()==values[1]), to_variable] = entity['entity']\n \n elif (match_type=='pattern') or ('pattern' in entity.keys()):\n if opperator=='AND':\n DataFrame.loc[(DataFrame[variable1].fillna('').str.contains(pat=entity['values'][0], case=case)) & (DataFrame[variable2].fillna('').str.contains(pat=entity['values'][1], case=case)), to_variable] = entity['entity']\n elif opperator=='OR':\n DataFrame.loc[(DataFrame[variable1].fillna('').str.contains(pat=entity['values'][0], case=case)) | (DataFrame[variable2].fillna('').str.contains(pat=entity['values'][1], case=case)), to_variable] = entity['entity'] \n else:\n print('Entity {} not created !'.format(entity))\n \n DataFrame.loc[(DataFrame[variable1].isna()) & (DataFrame[variable2].isna()), to_variable] = null\n DataFrame.loc[DataFrame[to_variable].isna(), to_variable] = default\n\n parameters = { \n 'match_type':match_type,\n 'dictionary': dictionary,\n 'default': default,\n 'null': null\n }\n script_dict = generate_create_variable_task_script(type='entity', out_type='cat', \n include=False, operation='valuepairs', \n source=[variable1, variable2],\n destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \n###############################################################################\n##[ CREATING FEATURES - PAIR EQUALITY ]######################################## \n###############################################################################\ndef create_pair_equality_variable(DataFrame, variable1, variable2, to_variable, magnitude=False, case=True, return_variable=False, return_script=False):\n if to_variable==None:\n to_variable = '{}CMP{}'.format(variable1,variable2)\n \n DataFrame.loc[(DataFrame[variable1]==DataFrame[variable2]), to_variable] = 'EQ'\n DataFrame.loc[(DataFrame[variable1]!=DataFrame[variable2]), to_variable] = 'DF'\n DataFrame.loc[(DataFrame[variable1].isna()) | (DataFrame[variable2].isna()), to_variable] = 'ON'\n DataFrame.loc[(DataFrame[variable1].isna()) & (DataFrame[variable2].isna()), to_variable] = 'BN'\n\n parameters = { \n 'magnitude':magnitude,\n 'case': case\n }\n script_dict = generate_create_variable_task_script(type='pair_equality', out_type='cat', \n include=False, operation='pairequality', \n source=[variable1, variable2], \n destination=to_variable, \n parameters=parameters) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n \n###############################################################################\n##[ CREATING FEATURES TASK - TARGET ]########################################## \n###############################################################################\ndef create_target_variable_task(DataFrame, rule_set, return_variable=False, return_script=False):\n to_variable = rule_set['variables']['destination']\n operation = rule_set['operation'] \n parameters = rule_set['parameters']\n \n target_condition_str = parameters['condition_str']\n default = parameters['default']\n null = parameters['null']\n \n DataFrame, to_variable, script_dict = set_binary_target(DataFrame, condition_str=target_condition_str, \n to_variable=to_variable, default=default, null=null, return_variable=True, return_script=True)\n\n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \n###############################################################################\n##[ CREATING FEATURES TASK - TRANSFORM ]####################################### \n###############################################################################\ndef create_transformed_variable_task(DataFrame, rule_set, return_variable=False, return_script=False):\n variable = rule_set['variables']['source']\n to_variable = rule_set['variables']['destination']\n operation = rule_set['operation'] \n parameters = rule_set['parameters']\n \n if operation=='normalize':\n method = rule_set['parameters']['method'] \n DataFrame, to_variable, script_dict = create_normalized_variable(DataFrame, variable, method=method, parameters=parameters, to_variable=to_variable, return_variable=True, return_script=True)\n elif operation=='datepart':\n part = rule_set['parameters']['part'] \n DataFrame, to_variable, script_dict = create_datepart_variable(DataFrame, variable, part=part, to_variable=to_variable, return_variable=True, return_script=True)\n elif operation=='dateadd':\n unit = rule_set['parameters']['unit'] \n value = rule_set['parameters']['value'] \n DataFrame, to_variable, script_dict = create_dateadd_variable(DataFrame, variable, unit=unit, value=value, to_variable=to_variable, return_variable=True, return_script=True)\n elif operation=='log':\n base = rule_set['parameters']['base'] \n DataFrame, to_variable, script_dict = create_log_variable(DataFrame, variable, base=base, to_variable=to_variable, return_variable=True, return_script=True)\n elif operation=='exponent':\n base = rule_set['parameters']['base'] \n DataFrame, to_variable, script_dict = create_exponent_variable(DataFrame, variable, base=base, to_variable=to_variable, return_variable=True, return_script=True)\n elif operation=='exponent':\n a = rule_set['parameters']['a'] \n b = rule_set['parameters']['b'] \n DataFrame, to_variable, script_dict = create_segmented_variable(DataFrame, variable, a=a, b=b, to_variable=to_variable, return_variable=True, return_script=True)\n else:\n pass # other transformations to be implemented\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n\ndef create_str_transformed_variable_task(DataFrame, rule_set, return_variable=False, return_script=False):\n variable = rule_set['variables']['source']\n to_variable = rule_set['variables']['destination']\n operation = rule_set['operation'] \n parameters = rule_set['parameters']\n\n if operation=='strcount':\n pattern = parameters['pattern']\n case_sensitive = parameters['case_sensitive']\n DataFrame, to_variable, script_dict = create_str_count_variable(DataFrame, variable, pattern=pattern, case_sensitive=case_sensitive, to_variable=to_variable, return_variable=True, return_script=True) \n elif operation=='normalize':\n to_case = parameters['to_case']\n chars = parameters['chars']\n numbers = parameters['numbers'] \n spchar = parameters['spchar']\n space = parameters['space'] \n\n DataFrame, to_variable, script_dict = create_str_normalized_variable(DataFrame, variable, \n to_case=to_case, \n chars=chars, \n numbers=numbers, \n spchar=spchar, \n space=space, \n to_variable=None, return_variable=False, return_script=True)\n elif operation=='extract':\n pattern = parameters['pattern']\n case_sensitive = parameters['case_sensitive']\n DataFrame, to_variable, script_dict = create_str_extract_variable(DataFrame, variable, pattern=pattern, \n case_sensitive=case_sensitive, \n to_variable=to_variable, return_variable=True, return_script=True) \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n##[ CREATING FEATURES TASK - MLTI VARIAVLE ]################################### \n###############################################################################\n \ndef create_operation_mult_variable_task(DataFrame, rule_set, return_variable=False, return_script=False):\n variable = rule_set['variables']['source']\n to_variable = rule_set['variables']['destination']\n operation = rule_set['operation'] \n parameters = rule_set['parameters'] \n expression_str = parameters['expression_str']\n \n DataFrame, to_variable, script_dict = create_operation_mult_variable(DataFrame, expression_str=expression_str, \n to_variable=to_variable, return_variable=True, return_script=True)\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n##[ CREATING FEATURES TASK - SEQUENCE ORDER ]################################## \n###############################################################################\ndef create_sequence_order_variable_task(DataFrame, rule_set, return_variable=False, return_script=False):\n variable1a = rule_set['variables']['source1a']\n variable2a = rule_set['variables']['source2a']\n variable1b = rule_set['variables']['source1b']\n variable2b = rule_set['variables']['source2b']\n to_variable = rule_set['variables']['destination']\n \n DataFrame, to_variable, script_dict = create_sequence_order_variable(DataFrame, variable1a, variable2a, variable1b, variable2b, output='binary', \n to_variable=to_variable, return_variable=True, return_script=True)\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \n###############################################################################\n##[ CREATING FEATURES TASK - COMPARISON ]###################################### \n###############################################################################\ndef create_comparison_variable_task(DataFrame, rule_set, return_variable=False, return_script=False):\n variable1 = rule_set['variables']['source1']\n variable2 = rule_set['variables']['source2']\n to_variable = rule_set['variables']['destination']\n operation = rule_set['operation']\n parameters = rule_set['parameters']\n \n try:\n multiplier = parameters['multiplier']\n except:\n multiplier=1 \n \n try:\n unit = parameters['unit']\n except:\n unit = 'D'\n onerror = None # parameters['onerror']\n \n if operation=='numdiff': \n DataFrame, to_variable, script_dict = create_numeric_difference_variable(DataFrame, variable1, variable2, multiplier=multiplier, onerror=onerror, to_variable=to_variable, return_variable=True, return_script=True)\n elif operation=='datediff':\n DataFrame, to_variable, script_dict = create_date_difference_variable(DataFrame, variable1, variable2, unit=unit, onerror=onerror, to_variable=to_variable, return_variable=True, return_script=True)\n elif operation=='rowmin':\n DataFrame, to_variable, script_dict = create_row_min_variable(DataFrame, variable1, variable2, to_variable=to_variable, return_variable=True, return_script=True)\n elif operation=='rowmax':\n DataFrame, to_variable, script_dict = create_row_max_variable(DataFrame, variable1, variable2, to_variable=to_variable, return_variable=True, return_script=True) \n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n \ndef create_str_comparison_variable_task(DataFrame, rule_set, return_variable=False, return_script=False):\n variable1 = rule_set['variables']['source1']\n variable2 = rule_set['variables']['source2']\n to_variable = rule_set['variables']['destination']\n operation = rule_set['operation'] \n parameters = rule_set['parameters']\n \n DataFrame, to_variable, script_dict = create_str_comparison_variable(DataFrame, variable1=variable1, variable2=variable2, to_variable=to_variable, operation=operation, parameters=parameters, \n return_variable=True, return_script=True)\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n##[ CREATING FEATURES TASK - BINARY VARIABLE ]################################# \n###############################################################################\ndef create_binary_variable_task(DataFrame, rule_set, return_variable=False, return_script=False):\n #variable = rule_set['variables']['source']\n to_variable = rule_set['variables']['destination']\n parameters = rule_set['parameters']\n condition_str = parameters['condition_str']\n default = parameters['default']\n null = parameters['null']\n \n DataFrame, to_variable, script_dict = create_binary_variable(DataFrame, to_variable, condition_str, default, null, \n return_variable=True, return_script=True)\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n##[ CREATING FEATURES TASK - CATEGORY VARIABLE ]############################### \n############################################################################### \ndef create_categorical_variable_task(DataFrame, rule_set, return_variable=False, return_script=False): \n variable = rule_set['variables']['source']\n to_variable = rule_set['variables']['destination']\n operation = rule_set['operation'] \n parameters = rule_set['parameters']\n labels_str = parameters['labels_str']\n right_inclusive = parameters['right_inclusive'] \n default = parameters['default']\n null = parameters['null']\n \n DataFrame, to_variable, script_dict = create_categorical_variable(DataFrame, variable, to_variable, labels_str, right_inclusive, default, null, \n return_variable=True, return_script=True)\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n##[ CREATING FEATURES TASK - ENTITY VARIABLE ]################################# \n############################################################################### \ndef create_entity_variable_task(DataFrame, rule_set, return_variable=False, return_script=False):\n \n to_variable = rule_set['variables']['destination']\n parameters = rule_set['parameters']\n match_type = parameters['match_type']\n dictionary = parameters['dictionary'] \n default = parameters['default']\n null = parameters['null']\n operation = rule_set['operation']\n\n if operation == 'dictionary':\n variable = rule_set['variables']['source'] \n DataFrame, to_variable, script_dict = create_entity_variable(DataFrame, variable=variable, to_variable=to_variable, \n dictionary=dictionary, match_type=match_type, default=default, null=null, \n return_variable=True, return_script=True)\n elif operation == 'valuepairs':\n variable1 = rule_set['variables']['source1'] \n variable2 = rule_set['variables']['source2'] \n DataFrame, to_variable, script_dict = create_value_pair_variable(DataFrame, variable1, variable2, to_variable, \n dictionary, match_type=None, default='OTHER', null='NA', \n return_variable=True, return_script=True)\n\n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n##[ CREATING FEATURES TASK - PAIR EQUALITY ]################################### \n############################################################################### \ndef create_pair_equality_variable_task(DataFrame, rule_set, return_variable=False, return_script=False): \n variable1 = rule_set['variables']['source1']\n variable2 = rule_set['variables']['source2']\n to_variable = rule_set['variables']['destination']\n parameters = rule_set['parameters']\n try:\n magnitude = parameters['magnitude']\n except:\n magnitude = 1\n case = parameters['case']\n \n DataFrame, to_variable, script_dict = create_pair_equality_variable(DataFrame, variable1=variable1, variable2=variable2, to_variable=to_variable, magnitude=magnitude, case=case, \n return_variable=True, return_script=True)\n \n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n##[ CREATING FEATURES TASK - MERGE CATEGORY ]################################## \n###############################################################################\ndef merge_categories_task(DataFrame, rule_set, return_variable=False, return_script=False):\n variable = rule_set['variables']['source']\n to_variable = rule_set['variables']['destination']\n values = rule_set['parameters']['values']\n group_value = rule_set['parameters']['group_value']\n \n DataFrame, to_variable, script_dict = merge_categories(DataFrame, variable=variable, to_variable=to_variable, values=values, group_value=group_value, \n return_variable=True, return_script=True) \n\n if return_script and return_variable:\n return DataFrame, to_variable, script_dict\n elif return_script:\n return DataFrame, script_dict\n elif return_variable:\n return DataFrame, to_variable\n else:\n return DataFrame \n\n###############################################################################\n \n###############################################################################\n##[ ENCODER ]################################################################## \n############################################################################### \ndef to_one_hot_encode(DataFrame, category_variables=[], binary_variables=[], target_variable='target', target_type='binary'):\n # TO DO: If target type is 'multi' apply one hot encoding to target\n feature_variables = []\n try:\n VariablesDummies = pd.get_dummies(DataFrame[category_variables]).astype('int8')\n dummy_variables = list(VariablesDummies.columns.values)\n DataFrame[dummy_variables] = VariablesDummies\n except:\n print('Category columns {} does not specified nor exists'.format(category_variables))\n \n try:\n DataFrame[binary_variables] = DataFrame[binary_variables].astype('int8')\n except:\n print('Binary columns {} does not specified nor exists'.format(binary_variables))\n \n try: \n feature_variables = binary_variables+dummy_variables\n except:\n print('Error in creating feature variables.')\n \n return DataFrame, feature_variables, target_variable\n\n###############################################################################\n##[ ML MODEL DRIVER ]########################################################## \n############################################################################### \ndef load_data_task(load_data_dict, return_name=False):\n \"\"\"\n Parameters\n ----------\n load_data_dict: dict\n e.g.: {\n \t \"type\": \"csv\",\n \t \"location\": \"local\",\n \t \"workclass\": \"Private\",\n \t \"source\": {\"path\":\"C:/Projects/Data/incomedata.csv\", \"separator\":\",\", \"encoding\":null},\n \t \"auth\": None,\n \t \"query\": None,\n \t \"limit\": None\n }\n \n Returns\n -------\n DataFrame: pandas.DataFrame\n data_name: str\n \"\"\" \n\n import json\n if type(load_data_dict)==dict:\n pass\n else:\n try:\n load_data_dict = json.loads(load_data_dict) \n except:\n print('ERROR in loading data:{}\\n {}'.format(load_data_dict, traceback.format_exc())) \n \n data_name = load_data_dict['data_name']\n \n if load_data_dict['type']=='csv':\n DataFrame = read_data_csv(\n file=load_data_dict['source']['path'], \n separator=load_data_dict['source']['separator'], \n encoding=load_data_dict['source']['encoding']\n )\n elif load_data_dict['type']=='pickle':\n DataFrame = read_data_pickle(\n file=load_data_dict['source']['path'], \n compression =load_data_dict['source']['compression']\n ) \n elif load_data_dict['type']=='sql':\n DataFrame = read_data_sql(\n query=load_data_dict['query'], \n server=load_data_dict['source']['server'], \n database=load_data_dict['source']['database'],\n auth=load_data_dict['auth']\n ) \n else:\n print(\"No valid data source provided!\")\n DataFrame = pd.DataFrame()\t\n\n # Add ID column\n DataFrame = add_identity_column(DataFrame, id_label='ID', start=1, increment=1)\n\n # Clean column names\n DataFrame = clean_column_names(DataFrame, replace='')\n \n if return_name: \n return DataFrame, data_name\n else:\n return DataFrame\n\n###############################################################################\ndef create_variable_task(DataFrame, create_variable_task_dict=None, return_extra=False, return_script=False):\n \"\"\"\n Interface function for single variable operation\n\n Parameters\n ----------\n DataFrame: pandas.DataFrame\n create_variable_task_dict : dict or JSON\n return_extra : bool, default False\n Returns variable_class and include if True\n \n Returns\n -------\n DataFrame: pandas.DataFrame\n data_name: str\n variable_class : str, optional\n include: bool, optional\n \"\"\" \n import json\n if type(create_variable_task_dict)==dict:\n pass\n else:\n try:\n create_variable_task_dict = json.loads(create_variable_task_dict) \n except:\n print('ERROR in creating variable:{}\\n {}'.format(create_variable_task_dict, traceback.format_exc())) \n \n rule_set = {\n 'operation':create_variable_task_dict['operation'],\n 'variables':create_variable_task_dict['variables'],\n 'parameters':create_variable_task_dict['parameters']\n }\n out_type = create_variable_task_dict['out_type']\n include = create_variable_task_dict['include'] \n\n try:\n if create_variable_task_dict['type']=='target':\n DataFrame, output_variable, script_dict = create_target_variable_task(DataFrame, rule_set, return_variable=True, return_script=True) \n if create_variable_task_dict['type']=='transform':\n DataFrame, output_variable, script_dict = create_transformed_variable_task(DataFrame, rule_set, return_variable=True, return_script=True) \n elif create_variable_task_dict['type']=='str_transform':\n DataFrame, output_variable, script_dict = create_str_transformed_variable_task(DataFrame, rule_set, return_variable=True, return_script=True) \n elif create_variable_task_dict['type']=='operation_mult':\n DataFrame, output_variable, script_dict = create_operation_mult_variable_task(DataFrame, rule_set, return_variable=True, return_script=True) \n elif create_variable_task_dict['type']=='seq_order':\n DataFrame, output_variable, script_dict = create_sequence_order_variable_task(DataFrame, rule_set, return_variable=True, return_script=True)\n elif create_variable_task_dict['type']=='comparison':\n DataFrame, output_variable, script_dict = create_comparison_variable_task(DataFrame, rule_set, return_variable=True, return_script=True) \n elif create_variable_task_dict['type']=='str_comparison':\n DataFrame, output_variable, script_dict = create_str_comparison_variable_task(DataFrame, rule_set, return_variable=True, return_script=True) \n elif create_variable_task_dict['type']=='condition':\n DataFrame, output_variable, script_dict = create_binary_variable_task(DataFrame, rule_set, return_variable=True, return_script=True) \n elif create_variable_task_dict['type']=='category':\n DataFrame, output_variable, script_dict = create_categorical_variable_task(DataFrame, rule_set, return_variable=True, return_script=True) \n elif create_variable_task_dict['type']=='entity':\n DataFrame, output_variable, script_dict = create_entity_variable_task(DataFrame, rule_set, return_variable=True, return_script=True) \n elif create_variable_task_dict['type']=='pair_equality':\n DataFrame, output_variable, script_dict = create_pair_equality_variable_task(DataFrame, rule_set, return_variable=True, return_script=True) \n elif create_variable_task_dict['type']=='category_merge':\n DataFrame, output_variable, script_dict = merge_categories_task(DataFrame, rule_set, return_variable=True, return_script=True) \n else:\n output_variable= None \n out_type = None\n include = False\n script_dict= {\n \"type\": \"\",\n \"out_type\":\"\",\n \"include\": False,\n \"operation\": \"\",\n \"variables\": {\n \"source\": \"\",\n \"destination\": None\n },\n \"parameters\": { \n }\n }\n except:\n output_variable= None \n out_type = None\n include = False\n script_dict= {\n \"type\": \"\",\n \"out_type\":\"\",\n \"include\": False,\n \"operation\": \"\",\n \"variables\": {\n \"source\": \"\",\n \"destination\": None\n },\n \"parameters\": { \n }\n } \n \n if return_script and return_extra:\n return DataFrame, output_variable, out_type, include, script_dict\n if return_script:\n return DataFrame, script_dict\n if return_extra: \n return DataFrame, output_variable, out_type, include \n else:\n return DataFrame, output_variable\n\ndef setup_variables_task(DataFrame, variables_setup_dict, return_script=False):\n \"\"\"\n Parameters\n ----------\n DataFrame: pandas.DataFrame\n variables_setup_dict: json or dict\n \n \n Returns\n -------\n DataFrame: pandas.DataFrame\n category_variables: list(str)\n binary_variables: list(str)\n target_variable: list(str)\n \"\"\"\n \n import re\n import json\n if type(variables_setup_dict)==dict:\n pass\n else:\n try:\n variables_setup_dict = json.loads(variables_setup_dict) \n except:\n print('ERROR in creating variables:{}\\n {}'.format(variables_setup_dict, traceback.format_exc())) \n \n # Setting = {'model', 'score'} \n setting = variables_setup_dict['setting']\n \n # verify if variables exists\n category_variables = variables_setup_dict['variables']['category_variables']\n binary_variables = variables_setup_dict['variables']['binary_variables'] \n target_variable = variables_setup_dict['variables']['target_variable'] \n \n #Create variables sets\n category_variables = set(category_variables) & set(DataFrame.columns)\n binary_variables = set(binary_variables) & set(DataFrame.columns)\n \n # Create placeholder for variable creation scripts\n script_dict = []\n \n # Check if target variable exists (fill the column with None in scoring)\n if not target_variable in DataFrame.columns:\n DataFrame[target_variable]=None \n \n # Run variable creation task list\n for preprocess_task in variables_setup_dict['preprocess_tasks']:\n task_type = preprocess_task['type'] #re.sub('[\\W\\d]', '', task_type) \n if task_type in ['target', 'transform', 'condition', 'category', 'entity', 'category_merge', 'pair_equality', 'str_transform', \n 'str_comparison', 'operation_mult', 'comparison', 'seq_order']:\n #print(task_type)\n \n DataFrame, variable_, variable_class_, include_, script_dict_ = create_variable_task(DataFrame, create_variable_task_dict=preprocess_task, return_extra=True, return_script=True) \n \n if include_:\n script_dict_['include'] = True\n script_dict.append(script_dict_)\n if variable_class_=='bin':\n binary_variables.add(variable_)\n elif variable_class_=='cat':\n category_variables.add(variable_)\n\n #Finalize variables lists\n category_variables=list(category_variables)\n binary_variables=list(binary_variables)\n target_variable = target_variable\n \n if return_script:\n return DataFrame, category_variables, binary_variables, target_variable, script_dict\n else:\n return DataFrame, category_variables, binary_variables, target_variable\n\n\n###############################################################################\n# Generate Script\n###############################################################################\ndef generate_variables_script(source, destination): \n if type(source)==list:\n if len(source)==2:\n variables = {\n 'source1': source[0],\n 'source2': source[1],\n 'destination': destination\n } \n elif len(source)==4:\n variables = {\n 'source1a': source[0],\n 'source2a': source[1],\n 'source1b': source[2],\n 'source2b': source[3],\n 'destination': destination\n }\n else:\n variables = {\n 'source': source,\n 'destination': destination\n }\n return variables\n \ndef generate_create_variable_task_script(type='', out_type='', include=False, operation='', source=None, destination=None, parameters={}):\n variable_task_script = {\n 'type': type,\n 'out_type':out_type,\n 'include': include,\n 'operation': operation,\n 'variables': generate_variables_script(source, destination),\n 'parameters': parameters\n }\n return variable_task_script\n\n###############################################################################\n# EZ User Functions\n###############################################################################\ndef create_category_ez(DataFrame, variable, labels_str, default='OTHER', null='NA', to_variable=None, target_variable=None, show_plot=True):\n rule_set = { \n 'operation':'bucket',\n 'variables': {\n 'source':variable, \n 'destination':to_variable\n },\n 'parameters': {\n 'labels_str': labels_str,\n 'right_inclusive':True,\n 'default':default,\n 'null':null\n }\n }\n DataFrame, category_variable = mltk.create_categorical_variable_task(DataFrame, rule_set, return_variable=True)\n print(variable_response(DataFrame=DataFrame, variable=category_variable, target_variable=target_variable, show_plot=show_plot))\n return DataFrame, category_variable\n\ndef create_binary_ez(DataFrame, condition_str, default=0, null=0, to_variable=None, target_variable=None, show_plot=True):\n rule_set = {\n 'operation':'condition', \n 'variables': {\n 'source': None, \n 'destination':to_variable\n },\n 'parameters': {\n 'condition_str':condition_str,\n 'default':default,\n 'null':null,\n }\n } \n \n DataFrame, binary_variable = create_binary_variable_task(DataFrame, rule_set, return_variables=True) \n print(variable_response(DataFrame=DataFrame, variable=binary_variable, target_variable=target_variable, show_plot=show_plot))\n return DataFrame, binary_variable \n\ndef create_entity_ez(DataFrame, variable, dictionary, default='OTHER', null='NA', to_variable=None, target_variable=None, show_plot=True):\n rule_set = {\n 'operation':'dictionary', \n 'variables': {\n 'source': variable, \n 'destination':to_variable\n },\n 'parameters': {\n 'match_type': None,\n 'dictionary':dictionary,\n 'default':default,\n 'null':null,\n }\n } \n \n DataFrame, entity_variable = create_entity_variable_task(DataFrame, rule_set, return_variables=True) \n print(variable_response(DataFrame=DataFrame, variable=entity_variable, target_variable=target_variable, show_plot=show_plot))\n return DataFrame, entity_variable \n\ndef create_entity_ez(DataFrame, variable, dictionary, default='OTHER', null='NA', to_variable=None, target_variable=None, show_plot=True):\n rule_set = {\n 'operation':'dictionary', \n 'variables': {\n 'source': variable, \n 'destination':to_variable\n },\n 'parameters': {\n 'match_type': None,\n 'dictionary':dictionary,\n 'default':default,\n 'null':null,\n }\n } \n \n DataFrame, entity_variable = create_entity_variable_task(DataFrame, rule_set, return_variables=True) \n print(variable_response(DataFrame=DataFrame, variable=entity_variable, target_variable=target_variable, show_plot=show_plot))\n return DataFrame, entity_variable ","sub_path":"MLToolkit/etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":105622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"227711533","text":"from typing import Final, Dict, Callable, Any, List, Optional, Tuple\nimport functools\nfrom llvmlite import ir # type: ignore\nfrom tinygrad.codegen.linearizer import UOps, UOp, Token, MemOp, ConstOp\nfrom tinygrad.helpers import dtypes\nfrom tinygrad.ops import Op, UnaryOps, BinaryOps, TernaryOps\n\nfrom tinygrad.shape.symbolic import Variable, NumNode, MulNode, DivNode, ModNode, LtNode, SumNode, AndNode\ndef int_const(x): return ir.Constant(ir.IntType(64), x)\nrender_llvm = {\n NumNode: lambda self,ops,ctx: int_const(self.b),\n MulNode: lambda self,ops,ctx: ctx.mul(self.a.render(ops,ctx), int_const(self.b)),\n DivNode: lambda self,ops,ctx: ctx.sdiv(self.a.render(ops,ctx), int_const(self.b)),\n ModNode: lambda self,ops,ctx: ctx.srem(self.a.render(ops,ctx), int_const(self.b)),\n LtNode: lambda self,ops,ctx: ctx.icmp_signed(\"<\", self.a.render(ops,ctx), int_const(self.b)),\n SumNode: lambda self,ops,ctx: functools.reduce(lambda a,b: ctx.add(a,b.render(ops,ctx)), self.nodes[1:], self.nodes[0].render(ops,ctx)),\n AndNode: lambda self,ops,ctx: functools.reduce(lambda a,b: ctx.and_(a,b.render(ops,ctx)), self.nodes[1:], self.nodes[0].render(ops,ctx))\n}\n\ncode_for_op: Final[Dict[Op, Callable]] = {\n UnaryOps.EXP2: lambda builder,x: builder.call(builder._block.module.declare_intrinsic('llvm.exp2', [ir.FloatType()]), [x], fastmath=('fast',)),\n UnaryOps.LOG2: lambda builder,x: builder.call(builder._block.module.declare_intrinsic('llvm.log2', [ir.FloatType()]), [x], fastmath=('fast',)),\n UnaryOps.SIN: lambda builder,x: builder.call(builder._block.module.declare_intrinsic('llvm.sin', [ir.FloatType()]), [x], fastmath=('fast',)),\n UnaryOps.SQRT: lambda builder,x: builder.call(builder._block.module.declare_intrinsic('llvm.sqrt', [ir.FloatType()]), [x], fastmath=('fast',)),\n BinaryOps.ADD: lambda builder,x,y: builder.add(x,y) if isinstance(x.type, ir.IntType) else builder.fadd(x,y, flags=('fast',)),\n BinaryOps.SUB: lambda builder,x,y: builder.sub(x,y) if isinstance(x.type, ir.IntType) else builder.fsub(x,y, flags=('fast',)),\n BinaryOps.MUL: lambda builder,x,y: builder.mul(x,y) if isinstance(x.type, ir.IntType) else builder.fmul(x,y, flags=('fast',)),\n BinaryOps.DIV: lambda builder,x,y: builder.sdiv(x,y) if isinstance(x.type, ir.IntType) else builder.fdiv(x,y, flags=('fast',)),\n BinaryOps.CMPLT: lambda builder,x,y: builder.zext(builder.icmp_signed(\"<\", x, y),ir.IntType(32)) if isinstance(x.type, ir.IntType) else builder.uitofp(builder.fcmp_ordered(\"<\", x, y, flags=('fast',)), ir.FloatType()),\n BinaryOps.MAX: lambda builder,x,y: builder.select(builder.fcmp_unordered(\">\", x, y, flags=('fast',)), x, y, flags=('fast',)),\n BinaryOps.MOD: lambda builder,x,y: builder.srem(x,y),\n TernaryOps.MULACC: lambda builder,x,y,z: builder.fadd(builder.fmul(x,y, flags=('fast',)), z, flags=('fast',)),\n TernaryOps.WHERE: lambda builder,x,y,z: builder.select(builder.fcmp_unordered(\"!=\", x, ir.Constant(ir.FloatType(), 0), flags=('fast',)), y, z, flags=('fast',)),\n}\n\ndtype_to_llvm_dtype = {dtypes.float64:ir.DoubleType(), dtypes.float16:ir.HalfType(), dtypes.bfloat16:ir.IntType(16), dtypes.float32:ir.FloatType(), dtypes.int8:ir.IntType(8), dtypes.uint8:ir.IntType(8), dtypes.bool: ir.IntType(1), dtypes.int64: ir.IntType(64), dtypes.int32: ir.IntType(32)}\n\ndef cast(bb, val, input_type, output_type):\n if input_type == output_type: return val\n\n if output_type == dtypes.float32:\n if dtypes.is_int(input_type) or input_type == dtypes.bool:\n val = bb[-1].uitofp(val, ir.FloatType()) if dtypes.is_unsigned(input_type) or input_type == dtypes.bool else bb[-1].sitofp(val, ir.FloatType())\n elif input_type == dtypes.bfloat16:\n val = bb[-1].sext(val, ir.IntType(32))\n val = bb[-1].shl(val, ir.Constant(ir.IntType(32), 16))\n val = bb[-1].bitcast(val, ir.FloatType())\n elif input_type == dtypes.float64:\n val = bb[-1].fptrunc(val, ir.FloatType())\n else:\n val = bb[-1].fpext(val, ir.FloatType())\n return val\n\n if input_type == dtypes.float32:\n if dtypes.is_int(output_type) or output_type == dtypes.bool:\n val = bb[-1].fptoui(val, dtype_to_llvm_dtype[output_type]) if dtypes.is_unsigned(output_type) or output_type == dtypes.bool else bb[-1].fptosi(val, dtype_to_llvm_dtype[output_type])\n elif output_type == dtypes.bfloat16:\n val = bb[-1].bitcast(val, ir.IntType(32))\n val = bb[-1].lshr(val, ir.Constant(ir.IntType(32), 16))\n val = bb[-1].trunc(val, ir.IntType(16))\n elif output_type == dtypes.float64:\n val = bb[-1].fpext(val, ir.DoubleType())\n else:\n val = bb[-1].fptrunc(val, dtype_to_llvm_dtype[output_type])\n return val\n\n raise NotImplementedError(f\"cast from {input_type} -> {output_type} not implemented\")\n\ndef uops_to_llvm_ir(function_name:str, uops:List[UOp]) -> Tuple[str, Optional[List[int]], Optional[List[int]]]:\n # all llvm stuff goes into a module\n module = ir.Module(name=__file__)\n\n # extract global buffers\n buf_to_dtype = {args[0]:args[1] for uop,_,_,args in uops if uop == UOps.DEFINE_GLOBAL}\n buf_index = {x:i for i,x in enumerate(buf_to_dtype.keys())}\n\n # create llvm function\n func_dtypes = [dtype_to_llvm_dtype[dtype] for dtype in buf_to_dtype.values()]\n func = ir.Function(module, ir.FunctionType(ir.VoidType(), [x.as_pointer() for x in func_dtypes]), name=function_name)\n for a in func.args: a.add_attribute(\"noalias\")\n\n # force llvmlite to allow us to add function attribute then add the attribute\n func.attributes._known = func.attributes._known.union(frozenset(['\"no-nans-fp-math\"=\"true\"']))\n func.attributes.add('\"no-nans-fp-math\"=\"true\"')\n\n bb = [ir.IRBuilder(func.append_basic_block(\"entry\"))]\n loop_blocks = []\n reduce_phis: List = []\n # TODO: newvar probably shouldn't be optional\n lvars: Dict[Optional[Token], Any] = {} # this Any is an llvm type\n render_llvm[Variable] = lambda self,ops,ctx: lvars[self.expr]\n\n for uop,newvar,vin,args in uops:\n if uop == UOps.LOOP:\n for var in args[0]:\n if isinstance(var, NumNode): continue\n bb.append(ir.IRBuilder(func.append_basic_block(f\"loop_body_{var.expr}\")))\n bb[-2].branch(bb[-1]._block)\n\n phis = []\n for rp in reduce_phis:\n incoming = lvars[rp]\n lvars[rp] = bb[-1].phi(ir.FloatType())\n lvars[rp].add_incoming(incoming, bb[-2]._block)\n phis.append((rp, lvars[rp]))\n loop_blocks.append((bb[-1], phis))\n\n lvars[var.expr] = bb[-1].phi(ir.IntType(64), name=var.expr)\n lvars[var.expr].add_incoming(int_const(var.min), bb[-2]._block)\n if uop == UOps.ENDLOOP:\n for var in args[0][::-1]:\n if isinstance(var, NumNode): continue\n block, phis = loop_blocks.pop()\n idx_p1 = bb[-1].add(lvars[var.expr], int_const(1))\n lvars[var.expr].add_incoming(idx_p1, bb[-1]._block)\n for n,phi in phis: phi.add_incoming(lvars[n], bb[-1]._block)\n bb.append(ir.IRBuilder(func.append_basic_block(f\"loop_exit_{var.expr}\")))\n bb[-2].cbranch(bb[-2].icmp_unsigned(\"==\", idx_p1, int_const(var.max+1)), bb[-1]._block, block._block)\n if uop == UOps.LOAD:\n assert newvar is not None and isinstance(args, (MemOp, ConstOp))\n valid = args.valid.render(render_llvm, bb[-1])\n if isinstance(args, ConstOp):\n value, invalid_value = [int(args.value), int(args.invalid_value)] if dtypes.is_int(newvar.dtype) else ([bool(args.value), bool(args.invalid_value)] if newvar.dtype == dtypes.bool else [args.value, args.invalid_value]) # type: ignore\n if args.valid.min == 0 and args.valid.max == 1:\n val = bb[-1].select(valid, ir.Constant(dtype_to_llvm_dtype[newvar.dtype], value), ir.Constant(dtype_to_llvm_dtype[newvar.dtype], invalid_value))\n else:\n val = ir.Constant(dtype_to_llvm_dtype[newvar.dtype], value if args.valid.min == 1 else invalid_value)\n # TODO: this is a hack. it shouldn't be const that signals this\n reduce_phis.append(newvar)\n else:\n idx = args.idx.render(render_llvm, bb[-1])\n if args.valid.min == 0:\n aug_idx = bb[-1].select(valid, idx, int_const(0))\n val = bb[-1].select(valid, bb[-1].load(bb[-1].gep(func.args[buf_index[args.name]], [aug_idx], inbounds=True)), ir.Constant(dtype_to_llvm_dtype[args.memory_dtype], args.invalid_value))\n else:\n val = bb[-1].load(bb[-1].gep(func.args[buf_index[args.name]], [idx], inbounds=True))\n val = cast(bb, val, args.memory_dtype, newvar.dtype)\n lvars[newvar] = val\n if uop == UOps.STORE:\n assert args.valid.min == 1 and isinstance(args, MemOp), \"store must be valid and to memory\"\n idx = args.idx.render(render_llvm, bb[-1])\n element = cast(bb, lvars[vin[0]], vin[0].dtype, args.memory_dtype)\n bb[-1].store(element, bb[-1].gep(func.args[buf_index[args.name]], [idx], inbounds=True))\n if uop == UOps.ALU:\n lvars[newvar] = code_for_op[args](bb[-1], *[lvars[x] for x in vin])\n\n bb[-1].ret_void()\n return str(module), None, None\n","sub_path":"tinygrad/renderer/llvmir.py","file_name":"llvmir.py","file_ext":"py","file_size_in_byte":8965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"627732189","text":"import random\nimport string\nimport time\nimport json\nfrom selenium import webdriver\n\ndef get_sites():\n alphabets = string.ascii_lowercase\n website = \"https://www.drugs.com/alpha/\"\n sites = []\n for i in alphabets:\n sites.append(website + i + \".html\")\n\ndef get_drugs_links_to_json(sites):\n driver = webdriver.Chrome('D:/PythonProjects/chromedriver.exe')\n drugs = {}\n for site in sites:\n driver.get(site)\n print(\"Site opend\")\n time.sleep(2)\n ul = driver.find_element_by_xpath('//*[@id=\"content\"]/div[2]/ul')\n lists = ul.find_elements_by_tag_name(\"li\")\n for li in lists:\n med = li.text\n link = (li.find_element_by_tag_name('a')).get_attripbute(\"href\")\n drugs[med] = link\n # print(med,link)\n print(\"*************done with {} site*********\".format(site))\n time.sleep(random.randint(2, 5))\n driver.close()\n with open('drugs_data.json', 'w') as fp:\n json.dump(drugs, fp)\n\ndef get_drug_info():\n driver = webdriver.Chrome('D:/PythonProjects/chromedriver.exe')\n f = open('drugs_data.json', )\n data = json.load(f)\n med_info = {}\n for i in data:\n path = str(data[i])\n print(path)\n driver.get(path)\n ul = driver.find_element_by_xpath('//*[@id=\"content\"]/div[2]')\n time.sleep(5)\n x = ([my_elem.text for my_elem in ul.find_elements_by_css_selector(\"h2\")])\n ul2 = driver.find_element_by_xpath('html/body')\n y = ul2.text\n med_info[i] = ((y.split(x[0]))[1].split(x[1])[0])\n print(\"Data done for \", i)\n time.sleep(random.randint(2, 5))\n for key in med_info:\n med_info[key] = med_info[key].strip('\\n')\n with open('med_info.json', 'w') as fp:\n json.dump(med_info, fp)\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n sites=get_sites()\n print(\"links scraped\")\n get_drugs_links_to_json(sites)\n print(\"drugs scarped\")\n get_drug_info()\n print(\"drugs information scaraped\")\n\n\n\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","sub_path":"scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"196922410","text":"__author__ = 'qianchu_liu'\nimport h5py\n\ndef h5py2word2vec(h5py_file,output_f):\n with open(output_f,'w') as output_f:\n f=h5py.File(h5py_file)\n f = {key: f[key] for key in f.keys() if '[CLS]' not in key}\n\n\n output_f.write('{0} {1}\\n'.format(str(len(f.keys())),len(f[list(f.keys())[0]][0])))\n for sent in f.keys():\n for i, word in enumerate(sent.split('\\t')):\n if len(sent.split('\\t'))==1:\n output_f.write('{0}'.format(sent)+' '+' '.join([str(v) for v in f[sent][i]])+'\\n')\n else:\n output_f.write('{0}||{1}'.format(sent,i)+' '+' '.join([str(v) for v in f[sent][i]])+'\\n')\n\nif __name__=='__main__':\n import sys\n hdf5file=sys.argv[1]\n output_word2vec=sys.argv[2]\n h5py2word2vec(hdf5file,output_word2vec)\n # h5py2word2vec('models/ELMoForManyLangs/chinese_elmo/ch_vocab.ly-1.hdf5','models/ELMoForManyLangs/chinese_elmo/ch_vocab.ly-1.word2vec')","sub_path":"h5py2word2vec.py","file_name":"h5py2word2vec.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"120414401","text":"import os\nimport datetime\nimport json\nimport urllib.request\nimport urllib.parse\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport streamlit as st\n\nbase_url = os.getenv(\"FORECAST_API\", \"http://127.0.0.1:8000/v1/forecast\")\n\nclass Forecast:\n\n def __init__(self, base_url):\n self.base_url = base_url\n\n @st.cache\n def get_data(self, geo_id: str, from_date: datetime.datetime, to_date: datetime.datetime):\n dtf = datetime.datetime.combine(from_date, datetime.datetime.min.time())\n dtt = datetime.datetime.combine(to_date, datetime.datetime.min.time())\n geo_id_encode = urllib.parse.quote(geo_id)\n url = f\"{self.base_url}/getMetric\"\n interval = {\"geo_id\": geo_id, \"metric\": \"cumulative_confirmed\", \"method\": \"curvefit\", \"time_from\": dtf.isoformat(), \"time_to\": dtt.isoformat()}\n interval_payload = json.dumps(interval).encode(\"utf-8\")\n req = urllib.request.Request(url, headers={\"User-Agent\": \"Mozilla/5.0\"}, data=interval_payload)\n r = urllib.request.urlopen(req).read()\n data = json.loads(r.decode(\"utf-8\"))\n df = pd.DataFrame(data[\"result\"][\"series\"]).set_index(\"date_id\")\n return df\n\n @st.cache\n def get_geo_id(self):\n url = f\"{self.base_url}/geo_id\"\n req = urllib.request.Request(url, headers={\"User-Agent\": \"Mozilla/5.0\"})\n r = urllib.request.urlopen(req).read()\n data = json.loads(r.decode(\"utf-8\"))\n return sorted(data)\n\n def write(self):\n with st.spinner(\"Loading Forecast ...\"):\n geos = self.get_geo_id()\n geo = st.selectbox(\"Select Geo Id:\", geos)\n from_date = st.date_input(\"From\", datetime.date(2020, 1, 1))\n to_date = st.date_input(\n \"To\", datetime.datetime.now() + datetime.timedelta(days=14)\n )\n\n df = self.get_data(geo, from_date, to_date)\n fig = go.Figure()\n fig.add_trace(\n go.Scatter(\n x=df.index,\n y=df[\"forecast\"],\n mode=\"lines+markers\",\n name=\"Forecast\",\n line_color=\"red\",\n )\n )\n\n fig.add_trace(\n go.Scatter(\n x=df.index,\n y=df[\"actual\"],\n mode=\"lines+markers\",\n name=\"cumulative cases\",\n line_color=\"rgba(132,183,83,1.0)\",\n )\n )\n\n fig.add_trace(\n go.Scatter(\n x=df.index,\n y=df[\"credible_interval_low\"],\n fill=None,\n mode=\"lines\",\n line_color=\"rgba(0,0,0,0.0)\",\n showlegend=False,\n )\n )\n\n fig.add_trace(\n go.Scatter(\n x=df.index,\n y=df[\"credible_interval_high\"],\n fill=\"tonexty\", # fill area between this and previous trace\n mode=\"lines\",\n line_color=\"rgba(0,0,0,0.0)\",\n fillcolor=\"rgba(0,0,0,0.1)\",\n name=\"95% credible interval\",\n )\n )\n\n st.plotly_chart(fig)\n\nMENU = {\n \"Forecast\": Forecast(base_url)\n}\n\ndef main():\n\n st.sidebar.title(\"Menu\")\n selection = st.sidebar.selectbox(\"Go to\", list(MENU.keys()))\n menu = MENU[selection]\n\n with st.spinner(f\"Loading {selection} ...\"):\n menu.write()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"285016435","text":"import pygame\npygame.init()\n\nX = 1360\nY = 768\ncolor1 = [250,250,250]\ncolor2 = [50,100,100]\nblack = [0,0,0]\nshift = False\npadding = 40\nfontName = \"montserrat.ttf\"\n\nclass Button():\n \"\"\"\n class defined to present a button to perform some function\n \"\"\"\n def __init__(self, title = \"Button\", position = (X//2,Y//2), width = 100, height = 50, fontname = fontName):\n \"\"\"\n Parameters : Title of Button\n \"\"\"\n self.title = title\n self.position = position\n self.width = width\n self.is_clicked = False\n self.is_hover = False\n self.height = height\n self.color = [240,0,40]\n self.hover_color = [220,0,0]\n self.click_color = [177,15,46]\n self.font = pygame.font.Font(fontname, 25)\n self.title_img = self.font.render(self.title, True, color1)\n self.title_img_rect = self.title_img.get_rect()\n self.title_img_rect.center = (self.position[0] + self.width //2, self.position[1] + self.height//2)\n\n def set_color(self,color):\n self.color = color\n\n def set_hover_color(self,hover):\n self.hover_color = hover\n\n def set_click_color(self,click):\n self.click_color = click\n\n def check(self, mouse_pos, event):\n \"\"\"\n THe function checks whether the button was clicked or if the mouse is hovering on the button.\n \"\"\"\n if mouse_pos[0] >= self.position[0] and mouse_pos[0] <= self.position[0] + self.width and mouse_pos[1] >= self.position[1] and mouse_pos[1] <= self.position[1] + self.height:\n self.is_hover = True\n if event.type == pygame.MOUSEBUTTONDOWN:\n self.is_hover = False\n self.is_clicked = True\n else:\n self.is_clicked = False\n else:\n self.is_clicked = False\n self.is_hover = False\n\n def display(self, screen):\n \"\"\"\n Displays the button on the screen according to its position and the action on the button.\n \"\"\"\n if self.is_hover :\n pygame.draw.rect(screen, self.hover_color , (self.position[0], self.position[1], self.width, self.height))\n elif self.is_clicked :\n pygame.draw.rect(screen, self.click_color, (self.position[0], self.position[1], self.width, self.height))\n else:\n pygame.draw.rect(screen, self.color, (self.position[0], self.position[1], self.width, self.height))\n screen.blit(self.title_img, self.title_img_rect)\n\n def set_center(self, pos):\n \"\"\"\n Sets the center for the button to the given parameters.\n \"\"\"\n self.title_img_rect.center = pos\n self.position = (pos[0] - self.width // 2, pos[1] - self.height // 2)\n","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"48162793","text":"import pandas as pd\nimport sys\nimport argparse\n\n\ndef get_extract_idx(f, extract, idx_type):\n df = pd.read_csv(f, sep='\\t', header=0)\n #print df.shape\n if extract == 1:\n df = df[df['gene_type'] == 'protein_coding']\n elif extract == 2:\n df = df[(df['gene_type'] == 'protein_coding') | (df['gene_type'] == 'lincRNA')]\n #print df.shape\n return list(df[idx_type])\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-t\", \"--type\", choices=['gene_id', 'my_index'],\n default='gene_id', required=True,\n help=\"criteria to be parsed by(gene_id or my_index) (Default: gene_id)\")\n parser.add_argument(\"-e\", \"--extract\", choices=[1, 2], default=1, type=int,\n help='Gene types to extract. 1 for protein coding, 2 for protein coding & lincRNA')\n parser.add_argument(\"annotation\", type=str, help=\"annotation file\")\n parser.add_argument(\"result\", type=str,\n help=\"File to be parsed. The file must contain a header.\")\n\n args = parser.parse_args()\n\n idx = get_extract_idx(args.annotation, args.extract, args.type)\n #print len(idx)\n df = pd.read_csv(args.result, sep='\\t', index_col=0, header=0)\n overlap_idx = sorted(list(set(idx) & set(df.columns)))\n #print len(overlap_idx)\n file_prefix = args.result.rsplit('.', 1)[0]\n if args.extract == 1:\n df.loc[:, overlap_idx].to_csv(file_prefix + '.protein_coding.tsv',\n sep='\\t', na_rep='NA')\n else:\n df.loc[:, overlap_idx].to_csv(file_prefix + '.protein_coding_lincRNA.tsv',\n sep='\\t', na_rep='NA')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"extract_protein_coding.py","file_name":"extract_protein_coding.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"323775648","text":"import asyncio\nfrom e2b import Session\n\nwatcher = None\nasync def create_watcher(session):\n watcher = await session.filesystem.watch_dir(\"/home\")\n watcher.add_event_listener(lambda event: print(event))\n\nasync def main():\n session = await Session.create(id=\"Nodejs\")\n\n\n create_watcher(session)\n\n for i in range(10):\n await session.filesystem.write(f\"/home/file{i}.txt\", f\"Hello World {i}!\")\n await asyncio.sleep(1)\n\n\n await session.close()\n\nasyncio.new_event_loop().run_until_complete(main())","sub_path":"apps/docs/src/code/python/basics/fs_watch.py","file_name":"fs_watch.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"78307012","text":"from dataclasses import dataclass, field\n\nimport pygame\nfrom pygame.locals import *\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\nimport numpy as np\n\nfrom .keel import Keel\nfrom .rib import Rib\n\nfrom typing import List, Any\n\n@dataclass\nclass Ship:\n keel:Keel = field(default=None)\n ribs:List[Rib] = field(default_factory=list)\n parent:any = field(default=None)\n parents:List[Any] = field(default_factory=list)\n parents_dirty_flag:bool = field(default=False)\n transration_dirty_flag:bool = field(default=False)\n parent_keels_position:float = field(default=1.)\n\n smoothing:bool = field(default=False)\n smoothing_from:any = field(default=None)\n smoothing_to:any = field(default=None)\n\n def length(self):\n return self.keel.length()\n\n def set_parent(self, parent, position=1.):\n self.parent_keels_position = position\n self.parent = parent\n self.sanitize_keel()\n self.parents = []\n self.get_parents()\n return self\n\n def get_parents(self):\n self.parents_dirty_flag = False\n if self.parent == None:\n return []\n self.parents = []\n self.parents.extend(self.parent.get_parents())\n self.parents.append(self.parent)\n return self.parents\n\n def end(self, child):\n child.end = self\n return self\n\n def relative_vector(self):\n if self.keel is None:\n return None\n return self.keel.end - self.keel.start\n\n def draw(self):\n if self.keel is None:\n return\n if self.smoothing:\n if self.smoothing_from is None\\\n or self.smoothing_from.ribs is None or len(self.smoothing_from.ribs) == 0\\\n or self.smoothing_to is None\\\n or self.smoothing_to.ribs is None or len(self.smoothing_to.ribs) == 0:\n return\n rib_from = self.get_rib_end(self.smoothing_from)\n translated_edges_from = []\n for edge in rib_from.edges:\n translated_edge_from = np.dot(np.array([edge[0], edge[1], 0., 1.]), self.smoothing_from.keel.translation(rib_from.position))\n translated_edges_from.append(translated_edge_from)\n\n rib_to = self.get_rib_start(self.smoothing_to)\n translated_edges_to = []\n for edge in rib_to.edges:\n translated_edge_to = np.dot(np.array([edge[0], edge[1], 0., 1.]), self.smoothing_to.keel.translation(rib_to.position))\n translated_edges_to.append(translated_edge_to)\n Rib.draw_beam(translated_edges_from, translated_edges_to)\n else:\n former_rib_edges = None\n for rib in self.ribs:\n former_rib_edges = rib.draw(self.keel, former_rib_edges)\n \n def write_stl(self, f):\n if self.keel is None:\n return\n if self.smoothing:\n pass\n if self.smoothing_from is None\\\n or self.smoothing_from.ribs is None or len(self.smoothing_from.ribs) == 0\\\n or self.smoothing_to is None\\\n or self.smoothing_to.ribs is None or len(self.smoothing_to.ribs) == 0:\n return\n rib_from = self.get_rib_end(self.smoothing_from)\n translated_edges_from = []\n for edge in rib_from.edges:\n translated_edge_from = np.dot(np.array([edge[0], edge[1], 0., 1.]), self.smoothing_from.keel.translation(rib_from.position))\n translated_edges_from.append(translated_edge_from)\n\n rib_to = self.get_rib_start(self.smoothing_to)\n translated_edges_to = []\n for edge in rib_to.edges:\n translated_edge_to = np.dot(np.array([edge[0], edge[1], 0., 1.]), self.smoothing_to.keel.translation(rib_to.position))\n translated_edges_to.append(translated_edge_to)\n \n xy_cross_product = rib_from.edges_xy_only_cross_product_trial()\n Rib.write_stl_inter_edges(translated_edges_from, translated_edges_to, xy_cross_product, f)\n else:\n if len(self.ribs) == 0:\n return\n rib_start = self.get_rib_start(self)\n rib_start.write_stl_start(self.keel, f)\n rib_end = self.get_rib_end(self)\n rib_end.write_stl_end(self.keel, f)\n former_rib_edges = None\n for rib in self.ribs:\n former_rib_edges = rib.write_stl_beam(self.keel, former_rib_edges, f)\n \n \n\n def init_keel(self):\n self.keel = Keel()\n return self.keel\n \n def sanitize_keel(self):\n self.keel.set_start(self.parent.keel.translation(self.parent_keels_position))\n\n def add_rib(self, position=0., edges=None):\n new_rib = Rib()\n new_rib.position = position\n new_rib.edges = edges\n self.ribs.append(new_rib)\n \n def set_smoothing(self, ship_smoothing_from, ship_smoothing_to=None):\n self.smoothing = True\n self.smoothing_from = ship_smoothing_from\n self.smoothing_to = ship_smoothing_to\n \n def set_smoothing_to(self, ship_smoothing_to):\n self.smoothing = True\n self.smoothing_to = ship_smoothing_to\n\n def get_rib_end(self, ship):\n rib_end = ship.ribs[-1]\n for rib in ship.ribs:\n if rib.position > rib_end.position:\n rib_end = rib\n return rib_end\n\n def get_rib_start(self, ship):\n rib_start = ship.ribs[0]\n for rib in ship.ribs:\n if rib.position < rib_start.position:\n rib_start = rib\n return rib_start\n\n","sub_path":"keel/ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":5615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"559844383","text":"import col_ver\nimport sonuncu_int_getirme\nimport update_mysql\n\n\ndef virgul_sil(virgullu): # virguller basta ya da sonda ise silinir. Gelen icerik tek parca str dir. liste icerigi int dir.\n # virgul sil\n \n if not virgullu == None:\n \n if len(virgullu) > 0:\n \n \n if virgullu[0] == \",\":\n \n virgullu = virgullu[1:]\n \n if virgullu[-1] == \",\":\n \n virgullu = virgullu[:-1]\n \n return virgullu \n\ndef kuyruk_ekle(table_name, bil_sira, bil_val, ist_sira, bil_var_name, ist_var_name, ek_liste, bil_sira_2 = None, bil_val_2 = None, double_val = False, bil_var_name_2 = None): # girisler liste halindedir\n\n # icerik cekilir\n \n olan_icerik = col_ver.fetch_one(table_name, bil_sira, bil_val, ist_sira)\n olan_icerik_raw = olan_icerik # olan icerikler double_var varliginda degisir\n \n if double_val == True:\n \n olan_icerik = col_ver.fetch_one_from_2(table_name, bil_sira, bil_val, bil_sira_2, bil_val_2, ist_sira)\n olan_icerik_raw = olan_icerik \n \n \n # virgul sil \n \n olan_icerik = virgul_sil(olan_icerik)\n\n # gelen listeyi tersten siralama:\n \n ters_ek_liste = ek_liste[::-1]\n \n # tersten listeyi numaratik yapma:\n \n # int_ters_ek_liste = sonuncu_int_getirme.getir(ters_ek_liste, True) # cunku zaten liste int\n virgullu_ters_ek_liste = str(ters_ek_liste)[1:-1]\n \n #kuyruga ekle\n \n yeni_kuyruk = olan_icerik + \",\" + virgullu_ters_ek_liste\n \n yeni_kuyruk = virgul_sil(yeni_kuyruk) # aslinda kendisidir.\n \n # yeni kuyrugu olaniyla degistirme\n \n if double_val == True: # iki degiskeni bilinmeni degistirme\n \n update_mysql.degistir(table_name, bil_var_name, bil_val, ist_var_name, yeni_kuyruk, bil_var_name_2, bil_val_2, True)\n \n else: # eski yontem. tek degiskeni bilineni degistirme\n \n \n update_mysql.degistir(table_name, bil_var_name, bil_val, ist_var_name, yeni_kuyruk)\n \n print(\"neden\")\n \n \n return \"ok\"\n \n\n\ndef sondan_birak(table_name, bil_sira, bil_val, ist_sira, bil_var_name, ist_var_name, cikarilacak = None, belirli_cikarma = None): # fx, sondan bir tane sile, varsa..\n \n \n #cikarilacak liste ya da int olarak girebilir. liste icerigi int olmalidi\n \n # icerik cekilir\n \n olan_icerik = col_ver.fetch_one(table_name, bil_sira, bil_val, ist_sira)\n olan_icerik_raw = olan_icerik\n \n # virgul sil \n \n olan_icerik = virgul_sil(olan_icerik)\n \n # numaratik yapma:\n \n int_olan_icerik = sonuncu_int_getirme.getir(olan_icerik, True) # int ler liste halindedir\n \n if belirli_cikarma == True:\n \n print(str(type(cikarilacak)), file=open(\"type-yaz.txt\", \"a\"))\n \n if not str(type(cikarilacak)) == \"\": # cikarilacak liste ya da int olarak girebilir. liste icerigi int olmalidir\n \n cikarilacak = int(cikarilacak) # bir sayi girer, int ya da degildir.\n \n cikarilacak = [cikarilacak]\n \n \n \n \n \n int_olan_icerik_cikarilmis = [x for x in int_olan_icerik if x not in cikarilacak]\n \n kesik_kuyruk = str(int_olan_icerik_cikarilmis)[1:-1]\n \n else:\n \n # sondan bir tane kesme\n \n if len(int_olan_icerik) > 0:\n \n int_olan_icerik_eksik = int_olan_icerik[0:-1]\n \n # duz str yapma:\n \n kesik_kuyruk = str(int_olan_icerik_eksik)[1:-1]\n \n \n #print(table_name, bil_var_name, bil_val, ist_var_name, kesik_kuyruk, sep=\"\\r\\n\", file=open(\"update_yaz.txt\", \"a\")) # update hatasi\n \n # yeni kuyrugu olaniyla degistirme\n \n update_mysql.degistir(table_name, bil_var_name, bil_val, ist_var_name, kesik_kuyruk)\n \n \n \n return \"ok\"\n \n \n \n \n\n# import kuyruk_ekle_at\n# kuyruk_ekle_at.kuyruk_ekle(\"users\", 1, \"1a4bab8535774b5b\", 5, \"ANDRID_ID\", \"SIRADAKILER\", ek_liste)\n# kuyruk_ekle_at.sondan_birak(\"users\", 1, \"1a4bab8535774b5b\", 5, \"ANDRID_ID\", \"SIRADAKILER\")\n# kuyruk_ekle_at.kuyruk_ekle(\"user_logs\", 0, \"1\", 2, \"USER_ID\", \"OGRENILMIS\", [44,66], 1, \"2019-09-02\", True, \"DATE\")\n\n# kuyruk_ekle_at.sondan_birak(\"users\", 1, \"1a4bab8535774b5b\", 5, \"ANDRID_ID\", \"SIRADAKILER\", 5, True)\n\n\n","sub_path":"apptrogren/kuyruk_ekle_at.py","file_name":"kuyruk_ekle_at.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"513439922","text":"# %%\nimport json\nimport os\nimport pathlib\nfrom datetime import datetime\nfrom functools import partial\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom chemhelp import mndo, units\nfrom data import load_data, prepare_params\nfrom hmc_utils import get_nuts_kernel, sample_chain, trace_fn_nuts\nfrom objective import jacobian_parallel, penalty\n\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n\nmols_atoms, mols_coords, _, _, reference = load_data(query_size=100, offset=110)\nref_energies = reference[\"binding_energy\"].values\n\n# Switch from Hartree to KCal/Mol\nref_energies *= units.hartree_to_kcalmol\n\ndh = 1e-5\nn_procs = 2\nmethod = \"MNDO\"\n\n# NOTE we probably can refactor to remove the duplication of input files\nfilename = \"_tmp_molecules\"\nscrdir = \"_tmp_optim\"\n\npathlib.Path(scrdir).mkdir(parents=True, exist_ok=True)\n\n# TODO JCK At some point we need to evaluate non-zero molecules\nn_molecules = len(mols_atoms)\nmols_charges = np.zeros(n_molecules)\nmols_names = np.arange(n_molecules)\n\nmndo.write_input_file(\n mols_atoms,\n mols_coords,\n mols_charges,\n mols_names,\n method,\n os.path.join(scrdir, filename),\n read_params=True,\n)\n\n# %%\nwith open(\"parameters/parameters-mndo-mean.json\", \"r\") as f:\n mean_params = json.loads(f.read())\n\nwith open(\"parameters/parameters-mndo-std.json\", \"r\") as f:\n scale_params = json.loads(f.read())\n\nparam_keys, _ = prepare_params(mols_atoms, mean_params)\nparam_values = [tf.random.truncated_normal([], stddev=1.0) for _ in param_keys]\n\nroot = os.path.abspath(__file__).split(\"/src\", 1)[0]\n\nkwargs = {\n \"param_keys\": param_keys,\n \"filename\": filename,\n \"n_procs\": n_procs,\n \"dh\": dh,\n \"ref_props\": ref_energies,\n \"mean_params\": mean_params,\n \"scale_params\": scale_params,\n \"binary\": root + \"/mndo/mndo99_binary\",\n \"scr\": scrdir,\n}\n\n# %%\n@tf.custom_gradient\ndef target_log_prob_fn(*param_vals):\n log_likelihood = -penalty(param_vals, **kwargs)\n\n def grad_fn(*dys):\n # grad = jacobian(param_vals, **kwargs)\n grad = jacobian_parallel(param_vals, **kwargs)\n return grad.tolist()\n\n return log_likelihood, grad_fn\n\n\ndef real_target_log_prob_fn(*param_vals):\n res = tf.py_function(target_log_prob_fn, inp=param_vals, Tout=tf.float64)\n # Avoid tripping up sample_chain due to loss of output shape in tf.py_function\n # when used in a tf.function context. https://tinyurl.com/y9ttqdpt\n res.set_shape(param_vals[0].shape[:-1]) # assumes parameter is vector-valued\n return res\n\n\n# %%\nstep_size = tf.cast(5e-3, tf.float64)\nn_adapt_steps = 100\n\n# with tf.GradientTape() as tape:\n# tape.watch(param_values)\n# lp = real_target_log_prob_fn(*param_values)\n# print(tape.gradient(lp, param_values))\n\n# %%\nnow = datetime.now().strftime(\"%Y.%m.%d-%H:%M:%S\")\nlog_dir = f\"runs/hmc-mndo/{now}\"\nsummary_writer = tf.summary.create_file_writer(log_dir)\n\n# %%\nchain, trace, final_kernel_results = sample_chain(\n num_results=30,\n current_state=param_values,\n kernel=get_nuts_kernel(real_target_log_prob_fn, step_size, n_adapt_steps),\n return_final_kernel_results=True,\n trace_fn=partial(trace_fn_nuts, summary_writer=summary_writer),\n)\n\nwith open(\"parameters/parameters-opt-hmc.json\", \"w\") as f:\n json.dump([list(x) for x in chain], f)\n","sub_path":"src/hmc_optim.py","file_name":"hmc_optim.py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"31026761","text":"\nimport logging\nimport sys\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\n# Add Stdout handler\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\n\ndef getLogger():\n return logger","sub_path":"connector-server/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"252082848","text":"import random\n\n\ndef benerate_name():\n\n endname = \"\"\n\n # choose first name\n with open('data/first-names.txt') as f:\n data = f.read().splitlines()\n endname += random.choice(data).capitalize()\n\n endname += \" \"\n\n # choose second name\n with open('data/last-names.txt') as f:\n data = f.read().splitlines()\n endname += random.choice(data).capitalize()\n\n return endname\n\n\ndef hello():\n\n print(\"Hello there, my name is \" + benerate_name() + \".\")\n\nif __name__ == \"__main__\":\n benerate_name()\n","sub_path":"benerator_cumberpy.py","file_name":"benerator_cumberpy.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"234012023","text":"import numpy as np\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.base import clone\nimport matplotlib.pyplot as plt\n\nclass AdaBoostBinaryClassifier(object):\n '''\n INPUT:\n - n_estimator (int)\n * The number of estimators to use in boosting\n * Default: 50\n\n - learning_rate (float)\n * Determines how fast the error would shrink\n * Lower learning rate means more accurate decision boundary,\n but slower to converge\n * Default: 1\n '''\n\n def __init__(self,\n n_estimators=50,\n learning_rate=1):\n\n self.base_estimator = DecisionTreeClassifier(max_depth=2)\n self.n_estimator = n_estimators\n self.learning_rate = learning_rate\n\n # Will be filled-in in the fit() step\n self.estimators_ = []\n self.estimator_weight_ = np.zeros(self.n_estimator, dtype=np.float)\n\n def fit(self, x, y):\n '''\n INPUT:\n - x: 2d numpy array, feature matrix\n - y: numpy array, labels\n\n Build the estimators for the AdaBoost estimator.\n '''\n\n n,m = x.shape\n weights = np.ones(y.shape, dtype=np.float) / n\n for i in range(self.n_estimator):\n estimator, weights, learning_rate = self._boost(x, y , weights)\n self.estimators_.append(estimator)\n self.estimator_weight_[i] = learning_rate\n pass\n\n def _boost(self, x, y, sample_weight):\n '''\n INPUT:\n - x: 2d numpy array, feature matrix\n - y: numpy array, labels\n - sample_weight: numpy array\n\n OUTPUT:\n - estimator: DecisionTreeClassifier\n - sample_weight: numpy array (updated weights)\n - estimator_weight: float (weight of estimator)\n\n Go through one iteration of the AdaBoost algorithm. Build one estimator.\n\n You will need to do these steps:\n\n Fix the Decision Tree using the weights. You can do this like this: estimator.fit(X, y, sample_weight=sample_weight)\n Calculate the error term (estimator_error)\n Calculate the alphas (estimator_weight)\n Update the weights (sample_weight)\n '''\n\n estimator = clone(self.base_estimator)\n estimator.fit(x, y, sample_weight=sample_weight)\n y_predict = estimator.predict(x).reshape(y.shape)\n mask = y != y_predict ## Calculate the wrong prediction\n estimator_error = np.sum(sample_weight[mask]) / np.sum(sample_weight)\n learning_rate = np.log((1 - estimator_error) / estimator_error)\n sample_weight[mask] = sample_weight[mask] * np.exp(learning_rate)\n return estimator, sample_weight, learning_rate\n\n def predict(self, x):\n '''\n INPUT:\n - x: 2d numpy array, feature matrix\n\n OUTPUT:\n - labels: numpy array of predictions (0 or 1)\n '''\n y_pred = np.zeros((x.shape[0], ))\n for i, tree in enumerate(self.estimators_):\n tree_pred = tree.predict(x)\n tree_pred[tree_pred == 0] = -1\n y_pred += self.estimator_weight_[i] * tree_pred\n y_ = np.sign(y_pred)\n y_[y_==-1] = 0\n return y_\n\n\n def score(self, x, y):\n '''\n INPUT:\n - x: 2d numpy array, feature matrix\n - y: numpy array, labels\n\n OUTPUT:\n - score: float (accuracy score between 0 and 1)\n '''\n\n y_pred = self.predict(x).reshape(y.shape)\n return np.sum(y_pred == y) / float(y.shape[0])\n","sub_path":"tree_models/boosting.py","file_name":"boosting.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"241505479","text":"#!/usr/bin/env python\n\nimport os, logging\n\nimport api, actions\n\nfrom flask import Flask, request, send_from_directory, render_template\napp = Flask(__name__)\n\n# probably don't have to modify this file, except for any custom api or action endpoints in add_routes()\n# see \"hello\" examples below\n\ndef page_handler(name):\n\ttpl = name + '.tpl.html'\n\tlogging.debug('Rendering template file %s', tpl)\n\treturn render_template(tpl)\n\ndef static_handler(path=''):\n\tDEFAULT = 'index.html'\n\tif path == '':\n\t\tpath = DEFAULT\n\tif path.endswith('/'):\n\t\tpath = path + DEFAULT\n\tprefix = os.path.dirname(path)\n\tfile = os.path.basename(path)\n\tdir = os.path.join('./static', prefix)\n\tlogging.debug('Sending static file %s', os.path.join(dir, file))\n\treturn send_from_directory(dir, file)\n\ndef add_routes():\n\t# GET /api/v1/data//[/col/]..\n\t# DELETE /api/v1/data/
/col/[/col/]..\n\t# PUT /api/v1/data/
/col/[/col/]..\n\t# POST /api/v1/data/
\n\n\t# Data: select on all\n\tapp.add_url_rule('/api/v1/data/
', 'api_data_table', api.data_handler, methods=['GET'])\n\t# Data: select, insert, update on all\n\tapp.add_url_rule('/api/v1/data/
/', 'api_data_table_path', api.data_handler, methods=['GET','POST','PUT'])\n\t# Data: example to allow delete on one table only\n\t#app.add_url_rule('/api/v1/data/sprocket/', 'api_data_sprocket_delete', api.data_handler, methods=['DELETE'], defaults={'table': 'sprocket'})\n\n\t# custom api method, returns json just like data methods\n\tapp.add_url_rule('/api/v1/hello', 'api_hello', api.hello_handler, methods=['GET'])\n\n\t# custom action, could return templated html, or a 302 redirect to some other page\n\tapp.add_url_rule('/go/to/hello', 'action_hello', actions.hello_handler, methods=['POST'])\n\n\t# generic page handler, looks for a matching tpl.html in templates/\n\tapp.add_url_rule('/page/', 'page', page_handler, methods=['GET'])\n\n\t# generic static doc handler, looks for a matching file in static/\n\tapp.add_url_rule('/', 'static_index', static_handler, methods=['GET'])\n\tapp.add_url_rule('/', 'static_default', static_handler, methods=['GET'])\n\nif __name__ == '__main__':\n\tdebug = os.environ.get('DEBUG', False)\n\n\tlogging.basicConfig(format = '%(asctime)-15s %(levelname)s %(message)s', level = logging.DEBUG if debug else logging.INFO)\n\n\tadd_routes()\n\tapp.run(debug=debug, host='0.0.0.0', port=int(os.environ.get('HTTP_PORT', 8000)))\n","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"600739238","text":"def animate():\n import numpy as np\n import matplotlib.pyplot as plt\n from matplotlib import animation\n\n fig,ax = plt.subplots()\n\n x = np.arange(0,10*np.pi,0.01)\n line, = ax.plot(x,np.sin(x))\n\n def anim(i):\n line.set_ydata(np.sin(x+i/100.0))\n return line,\n\n def init():\n line.set_ydata(np.sin(x))\n return line,\n\n ani = animation.FuncAnimation(fig=fig,func=anim,\n init_func=init,\n frames=1000,interval=20,\n blit=False\n )\n ani.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])\n plt.show()\n\nif __name__ == '__main__':\n animate()\n\n","sub_path":"util/plt.py","file_name":"plt.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"6593373","text":"from rest_framework.authentication import TokenAuthentication, get_authorization_header\nfrom rest_framework.exceptions import AuthenticationFailed\nfrom api_key.models import APIKey\n\n\nclass ApiKeyAuthentication(TokenAuthentication):\n\n def get_token_from_auth_header(self, auth):\n auth = auth.split()\n if not auth or auth[0].lower() != b'api-key':\n return None\n\n if len(auth) == 1:\n raise AuthenticationFailed('Invalid token header. No credentials provided.')\n elif len(auth) > 2:\n raise AuthenticationFailed('Invalid token header. Token string should not contain spaces.')\n\n try:\n return auth[1].decode()\n except UnicodeError:\n raise AuthenticationFailed('Invalid token header. Token string should not contain invalid characters.')\n\n def authenticate(self, request):\n auth = get_authorization_header(request)\n token = self.get_token_from_auth_header(auth)\n\n if not token:\n token = request.GET.get('api-key', request.POST.get('api-key', None))\n\n if token:\n return self.authenticate_credentials(token)\n\n def authenticate_credentials(self, key):\n try:\n token = APIKey.objects.get(api_key=key)\n except APIKey.DoesNotExist:\n raise AuthenticationFailed('Invalid Api key.')\n\n if not token.is_active:\n raise AuthenticationFailed('Api key inactive or deleted.')\n\n user = token.user\n return (user, token)\n","sub_path":"api_key/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"529267570","text":"import torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport numpy as np\nimport time\nimport logging\nimport os\nimport json\nfrom collections import OrderedDict\n\n\nfrom IO import WordDictionary, MonoDictionary, Language,\\\n CrossLingualDictionary, Batcher\nfrom sinkhorn import Prior_sinkhorn\nfrom evaluation import CSLS, Evaluator\nfrom model import bliMethod, LinearTrans\nfrom utils import to_cuda\n\nclass CSSBli(bliMethod):\n def __init__(self, src, tgt, cuda, seed, batcher, data_dir, save_dir): \n \"\"\"\n inputs:\n :param src (str): name of source lang\n :param tgt (str): name of target lang\n :param cuda (int): number of gpu to be used\n :param seed (int): seed for torch and numpy\n :param batcher (Batcher): The batcher object\n :param data_dir (str): Loaction of the data\n :param save_dir (str): Location to save models\n \"\"\"\n super(CSSBli, self).__init__(src, tgt, cuda, seed, batcher, data_dir, save_dir)\n embed_dim = self.batcher.name2lang[self.src].embeddings.shape[1]\n self.transform = LinearTrans(embed_dim).double().to(self.device)\n self.Q = None\n self.rcslsQ = None\n\n def P_solver(self, embi, embj, T, epsilon):\n Mt = -torch.mm(embi.mm(self.Q), embj.t())\n ones1 = torch.ones(Mt.shape[0], device = self.device) / Mt.shape[0]\n ones2 = torch.ones(Mt.shape[1], device = self.device) / Mt.shape[1]\n P = Prior_sinkhorn(ones1, ones2, Mt, T, 0, epsilon, stopThr=1e-3)\n return P\n\n def orthogonal_mapping_update(self, GQ, learning_rate):\n next_Q = (self.Q - learning_rate * GQ).cpu().numpy()\n U, S, VT = np.linalg.svd(next_Q)\n self.Q = torch.from_numpy((U.dot(VT))).to(self.device)\n self.transform.setWeight(self.Q)\n \n def supervised_rcsls_loss(self, src, tgt, nn_src, nn_tgt, k=10):\n # first an assert to ensure unit norming\n if not hasattr(self, \"check_rcsls_valid\"):\n self.check_rcsls_valid = True\n for l in self.batcher.name2lang.values():\n if l.unit_norm is False:\n self.check_rcsls_valid = False\n break\n if not self.check_rcsls_valid:\n raise RuntimeError(\"For RCSLS, need to unit norm\")\n\n xtrans = self.transform(Variable(src))\n yvar = Variable(tgt)\n sup_loss = 2 * torch.sum(xtrans * yvar)\n # Compute nearest nn loss wrt src\n nn_tgt = Variable(nn_tgt)\n dmat = torch.mm(xtrans, nn_tgt.t())\n _, tix = torch.topk(dmat, k, dim=1)\n nnbrs = nn_tgt[tix.view(-1)].view((tix.shape[0], tix.shape[1], -1))\n nnbrs = Variable(nnbrs.data) \n nnloss = torch.bmm(nnbrs, xtrans.unsqueeze(-1)).squeeze(-1)\n nn_tgt_loss = torch.sum(nnloss) / k\n # Compute nearest nn loss wrt tgt\n nn_src = Variable(nn_src)\n nn_src_transform = Variable(self.transform(nn_src).data)\n dmat = torch.mm(yvar, nn_src_transform.t())\n _, tix = torch.topk(dmat, k, dim=1)\n nnbrs = nn_src[tix.view(-1)].view((tix.shape[0], tix.shape[1], -1))\n nnbrs = Variable(nnbrs.data)\n nnloss = torch.bmm(self.transform(nnbrs), yvar.unsqueeze(-1)).squeeze(-1)\n nn_src_loss = torch.sum(nnloss) / k\n return - (sup_loss - nn_tgt_loss - nn_src_loss) / src.size(0)\n\n def procrustes_onestep(self, src_aligned_embeddings, tgt_aligned_embeddings):\n matrix = torch.mm(tgt_aligned_embeddings.transpose(1, 0), src_aligned_embeddings)\n u, _, v = torch.svd(matrix)\n weight = torch.mm(u, v.t())\n return weight\n\n def computePrior(self, X, Y, Q, t):\n M = torch.mm(X.mm(Q), Y.t())\n M = - M + M.topk(10, 1)[0].sum(1).reshape(M.shape[0], 1) / 10 + M.topk(10, 0)[0].sum(0).reshape(1, M.shape[1]) / 10\n Mmin, _ = M.min(axis = 1, keepdim=True)\n T = torch.zeros_like(M, device=self.device) \n torch.exp(-M / t, out=T)\n T = T / torch.sum(T, axis = 1, keepdim=True)\n return T\n\n def train(\n self, epochs, unsup_lr, unsup_epsilon, unsup_bsz, unsup_steps,\n unsup_t, sup_steps, expand_dict_size, expand_rank, save = True, sup_rcsls_k=10, sup_rcsls_tgt_rank=50000,\n sup_opt_params={\"name\": \"SGD\", \"lr\": 1.0},\n sup_bsz=-1\n ):\n logger = logging.getLogger(__name__)\n logger.info(\"[Cyclic Optimization(CSS) between Sup and UnSup]\")\n # train rcsls\n word_dict = self.batcher.pair2ix[f\"{self.src}-{self.tgt}\"]\n pairs = word_dict.word_map\n pairs = pairs[:sup_bsz]\n # init with procrutes\n logger.info(\"Initialize with procrutes\")\n src, tgt = self.batcher.supervised_minibatch(-1, self.src, self.tgt)\n weight = self.procrustes_onestep(src, tgt)\n self.Q = weight.t()\n self.transform.transform.weight.data.copy_(weight)\n\n sup_lr = sup_opt_params[\"lr\"]\n name = sup_opt_params.pop(\"name\")\n for epoch in range(epochs):\n start = time.time()\n logger.info(\"-------------------Start of Epoch {}/{}-------------------\".format(epoch+1, epochs))\n # start optimization with RCSLS\n logger.info(\"-----Supervised RCSLS Optimization-----\")\n fold = np.inf\n sup_opt_params[\"lr\"] = sup_lr\n rcsls_optimizer = getattr(optim, name)(self.transform.parameters(), **sup_opt_params)\n logafter = sup_steps / 4\n for iter in range(1, sup_steps+1):\n if sup_opt_params[\"lr\"] < 1e-4:\n break\n rcsls_optimizer.zero_grad()\n src, tgt, nn_src, nn_tgt = self.batcher.supervised_rcsls_minibatch(sup_bsz, self.src, self.tgt, sup_rcsls_tgt_rank)\n loss = self.supervised_rcsls_loss(\n src, tgt, nn_src, nn_tgt, k=sup_rcsls_k)\n f = loss.item()\n lr_str = sup_opt_params[\"lr\"]\n if f > fold and batch_size == -1:\n sup_opt_params[\"lr\"] /= 2\n rcsls_optimizer = getattr(optim, name)(\n self.transform.parameters(), **sup_opt_params)\n f = fold\n else:\n loss.backward()\n rcsls_optimizer.step()\n self.Q = self.transform.transform.weight.data.t()\n if iter == 1 or iter == sup_steps + 1 or iter % logafter == 0:\n logger.info(\"Sup. {0:4d}/{1:4d} iteration completes, supervied loss: {2:6.4f}\".format(iter, sup_steps, loss))\n self.PriorQ = self.Q\n self.evaluate_test(self.transform)\n logger.info(\"--------Supervised-Phase-Finised--------\")\n \n # Unsupervised\n logger.info(\"-----Unsupervised-Phase-Optimization-----\")\n if epoch == epochs - 1:\n logger.info(\"Skip the unsupervised minimization in the last epoch.\")\n logger.info(\"Finished epoch ({0:d} / {1:d}). Took {2:.2f}s.\".format(epoch + 1, epochs, time.time() - start))\n continue\n logafter = unsup_steps / 4\n rcsls_optimizer = getattr(optim, name)(\n self.transform.parameters(), **sup_opt_params)\n first_batch = self.batcher.firstNbatch(20000)\n embj = first_batch[self.tgt]\n for it in range(1, unsup_steps + 1):\n torch.cuda.empty_cache()\n rcsls_optimizer.zero_grad()\n # sample mini-batch\n mini_batch = self.batcher.minibatch(unsup_bsz)\n embi = mini_batch[self.src][1]\n T = self.computePrior(embi, embj, self.PriorQ, unsup_t)\n # update P and Q alterantively\n P = self.P_solver(embi, embj, T, unsup_epsilon)\n GQ = - torch.mm(embi.t(), P.mm(embj))\n self.orthogonal_mapping_update(GQ, unsup_lr/unsup_bsz)\n loss = torch.norm(torch.mm(embi, self.Q) - torch.mm(P, embj))\n if it == 1 or it == unsup_steps + 1 or it % logafter == 0:\n logger.info(\"Unsup. {0:2d}/{1:2d} iteration completes, unsupervised loss: {2:8.4f}\".format(it, unsup_steps, loss))\n logger.info(\"-----Unsupervised-Phase-Finised-----\")\n self.evaluate_test(self.transform)\n # expand the supervised dictionary\n pairs = self.expand_dict(self.Q, expand_dict_size, expand_rank)\n self.batcher.expand_supervised(self, self.src, self.tgt, pairs)\n logger.info(\"Finished epoch ({0:d} / {1:d}). Took {2:.2f}s.\".format(epoch + 1, epochs, time.time() - start))\n sup_opt_params[\"name\"] = name\n logger.info(\"Finished Training after {0} epochs\".format(epochs))\n self.evaluate_test(self.transform)","sub_path":"model/CSSBli.py","file_name":"CSSBli.py","file_ext":"py","file_size_in_byte":8903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"189200849","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018-12-04 19:02\n# @Author : yuxuecheng\n# @Contact : yuxuecheng@xinluomed.com\n# @Site : \n# @File : sequences_recurrent.py\n# @Software: PyCharm\n# @Description 循环神经网络\n\nimport tensorflow as tf\nfrom tensorflow.contrib import rnn\n\ntime_steps = 10\nbatch_size = 64\nnum_features = 10\nlstm_size = 10\nwords_in_dataset = tf.placeholder(tf.float32, [time_steps, batch_size, num_features])\n\nlstm = rnn.BasicLSTMCell(lstm_size)\n\n# Initial state of the LSTM memory\nstate = lstm.zero_state(batch_size=batch_size, dtype=tf.float32)\nprobabilities = []\nloss = 0.0\nfor current_batch_of_words in words_in_dataset:\n # The value of state is updated after processing each batch of words.\n output, state = lstm(inputs=current_batch_of_words, state=state)\n\n # The LSTM output can be used to make next word predictions\n logits = tf.matmul(output, softmax_w) + softmax_b\n probabilities.append(tf.nn.softmax(logits))\n loss += loss_function(probabilities, target_words)\n\n\nrnn.MultiRNNCell","sub_path":"tensorflow_code/examples/sequences_recurrent/sequences_recurrent.py","file_name":"sequences_recurrent.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"30083253","text":"class Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if prices == []:\n return 0\n length = len(prices)\n yes, no = [0] * length, [0] * length\n yes[-1] = prices[-1]\n for i in range(length - 2, -1, -1):\n if i < length - 2:\n yes[i] = max(yes[i + 1], no[i + 2] + prices[i])\n else:\n yes[i] = max(yes[i + 1], prices[i])\n no[i] = max(no[i + 1], yes[i + 1] - prices[i])\n return no[0]\n","sub_path":"online_judge/leetcode_py/309. Best Time to Buy and Sell Stock with Cooldown.py","file_name":"309. Best Time to Buy and Sell Stock with Cooldown.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"537608359","text":"# -*- coding: utf-8 -*-\nfrom core.helpers import AppRecipe, db_helper\nfrom core.models import RawDirectory\nfrom os.path import join\nfrom random import choice\nimport django\n\n\nclass BaseProjectRecipe(AppRecipe):\n requirements = 'django'\n templates = [\n 'auto_settings.pyt',\n 'auto_urls.pyt',\n 'requirements.txt'\n ]\n urlpatterns = []\n context_processors = []\n middleware_classes = []\n\n\n def __init__(self, project, appname, database='sqlite3'):\n super(BaseProjectRecipe, self).__init__(project, appname)\n\n # Generate secret key\n self.vars['settings.SECRET_KEY'] = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])\n\n # Append default project folder from django\n target_dir = self.project.path\n django_template_dir = join(django.__path__[0], 'conf', 'project_template')\n self.raw[0:0] = (RawDirectory(self, django_template_dir, target_dir),)\n\n # configure databases\n if type(database) is dict:\n self.vars['settings.DATABASES'] = database\n elif database == 'sqlite3':\n self.vars['settings.DATABASES'] = {'default': db_helper(self.project, 'sqlite3')}\n elif database == 'postgresql':\n self.vars['settings.DATABASES'] = {'default': db_helper(self.project, 'postgresql')}\n elif database == 'mysql':\n self.vars['settings.DATABASES'] = {'default': db_helper(self.project, 'mysql')}\n elif database == 'oracle':\n self.vars['settings.DATABASES'] = {'default': db_helper(self.project, 'oracle')}\n\nrecipe = BaseProjectRecipe\n","sub_path":"rscms/recipes/base_project/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"240089610","text":"# -*- coding: utf-8 -*-\nimport os\nimport logging\nimport time\n\nfrom app.omnitag import OmniTag\n\nfrom app.utils import (\n validate_filename,\n prettify_string,\n get_subpath,\n get_fullpath,\n get_only_filename,\n correct_filename_whitespace,\n get_artist_title_from_filename,\n validate_album_format\n)\n\nlog = logging.getLogger('app.convert')\n\n# my year started to collect music\nMY_YEAR = 2000\n\n\ndef use_same_filename(func):\n def wrapper(cls, source, *args, **kwargs):\n source_filename = source\n target = get_only_filename(source_filename)\n subpath = get_subpath(source_filename)\n target = get_fullpath(subpath, target)\n target = '{}.{}'.format(target, ConvertCollection.allow_only_file_type)\n return func(cls, source, target, *args, **kwargs)\n return wrapper\n\n\nclass ConvertCollection:\n\n allow_only_file_type = 'mp3'\n\n @classmethod\n def wav_to_mp3(cls):\n pass\n\n @classmethod\n def flac_to_wav(cls):\n pass\n\n @classmethod\n def ape_to_wav(cls):\n pass\n\n @classmethod\n @use_same_filename\n def m4a_to_mp3(cls, m4a, mp3):\n os.system('avconv -i \"{m4a}\" \"{mp3}\"'.format(\n m4a=m4a,\n mp3=mp3\n ))\n return mp3\n\n @classmethod\n def mp4_to_mp3(cls, *args, **kwargs):\n return cls.m4a_to_mp3(*args, **kwargs)\n\n @classmethod\n def pipe_flac_to_wav_to_mp3(cls, flac, mp3):\n os.system('flac -d \"{a}\" -o - | lame -b 320 -h -V 0 - \"{b}\"'.format(\n a=flac,\n b=mp3\n ))\n return mp3\n\n @classmethod\n def pipe_ape_to_wav_to_mp3(cls, ape, mp3):\n os.system(\n 'ffmpeg -i \"{a}\" -f wav - | lame -b 320 -h -V 0 - \"{b}\"'.format(\n a=ape,\n b=mp3\n ))\n return mp3\n\n @classmethod\n @use_same_filename\n def ape_to_mp3(cls, *args, **kwargs):\n return cls.pipe_ape_to_wav_to_mp3(*args, **kwargs)\n\n @classmethod\n @use_same_filename\n def flac_to_mp3(cls, *args, **kwargs):\n return cls.pipe_flac_to_wav_to_mp3(*args, **kwargs)\n\n\ndef remove_old_file(source):\n os.remove(source)\n\n\ndef rename_file(source, new_filename):\n os.rename(source, new_filename)\n\n\ndef is_filename_valid(filename):\n return validate_filename(OmniTag.REGEX, filename)\n\n\ndef valid_if_no_space(filename):\n name = correct_filename_whitespace(filename)\n is_valid = validate_filename(OmniTag.REGEX, name)\n if is_valid:\n return name\n return None\n\n\ndef get_field(field, namespace, fullpath):\n if field:\n field = prettify_string(field)\n else:\n field = prettify_string(\n input(\"{} for {} : \".format(namespace, fullpath)))\n return field\n\n\ndef rename_music(old_fullpath, subpath, new_filename):\n new_fullpath = get_fullpath(subpath, new_filename)\n rename_file(old_fullpath, new_fullpath)\n music = OmniTag(new_fullpath)\n update_tags(music)\n return music\n\n\ndef update_tags(music):\n if music.file_type != 'mp3':\n '''\n remove this and update_tags in convert block\n if set_field supports flac/ape/m4a\n '''\n return\n filename = music.true_filename.replace('.' + music.file_type, '')\n tags = music.clean_tags\n need_to_update = {}\n artist, title = get_artist_title_from_filename(filename)\n from_filename = {\n 'artist': artist,\n 'title': title,\n }\n for key, value in tags.items():\n if key in ('title', 'artist'):\n if not value:\n need_to_update[key] = from_filename[key]\n elif value.startswith(' ') or value.endswith(' '):\n need_to_update[key] = prettify_string(value)\n music.clean_tags = need_to_update\n\n\ndef update_album(album):\n if validate_album_format(album):\n return album\n\n if '{' in album and '}' in album:\n album = album.replace('}', '').split('{')\n album[1] = int(album[1]) + 1\n return '{}-01-{:02d}'.format(album[0], album[1])\n\n elif '20' in album:\n try:\n album = int(album)\n if album > MY_YEAR:\n return '{}-01-01'.format(album)\n except:\n pass\n\n return time.strftime('%Y-%m-%d')\n\n\ndef save_album(music):\n album = music.album\n new_album = update_album(album)\n if new_album != album:\n print(new_album, album)\n music.album = new_album\n music.music.tags.update_to_v24()\n music.music.save()\n\n\ndef rename_if_needed(music):\n\n fullpath = music.filename\n subpath = get_subpath(fullpath)\n filename = music.true_filename\n file_type = music.file_type\n title = music.title\n artist = music.artist\n if is_filename_valid(filename):\n log.debug('valid filename ' + filename)\n update_tags(music)\n return music\n else:\n second_chance = valid_if_no_space(filename)\n if second_chance:\n del music\n return rename_music(fullpath, subpath, second_chance)\n log.warn('invalid filename ' + filename)\n\n artist = get_field(artist, 'Artist', fullpath)\n title = get_field(title, 'Title', fullpath)\n\n new_filename = '{artist} - {title}.{ext}'.format(\n artist=artist,\n title=title,\n ext=file_type\n )\n del music\n return rename_music(fullpath, subpath, new_filename)\n\n\ndef convert(music):\n \"\"\"\n convert all types to mp3\n store all tag info in memory, and convert\n restore the tag info from memory to new converted file\n done.\n \"\"\"\n file_type = music.file_type\n if file_type != ConvertCollection.allow_only_file_type:\n print('should convert this {}, {}'.format(\n music.title, music.true_filename))\n convert_func = getattr(ConvertCollection, file_type + '_to_mp3')\n old_tags = music.clean_tags\n new_filename = convert_func(music.filename)\n remove_old_file(music.filename)\n del music\n music = OmniTag(new_filename)\n music.clean_tags = old_tags\n update_tags(music)\n\n else:\n print('OK with this {} {}'.format(music.title, music.true_filename))\n return music\n","sub_path":"app/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":6178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"219965632","text":"def solution(sentence):\n str = ''\n for c in sentence:\n if c != '.' or c != ' ':\n str += c\n size = len(str)\n for i in range(size // 2):\n if str[i] != str[size - 1 - i]:\n return False\n return True\n\n\n#아���는 테스트케이스 출력을 해보기 위한 코드입니다. 아래 코드는 잘못된 부분이 없으니, solution함수만 수정하세요.\nsentence1 = \"never odd or even.\"\nret1 = solution(sentence1)\n\n#[실행] 버튼을 누르면 출력 값을 볼 수 있습니다.\nprint(\"solution 함수의 반환 값은\", ret1, \"입니다.\")\n \nsentence2 = \"palindrome\"\nret2 = solution(sentence2)\n\n#[실행] 버튼을 누르면 출력 값을 볼 수 있습니다.\nprint(\"solution 함수의 반환 값은\", ret2, \"입니다.\")","sub_path":"COS-Pro/Python2급/문제/2급_8_initial_code.py","file_name":"2급_8_initial_code.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"202924800","text":"import random\nimport math\nimport mpmath\n\n\ndef acceptance_probability(score1, score2, t):\n return float(math.exp(((score2 - score1)/10000) / t))\n\ndef cooling_scheme(i):\n return (1.00 - 0.001 * i)\n\ndef simulated_annealing(iterations, woningen):\n score1 = random.randint(0, 100000)\n aantal_1 = 0\n aantal_2 = 0\n for i in range(iterations):\n if cooling_scheme(i) < 0.00001:\n print(\"minimale temperatuur bereikt\")\n break\n rand_woning = randint(0, (len(woningen) - 1))\n rand_x = randint(-1, 1)\n rand_y = randint(-1, 1)\n woningen2 = copy.deepcopy(woningen)\n score2 = random.randint(0, 100000)\n print(\"score1 = {} en score2 = {}\".format(score1, score2))\n if score1 > score2:\n\n ap = acceptance_probability(score1, score2, cooling_scheme(i))\n print(\"ap = {}\".format(ap))\n if ap > random.random():\n print(\"score 1 wordt gekozen\")\n aantal_1 += 1\n else:\n print(\"score 2 wordt gekozen\")\n score1 = score2\n aantal_2 += 1\n else:\n print(\"score 2 wordt gekozen\")\n score1 = score2\n aantal_2 += 1\n\n print(\"score 1 = {} keer gekozen\".format(aantal_1))\n print(\"score 2 = {} keer gekozen\".format(aantal_2))\n\n\nsimulated_annealing(100)\n","sub_path":"oud/annealing.py","file_name":"annealing.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"178237597","text":"#!/usr/bin/env python3.6\n# -*- coding: utf-8 -*-\n#@Author: Yang Xiaojun\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport operator\nfrom functools import reduce\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nmove_average_decay=0.99\n\nlearning_rate_decay=0.99\n\n\nlearning_rate_base = 0.8\n\n\nregularization = 0.0001\n\n\n\nbatch_size=128\n\ntr_set = r'C:\\Users\\XUEJW\\Desktop\\yang_test\\data_set\\tensor_input_train_set.csv'\ntest_file = r'C:\\Users\\XUEJW\\Desktop\\yang_test\\data_set\\tensor_input_test_set.csv'\n# pwd = os.getcwd()\n# os.chdir(os.path.dirname(tr_set))\ntrain_data = pd.read_csv(tr_set,header=None)#不能有中文出现\n# os.chdir(os.path.dirname(test_file))\ntest_data = pd.read_csv(test_file,header=None)\n\n\nnum_data=train_data.shape[0]\n\ntrain_x = train_data.iloc[:, :-1].values\n\ntrain_y_ = train_data.iloc[:, -1:].values\n\ntrain_2 = np.array(train_y_).tolist()\nlabels=reduce(operator.add,train_2)\none_hot = pd.get_dummies(labels)\none_hot = one_hot.astype('float')\n\ntest_x = test_data.iloc[:, 0:-1].values\ntest_0= test_data.iloc[:, -1:].values\n\ntest_1 = np.array(test_0).tolist()\nlabels_test=reduce(operator.add,test_1)\none_hot1= pd.get_dummies(labels_test)\none_hot1 = one_hot1.astype('float')\ndataSize=train_x.shape[0]\nprint('0:',len(one_hot1))\ndef inf(x,w0,w1,w2,w3,b0,b1,b2,b3,avgclass=None):\n if avgclass==None:\n y1=tf.nn.relu(tf.matmul(x,w0)+b0)\n y2 = tf.nn.relu(tf.matmul(y1, w1) + b1)\n y3 = tf.nn.relu(tf.matmul(y2, w2) + b2)\n return tf.matmul(y3,w3)+b3\n else:\n y1=tf.nn.relu(tf.matmul(x,avgclass.average(w0))+avgclass.average(b0))\n y2 = tf.nn.relu(tf.matmul(y1, avgclass.average(w1)) + avgclass.average(b1))\n y3 = tf.nn.relu(tf.matmul(y2, avgclass.average(w2)) + avgclass.average(b2))\n\n return tf.matmul(y3,avgclass.average(w3))+avgclass.average(b3)\n\nx=tf.placeholder(tf.float32,shape=[None,2763],name='x-input')\ny_=tf.placeholder(tf.float32,shape=[None,11],name='y-input')\nw0=tf.Variable(tf.truncated_normal(shape=[2763,8192],stddev=0.1,dtype=tf.float32))\nw1=tf.Variable(tf.truncated_normal(shape=[8192,4096],stddev=0.1,dtype=tf.float32))\nw2=tf.Variable(tf.truncated_normal(shape=[4096,1024],stddev=0.1,dtype=tf.float32))\nw3=tf.Variable(tf.truncated_normal(shape=[1024,11],stddev=0.1,dtype=tf.float32))\nb0=tf.Variable(tf.constant(0.1,shape=[8192]))\nb1=tf.Variable(tf.constant(0.1,shape=[4096]))\nb2=tf.Variable(tf.constant(0.1,shape=[1024]))\nb3=tf.Variable(tf.constant(0.1,shape=[11]))\n\nglobal_step=tf.Variable(0,trainable=False)\n\nlearning_rate=tf.train.exponential_decay(learning_rate_base,global_step,dataSize/batch_size,learning_rate_decay,staircase=False)\n\n# a=tf.nn.relu(tf.matmul(x,w1)+b1)\n\n# y__=tf.matmul(a,w2)+b2\n\ny__=inf(x,w0,w1,w2,w3,b0,b1,b2,b3)\n\n\n\nvariable_averages=tf.train.ExponentialMovingAverage(\n move_average_decay,global_step\n)\nvariable_averages_op=variable_averages.apply(tf.trainable_variables())#滑动平均的方法更新参数,decay为衰减速率\n\n\ny=inf(x,w0,w1,w2,w3,b0,b1,b2,b3,variable_averages)\n\nentropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y__))+tf.contrib.layers.l2_regularizer(regularization)(w0)+tf.contrib.layers.l2_regularizer(regularization)(w1)+tf.contrib.layers.l2_regularizer(regularization)(w2)+tf.contrib.layers.l2_regularizer(regularization)(w3)\n\n# train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(entropy,global_step)\n\ntrain_step=tf.train.AdamOptimizer(learning_rate).minimize(entropy)\n\nwith tf.control_dependencies([train_step,variable_averages_op]):\n train_op=tf.no_op(name='train')\n\ncor=tf.equal(tf.argmax(y_,1),tf.argmax(y,1))\naur=tf.reduce_mean(tf.cast(cor,tf.float32))\nmodel_path = r'C:\\Users\\XUEJW\\Desktop\\yang_test\\data_set\\model.ckpt'\nwith tf.Session() as sess:\n init_op=tf.global_variables_initializer()\n\n sess.run(init_op)\n\n saver = tf.train.Saver()\n if os.path.isfile(model_path):\n saver.restore(sess, \"D:\\sample\\model.ckpt\")\n for i in range(5000):\n if i%100==0 and i>30:\n auc=sess.run(aur,feed_dict={x:test_x,y_:one_hot1})\n\n print(\"第{}次,准确率为{}\".format(i+100,auc))\n start = (i * batch_size) % (dataSize )\n end = min(start + batch_size, dataSize )\n sess.run(train_op,feed_dict={x:train_x[start:end],y_:one_hot[start:end]})\n\n\n save_path = saver.save(sess, model_path)\n # yy = sess.run(y__, feed_dict={x: test_x})\n # yl = sess.run(tf.argmax(yy, 1))\n","sub_path":"untiltled code/ecif_xy/classify2tensor.py","file_name":"classify2tensor.py","file_ext":"py","file_size_in_byte":4449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"550121671","text":"\nfrom ComplexCar import ComplexCar\nimport random\nimport numpy as np\n\nclass Road:\n\n\tdef __init__(self, length, numRoads, prob):\n\t\tself.sections = [(0, ComplexCar(0))] * (length + 1 + numRoads)\n\t\tself.speed = 2\n\t\tself.numRoads = numRoads\n\t\tself.carPositions = []\n\t\tself.prob = prob\n\t\tself.length = length\n\t\tself.numCars = 0\n\n\tdef numCars(self):\n\t\treturn self.numCars\n\n\tdef binaryRepresentation(self):\n\t\ttemp = np.array([bit[0] for bit in self.sections])\n\t\treturn temp\n\n\n\tdef newInstance(self):\n\t\tself.sections = [(0, ComplexCar(0))] * (self.length + 1 + self.numRoads)\n\n\n\tdef getState(self):\n\t\tbinary = []\n\t\twait = []\n\t\tspeed = [self.speed]\n\t\tfor i in range(len(self.sections)):\n\t\t\tbinary.append(self.sections[i][0])\n\t\t\twait.append(self.sections[i][1].wait_time)\n\n\t\tstate = [each for each in binary] + [each for each in wait] + speed\n\t\treturn np.array(state)\n\n\tdef getSimpleState(self):\n\t\toutput = self.binaryRepresentation()\n\t\tfor each in self.sections:\n\t\t\toutput.append(each[1].wait_time)\n\t\toutput.append(self.speed)\n\t\treturn output\n\n\tdef crash(self):\n\t\tself.sections = [(-1, ComplexCar(0))] * (self.length + 1 + self.numRoads)\n\n\tdef setPositions(self):\n\t\tself.carPositions = []\n\t\tfor i in range(len(self.sections)):\n\t\t\tif(self.sections[i][0] == 1):\n\t\t\t\tself.carPositions.append(i)\n\n\tdef updateStep(self, stepNum):\n\t\tfor i in range(len(self.carPositions)):\n\t\t\tindex = self.carPositions[i]\n\t\t\tif(self.speed >= stepNum and self.sections[index][0] == 1):\n\t\t\t\tcars = self.sections[index - 1][0] + 1\n\t\t\t\tif(cars == 2):\n\t\t\t\t\treturn 0\n\n\t\t\t\twait_time = self.sections[index][1].wait_time\n\t\t\t\tself.sections[index - 1] = (cars, ComplexCar(wait_time))\n\t\t\t\tself.sections[index] = (0, ComplexCar(0))\n\t\tself.setPositions()\n\t\treturn 1\n\n\n\tdef totalWait(self):\n\t\ttotal_wait = sum([car[1].wait_time for car in self.sections])\n\t\treturn total_wait\n\n\n\tdef step(self,action, stepNum):\n\t\tif action == 1:\n\t\t\tif self.speed < 2:\n\t\t\t\tself.speed += 1\n\t\telif action == -1:\n\t\t\tif self.speed > 0:\n\t\t\t\tself.speed -= 1\n\t\toutput = []\n\t\tchance = random.random()\n\t\t#list - 1\n\t\tfinishCar = self.sections.pop(0)\n\t\tself.sections.insert(0, (0,ComplexCar(0)))\n\t\tupdate = self.updateStep(stepNum)\n\t\tif(update == 0):\n\t\t\tself.crash()\n\t\t\toutput.append(-1)\n\t\telse:\n\t\t\toutput.append(finishCar[0])\n\t\toutput.append(self.sections[1])\n\n\t\tif self.sections[len(self.sections) - 1][0] == 0:\n\t\t\tif (chance <= self.prob):\n\t\t\t\tself.sections[len(self.sections) - 1] = (1, ComplexCar(0))\n\t\t\t\tself.numCars += 1\n\t\treturn np.array(output)\n\n\n\tdef passiveStep(self, stepNum):\n\t\toutput = []\n\t\tchance = random.random()\n\t\t#list - 1\n\t\tfinishCar = self.sections.pop(0)\n\t\tself.sections.insert(0, (0,ComplexCar(0)))\n\t\tupdate = self.updateStep(stepNum)\n\t\tif(update == 0):\n\t\t\tself.crash()\n\t\t\toutput.append(-1)\n\t\telse:\n\t\t\toutput.append(finishCar[0])\n\t\toutput.append(self.sections[1])\n\n\t\tif self.sections[len(self.sections) - 1][0] == 0:\n\t\t\tif (chance <= self.prob):\n\t\t\t\tself.sections[len(self.sections) - 1] = (1, ComplexCar(0))\n\t\t\t\tself.numCars += 1\n\t\treturn np.array(output)\n\n\n\n","sub_path":"IntersectionSpeed/Road.py","file_name":"Road.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"555213548","text":"#!/usr/bin/env pyhton\n\nimport warnings\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit, least_squares\nfrom scipy.linalg import svd\nfrom scipy.optimize import OptimizeWarning\nfrom matplotlib.widgets import Button\nfrom astropy.io import fits\n\n# Local modules\nimport dbio\nimport funcs\nimport fitstools as ft\n\ndb=dbio.fit_database()\nfunc=funcs.funcs()\n\ndef model(x, param):\n i=0\n mod=0.0\n pp=[]\n vpnum=[]\n for k in range(db.component_num):\n pp.clear()\n vpnum1=[]\n for l in range(db.funcinfo[k][1]):\n if db.params[k][l][5] == 0:\n pp.append(param[i])\n vpnum1.append(i)\n i+=1\n elif db.params[k][l][5] == -1:\n pp.append(db.params[k][l][0])\n vpnum1.append(-1)\n else:\n pp.append(param[ vpnum[ db.params[k][l][5]-1 ] [l] ] * \\\n db.params[k][l][3])\n vpnum1.append(-1)\n vpnum.append(vpnum1)\n mod += getattr(func,db.funcinfo[k][0])(x, *pp)\n return(mod)\n\ndef calc_residuals(params, x, y):\n model_y = model(x, params)\n return model_y - y\n \ndef model_for_plot(x):\n mod=0.0\n for k in range(db.component_num):\n pp=[]\n for i in range(len(db.params[k])):\n pp.append(db.params[k][i][0])\n mod += getattr(func,db.funcinfo[k][0])(x, *pp)\n return(mod)\n\n\nclass Index(object):\n \n def accept(self, event):\n global key\n key='y'\n plt.close()\n return\n\n def redo(self, event):\n global key\n key = 'n'\n plt.close()\n return\n\ndef specplot(data, titleline, message_switch, message):\n # Plot the result\n callback = Index()\n\n fig = plt.figure() \n ax1 = fig.add_axes((0.1 ,0.35, 0.75, 0.55))\n ax2 = fig.add_axes((0.1, 0.1, 0.75, 0.2), sharex=ax1)\n \n ax1.set_title(titleline)\n ax1.step(data[:,0],data[:,1],where='mid')\n ax1.plot(data[:,0],model_for_plot(data[:,0]))\n for k in range(db.component_num):\n pp=[]\n for i in range(len(db.params[k])):\n pp.append(db.params[k][i][0])\n ax1.plot(data[:,0], getattr(func, db.funcinfo[k][0])(data[:,0], *pp))\n ax1.grid()\n ax1.set_ylabel('Intensity')\n ax1.tick_params(labelbottom=\"off\")\n \n ax2.plot(data[:,0],data[:,1] - model_for_plot(data[:,0]))\n ax2.grid()\n ax2.set_xlabel('Wavelength ($\\AA$)')\n ax2.set_ylabel('Residual')\n\n if not message_switch:\n ax1.text(0.5,0.5,message, horizontalalignment='center', \n verticalalignment='center', transform=ax1.transAxes, \n color='red', weight='bold') \n\n axredo = plt.axes([0.88, 0.8, 0.1, 0.05])\n bredo = Button(axredo, 'Redo')\n bredo.on_clicked(callback.redo)\n\n axaccept = plt.axes([0.88, 0.7, 0.1, 0.05])\n baccept = Button(axaccept, 'Accept')\n baccept.on_clicked(callback.accept)\n plt.show()\n return\n\n\ndef fitting(fnames, area, dbname, outdbfname, without_plot, sample_range, \n without_fit, method, en, absolute_sigma=False):\n\n titleline = ''\n for fname in fnames:\n titleline += fname\n \n global key\n key = 'n'\n while key == 'n':\n # Reading the parameters\n db.dbread(dbname)\n #print(db.params)\n\n # Selecting the data within the sample rages\n \n if sample_range != \"*\":\n datatmp = GetData(fnames[0], area, en)\n if len(fnames) > 1:\n for fname in fnames[1:]:\n datatmp3 = GetData(fname, area, en)\n datatmp = np.vstack((datatmp, datatmp3))\n wrangetmp = sample_range.split(\",\")\n wrange = []\n datatmp2 = []\n for i in range(len(wrangetmp)):\n wrange.append(wrangetmp[i].split(\"-\"))\n for i in range(len(wrangetmp)): \n for j in range(len(datatmp[:,0])):\n if datatmp[j][0] >= float(wrange[i][0]) and \\\n datatmp[j][0] <= float(wrange[i][1]):\n datatmp2.append([datatmp[j][0],datatmp[j][1]])\n data = np.array(datatmp2)\n else:\n data = GetData(fnames[0], area, en)\n if len(fnames) > 1:\n for fname in fnames[1:]:\n datatmp3 = GetData(fname, area, en)\n data = np.vstack((data, datatmp3))\n \n #plt.plot(data[:,0], data[:,1])\n #plt.show()\n \n if without_fit == False:\n # Scaling the data\n scale = np.average(data[:,1])\n data[:,1]=data[:,1]/scale\n\n # Scaling the parameters if needed\n db.params = func.scale(scale, db.component_num, db.funcinfo,\n db.params)\n\n # Set the initial parameters (p0) and\n # boundaries (maxbound, minbound) for fitting\n p0=[]\n minbound=[]\n maxbound=[]\n for i in range(db.component_num):\n for j in range(db.funcinfo[i][1]):\n if db.params[i][j][5] == 0:\n p0.append(db.params[i][j][0]) \n minbound.append(db.params[i][j][1])\n maxbound.append(db.params[i][j][2])\n # Fitting\n if method == 'lm':\n res = least_squares(calc_residuals, p0,\n args=(data[:,0],data[:,1]),\n method = method, verbose=2,\n xtol=3.0e-16, ftol=3.0e-16,\n gtol=3.0e-16, max_nfev=1000)\n elif method == 'trf' or method == 'dogbox':\n res = least_squares(calc_residuals, p0,\n args=(data[:,0],data[:,1]),\n method = method, verbose=2,\n bounds=(minbound,maxbound),\n xtol=3.0e-16, ftol=3.0e-16,\n gtol=3.0e-16, max_nfev=1000)\n else:\n print('Method is lm, trf or dogbox.')\n break\n \n ####### Taken from curve_fit function in minpack.py\n #if not res.success:\n # raise RuntimeError(\"Optimal parameters not found: \" + res.message)\n\n cost = 2 * res.cost # res.cost is half sum of squares!\n popt = res.x\n\n # Do Moore-Penrose inverse discarding zero singular values.\n _, s, VT = svd(res.jac, full_matrices=False)\n threshold = np.finfo(float).eps * max(res.jac.shape) * s[0]\n s = s[s > threshold]\n VT = VT[:s.size]\n pcov = np.dot(VT.T / s**2, VT)\n\n warn_cov = False\n if pcov is None:\n # indeterminate covariance\n pcov = np.zeros((len(popt), len(popt)), dtype=float)\n pcov.fill(np.inf)\n warn_cov = True\n elif not absolute_sigma:\n if data[:,1].size > len(p0):\n s_sq = cost / (data[:,1].size - len(p0))\n pcov = pcov * s_sq\n else:\n pcov.fill(np.inf)\n warn_cov = True\n\n if warn_cov:\n warnings.warn('Covariance of the parameters could not be estimated',\n category=OptimizeWarning)\n ###### End of quate\n\n perr = np.sqrt(np.diag(pcov)) \n\n # Canceling scaling and Substituting the resultant parameters\n # to the parameter list\n k=0\n for i in range(db.component_num):\n for j in range(db.funcinfo[i][1]):\n if db.params[i][j][5] == 0:\n db.params[i][j][0] = popt[k]\n db.params[i][j][4] = perr[k]\n k+=1\n elif db.params[i][j][5] == -1:\n db.params[i][j][4] = 0.0\n else:\n db.params[i][j][0] = db.params[db.params[i][j][5]-1][j][0]*db.params[i][j][3]\n db.params[i][j][4] = db.params[db.params[i][j][5]-1][j][4]*db.params[i][j][3]\n\n # Putting back before scaling\n scale = 1.0/scale\n db.params = func.scale(scale, db.component_num, db.funcinfo, db.params)\n\n else:\n #data=datatmp\n scale=1.0\n for i in range(db.component_num):\n for j in range(db.funcinfo[i][1]):\n if db.params[i][j][5] != 0 and db.params[i][j][5] != -1:\n db.params[i][j][0] = db.params[db.params[i][j][5]-1][j][0]*db.params[i][j][3]\n db.params[i][j][4] = db.params[db.params[i][j][5]-1][j][4]*db.params[i][j][3]\n\n # Plot\n if without_plot == False:\n data[:,1]=data[:,1]/scale\n if without_fit == False:\n specplot(data, titleline, res.success, res.message)\n else:\n specplot(data, titleline, 1, '')\n else:\n key ='y'\n\n if without_fit == False:\n # Writing the results\n db.dbwrite(fname, area, sample_range, dbname, method, outdbfname,\n res.message)\n\n return\n\ndef GetData(fname, area, en):\n # Creating a data array including wavelength and intensity.\n # fname: Input FITS file name\n # area: Spatial area (string like x1,x2,y1,y2)\n # en: Extension number of data used for ftting.\n\n hdl = fits.open(fname)\n lam = ft.GetLambdaArr(hdl[en].header)\n intensities = hdl[en].data\n\n # Creating array of 1D intensity data\n a = [int(s) for s in area.split(',')]\n # a is coodinate in DS9\n temp = np.sum(intensities[:, a[2]-1:a[3], a[0]-1:a[1]], axis=1)\n intensity = np.sum(temp, axis=1)\n\n # Stacking arrays of lambadas and 1D intensity data\n data = np.stack((lam, intensity)).T\n\n hdl.close()\n \n return data\n\n\nif __name__ == '__main__' :\n import argparse\n \n # Analize argments\n parser=argparse.ArgumentParser()\n parser.add_argument('fnames', help='Input file names')\n parser.add_argument('area', help='Area')\n parser.add_argument('dbfname',\n help='database file name for initial parameters')\n parser.add_argument('outfname', help='output file name')\n parser.add_argument('-without_plot',action='store_true',\n help='Without result plot')\n parser.add_argument('-without_fit',action='store_true', help='Without fit')\n parser.add_argument('-sample_range',action='store',\n help='Sample wavelength ranges',default=\"*\")\n parser.add_argument('-method',action='store',\n choices=['lm', 'trf', 'dogbox'],\n help='Algorithm to perform minimization. Default:trf',\n default='trf')\n parser.add_argument('-en', type=int, help='Extension number. Default:0')\n\n args = parser.parse_args()\n\n # Set the matplotlib figure saving directory to the current directory.\n plt.rcParams['savefig.directory'] = os.getcwd()\n \n print('')\n fitting(args.fnames.split(','), args.area, args.dbfname, args.outfname,\n args.without_plot,\n args.sample_range, args.without_fit, args.method, args.en)\n print('')\n\n","sub_path":"fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":11463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"647390973","text":"# Copyright 2015 Shannon Lucas\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy\n# 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 under\n# the License.\n\nfrom ordtext.commands import PatternMatch, AbstractCommand\nfrom aerodata.weather.metar.models import PresentWeatherModel, \\\n RecentWeatherModel\n\n\nclass PresentWeather(AbstractCommand):\n \"\"\"Parses present weather data from a METAR.\n\n .. sidebar:: Sources:\n - NOAA/FAA AC 00-45F, Change 2, Section 3.1.3.8\n - WMO FM 15-XIV METAR/FM 16-XIV SPECI, Regulation 15.8\n \"\"\"\n _CMD = PatternMatch((r\"^(?P-|\\+|VC)?\"\n \"(?PMI|PR|BC|DR|BL|SH|TS|FZ)?\"\n \"(?P(DZ|RA|SN|SG|IC|PL|GR|GS|UP)?\"\n \"(DZ|RA|SN|SG|IC|PL|GR|GS|UP)?\"\n \"(DZ|RA|SN|SG|IC|PL|GR|GS|UP)?)\"\n \"(?PBR|FG|FU|VA|DU|SA|HZ|PY)?\"\n \"(?PPO|SQ|FC|SS|DS)?$\"), by_name=True)\n\n def __call__(self, tokens):\n \"\"\"Extracts the present weather information from the METAR.\n\n :param Sequence[str] tokens: the sequence of tokens being parsed.\n\n :return: a tuple containing the present weather information (first\n element) and a sequence of the remaining tokens (second element).\n :rtype: (PresentWeatherModel, Sequence)\n \"\"\"\n m, remainder = PresentWeather._CMD(tokens)\n p = m[\"precipitation\"]\n\n # Split the precipitation into two character chunks.\n precip = [p[i:i + 2] for i in range(0, len(p), 2) if p]\n\n parsed = PresentWeatherModel(\n intensity=m[\"intensity\"],\n descriptor=m[\"descriptor\"],\n precipitation=precip,\n obscuration=m[\"obscuration\"],\n other=m[\"other\"]\n )\n\n return parsed, remainder\n\n\nclass RecentWeather(AbstractCommand):\n \"\"\"Parses recent weather data from a METAR.\n\n .. sidebar:: Sources:\n - WMO FM 15-XIV METAR/FM 16-XIV SPECI, Regulation 15.13.2\n \"\"\"\n _CMD = PatternMatch((r\"^RE(?PBL|SH|TS|FZ)?\"\n r\"(?PDZ|RA|SN|SG|IC|PL|GR|GS|UP)?\"\n r\"(?PVA|DU|SA)?\"\n r\"(?PFC|SS|DS)?$\"), by_name=True)\n\n def __call__(self, tokens):\n \"\"\"Extracts the recent weather information from the METAR.\n\n :param Sequence[str] tokens: the sequence of tokens being parsed.\n\n :return: a tuple containing the recent weather information (first\n element) and a sequence of the remaining tokens (second element).\n :rtype: (RecentWeatherModel, Sequence)\n \"\"\"\n m, remainder = RecentWeather._CMD(tokens)\n\n parsed = RecentWeatherModel(\n descriptor=m[\"descriptor\"],\n precipitation=m[\"precipitation\"],\n obscuration=m[\"obscuration\"],\n other=m[\"other\"]\n )\n\n return parsed, remainder\n","sub_path":"aerodata/weather/metar/commands/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"463915341","text":"print( \"you have successfully imported the jet latitude calculation subroutines\" )\n\nimport numpy as np\n\ndef getzonalmeanonplev( xdatin, plev ):\n# -----calculates zonal mean and picks out a pressure level-----\n# input: xdatin = xarray data array (plev,nlat,nlon)\n# : plev = desired pressure level (hPa)\n# oudput: xdatzmonp = the zonal mean of xdatin on plev\n# --------------------------------------------------------------\n plevpa = plev*100. #convert to Pa\n xdatzm = xdatin.mean(dim='lon') \n xdatzmonp = xdatzm.sel(plev = plevpa, method='nearest') \n\n return xdatzmonp \n\ndef calcjetlat( uzm, minlat, maxlat):\n# -----calculate the latitude of a maximum between latitude bounds \n# input: uzm = data array(nlat)\n# minlat = minimum latitude over which to search for the max\n# maxlat = maximum latitude over which to search for the max\n# output: jlatv = the jet latitude\n# jmaxv = the jet maximum\n# the jet is as the maximum of the quadratic fit to the grid point maximum\n# and the two adjacent grid points (as Kidston and Gerber 2010)\n# NaN's are skipped\n lats = uzm.sel(lat = slice(minlat,maxlat)).coords['lat']\n imax = uzm.sel(lat = slice(minlat,maxlat)).argmax(dim='lat', skipna=True, keep_attrs=True)\n if (imax == 0) or (imax == len(lats)-1):\n jlatv = np.nan\n jspeedv = np.nan\n print( \"!!!! no local maximum found in calcjetlat\" )\n\n else:\n lat4fit = lats.isel(lat=slice(int(imax)-1,int(imax)+2))\n u4fit = uzm.sel(lat = slice(minlat,maxlat)).isel(lat=slice(int(imax)-1,int(imax)+2))\n coefs = np.polyfit(lat4fit,u4fit,2)\n jlatv = -1.*coefs[1]/(2.*coefs[0])\n jspeedv = coefs[2] + coefs[1]*jlatv + coefs[0]*jlatv**2\n\n return jlatv, jspeedv\n\n \n","sub_path":"notebooks/jetlatcalcs.py","file_name":"jetlatcalcs.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"41593148","text":"# coding: utf-8\n# 在执行前注意不要在服务器上面直接改,在另外一个schame上面改\nfrom pyspark import SparkContext,SparkConf\nfrom pyspark.sql import SQLContext, HiveContext,UDFRegistration,SparkSession\nfrom pyspark.sql.functions import udf\nimport datetime\nimport re\n\n\ndef get_number(item):\n res = re.search(r'\\d+', str(item))\n if res:\n return str(res.group())\n return '0'\n\n\ndef get_shelf_life(item):\n if item:\n if 1 < int(item) < 8:\n return int(item)-1\n else:\n return int(item)\n return 1\n\n\ndef convert_material(item):\n if item == '产品':\n return 1\n return 0\n\n\nspark = SparkSession.builder.master(\"yarn\").appName(\"dim_product\").enableHiveSupport().getOrCreate()\n\n\nget_phone_number = spark.udf.register(\"get_phone_number\", get_number)\nget_shelf_life = spark.udf.register(\"get_shelf_life\", get_shelf_life)\nconvert_material = spark.udf.register(\"convert_material\", convert_material)\n\n\nsql_ods_oitm = \"\"\"\nselect ItemCode,ItemName,a8,MsrUnit,warranty,Stuff,ItemLive,Cancel from rbu_sxcp_ods_dev.ods_oitm\n\"\"\"\ndf_ods_oitm = spark.sql(sql_ods_oitm)\ndf_ods_oitm.createOrReplaceTempView(\"tmp_ods_oitm_spark\")\n\n\nfinal_sql = \"\"\"\nselect \ndistinct a.itemcode product_code,\na.ItemName product_name,\na.a8 large_class,\na.MsrUnit unit,\nget_phone_number(a.warranty) warranty,\nget_shelf_life(get_phone_number(a.warranty)) shelf_life,\nconvert_material(a.Stuff) is_material,\n1 is_valid,\na.ItemLive min_order_qty\nfrom tmp_ods_oitm_spark a \nwhere a.cancel='0' and a.itemcode is not null and a.ItemName is not null\n\"\"\"\ndf_final = spark.sql(final_sql)\ndf_final = df_final.dropDuplicates()\ndf_final.createOrReplaceTempView(\"final\")\n\nprint(\"starting..........\")\ninsert_sql = \"\"\"\ninsert overwrite table rbu_sxcp_edw_dev.dim_product\n(select \nproduct_code,\nproduct_name,\nlarge_class,\nNULL,\nNULL,\nunit,\nwarranty,\nshelf_life,\nis_material,\nis_valid,\nmin_order_qty,\nNULL,\nNULL,\nNULL,\ncurrent_timestamp()\nfrom final)\n\"\"\"\nspark.sql(insert_sql)\nprint(\"插入数据成功\")\ndf_ods_oitm.drop()\nprint(\"删除临时表成功\")\nprint(\"process successfully!\")\nprint(\"=====================\")","sub_path":"sxcp/edw/dim_product.py","file_name":"dim_product.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"227544749","text":"#! /usr/bin/env python3\n\nimport math\n\ndef main():\n sphere = Sphere(1, (0, 0))\n cone = Cone(sphere.radius*math.sqrt(2), 4*sphere.radius)\n print('the radius of the sphere is %s and the radius of the cone is %s' % (sphere.radius, cone.radius))\n\n while True:\n new_radius = float(input('''Enter the radius of the cone or '0' to exit: '''))\n if new_radius == 0:\n break\n while new_radius <= sphere.radius:\n new_radius = float(input('''Radius of cone must be larger than radius of sphere. Enter the radius of the cone or '0' to exit: '''))\n if new_radius == 0:\n break\n if new_radius == 0:\n break\n cone_2 = Cone(new_radius, cone_generator(sphere, new_radius)[1])\n print(cone_generator(sphere, new_radius), 'volume of cone is %s and volume of sphere is %s' % (cone_2.volume(), sphere.volume()))\n\nclass Sphere(object):\n def __init__(self, radius, center_point):\n self.radius = radius\n self.center_point = center_point\n def volume(self):\n return 4/3 * math.pi * self.radius**3\n\nclass Cone(object):\n def __init__(self, radius, height):\n self.radius = radius\n self.height = height\n def volume(self):\n return 1/3 * math.pi * self.radius**2 * self.height\n\ndef cone_generator(sphere, radius):\n new_height = (2*radius**2 * sphere.radius)/(radius**2 - 1) \n new_volume = math.pi * radius**2 * new_height\n return (radius, new_height)\n\nclass Transformer(object):\n def __init__(self, multiplier):\n self.multiplier = multiplier\n def stretch_radius(self, cone):\n new_radius = cone.radius * self.multiplier\n new_height = new_radius + new_radius + (2*new_radius)/(self.multiplier**2 - 1)\n return (new_radius, new_height)\n\nmain()\n","sub_path":"python/math_problems/sphere_cone.py","file_name":"sphere_cone.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"133973637","text":"# coding:utf8\n__author__ = 'bluesli'\n\n#读数据使用picke,只有python里面有,json什么语言都支持\n# 但是pickle支持的序列化有很多\n# import pickle\n# f = open(\"user_acc.txt\",'rb') #也必须要用二进制方式来读才行\n#\n# data_from_atm = pickle.loads(f.read()) 实现相同国能的有pickle.load(f)\n#\n# for i in data_from_atm:\n# print(i)\n\n\n# 使用json\n\nimport json\nf = open(\"user_acc.txt\",'r') #也必须要用二进制方式来读才行\n\ndata_from_atm = json.loads(f.read())\n\nfor i in data_from_atm:\n print(i)\n","sub_path":"day5/picle用于序列化个人.py","file_name":"picle用于序列化个人.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"319748387","text":"tableData = [['apples', 'oranges', 'cherries', 'banana'],\n ['Alice', 'Bob', 'Carol', 'David'],\n ['dogs', 'cats', 'moose', 'goose']]\n\ndef printTable(tablevals):\n i = 0 # integer to store length of longest string in our list of lists\n a = 0 # integer to store the longest list\n\n for items in tablevals: # get the length of the longest list\n if len(items) > a:\n a = len(items)\n\n for item in items: # get the length of the longest string in our lists\n if len(item) > i:\n i = len(item)\n\n # go through the list of lists and print all the first items on one line, second items on next line, etc\n for y in range(a):\n for x in range(len(tablevals)):\n if x == len(tablevals)-1:\n print(tablevals[x][y].rjust(i))\n else:\n print(tablevals[x][y].rjust(i), end='')\n\nprintTable(tableData)\n","sub_path":"Ch 6 - Strings/printTable.py","file_name":"printTable.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"138266682","text":"planets = ['Mercury', 'Venus', 'Earth', 'Mars',\n 'Jupiter', 'Saturn', 'Uranus', 'Neptune']\n\nname_file = open('planets.txt', 'w', encoding='utf-8')\n\n# write the names on separate lines\nfor planet in planets:\n name_file.write(planet + '\\n')\n\nname_file.close()","sub_path":"Problems/Solar system/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"343950429","text":"import os\nimport numpy as np\nimport torch\nimport torchvision.transforms as transforms\nfrom utils.dataset_cub import CUBCamDataset, get_image_name\nimport cv2\n\ndef load_image_size(dataset_path='datalist'):\n\n image_sizes = {}\n with open(os.path.join(dataset_path, 'sizes.txt')) as f:\n for each_line in f:\n file_info = each_line.strip().split()\n image_id = int(file_info[0])\n image_width, image_height = map(float, file_info[1:])\n\n image_sizes[image_id] = [image_width, image_height]\n return image_sizes\ndef load_bbox_size(dataset_path='datalist',\n resize_size=256, crop_size=224):\n origin_bbox = {}\n image_sizes = {}\n resized_bbox = {}\n with open(os.path.join(dataset_path, 'bounding_boxes.txt')) as f:\n for each_line in f:\n file_info = each_line.strip().split()\n image_id = int(file_info[0])\n\n x, y, bbox_width, bbox_height = map(float, file_info[1:])\n\n origin_bbox[image_id] = [x, y, bbox_width, bbox_height]\n\n with open(os.path.join(dataset_path, 'sizes.txt')) as f:\n for each_line in f:\n file_info = each_line.strip().split()\n image_id = int(file_info[0])\n image_width, image_height = map(float, file_info[1:])\n\n image_sizes[image_id] = [image_width, image_height]\n\n resize_size = float(resize_size-1)\n shift_size = (resize_size - crop_size) // 2\n for i in origin_bbox.keys():\n x, y, bbox_width, bbox_height = origin_bbox[i]\n image_width, image_height = image_sizes[i]\n left_bottom_x = x / image_width * resize_size - shift_size\n left_bottom_y = y / image_height * resize_size - shift_size\n\n right_top_x = (x+bbox_width) / image_width * resize_size - shift_size\n right_top_y = (y+bbox_height) / image_height * resize_size - shift_size\n resized_bbox[i] = [left_bottom_x, left_bottom_y, right_top_x, right_top_y]\n\n\n return resized_bbox\n\ndef see_originial_bouding_box(dataset_path='datalist'):\n cls_img_path = {}\n image_sizes = {}\n origin_bbox = {}\n with open(os.path.join(dataset_path, 'val.txt')) as f:\n for each_line in f:\n file_info = each_line.strip().split()\n file_name = file_info[1]\n file_id = int(file_info[0])\n cls_img_path[file_id] = file_name\n with open(os.path.join(dataset_path, 'sizes.txt')) as f:\n for each_line in f:\n file_info = each_line.strip().split()\n image_id = int(file_info[0])\n image_width, image_height = map(float, file_info[1:])\n\n image_sizes[image_id] = [image_width, image_height]\n with open(os.path.join(dataset_path, 'bounding_boxes.txt')) as f:\n for each_line in f:\n file_info = each_line.strip().split()\n image_id = int(file_info[0])\n\n x, y, bbox_width, bbox_height = map(float, file_info[1:])\n\n origin_bbox[image_id] = [int(x), int(y), int(bbox_width), int(bbox_height)]\n\n for i in sorted(cls_img_path.keys()):\n gxa = origin_bbox[i][0]\n gya = origin_bbox[i][1]\n gxb = origin_bbox[i][0] + origin_bbox[i][2]\n gyb = origin_bbox[i][1] + origin_bbox[i][3]\n image = cv2.imread(os.path.join(dataset_path,'images/',cls_img_path[i]), cv2.IMREAD_COLOR)\n cv2.rectangle(image, (gxa,gya), (gxb, gyb), (0, 0, 255), 2)\n file_name = cls_img_path[i].strip().split('/')[1]\n\n height, width, channel = image.shape\n # print(width == image_sizes[i][0], height == image_sizes[i][1])\n # print(i, height, image_sizes[i][0], width, image_sizes[i][1])\n\n # cv2.imwrite('./result_BBOX/{}'.format(file_name), image)\ndef see_transformed_bounding_box(dataset_path='/workspace/TPAMI2019/CUB_200_2011/CUB_200_2011'):\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n transforms_test = transforms.Compose([\n transforms.Resize((256, 256)),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ])\n\n testset = CUBCamDataset(dataset_path, 'val.txt', transforms=transforms_test)\n val_loader = torch.utils.data.DataLoader(testset, batch_size=32, shuffle=False, num_workers=4)\n name= 0\n bbox = load_bbox_size()\n image_names = get_image_name(dataset_path, 'val.txt')\n\n for i, (images, target, images_id) in enumerate(val_loader):\n images = ((images * 0.22 + 0.45) * 255.0).cpu().detach().numpy().transpose([0, 2, 3, 1])[..., ::-1]\n images = images - np.min(images)\n images = images / np.max(images) * 255.0\n\n for j in range(target.size(0)):\n\n image = images[j]\n image_id = images_id[j].item()\n gxa = int(bbox[image_id][0])\n gya = int(bbox[image_id][1])\n gxb = int(bbox[image_id][2])\n gyb = int(bbox[image_id][3])\n # print(gxa, gya, gxb, gyb)\n # print('hello')\n image = cv2.rectangle(image, (gxa,gya), (gxb, gyb), (0, 0, 255), 2)\n # cv2.imwrite('./result_resized/{}'.format(str(name)+'.jpg'), image)\n cv2.imwrite('./result_resized/'+image_names[image_id].split('/')[1], image)\n name += 1\n\ndef main():\n\n see_transformed_bounding_box()\n # see_originial_bouding_box()\n #\n # for i in bbox.keys():\n # print(bbox[i])\n\nif __name__ == '__main__':\n main()\n","sub_path":"Pytorch/utils/util_bbox.py","file_name":"util_bbox.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"534076589","text":"import plotly.io as pio\nfrom urllib.request import urlopen\nimport json\nfrom sqlalchemy import create_engine\nimport psycopg2\nimport plotly.express as px\nimport pandas as pd\nimport sys\ndef main():\n # df = pd.read_csv(\"/home/acc/twitter.csv\")\n df = pd.read_csv(sys.stdin)\n df.to_csv(\"/home/acc/output/last.csv\")\n df = df.drop(0)\n df.columns = [\"full_name\", \"time\", \"text\", \"lat\", \"lon\", \"sentiment\"]\n df['sentiment'] = (df['sentiment'] - 5)/10\n df = df.dropna()\n # transform\n df.lat = df.lat.astype('float')\n df.lon = df.lon.astype('float')\n # aggregate\n DF = df.groupby('full_name').mean()\n DF['n'] = df.groupby('full_name').count()['sentiment'].values\n DF = df.groupby('full_name').mean()\n DF['n'] = df.groupby('full_name').count()['sentiment'].values\n DF = DF.sort_values('n', ascending = False).reset_index()\n # filter out small towns\n # DF = DF[DF['n'] > thresh]\n # plot aggregates\n fig = px.scatter_mapbox(DF, lat=\"lat\", lon=\"lon\", hover_data=[\"full_name\"], mapbox_style=\"carto-positron\", color=\"sentiment\", size = \"n\", zoom = 3.5, opacity = .5)\n pio.write_json(fig, '/home/acc/output/tweet1.plotly')\n # plot individual data\n fig = px.scatter_mapbox(df, lat=\"lat\", lon=\"lon\", hover_data=[\"text\", \"full_name\", \"sentiment\"], mapbox_style=\"carto-positron\", color=\"sentiment\", zoom = 3.5, opacity = .5)\n pio.write_json(fig, '/home/acc/output/tweet2.plotly')\nif __name__ == \"__main__\":\n main()","sub_path":"NiFi/src/Twitter/twitterplot.py","file_name":"twitterplot.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"466268481","text":"import sys\n\ndef write_results(outlines,nogop,outputfile):\n\twith open(outputfile,'w') as wf:\n\t\twf.write('#nogop,cost,utterance,perspective,locSam, locLucy, moveLucyNoho, moveSamNoho, moveThelmaNoho,prob\\n')\n\t\tfor l in outlines:\n\t\t\twf.write(','.join([nogop]+l)+'\\n')\n\treturn\n\ndef parse_world(w):\n\twpieces = w.strip('\"').strip(',').strip('{').strip('}').split(',')\n\twanswers = [x.split(':')[1].strip('\"') for x in wpieces]\n\treturn(wanswers)\n\ndef main():\n\tif len(sys.argv) < 4:\n\t\tprint(\"Usage: python parse_results inputfile nogop outputfile\")\n\t\treturn\n\t#world property order: locSam, locLucy, moveLucyNoho, moveSamNoho, moveThelmaNoho\n\tdata = open(sys.argv[1],'r').readlines()\n\toutlines = []\n\tfor l in data:\n\t\tl = l.strip('\\n')\n\t\tpieces = l.split(' ')\n\t\tif pieces[0]==\"Cost:\":\n\t\t\tcost = pieces[1]\n\t\telif pieces[0]==\"Utterance:\":\n\t\t\tutterance = ' '.join(pieces[1:])\n\t\t\twanswers = parse_world(utterance)\n\t\telif pieces[0]==\"Evidence:\":\n\t\t\tevidences = ' '.join(pieces[1:]).strip('{').strip('}').split('support')\n\t\t\tprobs = evidences[0].strip('\"').strip(',').split(':')[1].strip('[').strip(']').split(',')\n\t\t\tpairs = evidences[1].strip('\"').strip(']').strip(':').strip('[').strip('{').split('},{')\n\t\t\tfor i,p in enumerate(pairs):\n\t\t\t\tpieces = p.split(\"perspective\")\n\t\t\t\tp = pieces[1].split(':')[-1].strip('}').strip('\"')\n\t\t\t\tu = pieces[0].split('utterance\":')[1].strip(',').strip('\"')\n\t\t\t\tu = u.strip(',').strip('\"')\n\t\t\t\toutlines.append([cost,u,p]+wanswers+[probs[i]])\n\t\telse:\n\t\t\tpass\n\twrite_results(outlines,sys.argv[2],sys.argv[3])\n\nmain()","sub_path":"parse_speaker_results.py","file_name":"parse_speaker_results.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"652465175","text":"import glob\nimport numpy\nimport pandas as pd\n#import matplotlib.pyplot as plt\n#import seaborn as sns\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.feature_extraction.text import (CountVectorizer, TfidfTransformer)\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import LinearSVC\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import KFold\n#from sklearn.metrics import (confusion_matrix, classification_report, accuracy_score)\n#from sklearn.calibration import (calibration_curve, CalibratedClassifierCV)\nfrom sklearn.model_selection._split import RepeatedKFold\nfrom sklearn.metrics import f1_score\n\n \n#read training set from training file \nprint('Initiated...') \ndf = pd.read_csv(\"train2.csv\", sep=\",\", encoding=\"latin-1\")\n\ndf = df.set_index('id')\ndf.columns = ['class', 'text']\n\ndata = df.reindex(numpy.random.permutation(df.index))\nprint('Training data read')\n\n#create layout for classifier\npipeline = Pipeline([\n ('count_vectorizer', CountVectorizer(ngram_range=(1, 2))),\n ('tfidf', TfidfTransformer()),\n ('classifier', OneVsRestClassifier(LinearSVC()))\n])\n\nprint('Training data...')\n#train data \nk_fold = RepeatedKFold(n_splits=6)\n#k_fold = KFold(n_splits=6, shuffle = True)\nk_fold.get_n_splits(data)\n\nscores = []\nfor train_indices, test_indices in k_fold.split(data):\n train_text = data.iloc[train_indices]['text'].values\n train_y = data.iloc[train_indices]['class'].values.astype(str)\n\n test_text = data.iloc[test_indices]['text'].values\n test_y = data.iloc[test_indices]['class'].values.astype(str)\n\n #Read test data\n files = glob.glob(\"predict.txt\")\n lines = []\n for fle in files:\n with open(fle) as f:\n lines += f.readlines() \n #test_text = numpy.array(lines)\n print('Test data read')\n #fit training data\n lb = LabelBinarizer()\n Z = lb.fit_transform(train_y)\n \n print('Classifying Test data...')\n #fit test data using results from training\n pipeline.fit(train_text, Z)\n predicted = pipeline.predict(test_text)\n predictions = lb.inverse_transform(predicted)\n\n #Try to add prediction's probability\n #clf = CalibratedClassifierCV(pipeline)\n #clf.fit(train_text, Z)\n #y_proba = clf.predict_proba(test_text)\n\n print('Writing results...')\n df2=pd.DataFrame(predictions)\n df2.index+=1\n df2.index.name='Id'\n df2.columns=['Label']\n #df2.to_csv('results.csv',header=True)\n\n for item, labels in zip(test_text, predictions):\n print('Item: {0} => Label: {1}'.format(item, labels))\n\n lb=LabelBinarizer()\n \n y = lb.fit_transform(test_y)\n score = f1_score(y, predicted)\n scores.append(score)\n\nprint('The resulting accuracy using Linear SVC is ', sum(scores)/len(scores), '%\\n')\n#print y_proba\n\"\"\"\npercentage_matrix = 100 * cm / cm.sum(axis=1).astype(float)\nplt.figure(figsize=(16, 16))\n#sns.heatmap(percentage_matrix, annot=True, fmt='.2f', xticklabels=['Java', 'Python', 'Scala'], yticklabels=['Java', 'Python', 'Scala']);\nplt.title('Confusion Matrix (Percentage)');\nplt.show()\n#print(classification_report(test_y, predictions,target_names=['Java', 'Python', 'Scala'], digits=2))\n\"\"\"","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"127393631","text":"kucuk = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\",]\n\nbuyuk = [ \"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"]\n\ndef harfsayisi(kelime):\n kucuktoplam = []\n buyuktoplam = []\n\n for i in kelime:\n if i in kucuk:\n kucuktoplam+=i\n\n elif i in buyuk:\n buyuktoplam += i\n else:\n print(\"Bosluk ve ozel karakter iceremez !\")\n\n return len(kucuktoplam),len(buyuktoplam)\n\nwhile True:\n a = input(\"Lutfen Kelimeyi Giriniz : \")\n print(\"Buyuk Ve Kucuk HArf Sayisi : \",harfsayisi(a),\"\\n\")\n","sub_path":"9 - Buyuk Kucuk HArf.py","file_name":"9 - Buyuk Kucuk HArf.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"636967506","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\n'''def location(image):\n\n #gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n #ksize :表示卷积核的大小\n #dst1 = cv2.blur(image,(5, 5))\n #cv2.imshow(\"blur_demo\",dst1)\n dst2 = cv2.medianBlur(image, 5)\n cv2.imshow(\"median_demo\",dst2)\n dst3 = cv2.GaussianBlur(dst2,(3, 3), 0)\n cv2.imshow(\"gaussian_noise_blur\", dst3)\n\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n ret, binary = cv2.threshold(gray,235,255, cv2.THRESH_BINARY)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n dst = cv2.erode(binary, kernel=kernel)\n\n cv2.imshow(\"dst\", dst)'''\n\ndef goodpoint(img):\n kernel = np.array([[0, -1, 0],[-1, 7, -1],[0, -1, 0]], np.float32)\n dst = cv2.filter2D(img,-1, kernel=kernel)\n gray = cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n ret, binary = cv2.threshold(gray,220,255, cv2.THRESH_BINARY)\n dst = cv2.dilate(binary, kernel=kernel)\n cv2.imshow(\"dst1\", dst)\n l, contours1, hst1 = cv2.findContours(gray, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n cv2.imshow(\"i\",l)\n corners = cv2.goodFeaturesToTrack(l,400,0.5,5)\n # 返回的结果是 [[ 311., 250.]] 两层括号的数组。\n corners = np.int0(corners)\n for i in corners:\n x,y = i.ravel()\n img = cv2.circle(img,(x,y),3,255,-1)\n cv2.imshow(\"img\", img)\n\ndef stft(img1, img2):\n\n gray1= cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)\n sift1 = cv2.xfeatures2d.SIFT_create()\n kp1 = sift1.detect(gray1,None)\n print(kp1)\n #im12 = img1.copy\n img1=cv2.drawKeypoints(gray1,kp1, outImage=np.array([]), color = (0, 0, 255))\n #cv2.imwrite('sift_keypoints.jpg',img)\n cv2.imshow(\"img\", img1)\n gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n sift2 = cv2.xfeatures2d.SIFT_create()\n kp2 = sift2.detect(gray2,None)\n print(kp2)\n #img2 = img2.copy\n img2=cv2.drawKeypoints(gray2,kp2, outImage=np.array([]), color = (0, 0, 255))\n #cv2.imwrite('sift_keypoints.jpg',img)\n cv2.imshow(\"img2\", img2)\n #sift1 = np.int(sift1)\n #sift2 = np.int(sift2)\n\n kp1, des1 = sift1.detectAndCompute(img1,None)\n kp2, des2 = sift2.detectAndCompute(img2,None)\n\n bf = cv2.BFMatcher()\n matches = bf.knnMatch(des1,des2, k=2)\n # Apply ratio test\n # 比值测试,首先获取与 A 距离最近的点 B(最近)和 C(次近),只有当 B/C\n # 小于阈值时(0.75)才被认为是匹配,因为假设匹配是一一对应的,真正的匹配的理想距离为 0\n good = []\n for m,n in matches:\n if m.distance < 0.75*n.distance:\n good.append([m])\n # cv2.drawMatchesKnn expects list of lists as matches.\n # img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good[:10],flags=2)\n img4 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, good[:10], outImg=None, flags=2)\n plt.imshow(img4),plt.show()\n\n\ndef surf(img):\n gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n sift = cv2.xfeatures2d.SURF_create()\n kp = sift.detect(gray,None)\n print(kp)\n img2 = img.copy\n img=cv2.drawKeypoints(gray,kp, outImage=np.array([]), color = (0, 0, 255))\n #cv2.imwrite('sift_keypoints.jpg',img)\n cv2.imshow(\"img\", img)\n\ndef kvze(img):\n gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n kaze = cv2.KAZE_create()\n kp = kaze.detect(gray,None)\n print(kp)\n img2 = img.copy\n img=cv2.drawKeypoints(gray,kp, outImage=np.array([]), color = (0, 0, 255))\n #cv2.imwrite('sift_keypoints.jpg',img)\n cv2.imshow(\"img\", img)\n\ndef harris(image):\n dst = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n dse = np.float32(dst)\n #blocksize表示窗口大小ksize表示所贝尔算子求导得到的矩阵m之后进行打分得到r自由参数k表示det(m) - k(trance(m))返回是一个打完分的灰度图像\n dst2 = cv2.cornerHarris(dse, 3,3, 0.04)\n cv2.imshow(\"dst2\", dst2)\n dst2 = cv2.dilate(dst2,None)\n\n image[dst2>0.01*dst2.max()]=[0,255,255]\n cv2.imshow(\"imae2\", image)\n #ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst2)\n # print(ret,labels,stats,centroids)\n\ndef no(image1, image2):\n image1_gary = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)\n image2_gary = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)\n cv2.imshow(\"image1_gary\", image1_gary)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n ret1, binary1= cv2.threshold(image1_gary,220,255, cv2.THRESH_BINARY)\n dst1 = cv2.dilate(binary1, kernel=kernel)\n cv2.imshow(\"dst1\", dst1)\n ret2, binary2 = cv2.threshold(image2_gary,220,255, cv2.THRESH_BINARY)\n dst2 = cv2.dilate(binary2, kernel=kernel)\n cv2.imshow(\"dst2\", dst2)\n\n #ret, binary = cv2.threshold(image1_gary,127,255,cv2.THRESH_BINARY)\n l, contours1, hst1 = cv2.findContours(binary1, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n l, contours2, hst2 = cv2.findContours(binary2, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n\n img1 = cv2.drawContours(dst1,contours1,0,(0,0,255),1)\n cv2.imshow(\"image1_gary\", img1)\n\n #contours2, hst2 = cv2.findContours(img1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n #print(contours2)\n\n Min_Area = 800#除去小矩形\n Max_Area = 10000\n contours1 = [cnt for cnt in contours1 if cv2.contourArea(cnt) > Min_Area and cv2.contourArea(cnt) 0.99 and wh_ratio <=1.0:\n\n image_contours.append(rect)\n\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n\n oldimg = cv2.drawContours(image1, [box], 0, (0, 255, 255), 2)\n\n cv2.imshow(\"edge4\", oldimg)\n #print(rect)\n # print(rect[0])\n #print(cnt)\n #print(box)\n contours2 = [cnt for cnt in contours2 if cv2.contourArea(cnt) > Min_Area and cv2.contourArea(cnt) 0.99 and wh_ratio <=1.0:\n\n image_contours.append(rect)\n\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n\n oldimg = cv2.drawContours(image2, [box], 0, (0, 255, 255), 2)\n\n cv2.imshow(\"edge5\", oldimg)\n #print(rect)\n print(rect[0])\n # print(cnt)\n # print(box)\n\n\n#def fast(img):\n\n\nimage1= cv2.imread(\"Try_1.jpg\")\ncv2.imshow(\"image1\",image1)\nimage2= cv2.imread(\"image_qrcode02.png\")\n#cv2.imshow(\"image_qrcode02\", image2)\nprint(image1.dtype)\nprint(image2.dtype)\nprint(image1.shape)\nprint(image2.shape)\n\n\n\nno(image1, image2)\nc = cv2.waitKey()\nif c == 27:\n cv2.destroyAllWindows()\n","sub_path":"untitled1/11311的尝试.py.py","file_name":"11311的尝试.py.py","file_ext":"py","file_size_in_byte":7386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"533505566","text":"\"\"\"\r\n 出拳id 出拳名字\r\n 1 石头\r\n 2 剪刀\r\n\"\"\"\r\n\"\"\"\r\n猜拳:1石头 2剪刀 3布\r\n\r\n玩家: (1)选角色(喜羊羊,美羊羊 懒羊羊)\r\n (2)出拳\r\n计算机:(1)选角色(慢羊羊,沸羊羊,暖羊羊)\r\n (2)出拳\r\n\r\n比较大小\r\n输出谁赢了\r\n\r\n\r\n---------\r\n再来一局\r\n加比分\r\n\r\n如果退出不玩了,显示最后的比分\r\n\"\"\"\r\nimport random\r\nclass Computer:\r\n def __init__(self):\r\n self.id=None\r\n self.name=None\r\n self.fingerid=None\r\n self.finger=None\r\n self.score=0\r\n def chooserole(self):\r\n names=[\"沸羊羊\",\"慢羊羊\",\"软绵绵\"]\r\n print(\"计算机正在从【1沸羊羊,2慢羊羊,3软绵绵】中选中角色:\")\r\n self.id=random.randint(1,3)\r\n self.name=names[self.id-1]\r\n print(\"计算机已选角色:【{}】\".format(self.name))\r\n\r\n def showfinger(self):\r\n fingers = [\"石头\", \"剪刀\", \"布\"]\r\n print(\"计算机正在出拳:\")\r\n self.fingerid = random.randint(1, 3)\r\n self.finger = fingers[self.fingerid - 1]\r\n print(\"计算机出拳:【{}】\".format(self.finger))\r\n\r\nclass Player:\r\n def __init__(self):\r\n self.id=None\r\n self.name=None\r\n self.fingerid=None\r\n self.finger=None\r\n self.score = 0\r\n def chooserole(self):\r\n names = [\"喜羊羊\", \"懒羊羊\", \"美羊羊\"]\r\n while True:\r\n id=int(input(\"请从以下角色中【1喜羊羊,2懒羊羊,3美羊羊】选取一个角色:\"))\r\n if 1<=id<=3:\r\n self.id=id\r\n self.name=names[id-1]\r\n break\r\n else:\r\n print(\"所选角色有误,请重新选择\")\r\n print(\"您已经选取了{}角色\".format(self.name))\r\n\r\n def showfinger(self):\r\n fingers=[\"石头\",\"剪刀\",\"布\"]\r\n while True:\r\n finger_id=int(input(\"请出拳【1石头,2剪刀,3布】\"))\r\n if 1<=finger_id<=3:\r\n self.fingerid=finger_id\r\n self.finger=fingers[finger_id-1]\r\n break\r\n else:\r\n print(\"出拳错误,请重新出拳\")\r\n print(\"您已经出了{}\".format(self.finger))\r\n\r\nclass Game:\r\n def __init__(self):\r\n self.drawtimes=0\r\n self.player=None\r\n self.computer=None\r\n def init(self):\r\n info =\"\"\"\r\n **************************************\r\n *******欢迎来到羊村游戏大世界***********\r\n **************************************\r\n \"\"\"\r\n print(info)\r\n def gamestart(self):\r\n choose=input(\"您已经进入羊村游戏大世界,是否要开始游戏,y/n\")\r\n\r\n return choose\r\n\r\n def compare(self,player,computer):\r\n self.player=player\r\n self.computer=computer\r\n restart=\"y\"\r\n while restart==\"y\":\r\n player.showfinger()\r\n computer.showfinger()\r\n # 1 石头, 2 剪刀, 3 布\r\n if player.fingerid==computer.fingerid:\r\n print(\"这是平局\")\r\n self.drawtimes+=1\r\n elif player.fingerid ==1 and computer.fingerid==3 or \\\r\n player.fingerid==2 and computer.fingerid==1 or\\\r\n player.fingerid==3 and computer.fingerid==2:\r\n print(\"这一局计算机【{}】赢了\".format(computer.name))\r\n computer.score+=1\r\n else:\r\n print(\"这一局您【{}】赢了\".format(player.name))\r\n player.score+=1\r\n\r\n restart=input(\"您是否要重来一局? y/n\")\r\n return restart\r\n\r\n def resultRecored(self):\r\n print(\"游戏结束,结果如下:\")\r\n print(\"平局的次数:{}\".format(self.drawtimes))\r\n print(\"计算机【{}】的分数是【{}】,您【{}】的分数是【{}】\".format(self.computer.name,self.computer.score,self.player.name,self.player.score))\r\n\r\nif __name__==\"__main__\":\r\n g=Game()\r\n g.init()\r\n start=g.gamestart()\r\n if start==\"y\":\r\n p=Player()\r\n c=Computer()\r\n p.chooserole()\r\n c.chooserole()\r\n restart=g.compare(p,c)\r\n if restart==\"n\":\r\n g.resultRecored()\r\n","sub_path":"code/day10/games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":4288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"408535122","text":"#!/usr/bin/python\n\nimport multiprocessing\nfrom multiprocessing import Queue\nimport os\nimport time\nimport re\nimport csv\n\ntimeQ=Queue()\nq=Queue()\n\ndef create_VCH(cmd,ts):\n vchInfo =[]\n #print(\"cmd : \", cmd)\n vch=re.search('-H (.+?) --tls',cmd)\n vch = vch.group(1)\n vchInfo.append(ts)\n #vchInfo.append(vch)\n\n start_time=time.time()\n outpu=str(os.system(cmd))\n if \"cannot\" in outpu:\n #print(output)\n elapsed_time=0.000\n else:\n elapsed_time=time.time() - start_time\n \n #print(elapsed_time)\n vchInfo.append(elapsed_time)\n #print (\" ----%s seconds -----\" % elapsed_time)\n q.put(vchInfo)\n timeQ.put(elapsed_time)\n\nnum_lines = sum(1 for line in open('dockerInfo.txt'))\n\nwith open('dockerInfo.txt') as f:\n commands = [line.rstrip('\\n') for line in f]\n #print(commands)\n\nprocs = []\n\n\ntime_stamp=time.time()\nfor command in commands:\n proc = multiprocessing.Process(target=create_VCH,args=(command,time_stamp,))\n procs.append(proc)\n proc.start()\n\nfor proc in procs:\n proc.join()\n\n\n\n'''\nvch_time = []\n\nwhile not q.empty():\n #print(q.get())\n vch_time.append(q.get())\n\nprint(vch_time)\n\nfname= 'time_vch.csv'\nif os.path.isfile(fname):\n with open(fname,'a') as wfile:\n writer = csv.writer(wfile)\n writer.writerows(vch_time)\nelse:\n with open(fname,'w') as wfile:\n writer = csv.writer(wfile)\n writer.writerows(vch_time)\n'''\n\n\n\n'''\nt=0.000\nsum_time=0.0000\nwhile not timeQ.empty():\n t=float(timeQ.get())\n print(t)\n if t==0.000:\n num_lines=num_lines-1\n sum_time = sum_time + (t)\n\nprint (sum_time/num_lines) \n'''\n\n\nwhile not q.empty():\n print(q.get())\n\n\n'''\nfile_name='vchCreation.csv'\n\nif os.path.isfile(fname):\n with open(fname,'a') as wfile:\n writer = csv.writer(wfile)\n writer.writerows(vch_time)\nelse:\n with open(fname,'w') as wfile:\n writer = csv.writer(wfile)\n writer.writerows(vch_time)\n'''\n","sub_path":"Pipeline/Master/execVCH.py","file_name":"execVCH.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"382604787","text":"# #Matrix 1 input\n# N = int(input(\"Enter the number of rows in square matrix:\"))\n \n# # Initialize matrix\n# a = []\n# print(\"Enter the entries rowwise of matrix 1:\")\n\n# for i in range(N): # A for loop for row entries\n# row1 = input().split(\" \")\n# row1 = list(map(int,row1))\n# a.append(row1)\n\n# #Matrix 2 input\n# b = []\n# print(\"Enter the entries rowwise of matrix 2:\")\n\n# for i in range(N): # B for loop for row entries\n# row2 = input().split(\" \")\n# row2 = list(map(int,row2))\n# b.append(row1)\n\nimport numpy as np\n\nN1 = int(input(\"Enter Number of Rows of Mat1: \"))\nN2 = int(input(\"Enter Number of Columns of Mat1: \"))\nN3 = int(input(\"Enter Number of Columns of Mat2: \"))\n\na = np.random.randint(low = 0,high = 20,size = (N1, N2))\nb = np.random.randint(low = 0,high = 20,size = (N2, N3))\n\nres_np = np.matmul(a, b)\n\nres = np.zeros((N1, N3))\n# a = [[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], [3, 2, 1, 0]]\n# b = [[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], [3, 2, 1, 0]]\n\nmem1 = [0] * 4096\nmem2 = [0] * 4096\nmem3 = [0] * 4096\nmem4 = [0] * 4096\nif (max(N1,N2,N3)==N1):\n if (N1%2 == 0):\n N = N1\n else:\n N = N1+1\nif (max(N1,N2,N3) == N2):\n if (N2%2 == 0):\n N = N2\n else:\n N = N2+1\nif (max(N1,N2,N3) == N3):\n if (N3%2 == 0):\n N = N3\n else:\n N = N3+1\n \nii = 0\njj = N\nkk = 2 * N\n\nn_start_bit = 4091\nmem1[n_start_bit] = N\nmem2[n_start_bit] = N\nmem3[n_start_bit] = N\nmem4[n_start_bit] = N\n\nfor i in range(ii, jj):\n for k in range(kk, 3 * N):\n\n loc1 = bin(i)[2:]\n sixloc1 = (6 - len(loc1)) * '0' + loc1\n\n loc2 = bin(k)[2:]\n sixloc2 = (6 - len(loc2)) * '0' + loc2\n\n twelveloc = sixloc1 + sixloc2\n\n decimal_loc = int(twelveloc, 2)\n\n # print(decimal_loc, a[i][k % N])\n try:\n mem1[decimal_loc] = a[i][k % N]\n mem2[decimal_loc] = a[i][k % N]\n mem3[decimal_loc] = a[i][k % N]\n mem4[decimal_loc] = a[i][k % N]\n except IndexError:\n mem1[decimal_loc] = 0\n mem2[decimal_loc] = 0\n mem3[decimal_loc] = 0\n mem4[decimal_loc] = 0\n\n#ik\nfor k in range(kk, 3 * N):\n for j in range(jj, kk):\n\n loc1 = bin(k)[2:]\n sixloc1 = (6 - len(loc1)) * '0' + loc1\n\n loc2 = bin(j)[2:]\n sixloc2 = (6 - len(loc2)) * '0' + loc2\n\n twelveloc = sixloc1 + sixloc2\n\n decimal_loc = int(twelveloc, 2)\n\n # print(decimal_loc, b[k % N][j % N])\n try:\n mem1[decimal_loc] = b[k % N][j % N]\n mem2[decimal_loc] = b[k % N][j % N]\n mem3[decimal_loc] = b[k % N][j % N]\n mem4[decimal_loc] = b[k % N][j % N]\n except IndexError:\n mem1[decimal_loc] = 0\n mem2[decimal_loc] = 0\n mem3[decimal_loc] = 0\n mem4[decimal_loc] = 0\n\nwith open('mat_core1.txt', 'w') as file:\n for i in mem1:\n i_s = str(bin(int(i)))[2:]\n zeros = \"0\" * (12-len(str(i_s)))\n file.write(zeros+str(i_s)+'\\n')\n # print(i)\n # print(str(i)+'\\n')\n\nwith open('mat_core2.txt', 'w') as file:\n for i in mem2:\n i_s = str(bin(int(i)))[2:]\n zeros = \"0\" * (12-len(str(i_s)))\n file.write(zeros+str(i_s)+'\\n')\n # print(i)\n # print(str(i)+'\\n')\n\nwith open('mat_core3.txt', 'w') as file:\n for i in mem3:\n i_s = str(bin(int(i)))[2:]\n zeros = \"0\" * (12-len(str(i_s)))\n file.write(zeros+str(i_s)+'\\n')\n # print(i)\n # print(str(i)+'\\n')\n\nwith open('mat_core4.txt', 'w') as file:\n for i in mem4:\n i_s = str(bin(int(i)))[2:]\n zeros = \"0\" * (12-len(str(i_s)))\n file.write(zeros+str(i_s)+'\\n')\n # print(i)\n # print(str(i)+'\\n')\n\n#result indices finding\naddr_mem = [0]*512\naddr_i = 0;\nfor i in range(ii, jj):\n for j in range(jj, 2 * N):\n\n loc1 = bin(i)[2:]\n sixloc1 = (6 - len(loc1)) * '0' + loc1\n\n loc2 = bin(j)[2:]\n sixloc2 = (6 - len(loc2)) * '0' + loc2\n\n twelveloc = sixloc1 + sixloc2\n\n decimal_loc = int(twelveloc, 2)\n\n print(decimal_loc)\n addr_mem[addr_i] = decimal_loc\n addr_i += 1\nprint(addr_mem)\n\nwith open('addr_mem.txt', 'w') as file:\n for i in addr_mem:\n i_s = str(bin(int(i)))[2:]\n zeros = \"0\" * (12-len(str(i_s)))\n file.write(zeros+str(i_s)+'\\n')\n # print(i)\n # print(str(i)+'\\n')\n\n#matrix multiplication for verification\nresultant = []\n\nfor i in range(N):\n row = []\n for j in range(N):\n row.append(0)\n resultant.append(row)\n \nfor i in range(N):\n for j in range(int(N)):\n for k in range(int(N)) :\n resultant[i][j] += a[i][k] * b[k][j] \n\nprint(resultant)","sub_path":"input_and_output_python_and_other_files/python_matrix/mult_core_matrix.py","file_name":"mult_core_matrix.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"383848424","text":"import numpy as np\nimport tensorflow as tf\n\n_INITIALIZERS = {'glorot_uniform': tf.glorot_uniform_initializer(),\n 'glorot_normal': tf.glorot_normal_initializer(),\n 'orthogonal': tf.orthogonal_initializer(),\n 'lecun_normal': tf.initializers.lecun_normal(),\n 'lecum_uniform': tf.initializers.lecun_uniform(),\n 'he_normal': tf.initializers.he_normal(),\n 'he_uniform': tf.initializers.he_uniform(),\n 'constant_one': tf.constant_initializer(value=1.0),\n 'constant_zero': tf.constant_initializer(value=0.0),\n }\n\n_BIAS_INITIALIZER = tf.constant_initializer(value=0.0)\n_DEFAULT_INIT = 'he_uniform'\n_DEFAULT_NORM = 'BN'\n\ndef Linear(name, x, output_dim, bias=True, SN=False, initializer=_DEFAULT_INIT):\n if SN:\n return LinearSN(name, x, output_dim, bias=bias, initializer=initializer, power_iters=1)\n\n input_dim = x.get_shape()[1]\n\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n weights = tf.get_variable('Filters',\n shape=[input_dim, output_dim],\n initializer=_INITIALIZERS[initializer],\n trainable=True)\n\n if bias:\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n biases = tf.get_variable('Biases',\n shape=[output_dim],\n initializer=_BIAS_INITIALIZER,\n trainable=True)\n\n if bias:\n out = tf.add(tf.matmul(x, weights, name='Matmul'), biases, name='Output')\n else:\n out = tf.matmul(x, weights, name='Matmul')\n\n return out\n\ndef norm(x, axes=[1,2,3]):\n return tf.sqrt(tf.reduce_sum(tf.square(x), axis=axes, keepdims=True))\n\ndef LinearSN(name, x, output_dim, bias=True, initializer=_DEFAULT_INIT, power_iters=1):\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n def spectral_normalization(W):\n W_shape = W.shape.as_list()\n u = tf.get_variable('u',\n [1, W_shape[0]],\n initializer=tf.random_normal_initializer(),\n trainable=False)\n\n v_ = tf.matmul(u, W)\n v_hat = v_/norm(v_, [1])\n\n u_ = tf.matmul(v_hat, tf.transpose(W))\n u_hat = u_/norm(u_, [1])\n\n u_hat = tf.stop_gradient(u_hat)\n v_hat = tf.stop_gradient(v_hat)\n\n sigma = tf.reduce_sum(u_hat * tf.matmul(v_hat, tf.transpose(W)), axis=1)\n\n with tf.control_dependencies([u.assign(u_hat)]):\n W_norm = W/sigma\n\n return W_norm\n\n shape = x.get_shape().as_list()\n input_dim = shape[1]\n\n weights = tf.get_variable('Filters',\n shape=[input_dim, output_dim],\n initializer=_INITIALIZERS[initializer],\n trainable=True)\n\n biases = tf.get_variable('Biases',\n shape=[output_dim],\n initializer=_BIAS_INITIALIZER,\n trainable=True)\n\n out = tf.matmul(x, spectral_normalization(weights), name='Matmul')\n if bias: out = tf.add(out, biases, name='Output')\n\n return out\n\ndef Conv2D(name, x, output_dim, kernel_size=3, stride=1, padding='SAME', bias=True, initializer=_DEFAULT_INIT):\n shape = x.get_shape().as_list()\n input_dim = shape[1]\n\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n weights = tf.get_variable('Filters',\n shape=[kernel_size, kernel_size, input_dim, output_dim],\n initializer=_INITIALIZERS[initializer],\n trainable=True)\n if bias:\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n biases = tf.get_variable('Biases',\n shape=[output_dim],\n initializer=_BIAS_INITIALIZER,\n trainable=True)\n\n strides = [1,1,stride, stride]\n out = tf.nn.conv2d(x, weights, strides, padding, name='Conv2d', data_format='NCHW')\n\n if bias: out = tf.nn.bias_add(out, biases, data_format='NCHW')\n\n return out\n\ndef LayerNorm1d(name, x, SN=False):\n x = tf.convert_to_tensor(x)\n x_shape = x.get_shape()\n num_channels = x.get_shape().as_list()[1]\n\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n if not SN: gamma = tf.get_variable('LN.Gamma', shape=[num_channels], initializer=tf.ones_initializer(), trainable=True)\n beta = tf.get_variable('LN.Beta', shape=[num_channels], initializer=tf.zeros_initializer(), trainable=True)\n\n mean, variance = tf.nn.moments(x, [1], keep_dims=True)\n if not SN: output = tf.nn.batch_normalization(x, mean=mean, variance=variance, offset=beta, scale=gamma, variance_epsilon=1e-5)\n else: output = tf.nn.batch_normalization(x, mean=mean, variance=variance, offset=beta, scale=tf.ones([num_channels]), variance_epsilon=1e-5)\n\n return output\n\ndef Normalize(name, x, method=_DEFAULT_NORM, bn_is_training=True):\n if method == 'BN':\n num_channels = x.get_shape().as_list()[1]\n\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n weights = tf.get_variable('Gamma',\n shape=[num_channels],\n initializer=tf.ones_initializer(),\n trainable=True)\n\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n biases = tf.get_variable('Beta',\n shape=[num_channels],\n initializer=tf.zeros_initializer(),\n trainable=True)\n\n with tf.variable_scope(name.replace('meta.',''), reuse=tf.AUTO_REUSE):\n moving_mean = tf.get_variable('FBN.Moving_mean',\n shape=[num_channels],\n trainable=False,\n initializer=tf.zeros_initializer())\n moving_variance = tf.get_variable('FBN.Moving_variance',\n shape=[num_channels],\n trainable=False,\n initializer=tf.ones_initializer())\n\n def _bn_training():\n training_bn_output, mean, variance = tf.nn.fused_batch_norm(x,\n scale=weights,\n offset=biases,\n epsilon=1e-5,\n data_format='NCHW')\n momentum = 0.9\n update_moving_mean = (1.-momentum)*moving_mean + momentum*mean\n update_moving_variance = (1.-momentum)*moving_variance + momentum*variance\n\n update_ops = [moving_mean.assign(update_moving_mean), moving_variance.assign(update_moving_variance)]\n with tf.control_dependencies(update_ops):\n return tf.identity(training_bn_output)\n\n def _bn_inference():\n inference_bn_output, _, _ = tf.nn.fused_batch_norm(x,\n mean=moving_mean,\n variance=moving_variance,\n scale=weights,\n offset=biases,\n is_training=False,\n epsilon=1e-5,\n data_format='NCHW')\n return inference_bn_output\n\n output = tf.cond(bn_is_training, lambda: _bn_training(), lambda: _bn_inference())\n return output\n\n elif method == 'LN':\n x = tf.convert_to_tensor(x)\n x_shape = x.get_shape()\n num_channels = x.get_shape().as_list()[1]\n\n with tf.variable_scope(name+'.LN', reuse=tf.AUTO_REUSE):\n weights = tf.get_variable('Gamma', shape=[1,num_channels,1,1], initializer=tf.ones_initializer(), trainable=True)\n\n with tf.variable_scope(name+'.LN', reuse=tf.AUTO_REUSE):\n biases = tf.get_variable('LN.Beta', shape=[1,num_channels,1,1], initializer=tf.zeros_initializer(), trainable=True)\n\n mean, variance = tf.nn.moments(x, [1,2,3], keep_dims=True)\n output = tf.nn.batch_normalization(x, mean, variance, biases, weights, 1e-5)\n return output\n\n elif method == 'GN':\n _shape = tf.shape(x)\n N, C, H, W = _shape[0], _shape[1], _shape[2], _shape[3]\n G = tf.math.minimum(8, C)\n _C = x.get_shape()[1]\n\n output = tf.transpose(x, [0,2,3,1])\n output = tf.reshape(output, [N,H,W,G,C//G])\n mean, var = tf.nn.moments(output, [1,2,4], keep_dims=True)\n output = (output - mean) / tf.sqrt(var + 1e-5)\n\n with tf.variable_scope(name+'.GN', reuse=tf.AUTO_REUSE):\n weights = tf.get_variable('Gamma', [1,1,1,_C], initializer=tf.ones_initializer(), trainable=True)\n\n with tf.variable_scope(name+'.GN', reuse=tf.AUTO_REUSE):\n biases = tf.get_variable('Beta', [1,1,1,_C], initializer=tf.zeros_initializer(), trainable=True)\n\n return tf.transpose(tf.reshape(output, [N,H,W,C]) * weights + biases, [0,3,1,2])\n\n\ndef ResidualLayer(name, x, output_dim, kernel_size=3, stride=1, norm=_DEFAULT_NORM, is_training=None, dropout=None):\n shape = x.get_shape().as_list()\n input_dim = shape[1]\n\n output = Normalize(name+'.NORM.L1', x, norm, is_training)\n output = tf.nn.relu(output)\n\n if input_dim == output_dim and stride == 1: shortcut = x\n else: shortcut = Conv2D(name+'.shortcut', x, output_dim, 1, stride, bias=False, initializer='glorot_uniform')\n\n output = Conv2D(name+'.CONV.L1', output, output_dim, kernel_size, stride, bias=False)\n output = Normalize(name+'.NORM.L2', output, norm, is_training)\n output = tf.nn.relu(output)\n if dropout is not None: output = tf.layers.dropout(output, rate=dropout, training=is_training)\n\n output = Conv2D(name+'.CONV.L2', output, output_dim, kernel_size, bias=False)\n return shortcut + output\n","sub_path":"coco/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":9511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"74825805","text":"from sqlalchemy import and_, func\n\nfrom indexd.errors import UserError\nfrom indexd.index.drivers.alchemy import IndexRecord, IndexRecordUrlMetadataJsonb\nfrom indexd.index.drivers.query import URLsQueryDriver\n\ndriver_query_map = {\n \"sqlite\": dict(array_agg=func.group_concat, string_agg=func.group_concat),\n \"postgresql\": dict(array_agg=func.array_agg, string_agg=func.string_agg),\n}\n\n\nclass AlchemyURLsQueryDriver(URLsQueryDriver):\n \"\"\"SQLAlchemy based impl\"\"\"\n\n def __init__(self, alchemy_driver):\n \"\"\"Queries index records based on URL\n Args:\n alchemy_driver (indexd.index.drivers.alchemy.SQLAlchemyIndexDriver):\n \"\"\"\n self.driver = alchemy_driver\n\n def query_urls(\n self,\n exclude=None,\n include=None,\n versioned=None,\n exclude_deleted=False,\n offset=0,\n limit=1000,\n fields=\"did,urls\",\n **kwargs,\n ):\n \"\"\"\n Get a list of document fields matching the search parameters\n Args:\n include (str): If defined, at least one URL in a document must contain this string to be included in search.\n exclude (str): If defined, no URL in a document may contain this string to be included in search.\n versioned (bool): If None (default), search documents regardless of whether they are versioned or not. If\n True, filter only for versioned documents. If False, filter only for un-versioned documents.\n exclude_deleted (bool): If True, exclude deleted documents from search. If False, include deleted\n and not deleted documents in search.\n offset (int): Defines a position offset, the first n results to skip\n limit (int): Defines the number of results to return\n fields (str): Comma separated list (defaults to did,urls) of fields to return\n Returns:\n list (dict): matching documents with specified return fields\n \"\"\"\n if kwargs:\n raise UserError(f\"Unexpected query parameter(s) {kwargs.keys()}\")\n\n with self.driver.session as session:\n # special database specific functions dependent of the selected dialect\n q_func = driver_query_map.get(session.bind.dialect.name)\n\n query = session.query(\n IndexRecordUrlMetadataJsonb.did,\n q_func[\"string_agg\"](IndexRecordUrlMetadataJsonb.url, \",\"),\n )\n\n # handle filters for versioned and/or exclude_deleted flags\n query = self._filter_indexrecord(query, versioned, exclude_deleted)\n\n query = query.group_by(IndexRecordUrlMetadataJsonb.did)\n\n # add url filters\n if include and exclude:\n query = query.having(\n and_(\n ~q_func[\"string_agg\"](\n IndexRecordUrlMetadataJsonb.url, \",\"\n ).contains(exclude),\n q_func[\"string_agg\"](\n IndexRecordUrlMetadataJsonb.url, \",\"\n ).contains(include),\n )\n )\n elif include:\n query = query.having(\n q_func[\"string_agg\"](IndexRecordUrlMetadataJsonb.url, \",\").contains(\n include\n )\n )\n elif exclude:\n query = query.having(\n ~q_func[\"string_agg\"](\n IndexRecordUrlMetadataJsonb.url, \",\"\n ).contains(exclude)\n )\n # [(\"did\", \"urls\")]\n record_list = (\n query.order_by(IndexRecordUrlMetadataJsonb.did.asc())\n .offset(offset)\n .limit(limit)\n .all()\n )\n return self._format_response(fields, record_list)\n\n def query_metadata_by_key(\n self,\n key,\n value,\n url=None,\n versioned=None,\n exclude_deleted=False,\n offset=0,\n limit=1000,\n fields=\"did,urls,rev\",\n **kwargs,\n ):\n \"\"\"\n Get a list of document fields matching the search parameters\n Args:\n key (str): metadata key\n value (str): metadata value for key\n url (str): full url or pattern for limit to\n versioned (bool): If None (default), search documents regardless of whether they are versioned or not. If\n True, filter only for versioned documents. If False, filter only for un-versioned documents.\n exclude_deleted (bool): If True, exclude deleted documents from search. If False, include deleted\n and not deleted documents in search.\n offset (int): Defines a position offset, the first n results to skip\n limit (int): Defines the number of results to return\n fields (str): Comma separated list (defaults to did,urls) of fields to return\n Returns:\n list (dict): matching documents with specified return fields\n \"\"\"\n if kwargs:\n raise UserError(f\"Unexpected query parameter(s) {kwargs.keys()}\")\n\n with self.driver.session as session:\n query = session.query(\n IndexRecordUrlMetadataJsonb.did,\n IndexRecordUrlMetadataJsonb.url,\n IndexRecord.rev,\n )\n if key == \"type\":\n query = query.filter(\n IndexRecord.did == IndexRecordUrlMetadataJsonb.did,\n IndexRecordUrlMetadataJsonb.type == value,\n )\n elif key == \"state\":\n query = query.filter(\n IndexRecord.did == IndexRecordUrlMetadataJsonb.did,\n IndexRecordUrlMetadataJsonb.state == value,\n )\n else:\n query = query.filter(\n IndexRecord.did == IndexRecordUrlMetadataJsonb.did,\n IndexRecordUrlMetadataJsonb.urls_metadata[key].astext == value,\n )\n\n # handle filters for versioned and/or exclude_deleted flags\n query = self._filter_indexrecord(query, versioned, exclude_deleted)\n\n # add url filter\n if url:\n query = query.filter(IndexRecordUrlMetadataJsonb.url.like(f\"%{url}%\"))\n\n # [('did', 'url', 'rev')]\n record_list = (\n query.order_by(IndexRecordUrlMetadataJsonb.did.asc())\n .offset(offset)\n .limit(limit)\n .all()\n )\n return self._format_response(fields, record_list)\n\n @staticmethod\n def _filter_indexrecord(query, versioned, exclude_deleted):\n \"\"\"Handles outer join to IndexRecord for versioned and exclude_deleted filters if filter flags exist\"\"\"\n if versioned is not None or exclude_deleted:\n query = query.outerjoin(IndexRecord)\n\n # handle not deleted filter\n if exclude_deleted:\n query = query.filter(\n (\n func.lower(IndexRecord.index_metadata[\"deleted\"].astext)\n == \"true\"\n ).isnot(True)\n )\n\n # handle version filter if not None\n if versioned is True: # retrieve only those with a version number\n query = query.filter(IndexRecord.version.isnot(None))\n elif versioned is False: # retrieve only those without a version number\n query = query.filter(~IndexRecord.version.isnot(None))\n\n return query\n\n @staticmethod\n def _format_response(requested_fields, record_list):\n \"\"\"loops through the query result and removes undesired columns and converts result of urls string_agg to list\n Args:\n requested_fields (str): comma separated list of fields to return, if not specified return all fields\n record_list (list(tuple]): must be of the form [(did, urls, rev)], rev is not required for urls query\n Returns:\n list[dict]: list of response dicts\n \"\"\"\n result = []\n provided_fields_dict = {k: 1 for k in requested_fields.split(\",\")}\n for record in record_list:\n resp_dict = {}\n if provided_fields_dict.get(\"did\"):\n resp_dict[\"did\"] = record[0]\n if provided_fields_dict.get(\"urls\"):\n resp_dict[\"urls\"] = record[1].split(\",\") if record[1] else []\n\n # check if record is returned in tuple\n if provided_fields_dict.get(\"rev\") and len(record) == 3:\n resp_dict[\"rev\"] = record[2]\n result.append(resp_dict)\n return result\n","sub_path":"indexd/index/drivers/query/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":8768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"27056720","text":"#-*- encoding=utf-8 -*-\n\n'''\n'''\n\nfrom threading import Lock\n\nclass LogSys(object):\n def __init__(self):\n self.m_effLock = Lock()\n self.m_effLog = []\n\n # 输出一行信息\n def info(self, desc):\n if not desc is None:\n self.m_effLock.acquire()\n if isinstance(desc, bytes):\n try:\n desc = desc.decode(\"utf-8\")\n except:\n desc = desc.decode(\"gbk\")\n if len(desc):\n self.m_effLog.append(desc)\n self.m_effLock.release()\n\n def getlogger(self, loglist):\n self.m_effLock.acquire()\n for log in self.m_effLog:\n loglist.append(log)\n del self.m_effLog[:]\n self.m_effLock.release()\n","sub_path":"FileDirDiff/FileDirDiff/src/FileDirDiff/Core/LogSys.py","file_name":"LogSys.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"134522109","text":"#!/usr/bin/env python\n\nimport os.path\nimport subprocess\n\ndef has_ffmpeg_installed():\n try:\n subprocess.call(['ffmpeg', '-loglevel', '0'])\n return True\n except:\n return False\n\ndef ffmpeg_convert_ts_to_mkv(files, output = 'output.mkv'):\n for file in files:\n if os.path.isfile(file):\n params = ['ffmpeg', '-i']\n params.append(file)\n params.append(output)\n subprocess.call(params)\n \n return\n\ndef ffmpeg_concat_mp4_to_mpg(files, output = 'output.mpg'):\n for file in files:\n if os.path.isfile(file):\n params = ['ffmpeg', '-i']\n params.append(file)\n params.append(file + '.mpg')\n subprocess.call(params)\n \n inputs = [open(file + '.mpg', 'rb') for file in files]\n with open(output + '.mpg', 'wb') as o:\n for input in inputs:\n o.write(input.read())\n \n params = ['ffmpeg', '-i']\n params.append(output + '.mpg')\n params += ['-vcodec', 'copy', '-acodec', 'copy']\n params.append(output)\n subprocess.call(params)\n \n for file in files:\n os.remove(file + '.mpg')\n os.remove(output + '.mpg')\n \n return\n\ndef ffmpeg_concat_ts_to_mkv(files, output = 'output.mkv'):\n params = ['ffmpeg', '-isync', '-i']\n params.append('concat:')\n for file in files:\n if os.path.isfile(file):\n params[-1] += file + '|'\n params += ['-f', 'matroska', '-c', 'copy', output]\n \n try:\n if subprocess.call(params) == 0:\n return True\n else:\n return False\n except:\n return False\n","sub_path":"src/you_get/processor/ffmpeg.py","file_name":"ffmpeg.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"42377957","text":"\"\"\"Shared methods for outline and seamcarve.\"\"\"\nfrom os import path\nfrom timeit import default_timer as timer\n\nimport numpy\nfrom PIL import Image\n\nHERE = path.abspath(path.dirname(__file__))\n\nIN_NAME = path.join(HERE, \"in.jpg\")\nOUT_NAME = path.join(HERE, \"out.png\")\n\nBG_COLOR = (255, 255, 255, 254)\n\ndef get_neighbors(pixels, x, y, height, width, diagonals_on=False, flatten_and_filter=True):\n \"\"\"Get neighbors of a pixel.\"\"\"\n neighbors = [[(0, 0, 0, 0) for w in range(3)] for h in range(3)]\n # Left.\n if x > 0:\n neighbors[1][0] = pixels[(x-1, y)]\n # Right.\n if x < width-1:\n neighbors[1][2] = pixels[(x+1, y)]\n # Top.\n if y > 0:\n neighbors[0][1] = pixels[(x, y-1)]\n # Bottom.\n if y < height-1:\n neighbors[2][1] = pixels[(x, y+1)]\n\n # Diagonals.\n if diagonals_on:\n # Upper left.\n if x > 0 and y > 0:\n neighbors[0][0] = pixels[(x-1, y-1)]\n # Upper right\n if x < width-1 and y > 0:\n neighbors[0][2] = pixels[(x+1, y-1)]\n # Lower right.\n if x < width-1 and y < height-1:\n neighbors[2][2] = pixels[(x+1, y+1)]\n # Lower left.\n if x > 0 and y < height-1:\n neighbors[2][0] = pixels[(x-1, y+1)]\n\n if flatten_and_filter:\n return [item for sublist in neighbors for item in sublist if item is not None]\n\n return neighbors\n\ndef save_pixels(pixels):\n \"\"\"Save array of pixels to an RGBA image.\"\"\"\n print(\"Saving pixels to out image...\")\n start = timer()\n array = numpy.array(pixels)\n out_image = Image.fromarray(array)\n out_image.save(\"seamcarved_image.png\")\n end = timer()\n print(f\"Took {end-start} seconds.\")\n","sub_path":"image_processing/shared.py","file_name":"shared.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"426047438","text":"\"\"\"\n:copyright: (c)Copyright 2013, Intel Corporation All Rights Reserved.\nThe source code contained or described here in and all documents related\nto the source code (\"Material\") are owned by Intel Corporation or its\nsuppliers or licensors. Title to the Material remains with Intel Corporation\nor its suppliers and licensors. The Material contains trade secrets and\nproprietary and confidential information of Intel or its suppliers and\nlicensors.\n\nThe Material is protected by worldwide copyright and trade secret laws and\ntreaty provisions. No part of the Material may be used, copied, reproduced,\nmodified, published, uploaded, posted, transmitted, distributed, or disclosed\nin any way without Intel's prior express written permission.\n\nNo license under any patent, copyright, trade secret or other intellectual\nproperty right is granted to or conferred upon you by disclosure or delivery\nof the Materials, either expressly, by implication, inducement, estoppel or\notherwise. Any license under such intellectual property rights must be express\nand approved by Intel in writing.\n\n:organization: INTEL MCG PSI\n:summary: This script implements fishtank benchmark\n:since: 13/06/2013\n:author: jbourgex\n\"\"\"\nimport re\nfrom acs_test_scripts.Device.Model.AndroidDevice.Application.IBrowsing import IBrowsing\nfrom ErrorHandling.DeviceException import DeviceException\n\n\nclass Fishtank(IBrowsing):\n \"\"\"\n Fishtank benchmark implementation\n \"\"\"\n\n def __init__(self, device):\n \"\"\"\n Initializes this instance.\n\n :type device: Device\n :param device: The DUT\n \"\"\"\n IBrowsing.__init__(self, device)\n self.is_lower_better = False\n\n self._results = {\"score\": []}\n\n def wait(self, timeout):\n \"\"\"\n Wait until the end of benchmark\n\n :type timeout: integer\n :param timeout: Timeout beyond no message is triggered\n \"\"\"\n\n logger = self._get_device_logger()\n\n pattern = r\"Version RAF_2.1, Result: (?P[\\d\\.]*)\"\n logcat = logger.is_message_received(\"regex:\" + pattern, timeout)\n if logcat:\n result = re.search(pattern, logcat[0])\n self._results[\"score\"].append(float(result.group(\"score\")))\n else:\n raise DeviceException(DeviceException.TIMEOUT_REACHED,\n \"Timeout while browsing\")\n","sub_path":"ACS_v.18.20.4_1/ACS/acs_test_scripts/Device/Model/AndroidDevice/Application/Fishtank.py","file_name":"Fishtank.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"497455325","text":"# -*- coding: utf-8 -*-\nimport json\nimport os\nimport shutil\n\nfrom django.conf import settings # For mocking.\n\nimport jwt\nimport mock\nfrom nose.tools import eq_, raises\n\nimport amo.tests\nfrom lib.crypto.receipt import crack, sign, SigningError\nfrom versions.models import Version\n\n\ndef mock_sign(version_id, reviewer=False):\n \"\"\"\n This is a mock for using in tests, where we really don't want to be\n actually signing the apps. This just copies the file over and returns\n the path. It doesn't have much error checking.\n \"\"\"\n version = Version.objects.get(pk=version_id)\n file_obj = version.all_files[0]\n path = (file_obj.signed_reviewer_file_path if reviewer else\n file_obj.signed_file_path)\n try:\n os.makedirs(os.path.dirname(path))\n except OSError:\n pass\n shutil.copyfile(file_obj.file_path, path)\n return path\n\n\n@mock.patch('lib.crypto.receipt.urllib2.urlopen')\n@mock.patch.object(settings, 'SIGNING_SERVER', 'http://localhost')\nclass TestReceipt(amo.tests.TestCase):\n\n def test_called(self, urlopen):\n urlopen.return_value = self.get_response(200)\n sign('my-receipt')\n eq_(urlopen.call_args[0][0].data, 'my-receipt')\n\n def test_some_unicode(self, urlopen):\n urlopen.return_value = self.get_response(200)\n sign({'name': u'Вагиф Сәмәдоғлу'})\n\n def get_response(self, code):\n response = mock.Mock()\n response.getcode = mock.Mock()\n response.getcode.return_value = code\n response.read.return_value = json.dumps({'receipt': ''})\n return response\n\n @raises(SigningError)\n def test_error(self, urlopen):\n urlopen.return_value = self.get_response(403)\n sign('x')\n\n def test_good(self, urlopen):\n urlopen.return_value = self.get_response(200)\n sign('x')\n\n @raises(SigningError)\n def test_other(self, urlopen):\n urlopen.return_value = self.get_response(206)\n sign('x')\n\n\nclass TestCrack(amo.tests.TestCase):\n\n def test_crack(self):\n eq_(crack(jwt.encode('foo', 'x')), [u'foo'])\n\n def test_crack_mulitple(self):\n eq_(crack('~'.join([jwt.encode('foo', 'x'), jwt.encode('bar', 'y')])),\n [u'foo', u'bar'])\n","sub_path":"lib/crypto/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"653351298","text":"# # Visualization with Pandas (and Matplotlib)\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# display plots in the console\n\n# increase default figure and font sizes for easier viewing\nplt.rcParams['figure.figsize'] = (8, 6)\nplt.rcParams['font.size'] = 14\n\n\n# read in the drinks data\nfile_path_drinks = '/Users/jim_byers/Documents/GA/GA_Data_Science_course/SEA-DAT1/data/'\ndrink_cols = ['country', 'beer', 'spirit', 'wine', 'liters', 'continent']\nurl = file_path_drinks + 'drinks.csv'\ndrinks = pd.read_csv(url, header=0, names=drink_cols, na_filter=False)\n\n\n# ## Histogram: show the distribution of a numerical variable\n\n# sort the beer column and mentally split it into 3 groups\ndrinks.beer.order().values\n\n\n# compare with histogram\ndrinks.beer.plot(kind='hist', bins=3)\n\n\n# try more bins\ndrinks.beer.plot(kind='hist', bins=20)\n\n\n# add title and labels\ndrinks.beer.plot(kind='hist', bins=20, title='Histogram of Beer Servings')\nplt.xlabel('Beer Servings')\nplt.ylabel('Frequency')\n\n\n# compare with density plot (smooth version of a histogram)\ndrinks.beer.plot(kind='density', xlim=(0, 500))\n\n\n# ## Scatter Plot: show the relationship between two numerical variables\n\n# select the beer and wine columns and sort by beer\ndrinks[['beer', 'wine']].sort('beer').values\n\n\n# compare with scatter plot\ndrinks.plot(kind='scatter', x='beer', y='wine')\n\n\n# add transparency\ndrinks.plot(kind='scatter', x='beer', y='wine', alpha=0.3)\n\n\n# vary point color by spirit servings\ndrinks.plot(kind='scatter', x='beer', y='wine', c='spirit', colormap='Blues')\n\n\n# scatter matrix of three numerical columns\npd.scatter_matrix(drinks[['beer', 'spirit', 'wine']])\n\n\n# increase figure size\npd.scatter_matrix(drinks[['beer', 'spirit', 'wine']], figsize=(10, 8))\n\n\n# ## Bar Plot: show a numerical comparison across different categories\n\n# count the number of countries in each continent\ndrinks.continent.value_counts()\n\n\n# compare with bar plot\ndrinks.continent.value_counts().plot(kind='bar')\n\n\n# calculate the mean alcohol amounts for each continent\ndrinks.groupby('continent').mean()\n\n\n# side-by-side bar plots\ndrinks.groupby('continent').mean().plot(kind='bar')\n\n\n# drop the liters column\ndrinks.groupby('continent').mean().drop('liters', axis=1).plot(kind='bar')\n\n\n# stacked bar plots\ndrinks.groupby('continent').mean().drop('liters', axis=1).plot(kind='bar', stacked=True)\n\n\n### Exercise 1#: Visualize the Pronto rider age data in a histogram\n#\n# read in the Pronto data and merge the two files\n# read in the data from '2015_trip_data.csv' file into a dataframe names 'file_path' and examine the contents.\n# name the file trip_data\n#\n###\n\n## read in two files into separate dataframes\nfile_path_pronto = '/Users/reneehosogi/Documents/GitHub_Clones/GA-SEA-DAT1/data/pronto_cycle_share/'\n\ntrip_data_url = file_path_pronto + '2015_trip_data.csv'\ntrip_data = pd.read_table(trip_data_url, sep=',', header=0)\n\nstation_data_url = file_path_pronto + '2015_station_data.csv'\nstation_data = pd.read_table(station_data_url, sep=',', header=0, usecols=['name','dockcount'])\n\n## merge the two files on with left join on 'from_station_name' = 'name'\ntrip_and_dockcount_data = pd.merge(trip_data, station_data, how='left', left_on='from_station_name', right_on='name')\ndel trip_and_dockcount_data['name']\n\n## create a new column of age where age is 2015 - birthyear\ntype(trip_and_dockcount_data.birthyear[1]) # this test shows that birthyear is a float in our dataframe rather than text. So do we do not have to convert birthyear to int of float for our calculation of age\ntrip_and_dockcount_data['age'] = 2015 - trip_and_dockcount_data.birthyear\n\n\ntrip_and_dockcount_data['age'] = 2015 - trip_and_dockcount_data.birthyear\ntrip_and_dockcount_data.age\ntype(trip_and_dockcount_data.age[1]) #this test shows that the age values are floats. If we prefer we can change it it and integer.\n\n\n## Display a histogram of the number of trips by age\n\n# < your code here >\n\ntrip_and_dockcount_data.age.plot(kind='hist', bins=7)\n\n## Re-display the histogram and add title and labels\n# Title the chart \"Histogram of # of rides by age\"\n# Label the x-axis \"Age\" and the \n\n# \ntrip_and_dockcount_data.age.plot(kind='hist' , bins=7, title='Histogram of # of rides by age')\nplt.xlabel('Age')\nplt.ylabel('# of rides')\n\n# Display a density plot for comparison\ntrip_and_dockcount_data.age.plot(kind='density', title='Density plot of # of rides by age')\nplt.xlabel('Age')\nplt.ylabel('Density of rides')\n\n\n\n# ## Box Plot: show quartiles (and outliers) for one or more numerical variables\n# \n# **Five-number summary:**\n# \n# - min = minimum value\n# - 25% = first quartile (Q1) = median of the lower half of the data\n# - 50% = second quartile (Q2) = median of the data\n# - 75% = third quartile (Q3) = median of the upper half of the data\n# - max = maximum value\n# \n# (More useful than mean and standard deviation for describing skewed distributions)\n# \n# **Interquartile Range (IQR)** = Q3 - Q1\n# \n# **Outliers:**\n# \n# - below Q1 - 1.5 * IQR\n# - above Q3 + 1.5 * IQR\n\n#sort the spirit column\ndrinks.spirit.order().values\n\n\n# show \"five-number summary\" for spirit\ndrinks.spirit.describe()\n\n\n# display a box plot of spirits\ndrinks.spirit.plot(kind='box')\n\n\n# include multiple variables\ndrinks.drop('liters', axis=1).plot(kind='box')\n\n\n### Exercise 2: Display a box plot of the Pronto ride volume by age\n##\n\n#Display a box plot of age\n\n# \ntrip_and_dockcount_data.age.plot(kind='box', title='Box plot of # of rides by age')\nplt.ylabel('# of rides first Pronto year')\n\n## Bonus: State a conclusion you can make about the distribution of rider ages for the rides?\ntrip_and_dockcount_data.age.describe()\n\n# \n\n\n# One statement that we can make is that half of our rides in the first year are from riders with ages\n# between 28 and 41.\n\n\n\n\n# ## Line Plot: show the trend of a numerical variable over time\n\n# read in the ufo data\nfile_path_ufo = '/Users/jim_byers/Documents/GA/GA_Data_Science_course/SEA-DAT1/data/'\nurl = file_path_ufo + 'ufo.csv'\nufo = pd.read_csv(url)\nufo['Time'] = pd.to_datetime(ufo.Time)\nufo['Year'] = ufo.Time.dt.year\n\n\n# count the number of ufo reports each year (and sort by year)\nufo.Year.value_counts().sort_index()\n\n\n# Look at trend with a line plot\nufo.Year.value_counts().sort_index()\nufo.Year.value_counts().sort_index().plot()\nufo.Year.value_counts().sort_index().plot(kind='line')\n\n# don't use a line plot when there is no logical ordering\ndrinks.continent.value_counts().plot()\n\n\n\n### Exercise 3: Display a line plot of the Pronto ride volume by day\n###\n\ntype(trip_and_dockcount_data.starttime[1]) # note that type of starttime is string but we want datetime\n\n## Create a new column 'start_datetime' in the dataframe from_date_day that contains datetimes from the starttime str values\n\n# \ntrip_and_dockcount_data['start_datetime'] = pd.to_datetime(trip_and_dockcount_data.starttime, infer_datetime_format=True)\n\n## Display a line chart of trips by date\n# Note: the line chart will be quite noisy \n# \n\ntrip_and_dockcount_data.start_datetime.value_counts().sort_index() # Get the sort of the values working\ntrip_and_dockcount_data.start_datetime.value_counts().sort_index().plot(kind='line') # plot the values\n\n# \n\n\n## Bonus: create a line chart with the rides per month. You can use the month number for the month rather than the month name\ntrip_and_dockcount_data['month_number'] = trip_and_dockcount_data.start_datetime.dt.month\ntrip_and_dockcount_data.month_number.value_counts().sort_index() # Get the sort of the values working\n\ntrip_and_dockcount_data.month_number.value_counts().sort_index().plot(kind='line') # plot it as a line plot\n\n#plot with title and axis labels\ntrip_and_dockcount_data.month_number.value_counts().sort_index().plot(kind='line', title='Pronto rides by month number') # plot it as a line plot\nplt.xlabel('Month number')\nplt.ylabel('Number of rides')\n\n\n\n\n### Grouping in plots \n# ## Grouped Box Plots: show one box plot for each group\n\n# reminder: box plot of beer servings\ndrinks.beer.plot(kind='box')\n\n\n# box plot of beer servings grouped by continent\ndrinks.boxplot(column='beer', by='continent')\n\n\n# box plot of all numeric columns grouped by continent\ndrinks.boxplot(by='continent')\n\n\n# ## Grouped Histograms: show one histogram for each group\n\n# reminder: histogram of beer servings\ndrinks.beer.plot(kind='hist')\n\n\n# histogram of beer servings grouped by continent\ndrinks.hist(column='beer', by='continent')\n\n\n# share the x axes\ndrinks.hist(column='beer', by='continent', sharex=True)\n\n\n# share the x and y axes\ndrinks.hist(column='beer', by='continent', sharex=True, sharey=True)\n\n\n# change the layout\ndrinks.hist(column='beer', by='continent', sharex=True, layout=(2, 3))\n\n\n# ## Assorted Functionality\n\n# saving a plot to a file\ndrinks.beer.plot(kind='hist', bins=20, title='Histogram of Beer Servings')\nplt.xlabel('Beer Servings')\nplt.ylabel('Frequency')\nplt.savefig('beer_histogram.png')\n\n\n# list available plot styles\nplt.style.available\n\n\n# change to a different style\nplt.style.use('ggplot')\n\n## Exercise 4 - Display a grouped box plot of the trip_and_dockcount_data ride durations by usertype\n\n# Reminder, in Exercise 1 your line chart by day code was like this:\ntrip_and_dockcount_data.start_datetime.value_counts().sort_index().plot(kind='line') \n\n# also in exercise #3 you did something like this to change the text values of start_time to type datetime and assign it to a new column\ntrip_and_dockcount_data['start_datetime'] = pd.to_datetime(trip_and_dockcount_data.starttime, infer_datetime_format=True)\n\n# Create a new column 'trip_duration' that is stoptime - startime in minutes\n\ntrip_and_dockcount_data['trip_duration'] = pd.to_datetime(trip_and_dockcount_data.starttime, infer_datetime_format=True)\ntrip_and_dockcount_data['starttime_date'] = pd.to_datetime(trip_and_dockcount_data.starttime, infer_datetime_format=True)\ntrip_and_dockcount_data.trip_duration\n\n# Create a group box plot of the the frequency of the trip_duration values by usertype\n\ntrip_data.trip_duration.plot(kind='box')\nplt.xlabel('usertype')\n\n\n\n\n# Bonus 1: Display a box plot of duration that compares the duration box plots for each month\n\n# \n\n\n\n# Bonus 2: Write your box plot to a file\n\n# \n\n\n\n\n# Bonus 3: Write your box plot to a file with image size 700x700\n# Hint: Web search for plt.savefig and image size\n\n# \n\n\n\n\n\n","sub_path":"code/solutions/05_pandas_visualization_nb_with_part_1_answers1.py","file_name":"05_pandas_visualization_nb_with_part_1_answers1.py","file_ext":"py","file_size_in_byte":10526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"25168949","text":"from HorizonQuiz.models import Question, AccuracyQuestion\nfrom .my_unit import views_unit\nfrom django.http import JsonResponse\nfrom HorizonQuiz.my_unit import game_logic, map_model\nimport uuid\nfrom push_notifications.models import APNSDevice, GCMDevice\n\n\ndef get_enum_question(request):\n res = views_unit.user_want_question(request, views_unit.WE_GET_ENUM_QUESTION, Question)\n return JsonResponse(res)\n\n\ndef get_accuracy_question(request):\n res = views_unit.user_want_question(request, views_unit.WE_GET_ACCURACY_QUESTION, AccuracyQuestion)\n return JsonResponse(res)\n\n\ndef get_enum_answer(request, user_answer):\n res = views_unit.user_want_take_answer(request, views_unit.WE_GET_ENUM_QUESTION, int(user_answer))\n return JsonResponse(res)\n\n\ndef get_accuracy_answer(request, digit_of_answer):\n res = views_unit.user_want_take_answer(request, views_unit.WE_GET_ACCURACY_QUESTION, int(digit_of_answer))\n return JsonResponse(res)\n\n\ndef clear_all_of_user(key):\n del game_logic.enemies[key]\n del game_logic.game_ids[key]\n\n\ndef drop_old_session(request):\n key = request.session.session_key\n if game_logic.game_ids.get(key) is None:\n return False\n\n del game_logic.games[game_logic.game_ids[key]]\n enemy = game_logic.enemies[key]\n clear_all_of_user(key)\n clear_all_of_user(enemy)\n return True\n\n\ndef player_start_game(request, width=1, height=1, map_id=1):\n \"\"\"\n Инициализация игры пользователем.\n Если он единственный игрок в очереди, он получает карту и ожидает\n Если уже кто-то ждет игры, пользователи объединяются в игровую комнату\n :param request: Запрос клиента\n :param width: Ширина экрана устройства пользователя\n :param height: Высота экрана устройства пользователя\n :param map_id: id игрового поля\n :return: Json, содержащий информацию об игровом поле\n \"\"\"\n\n if request.session.session_key:\n drop_old_session(request)\n\n regions = map_model.get_play_map_as_dict(int(map_id), int(width), int(height))\n game_map = JsonResponse(regions)\n\n request.session.save()\n player_key = request.session.session_key\n if len(game_logic.players) == 0: # or game_logic.players[0] == player_key:\n # если новый игрок единственный, кто ожидающий игру, добавляем его в очередь\n game_logic.players.append(player_key)\n return game_map\n\n if game_logic.players[0] == player_key:\n return game_map\n\n enemy = game_logic.players[0] # за врага принимаем первого в очереди\n game_logic.players = game_logic.players[1:] # и удаляем его из очереди\n\n game_id = uuid.uuid1() # случайную уникальную комбинацию принимаем за игровой id\n init_game(player_key, enemy, game_id, int(map_id)) # инициализация карты, соперников, стадии игры\n\n return game_map\n\n\ndef init_game(player_key, his_enemy, game_id, map_id):\n game_logic.enemies[player_key] = his_enemy\n game_logic.enemies[his_enemy] = player_key\n\n game_logic.game_ids[player_key] = game_id # id сессии нового игрока присваиваем словарю игровых сессий\n game_logic.game_ids[his_enemy] = game_id # id сессии его врага присваиваем словарю игровых сессий\n\n game_logic.maps[game_id] = map_model.get_regions_as_list(map_id, player_key, his_enemy)\n game_logic.games[game_id] = game_logic.Game(player_who_comes_now=player_key,\n player_who_has_waited_some_times=his_enemy)\n\n\ndef game_center(request, num=1):\n player_key = request.session.session_key\n if player_key not in game_logic.game_ids:\n return JsonResponse({'error': 'the game is not initialized!'})\n\n current_game_id = game_logic.game_ids[player_key] # ищем игру по id сессии\n the_game = game_logic.games[current_game_id]\n if the_game.status_for_player[player_key] == game_logic.TURN_STATUS['player_wait_step']:\n return JsonResponse({'error': 'not your step!'})\n\n enemy_of_player = game_logic.enemies[player_key]\n num = int(num) # из url параметр пришел строкой. Получаем число\n\n one = the_game.status_for_player[player_key] == game_logic.TURN_STATUS['check_enum_quest']\n if one or the_game.status_for_player[player_key] == game_logic.TURN_STATUS['check_accuracy_question']:\n res = fight_result(request=request,\n user_answer=num,\n player_key=player_key,\n his_enemy=enemy_of_player,\n the_game=the_game)\n return JsonResponse(res)\n\n if the_game.status_for_player[player_key] == game_logic.TURN_STATUS['player_can_attack']:\n check = game_logic.init_round(the_game=the_game, area_id=num, player_key=player_key, his_enemy=enemy_of_player)\n if 'error' in check:\n return JsonResponse(check)\n\n return attack_area(request=request,\n player_key=player_key,\n the_game=the_game)\n\n\ndef attack_area(request, player_key, the_game):\n if the_game.round_state[player_key] == game_logic.TURN_STATUS['get_me_enum_question']:\n the_game.status_for_player[player_key] = game_logic.TURN_STATUS['check_enum_quest']\n return get_enum_question(request)\n else:\n the_game.status_for_player[player_key] = game_logic.TURN_STATUS['check_accuracy_question']\n return get_accuracy_question(request)\n\n\ndef fight_result(request, user_answer, player_key, his_enemy, the_game):\n if the_game.status_for_player[player_key] == game_logic.TURN_STATUS['check_enum_quest']:\n what_we_want = views_unit.WE_GET_ENUM_QUESTION\n else:\n what_we_want = views_unit.WE_GET_ACCURACY_QUESTION\n res_obj = views_unit.user_want_take_answer(request, what_we_want, int(user_answer))\n\n if 'error' in res_obj:\n return res_obj\n\n answer = 'taken_'+str(res_obj['its_true_answer?']).lower()+'_answer'\n the_game.round_state[player_key] = game_logic.TURN_STATUS[answer]\n\n def answer_of_enemy(x):\n return the_game.round_state[his_enemy] == game_logic.TURN_STATUS['taken_' + x + '_answer']\n\n fight_for_neutral = the_game.game_status['what_was_attacked'] == game_logic.TURN_STATUS['attacked_neutral_area']\n if fight_for_neutral or answer_of_enemy('true') or answer_of_enemy('false'):\n the_game.resume_part_of_round() # resume step -> должна уметь делать игра!\n\n return res_obj\n\n\ndef get_curr_map(request):\n key = request.session.session_key\n the_game = game_logic.games[game_logic.game_ids[key]]\n return JsonResponse({\n 'you_are': the_game.key_to_player_id(key),\n 'map': the_game.regions,\n })\n\n\ndef check_pair(request):\n return JsonResponse({'enemy': request.session.session_key in game_logic.game_ids})\n","sub_path":"HorizonQuiz/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"481647656","text":"\"\"\"\nImport packages to simplify code and give better analyzing methods\n\"\"\"\n\nimport time\nimport pandas as pd\nimport numpy as np\nimport calendar\nimport datetime\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 # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n city = input('The Bikeshare Data of which city do you want to analyze? Please choose from: Chicago, New York City or Washington. \\n ').lower()\n # the .lower() makes sure that users can enter in small or capt letters\n\n while city not in ['chicago', 'new york city', 'washington']:\n # to check if response is valid\n\n print('Sorry we can only evaluate data for Chicago, New York City or Washington. Please check for correct spelling. \\n ')\n city = input('Choose again, which city do you want to analyze: Chicago, New York or Washington? \\n ').lower()\n\n print('Your input was valid we will have a closer look at ' + city + '.\\n')\n\n month = input('Do you want to filter by a specific month? \\n If yes you can choose between: January, February, March, April, May or June. \\n Otherwise just type: all \\n').lower()\n\n while month not in ['january', 'february', 'march', 'april', 'may', 'june', 'all']:\n print('Sorry we can only filter from january to june or without a specific filter by entering: all. Please check for correct spelling. \\n ')\n month = input('Choose again which filter do you want to set? You can choose from january to june or simply: all \\n ').lower()\n\n print('Your input was valid we will have a closer look at ' + city + ' and filter by ' + month + '.\\n')\n\n day = input('Do you want to filter by a specific day? \\n Choose the day by typing monday, tuesday, ... Otherwise just type: all.\\n').lower()\n\n while day not in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']:\n print('Sorry we can only filter by weekday or without a specific filter by entering: all \\n ')\n day = input('Choose again which filter do you want to set? You can type the weekday: monday, tuesday, ... or: all. \\n').lower()\n\n print('Your input was valid we will have a closer look at ' + city + ' filtered by ' + month + ' and ' + day + '.\\n')\n\n print('-'*50)\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 # here I use the code presented in Practice Problem 3 for loading and filtering the city dataset\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['Start_hour'] = df['Start Time'].dt.hour # convert start hour into hour\n\n # extract month and day of week 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['month_name'] = df['month'].apply(lambda x:calendar.month_abbr[x])\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 = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month) + 1\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 # TO DO: display the most common month\n common_month = df['day_of_week'].mode().loc[0] # mode to find most common value\n print('The most common month is: ' + common_month + '!\\n')\n # month is in the wrong format!\n\n # TO DO: display the most common day of week\n common_day = df['day_of_week'].mode().loc[0]\n print('The most common day is: ' + common_day + '!\\n')\n # TO DO: display the most common start hour\n common_start_hour = df['Start Time'].mode().loc[0].strftime('%m/%d/%Y')\n\n print('The most common start hour is: ' + common_start_hour + '!\\n')\n\n print(\"\\nThis calculation took %s seconds.\" % (time.time() - start_time))\n\n print('-'*50)\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 # TO DO: display most commonly used start station\n common_start_station = df['Start Station'].mode().loc[0]\n print('The most common start station is: ' + common_start_station + '!\\n')\n # TO DO: display most commonly used end station\n common_end_station = df['End Station'].mode().loc[0]\n print('The most common start hour is: ' + common_end_station + '!\\n')\n # TO DO: display most frequent combination of start station and end station trip\n # Define a new column with string indicating start and end station\n # Then sort for the most common combination\n df['Station Combination'] = df['End Station'] + df['Start Station']\n common_station_combo = df['Station Combination'].mode().loc[0]\n print('The most common trip is: ' + common_station_combo + '!\\n')\n\n print(\"\\nThis calculation took %s seconds.\" % (time.time() - start_time))\n print('-'*50)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating the Trip Duration...\\n')\n start_time = time.time()\n\n # TO DO: display total travel time\n total_travel_time = df['Trip Duration'].sum()/3600\n print('The total travel time is: %d hours!\\n' % total_travel_time )\n\n # TO DO: display mean travel time\n mean_travel_time = df['Trip Duration'].mean()/60\n print('The mean travel time is: %d minutes!\\n' % mean_travel_time )\n print(\"\\nThis calculation took %s seconds.\" % (time.time() - start_time))\n print('-'*50)\n\n\ndef user_stats(df, city):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Statistics...\\n')\n start_time = time.time()\n\n # TO DO: Display counts of user types\n user_types = df['User Type'].value_counts()\n print('The user numbers per type are as follows:\\n', user_types ,'\\n')\n\n # TO DO: Display counts of gender\n # Gender data is not availbe for all cities thus we need a if condition\n if city in ['chicago', 'new york']:\n gender_types= df['Gender'].value_counts()\n print('The user numbers per gender are as follows:\\n', gender_types,'\\n')\n else:\n print('For this set there is no gender data available. \\n')\n\n # TO DO: Display earliest, most recent, and most common year of birth\n if city in ['chicago', 'new york']:\n early_byear= df['Birth Year'].min().astype(int)\n print('The most common birth year was:', early_byear,'\\n')\n\n recent_byear= df['Birth Year'].max().astype(int)\n print('The most common birth year was:', recent_byear,'\\n')\n\n common_byear= df['Birth Year'].mode().loc[0].astype(int)\n print('The most common birth year was:', common_byear, '\\n')\n else:\n print('For this set there is no birth year data available.')\n\n print(\"\\nThis calculation took %s seconds.\" % (time.time() - start_time))\n print('-'*50)\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, city)\n\n restart = input('\\nWould you like to do another search on the databasis? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":8761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"329338955","text":"# Definition for a binary tree node.\r\nclass TreeNode(object):\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\n\r\nclass Solution(object):\r\n def trimBST(self, root, L, R):\r\n \"\"\"\r\n :type root: TreeNode\r\n :type L: int\r\n :type R: int\r\n :rtype: TreeNode\r\n \"\"\"\r\n if root == None: return None\r\n if root.val < L:\r\n return self.trimBST(root.right, L, R)\r\n elif root.val > R:\r\n return self.trimBST(root.left, L, R)\r\n else:\r\n root.left = self.trimBST(root.left, L, R)\r\n root.right = self.trimBST(root.right, L, R)\r\n return root\r\n\r\ndef InOrder(root):\r\n if root == None: return\r\n InOrder(root.left)\r\n print(root.val)\r\n InOrder(root.right)\r\n\r\nif __name__ == \"__main__\":\r\n n3 = TreeNode(3)\r\n n0 = TreeNode(0)\r\n n4 = TreeNode(4)\r\n n2 = TreeNode(2)\r\n n1 = TreeNode(1)\r\n\r\n n3.left = n0; n3.right = n4\r\n n0.right = n2\r\n n2.left = n1\r\n\r\n s = Solution()\r\n newRoot = s.trimBST(n3, 1, 3)\r\n InOrder(newRoot)\r\n","sub_path":"Tree/TrimBST.py","file_name":"TrimBST.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"630592373","text":"import wx\r\nimport wx.lib.plot as plot\r\nimport math\r\n\r\n\r\nclass Kompas(wx.Panel):\r\n def __init__(self, parent, id, pos=(0,0), size=(200,200)):\r\n wx.Panel.__init__(self, parent, id, pos, size=size)\r\n\r\n self.pwidth = size[0]\r\n self.pheight = size[1]\r\n\r\n self.parent = parent\r\n\r\n self.roos = wx.Image('kompas_roos.png')\r\n self.naald = wx.Image('kompas_naald.png')\r\n\r\n self.roos.Rescale(self.pwidth,self.pheight)\r\n self.naald.Rescale(self.pwidth,self.pheight)\r\n\r\n self.SetAngle()\r\n\r\n\r\n\r\n\r\n self.SetBackgroundColour('#000000')\r\n\r\n\r\n self.Bind(wx.EVT_PAINT, self.OnPaint)\r\n\r\n def SetAngle(self,angle = 0):\r\n\r\n self.angle = angle * (2 * math.pi/360.0)\r\n self.InitBuffer()\r\n self.Refresh()\r\n\r\n def InitBuffer(self):\r\n\r\n self.buffer = wx.EmptyBitmap(self.pwidth, self.pheight)\r\n dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)\r\n dc.SetDeviceOrigin(0, self.pheight)\r\n dc.SetAxisOrientation(True, True)\r\n\r\n roos_gedraaid = self.roos.Rotate(math.pi + self.angle,(self.roos.GetWidth()/2,self.roos.GetHeight()/2))\r\n roos_gedraaid = roos_gedraaid.Mirror()\r\n roos_gedraaid = wx.BitmapFromImage(roos_gedraaid, depth=-1)\r\n\r\n\r\n\r\n\r\n\r\n naald_gedraaid = self.naald.Rotate(math.pi,(self.naald.GetWidth()/2,self.naald.GetHeight()/2))\r\n naald_gedraaid = naald_gedraaid.Mirror()\r\n naald_gedraaid = wx.BitmapFromImage(naald_gedraaid, depth=-1)\r\n\r\n\r\n dc.DrawBitmap(roos_gedraaid,\r\n dc.GetSize().GetWidth()/2 - roos_gedraaid.GetWidth()/2,\r\n dc.GetSize().GetWidth()/2 - roos_gedraaid.GetHeight()/2, True);\r\n dc.DrawBitmap(naald_gedraaid,0,0)##,\r\n ## dc.GetSize().GetWidth()/2 - naald_gedraaid.GetWidth()/2,\r\n ## dc.GetSize().GetWidth()/2 - naald_gedraaid.GetHeight()/2, True);\r\n\r\n def OnPaint(self, event):\r\n dc = wx.BufferedPaintDC(self, self.buffer)\r\n\r\nclass Wind(wx.Panel):\r\n def __init__(self, parent, id, pos=(0,0), size=(200,200)):\r\n wx.Panel.__init__(self, parent, id, pos, size=size)\r\n\r\n self.pwidth = size[0]\r\n self.pheight = size[1]\r\n\r\n self.parent = parent\r\n\r\n self.roos = wx.Image('wind_roos.png')\r\n self.naald = wx.Image('wind_naald.png')\r\n\r\n self.roos.Rescale(self.pwidth,self.pheight)\r\n self.naald.Rescale(self.pwidth,self.pheight)\r\n\r\n self.SetAngle()\r\n\r\n\r\n\r\n\r\n self.SetBackgroundColour('#000000')\r\n\r\n\r\n self.Bind(wx.EVT_PAINT, self.OnPaint)\r\n\r\n def SetAngle(self,angle = 0):\r\n\r\n self.angle = -(angle) * (2 * math.pi/360.0)\r\n self.InitBuffer()\r\n self.Refresh()\r\n\r\n def InitBuffer(self):\r\n\r\n self.buffer = wx.EmptyBitmap(self.pwidth, self.pheight)\r\n dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)\r\n dc.SetDeviceOrigin(0, self.pheight)\r\n dc.SetAxisOrientation(True, True)\r\n\r\n roos_gedraaid = self.roos.Rotate(math.pi,(self.roos.GetWidth()/2,self.roos.GetHeight()/2))\r\n roos_gedraaid = roos_gedraaid.Mirror()\r\n roos_gedraaid = wx.BitmapFromImage(roos_gedraaid, depth=-1)\r\n\r\n\r\n\r\n\r\n\r\n naald_gedraaid = self.naald.Rotate(math.pi + self.angle,(self.naald.GetWidth()/2,self.naald.GetHeight()/2))\r\n naald_gedraaid = naald_gedraaid.Mirror()\r\n naald_gedraaid = wx.BitmapFromImage(naald_gedraaid, depth=-1)\r\n\r\n\r\n dc.DrawBitmap(roos_gedraaid,\r\n dc.GetSize().GetWidth()/2 - roos_gedraaid.GetWidth()/2,\r\n dc.GetSize().GetWidth()/2 - roos_gedraaid.GetHeight()/2, True)\r\n dc.DrawBitmap(naald_gedraaid,\r\n dc.GetSize().GetWidth()/2 - naald_gedraaid.GetWidth()/2,\r\n dc.GetSize().GetWidth()/2 - naald_gedraaid.GetHeight()/2, True)\r\n\r\n\r\n\r\n\r\n def OnPaint(self, event):\r\n dc = wx.BufferedPaintDC(self, self.buffer)\r\n\r\nclass Roer(wx.Panel):\r\n\r\n\r\n\r\n def __init__(self, parent, id, pos=(0,0), size=(200,200)):\r\n wx.Panel.__init__(self, parent, id, pos, size=size)\r\n\r\n self.pwidth = size[0]\r\n self.pheight = size[1]\r\n\r\n self.parent = parent\r\n\r\n self.roos = wx.Image('roer_roos.png')\r\n self.naald = wx.Image('roer_naald.png')\r\n\r\n self.roos.Rescale(self.pwidth,self.pheight)\r\n self.naald.Rescale(self.pwidth,self.pheight)\r\n\r\n self.SetAngle()\r\n\r\n\r\n\r\n\r\n self.SetBackgroundColour('#000000')\r\n\r\n\r\n self.Bind(wx.EVT_PAINT, self.OnPaint)\r\n\r\n def SetAngle(self,angle = 0):\r\n\r\n self.angle = ((-angle + 46) * 1.6) * (2 * math.pi/360.0)\r\n self.InitBuffer()\r\n self.Refresh()\r\n\r\n def InitBuffer(self):\r\n\r\n self.buffer = wx.EmptyBitmap(self.pwidth, self.pheight)\r\n dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)\r\n dc.SetDeviceOrigin(0, self.pheight)\r\n dc.SetAxisOrientation(True, True)\r\n\r\n roos_gedraaid = self.roos.Rotate(math.pi,(self.roos.GetWidth()/2,self.roos.GetHeight()/2))\r\n roos_gedraaid = roos_gedraaid.Mirror()\r\n roos_gedraaid = wx.BitmapFromImage(roos_gedraaid, depth=-1)\r\n\r\n\r\n\r\n\r\n\r\n naald_gedraaid = self.naald.Rotate(math.pi + self.angle,(self.naald.GetWidth()/2,self.naald.GetHeight()/2))\r\n naald_gedraaid = naald_gedraaid.Mirror()\r\n naald_gedraaid = wx.BitmapFromImage(naald_gedraaid, depth=-1)\r\n\r\n\r\n dc.DrawBitmap(roos_gedraaid,\r\n dc.GetSize().GetWidth()/2 - roos_gedraaid.GetWidth()/2,\r\n dc.GetSize().GetWidth()/2 - roos_gedraaid.GetHeight()/2, True)\r\n dc.DrawBitmap(naald_gedraaid,\r\n dc.GetSize().GetWidth()/2 - naald_gedraaid.GetWidth()/2,\r\n dc.GetSize().GetWidth()/2 - naald_gedraaid.GetHeight()/2, True)\r\n\r\n\r\n\r\n\r\n def OnPaint(self, event):\r\n dc = wx.BufferedPaintDC(self, self.buffer)\r\n\r\nclass Zeil(wx.Panel):\r\n\r\n\r\n\r\n def __init__(self, parent, id, pos=(0,0), size=(200,200)):\r\n wx.Panel.__init__(self, parent, id, pos, size=size)\r\n\r\n self.pwidth = size[0]\r\n self.pheight = size[1]\r\n\r\n self.parent = parent\r\n\r\n self.roos = wx.Image('zeil_roos.png')\r\n self.naald = wx.Image('zeil_naald.png')\r\n\r\n self.roos.Rescale(self.pwidth,self.pheight)\r\n self.naald.Rescale(self.pwidth,self.pheight)\r\n\r\n self.SetAngle()\r\n\r\n\r\n\r\n\r\n self.SetBackgroundColour('#000000')\r\n\r\n\r\n self.Bind(wx.EVT_PAINT, self.OnPaint)\r\n\r\n def SetAngle(self,angle = 0):\r\n\r\n self.angle = ((-angle + 46) * 1.6) * (2 * math.pi/360.0)\r\n self.InitBuffer()\r\n self.Refresh()\r\n\r\n def InitBuffer(self):\r\n\r\n self.buffer = wx.EmptyBitmap(self.pwidth, self.pheight)\r\n dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)\r\n dc.SetDeviceOrigin(0, self.pheight)\r\n dc.SetAxisOrientation(True, True)\r\n\r\n roos_gedraaid = self.roos.Rotate(math.pi,(self.roos.GetWidth()/2,self.roos.GetHeight()/2))\r\n roos_gedraaid = roos_gedraaid.Mirror()\r\n roos_gedraaid = wx.BitmapFromImage(roos_gedraaid, depth=-1)\r\n\r\n\r\n\r\n\r\n\r\n naald_gedraaid = self.naald.Rotate(math.pi + self.angle,(self.naald.GetWidth()/2,self.naald.GetHeight()/2))\r\n naald_gedraaid = naald_gedraaid.Mirror()\r\n naald_gedraaid = wx.BitmapFromImage(naald_gedraaid, depth=-1)\r\n\r\n\r\n dc.DrawBitmap(roos_gedraaid,\r\n dc.GetSize().GetWidth()/2 - roos_gedraaid.GetWidth()/2,\r\n dc.GetSize().GetWidth()/2 - roos_gedraaid.GetHeight()/2, True)\r\n dc.DrawBitmap(naald_gedraaid,\r\n dc.GetSize().GetWidth()/2 - naald_gedraaid.GetWidth()/2,\r\n dc.GetSize().GetWidth()/2 - naald_gedraaid.GetHeight()/2, True)\r\n\r\n\r\n\r\n\r\n def OnPaint(self, event):\r\n dc = wx.BufferedPaintDC(self, self.buffer)\r\n\r\nclass Kaart(wx.Panel):\r\n def __init__(self, parent, id, s, pos=(0,0), size=(200,200)):\r\n wx.Panel.__init__(self, parent, id, pos, size=size)\r\n\r\n self.pwidth = size[0]\r\n self.pheight = size[1]\r\n\r\n self.parent = parent\r\n self.s = s\r\n\r\n\r\n\r\n\r\n\r\n self.SetBackgroundColour(\"black\")\r\n\r\n self.redraw()\r\n\r\n\r\n\r\n self.Bind(wx.EVT_PAINT, self.OnPaint)\r\n\r\n\r\n def redraw(self,punten = [(0,0)]):\r\n self.buffer = wx.EmptyBitmap(self.pwidth, self.pheight)\r\n dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)\r\n dc.SetDeviceOrigin(0, self.pheight)\r\n dc.SetAxisOrientation(True, True)\r\n dc.SetBackground(wx.Brush('white'))\r\n dc.Clear()\r\n \r\n dc.SetPen(wx.Pen('black', 2))\r\n\r\n dc.DrawRectangle(1,1,self.pwidth-2,self.pheight-2)\r\n\r\n x = []\r\n y = []\r\n\r\n for punt in punten:\r\n x.append(punt[1])\r\n y.append(punt[0])\r\n\r\n xmin = min(x)\r\n xmax = max(x)\r\n\r\n\r\n\r\n ymin = min(y)\r\n ymax = max(y)\r\n\r\n if xmin == xmax:\r\n xscale = (self.pwidth - 20)\r\n xmin -= 0.5\r\n else:\r\n xscale = (self.pwidth - 20)/ (xmax - xmin)\r\n\r\n if ymin == ymax:\r\n yscale = (self.pheight - 20)\r\n ymin -= 0.5\r\n else:\r\n yscale = (self.pheight - 20)/ (ymax - ymin)\r\n\r\n if yscale < xscale:\r\n scale = yscale\r\n else:\r\n scale = xscale\r\n\r\n\r\n vorig_punt = None\r\n for punt in punten:\r\n\r\n x = punt[1]\r\n y = punt[0]\r\n if punten.index(punt) == 0:\r\n dc.SetPen(wx.Pen('red', 1))\r\n dc.SetBrush(wx.Brush('red'))\r\n\r\n else:\r\n dc.SetPen(wx.Pen('blue', 1))\r\n dc.SetBrush(wx.Brush('blue'))\r\n dc.DrawText(str(punten.index(punt)),(x - xmin)*scale + 15,(y - ymin)*scale + 15)\r\n\r\n\r\n \r\n dc.DrawCircle((x - xmin)*scale + 10,(y - ymin)*scale + 10, 3)\r\n\r\n #draw line\r\n\r\n if vorig_punt and punten.index(punt) > 1:\r\n dc.SetPen(wx.Pen('black', 2))\r\n x_vorig, y_vorig = punt\r\n\r\n huidig = vorig_punt\r\n\r\n\r\n\r\n #simualte and draw\r\n tot_afstand = self.distance(vorig_punt,punt)\r\n tot_koers = self.heading(vorig_punt,punt)\r\n self.opkruisen = False\r\n\r\n while self.distance(huidig,punt) > tot_afstand / 100:\r\n cts = self.bereken_koers(huidig,punt)\r\n #print cts\r\n\r\n huidig = self.simulate(huidig,cts,tot_afstand / 100)\r\n\r\n y_huidig,x_huidig = huidig\r\n dc.DrawPoint((x_huidig - xmin)*scale + 10,(y_huidig - ymin)*scale + 10)\r\n\r\n\r\n vorig_punt = punt\r\n\r\n if self.s.boot[\"loop\"]:\r\n vorig_punt = punten[-1]\r\n punt = punten[1]\r\n x = punt[1]\r\n y = punt[0]\r\n \r\n #draw line\r\n\r\n dc.SetPen(wx.Pen('black', 2))\r\n x_vorig, y_vorig = punt\r\n\r\n huidig = vorig_punt\r\n\r\n\r\n\r\n #simualte and draw\r\n tot_afstand = self.distance(vorig_punt,punt)\r\n tot_koers = self.heading(vorig_punt,punt)\r\n self.opkruisen = False\r\n\r\n while self.distance(huidig,punt) > tot_afstand / 100:\r\n cts = self.bereken_koers(huidig,punt)\r\n #print cts\r\n\r\n huidig = self.simulate(huidig,cts,tot_afstand / 100)\r\n\r\n y_huidig,x_huidig = huidig\r\n dc.DrawPoint((x_huidig - xmin)*scale + 10,(y_huidig - ymin)*scale + 10)\r\n \r\n\r\n\r\n\r\n\r\n\r\n self.Refresh()\r\n\r\n\r\n def OnPaint(self, event):\r\n dc = wx.BufferedPaintDC(self, self.buffer)\r\n\r\n def simulate(self,pos,koers,afstand):\r\n\r\n koers = math.radians(koers)\r\n afstand /= 6371.0\r\n\r\n\r\n lat1 = math.radians(pos[0])\r\n lon1 = math.radians(pos[1])\r\n\r\n dlat = afstand*math.cos(koers)\r\n lat2 = dlat + lat1\r\n\r\n\r\n\r\n\r\n\r\n df = math.log(math.tan(lat2/2 + math.pi/4)/math.tan(lat1/2 + math.pi/4))\r\n\r\n try:\r\n q = dlat / df\r\n except ZeroDivisionError:\r\n q = math.cos(lat1)\r\n\r\n dlon = afstand * math.sin(koers)/q\r\n lat = math.degrees(lat2)\r\n\r\n\r\n lon2 = (lon1 + dlon + math.pi) % (2 * math.pi) - math.pi\r\n lon = math.degrees(lon2)\r\n\r\n return (lat,lon)\r\n\r\n def distance(self,pos1,pos2):\r\n #def distance(self, (lat_cur, long_cur), (lat_tar, long_tar)):\r\n #convert to radians\r\n\r\n (lat_cur_r, long_cur_r, lat_tar_r, long_tar_r) = map(math.radians, (pos1[0], pos1[1], pos2[0], pos2[1]))\r\n\r\n df = math.log(math.tan(lat_tar_r/2 + math.pi/4)/math.tan(lat_cur_r/2 + math.pi/4))\r\n\r\n\r\n dla = lat_tar_r - lat_cur_r\r\n dlo = long_tar_r - long_cur_r\r\n\r\n\r\n try:\r\n q = dla / df\r\n except ZeroDivisionError:\r\n q = math.cos(lat_cur_r)\r\n r = 6371\r\n\r\n\r\n d = math.sqrt(math.pow(dla,2) + math.pow(q,2) * math.pow(dlo,2)) * r\r\n k = math.degrees(math.atan2(dlo,df))\r\n if k < 0:\r\n k += 360\r\n\r\n return d\r\n def heading(self,pos1,pos2):\r\n #def distance(self, (lat_cur, long_cur), (lat_tar, long_tar)):\r\n #convert to radians\r\n\r\n (lat_cur_r, long_cur_r, lat_tar_r, long_tar_r) = map(math.radians, (pos1[0], pos1[1], pos2[0], pos2[1]))\r\n\r\n df = math.log(math.tan(lat_tar_r/2 + math.pi/4)/math.tan(lat_cur_r/2 + math.pi/4))\r\n\r\n\r\n dla = lat_tar_r - lat_cur_r\r\n dlo = long_tar_r - long_cur_r\r\n\r\n\r\n try:\r\n q = dla / df\r\n except ZeroDivisionError:\r\n q = math.cos(lat_cur_r)\r\n r = 6371\r\n\r\n\r\n d = math.sqrt(math.pow(dla,2) + math.pow(q,2) * math.pow(dlo,2)) * r\r\n k = math.degrees(math.atan2(dlo,df))\r\n if k < 0:\r\n k += 360\r\n\r\n return k\r\n\r\n def bereken_koers(self,cur,tar):\r\n #(lat_cur, long_cur) = cur\r\n #(lat_tar, long_tar) = tar\r\n\r\n koers = self.heading(cur,tar)\r\n\r\n resultaat = koers\r\n afstand = self.distance(cur, tar)\r\n\r\n #ware_wind = self.vaantje.get() + self.kompas.get()\r\n #voor tesen:\r\n ware_wind = self.s.boot[\"wind\"]\r\n if ware_wind > 360:\r\n ware_wind -= 360\r\n\r\n\r\n\r\n if math.fabs(self.verschil(koers,ware_wind)) < self.s.boot[\"minhoek\"] - 5:\r\n if not self.opkruisen:\r\n self.begin_opkruisen = cur[:]\r\n self.begin_rak = cur[:]\r\n self.koers_begin = koers\r\n self.eerste = True\r\n\r\n else:\r\n self.reset = False\r\n self.opkruisen = True\r\n\r\n if math.fabs(self.verschil(koers,ware_wind)) > self.s.boot[\"minhoek\"] + 5:\r\n self.opkruisen = False\r\n self.eerste = False\r\n\r\n if not self.opkruisen:\r\n self.cts = koers\r\n return koers\r\n\r\n if self.opkruisen:\r\n boeg1 = ware_wind + self.s.boot[\"minhoek\"] #bereken de koersen van de twee mogelijk te varen aan de windse koersen\r\n if boeg1 > 360:\r\n boeg1 -= 360\r\n boeg2 = ware_wind - self.s.boot[\"minhoek\"]\r\n if boeg2 < 0:\r\n boeg2 += 360\r\n\r\n\r\n\r\n lengte = self.distance(self.begin_opkruisen, tar) * self.s.boot[\"breedte\"]/100\r\n\r\n a = math.fabs(self.verschil(ware_wind,self.koers_begin))\r\n\r\n lengte1 = lengte / math.sin(math.radians(35+a))\r\n lengte2 = lengte / math.sin(math.radians(35-a))\r\n\r\n self.l1 = lengte1\r\n self.l2 = lengte2\r\n\r\n if self.eerste:\r\n lengte1 /= 2.0\r\n lengte2 /= 2.0\r\n\r\n if math.fabs(self.verschil(boeg1,self.s.boot[\"koers\"])) < math.fabs(self.verschil(boeg2,self.s.boot[\"koers\"])):\r\n self.boeg = 1\r\n else:\r\n self.boeg = 2\r\n\r\n\r\n\r\n\r\n if self.boeg == 1:\r\n if self.distance(self.begin_rak, cur)> lengte1:\r\n self.eerste = False\r\n self.boeg = 2\r\n self.begin_rak = cur\r\n self.cts = boeg1\r\n return boeg1\r\n if self.boeg == 2:\r\n if self.distance(self.begin_rak, cur) > lengte2:\r\n self.eerste = False\r\n self.boeg = 1\r\n self.begin_rak = cur\r\n self.cts = boeg2\r\n return boeg2\r\n\r\n def verschil(self,van,naar):\r\n error = naar - van\r\n\r\n if error > 180:\r\n error -= 360\r\n if error < -180:\r\n error += 360\r\n\r\n\r\n return error\r\n\r\nclass Grafiek(plot.PlotCanvas):\r\n def __init__(self,parent,min = 0,max = 360, size = (400,300) ):\r\n self.min = min\r\n self.max = max\r\n plot.PlotCanvas.__init__(self,parent)\r\n self.SetInitialSize(size=size)\r\n self.SetEnableZoom(False)\r\n def new_data(self,s,name):\r\n\r\n if ',' in name:\r\n names = name.split(',')\r\n title = \"\"\r\n\r\n\r\n line = []\r\n for n in names:\r\n data = zip(range(0,len(s.boot[n + \"_history\"])),s.boot[n + \"_history\"])\r\n colours = [\"red\",\"blue\",\"black\",\"brown\",\"pink\"]\r\n line.append(plot.PolyLine(data, colour=colours[names.index(n)], width=1))\r\n title += n.capitalize() + \": \" + colours[names.index(n)] + \" \"\r\n\r\n l = len(s.boot[n + \"_history\"])\r\n \r\n gc = plot.PlotGraphics(line, title)\r\n self.Draw(gc, xAxis=(0,l), yAxis=(self.min,self.max))\r\n else:\r\n data = zip(range(0,len(s.boot[name + \"_history\"])),s.boot[name + \"_history\"])\r\n line = plot.PolyLine(data, colour='red', width=1)\r\n gc = plot.PlotGraphics([line], name.capitalize())\r\n\r\n self.Draw(gc, xAxis=(0,len(s.boot[name + \"_history\"])), yAxis=(self.min,self.max))\r\n\r\nclass RouteBox(wx.BoxSizer):\r\n def __init__(self, parent, s):\r\n wx.BoxSizer.__init__(self, wx.VERTICAL)\r\n\r\n self.s = s\r\n \r\n self.routebox = wx.ListBox(parent, -1, size=(150,200), style=wx.CB_SIMPLE)\r\n\r\n\r\n goto = wx.Button(parent,-1,\"->\",size=(25,-1))\r\n parent.Bind(wx.EVT_BUTTON, self.OnGoto, goto)\r\n\r\n addcur = wx.Button(parent,-1,\"Add cur. pos\")\r\n parent.Bind(wx.EVT_BUTTON, self.OnAddcur, addcur)\r\n\r\n up = wx.Button(parent,-1,\"^\", size=(25,-1))\r\n parent.Bind(wx.EVT_BUTTON, self.OnUp, up)\r\n\r\n down = wx.Button(parent,-1,\"v\", size=(25,-1))\r\n parent.Bind(wx.EVT_BUTTON, self.OnDown, down)\r\n\r\n delete = wx.Button(parent,-1,\"X\", size=(25,-1))\r\n parent.Bind(wx.EVT_BUTTON, self.OnDelete, delete)\r\n\r\n add = wx.Button(parent,-1,\"+\", size=(25,-1))\r\n parent.Bind(wx.EVT_BUTTON, self.OnAdd, add)\r\n\r\n self.latvakje = wx.TextCtrl(parent, -1,size=(150,-1))\r\n lat = wx.BoxSizer(wx.HORIZONTAL)\r\n lat.Add(wx.StaticText(parent, -1,\"Latitude:\"), 0, wx.ALL, 5)\r\n lat.Add(self.latvakje, 0, wx.ALL, 5)\r\n\r\n self.lonvakje = wx.TextCtrl(parent, -1,size=(150,-1))\r\n lon = wx.BoxSizer(wx.HORIZONTAL)\r\n lon.Add(wx.StaticText(parent, -1,\"Longitude:\"), 0, wx.ALL, 5)\r\n lon.Add(self.lonvakje, 0, wx.ALL, 5)\r\n\r\n self.wpkoersvakje = wx.TextCtrl(parent, -1,size=(150,-1))\r\n wpkoers = wx.BoxSizer(wx.HORIZONTAL)\r\n wpkoers.Add(wx.StaticText(parent, -1,\"Koers:\"), 0, wx.ALL, 5)\r\n wpkoers.Add(self.wpkoersvakje, 0, wx.ALL, 5)\r\n\r\n self.wpafstandvakje = wx.TextCtrl(parent, -1,size=(150,-1))\r\n wpafstand = wx.BoxSizer(wx.HORIZONTAL)\r\n wpafstand.Add(wx.StaticText(parent, -1,\"Afstand:\"), 0, wx.ALL, 5)\r\n wpafstand.Add(self.wpafstandvakje, 0, wx.ALL, 5)\r\n\r\n self.active = wx.TextCtrl(parent, -1,size=(150,-1))\r\n act = wx.BoxSizer(wx.HORIZONTAL)\r\n act.Add(wx.StaticText(parent, -1,\"Active:\"), 0, wx.ALL, 5)\r\n act.Add(self.active, 0, wx.ALL, 5)\r\n\r\n bottom1 = wx.BoxSizer(wx.HORIZONTAL)\r\n bottom1.Add(goto, 0, wx.ALL, 5)\r\n bottom1.Add(addcur, 0, wx.ALL, 5)\r\n bottom1.Add(add, 0, wx.ALL, 5)\r\n\r\n bottom = wx.BoxSizer(wx.VERTICAL)\r\n bottom.Add(bottom1, 0, wx.ALL, 5)\r\n bottom.Add(lat, 0, wx.ALL, 5)\r\n bottom.Add(lon, 0, wx.ALL, 5)\r\n bottom.Add(wpkoers, 0, wx.ALL, 5)\r\n bottom.Add(wpafstand, 0, wx.ALL, 5)\r\n bottom.Add(act, 0, wx.ALL, 5)\r\n\r\n right = wx.BoxSizer(wx.VERTICAL)\r\n right.Add(up, 0, wx.ALL, 5)\r\n right.Add(down, 0, wx.ALL, 5)\r\n right.Add(delete, 0, wx.ALL, 5)\r\n\r\n top = wx.BoxSizer(wx.HORIZONTAL)\r\n top.Add(self.routebox, 0, wx.ALL, 5)\r\n top.Add(right, 0, wx.ALL, 5)\r\n\r\n\r\n self.Add(top, 0, wx.ALL, 5)\r\n self.Add(bottom, 0, wx.ALL, 5)\r\n\r\n def OnGoto(self,evt):\r\n n = self.routebox.GetSelection()\r\n if n == -1:\r\n n = None\r\n self.s.update(\"active\",n)\r\n\r\n def OnAddcur(self,evt):\r\n\r\n curRoute = self.s.boot[\"waypoints\"]\r\n n = self.routebox.GetSelection()\r\n newRoute = curRoute[:n+1] + [( self.s.boot[\"lat\"], self.s.boot[\"lon\"] )] + curRoute[n+1:]\r\n self.s.update(\"waypoints\",newRoute)\r\n\r\n def OnAdd(self,evt):\r\n\r\n curRoute = self.s.boot[\"waypoints\"]\r\n n = self.routebox.GetSelection()\r\n if len(self.latvakje.GetValue()):\r\n newRoute = curRoute[:n+1] + [( float(self.latvakje.GetValue()), float(self.lonvakje.GetValue()) )] + curRoute[n+1:]\r\n else:\r\n (lat,lon) = self.simulate(self.s.boot[\"lat\"],self.s.boot[\"lon\"],float(self.wpkoersvakje.GetValue()),float(self.wpafstandvakje.GetValue()))\r\n newRoute = curRoute[:n+1] + [( lat, lon )] + curRoute[n+1:]\r\n self.s.update(\"waypoints\",newRoute)\r\n\r\n def simulate(self,lat,lon,koers,afstand):\r\n\r\n koers = math.radians(koers)\r\n afstand /= 6371.0\r\n\r\n lat1 = math.radians(lat)\r\n lon1 = math.radians(lon)\r\n\r\n dlat = afstand*math.cos(koers)\r\n lat2 = dlat + lat1\r\n\r\n\r\n\r\n \r\n\r\n df = math.log(math.tan(lat2/2 + math.pi/4)/math.tan(lat1/2 + math.pi/4))\r\n\r\n try:\r\n q = dlat / df\r\n except ZeroDivisionError:\r\n q = math.cos(lat1)\r\n\r\n dlon = afstand * math.sin(koers)/q\r\n lat = math.degrees(lat2)\r\n\r\n \r\n lon2 = (lon1 + dlon + math.pi) % (2 * math.pi) - math.pi\r\n lon = math.degrees(lon2)\r\n return (lat,lon)\r\n def OnDown(self,evt):\r\n if self.routebox.GetSelection() > -1 and self.routebox.GetSelection() < len(self.routebox.GetItems()) - 1:\r\n\r\n curRoute = self.s.boot[\"waypoints\"]\r\n n = self.routebox.GetSelection()\r\n newRoute = curRoute[:n] + [curRoute[n+1]] + [curRoute[n]] + curRoute[n+2:]\r\n self.s.update(\"waypoints\",newRoute)\r\n\r\n self.routebox.SetSelection(self.routebox.GetSelection() + 1)\r\n\r\n def OnUp(self,evt):\r\n if self.routebox.GetSelection() > 0:\r\n curRoute = self.s.boot[\"waypoints\"]\r\n n = self.routebox.GetSelection()\r\n newRoute = curRoute[:n-1] + [curRoute[n]] + [curRoute[n-1]] + curRoute[n+1:]\r\n self.s.update(\"waypoints\",newRoute)\r\n\r\n self.routebox.SetSelection(self.routebox.GetSelection() - 1)\r\n\r\n def OnDelete(self,evt):\r\n\r\n if self.routebox.GetSelection() > -1:\r\n curRoute = self.s.boot[\"waypoints\"]\r\n n = self.routebox.GetSelection()\r\n newRoute = curRoute[:n] + curRoute[n+1:]\r\n self.s.update(\"waypoints\",newRoute)\r\n if len(newRoute) > 0:\r\n self.routebox.SetSelection(self.routebox.GetSelection() - 1)\r\n else:\r\n self.routebox.SetSelection(-1)\r\n\r\n\r\n def Update(self):\r\n\r\n selection = self.routebox.GetSelection()\r\n\r\n self.routebox.Clear()\r\n wp = self.s.boot[\"waypoints\"]\r\n\r\n for w in wp:\r\n self.routebox.Append(str(w))\r\n\r\n self.routebox.SetSelection(selection)\r\n\r\n self.active.SetValue(str(int(self.s.boot[\"active\"])))\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":"pc/klokkies.py","file_name":"klokkies.py","file_ext":"py","file_size_in_byte":24253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"459387759","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.4.2\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %%\nfrom osgeo import gdal\n\n# %%\ndata = gdal.Open(\"RAD_NL25_RAC_RT_1340.h5\")\n\n# %%\n# !gdalinfo RAD_NL25_RAC_RT_1340.h5\n\n# %%\nfrom mpl_toolkits.basemap import Basemap\nimport osr, gdal\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# %%\ndef convertXY(xy_source, inproj, outproj):\n # function to convert coordinates\n\n shape = xy_source[0,:,:].shape\n size = xy_source[0,:,:].size\n\n # the ct object takes and returns pairs of x,y, not 2d grids\n # so the the grid needs to be reshaped (flattened) and back.\n ct = osr.CoordinateTransformation(inproj, outproj)\n xy_target = np.array(ct.TransformPoints(xy_source.reshape(2, size).T))\n\n xx = xy_target[:,0].reshape(shape)\n yy = xy_target[:,1].reshape(shape)\n\n return xx, yy\n\n\n# %%\n# Read the data and metadata\nds = gdal.Open(r'RAD_NL25_RAC_RT_1340.h5')\n\ndata = ds.ReadAsArray()\ngt = ds.GetGeoTransform()\nproj = ds.GetProjection()\n\nxres = gt[1]\nyres = gt[5]\n\n# get the edge coordinates and add half the resolution \n# to go to center coordinates\nxmin = gt[0] + xres * 0.5\nxmax = gt[0] + (xres * ds.RasterXSize) - xres * 0.5\nymin = gt[3] + (yres * ds.RasterYSize) + yres * 0.5\nymax = gt[3] - yres * 0.5\n\nds = None\n\n# create a grid of xy coordinates in the original projection\nxy_source = np.mgrid[xmin:xmax+xres:xres, ymax+yres:ymin:yres]\n\n# %%\n# Create the figure and basemap object\nfig = plt.figure(figsize=(12, 6))\nm = Basemap(projection='robin', lon_0=0, resolution='c')\n\n# Create the projection objects for the convertion\n# original (Albers)\ninproj = osr.SpatialReference()\ninproj.ImportFromWkt(proj)\n\n# Get the target projection from the basemap object\noutproj = osr.SpatialReference()\noutproj.ImportFromProj4(m.proj4string)\n\n# Convert from source projection to basemap projection\nxx, yy = convertXY(xy_source, inproj, outproj)\n\n# plot the data (first layer)\nim1 = m.pcolormesh(xx, yy, data[0,:,:].T, cmap=plt.cm.jet)\n\n# annotate\nm.drawcountries()\nm.drawcoastlines(linewidth=.5)\n\nplt.savefig('world.png',dpi=75)\n","sub_path":"test_gdal.py","file_name":"test_gdal.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"282148561","text":"# Guess the number (version where the computer guesses)\n#\n# You select a random integer in the range of 1 to 100.\n# The computer is trying to guess this number.\n# The process continues until the computer guesses the number.\n\nintro = '''Welcome to \"Guess the Number (version where the computer guesses)\"!\nYou need to select a random integer number in the range from 1 to 100.\nThe process continues until the computer guesses the number.\nLet's go!\n'''\n\nprint(intro)\n\n# Initial values\nguessed_number = 0\nassumption = 0\ntries = 0\nleft = 1\nright = 100\n\n# \nwhile not left <= guessed_number <= right:\n guessed_number = int(input('Make a number from 1 to 100: '))\n\n if not left <= guessed_number <= right:\n print('The number is not in the range! Try it again\\n')\n\nwhile assumption != guessed_number:\n assumption = (left + right) // 2\n tries += 1\n\n if assumption == guessed_number:\n print('Computer guessed!')\n print(f'It took {tries} attempts')\n break\n elif assumption > guessed_number:\n right = assumption - 1\n elif assumption < guessed_number:\n left = assumption + 1","sub_path":"python_programming_for_the_absolute_beginner/guess_the_number_computer.py","file_name":"guess_the_number_computer.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"442691400","text":"from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter\n\n\nclass Command(BaseXpressDemocracyClubCsvImporter):\n council_id = \"E07000226\"\n addresses_name = \"local.2019-05-02/Version 2/Democracy_Club__02May2019.tsv\"\n stations_name = \"local.2019-05-02/Version 2/Democracy_Club__02May2019.tsv\"\n elections = [\"local.2019-05-02\"]\n csv_delimiter = \"\\t\"\n\n def address_record_to_dict(self, record):\n rec = super().address_record_to_dict(record)\n uprn = record.property_urn.strip().lstrip(\"0\")\n\n if record.addressline6 == \"RH10 3HW\":\n rec[\"postcode\"] = \"RH10 3GW\"\n\n if uprn in [\n \"10024122201\" # RH110EA -> RH110AE : 50A Ifield Drive, Ifield, Crawley\n ]:\n rec[\"accept_suggestion\"] = True\n\n return rec\n\n def station_record_to_dict(self, record):\n if record.polling_place_id == \"675\":\n record = record._replace(polling_place_easting=\"526564\")\n record = record._replace(polling_place_northing=\"135576\")\n if record.polling_place_id == \"692\":\n record = record._replace(polling_place_easting=\"528408\")\n record = record._replace(polling_place_northing=\"135808\")\n return super().station_record_to_dict(record)\n","sub_path":"polling_stations/apps/data_collection/management/commands/import_crawley.py","file_name":"import_crawley.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"140486437","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n#-------------------------------------------------------------------#\n# Srit Software LTD Corporation Confidential #\n# All Rights Reserved. #\n# #\n# NOTICE: All information contained herein is, and remains #\n# the property of Srit Software LTD Corporation. The #\n# intellectual and technical concepts contained herein are #\n# proprietary to Srit Software LTD Corporation, and are #\n# protected by trade secret or copyright law. Dissemination of #\n# this information or reproduction of this material is strictly #\n# forbidden unless prior written permission is obtained #\n# Srit Software LTD Corporation. #\n#-------------------------------------------------------------------#\nfrom flask import Blueprint, render_template, make_response\nimport json\nfrom flask import g,request\nfrom models.data import Wendu,Shidu\nfrom models.data import *\nfrom flask_login import login_required\nimport os\nfrom setting import CURRENT_SETTINGS, generate_settings, update_settings\nfrom test_use_c import generate_now_frequency, generate_wav, check_time\nbp = Blueprint(\"set\", __name__)\n\ndef change_mav_by_set():\n wendu = Wendu.query.order_by(Wendu.save_time.desc()).first()\n shidu = Shidu.query.order_by(Shidu.save_time.desc()).first()\n now_frequency = generate_now_frequency(int(wendu.data),int(shidu.data))\n generate_wav(now_frequency)\n\n\n@bp.route(\"/set_grade_frequency_form\", methods=['GET', 'POST'])\ndef set_grade_frequency_form():\n new_settings = request.values.dicts[1].to_dict()\n update_settings(new_settings)\n change_mav_by_set()\n return make_response('保存成功!'), 200\n\n\n@bp.route(\"/set_other_parameters\", methods=['GET', 'POST'])\ndef set_other_parameters():\n new_settings = request.values.dicts[1].to_dict()\n update_settings(new_settings)\n com_audio_size = \"sudo amixer -M set PCM \" + str(new_settings['audio_size']) + \"%\" \n os.system(com_audio_size)\n change_mav_by_set()\n check_time()\n return make_response('保存成功!'), 200\n","sub_path":"raspy_python/api/set.py","file_name":"set.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"62149692","text":"from flask import Blueprint, request\nfrom mysql.connector.errors import IntegrityError\nfrom registhor_app.departments_routes.queries import queries\nfrom registhor_app.utils import (check_api_key, _invalid_delete,\n\t_invalid_post, _missing_args, _valid_delete, _valid_post,\n\t_valid_get)\n\n# Instantiate blueprint\ndepartments = Blueprint('departments', __name__)\n\n\n@departments.route('/api/v1/departments/mandatory-courses', methods=['GET'])\n@check_api_key\ndef get_mandatory_courses():\n\t\"\"\"Return list of all active courses and if the given department\n\tconsiders them mandatory for its employees.\n\t\"\"\"\n\t# Only allow 'en' and 'fr' to be passed to app\n\tlang = 'fr' if request.args.get('lang', None) == 'fr' else 'en'\n\t\n\t# Unpack arguments\n\tdepartment_code = request.args.get('department_code', '').upper()\n\t\n\tif not department_code:\n\t\treturn _missing_args(missing=['department_code'])\n\t\n\t# Run query and return as JSON\n\tresults = queries.load_mandatory_courses(lang, department_code)\n\tresults_processed = _valid_get(results)\n\treturn results_processed\n\n\n@departments.route('/api/v1/departments/mandatory-courses', methods=['POST'])\n@check_api_key\ndef add_mandatory_course():\n\t# Unpack arguments\n\tdata = request.json\n\tdepartment_code = data.get('department_code', None)\n\tcourse_code = data.get('course_code', None)\n\t\n\tif not department_code:\n\t\treturn _missing_args(missing=['department_code'])\n\tif not course_code:\n\t\treturn _missing_args(missing=['course_code'])\n\t\n\ttry:\n\t\tqueries.add_mandatory_course(department_code, course_code)\n\t# If IntegrityError i.e. course entry already exists, return status 'OK'\n\texcept IntegrityError:\n\t\treturn _valid_post()\n\texcept Exception as e:\n\t\treturn _invalid_post()\n\telse:\n\t\treturn _valid_post()\n\n\n@departments.route('/api/v1/departments/mandatory-courses', methods=['DELETE'])\n@check_api_key\ndef remove_mandatory_course():\n\t# Unpack arguments\n\tdata = request.json\n\tdepartment_code = data.get('department_code', None)\n\tcourse_code = data.get('course_code', None)\n\t\n\tif not department_code:\n\t\treturn _missing_args(missing=['department_code'])\n\tif not course_code:\n\t\treturn _missing_args(missing=['course_code'])\n\t\n\ttry:\n\t\tqueries.remove_mandatory_course(department_code, course_code)\n\texcept Exception as e:\n\t\treturn _invalid_delete()\n\telse:\n\t\treturn _valid_delete()\n","sub_path":"registhor_app/departments_routes/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"463933566","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 12 03:53:02 2018\r\n\r\n@author: Chunbi\r\n\"\"\"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 2 14:13:25 2018\r\n\r\n@author: \r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom scipy import stats, integrate\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport queue\r\nimport networkx as nx \r\n\r\n\r\ndef main():\r\n df = pd.read_csv('com-youtube.ungraph.csv') #file name\r\n # Nodes: 1134890 Edges: 2987624\r\n lenght = df.FromNodeId.size\r\n\r\n \r\n ''' average degree '''\r\n print(\"average degree: \",(2987624*2)/1134890)\r\n\r\n \r\n '''daimeter'''\r\n G = nx.Graph() \r\n for i in range(0,lenght): \r\n G.add_edge(df.iloc[i]['FromNodeId'],df.iloc[i]['ToNodeId'])\r\n #max degree\r\n MaxDegree = max(G.degree().items(), key = lambda x: x[1]) \r\n bfs = list(nx.bfs_edges(G,MaxDegree[0]))\r\n r1 = bfs[len(bfs)-1][1]\r\n a1 = list(nx.bfs_edges(G,r1))\r\n a1 = a1[len(a1)-1][1]\r\n b1 = list(nx.bfs_edges(G,a1))\r\n b1 = b1[len(b1)-1][1]\r\n distance = nx.dijkstra_path_length(G, source=a1, target=b1)\r\n ##\r\n MaxDegree = max(G.degree().items(), key = lambda x: x[1]) \r\n bfs = list(nx.bfs_edges(G,MaxDegree[0]))\r\n r1 = bfs[len(bfs)-1][1]\r\n a1 = list(nx.bfs_edges(G,r1))\r\n a1 = a1[len(a1)-1][1]\r\n b1 = list(nx.bfs_edges(G,a1))\r\n b1 = b1[len(b1)-1][1]\r\n r2 = nx.dijkstra_path(G, source=a1, target=b1)\r\n r2 = r2[int((len(r2)+1)/2)]\r\n bfs_r2 = list(nx.bfs_edges(G,r2))\r\n a2 = bfs_r2[len(bfs_r2)-1][1]\r\n b2 = list(nx.bfs_edges(G,a2))\r\n b2 = b2[len(b2)-1][1]\r\n path = nx.dijkstra_path(G, source=a2, target=b2)\r\n lb = len(path)-1\r\n u = path[int((len(path)-1)/2)]\r\n ecc_u = list(nx.bfs_edges(G,u))\r\n ecc_u = ecc_u[len(ecc_u)-1][1]\r\n ecc_u = nx.dijkstra_path_length(G, source=u, target=ecc_u)\r\n ub = 2 * ecc_u\\\r\n ##\r\n print('diameter: ',distance)\r\n \r\n \r\n ### clustering coefficietn ###\r\n c = nx.average_clustering(G)\r\n \r\nif __name__ == '__main__':\r\n main()\r\n \r\n \r\n\r\n","sub_path":"diameter.py","file_name":"diameter.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"554244611","text":"import unittest\n\nfrom pysqes.queue import Queue\nfrom pysqes.task import Task\n\nfrom .stubs import SQSConnStub, SQSQueueStub\nfrom .test_tasks import add_func\n\n\nclass TestQueue(unittest.TestCase):\n\n def setUp(self):\n connection = SQSConnStub()\n self.queue = Queue(connection, 'pysqes_test')\n\n def test_enqueue_task(self):\n \"\"\"\n Here we're actually testing both enqueue and dequeue methods\n from the queue.\n \"\"\"\n\n task = Task(add_func, [1, 2])\n self.queue.enqueue_task(task)\n\n messages = self.queue.dequeue()\n self.assertEqual(messages[0][1]._args, [1, 2])\n\n task2 = Task(data={\n \"key\": 3\n })\n\n self.queue.enqueue_task(task2)\n messages2 = self.queue.dequeue()\n self.assertEqual(messages2[0][1].data, {\"key\": 3})\n\n def test_enqueue(self):\n self.queue.enqueue(add_func, 1, 2)\n\n messages = self.queue.dequeue()\n self.assertEqual(messages[0][1]._args, [1, 2])\n\n def test_get_queue(self):\n \"\"\"Test getting queue name from dictionary\"\"\"\n connection = SQSConnStub()\n queue = Queue(connection, 'pysqes_test', {'pysqes_test': 'test'})\n queue_stub = queue.queue\n self.assertEqual(queue_stub.name, 'test')\n\n def test_not_queue_lookup(self):\n connection = SQSConnStub()\n queue = Queue(connection, False)\n queue_stub = queue.queue\n self.assertIsInstance(queue_stub, SQSQueueStub)\n\n def test_delete_messages(self):\n messages = self.queue.delete_message_batch(['message'])\n self.assertEqual(messages, ['message'])\n\n def test_delete_message(self):\n messages = self.queue.delete_message('message')\n self.assertEqual(messages, 'message')\n\n def test_enqueue_validation(self):\n def fn():\n pass\n fn.__module__ = '__main__'\n with self.assertRaises(ValueError):\n self.queue.enqueue(fn)\n","sub_path":"tests/test_queue.py","file_name":"test_queue.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"188110062","text":"confs = int(input())\n\nl = []\n\nfor x in range(confs):\n l.append(tuple(map(int, input().split())))\n\nl = sorted(l, key=lambda x: (x[1], x[0]))\n\nconf_num = 0\nprev_end = -1\n\nfor x in l:\n if prev_end < x[0]:\n conf_num += 1\n prev_end = x[1]\n\n\nprint(conf_num)\n\n\n","sub_path":"Timus Online Judge/Correct/1203.py","file_name":"1203.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"499943410","text":"import os\nimport ast\nimport copy\n\nimport git\n\nfrom fiasko_bro.config import VALIDATOR_SETTINGS\nfrom . import file_helpers\n\n\nclass LocalRepositoryInfo:\n def __init__(self, repository_path):\n self.path = repository_path\n self._repo = git.Repo(self.path)\n self._python_filenames, self._main_file_contents, self._ast_trees = (\n self._get_ast_trees()\n )\n\n def count_commits(self):\n return len(list(self._repo.iter_commits()))\n\n def does_file_exist(self, filename):\n return os.path.isfile(os.path.join(self.path, filename))\n\n def get_source_file_contents(self, extension_list):\n file_paths = []\n file_contents = []\n for dirname, directories_list, filenames in os.walk(self.path, topdown=True):\n directories_list[:] = [\n d for d in directories_list\n if d not in VALIDATOR_SETTINGS['directories_to_skip']\n ]\n for filename in filenames:\n extension = os.path.splitext(filename)[1]\n if extension in extension_list:\n file_paths.append(os.path.join(dirname, filename))\n for file_path in file_paths:\n with open(file_path, 'r', encoding='utf-8') as file_handler:\n file_contents.append(file_handler.read())\n source_file_contents = list(zip(file_paths, file_contents))\n return source_file_contents\n\n def _get_ast_trees(self):\n py_files = list(zip(*self.get_source_file_contents(['.py']))) or [(), ()]\n filenames, main_file_contents = py_files\n ast_trees = []\n for file_content in main_file_contents:\n try:\n tree = ast.parse(file_content)\n except SyntaxError as e:\n tree = None\n if tree:\n self._set_parents(tree)\n ast_trees.append(tree)\n return filenames, main_file_contents, ast_trees\n\n def get_ast_trees(self, with_filenames=False, with_file_content=False, whitelist=None,\n with_syntax_error_trees=False):\n ast_trees_copy = copy.deepcopy(self._ast_trees)\n all_items = zip(self._python_filenames, self._main_file_contents, ast_trees_copy)\n filtered_items = self.filter_file_paths(all_items, whitelist)\n\n if with_filenames:\n if not with_syntax_error_trees:\n filtered_items = [r for r in filtered_items if r[2] is not None]\n if with_file_content:\n return filtered_items\n else:\n return [(f, t) for (f, c, t) in filtered_items]\n else:\n if with_syntax_error_trees:\n return ast_trees_copy\n else:\n return [t for t in ast_trees_copy if t is not None]\n\n def get_python_file_filenames(self):\n return self._python_filenames\n\n def get_file(self, filename):\n for dirname, _, files in os.walk(self.path, topdown=True):\n for file in files:\n if file == filename:\n with open(os.path.join(dirname, file), encoding='utf-8') as file_handler:\n return file_handler.read()\n\n def does_directory_exist(self, dirname_to_find):\n for dirname, dirs, _ in os.walk(self.path, topdown=True):\n if dirname == dirname_to_find or dirname_to_find in dirs:\n return True\n return False\n\n def iter_commits(self, *args, **kwargs):\n return self._repo.iter_commits(*args, **kwargs)\n\n @staticmethod\n def filter_file_paths(all_items, whitelist):\n if not whitelist:\n return all_items\n filtered_items = []\n for file_name, file_content, ast_tree in all_items:\n if not file_helpers.is_filename_in_whitelist(file_name, whitelist):\n filtered_items.append(\n (file_name, file_content, ast_tree)\n )\n return filtered_items\n\n @staticmethod\n def _set_parents(tree):\n for node in ast.walk(tree):\n for child in ast.iter_child_nodes(node):\n child.parent = node\n","sub_path":"fiasko_bro/repository_info.py","file_name":"repository_info.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"337543889","text":"\"\"\"\nPipeline for text processing implementation\n\"\"\"\nimport os\nimport re\nfrom pathlib import Path\nfrom pymystem3 import Mystem\nfrom article import Article\nfrom typing import List\n\n\nclass EmptyDirectoryError(Exception):\n \"\"\"\n Custom error\n \"\"\"\n\n\nclass InconsistentDatasetError(Exception):\n \"\"\"\n Custom error\n \"\"\"\n\n\nclass UnknownDatasetError(Exception):\n \"\"\"\n Custom error\n \"\"\"\n\n\nclass MorphologicalToken:\n \"\"\"\n Stores language params for each processed token\n \"\"\"\n def __init__(self, original_word, normalized_form):\n self.original_word = original_word\n self.normalized_form = normalized_form\n self.mystem_tags = ''\n self.pymorphy_tags = ''\n\n def __str__(self):\n return f\"{self.normalized_form}<{self.mystem_tags}>\"\n\n\nclass CorpusManager:\n \"\"\"\n Works with articles and stores them\n \"\"\"\n def __init__(self, path_to_raw_txt_data: str):\n self.path_to_raw_txt_date = path_to_raw_txt_data\n self._storage = {}\n self._scan_dataset()\n\n def _scan_dataset(self):\n \"\"\"\n Register each dataset entry\n \"\"\"\n path = Path(self.path_to_raw_txt_date)\n\n for file in path.glob('*_raw.txt'):\n art_id = str(file).split('/')[-1].split('_')[0]\n self._storage[art_id] = Article(url=None, article_id=art_id)\n\n def get_articles(self):\n \"\"\"\n Returns storage params\n \"\"\"\n return self._storage\n\n\nclass TextProcessingPipeline:\n \"\"\"\n Process articles from corpus manager\n \"\"\"\n def __init__(self, corpus_manager: CorpusManager):\n self.corpus_manager = corpus_manager\n self.raw_text = \"\"\n\n def run(self):\n \"\"\"\n Runs pipeline process scenario\n \"\"\"\n articles = self.corpus_manager.get_articles()\n\n for article in articles.values():\n self.raw_text = article.get_raw_text()\n tokens = self._process()\n processed_text = []\n for token in tokens:\n processed_text.append(str(token))\n article.save_processed(' '.join(processed_text))\n\n def _process(self) -> List[type(MorphologicalToken)]:\n \"\"\"\n Performs processing of each text\n \"\"\"\n process = Mystem().analyze(self.raw_text)\n tokens = []\n\n for token in process:\n if token.get('analysis') and token.get('text'):\n morph_token = MorphologicalToken(original_word=token['text'],\n normalized_form=token['analysis'][0]['lex'])\n morph_token.mystem_tags = token['analysis'][0]['gr']\n tokens.append(morph_token)\n\n return tokens\n\n\ndef validate_dataset(path_to_validate):\n \"\"\"\n Validates folder with assets\n \"\"\"\n path = Path(path_to_validate)\n\n if not path.exists():\n raise FileNotFoundError\n\n if not path.is_dir():\n raise NotADirectoryError\n\n if not list(path.iterdir()):\n raise EmptyDirectoryError\n\n\ndef main():\n print('Your code goes here')\n from constants import ASSETS_PATH\n\n validate_dataset(ASSETS_PATH)\n corpus_manager = CorpusManager(path_to_raw_txt_data=ASSETS_PATH)\n pipeline = TextProcessingPipeline(corpus_manager=corpus_manager)\n pipeline.run()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"396760101","text":"import h5py\nimport random\nimport cv2\nimport numpy as np\nimport os\n\nfrom crop import crop, cropOutROIs\nfrom annotation import RectangleAnnotation, EllipseAnnotation, getFaceAnnotations, ANNOTATIONS_FOLDER, POSITIVE_IMAGES_FOLDER\n\nNEGATIVE_IMAGES_FOLDER = r'./Negative Images/images'\nFACE_DATABASE_PATHS = ('face12.hdf', 'face24.hdf', 'face48.hdf')\nNEGATIVE_DATABASE_PATHS = ('neg12.hdf', 'neg24.hdf', 'neg48.hdf')\nTRAIN_DATABASE_PATH = 'train.hdf'\nNUM_NEGATIVES_PER_IMG = 20\nTARGET_NUM_NEGATIVES = 50000\nMIN_FACE_SCALE = 50\nOFFSET = 4\n\nSCALES = ((12,12),(24,24),(48,48))\n\nCALIBRATION_DATABASE_PATHS = {SCALES[0][0]:'calib12.hdf',SCALES[1][0]:'calib24.hdf',SCALES[2][0]:'calib48.hdf'}\nTARGET_NUM_CALIBRATION_SAMPLES = 5000\nSN = (.83, .91, 1, 1.1, 1.21)\nXN = (-.17, 0, .17)\nYN = XN\nCALIB_PATTERNS = [(sn, xn, yn) for sn in SN for xn in XN for yn in YN]\n\ndef loadDatabase(databasePath, isNegativeDataset = False):\n db = None\n\n try:\n with h5py.File(databasePath, 'r') as infile:\n db = infile[databasePath[:databasePath.find('.')]][:]\n except IOError as ioError:\n pass\n\n return db\n\ndef getNegatives(w, h, imgFolder = NEGATIVE_IMAGES_FOLDER, numNegativesPerImg = NUM_NEGATIVES_PER_IMG, numNegatives = None):\n posDb = loadDatabase('face%d.hdf' % w)\n numNegatives = posDb.shape[0]*NUM_NEGATIVES_PER_IMG if posDb is not None and numNegatives is None else numNegatives\n db = np.ones((numNegatives,w,h,3),dtype=posDb[0].dtype)\n len = 0\n\n for i, imgPath in enumerate(os.listdir(imgFolder)):\n if len >= int(numNegatives*.9): break\n img = cv2.imread('%s\\%s' % ( NEGATIVE_IMAGES_FOLDER, imgPath ))\n maxDimIdx = ((img.shape[1]-MIN_FACE_SCALE)//MIN_FACE_SCALE,(img.shape[0]-MIN_FACE_SCALE)//MIN_FACE_SCALE)\n randXIdx = np.random.permutation(maxDimIdx[0])\n randYIdx = np.random.permutation(maxDimIdx[1])\n checked = 0\n extracted = 0\n\n for j in np.arange(min(randXIdx.shape[0], randYIdx.shape[0])):\n if len >= int(numNegatives*.9) or checked >= randXIdx.shape[0]*randYIdx.shape[0] or extracted >= NUM_NEGATIVES_PER_IMG: break\n top_left = (randXIdx[j] * MIN_FACE_SCALE, randYIdx[j] * MIN_FACE_SCALE)\n bottom_right = (top_left[0] + MIN_FACE_SCALE, top_left[1] + MIN_FACE_SCALE)\n cropped = crop(img, top_left, bottom_right, MIN_FACE_SCALE, MIN_FACE_SCALE)\n if cropped is None: \n continue\n db[len] = cv2.resize(cropped, (w,h))\n len += 1\n extracted += 1\n\n faceAnnotations = getFaceAnnotations()\n\n for i, imgPath in enumerate(faceAnnotations.keys()):\n if len >= numNegatives: break\n annotations = faceAnnotations.getAnnotations(imgPath)\n img = cv2.imread(imgPath)\n maxDimIdx = ((img.shape[1]-MIN_FACE_SCALE)//MIN_FACE_SCALE,(img.shape[0]-MIN_FACE_SCALE)//MIN_FACE_SCALE)\n randXIdx = np.random.permutation(maxDimIdx[0])\n randYIdx = np.random.permutation(maxDimIdx[1])\n checked = 0\n extracted = 0\n\n for j in np.arange(min(randXIdx.shape[0], randYIdx.shape[0])):\n if len >= numNegatives or checked >= randXIdx.shape[0]*randYIdx.shape[0] or extracted >= NUM_NEGATIVES_PER_IMG: break\n checked += 1\n top_left = (randXIdx[j] * MIN_FACE_SCALE, randYIdx[j] * MIN_FACE_SCALE)\n bottom_right = (top_left[0] + MIN_FACE_SCALE, top_left[1] + MIN_FACE_SCALE)\n rect = RectangleAnnotation(MIN_FACE_SCALE, MIN_FACE_SCALE, top_left[0] + MIN_FACE_SCALE//2, top_left[1] + MIN_FACE_SCALE//2)\n if any([annotation.computeIoU(rect) > 0 for annotation in annotations]):\n continue\n cropped = crop(img, top_left, bottom_right, MIN_FACE_SCALE, MIN_FACE_SCALE)\n if cropped is None: continue\n db[len] = cv2.resize(cropped, (w,h))\n len += 1\n extracted += 1\n\n return db\n\ndef createDatabase(databasePaths, loadFunc, scales = SCALES):\n for i, databasePath in enumerate(databasePaths):\n with h5py.File(databasePath, 'w') as out:\n w, h = SCALES[i]\n out.create_dataset(databasePath[:databasePath.find('.')], data = loadFunc(w,h), chunks=(32,w,h,3))\n\ndef createNegativeDatasetFor12Net():\n createDatabase(NEGATIVE_DATABASE_PATHS, lambda w, h: getNegatives(w,h), ((12,12)))\n\ndef mineNegatives(stageNum, numNegatives = TARGET_NUM_NEGATIVES, negImgFolder = NEGATIVE_IMAGES_FOLDER):\n from detect import stage1_predict_multiscale, IoU\n from util import detections2boxes\n\n IOU_THRESH = .01\n\n scale = SCALES[stageNum-1][0]\n predict = stage1_predict_multiscale\n databasePath = NEGATIVE_DATABASE_PATHS[stageNum-1]\n annotations = getFaceAnnotations()\n dataset = None\n len = 0\n\n with h5py.File(databasePath, 'w') as out:\n for imgPath in annotations.keys():\n if len >= numNegatives: break\n img = cv2.imread(imgPath)\n if dataset is None: dataset = np.ones((numNegatives, scale, scale, 3),dtype=img.dtype)\n detections = predict(img, IOU_THRESH)\n faces = detections2boxes(annotations.getAnnotations(imgPath))\n \n for i, detection in enumerate(detections):\n if len >= numNegatives: break\n if np.all(IoU(faces, detection.coords)==0):\n cropped = detection.cropOut(img, scale, scale)\n if cropped is None: continue\n dataset[len] = detection.cropOut(img, scale, scale)\n len += 1\n print('pos', len)\n\n for root, _, files in os.walk(negImgFolder):\n if len >= numNegatives: break\n for fileName in files:\n if len >= numNegatives: break\n img = cv2.imread(os.path.join(root, fileName))\n detections = predict(img, IOU_THRESH)\n for i, detection in enumerate(detections):\n if len >= numNegatives: break\n cropped = detection.cropOut(img, scale, scale)\n if cropped is None: continue\n dataset[len] = detection.cropOut(img,scale,scale)\n len += 1\n print('neg', len)\n\n if len < numNegatives:\n np.delete(dataset, np.s_[len:], 0)\n\n out.create_dataset(databasePath[:databasePath.find('.')], data = dataset, chunks=(32,scale,scale,3))\n\ndef createFaceDatabase(faces):\n createDatabase(FACE_DATABASE_PATHS, lambda w, h, faces = faces: cropOutROIs(faces, w, h))\n\ndef createCalibrationDataset(faces, scale = SCALES[0][0], numCalibrationSamples = TARGET_NUM_CALIBRATION_SAMPLES):\n imgDtype = loadDatabase('face%d.hdf' % scale)[0].dtype\n numCalibPatterns = len(SN)*len(XN)*len(YN)\n calibDbLen = numCalibrationSamples * numCalibPatterns\n\n db = np.ones((calibDbLen, scale, scale, 3), imgDtype)\n y = np.ones((calibDbLen,1))\n\n i = 0\n j = 0\n posImgPaths = tuple(faces.keys())\n\n with h5py.File(CALIBRATION_DATABASE_PATHS.get(scale), 'w') as out:\n while i < calibDbLen and j < len(posImgPaths):\n img = cv2.imread(posImgPaths[j])\n \n for annotation in faces.getAnnotations(posImgPaths[j]):\n for n, (sn, xn, yn) in enumerate(CALIB_PATTERNS):\n dim = np.array([annotation.w, annotation.h])\n top_left = annotation.top_left + (np.array([xn, yn])*dim).astype(int)\n dim = (dim*sn).astype(int)\n cropped = crop(img, top_left, top_left + dim, scale, scale)\n\n if cropped is not None:\n db[i] = cropped\n y[i] = n\n i += 1\n j += 1\n \n if i < calibDbLen:\n np.delete(y, np.s_[i:], 0)\n np.delete(db, np.s_[i:], 0)\n\n out.create_dataset('labels', data=y, chunks=(32,1))\n out.create_dataset('data', data=db, chunks=(32, scale, scale, 3))\n\ndef createCalibrationDatabase(scale = SCALES):\n faces = getFaceAnnotations()\n for (w, h) in SCALES:\n _createCalibrationDataset(faces, w)\n\n\ndef createTrainingDataset(scale = SCALES[0][0]):\n pos_db = loadDatabase('face%d.hdf' % scale)\n neg_db = loadDatabase('neg%d.hdf' % scale)\n img_dtype = pos_db[0].dtype\n y = np.vstack((np.ones((len(pos_db),1),dtype=img_dtype),np.zeros((len(neg_db),1))))\n db = np.vstack((pos_db,neg_db))\n \n perm = np.random.permutation(db.shape[0])\n y = y[perm]\n db = db[perm]\n\n with h5py.File(TRAIN_DATABASE_PATH, 'w') as out:\n out.create_dataset('labels', data=y, chunks=(32,1))\n out.create_dataset('data', data=db, chunks=(32, scale, scale, 3))\n","sub_path":"Vision/FaceDetection/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":8734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"552873151","text":"# coding=utf-8\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport time\n\ncartoon_name = '一拳超人'\n\ndriver = webdriver.Chrome(\"/mnt/d/Code/PycharmProjects/chromedriver.exe\")\n# driver = webdriver.PhantomJS()\n\ndriver.get(\"https://www.manhuadui.com/\")\n\ndriver.find_element_by_id(\"keywords\").send_keys(cartoon_name)\ntime.sleep(1)\ndriver.find_element_by_id(\"btnSearch\").click()\n\ntime.sleep(1)\ndriver.find_element_by_xpath(\"//li[@class='list-comic']//a[text()='{}']\".format(cartoon_name)).click()\n\n# time.sleep(1)\n# driver.find_element_by_xpath(\"//a[@class='beread_btn']\").click()\ntime.sleep(3)\n# lis = driver.find_elements_by_xpath(\"//ul[@id='chapter-list-1']/li/a\")\ndriver.find_element_by_xpath(\"//ul[@id='chapter-list-1']/li[last()]/a\").click()\n\n# print(\"*******%d******\" % len(lis))\ndriver.switch_to_window(driver.window_handles[2])\nfor i in range(100):\n time.sleep(5)\n driver.find_element_by_xpath(\"//span[@class='next']/a\").click()\n\n# driver.save_screenshot(\"./temp/manhuadui5.png\")\n\ndriver.quit()\n","sub_path":"driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"84951969","text":"import cv2\nimport numpy as np\n \noriginalImage = cv2.imread('images/path.jpg')\ngrayImage = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY)\n \n(thresh, blackAndWhiteImage) = cv2.threshold(grayImage, 170, 180, cv2.THRESH_BINARY)\n \nimageArr = np.argwhere(np.logical_and(blackAndWhiteImage>=170, blackAndWhiteImage<=180)) \naverage = [sum(x)/len(x) for x in zip(*imageArr)]\n\ncv2.imshow(grayImage)\ncv2.waitKey(0)\n","sub_path":"grayscale-tutorial-opencv.py","file_name":"grayscale-tutorial-opencv.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"347564104","text":"import turtle\r\nimport math\r\n\r\nlength = 100\r\nangles_1 = [30, 270, 150]\r\nangles_2 = [270, 30, 150]\r\ncolors_1 = [\"red\", \"orange\", \"blue\"]\r\ncolors_2 = [\"purple\", \"green\", \"brown\"]\r\nfor i in range(3):\r\n turtle.color(colors_1[i])\r\n turtle.seth(angles_1[i])\r\n turtle.fd(length)\r\nturtle.color(\"white\")\r\nturtle.seth(60)\r\nturtle.fd(length / math.sqrt(3))\r\nfor j in range(3):\r\n turtle.color(colors_2[j])\r\n turtle.seth(angles_2[j])\r\n turtle.fd(length)\r\n\r\nturtle.done()\r\n","sub_path":"renwu2/2.7.py","file_name":"2.7.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"106848071","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function, division\nfrom io_helpers import *\nfrom models.alexnet import alexnet\nfrom models.densenet import DenseNet\nfrom models.inception import inception_v3\nfrom models.resnet import resnet18\nfrom models.squeezenet import squeezenet1_1\n\nimport os\nimport torch\nimport torch.nn as nn\n\ndef test_model(modname = 'alexnet', pm_ch = 'both', bs = 16):\n # hyperparameters\n batch_size = bs\n\n # device configuration\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n # determine number of input channels\n nch = 2\n if pm_ch != 'both':\n nch = 1\n\n # restore model\n model = None\n if modname == 'alexnet':\n model = alexnet(num_classes=3, in_ch=nch).to(device)\n elif modname == 'densenet':\n model = DenseNet(num_classes=3, in_ch=nch).to(device)\n elif modname == 'inception':\n model = inception_v3(num_classes=3, in_ch=nch).to(device)\n elif modname == 'resnet':\n model = resnet18(num_classes=3, in_ch=nch).to(device)\n elif modname == 'squeezenet':\n model = squeezenet1_1(num_classes=3, in_ch=nch).to(device) \n else:\n print('Model {} not defined.'.format(modname))\n return\n \n # retrieve trained model\n # load path\n load_path = '../../../data/saved_models/{}/{}'.format(modname, pm_ch)\n model_pathname = os.path.join(load_path, 'model.ckpt')\n if not os.path.exists(model_pathname):\n print('Trained model file {} does not exist. Abort.'.format(model_pathname))\n return\n model.load_state_dict(torch.load(model_pathname))\n\n # load test dataset\n test_dataset = PixelMapDataset('test_file_list.txt', pm_ch)\n\n test_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=batch_size, \n shuffle=False)\n\n # test the model\n model.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)\n with torch.no_grad():\n correct = 0\n total = 0\n correct_cc_or_bkg = 0\n ws_total = 0\n ws_correct = 0\n for images, labels in test_loader:\n images = images.float().to(device)\n if modname != 'alexnet':\n images = nn.ZeroPad2d((0,117,64,64))(images)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n for i in range(len(predicted)):\n if (predicted[i] < 2 and labels[i] < 2) or (predicted[i] == 2 and labels[i] == 2):\n correct_cc_or_bkg += 1\n if labels[i] < 2:\n ws_total += 1\n if (predicted[i] == labels[i]):\n ws_correct += 1\n print('Model Performance:')\n print('Model:', modname)\n print('Channel:', pm_ch)\n print('3-class Test Accuracy of the model on the test images: {}/{}, {:.2f} %'.format(correct, total, 100 * correct / total))\n print('2-class Test Accuracy of the model on the test images: {}/{}, {:.2f} %'.format(correct_cc_or_bkg, total, 100 * correct_cc_or_bkg / total))\n print('Wrong-sign Test Accuracy of the model on the test images: {}/{}, {:.2f} %'.format(ws_correct, ws_total, 100 * ws_correct / ws_total))\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-m', '--model_name', default='alexnet', type=str)\n parser.add_argument('-c', '--pixelmap_channel', default='both', type=str)\n parser.add_argument('-b', '--batch_size', default=16, type=int)\n\n args = parser.parse_args()\n\n test_model(args.model_name, args.pixelmap_channel, args.batch_size)","sub_path":"wrong_sign_convnets_single_view/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"470342993","text":"from dataclasses import dataclass\nfrom logging import getLogger\nfrom typing import Any, List, Literal, Optional\n\nimport numpy as np\nimport pytorch_lightning as pl\nfrom summarization_models.models.codebert.model import Seq2Seq\nfrom torch import nn\nfrom transformers import (\n AdamW,\n RobertaConfig,\n RobertaModel,\n RobertaTokenizer,\n get_linear_schedule_with_warmup,\n)\n\nlogger = getLogger(__name__)\n\nMODEL_CLASSES = {\"roberta\": (RobertaConfig, RobertaModel, RobertaTokenizer)}\n\n\n@dataclass\nclass CodeBERTConfig:\n max_target_length: int = 128\n max_source_length: int = 256\n pretrained_model: Literal[\n \"microsoft/codebert-base\", \"roberta-base\"\n ] = \"microsoft/codebert-base\"\n num_decoder_layers: int = 6\n beam_size: int = 10\n lr: float = 1e-5\n weight_decay: float = 0.0\n warmup_steps: float = 0.1\n uncased: bool = True\n cls_token_id: int = 0\n sep_token_id: int = 2\n adam_epsilon: float = 1e-8\n pretrained_weights_cache_dir: Optional[str] = None\n\n\nfrom pathlib import Path\n\nfrom omegaconf import OmegaConf\n\n\nclass CodeBERT(pl.LightningModule):\n def __init__(self, cfg: CodeBERTConfig):\n super().__init__()\n\n self.save_hyperparameters(cfg.__dict__)\n self.cfg = cfg\n config_class = RobertaConfig\n model_class = RobertaModel\n weights_cache_dir = (\n Path(cfg.pretrained_weights_cache_dir)\n if cfg.pretrained_weights_cache_dir is not None\n else None\n )\n\n if weights_cache_dir is not None:\n if not weights_cache_dir.exists():\n weights_cache_dir.mkdir()\n\n pretrain_config = config_class.from_pretrained(\n cfg.pretrained_model, cache_dir=cfg.pretrained_weights_cache_dir\n )\n encoder = model_class.from_pretrained(\n cfg.pretrained_model, config=pretrain_config\n )\n\n decoder_layer = nn.TransformerDecoderLayer(\n d_model=pretrain_config.hidden_size,\n nhead=pretrain_config.num_attention_heads,\n )\n decoder = nn.TransformerDecoder(\n decoder_layer, num_layers=cfg.num_decoder_layers\n )\n self.model = Seq2Seq(\n encoder=encoder,\n decoder=decoder,\n config=pretrain_config,\n beam_size=cfg.beam_size,\n max_length=cfg.max_target_length,\n sos_id=cfg.cls_token_id,\n eos_id=cfg.sep_token_id,\n )\n\n def forward(self, batch):\n # in lightning, forward defines the prediction/inference actions\n index, source_ids, target_ids, source_mask, target_mask = batch\n _, loss, num = self.model(\n source_ids=source_ids,\n source_mask=source_mask,\n target_ids=target_ids,\n target_mask=target_mask,\n )\n\n return loss\n\n def on_post_move_to_device(self) -> None:\n # To maintain compatibility with TPUs\n self.model.tie_weights()\n\n def training_step(self, batch, batch_idx):\n # training_step defined the train loop.\n # It is independent of forward\n loss, _, _ = self.model(\n source_ids=batch[\"source_ids\"],\n source_mask=batch[\"source_mask\"],\n target_ids=batch[\"target_ids\"],\n target_mask=batch[\"target_mask\"],\n )\n\n self.log(\"train/loss\", loss)\n return loss\n\n def validation_step(self, batch, *args):\n _, loss, num = self.model(\n source_ids=batch[\"source_ids\"],\n source_mask=batch[\"source_mask\"],\n target_ids=batch[\"target_ids\"],\n target_mask=batch[\"target_mask\"],\n )\n\n return {\"val_loss\": loss.sum().item(), \"tokens_num\": num.sum().item()}\n\n def validation_epoch_end(self, outputs: List[Any]) -> None:\n total_tokens = 0\n total_loss = 0\n for output in outputs:\n total_loss += output[\"val_loss\"]\n total_tokens += output[\"tokens_num\"]\n\n val_loss = total_loss / total_tokens\n val_ppl = round(np.exp(val_loss), 5)\n\n self.log(\"validation/ppl\", val_ppl)\n self.log(\"validation/loss\", val_loss)\n\n def test_step(self, batch, *args, **kwargs):\n index, source_ids, target_ids, source_mask, target_mask = batch\n preds = self.model(source_ids=source_ids, source_mask=source_mask)\n\n preds = preds[:, 0, :]\n return {\n \"preds\": preds,\n \"refs\": target_ids,\n \"index\": index,\n }\n\n def test_step_end(self, batch_parts):\n # Need this so that pytorch does not\n return batch_parts\n\n def predict_step(self, batch: Any, *args, **kwargs,) -> Any:\n preds = self.model(\n source_ids=batch[\"source_ids\"], source_mask=batch[\"source_mask\"]\n )\n preds = preds[:, 0, :].detach()\n\n return preds\n\n # def test_epoch_end(self, outputs: List[Any]) -> None:\n # try:\n # if self.hparams.save_test_output:\n # # gather results from different batches\n # preds = list(map(itemgetter(\"preds\"), outputs))\n # refs = np.array(list(map(itemgetter(\"refs\"), outputs)))\n # indices = list(map(itemgetter(\"index\"), outputs))\n # all_preds = [pred.cpu().numpy() for pred in preds]\n # all_refs = [ref.cpu().numpy() for ref in refs]\n # all_indices = [index.cpu().numpy() for index in indices]\n # all_preds = np.row_stack(all_preds)\n # all_refs = np.row_stack(all_refs)\n # all_indices = np.row_stack(all_indices)\n # with open(self.hparams.save_test_output, \"wb\") as outfile:\n # pickle.dump(\n # {\"preds\": all_preds, \"refs\": all_refs, \"index\": all_indices,},\n # outfile,\n # )\n # except Exception as e:\n # print()\n # print(f\"=>>>> Encountered exception\")\n # print(e)\n\n @property\n def num_training_steps(self) -> int:\n \"\"\"Total training steps inferred from datamodule and devices.\n\n Adapted from: https://github.com/PyTorchLightning/pytorch-lightning/issues/5449\n \"\"\"\n if self.trainer.max_steps:\n return self.trainer.max_steps\n\n limit_batches = self.trainer.limit_train_batches\n batches = len(self.train_dataloader())\n batches = (\n min(batches, limit_batches)\n if isinstance(limit_batches, int)\n else int(limit_batches * batches)\n )\n\n num_devices = max(1, self.trainer.num_gpus, self.trainer.num_processes)\n if self.trainer.tpu_cores:\n num_devices = max(num_devices, self.trainer.tpu_cores)\n\n effective_accum = self.trainer.accumulate_grad_batches * num_devices\n return (batches // effective_accum) * self.trainer.max_epochs\n\n def configure_optimizers(self):\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [\n p\n for n, p in self.model.named_parameters()\n if not any(nd in n for nd in no_decay)\n ],\n \"weight_decay\": self.cfg.weight_decay,\n },\n {\n \"params\": [\n p\n for n, p in self.model.named_parameters()\n if any(nd in n for nd in no_decay)\n ],\n \"weight_decay\": 0.0,\n },\n ]\n logger.warning(\n f\"total training steps: {self.num_training_steps}, warmup steps: {self.num_training_steps * self.cfg.warmup_steps}, lr: {self.cfg.lr}\"\n )\n optimizer = AdamW(\n optimizer_grouped_parameters, lr=self.cfg.lr, eps=self.cfg.adam_epsilon,\n )\n lr_scheduler = get_linear_schedule_with_warmup(\n optimizer,\n num_warmup_steps=int(self.num_training_steps * self.cfg.warmup_steps),\n num_training_steps=self.num_training_steps,\n )\n\n return [optimizer], [{\"scheduler\": lr_scheduler, \"interval\": \"step\"}]\n","sub_path":"src/summarization_models/models/codebert/codebert.py","file_name":"codebert.py","file_ext":"py","file_size_in_byte":8186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"28958491","text":"from flask import Flask\nfrom flask_restful import Api, Resource, reqparse\nfrom trained_model import TrainedModel as tm\n\napp = Flask(__name__)\napi = Api(app)\n\nclass GetResult(Resource):\n def get(self):\n parser = reqparse.RequestParser()\n parser.add_argument('sentence1', type=str)\n parser.add_argument('sentence2', type=str)\n req_data = parser.parse_args()\n sent1, sent2 = req_data[\"sentence1\"], req_data[\"sentence2\"]\n res = tm.predict(sent1, sent2)\n return {\"result\": res}\n\n# Add url resource\napi.add_resource(GetResult, '/')\n\nif __name__==\"__main__\":\n app.run(debug=True, host='0.0.0.0')\n","sub_path":"run_server.py","file_name":"run_server.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"445411051","text":"import cv2 as cv\nimport math\n\nfrom classes import Pixel\n\nINPUT_IMAGE = \"./img/img.png\"\nWINDOWSIZE = 15\n\ndef create_integral_image(img, height, width):\n intimg = [[Pixel(0,0,0) for x in range(width)] for y in range(height)]\n\n for h in range(height):\n for w in range(width):\n\n # apply sum to all pixels, except the first one\n if w == 0 and h == 0:\n intimg[h][w].b, intimg[h][w].g, intimg[h][w].r = int(img[h, w][0]), int(img[h, w][1]), int(img[h, w][2])\n else:\n # first row\n if h == 0:\n intimg[h][w].b = int(img[h, w][0]) + intimg[h][w-1].b\n intimg[h][w].g = int(img[h, w][1]) + intimg[h][w-1].g\n intimg[h][w].r = int(img[h, w][2]) + intimg[h][w-1].r\n\n # first column\n elif w == 0:\n intimg[h][w].b = int(img[h, w][0]) + intimg[h-1][w].b\n intimg[h][w].g = int(img[h, w][1]) + intimg[h-1][w].g\n intimg[h][w].r = int(img[h, w][2]) + intimg[h-1][w].r\n # others pixels\n else:\n intimg[h][w].b = int(img[h][w][0]) + intimg[h-1][w].b + intimg[h][w-1].b - intimg[h-1][w-1].b\n intimg[h][w].g = int(img[h][w][1]) + intimg[h-1][w].g + intimg[h][w-1].g - intimg[h-1][w-1].g\n intimg[h][w].r = int(img[h][w][2]) + intimg[h-1][w].r + intimg[h][w-1].r - intimg[h-1][w-1].r\n\n return intimg\n\n\ndef meanfilter_simple(img_original, img_blur, height, width, wsize):\n sum = [0,0,0]\n\n for h in range(height):\n for w in range(width):\n # Check if window size don't exceeds image margins\n if (w - int(math.floor(wsize/2)) >= 0 and h - int(math.floor(wsize/2)) >= 0) and (w + int(math.floor(wsize/2)) < width and h + int(math.floor(wsize/2)) < height):\n\n # Analyze every pixel on window\n for h_window in range(h - int(math.floor(wsize/2)), h + int(math.floor(wsize/2))):\n for w_window in range(w - int(math.floor(wsize/2)), w + int(math.floor(wsize/2))):\n pix = img_original[h_window][w_window]\n sum[0] += pix[0]\n sum[1] += pix[1]\n sum[2] += pix[2]\n\n # Apply blur on every channel\n img_blur[h][w] = [sum[0] / (wsize * wsize), sum[1] / (wsize * wsize), sum[2] / (wsize * wsize)]\n sum = [0,0,0]\n\n return img_blur\n\n\ndef meanfilter_integral(intimg, imgblur, height, width, wsize):\n wsize2 = int(math.floor(wsize/2))\n\n for h in range(height):\n for w in range(width):\n\n # Check if window size don't exceeds image margins\n if w - wsize2 >= 0 and h - wsize2 >= 0 and w + wsize2 < width and h + wsize2 < height:\n # finds the mean of all the 3 channels within window size\n\n imgblur[h, w][0] = round((intimg[h + wsize2][w + wsize2].b - intimg[h - wsize2][w + wsize2].b - intimg[h + wsize2][w - wsize2].b + intimg[h - wsize2][w - wsize2].b) / (wsize * wsize))\n imgblur[h, w][1] = round((intimg[h + wsize2][w + wsize2].g - intimg[h - wsize2][w + wsize2].g - intimg[h + wsize2][w - wsize2].g + intimg[h - wsize2][w - wsize2].g) / (wsize * wsize))\n imgblur[h, w][2] = round((intimg[h + wsize2][w + wsize2].r - intimg[h - wsize2][w + wsize2].r - intimg[h + wsize2][w - wsize2].r + intimg[h - wsize2][w - wsize2].r) / (wsize * wsize))\n \n else:\n # if window size exceeds image margins, apply a black background\n imgblur[h, w] = [0, 0, 0]\n\n return imgblur\n\n\ndef main ():\n img_original = cv.imread(INPUT_IMAGE)\n img_simple = cv.imread(INPUT_IMAGE)\n img_integral = cv.imread(INPUT_IMAGE)\n height, width, channel = img_original.shape\n\n # Apply simple mean filter\n img_simple = meanfilter_simple(img_original, img_simple, height, width, WINDOWSIZE)\n cv.imwrite('./img/01-simple.png', img_simple)\n\n # Apply divisible mean filter\n\n # Apply integral image mean filter\n auxintegral = create_integral_image(img_original, height, width)\n img_integral = meanfilter_integral(auxintegral, img_integral, height, width, WINDOWSIZE)\n cv.imwrite('./img/03-integral.png', img_integral)\n\n\nmain()","sub_path":"T2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"136518401","text":"from base import Definition\nfrom physics import PhysicsObject\n\nclass Reference(Definition):\n \"\"\"\n Sets reference within a tree definition. Syntax:\n (.)->\n \"\"\"\n\n def __init__(self, line):\n Definition.__init__(self, line, '([^ ]+)->([^ ]+)')\n self.ref_name = self.matches.group(1).split('.')\n self.target = self.matches.group(2)\n\n def write_def(self, out, objbranches):\n \"\"\"\n Part of the tree entry constructor code to pass the target collection pointer to the reference.\n \"\"\"\n\n if len(self.ref_name) == 1:\n out.writeline('{rname}Container_ = &{target};'.format(rname = '.'.join(self.ref_name), target = self.target))\n else:\n bname = self.ref_name[-2]\n branch = next(b for b in objbranches if b.name == bname)\n objdef = PhysicsObject.get(branch.objname)\n\n if objdef.is_singlet():\n out.writeline('{rname}Container_ = &{target};'.format(rname = '.'.join(self.ref_name), target = self.target))\n else:\n out.writeline('{rname}.data.{bname}Container_ = &{target};'.format(rname = '.'.join(self.ref_name[:-1]), bname = self.ref_name[-1], target = self.target))\n","sub_path":"lib/panda/reference.py","file_name":"reference.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"526925621","text":"class PluginLoader(object):\n def __init__(self, path):\n self._path = path\n\n def install(self):\n pass\n\n @property\n def uri(self):\n return self._path\n\n\nclass QMLPluginLoader(PluginLoader):\n def __init__(self, path):\n PluginLoader.__init__(self, path)\n\n\nclass PythonPluginLoader(PluginLoader):\n def __init__(self, path):\n PluginLoader.__init__(self, path)\n\n def install(self):\n from PySide2.QtQml import qmlRegisterType\n import importlib\n\n pkg = importlib.import_module(self._path)\n for export in pkg.qmlexports:\n qmlRegisterType(\n export['class'],\n export['uri'],\n export['major'],\n export['minor'],\n export['exportName']\n )\n\n\ndef scan_plugins(folder, prefix=''):\n import os\n from os import listdir\n\n ret = []\n for fn in listdir(folder):\n if os.path.isdir(os.path.join(folder, fn)):\n if os.path.isfile(os.path.join(folder, fn, '__init__.py')):\n ret.append(PythonPluginLoader('%s.%s' % (prefix, fn)))\n elif os.path.isfile(os.path.join(folder, fn, 'qmldir')):\n ret.append(QMLPluginLoader('%s.%s' % (prefix, fn)))\n else:\n ret += scan_plugins(os.path.join(folder, fn), fn)\n\n return ret\n","sub_path":"src/pyqmlapp/PluginLoader.py","file_name":"PluginLoader.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"228629128","text":"import shutil\n\ninfile = \"cleanlogfile.log\"\noutfile = \"cleanestlogfile.log\"\noriginal = r'cleanestlogfile.log'\ntarget = r'cleanlogfile.log'\n\ndelete_list = [\"already\"]\nwith open(infile) as fin, open(outfile, \"w+\") as fout:\n for line in fin:\n for word in delete_list:\n line = line.replace(word, \" already\")\n fout.write(line)\n\n\nshutil.copyfile(original, target)\n","sub_path":"step one/space.py","file_name":"space.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"496500872","text":"import itertools\n\nimport colorlabels as cl\nfrom decouple import config\nfrom github import Github\n\nfrom util import merge_whitespaces\n\ntry:\n gh = Github(config('GITHUB_ACCESS_TOKEN'))\nexcept Exception:\n cl.warning('GitHub access token is not correctly configured, '\n 'cannot retrieve GitHub data.')\n gh = None\n\n\ndef get_labels(issue):\n for label in issue.labels:\n yield label.name\n\n\ndef github_issue_repo_fetch(repo, since):\n if isinstance(repo, str):\n repo = gh.get_repo(repo)\n\n cl.plain('Fetching issues from repo: %s' % repo.full_name)\n\n for issue in repo.get_issues(state='all', since=since):\n yield {\n 'id': 'issue-%d' % issue.number,\n 'text': merge_whitespaces('%s %s' % (issue.title, issue.body)),\n 'type': 'pull' if issue.pull_request else 'issue',\n 'created_at': issue.created_at,\n 'updated_at': issue.updated_at,\n 'closed_at': issue.closed_at,\n 'labels': ','.join(get_labels(issue)),\n 'state': issue.state,\n 'from_issue': None,\n 'user_id': issue.user.id,\n 'user_login': issue.user.login,\n 'user_type': issue.user.type,\n 'user_site_admin': issue.user.site_admin\n }\n\n for comment in issue.get_comments(since=since):\n yield {\n 'id': 'comment-%d' % comment.id,\n 'text': merge_whitespaces(comment.body),\n 'type': 'comment',\n 'created_at': comment.created_at,\n 'updated_at': comment.updated_at,\n 'closed_at': None,\n 'labels': None,\n 'state': None,\n 'from_issue': issue.number,\n 'user_id': comment.user.id,\n 'user_login': comment.user.login,\n 'user_type': comment.user.type,\n 'user_site_admin': comment.user.site_admin\n }\n\n\ndef github_issue_org_fetch(org, since):\n org = gh.get_organization(org)\n return itertools.chain(*(\n github_issue_repo_fetch(repo, since) for repo in org.get_repos()))\n","sub_path":"scraper/github_api.py","file_name":"github_api.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"259264906","text":"#!/usr/bin/python\n# coding: utf-8\nimport sys\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GLUT import *\n\nfrom func import *\nimport variables as var\n\nimport math\n\nfrom Object.bullet import *\n\nDEG2RAD = math.pi/180\n\n# callback\ndef cb():\n var.clock_pre = var.clock_now\n var.clock_now = getClockNow()\n\n if var.play_flag == 1:\n var.day += (var.clock_now - var.clock_pre)*10\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n\n MoveSelf()\n\n # ズームイン・ズームアウト & 視点の移動\n gluLookAt(var.horizontal, var.vertical, var.orthogonal, var.horizontal+math.sin(var.yaw)*math.cos(var.pitch), var.vertical+math.sin(var.pitch), var.orthogonal-math.cos(var.yaw)*math.cos(var.pitch), 0.0, 1.0, 0.0)\n\n # 弾丸発射\n ShootBullet()\n\n glMaterialfv(GL_FRONT, GL_DIFFUSE, var.mat_default_color)\n glMaterialfv(GL_FRONT, GL_AMBIENT, var.mat_default_color)\n for i in range(len(var.planet_array)):\n if not var.planet_array[i].orbit_rad == 0:\n DrawCircle(var.planet_array[i].orbit_rad)\n # DrawCircle(var.orbit_radius_mercury)\n # DrawCircle(var.orbit_radius_venus)\n # DrawCircle(var.orbit_radius_earth)\n # DrawCircle(var.orbit_radius_mars)\n\n # glMaterialfv(GL_FRONT, GL_DIFFUSE, [1.0,0.0,0.8,1.0])\n # glMaterialfv(GL_FRONT, GL_AMBIENT, [1.0,0.0,0.0,1.0])\n # glBegin(GL_LINE_STRIP)\n # glVertex3f(0.0,0.3,0.0)\n # glVertex3f(100.0,0.3,0.0)\n # glEnd()\n\n # glMaterialfv(GL_FRONT, GL_DIFFUSE, [0.8,1.0,0.0,1.0])\n # glMaterialfv(GL_FRONT, GL_AMBIENT, [0.0,1.0,0.0,1.0])\n # glBegin(GL_LINE_STRIP)\n # glVertex3f(0.0,0.3,0.0)\n # glVertex3f(0.0,100.0,0.0)\n # glEnd()\n\n # glMaterialfv(GL_FRONT, GL_DIFFUSE, [0.0,0.8,1.0,1.0])\n # glMaterialfv(GL_FRONT, GL_AMBIENT, [0.0,0.0,1.0,1.0])\n # glBegin(GL_LINE_STRIP)\n # glVertex3f(0.0,0.3,0.0)\n # glVertex3f(0.0,0.3,100.0)\n # glEnd()\n\n glPushMatrix() #level01\n\n # 太陽\n # glMaterialfv(GL_FRONT, GL_AMBIENT, var.mat_color_sun)\n # glMaterialfv(GL_FRONT, GL_DIFFUSE, var.mat_color_sun)\n\n # glPushMatrix() #level02\n # glRotatef(var.rot_vel_sun * var.day, 0.0, 1.0, 0.0)\n # DrawPlanet(var.radius_sun)\n # glPopMatrix() #level02\n\n for i in range(len(var.planet_array)):\n var.planet_array[i].draw()\n\n # # 水星\n # glPushMatrix() #level02\n\n # glRotatef(var.rev_vel_mercury * var.day, 0.0, 1.0, 0.0)\n # glTranslatef(var.orbit_radius_mercury, 0.0, 0.0)\n # glRotatef(var.rot_vel_mercury * var.day, 0.0, 1.0, 0.0)\n\n # glMaterialfv(GL_FRONT, GL_AMBIENT, var.mat_color_mercury)\n # glMaterialfv(GL_FRONT, GL_DIFFUSE, var.mat_color_mercury)\n\n # DrawPlanet(var.planet_radius_mercury)\n\n # glPopMatrix() #level02\n\n # # 金星\n # glPushMatrix() #level02\n\n # glRotatef(var.rev_vel_venus * var.day, 0.0, 1.0, 0.0)\n # glTranslatef(var.orbit_radius_venus, 0.0, 0.0)\n # glRotatef(var.rot_vel_venus * var.day, 0.0, 1.0, 0.0)\n\n # glMaterialfv(GL_FRONT, GL_AMBIENT, var.mat_color_venus)\n # glMaterialfv(GL_FRONT, GL_DIFFUSE, var.mat_color_venus)\n\n # DrawPlanet(var.planet_radius_venus)\n\n # glPopMatrix() #level02\n\n # # 地球\n # glPushMatrix() #level02\n\n # glRotatef(var.rev_vel_earth * var.day, 0.0, 1.0, 0.0)\n # glTranslatef(var.orbit_radius_earth, 0.0, 0.0)\n # glRotatef(var.rot_vel_earth * var.day, 0.0, 1.0, 0.0)\n\n # glMaterialfv(GL_FRONT, GL_AMBIENT, var.mat_color_earth)\n # glMaterialfv(GL_FRONT, GL_DIFFUSE, var.mat_color_earth)\n\n # DrawPlanet(var.planet_radius_earth)\n\n # # 月\n # glPushMatrix() #level03\n\n # glRotatef(var.rev_vel_moon * var.day, math.cos(math.pi/3), math.sin(math.pi/3), 0.0)\n # glTranslatef(0.0, 0.0, var.orbit_radius_moon)\n # glRotatef(var.rot_vel_moon * var.day, 0.0, 1.0, 0.0)\n\n # glMaterialfv(GL_FRONT, GL_AMBIENT, var.mat_color_moon)\n # glMaterialfv(GL_FRONT, GL_DIFFUSE, var.mat_color_moon)\n\n # DrawPlanet(var.planet_radius_moon)\n\n # glPopMatrix() #level03\n\n # glPopMatrix() #level02\n\n # # 火星\n # glPushMatrix() #level02\n\n # glRotatef(var.rev_vel_mars * var.day, 0.0, 1.0, 0.0)\n # glTranslatef(var.orbit_radius_mars, 0.0, 0.0)\n # glRotatef(var.rot_vel_mars * var.day, 0.0, 1.0, 0.0)\n\n # glMaterialfv(GL_FRONT, GL_AMBIENT, var.mat_color_mars)\n # glMaterialfv(GL_FRONT, GL_DIFFUSE, var.mat_color_mars)\n\n # DrawPlanet(var.planet_radius_mars)\n\n # glPopMatrix() #level02\n\n glPopMatrix() #level01\n\n glutSwapBuffers()\n\n\n\ndef DrawCircle(radius):\n glBegin(GL_LINE_LOOP)\n\n for i in range(360):\n degInRad = i * DEG2RAD\n glVertex3f(math.cos(degInRad)*radius, 0.0, math.sin(degInRad)*radius)\n\n glEnd()\n\ndef DrawPlanet(radius):\n glPushMatrix()\n\n glRotatef(90.0, 1.0, 0.0, 0.0)\n glutWireSphere(radius, 20, 20)\n\n glPopMatrix()\n\ndef MoveSelf():\n var.horizontal += var.speed * var.horizontal_flag * math.cos(var.yaw) + var.speed * var.orthogonal_flag * math.sin(var.yaw)\n var.orthogonal += var.speed * var.horizontal_flag * math.sin(var.yaw) - var.speed * var.orthogonal_flag * math.cos(var.yaw)\n\ndef ShootBullet():\n if var.shoot_flag==1 and var.shoot_lock==0:\n for i in range(3):\n if var.shoot_array[i].shot_flag == 0:\n var.shoot_array[i].shot_flag = 1\n var.shoot_array[i].set_pos()\n var.shoot_array[i].set_vel()\n var.shoot_lock = 1\n break\n for i in range(3):\n if var.shoot_array[i].shot_flag == 1:\n var.shoot_array[i].move()\n var.shoot_array[i].judge()\n\n\n\n\n\n\n\n\n\n","sub_path":"game-project/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":5626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"144309967","text":"from Rojas import libreria\n\ndef agregar_libro():\n libro=libreria.pedir_nombre(\"Agregar el nombre del libro: \")\n autor=libreria.pedir_nombre(\"Agregar el nombre del autor(a): \")\n neto=libro+\"-\"+autor+\"\\n\"\n libreria.guardar_datos(\"libros.txt\",neto,\"a\")\n print(\"contenido agregado\")\n\ndef ber_libros():\n vovo=libreria.obtener_datos(\"libros.txt\")\n print(vovo)\n\noppcn=0\nlimit=3\nwhile (oppcn != limit):\n print(\"########################\")\n print(\"# LIBROS #\")\n print(\"########################\")\n print(\"# 1. Agregar libro #\")\n print(\"# 2. Ver agregados #\")\n print(\"# 3. Salir #\")\n print(\"########################\")\n\n oppcn=libreria.pedir_numero(\"Ingrese la opcion deseada: \",1,3)\n if (oppcn == 1):\n agregar_libro()\n\n if (oppcn == 2):\n ber_libros()\n\nprint(\"fin del programa\")\n","sub_path":"rojas/app8.py","file_name":"app8.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"287905840","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport json # natif à python3\nimport socket\nimport sys\nimport time\nimport xml\n\nimport sl4a\n\nimport dicttoxml # pip3 install dicttoxml\nimport xmltodict # pip3 install xmltodict\n\n\nclass JSONParser:\n def __init__(self):\n pass\n\n def encode(self, aDict):\n return json.dumps(aDict)\n\n def decode(self, aJson):\n return json.loads(aJson)\n\n\nclass XMLParser:\n def __init__(self):\n pass\n\n def encode(self, aDict):\n if 'action' in aDict:\n return '<'+str(aDict['action'])+' />';\n elif 'salutation' in aDict:\n return '<'+str(aDict['salutation'])+' />';\n return str(dicttoxml.dicttoxml(aDict, attr_type=False))[47:-8]\n def decode(self, aXml):\n data = xmltodict.parse(aXml)\n ##data = json.loads(json.dumps(data))\n if list(data.values())[0] == None:\n mergedData = {'reponse':list(data.keys())[0]}\n return mergedData\n return data\n\n\nfrom serveur.file_system import *\n\n\nclass StandardStream:\n def print(self, data):\n print(data)\n\n def input(self, aString):\n return input(aString)\n\n\nclass DropboxServer:\n MAX_RECV = 1024 * 1024 * 512\n\n def __init__(self, host, port, parser):\n self.parser = parser\n self.socket = socket.socket()\n try:\n self.socket.connect((host, port))\n except:\n print('Erreur de connexion, vérifiez que le serveur est bien lancé')\n sys.exit(1)\n\n def send(self, data):\n parsedData = self.parser.encode(data)\n #print(parsedData)\n utf8Data = parsedData.encode(encoding='UTF-8')\n self.socket.send(utf8Data)\n\n def response(self):\n receivedData = self.socket.recv(DropboxServer.MAX_RECV).decode('UTF-8')\n unparsedData = self.parser.decode(receivedData)\n return unparsedData\n\n def close(self):\n self.socket.close()\n\n\nclass DropboxClient:\n def __init__(self, server, fileSystem, ioStream, interrupt):\n self.server = server\n self.interruptServer = interrupt[0]\n self.fileSystem = fileSystem\n self.interrupt = interrupt[1]\n self.ioStream = ioStream\n self.envDict = dict()\n\n def connect(self, isPrompt):\n if isPrompt:\n self.prompting()\n else:\n\n self.syncronize()\n\n def prompting(self):\n self.ioStream.print('Bienvenue dans la ligne de commande du client Dropbox!')\n command = ''\n try:\n while 1:\n self.ioStream.print('Commande:')\n command = self.ioStream.input('')\n\n #connecter?\n if command == 'connecter?':\n self.server.send({'salutation': 'bonjourServeur'})\n data = self.server.response()\n if list(data.values())[0] == 'bonjourClient':\n self.ioStream.print('Oui')\n else:\n self.ioStream.print('Non')\n\n #nomServeur?\n elif command == 'nomServeur?':\n self.server.send({'action': 'questionNomServeur'})\n data = self.server.response()\n self.ioStream.print(data['nomServeur'])\n\n #listeDossier?\n elif command == 'listeDossier?':\n data = self.getDirListServer('./')\n if 'reponse' in data:\n if data['reponse'] == 'erreurDossierInexistant':\n self.ioStream.print('Le dossier n\\'existe pas')\n elif data['reponse'] == 'erreurDossierLecture':\n self.ioStream.print('Vous n\\'avez pas l\\'acces')\n else:\n self.ioStream.print(data)\n\n #listeFichier?\n elif command == 'listeFichier?':\n self.ioStream.print(self.getFileListServer('./'))\n\n #dossier?\n elif command.split(' ', 1)[0] == 'dossier?':\n data = self.existDirServer(command.split(' ', 1)[1])\n if data:\n self.ioStream.print('Oui')\n else:\n self.ioStream.print('Non')\n\n #creerDossier?\n elif command.split(' ', 1)[0] == 'creerDossier?':\n data = self.addDirServer(command.split(' ', 1)[1])\n if data['reponse'] == 'erreurDossierExiste':\n self.ioStream.print('Dossier existe déjà.')\n else:\n self.ioStream.print('Oui')\n\n #televerser?\n elif command.split(' ', 1)[0] == 'televerser?':\n filePath = command.split(' ', 1)[1]\n if not self.fileSystem.dirExists(self.fileSystem.getDirName(filePath)):\n self.ioStream.print('Dossier n\\'existe pas')\n elif not self.fileSystem.fileExists(filePath):\n self.ioStream.print('Fichier n\\'existe pas')\n else:\n data = self.addFileServer(filePath)\n if data['reponse'] == 'erreurDossierInexistant':\n self.ioStream.print('Dossier n\\'existe pas')\n elif data['reponse'] == 'erreurFichierExiste':\n self.ioStream.print('Fichier existe déjà.')\n elif data['reponse'] == 'ok':\n self.ioStream.print('Ok')\n else:\n self.ioStream.print('Erreur lors de l\\'envoie. Les signatures ne concordent pas.')\n\n #telecharger?\n elif command.split(' ', 1)[0] == 'telecharger?':\n filePath = command.split(' ', 1)[1]\n data = self.addFileClient(filePath)\n\n if 'reponse' in data:\n if data['reponse'] == 'erreurFichierInexistant':\n self.ioStream.print('Fichier n\\'existe pas.')\n elif data['reponse'] == 'erreurFichierLecture':\n self.ioStream.print('Vous n\\'avez pas l\\'acces')\n elif self.fileSystem.getSignature(self.fileSystem.decode64(data['fichier']['contenu'])) != data['fichier']['signature']:\n self.ioStream.print('Erreur lors de l\\'envoie. Les signatures ne concordent pas.')\n else:\n self.ioStream.print('Ok')\n\n #supprimerDossier?\n elif command.split(' ', 1)[0] == 'supprimerDossier?':\n filePath = command.split(' ', 1)[1]\n data = self.removeDirServer(filePath)\n if data['reponse'] == 'erreurDossierInexistant':\n self.ioStream.print('Dossier n\\'existe pas.')\n elif data['reponse'] == 'erreurDossierLecture':\n self.ioStream.print('Vous n\\'avez pas l\\'acces')\n else:\n self.ioStream.print('Ok')\n\n #supprimerFichier?\n elif command.split(' ', 1)[0] == 'supprimerFichier?':\n filePath = command.split(' ', 1)[1]\n data = self.removeFileServer(filePath)\n if data['reponse'] == 'erreurFichierInexistant':\n self.ioStream.print('Fichier n\\'existe pas.')\n elif data['reponse'] == 'erreurFichierLecture':\n self.ioStream.print('Vous n\\'avez pas l\\'acces')\n else:\n self.ioStream.print('Ok')\n\n #fichier?\n elif command.split(' ', 1)[0] == 'fichier?':\n data = self.existsFileServer(command.split(' ', 1)[1])\n if data:\n self.ioStream.print('Oui')\n else:\n self.ioStream.print('Non')\n\n #identiqueFichier?\n elif command.split(' ', 1)[0] == 'identiqueFichier?':\n filePath = command.split(' ', 1)[1]\n data = self.sameFile(filePath)\n if data == True:\n self.ioStream.print('Oui')\n elif data == False:\n self.ioStream.print('Non')\n elif data['reponse'] == 'erreurFichierInexistant':\n self.ioStream.print('Fichier n\\'existe pas.')\n else:\n self.ioStream.print('Vous n\\'avez pas l\\'acces')\n\n #fichierRecent?\n elif command.split(' ', 1)[0] == 'fichierRecent?':\n filePath = command.split(' ', 1)[1]\n data = self.clientMoreRecent(filePath)\n if data == False:\n self.ioStream.print('Non')\n elif data == True:\n self.ioStream.print('Oui')\n elif data['reponse'] == 'erreurFichierInexistant':\n self.ioStream.print('Fichier n\\'existe pas.')\n else:\n self.ioStream.print('Vous n\\'avez pas l\\'acces')\n\n #miseAjour?\n elif command.split(' ', 1)[0] == 'miseAjour?':\n filePath = command.split(' ', 1)[1]\n if self.fileSystem.dirExists(filePath):\n self.reload(filePath)\n self.ioStream.print('Ok')\n else:\n self.ioStream.print('Dossier n\\'existe pas.')\n\n #quitter\n elif command == 'quitter':\n self.server.send({'action': 'quitter'})\n data = self.server.response()\n if data == {'reponse': 'bye'}:\n self.ioStream.print('Bye')\n else:\n self.ioStream.print('Erreur lors de la déconnection, arrêt du client...')\n break\n\n else:\n self.ioStream.print('commande inconnue')\n\n except (ValueError, KeyboardInterrupt, xml.parsers.expat.ExpatError) as error:\n pass\n\n self.server.close()\n self.ioStream.print('Connexion Perdue')\n\n\n def syncronize(self):\n self.ioStream.print('Reloading...')\n self.ioStream.print('Ctrl+C to stop reloading')\n if self.interrupt is not None:\n self.reload('.')\n self.interrupt.connect(self.fileSystem.getPath(), self)\n try:\n while 1:\n data = self.interruptServer.response()\n self.reload(data['invalidate'])\n\n except (KeyboardInterrupt, ValueError, xml.parsers.expat.ExpatError) as err:\n pass\n self.interrupt.disconnect()\n self.server.close()\n self.ioStream.print('\\nConnexion Perdue')\n\n else:\n try:\n while 1:\n self.reload('.')\n time.sleep(5)\n except (KeyboardInterrupt, ValueError, xml.parsers.expat.ExpatError) as err:\n pass\n self.server.close()\n self.ioStream.print('\\nConnexion Perdue')\n\n def reload(self, path):\n \"\"\"\n faire un dictionnaire qui se rappel des derniers fichiers et dossiers\n ce dictionnaire est sauvegardé dans le fichier clientDropBox.conf\n il est sous la forme:\n [{'./':''}, {'./d1':''}, {'./f1.txt':'md5'}]\n il y a aussi sauvegardé le fichier racine du client\n fonctions nécessaires:\n \"\"\"\n if self.fileSystem.isFiltered(path):\n return\n\n fc = self.existFileClient(path)\n fs = self.existFileServer(path)\n fe = self.existFileEnv(path)\n\n dc = self.existDirClient(path)\n ds = self.existDirServer(path)\n de = self.existDirEnv(path)\n\n\n self.ioStream.print('Reloading: ' + path)\n print(\"fc: \"+str(fc))\n print(\"fe: \"+str(fe))\n print(\"fs: \"+str(fs))\n print(\"dc: \"+str(dc))\n print(\"de: \"+str(de))\n print(\"ds: \"+str(ds))\n\n\n #File manager\n if fc or fs or fe:\n\n if not fc and not fs:\n self.removeFileEnv(path)\n elif not fc and not fe:\n self.addFileClient(path)\n self.addFileEnv(path)\n elif not fs and not fe:\n self.addFileServer(path)\n self.addFileEnv(path)\n elif not fc:\n self.removeFileServer(path)\n self.removeFileEnv(path)\n elif not fs:\n self.removeFileClient(path)\n self.removeFileEnv(path)\n else:\n if not self.sameFile(path):\n if self.clientMoreRecent(path):\n self.removeFileServer(path)\n self.addFileServer(path)\n self.addFileEnv(path)\n else:\n self.removeFileClient(path)\n self.addFileClient(path)\n self.addFileEnv(path)\n\n\n #Directory manager\n elif dc or ds or de:\n if not dc and not ds:\n self.removeDirEnv(path)\n return\n elif not dc and not de:\n self.addDirClient(path)\n self.addDirEnv(path)\n elif not ds and not de:\n self.addDirServer(path)\n self.addDirEnv(path)\n elif not dc:\n self.removeDirServer(path)\n self.removeDirEnv(path)\n return\n elif not ds:\n self.removeDirClient(path)\n self.removeDirEnv(path)\n return\n elif not de:\n self.addDirEnv(path)\n pathList = set()\n pathList.update(self.getFileListServer(path))\n pathList.update(self.getFileListClient(path))\n pathList.update(self.getDirListServer(path))\n pathList.update(self.getDirListClient(path))\n for element in pathList:\n self.reload(element)\n\n\n def getFileListServer(self,path):\n self.server.send({'questionListeFichiers': path})\n data=self.server.response()\n print(data)\n if 'listeFichiers' not in data:\n return []\n data=data['listeFichiers']['fichier']\n if data == None:\n return []\n elif isinstance(data, str):\n return [path+'/'+data]\n elif 'item' in data:\n if isinstance(data['item'], list):\n index = 0\n while index < len(data['item']):\n data['item'][index]=path+'/'+data['item'][index]\n index+=1\n return data['item']\n else:\n return [path+'/'+str(data['item'])]\n index = 0\n while index < len(data):\n data[index]=path+'/'+data[index]\n index+=1\n return data\n\n def getFileListClient(self,path):\n return self.fileSystem.getFileList(path)\n\n def getDirListServer(self,path):\n self.server.send({'questionListeDossiers': path})\n data = self.server.response()\n if 'reponse' in data:\n return data\n else:\n data = data['listeDossiers']['dossier']\n print(data)\n if data == None:\n return []\n elif isinstance(data, str):\n return [path+'/'+data]\n elif 'item' in data:\n if isinstance(data['item'], list):\n index = 0\n while index < len(data['item']):\n data['item'][index]=path+'/'+data['item'][index]\n index+=1\n return data['item']\n else:\n return [path+'/'+str(data['item'])]\n index = 0\n while index < len(data):\n data[index]=path+'/'+data[index]\n index+=1\n return data\n\n def getDirListClient(self,path):\n return self.fileSystem.getDirList(path)\n\n def addFileServer(self, path):\n self.server.send({'televerserFichier': {'nom': self.fileSystem.getFileName(path),\n 'dossier': self.fileSystem.getDirName(path),\n 'signature': self.fileSystem.getSignature(self.fileSystem.getContent(path)),\n 'contenu': self.fileSystem.encode64(self.fileSystem.getContent(path)).decode('UTF-8'),\n 'date': self.fileSystem.getDate(path)}})\n return self.server.response()\n\n def addFileClient(self, path):\n self.server.send({'telechargerFichier': {'nom': self.fileSystem.getFileName(path),\n 'dossier': self.fileSystem.getDirName(path)}})\n data = self.server.response()\n if 'reponse' in data:\n return data\n elif self.fileSystem.getSignature(self.fileSystem.decode64(data['fichier']['contenu'].encode(encoding='UTF-8'))) != data['fichier']['signature']:\n return data\n self.fileSystem.setContent(path, self.fileSystem.decode64(data['fichier']['contenu'].encode(encoding='UTF-8')))\n self.fileSystem.setUTime(path, data['fichier']['date'])\n return data\n\n def addFileEnv(self, path):\n self.envDict[path] = 'f'\n\n\n def removeFileServer(self, path):\n self.server.send({'supprimerFichier': {'nom': self.fileSystem.getFileName(path),\n 'dossier': self.fileSystem.getDirName(path)}})\n return self.server.response()\n\n def removeFileClient(self, path):\n self.fileSystem.removeFile(path)\n\n def removeFileEnv(self, path):\n del self.envDict[path]\n\n def addDirServer(self, path):\n self.server.send({'creerDossier': path})\n return self.server.response()\n\n def addDirClient(self, path):\n self.fileSystem.createDir(path)\n\n def addDirEnv(self, path):\n self.envDict[path] = 'd'\n\n def removeDirServer(self, path):\n dirs=self.getDirListServer(path)\n for dir in dirs:\n self.removeDirServer(dir)\n files=self.getFileListServer(path)\n for file in files:\n self.removeFileServer(file)\n self.server.send({'supprimerDossier': path})\n return self.server.response()\n\n def removeDirClient(self, path):\n self.fileSystem.removeDir(path)\n\n def removeDirEnv(self, path):\n del self.envDict[path]\n\n def existFileServer(self, path):\n if self.fileSystem.getDirName(path)=='':\n path='./'\n self.server.send({'questionListeFichiers': self.fileSystem.getDirName(path)})\n data = self.server.response()\n if 'listeFichiers' in data and data['listeFichiers']['fichier']!= None:\n if self.fileSystem.getFileName(path) in data['listeFichiers']['fichier']:\n return True\n return False\n\n def existFileClient(self, path):\n return self.fileSystem.fileExists(path)\n\n def existFileEnv(self, path):\n if path in self.envDict:\n return self.envDict[path]=='f'\n return False\n\n def existDirServer(self, path):\n self.server.send({'questionListeDossiers': path})\n data = self.server.response()\n if 'reponse' in data:\n if data['reponse'] == 'erreurDossierInexistant':\n return False\n return True\n\n def existDirClient(self, path):\n return self.fileSystem.dirExists(path)\n\n def existDirEnv(self, path):\n #return path in self.envDict\n if path in self.envDict:\n return self.envDict[path]=='d'\n return False\n\n def clientMoreRecent(self, path):\n self.server.send({'questionFichierRecent': {'nom': self.fileSystem.getFileName(path),\n 'dossier': self.fileSystem.getDirName(path),\n 'date': self.fileSystem.getDate(path)}})\n data = self.server.response()\n if data['reponse'] == 'oui':\n return True\n elif data['reponse'] == 'non':\n return False\n return data\n\n def sameFile(self, path):\n self.server.send({'questionFichierIdentique': {'nom': self.fileSystem.getFileName(path),\n 'dossier': self.fileSystem.getDirName(path),\n 'signature': self.fileSystem.getSignature(\n self.fileSystem.getContent(path)),\n 'date': self.fileSystem.getDate(path)}})\n data = self.server.response()\n if data['reponse']=='oui':\n return True\n elif data['reponse']=='non':\n return False\n return data\n\n\n def help(self):\n self.ioStream.print('help')\n\ndef welcome_message():\n title = 'Client Dropbox'\n message = 'Bienvenue dans Dropbox'\n droid = sl4a.Android()\n droid.dialogCreateAlert(title, message)\n droid.dialogSetPositiveButtonText('Commencer')\n droid.dialogShow()\n response = droid.dialogGetResponse().result\n return response['which'] == 'positive'\n\ndef ask_user_ip():\n title = 'Ip address'\n message = ('Enter the ip address.')\n placeholder = '159.203.9.85'\n droid = sl4a.Android()\n droid.dialogCreateInput(title, message, placeholder)\n droid.dialogSetPositiveButtonText('Next')\n droid.dialogShow()\n response = droid.dialogGetResponse().result\n return response['value']\n\n\ndef ask_user_port():\n title = 'Port'\n message = ('Enter the port')\n placeholder = '60000'\n droid = sl4a.Android()\n droid.dialogCreateInput(title, message, placeholder)\n droid.dialogSetPositiveButtonText('Next')\n droid.dialogShow()\n response = droid.dialogGetResponse().result\n return response['value']\n\n\ndef ask_user_parser():\n title = 'Parser'\n droid = sl4a.Android()\n droid.dialogCreateAlert(title)\n droid.dialogSetItems(['JSON', 'XML'])\n droid.dialogShow()\n response = droid.dialogGetResponse().result\n return response\n\ndef ask_menu_to_user():\n title = 'Menu'\n droid = sl4a.Android()\n droid.dialogCreateAlert(title)\n droid.dialogSetItems(['Mise à jour', 'Tout supprimer'])\n droid.dialogShow()\n response = droid.dialogGetResponse().result\n return response\n\n\nif __name__ == '__main__':\n\n welcome_message()\n\n HOST = ask_user_ip()\n PORT = int(ask_user_port())\n if ask_user_parser()['item'] == 0:\n parser = JSONParser()\n else:\n parser = XMLParser()\n\n server = DropboxServer(HOST, PORT, parser)\n interrupt = (None, None)\n fileSystem = FileSystem('/storage/emulated/legacy/com.hipipal.qpyplus/projects3/Client/')\n ioStream = StandardStream()\n client = DropboxClient(server, fileSystem, ioStream, interrupt)\n while 1:\n choice = ask_menu_to_user()\n if choice['item'] == 0:\n client.reload('.')\n else:\n client.reload('.')\n client.removeDirClient('')\n client.addDirClient('')\n client.reload('.')\n\n server.close()\n","sub_path":"android_client_tp4.py","file_name":"android_client_tp4.py","file_ext":"py","file_size_in_byte":23627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"536635551","text":"# -*- coding: utf-8 -*-\n# training the model.\n# modified: lzw\n# reference: brightmart/text_classification (\n# https://github.com/brightmart/text_classification)\n# description: textrnn handle sentiment classification\n# handle vocabulary size, drop too rare word and too frequent word( if in stopwords )\n\nimport os\nimport sys\n\nsys.path.insert(0, \"../\")\nimport numpy as np\nimport tensorflow as tf\n# from data_util_zhihu import load_data_multilabel_new,create_voabulary,create_voabulary_label\nfrom tflearn.data_utils import pad_sequences, shuffle # to_categorical\nfrom _textcnn.textcnn_model import TextCNN\nfrom data_helper import load_text_label, split_file_classes, load_text_label_test, load_obj, generate_texts2indexes\nimport jieba\nimport logging\nimport pickle\n\n# configuration\nFLAGS = tf.app.flags.FLAGS\ntf.app.flags.DEFINE_integer(\"num_classes\", 2, \"number of label\")\ntf.app.flags.DEFINE_float(\"learning_rate\", 0.01, \"learning rate\")\ntf.app.flags.DEFINE_integer(\"batch_size\", 128, \"Batch size for training/evaluating.\") # 批处理的大小 32-->128\ntf.app.flags.DEFINE_integer(\"decay_steps\", 1000, \"how many steps before decay learning rate.\")\ntf.app.flags.DEFINE_float(\"decay_rate\", 0.9, \"Rate of decay for learning rate.\")\ntf.app.flags.DEFINE_string(\"ckpt_dir\", \"text_cnn_checkpoint/\", \"checkpoint location for the model\")\ntf.app.flags.DEFINE_integer(\"sequence_length\", 30, \"max sentence length\")\ntf.app.flags.DEFINE_integer(\"embed_size\", 300, \"embedding size\")\ntf.app.flags.DEFINE_boolean(\"is_training\", True, \"is traning.true:tranining,false:testing/inference\")\ntf.app.flags.DEFINE_integer(\"num_epochs\", 60, \"embedding size\")\ntf.app.flags.DEFINE_integer(\"validate_every\", 10, \"Validate every validate_every epochs.\") # 每10轮做一次验证\ntf.app.flags.DEFINE_boolean(\"use_embedding\", True, \"whether to use embedding or not.\")\ntf.app.flags.DEFINE_integer(\"num_filters\", 64, \"cnn filter size\")\ntf.app.flags.DEFINE_string(\"traning_data_path\", \"\", \"path of traning data.\")\ntf.app.flags.DEFINE_string(\"pretrained_word_embeddings_path\",\n \"../_gensim_support/vocabulary/new_word2vec_12.3w.pkl\",\n \"word2vec's vocabulary and vectors\")\ntf.app.flags.DEFINE_string(\"cache_path\", \"cache/tmp_cache.save\", \"for tmp data reload.\")\ntf.app.flags.DEFINE_boolean(\"multi_label_flag\",False,\"use multi label or single label.\")\ntf.app.flags.DEFINE_integer(\"tolerance\",5,\"early stop of training.\")\ntf.app.flags.DEFINE_float(\"eplison\",1e-4,\"how much to set as an improvement\")\nfilter_sizes=[1,2,3,4,5,6,7]\n\ndef main(_):\n jieba.load_userdict('../dataset/digital_forum/digital_selfdict.txt')\n\n if os.path.exists(FLAGS.cache_path):\n with open(FLAGS.cache_path, 'rb') as data_f:\n trainX, trainY, devX, devY, testX, testY, word2vec_dict, index2word, label_index = pickle.load(data_f)\n vocab_size = len(index2word)\n else:\n\n \"\"\" load texts \"\"\"\n classes_path = '../dataset/digital_forum/classes/'\n label_index, class_name_count = split_file_classes('../dataset/digital_forum/all.txt',\n '../dataset/digital_forum/classes/')\n split = [0.7, 0.3]\n corpus, train_len_total, dev_len_total = load_text_label(classes_path, class_name_count, label_index, split,\n shuffle=True)\n corpus_train = [d for d in corpus if d.split == 'train']\n corpus_dev = [d for d in corpus if d.split == 'dev']\n corpus_unk = [d for d in corpus if d.split == 'UNK'] # sentences with unknown label # corpus_len = len(corpus)\n print('train texts num: %d' % (train_len_total))\n print('dev texts num: %d' % (dev_len_total))\n print('unk texts num %d' % (len(corpus_unk)))\n\n \"\"\" load test texts \"\"\"\n test_filepath = '../dataset/digital_forum/测试集3_联想_杨欣标注15000_20171116 (2).txt'\n corpus_test = load_text_label_test(test_filepath, label_index)\n # test_labels = [d.label for d in corpus_test]\n # test_negative_len = len([d for d in corpus_test if d.label == 0])\n\n \"\"\"\n using a corpus or a built vocabulary.\n \"\"\"\n use_pretrained_word_embeddings = True\n if use_pretrained_word_embeddings:\n pretrained_word_embeddings_path = FLAGS.pretrained_word_embeddings_path\n logging.info(\n \"using pre-trained word embeddings, word2vec_model_path: {}\".format(pretrained_word_embeddings_path))\n word2vec_dict = load_obj(pretrained_word_embeddings_path)\n word2index = {'_UNK_': 0, '_NULL_': 1}\n for i, k_v in enumerate(word2vec_dict.items()):\n word2index[k_v[0]] = i + 2\n index2word = dict(zip(word2index.values(), word2index.keys()))\n vocab_size = len(index2word)\n\n trainX = generate_texts2indexes(input_data=[d.words for d in corpus_train],\n word2index=word2index)\n trainY = [d.label for d in corpus_train]\n devX = generate_texts2indexes(input_data=[d.words for d in corpus_dev],\n word2index=word2index)\n devY = [d.label for d in corpus_dev]\n testX = generate_texts2indexes(input_data=[d.words for d in corpus_test],\n word2index=word2index)\n testY = [d.label for d in corpus_test]\n\n # 2.Data preprocessing.Sequence padding; why pad behind?\n print(\"start padding & transform to one hot...\")\n trainX = pad_sequences([t.word_indexes for t in trainX], maxlen=FLAGS.sequence_length,\n value=0.) # padding to max length\n devX = pad_sequences([t.word_indexes for t in devX], maxlen=FLAGS.sequence_length,\n value=0.) # padding to max length\n testX = pad_sequences([t.word_indexes for t in testX], maxlen=FLAGS.sequence_length,\n value=0.) # padding to max length\n # print(testY)\n ###############################################################################################\n with open(FLAGS.cache_path, 'wb') as data_f: # save data to cache file, so we can use it next time quickly.\n pickle.dump((trainX, trainY, devX, devY, testX, testY, word2vec_dict, index2word, label_index), data_f)\n ###############################################################################################\n print(\"trainX[0]:\", trainX[0]) # ;print(\"trainY[0]:\", trainY[0])\n print(\"end padding & transform to one hot...\")\n exit()\n\n class_weights = tf.constant([0.75, 0.25])\n train(trainX, trainY, devX, devY, testX, testY, word2vec_dict, index2word, vocab_size, FLAGS.embed_size,\n label_index,class_weights)\n\n\ndef train(trainX, trainY, devX, devY, testX, testY, word2vec_dict, index2word, vocab_size, embed_size, label_index,class_weights):\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n\n textcnn = TextCNN(filter_sizes,\n FLAGS.num_filters,\n FLAGS.num_classes,\n FLAGS.learning_rate, \n FLAGS.batch_size, \n FLAGS.decay_steps,\n FLAGS.decay_rate,\n FLAGS.sequence_length,\n vocab_size,\n FLAGS.embed_size,\n FLAGS.is_training,\n class_weights,\n multi_label_flag=FLAGS.multi_label_flag)\n\n saver = tf.train.Saver() # Initialize Save\n if os.path.exists(FLAGS.ckpt_dir + \"checkpoint\"): # for continue training\n print(\"Restoring Variables from Checkpoint for rnn model.\")\n saver.restore(sess, tf.train.latest_checkpoint(FLAGS.ckpt_dir))\n else:\n print('Initializing Variables')\n sess.run(tf.global_variables_initializer())\n if FLAGS.use_embedding: # assign pre-trained word embedding\n assign_pretrained_word_embedding(sess, word2vec_dict, index2word, embed_size, textcnn)\n\n curr_epoch = sess.run(textcnn.epoch_step)\n number_of_training_data = len(trainX)\n num_batches_per_epoch = int(number_of_training_data / FLAGS.batch_size) + 1\n tol = FLAGS.tolerance\n best_train_loss, best_at_step = float(\"inf\"), 1\n\n for epoch in range(curr_epoch, FLAGS.num_epochs + 1): # 3.feed data & training\n shuffle(trainX) # shuffle data\n loss, acc, counter = 0.0, 0.0, 0\n for batch_num in range(num_batches_per_epoch):\n start_index = batch_num * FLAGS.batch_size\n end_index = min((batch_num + 1) * FLAGS.batch_size, number_of_training_data)\n # for start, end in zip(range(0, number_of_training_data, FLAGS.batch_size),\n # range(FLAGS.batch_size, number_of_training_data, FLAGS.batch_size)):\n if epoch == 1 and counter == 0:\n print(\"trainX[start:end]:\",\n trainX[start_index:end_index]) # ;print(\"trainY[start:end]:\",trainY[start:end])\n curr_loss, curr_acc, _ = sess.run([textcnn.loss_val, textcnn.accuracy, textcnn.train_op],\n feed_dict={textcnn.input_x: trainX[start_index:end_index],\n textcnn.input_y: trainY[start_index:end_index],\n textcnn.dropout_keep_prob: 0.5})\n loss, counter, acc = loss + curr_loss, counter + 1, acc + curr_acc\n if counter % 250 == 0:\n print(\"Epoch %d\\tBatch %d\\tTrain Loss:%.5f\\tTrain Accuracy:%.5f\" % (\n epoch, counter, loss / float(counter),acc / float(counter)))\n\n loss_avg = loss/counter\n if best_train_loss - loss_avg > FLAGS.eplison:\n best_train_loss, best_at_step = loss_avg, epoch\n else:\n tol -= 1\n print(\"%d tolerance left\" % tol)\n\n # print(epoch, FLAGS.validate_every, (epoch % FLAGS.validate_every == 0))\n if epoch % FLAGS.validate_every == 0 or epoch == FLAGS.num_epochs or tol==0: # 4.validation\n # eval_loss, eval_acc = do_eval(sess, textRNN, testX, testY, FLAGS.batch_size, index2word)\n # print(\"Epoch %d Validation Loss:%.3f\\tValidation Accuracy: %.3f\" % (epoch, eval_loss, eval_acc))\n do_eval_confusion_matrix(sess, textcnn, devX, devY, 2, label_index)\n\n # save model to checkpoint\n save_path = FLAGS.ckpt_dir + \"model.ckpt\"\n saver.save(sess, save_path, global_step=epoch)\n\n if tol==0:\n print (\"0 tolerance. training stops.\")\n break\n\n # print(\"going to increment epoch counter....\") # epoch increment\n sess.run(textcnn.epoch_increment)\n\n # 5.最后在测试集上做测试,并报告测试准确率 Test\n do_eval_confusion_matrix(sess, textcnn, testX, testY, 2, label_index)\n\n\n\ndef assign_pretrained_word_embedding(sess, word2vec_dict, index2word, embed_size, target_model):\n \"\"\"\n \"\"\"\n vocab_size = len(index2word)\n word_embedding_2dlist = [[]] * vocab_size # create an empty word_embedding list.\n word_embedding_2dlist[0] = np.zeros(embed_size) # assign empty for first word:'PAD'\n bound = np.sqrt(6.0) / np.sqrt(vocab_size) # bound for random variables.\n count_exist = 0\n count_not_exist = 0\n for i in range(0, vocab_size): # loop each word\n word = index2word[i] # get a word\n embedding = None\n try:\n embedding = word2vec_dict[word] # try to get vector:it is an array.\n except Exception:\n embedding = None\n if embedding is not None: # the 'word' exist a embedding\n word_embedding_2dlist[i] = embedding\n count_exist = count_exist + 1 # assign array to this word.\n else: # no embedding for this word\n word_embedding_2dlist[i] = np.random.uniform(-bound, bound, embed_size)\n count_not_exist = count_not_exist + 1 # init a random value for the word.\n\n word_embedding_final = np.array(word_embedding_2dlist) # covert to 2d array.\n word_embedding = tf.constant(word_embedding_final, dtype=tf.float32) # convert to tensor\n # print (word_embedding_final)\n t_assign_embedding = tf.assign(target_model.word_embeddings,\n word_embedding)\n sess.run(t_assign_embedding)\n logging.info(\"word exists embedding: {}, word not exist embedding: {}\".format(count_exist, count_not_exist))\n logging.info(\"using pre-trained word emebedding ended.\")\n\n\ndef do_eval_confusion_matrix(sess, textRNN, evalX, evalY, num_classes, label_index):\n \"\"\"\n ref:https://stats.stackexchange.com/questions/179835/how-to-build-a-confusion-matrix-for-a-multiclass-classifier\n \"\"\"\n number_examples = len(evalX)\n num_batches_per_epoch = int(number_examples / FLAGS.batch_size) + 1\n all_predictions = []\n for batch_num in range(num_batches_per_epoch):\n start_index = batch_num * FLAGS.batch_size\n end_index = min((batch_num + 1) * FLAGS.batch_size, number_examples)\n # for start, end in zip(range(0, number_examples, batch_size), range(batch_size, number_examples, batch_size)):\n batch_predictions = sess.run(textRNN.predictions, feed_dict={textRNN.input_x: evalX[start_index:end_index],\n textRNN.input_y: evalY[start_index:end_index],\n textRNN.dropout_keep_prob: 1})\n\n all_predictions = np.concatenate((all_predictions, batch_predictions))\n\n confusion_matrix = tf.contrib.metrics.confusion_matrix(all_predictions, evalY)\n matrix = sess.run(confusion_matrix)\n # print(matrix)\n true_pos = np.diag(matrix)\n false_pos = np.sum(matrix, axis=0) - true_pos\n false_neg = np.sum(matrix, axis=1) - true_pos\n precision = true_pos / (true_pos + false_pos)\n recall = true_pos / (true_pos + false_neg)\n\n print('\\t\\tprecision\\trecall\\t\\tf1-score')\n index_label = dict(zip(label_index.values(), label_index.keys()))\n for _class_index in range(num_classes):\n f1_score = (2 * recall[_class_index] * precision[_class_index]) / (\n recall[_class_index] + precision[_class_index])\n print('' + index_label[_class_index] + ' \\t%.3f\\t\\t%.3f\\t\\t%.3f' % (\n recall[_class_index], precision[_class_index], f1_score))\n\n\n# 在验证集上做验证,报告损失、精确度\ndef do_eval(sess, textRNN, evalX, evalY, batch_size, vocabulary_index2word_label):\n number_examples = len(evalX)\n eval_loss, eval_acc, eval_counter = 0.0, 0.0, 0\n for start, end in zip(range(0, number_examples, batch_size), range(batch_size, number_examples, batch_size)):\n curr_eval_loss, logits, curr_eval_acc = sess.run([textRNN.loss_val, textRNN.logits, textRNN.accuracy],\n # curr_eval_acc--->textCNN.accuracy\n feed_dict={textRNN.input_x: evalX[start:end],\n textRNN.input_y: evalY[start:end]\n , textRNN.dropout_keep_prob: 1})\n # label_list_top5 = get_label_using_logits(logits_[0], vocabulary_index2word_label)\n # curr_eval_acc=calculate_accuracy(list(label_list_top5), evalY[start:end][0],eval_counter)\n eval_loss, eval_acc, eval_counter = eval_loss + curr_eval_loss, eval_acc + curr_eval_acc, eval_counter + 1\n return eval_loss / float(eval_counter), eval_acc / float(eval_counter)\n\nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"_textcnn/textcnn_train1.py","file_name":"textcnn_train1.py","file_ext":"py","file_size_in_byte":16092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"464423824","text":"from django.shortcuts import render, redirect\nfrom .models import User\nfrom django.contrib import messages\n\n# Create your views here.\ndef index(request):\n\tif \"logged_user\" in request.session:\n\t\treturn redirect('products:all_products')\n\treturn render(request, \"logreg/index.html\")\n\ndef success(request):\n\tif \"logged_user\" not in request.session:\n\t\treturn redirect('/')\n\tuser = User.objects.get(id=request.session['logged_user'])\n\treturn render(request, \"logreg/success.html\", {\"user\":user})\n\ndef signout(request):\n\trequest.session.pop('logged_user', None)\n\treturn redirect('/')\n\ndef register(request):\n\tif request.method == \"POST\":\t\n\t\tform = request.POST\t\n\t\t#replace view/controller code with model code\n\t\terrors = User.objects.validate_registration(form)\n\t\tif errors:\n\t\t\tfor error in errors: \n\t\t\t\tmessages.error(request, error)\n\t\telse:\n\t\t\t#replace view/controller code with model code\n\t\t\tif User.objects.register(form):\n\t\t\t\tmessages.success(request, \"You have successfully created an accout, please login to continue\")\n\t\t\telse:\n\t\t\t\tmessages.error(request,\"Something went wrong!\")\n\treturn redirect('/')\n\ndef login(request):\n\tif request.method != \"POST\":\n\t\treturn redirect('/')\n\tuser = User.objects.check_login(request.POST)\n\tif user:\n\t\tmessages.success(request, \"Successful login\")\n\t\trequest.session['logged_user'] = user.id\n\t\treturn redirect('products:all_products')\n\telse: \n\t\tmessages.error(request, \"Invalid login credentials\")\n\t\treturn redirect('/')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"apps/logreg/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"342564549","text":"#!/usr/bin/env python3\n\n\"\"\"\nCreated on 20 Feb 2017\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nDESCRIPTION\nThe led utility is used to control a two-colour (red / green) LED mounted on the South Coast Science free-to-air\nSHT board.\n\nOn some Praxis device configurations, a free-to-air temperature and humidity board is mounted in the air intake of the\noptical particle counter (OPC). Since the board is visible from outside the unit, it is useful to mount indicator\nLEDs in this position.\n\nLED options are as follows:\n\n* R - Red\n* A - Amber (Red + Green)\n* G - Green\n* 0 - Off\n\nIn practice, the led utility does a very simple job: it validates its parameters, then presents these on stdout or\nthe named Unix domain socket in a format that is compatible with the led_controller utility.\n\nIf the Unix domain socket has no listener, the led utility discards messages.\n\nSYNOPSIS\nled.py { -s { R | A | G | 0 } | -f { R | A | G | 0 } { R | A | G | 0 } } [-u UDS] [-v]\n\nEXAMPLES\n./led.py -v -f R 0 -u /home/scs/SCS/pipes/scs_led_control.uds\n\nDOCUMENT EXAMPLE\n{\"colour0\": \"R\", \"colour1\": \"G\"}\n\nSEE ALSO\nscs_dev/led_controller\n\"\"\"\n\nimport sys\n\nfrom scs_core.comms.uds_writer import UDSWriter\nfrom scs_core.data.json import JSONify\nfrom scs_core.led.led_state import LEDState\nfrom scs_core.sys.signalled_exit import SignalledExit\n\nfrom scs_dev.cmd.cmd_led import CmdLED\n\nfrom scs_host.comms.domain_socket import DomainSocket\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n\n writer = None\n\n # ----------------------------------------------------------------------------------------------------------------\n # cmd...\n\n cmd = CmdLED()\n\n if not cmd.is_valid():\n cmd.print_help(sys.stderr)\n exit(2)\n\n if cmd.verbose:\n print(\"led: %s\" % cmd, file=sys.stderr)\n\n try:\n # ------------------------------------------------------------------------------------------------------------\n # resources...\n\n writer = UDSWriter(DomainSocket, cmd.uds)\n\n if cmd.verbose:\n print(\"led: %s\" % writer, file=sys.stderr)\n\n\n # ------------------------------------------------------------------------------------------------------------\n # run...\n\n # signal handler...\n SignalledExit.construct(\"led\", cmd.verbose)\n\n state = LEDState(cmd.solid, cmd.solid) if cmd.solid is not None else LEDState(cmd.flash[0], cmd.flash[1])\n\n writer.connect()\n\n try:\n writer.write(JSONify.dumps(state))\n\n if cmd.verbose:\n print(JSONify.dumps(state), file=sys.stderr)\n\n except OSError:\n if cmd.verbose:\n print(\"led: unable to write to %s\" % cmd.uds, file=sys.stderr)\n\n\n # ----------------------------------------------------------------------------------------------------------------\n # end...\n\n except ConnectionError as ex:\n print(\"led: %s\" % ex, file=sys.stderr)\n\n except (KeyboardInterrupt, SystemExit):\n pass\n\n finally:\n if cmd and cmd.verbose:\n print(\"led: finishing\", file=sys.stderr)\n\n if writer:\n writer.close()\n","sub_path":"src/scs_dev/led.py","file_name":"led.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"456025779","text":"# coding=utf-8\n\nimport os\nimport shutil\n\nd = 'D:\\\\PythonProject\\\\HelloPythonStudy\\\\com.bjsxt.study\\\\test_test'\nfor i in os.listdir(d):\n # 因为windows系统不是utf8编码,所以需要decode一下\n # print i.decode('GBK')\n new_file = i.replace('part-r-0000', 'part')\n old_full_file = d + '\\\\' + i\n new_full_file = d + '\\\\' + new_file\n shutil.move(old_full_file, new_full_file)\nprint('Done!')\n","sub_path":"data_analyse/py_04_change_filenames.py","file_name":"py_04_change_filenames.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"441760379","text":"import gensim\nfrom nltk.tokenize import word_tokenize\nimport pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom gensim.models import Word2Vec\nfrom collections import OrderedDict\nimport logging\nimport os\n\nlogging.basicConfig(format=\"%(asctime)s : %(levelname)s : %(message)s\", level=logging.INFO)\n\nembedding_dim = 150\nmin_occurrence = 20\nreplace_word = \"\"\nvocabulary_file = \"models/vocabulary.csv\"\nword2vec_model_file = \"models/word2vec_model\"\n\ndef load_model():\n model = None\n if os.path.exists(word2vec_model_file):\n model = Word2Vec.load(word2vec_model_file)\n return model\n else:\n print(\"Model file does not exists.\")\n exit(0)\n\ndef load_vocabulary():\n v_df = pd.read_csv(vocabulary_file)\n vocabulary = {}\n for idx, row in v_df.iterrows():\n vocabulary[row[\"word\"]] = row[\"index\"]\n return vocabulary\n\n\nif __name__ == \"__main__\":\n\n \n train_df = pd.read_csv(\"train_clean.csv\")\n test_df = pd.read_csv(\"test_clean.csv\")\n\n corpus = set()\n corpus.update(train_df[\"question1\"].apply(lambda s : str(s).strip()).tolist())\n corpus.update(train_df[\"question2\"].apply(lambda s : str(s).strip()).tolist())\n corpus.update(test_df[\"question1\"].apply(lambda s : str(s).strip()).tolist())\n corpus.update(test_df[\"question2\"].apply(lambda s : str(s).strip()).tolist())\n print(\"Find %d sentences\"%len(corpus))\n\n cv = CountVectorizer(lowercase=False, token_pattern=\"\\S+\", min_df=min_occurrence)\n cv.fit(corpus)\n vocabulary = cv.vocabulary_\n vocabulary[replace_word] = len(vocabulary)\n voc_df = pd.DataFrame.from_dict(vocabulary, orient=\"index\").reset_index()\n voc_df.columns = [\"word\", \"index\"]\n print(\"Find %d words.\"%len(vocabulary))\n print(\"Vocabulary save to %s\"%vocabulary_file)\n voc_df.to_csv(vocabulary_file, encoding=\"utf8\")\n\n corpus_list = []\n for s in corpus:\n s = s.strip()\n tokens = map(lambda x : x if x in vocabulary else replace_word, s.split())\n tokens = [w for w in tokens]\n corpus_list.append(tokens)\n\n model = Word2Vec(corpus_list, size=embedding_dim, min_count=1, workers=4, iter=20)\n print(\"Training completed, model save to %s\"%word2vec_model_file)\n model.save(word2vec_model_file)\n","sub_path":"word2vec.py","file_name":"word2vec.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"625829393","text":"from flask import url_for\n\nfrom tests import FrontendWithAdminTestBase\nfrom tests.factories import RoomFactory, SubnetFactory, PatchPortFactory\n\n\nclass UserLogTestBase(FrontendWithAdminTestBase):\n def get_logs(self, user_id=None, **kw):\n \"\"\"Request the logs, assert validity, and return the response.\n\n By default, the logs are fetched for the user logging in.\n\n The following assertions are made:\n * The response code is 200\n * The response content_type contains ``\"json\"``\n * The response's JSON contains an ``\"items\"`` key\n\n :returns: ``response.json['items']``\n \"\"\"\n if user_id is None:\n user_id = self.user_id\n log_endpoint = url_for('user.user_show_logs_json',\n user_id=user_id,\n **kw)\n response = self.assert_response_code(log_endpoint, code=200)\n self.assertIn(\"json\", response.content_type.lower())\n json = response.json\n self.assertIsNotNone(json.get('items'))\n return json['items']\n\n\nclass UserFrontendTestBase(FrontendWithAdminTestBase):\n def create_factories(self):\n super().create_factories()\n self.room = RoomFactory()\n self.subnet = SubnetFactory()\n self.patch_port = PatchPortFactory(room=self.room, patched=True,\n switch_port__switch__host__owner=self.admin)\n # 2. A pool of default vlans so an IP can be found\n self.patch_port.switch_port.default_vlans.append(self.subnet.vlan)\n","sub_path":"tests/frontend/user/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"14663052","text":"class BinarySearchTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def insert(self, value):\n if self.value:\n if value < self.value:\n if self.left is None:\n self.left = BinarySearchTree(value)\n else:\n self.left.insert(value)\n elif value > self.value:\n if self.right is None:\n self.right = BinarySearchTree(value)\n else:\n self.right.insert(value)\n else:\n self.value = value\n \n def contains(self, value):\n if value < self.value:\n if self.left is None:\n return None\n return self.left.contains(value)\n elif value > self.value:\n if self.right is None:\n return None\n return self.right.contains(value)\n else:\n return self\n\n def get_max(self):\n if self.right:\n x = self.right\n else:\n return self.value\n max = self.value\n while True:\n if x.value > max:\n max = x.value\n if x.right is None:\n return max\n else:\n x = x.right\n \n\n","sub_path":"binary_search_tree/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"282275673","text":"from selenium import webdriver\nimport time\nfrom selenium.webdriver.common.by import By\nfrom math import log,sin\n\n\ntry:\n browser = webdriver.Chrome()\n browser.get(\"http://suninjuly.github.io/redirect_accept.html\")\n\n button = browser.find_element(By.CSS_SELECTOR, '.trollface.btn')\n button.click()\n new_window = browser.window_handles[1]\n browser.switch_to.window(new_window)\n\n x = int(browser.find_element(By.CSS_SELECTOR, '#input_value').text)\n x_solved = str(log(abs(12*sin(x))))\n\n input_field = browser.find_element(By.CSS_SELECTOR, '#answer')\n input_field.send_keys(x_solved)\n\n submit = browser.find_element(By.XPATH, \"//button[@type='submit']\")\n submit.click()\n\nfinally:\n time.sleep(5)\n browser.quit()\n","sub_path":"part2_lesson3_step6.py","file_name":"part2_lesson3_step6.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"546256047","text":"import re\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nclass Anime1Me:\n def getData(self, url):\n data = {\n 'episodes': 0\n }\n text = requests.get(url).text\n soup = BeautifulSoup(text, 'html.parser')\n title = soup.find('h1', {'class': 'page-title'}).text\n\n # print('title', title)\n text = requests.get('https://anime1.me').text\n m = re.search(r'>{}'.format(re.escape(title)), text)\n if m:\n episodes = m.group(1)\n data['episodes'] = self._parse_episodes(episodes)\n else:\n # print('Not match')\n pass\n\n return data\n\n def _parse_episodes(self, episodes):\n if episodes == '劇場版':\n return 1\n\n m = re.match(r'^連載中\\((\\d+)\\)$', episodes)\n if m:\n return int(m.group(1))\n\n m = re.match(r'^1-(\\d+)$', episodes)\n if m:\n return int(m.group(1))\n\n raise Exception('Unknwon episodes format: {}'.format(episodes))\n","sub_path":"my-ACG/util/anime1_me.py","file_name":"anime1_me.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"10236502","text":"from ..io import read_all_genes, read_all_structures\nimport numpy as np\nimport pytest\nimport random\n\n\ndef test_read_all_genes():\n with pytest.raises(KeyError):\n read_all_genes(entry_type='wrong_entry_type')\n\n all_genes = read_all_genes(entry_type='id')\n assert isinstance(all_genes, np.ndarray)\n\n all_genes = read_all_genes(\n entry_type=['id', 'acronym', 'name']\n )\n assert all_genes.shape == (19991, 3)\n\n\ndef test_real_all_structures():\n with pytest.raises(KeyError):\n read_all_structures(entry_type='wrong_entry_type')\n default_structures = \\\n read_all_structures(entry_type='acronym')\n assert isinstance(default_structures, np.ndarray)\n assert isinstance(\n random.choice(default_structures), str\n )\n default_structures = \\\n read_all_structures(\n entry_type=['id', 'acronym', 'name']\n )\n assert default_structures.shape == (56, 3)\n","sub_path":"abagen/mouse/tests/test_io.py","file_name":"test_io.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"510955432","text":"from twisted.plugin import IPlugin\nfrom twisted.words.protocols import irc\nfrom txircd.config import ConfigValidationError\nfrom txircd.module_interface import Command, ICommand, IModuleData, ModuleData\nfrom zope.interface import implements\n\nclass PartCommand(ModuleData):\n\timplements(IPlugin, IModuleData)\n\t\n\tname = \"PartCommand\"\n\tcore = True\n\t\n\tdef actions(self):\n\t\treturn [ (\"leavemessage\", 101, self.broadcastPart),\n\t\t (\"leavemessage\", 1, self.sendPartMessage) ]\n\t\n\tdef userCommands(self):\n\t\treturn [ (\"PART\", 1, UserPart(self.ircd)) ]\n\t\n\tdef serverCommands(self):\n\t\treturn [ (\"PART\", 1, ServerPart(self.ircd)) ]\n\n\tdef verifyConfig(self, config):\n\t\tif \"part_message_length\" in config:\n\t\t\tif not isinstance(config[\"part_message_length\"], int) or config[\"part_message_length\"] < 0:\n\t\t\t\traise ConfigValidationError(\"part_message_length\", \"invalid number\")\n\t\t\telif config[\"part_message_length\"] > 300:\n\t\t\t\tconfig[\"part_message_length\"] = 300\n\t\t\t\tself.ircd.logConfigValidationWarning(\"part_message_length\", \"value is too large\", 300)\n\t\n\tdef broadcastPart(self, sendUserList, channel, user, type, typeData, fromServer):\n\t\tif type != \"PART\":\n\t\t\treturn\n\t\treason = \"\"\n\t\tif \"reason\" in typeData:\n\t\t\treason = typeData[\"reason\"]\n\t\tself.ircd.broadcastToServers(fromServer, \"PART\", channel.name, reason, prefix=user.uuid)\n\t\n\tdef sendPartMessage(self, sendUserList, channel, user, type, typeData, fromServer):\n\t\tif type != \"PART\":\n\t\t\treturn\n\t\tmsgPrefix = user.hostmask()\n\t\tconditionalTags = {}\n\t\tself.ircd.runActionStandard(\"sendingusertags\", user, conditionalTags)\n\t\tif \"reason\" in typeData and typeData[\"reason\"]:\n\t\t\treason = typeData[\"reason\"]\n\t\t\tfor destUser in sendUserList:\n\t\t\t\tif destUser.uuid[:3] == self.ircd.serverID:\n\t\t\t\t\ttags = destUser.filterConditionalTags(conditionalTags)\n\t\t\t\t\tdestUser.sendMessage(\"PART\", reason, to=channel.name, prefix=msgPrefix, tags=tags)\n\t\telse:\n\t\t\tfor destUser in sendUserList:\n\t\t\t\tif destUser.uuid[:3] == self.ircd.serverID:\n\t\t\t\t\ttags = destUser.filterConditionalTags(conditionalTags)\n\t\t\t\t\tdestUser.sendMessage(\"PART\", to=channel.name, prefix=msgPrefix, tags=tags)\n\t\tdel sendUserList[:]\n\nclass UserPart(Command):\n\timplements(ICommand)\n\t\n\tdef __init__(self, ircd):\n\t\tself.ircd = ircd\n\t\n\tdef parseParams(self, user, params, prefix, tags):\n\t\tif not params or not params[0]:\n\t\t\tuser.sendSingleError(\"PartCmd\", irc.ERR_NEEDMOREPARAMS, \"PART\", \"Not enough parameters\")\n\t\t\treturn None\n\t\tif params[0] not in self.ircd.channels:\n\t\t\tuser.sendSingleError(\"PartCmd\", irc.ERR_NOSUCHCHANNEL, params[0], \"No such channel\")\n\t\t\treturn None\n\t\tchannel = self.ircd.channels[params[0]]\n\t\tif user not in channel.users:\n\t\t\tuser.sendSingleError(\"PartCmd\", irc.ERR_NOTONCHANNEL, params[0], \"You're not on that channel\")\n\t\t\treturn None\n\t\treason = params[1] if len(params) > 1 else \"\"\n\t\treason = reason[:self.ircd.config.get(\"part_message_length\", 300)]\n\t\treturn {\n\t\t\t\"channel\": channel,\n\t\t\t\"reason\": reason\n\t\t}\n\t\n\tdef affectedChannels(self, user, data):\n\t\treturn [ data[\"channel\"] ]\n\t\n\tdef execute(self, user, data):\n\t\tchannel = data[\"channel\"]\n\t\treason = data[\"reason\"]\n\t\tuser.leaveChannel(channel, \"PART\", { \"reason\": reason })\n\t\treturn True\n\nclass ServerPart(Command):\n\timplements(ICommand)\n\t\n\tdef __init__(self, ircd):\n\t\tself.ircd = ircd\n\t\n\tdef parseParams(self, server, params, prefix, tags):\n\t\tif len(params) != 2 or not params[0]:\n\t\t\treturn None\n\t\tif prefix not in self.ircd.users:\n\t\t\tif prefix in self.ircd.recentlyQuitUsers:\n\t\t\t\treturn {\n\t\t\t\t\t\"lostuser\": True\n\t\t\t\t}\n\t\t\treturn None\n\t\tif params[0] not in self.ircd.channels:\n\t\t\tif params[0] in self.ircd.recentlyDestroyedChannels:\n\t\t\t\treturn {\n\t\t\t\t\t\"lostchannel\": True\n\t\t\t\t}\n\t\t\treturn None\n\t\treturn {\n\t\t\t\"user\": self.ircd.users[prefix],\n\t\t\t\"channel\": self.ircd.channels[params[0]],\n\t\t\t\"reason\": params[1]\n\t\t}\n\t\n\tdef execute(self, server, data):\n\t\tif \"lostuser\" in data or \"lostchannel\" in data:\n\t\t\treturn True\n\t\tuser = data[\"user\"]\n\t\tchannel = data[\"channel\"]\n\t\treason = data[\"reason\"]\n\t\tuser.leaveChannel(channel, \"PART\", { \"reason\": reason }, server)\n\t\treturn True\n\npartCommand = PartCommand()","sub_path":"txircd/modules/rfc/cmd_part.py","file_name":"cmd_part.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"612611340","text":"# Android Device Testing Framework (\"dtf\")\n# Copyright 2013-2015 Jake Valletta (@jake_valletta)\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\"\"\"Python helper for using `adb`\"\"\"\n\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport os\nimport os.path\nimport tempfile\nimport shutil\nfrom subprocess import Popen, PIPE\n\nfrom dtf.properties import get_prop\nfrom dtf.constants import DTF_CLIENT\n\nADB_BINARY = \"adb\"\n\nSTATUS_DEVICE = 'device'\nSTATUS_OFFLINE = 'offline'\nSTATUS_BOOTLOADER = 'bootloader'\n\nMODE_USB = 'usb'\nMODE_WIFI = 'wifi'\n\n\ndef get_mode_serial():\n\n \"\"\"Return the serial dependent on the mode\"\"\"\n\n if get_prop('Client', 'mode') == MODE_USB:\n return get_prop(\"Info\", \"serial\")\n else:\n return (\"%s:%s\" % (get_prop('Client', 'ip-addr'),\n get_prop('Client', 'port')))\n\n\n# pylint:disable=too-many-public-methods\nclass DtfAdb(object):\n\n \"\"\"Python wrapper class for `adb`\"\"\"\n\n serial = ''\n pre_1_0_36 = False\n no_serial = False\n stdout = None\n stderr = None\n returncode = ''\n\n def __init__(self, no_serial=False):\n\n \"\"\"Object initialization\"\"\"\n\n self.no_serial = no_serial\n\n if not self.no_serial:\n\n self.serial = get_mode_serial()\n\n # Determine if we are the new version of adb\n self.pre_1_0_36 = self.__is_old_adb_version()\n\n def __is_old_adb_version(self):\n\n \"\"\"Determine if adb is the new version\"\"\"\n\n self.__run_command(\"\")\n\n try:\n version_line = self.get_errors()[0]\n version = version_line.split()[-1]\n split_version = version.split(\".\")\n\n if split_version[0] == \"1\" and split_version[1] == \"0\":\n if int(split_version[2]) < 36:\n return True\n\n return False\n\n except IndexError:\n return False\n\n def __run_command(self, in_cmd):\n\n \"\"\"Internal function to run `adb` command\"\"\"\n\n if self.no_serial:\n cmd = (\"%s %s\" % (ADB_BINARY, in_cmd)).split(' ')\n else:\n cmd = (\"%s -s %s %s\"\n % (ADB_BINARY, self.serial, in_cmd)).split(' ')\n\n proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=False)\n\n tmp_out = proc.stdout.read().replace(\"\\r\", '')\n tmp_err = proc.stderr.read().replace(\"\\r\", '')\n\n self.stdout = tmp_out.split(\"\\n\")\n self.stderr = tmp_err.split(\"\\n\")\n\n proc.terminate()\n\n def get_output(self):\n\n \"\"\"Read output stream\"\"\"\n\n return self.stdout\n\n def get_errors(self):\n\n \"\"\"Read error stream\"\"\"\n\n return self.stderr\n\n def shell_command(self, cmd):\n\n \"\"\"Execute a shell command on device\"\"\"\n\n self.__run_command(\"shell %s\" % cmd)\n\n def wait_for_device(self):\n\n \"\"\"Block until device is found\"\"\"\n\n self.__run_command(\"wait-for-device\")\n\n def get_devices(self):\n\n \"\"\"List all connected devices\"\"\"\n\n self.__run_command(\"devices\")\n\n device_list = list()\n\n output = self.get_output()\n\n # Remove the \"List of devices...\"\n output.pop(0)\n\n # ...Also the two '' at the end.\n output.pop()\n output.pop()\n\n if len(output) == 0:\n return device_list\n\n for device in output:\n\n try:\n serial, status = device.split('\\t')\n except ValueError:\n continue\n\n device_list.append({'serial': serial, 'status': status})\n\n return device_list\n\n def pull(self, file_name, local=\"./\"):\n\n \"\"\"Pull file off device\"\"\"\n\n if self.pre_1_0_36:\n self.__run_command(\"pull %s %s\" % (file_name, local))\n\n else:\n self.__run_command(\"pull %s %s\" % (file_name, local))\n\n def pull_dir(self, dir_name, local=\"./\"):\n\n \"\"\"Pull a directory off device\"\"\"\n\n if self.pre_1_0_36:\n self.__run_command(\"pull %s %s\" % (dir_name, local))\n\n else:\n temp_pull = tempfile.mkdtemp()\n base = os.path.basename(dir_name.rstrip(\"/\"))\n\n self.__run_command(\"pull %s %s\" % (dir_name, temp_pull))\n full_tmp = \"%s/%s\" % (temp_pull, base)\n\n shutil.copytree(full_tmp, local)\n shutil.rmtree(temp_pull)\n\n def push(self, local_file_name, upload_path):\n\n \"\"\"Push a file to a device\"\"\"\n\n self.__run_command(\"push %s %s\" % (local_file_name, upload_path))\n\n def run_as(self, user, cmd):\n\n \"\"\"Run as a user\"\"\"\n\n self.shell_command(\"run-as %s %s\" % (user, cmd))\n\n def busybox(self, cmd):\n\n \"\"\"Execute a busybox command on device\"\"\"\n\n busybox = get_prop(\"Info\", \"busybox\")\n self.shell_command(\"run-as %s %s %s\" % (DTF_CLIENT, busybox, cmd))\n\n def is_file(self, file_name):\n\n \"\"\"Check if a file exists on device\"\"\"\n\n self.shell_command(\"ls %s\" % file_name)\n\n return bool(self.stdout[0] == file_name)\n\n def is_dir(self, dir_name):\n\n \"\"\"Check if a directory exists on device\"\"\"\n\n self.shell_command(\"ls -ld %s\" % dir_name)\n\n line = [x for x in self.stdout if x][0]\n\n if line[-26:] == \" No such file or directory\":\n return False\n elif line[0] == 'd':\n return True\n else:\n return False\n\n def install(self, apk_path):\n\n \"\"\"Install an APK on a device\"\"\"\n\n self.__run_command(\"install %s\" % apk_path)\n\n def uninstall(self, app_name):\n\n \"\"\"Uninstall an application on a device\"\"\"\n\n self.__run_command(\"uninstall %s\" % app_name)\n\n def is_installed(self, app_name):\n\n \"\"\"Check if an application is installed on device\"\"\"\n\n self.shell_command(\"pm list packages %s\" % app_name)\n\n if self.get_output() == ['']:\n return 0\n else:\n return 1\n\n def add_forward(self, local, remote):\n\n \"\"\"Add an adb forward rule\"\"\"\n\n forward_string = \"forward %s %s\" % (local, remote)\n\n self.__run_command(forward_string)\n\n def remove_forward(self, local):\n\n \"\"\"Remove a adb forward rule\"\"\"\n\n remove_string = \"forward --remove %s\" % local\n\n self.__run_command(remove_string)\n\n def kill_server(self):\n\n \"\"\"Kill the adb daemon\"\"\"\n\n self.__run_command(\"kill-server\")\n\n def start_server(self):\n\n \"\"\"Start the adb daemon\"\"\"\n\n self.__run_command(\"start-server\")\n\n def usb(self):\n\n \"\"\"Restart device in USB mode\"\"\"\n\n self.__run_command(\"usb\")\n\n def tcpip(self, port):\n\n \"\"\"Restart device in TCP/IP mode\"\"\"\n\n self.__run_command(\"tcpip %s\" % port)\n\n def connect(self, ip_addr, port):\n\n \"\"\"Connect to IP/port\"\"\"\n\n self.__run_command(\"connect %s:%s\" % (ip_addr, port))\n\n # Any news is bad news.\n if self.get_output() != ['']:\n return None\n\n print('returning whatever')\n return 0\n","sub_path":"python-dtf/dtf/adb.py","file_name":"adb.py","file_ext":"py","file_size_in_byte":7433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"651167176","text":"\"\"\"Helper functions to process patches from WSI images\"\"\"\nimport argparse\nfrom collections import defaultdict\nimport json\nimport random\nimport warnings\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport openslide\nimport skimage.color\nimport skimage.transform\nfrom tqdm import tqdm\n\n\ndef is_patch_tumor(patch):\n \"\"\"Uses Hue and Saturation to select tumour patches\"\"\"\n\n assert(patch.shape[2] == 3)\n\n SAT_THRESHOLD = 0.05 # White pixel below this threshold.\n PERCENT_WHITE_PIXELS_THRESHOLD = 0.60\n\n HUE_LOWER_THRESHOLD = 320 / 360 # Red and pink above this threshold.\n PERCENT_PINK_PIXELS_THRESHOLD = 0.30\n VAL_PINK_RED_THRESHOLD = 0.55\n\n def is_patch_pink_or_red(hsv_patch):\n \"\"\"Checks if a patch is overwhelmingly pink/red\n\n Each pixel is evaluted if it is pink by\n checking first if the saturation is above\n a threshold to make sure the pixel is not too light.\n A check is made such that the hue is corresponds to\n pink or red and that colour is bright enough.\n\n Note: pink hue is in [325, 335]\n red hue is in [335, 360]\n \"\"\"\n\n hue = hsv_patch[:,:,0]\n sat = hsv_patch[:,:,1]\n val = hsv_patch[:,:,2]\n\n sat_mask = sat > SAT_THRESHOLD\n hue_mask = hue > HUE_LOWER_THRESHOLD\n\n pink_or_red_mask = np.logical_and(sat_mask, hue_mask)\n\n # For us to call the colour pink or red, it needs to be bright enough.\n non_dark_mask = val > VAL_PINK_RED_THRESHOLD\n\n final_mask = np.logical_and(pink_or_red_mask, non_dark_mask)\n percent = np.mean(final_mask)\n\n return (percent > PERCENT_PINK_PIXELS_THRESHOLD)\n\n def is_patch_white(hsv_patch):\n \"\"\"Determines if a patch is white based on the saturation level\"\"\"\n\n sat = hsv_patch[:,:,1] # in range [0,1]\n percent = np.mean(sat < SAT_THRESHOLD)\n\n return (percent > PERCENT_WHITE_PIXELS_THRESHOLD)\n\n # Hue, sat and val are in range [0,1]\n # Note that h otherwise usually is in range (0,360)\n hsv_patch = matplotlib.colors.rgb_to_hsv(patch)\n # TODO uncomment below and turn is_patch_white into own function,\n # implement functions below with passing in patch filter\n return not is_patch_white(hsv_patch) and not is_patch_pink_or_red(hsv_patch)\n\ndef get_patch_indices_that_contain_tumor(patches):\n tumor_indices = []\n for i, patch in enumerate(patches):\n if is_patch_tumor(patch):\n tumor_indices.append(i)\n return tumor_indices\n\n\ndef get_patches_as_flat_list_from_slide(hdf5_fh, slide_name,\n chunk_size=16, image_resolution=16):\n slide = hdf5_fh[slide_name]\n patches = []\n for i in tqdm(range(0, slide.shape[0], chunk_size)):\n patches_chunked = slide[i: i+chunk_size]\n assert(patches_chunked.shape[1] == 3)\n patches_chunked = np.swapaxes(patches_chunked, 1, 3)\n patches_chunked = np.swapaxes(patches_chunked, 1, 2)\n\n assert(patches_chunked.max() <= 255)\n if (patches_chunked.max() <= 1):\n patches_chunked = patches_chunked * 255\n\n for patch in patches_chunked:\n patch = skimage.transform.resize(\n patch/ 255,\n (image_resolution,image_resolution),\n mode='reflect', order=3, anti_aliasing=False)\n patches.append(patch)\n patches = np.array(patches)\n return patches\n\ndef get_tumor_patch_indices_from_slide(hdf5_fh, slide_name, verbose=False):\n patches = get_patches_as_flat_list_from_slide(hdf5_fh, slide_name)\n indices = get_patch_indices_that_contain_tumor(patches)\n if verbose is True:\n print(\"{}/{} kept\".format(len(indices), len(patches)))\n return indices\n\n\ndef create_whole_slide_image_from_slide_name_and_meta(hdf5_fh, slide_name, slide_meta):\n patches = get_patches_as_flat_list_from_slide(hdf5_fh, slide_name)\n indices = get_patch_indices_that_contain_tumor(patches)\n slide = create_whole_slide_image_from_patches_flat_list(patches,\n num_patches_in_row = slide_meta['partition_dims'][1],\n num_patches_in_col = slide_meta['partition_dims'][0],\n tumor_patch_indices = indices)\n return slide\n\n\ndef create_whole_slide_image_from_patches_flat_list(patches,\n num_patches_in_row, num_patches_in_col,\n tumor_patch_indices=[], stride=16):\n\n def draw_green_border(patch, border_width=2):\n patch[:border_width,:, :] = [0., 1., 0.]\n patch[-border_width,:, :] = [0., 1., 0.]\n patch[:, :border_width, :] = [0., 1., 0.]\n patch[:, -border_width:, :] = [0., 1., 0.]\n return patch\n\n slide = np.zeros((num_patches_in_row * stride, num_patches_in_col * stride, 3))\n\n for i in range(num_patches_in_row):\n for j in range(num_patches_in_col):\n patch_index = i*num_patches_in_col + j\n patch = patches[patch_index]\n slide[i*stride: (i+1)*stride, j*stride:(j+1)*stride] = \\\n draw_green_border(patch) if patch_index in tumor_patch_indices else patch\n return slide\n\n\ndef un_normalize(tensor, pixel_dict):\n \"\"\"Un-normalize a PyTorch Tensor seen by the model into a NumPy array of\n pixels fit for visualization.\n Args:\n tensor: Tensor with pixel values in range (-1, 1).\n If image, shape (batch_size, num_channels, height, width).\n pixel_dict: Dictionary containing min, max, avg (array with 3 elements in mean\n of pixel data; window center, width.\n Returns:\n pixels: Numpy ndarray with entries of type `uint8`.\n \"\"\"\n pixels = tensor.cpu().float().numpy()\n\n assert(pixels.shape[0] == 3)\n\n # Reverse pre-processing steps for visualization\n for i in range(pixels.shape[0]):\n pixels[i, :, :] = (pixels[i, :, :] + pixel_dict['means'][i]) * \\\n (pixel_dict['max'] - pixel_dict['min']) + pixel_dict['min']\n pixels = pixels * 255\n pixels = pixels.astype(dtype=np.uint8)\n\n return pixels\n\n\ndef normalize(pixels, pixel_dict):\n assert(pixels.shape[0] == 3)\n\n if (pixels.max() <= 1.):\n warnings.warn('Expecting 0-255 range, not 0-1. Auto-rescaling...')\n pixels = pixels * 255.\n\n # Pre-processing steps for visualization\n pixels = pixels / 255.\n\n assert(pixels.max() <= pixel_dict['max'])\n assert(pixels.min() >= pixel_dict['min'])\n\n for i in range(pixels.shape[0]):\n pixels[i, :, :] = ((pixels[i, :, :] - pixel_dict['min']) / (pixel_dict['max'] - pixel_dict['min'])) \\\n - pixel_dict['means'][i]\n return pixels\n\n\ndef add_heat_map(pixels_np, intensities_np,\n alpha_img=0.33, color_map='magma', normalize=True):\n \"\"\"Add a CAM heat map as an overlay on a PNG image.\n\n Args:\n pixels_np: Pixels to add the heat map on top of. Must be in range (0, 1).\n intensities_np: Intensity values for the heat map. Must be in range (0, 1).\n alpha_img: Weight for image when summing with heat map. Must be in range (0, 1).\n color_map: Color map scheme to use with PyPlot.\n normalize: If True, normalize the intensities to range exactly from 0 to 1.\n\n Returns:\n Original pixels with heat map overlaid.\n \"\"\"\n def _normalize_png(image):\n \"\"\"Normalize pixels to the range 0-255.\"\"\"\n image -= np.amin(image)\n image /= (np.amax(image) + 1e-7)\n image *= 255\n\n return image\n\n assert(np.max(intensities_np) <= 1 and np.min(intensities_np) >= 0)\n color_map_fn = plt.get_cmap(color_map)\n if normalize:\n intensities_np = _normalize_png(intensities_np)\n else:\n intensities_np *= 255\n heat_map = color_map_fn(intensities_np.astype(np.uint8))\n if len(heat_map.shape) == 3:\n heat_map = heat_map[:, :, :3]\n else:\n heat_map = heat_map[:, :, :, :3]\n\n new_img = alpha_img * pixels_np.astype(\n np.float32) + (1. - alpha_img) * heat_map.astype(np.float32)\n new_img = np.uint8(_normalize_png(new_img))\n\n return new_img\n\ndef get_plot(title, curve):\n \"\"\"Get a NumPy array for the given curve.\n Args:\n title: Name of curve.\n curve: NumPy array of x and y coordinates.\n Returns:\n NumPy array to be used as a PNG image.\n \"\"\"\n fig = plt.figure()\n ax = plt.gca()\n\n plot_type = title.split('_')[-1]\n ax.set_title(plot_type)\n if plot_type == 'PRC':\n precision, recall, _ = curve\n ax.step(recall, precision, color='b', alpha=0.2, where='post')\n ax.fill_between(recall, precision, step='post', alpha=0.2, color='b')\n ax.set_xlabel('Recall')\n ax.set_ylabel('Precision')\n elif plot_type == 'ROC':\n false_positive_rate, true_positive_rate, _ = curve\n ax.plot(false_positive_rate, true_positive_rate, color='b')\n ax.plot([0, 1], [0, 1], 'r--')\n ax.set_xlabel('False Positive Rate')\n ax.set_ylabel('True Positive Rate')\n else:\n ax.plot(curve[0], curve[1], color='b')\n\n ax.set_ylim([0.0, 1.05])\n ax.set_xlim([0.0, 1.0])\n\n fig.canvas.draw()\n\n curve_img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')\n curve_img = curve_img.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n\n return curve_img\n\n\ndef box_filter(box, patch_dim):\n \"\"\"Remove rectangles that are too small\"\"\"\n x1, y1, x2, y2 = box\n return (x2-x1 > patch_dim) and (y2-y1 > patch_dim)\n\ndef test_filter_on_slide(svs_path, total_pos, total_neg, tumor_boxes,\n non_tumor_boxes, filter_fn, patch_dim):\n \"\"\"Test filter from patches from slide\n\n Compute statistics on patch filter based on\n hand-drawn tumor and non-tumor boxes.\n\n Args:\n svs_path (str): path to slide .svs file\n total_pos (int): desired number of true postive samples\n total_neg (int): desired number of true negative samples\n patch_dim (int): size of patches (assumed square)\n tumor_boxes (list): list of rectangles in slide which contain\n only tumor cells. Each rectangle consists\n of tuple (x1, y1, x2, y2), wehre (x1, x2)\n is top left, (x2, y2) is bottom right\n non_tumor_boxes (list): same as tumor boxes, except all \n cells in each box are healthy\n filter_fn (fn): funciton which takes in patch and outputs\n boolean\n\n Return:\n false_pos (int): number of false positives\n true_pos (int): number of true positives false_neg (int): number of false negatives\n true_neg (int): number of true positives\n total_pos (int): total number of positives\n total_neg (itn): total number of negatives\n \"\"\"\n slide = openslide.open_slide(svs_path)\n box_size_filter = lambda box: box_filter(box, patch_dim)\n tumor_boxes = filter(box_size_filter, tumor_boxes)\n non_tumor_boxes = filter(box_size_filter, non_tumor__boxes)\n \n results = defaultdict(int)\n for ground_truth in [True, False]:\n if ground_truth:\n relevant_boxes = tumor_boxse\n else:\n relevant_boxes = non_tumor_boxes\n for t in range(total_pos):\n x1, y1, x2, y2 = random.choice(relevant_boxes)\n x = random.choice(range(x1, x2))\n y = random.choice(range(y1, y2))\n patch = slide.read_region((x, y), 0, (patch_dim, patch_dim))\n patch = np.asarray(patch, dtype=np.unit8)\n patch = patch[:, :, :3] / 255.0\n label = filter_fn(patch)\n if ground_truth == 1:\n if label==ground_truth:\n results['true_pos'] += 1\n else:\n results['false_neg'] += 1\n else:\n if label==ground_truth:\n results['true_neg'] += 1\n else:\n results['false_pos'] += 1\n\n return false_pos, true_pos, false_neg, true_neg, total_pos, total_neg \n\n\ndef get_svs_files(svs_root):\n \"\"\"Get path to svs files in directory\"\"\"\n file_dict = {} \n for root, dirs, files in os.walk(svs_root):\n for f in files:\n if f.endswith(\".svs\"):\n file_dict[f[:-4]] = os.path.join(root, f)\n return file_dict \n\n\ndef test_on_slides(svs_root, json_path, filter_fn, patch_dim,\n total_pos_per_slide=25, total_neg_per_slide=25):\n \"\"\"Accumulate filter tests from multiple slides\n\n For each slide in root directory, test filter_fn and count\n true positives, false positives, true negatives, and false negatives.\n\n Args:\n svs_root (str): directory which holds relevant .svs files\n json_path (str): path to json which holds bounding boxes for\n each slide\n filter_fn (fn): function which takes in patch and outputs boolean\n patch_dim (int): size of patch (assumed square)\n total_pos_per_slide (int): desired number of true postive examples\n per slide\n total_neg_per_slide (int): desired number of true negative examples\n per slide\n \"\"\"\n \n svs_files = get_svs_files(svs_root)\n json_list = []\n for f_name in os.listdir(json_path):\n if f_name.endswith(\".json\"):\n with open(os.path.join(json_path, f_name), 'r') as f:\n json_list.append(json.load(f))\n slide_list = [x for l in json_list for x in l]\n \n result_dict = {}\n for entry in slide_list:\n slide_name = entry[\"metadata\"][\"slide_id\"]\n svs_filename = svs_files[slide_name]\n\n tumor_boxes = entry[\"boxes\"][\"Tumor\"]\n non_tumor_boxes = entry[\"boxes\"][\"Non_Tumor\"]\n\n slide_stats = test_filter_on_slide(svs_filename,\n total_pos_per_slide, total_neg_per_slide, tumor_boxes,\n non_tumor_boxes, filter_fn, patch_dim)\n\n result_dict[slide_name] = slide_stats \n print(\"Results for slide: {}\".format(slide_name))\n print(\"True pos: {}, False Pos: {}, True Neg: {}, False Neg: {}\"\n .format(slide_stats['true_pos'], slide_stats['false_pos'],\n slide_stats['true_neg'], slide_stats['false_neg']))\n print(\"Total pos: {}, Total neg: {}\".format(totp, totn))\n return result_dict\n \n\ndef main(args): \n result_dict = test_on_slides(args.svs_path, args.json_path,\n is_patch_tumor,\n args.patch_dim)\n\n\nif __name__ == \"__main__\": \n parser = argparse.ArgumentParser()\n parser.add_argument(\"--svs_path\", type=str,\n help=\"path to directory of .svs slide files\")\n parser.add_argument(\"--json_path\", type=str,\n help=\"path to directory of json files holding annotations\")\n parser.add_argument(\"--patch_dim\", type=int,\n help=\"dimension of square patches to be extracted\")\n\n args_ = parser.parse_args()\n main(args_)\n\n","sub_path":"util/patch_util.py","file_name":"patch_util.py","file_ext":"py","file_size_in_byte":15079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"466993626","text":"import sys\nimport os\nfrom optparse import OptionParser\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom general_utils import execute_command\nfrom general_utils import remove_file_if_exists\nfrom general_utils import get_average_accuracy\nfrom general_utils import cleanup_dir\nimport datetime\nfrom timeit import timeit\nfrom data_processing import plot_accuracy_for_tool\nfrom data_processing import plot_runtime_for_tool\nfrom data_processing import save_result_matrix_as_csv\n\n\n################### Global Vars ############################\n\nproject_dir = \"\"\nlog_dir = \"\"\nsimulation_script_path = \"\"\ntranscriptome_reference_file = \"\"\nsimulated_reads_dir = \"\"\n\nnumber_of_transcripts = 10\nverbose = True\n\nlog_file_name = \"\"\n\n################### Default Settings ############################\ndefault_readlen = 100\ndefault_error_rate = 0.005\ndefault_coverage = 20\n\n\ndef print_and_log(line):\n print(line)\n\n with open(log_dir + \"/\" + log_file_name, \"a\") as log:\n log.write(line + \"\\n\")\n\n\ndef simulate_reads(\n script_path, \n number_of_transcripts, \n readlen, \n error_rate, \n coverage, \n output_dir):\n \n remove_file_if_exists(output_dir + '/transcript_names.txt')\n remove_file_if_exists(output_dir + '/num_of_reads.txt')\n\n command = \"Rscript --vanilla \" \\\n + script_path + \" \" \\\n + str(number_of_transcripts) + \" \" \\\n + str(readlen) + \" \" \\\n + str(error_rate) + \" \" \\\n + str(coverage) + \" \" \\\n + str(output_dir) + \" \" \\\n\n execute_command(command, verbose)\n\n transcript_names = np.genfromtxt(\n output_dir + '/transcript_names.txt',\n names = None,\n dtype= None,\n usecols = (0))\n num_of_reads = np.genfromtxt(\n output_dir + '/num_of_reads.txt',\n names = None,\n dtype= None,\n usecols = (0))\n\n ground_truth_map = dict(zip(transcript_names, num_of_reads))\n\n return ground_truth_map\n\n\ndef get_index_dir_by_toolname(tool_name):\n return project_dir + \"/\" + tool_name + \"/index\"\n\n\ndef get_output_dir_by_toolname(tool_name):\n return project_dir + \"/\" + tool_name + \"/output\"\n\n\ndef convert_tool_name_to_module_name(tool_name):\n return tool_name + \"_adapter\"\n\n\ndef run_with_k_for_tool(tool_name, k, ground_truth_map, transcriptome_reference_file, simulated_reads_dir):\n print_and_log(\"quant with {0}, k={1}...\".format(tool_name,str(k)))\n tool = __import__(convert_tool_name_to_module_name(tool_name), fromlist=[''])\n tool.set_verbose(verbose)\n quantificatoin_map, runtime_ms = tool.run(k, transcriptome_reference_file, get_index_dir_by_toolname(tool_name), simulated_reads_dir, get_output_dir_by_toolname(tool_name))\n accuracy = get_average_accuracy(ground_truth_map, quantificatoin_map)\n print_and_log(\"\\t{0}_accuracy={1:f}, runtime(ms)={2:f}\".format(tool_name, accuracy, runtime_ms))\n return accuracy, runtime_ms\n\n\ndef run_with_simulation_parameters_for_tool(tool_name, k_range, number_of_transcripts, readlen, error_rate, coverage):\n global log_file_name\n log_file_name = \"{0}_readlen{1}_error{2:.0f}_coverage{3}\".format(tool_name,str(readlen),error_rate*1000.0,str(coverage))\n print(\"\\n\\n\")\n print_and_log(\"Simulation settings:\")\n print_and_log('{:>30} {:>8}'.format('number_of_transctipts:', str(number_of_transcripts)))\n print_and_log('{:>30} {:>8}'.format('readlen:', str(readlen)))\n print_and_log('{:>30} {:>8}'.format('error_rate:', str(error_rate)))\n print_and_log('{:>30} {:>8}'.format('coverage:', str(coverage)))\n ground_truth_map = simulate_reads(simulation_script_path, number_of_transcripts, readlen, error_rate, coverage, project_dir)\n print_and_log('{:>30} {:>8}'.format('Total Number of Reads:', str(sum(ground_truth_map.values()))))\n print_and_log(\"\")\n\n accuracies = []\n runtimes = []\n for k in k_range:\n if tool_name==\"kallisto\" and k>31:\n continue\n if tool_name==\"sailfish\" and k>31:\n continue\n accuracy, runtime_ms = run_with_k_for_tool(tool_name, k, ground_truth_map, transcriptome_reference_file, simulated_reads_dir)\n accuracies.append(accuracy) \n runtimes.append(runtime_ms)\n\n return accuracies, runtimes\n\n\ndef get_np_data_file_name(tool_name, loop_type, file_type):\n return \"{0}/{1}/{2}_{3}_{4}_matrix\".format(project_dir,'np_data',tool_name,loop_type, file_type)\n\n\ndef run_loop_for_tool(tool_name, loop_type, loop_range, k_range):\n accuracy_matrix = []\n runtime_matrix = []\n current_readlen = default_readlen\n current_coverage = default_coverage\n current_error_rate = default_error_rate\n\n for loop_value in loop_range:\n if(loop_type==\"coverage\"):\n current_coverage = loop_value\n elif(loop_type==\"error_rate\"):\n current_error_rate = loop_value\n elif(loop_type==\"readlen\"):\n current_readlen = loop_value\n\n accuracies, runtimes = run_with_simulation_parameters_for_tool(tool_name, k_range, number_of_transcripts, current_readlen, current_error_rate, current_coverage)\n accuracy_matrix.append(accuracies)\n runtime_matrix.append(runtimes)\n\n accuracy_np_data_file_name = get_np_data_file_name(tool_name, loop_type, 'accuracy')\n runtime_np_data_file_name = get_np_data_file_name(tool_name, loop_type, 'runtime')\n\n np.save(accuracy_np_data_file_name, accuracy_matrix)\n np.save(runtime_np_data_file_name, runtime_matrix)\n\n\ndef run_coverage_for_tool(tool_name, coverage_range, k_range):\n accuracy_matrix = []\n runtime_matrix = []\n\n for coverage in coverage_range:\n accuracies, runtimes = run_with_simulation_parameters_for_tool(tool_name, k_range, number_of_transcripts, default_readlen, default_error_rate, coverage)\n accuracy_matrix.append(accuracies)\n runtime_matrix.append(runtimes)\n\n accuracy_np_data_file = get_np_data_file_name(tool_name, 'coverage', 'accuracy')\n runtime_np_data_file = get_np_data_file_name(tool_name, 'coverage', 'runtime')\n\n np.save(accuracy_np_data_file,accuracy_matrix)\n np.save(runtime_np_data_file,runtime_matrix)\n\n\ndef run_error_rate_for_tool(tool_name, error_rate_range, k_range):\n accuracy_matrix = []\n runtime_matrix = []\n \n for error_rate in error_rate_range:\n accuracies, runtimes = run_with_simulation_parameters_for_tool(tool_name, k_range, number_of_transcripts, default_readlen, error_rate, default_coverage)\n accuracy_matrix.append(accuracies)\n runtime_matrix.append(runtimes)\n\n accuracy_np_data_file = get_np_data_file_name(tool_name, 'error_rate', 'accuracy')\n runtime_np_data_file = get_np_data_file_name(tool_name, 'error_rate', 'runtime')\n\n np.save(accuracy_np_data_file,accuracy_matrix)\n np.save(runtime_np_data_file,runtime_matrix)\n\n\ndef run_readlen_for_tool(tool_name, readlen_range, k_range):\n accuracy_matrix = []\n runtime_matrix = []\n \n for readlen in readlen_range:\n accuracies, runtimes = run_with_simulation_parameters_for_tool(tool_name, k_range, number_of_transcripts, readlen, default_error_rate, default_coverage)\n accuracy_matrix.append(accuracies)\n runtime_matrix.append(runtimes)\n\n accuracy_np_data_file = get_np_data_file_name(tool_name, 'readlen', 'accuracy')\n runtime_np_data_file = get_np_data_file_name(tool_name, 'readlen', 'runtime')\n\n np.save(accuracy_np_data_file,accuracy_matrix)\n np.save(runtime_np_data_file,runtime_matrix)\n\n\ndef init():\n parser = OptionParser()\n parser.add_option(\"-t\", \"--transcript\", dest=\"number_of_transcripts\", default=10,\n action=\"store\", type=\"int\",\n help=\"int, number of transcripts to use in the simulation\")\n\n parser.add_option(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\", default=True,\n help=\"don't print execution outputs\")\n\n (options, args) = parser.parse_args()\n\n\n global number_of_transcripts\n global project_dir\n global simulation_script_path\n global transcriptome_reference_file\n global simulated_reads_dir\n global verbose\n global log_dir\n\n number_of_transcripts = options.number_of_transcripts\n verbose = options.verbose\n\n OS = sys.platform\n # mac\n if(OS==\"darwin\"):\n project_dir = \"/Users/liyuanqi/Google_Drive/UCLA_MSCS/Quarter3/CS229S/Project\"\n simulation_script_path = project_dir + \"/simulation_script.R\"\n #ubuntu\n else:\n project_dir = \"/home/ubuntu/cs229\"\n simulation_script_path = project_dir + \"/CS229S_Project/simulation_script.R\"\n\n transcriptome_reference_file = project_dir + \"/chr22_small.fa\"\n simulated_reads_dir = project_dir + \"/simulated_reads\"\n\n start_time = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n log_dir = project_dir + \"/logs/\" +start_time\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n print(\"\\nRunning on platform: \" + OS + \"\\n\")\n print(\"Script Settings:\")\n print('{:>30} {:<50}'.format('Verbose:', str(verbose)))\n print('{:>30} {:<50}'.format('Project Directory:', str(project_dir)))\n print('{:>30} {:<50}'.format('Simulation Script:', str(simulation_script_path)))\n print('{:>30} {:<50}'.format('Transcript Reference:', str(transcriptome_reference_file)))\n print('{:>30} {:<50}'.format('Simulated Reads Directory:', str(simulated_reads_dir)))\n print(\"\")\n\n\ndef save_result(tool_name, loop_type, k_range, loop_range):\n accuracy_np_data_file_name = get_np_data_file_name(tool_name,loop_type,\"accuracy\")\n runtime_np_data_file = get_np_data_file_name(tool_name,loop_type,\"runtime\")\n accuracy_matrix = np.load(accuracy_np_data_file_name+'.npy')\n runtime_matrix = np.load(runtime_np_data_file+'.npy')\n while(len(k_range)!=len(accuracy_matrix[0])):\n k_range = np.delete(k_range,len(k_range)-1)\n\n # accuracy_matrix = np.delete(accuracy_matrix,(0),axis=0)\n # runtime_matrix = np.delete(runtime_matrix,(0),axis=0)\n\n save_result_matrix_as_csv(tool_name,\"accuracy\",loop_type,k_range,loop_range,accuracy_matrix)\n save_result_matrix_as_csv(tool_name,\"runtime\",loop_type,k_range,loop_range,runtime_matrix)\n plot_accuracy_for_tool(tool_name, loop_type, loop_range, k_range, accuracy_matrix)\n plot_runtime_for_tool(tool_name, loop_type, loop_range, k_range, runtime_matrix)\n\n\ndef main():\n init()\n # range settings\n k_range = []\n coverage_range = [1,10,20,30,40]\n error_rate_range = np.arange(0.0,0.08,0.01)\n readlen_range = np.arange(80,130,10)\n\n ranges_dict = {}\n ranges_dict[\"coverage\"] = coverage_range\n ranges_dict[\"error_rate\"] = error_rate_range\n ranges_dict[\"readlen\"] = readlen_range\n\n # tools = [\"kallisto\"]\n tools = [\"rnaskim\", \"sailfish\", \"salmon\", \"kallisto\"]\n\n for tool_name in tools:\n if tool_name == \"rnaskim\":\n k_range = np.arange(21,76,1)\n else:\n k_range = np.arange(11,32,2)\n\n for loop_type in ranges_dict.keys():\n run_loop_for_tool(tool_name, loop_type, ranges_dict[loop_type], k_range)\n save_result(tool_name,loop_type,k_range,ranges_dict[loop_type])\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"quantification_script.py","file_name":"quantification_script.py","file_ext":"py","file_size_in_byte":11146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"289298640","text":"import logging\nimport jwt\n\nfrom functools import wraps\nfrom flask import request, jsonify, current_app\nfrom gorillaspy.web.api.util import unauthenticated, unauthorized\n\n__author__ = 'toni'\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef user_has_roles(user, roles):\n \"\"\"\n Função auxilizar que verifica se o usuário possui ao menos uma das roles informadas.\n :param user:\n :param roles:\n :return:\n \"\"\"\n if not roles or len(roles) == 0:\n return True\n\n user_roles = user['roles']\n for user_role in user_roles:\n if user_role in roles:\n return True\n\n return False\n\n\ndef _get_authentication_payload():\n token = request.headers.get('Authentication-Token', request.cookies.get('token'))\n if not token:\n return None\n\n try:\n payload = jwt.decode(token, current_app.config.get('SECRET_KEY'))\n return payload\n except Exception as exc:\n LOGGER.error(exc)\n return None\n\n\ndef get_logged_user():\n payload = _get_authentication_payload()\n if not payload:\n return None\n\n try:\n from gorillaspy.web.auth import gorillas_auth\n user = gorillas_auth.gorillasauth_api.get_user(payload['auth_id'])\n user['auth_id'] = user['id']\n user['id'] = payload['id']\n return user\n except Exception as exc:\n LOGGER.error(exc)\n return None\n\n\ndef raise_for_authentication_fail(*roles):\n \"\"\"\n Raise uma exceção caso não tenha usuário autenticado.\n \"\"\"\n roles_list = list(roles)\n payload = _get_authentication_payload()\n\n if not payload:\n unauthorized()\n\n if not user_has_roles(payload, roles_list):\n unauthorized()\n\n\ndef check_authentication(*roles):\n return lambda **kw: raise_for_authentication_fail(*roles)\n\n\ndef auth_required(*args, **kwargs):\n \"\"\"\n Decorator que verifica o token de autenticação informado na requisição.\n\n Excemplo de utilização:\n\n @actions.route('/test', methods=['POST'])\n @cross_origin()\n @auth_required('role1', 'role2')\n def test():\n return 'OK'\n\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n\n roles = list(args)\n\n def wrapper(fn):\n\n @wraps(fn)\n def decorator(*args, **kargs):\n unauthorized = jsonify(error='Unauthorized'), 401\n\n payload = _get_authentication_payload()\n if not payload and len(roles):\n return unauthorized\n\n if payload and not user_has_roles(payload, roles):\n return unauthorized\n\n # if 'user' in fn.__code__.co_varnames:\n user = get_logged_user()\n kargs['user'] = user\n\n return fn(*args, **kargs)\n\n return decorator\n\n return wrapper\n\n\ndef generate_payload(local_user=None, auth_user=None):\n\n payload = dict(\n id=local_user.id,\n auth_id=auth_user['id'],\n name=auth_user['name'],\n email=auth_user['email'],\n roles=auth_user['roles'],\n profile_photo=auth_user['profile_photo']\n )\n\n return payload\n\n\ndef generate_authentication_token(payload):\n\n return jwt.encode(payload, current_app.config.get('SECRET_KEY'), algorithm='HS256').decode('utf-8')\n","sub_path":"gorillaspy/web/auth/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"157055264","text":"import infoGen\nimport random\n\nclass Account:\n def __init__(self):\n self.name = infoGen.getCompanyName()\n self.budget = random.randint(500000, 2000000)\n self.difficulty = random.randint(0, 100)\n def addToFile(self, file):\n with open(file, 'a') as myFile:\n myFile.write(self.name + ',' + str(self.budget) + ',' + str(self.difficulty) + '\\n')","sub_path":"account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"578051828","text":"import os\nimport mock\nimport logging\nimport unittest\nfrom rackattack.common import hoststatemachine\nfrom rackattack.common import globallock\nfrom rackattack.common import timer\nfrom rackattack.common.tests.common import FakeHost\nfrom rackattack.common import reclaimhostspooler\n\n\nclass Empty:\n pass\n\n\nclass FakeTFTPBoot:\n def __init__(self, test):\n self.inauguratorCommandLine = mock.Mock(side_effect=self._inauguratorCommandLine)\n self.configureForInaugurator = mock.Mock(side_effect=self._configureForInaugurator)\n self.configureForLocalBoot = mock.Mock(side_effect=self._configureForLocalBoot)\n self.test = test\n self.expectedToBeConfiguredForLocalBoot = False\n self.expectedToBeConfiguredForInaugurator = False\n self._reset()\n\n def expectToBeConfiguredForInaugurator(self):\n self.test.assertFalse(self.expectedToBeConfiguredForInaugurator)\n self.expectedToBeConfiguredForInaugurator = True\n\n def expectToBeConfiguredForLocalBoot(self):\n self.test.assertFalse(self.expectedToBeConfiguredForLocalBoot)\n self.expectedToBeConfiguredForLocalBoot = True\n\n def validateConfiguredOnceForInaugurator(self):\n callCount = self.configureForInaugurator.call_count\n self.configureForInaugurator.reset_mock()\n self.test.assertEquals(callCount, 1)\n\n def validateConfiguredOnceForLocalBoot(self):\n callCount = self.configureForLocalBoot.call_count\n self.configureForLocalBoot.reset_mock()\n self.test.assertEquals(callCount, 1)\n\n def _inauguratorCommandLine(self, id, mac, ip):\n self.test.assertEquals(id, self.test.hostImplementation.id())\n self.test.assertEquals(mac, self.test.hostImplementation.primaryMACAddress())\n self.test.assertEquals(ip, self.test.hostImplementation.ipAddress())\n return \"fake inaugurator command line\"\n\n def _reset(self):\n self.expectedToBeConfiguredForLocalBoot = False\n self.expectedToBeConfiguredForInaugurator = False\n self.inauguratorCommandLine.reset_mock()\n self.configureForInaugurator.reset_mock()\n self.configureForLocalBoot.reset_mock()\n\n def _configureForInaugurator(self, id, mac, ip, serialPort, clearDisk=False, targetDevice=None,\n targetDeviceType=None):\n self.test.assertEquals(id, self.test.hostImplementation.id())\n self.test.assertEquals(mac, self.test.hostImplementation.primaryMACAddress())\n self.test.assertEquals(ip, self.test.hostImplementation.ipAddress())\n self.test.assertTrue(self.expectedToBeConfiguredForInaugurator)\n self.test.assertEquals(clearDisk, self.test.expectedClearDisk)\n self.expectedToBeConfiguredForInaugurator = False\n\n def _configureForLocalBoot(self, mac, serialPort):\n self.test.assertEquals(mac, self.test.hostImplementation.primaryMACAddress())\n self.test.assertTrue(self.expectedToBeConfiguredForLocalBoot)\n self.expectedToBeConfiguredForLocalBoot = False\n\n\nclass Test(unittest.TestCase):\n def setUp(self):\n globallock._lock.acquire()\n self.addCleanup(self.releaseGlobalLock)\n self.checkInCallback = None\n self.doneCallback = None\n self.failureCallback = None\n self.expectedProvidedLabel = None\n self.provideLabelRaises = False\n self.expectedReportedState = None\n timer.scheduleIn = self.scheduleTimerIn\n timer.cancelAllByTag = self.cancelAllTimersByTag\n self.currentTimer = None\n self.currentTimerTag = None\n self.expectedColdReclaim = False\n self.expectReconfigureBIOS = False\n self.expectedHardReset = True\n self.expectedSoftReclaim = False\n self.expectedSelfDestruct = False\n self.softReclaimFailedCallback = None\n self.construct()\n\n @classmethod\n def setUpClass(cls):\n cls.configureLogging()\n\n @classmethod\n def configureLogging(self):\n logger = logging.getLogger()\n verbosity = int(os.getenv(\"VERBOSITY\", 0))\n logLevels = {0: logging.CRITICAL + 1,\n 1: logging.ERROR,\n 2: logging.INFO,\n 3: logging.DEBUG}\n maxVerbosity = max(logLevels.keys())\n if verbosity > maxVerbosity:\n verbosity = maxVerbosity\n elif verbosity < 0:\n verbosity = 0\n logLevel = logLevels[verbosity]\n logger.setLevel(logLevel)\n\n def releaseGlobalLock(self):\n globallock._lock.release()\n\n def construct(self):\n self.hostImplementation = FakeHost()\n self.fakeInaugurate = Empty()\n self.fakeInaugurate.provideLabel = self.provideLabelForInauguration\n self.fakeInaugurate.register = self.registerForInauguration\n self.fakeInaugurate.unregister = self.unregisterForInauguration\n self.fakeTFTPBoot = FakeTFTPBoot(self)\n self.fakeDnsmasq = Empty()\n self.fakeDnsmasq.addIfNotAlready = self.dnsmasqAddIfNotAlready\n self.fakeReclaimHost = Empty()\n self.patchWithSpecValidation(fakeObject=self.fakeReclaimHost,\n realMethod=reclaimhostspooler.ReclaimHostSpooler.cold,\n fakeMethod=self.reclaimHostCold)\n self.patchWithSpecValidation(fakeObject=self.fakeReclaimHost,\n realMethod=reclaimhostspooler.ReclaimHostSpooler.soft,\n fakeMethod=self.reclaimHostSoft)\n self.fakeTFTPBoot.expectToBeConfiguredForInaugurator()\n self.expectedDnsmasqAddIfNotAlready = True\n self.expectedClearDisk = False\n hoststatemachine.HostStateMachine.ALLOW_CLEARING_OF_DISK = True\n self.tested = hoststatemachine.HostStateMachine(\n hostImplementation=self.hostImplementation,\n inaugurate=self.fakeInaugurate, tftpboot=self.fakeTFTPBoot, dnsmasq=self.fakeDnsmasq,\n reclaimHost=self.fakeReclaimHost)\n self.tested.setDestroyCallback(self.destroyHost)\n self.assertIs(self.tested.hostImplementation(), self.hostImplementation)\n self.fakeTFTPBoot.validateConfiguredOnceForInaugurator()\n assert self.checkInCallback is not None\n assert self.doneCallback is not None\n\n def patchWithSpecValidation(self, fakeObject, realMethod, fakeMethod):\n specValidator = mock.create_autospec(realMethod)\n methodName = realMethod.__name__\n\n def useFakeMethodWithSpecValidation(*args, **kwargs):\n fakeSelf = None\n try:\n specValidator(fakeSelf, *args, **kwargs)\n except TypeError as ex:\n msg = \"It seems that method '%(methodName)s' was used with the wrong argument \" \\\n \"specification; args:%(args)s, kwargs: %(kwargs)s \" \\\n % dict(methodName=methodName, args=args, kwargs=kwargs)\n ex.message = \"%(msg)s. Original message: '%(origMessage)s'.\" % dict(msg=msg,\n origMessage=ex.message)\n ex.args = (ex.message,)\n raise ex\n fakeMethod(*args, **kwargs)\n setattr(fakeObject, methodName, useFakeMethodWithSpecValidation)\n\n def destroyHost(self, stateMachine):\n self.assertIs(stateMachine, self.tested)\n self.assertTrue(self.expectedSelfDestruct)\n self.expectedSelfDestruct = False\n\n def scheduleTimerIn(self, timeout, callback, tag):\n self.assertIs(self.currentTimer, None)\n self.assertIs(self.currentTimerTag, None)\n self.currentTimer = callback\n self.currentTimerTag = tag\n\n def cancelAllTimersByTag(self, tag):\n if self.currentTimerTag is not None:\n self.assertIsNot(self.currentTimer, None)\n self.assertIs(self.currentTimerTag, tag)\n self.currentTimer = None\n self.currentTimerTag = None\n\n def triggerTimeout(self):\n self.assertIsNot(self.currentTimer, None)\n self.assertIsNot(self.currentTimerTag, None)\n self.currentTimer()\n self.currentTimer = None\n self.currentTimerTag = None\n\n def registerForInauguration(self, id, checkInCallback, doneCallback, progressCallback, failureCallback):\n self.assertEquals(id, self.hostImplementation.id())\n self.assertIs(self.checkInCallback, None)\n self.assertIs(self.doneCallback, None)\n self.checkInCallback = checkInCallback\n self.doneCallback = doneCallback\n self.progressCallback = progressCallback\n self.failureCallback = failureCallback\n\n def unregisterForInauguration(self, id):\n self.assertIsNot(self.checkInCallback, None)\n self.assertIsNot(self.doneCallback, None)\n self.assertIsNot(self.progressCallback, None)\n self.checkInCallback = None\n self.doneCallback = None\n self.progressCallback = None\n\n def assertRegisteredForInauguration(self, id):\n self.assertEquals(id, self.hostImplementation.id())\n self.assertIsNot(self.checkInCallback, None)\n self.assertIsNot(self.doneCallback, None)\n self.assertIsNot(self.progressCallback, None)\n\n def assertUnegisteredForInauguration(self, id):\n self.assertIs(self.checkInCallback, None)\n self.assertIs(self.doneCallback, None)\n self.assertIs(self.progressCallback, None)\n\n def provideLabelForInauguration(self, id, label):\n self.assertEquals(id, self.hostImplementation.id())\n if self.provideLabelRaises:\n raise Exception(\"Provide label raises on purpose, as part of test\")\n self.actualProvidedLabel = label\n\n def isObjectInitialized(self):\n return hasattr(self, 'tested')\n\n def dnsmasqAddIfNotAlready(self, mac, ip):\n self.assertEquals(mac, self.hostImplementation.primaryMACAddress())\n self.assertEquals(ip, self.hostImplementation.ipAddress())\n self.assertTrue(self.expectedDnsmasqAddIfNotAlready)\n self.expectedDnsmasqAddIfNotAlready = False\n\n def reclaimHostCold(self, hostImplementation, reconfigureBIOS=False, hardReset=False):\n self.assertIs(hostImplementation, self.hostImplementation)\n self.assertTrue(self.expectedColdReclaim)\n self.expectedColdReclaim = False\n self.assertEqual(self.expectReconfigureBIOS, reconfigureBIOS)\n self.assertEqual(self.expectedHardReset, hardReset)\n\n def reclaimHostSoft(self, hostImplementation, serialPort, isInauguratorActive=False,\n maxUptime=9999):\n self.assertIs(hostImplementation, self.hostImplementation)\n self.assertTrue(self.expectedSoftReclaim)\n self.expectedSoftReclaim = False\n self.softReclaimFailedCallback = self.tested.softReclaimFailed\n\n def validateProvidedLabel(self, expected):\n self.assertEquals(self.actualProvidedLabel, expected)\n self.expectedProvidedLabel = None\n\n def validateCheckInCallbackProvidesLabelImmediately(self, label):\n self.assertIn(self.tested.state(), [\n hoststatemachine.STATE_SOFT_RECLAMATION,\n hoststatemachine.STATE_COLD_RECLAMATION])\n self.assertIs(self.expectedProvidedLabel, None)\n self.expectedProvidedLabel = label\n self.assertIs(self.expectedReportedState, None)\n self.expectedReportedState = hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED\n self.checkInCallback()\n self.validateProvidedLabel(expected=label)\n self.assertIs(self.expectedReportedState, None)\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED)\n\n def stateChangedCallback(self, tested):\n self.assertIs(tested, self.tested)\n self.assertIsNot(self.expectedReportedState, None)\n self.assertEquals(tested.state(), self.expectedReportedState)\n self.expectedReportedState = None\n\n def inaugurationDone(self):\n self.assertIn(self.tested.state(), [hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED])\n self.assertIs(self.expectedProvidedLabel, None)\n self.assertIs(self.expectedReportedState, None)\n self.expectedReportedState = hoststatemachine.STATE_INAUGURATION_DONE\n self.fakeTFTPBoot.expectToBeConfiguredForLocalBoot()\n self.doneCallback()\n self.assertIs(self.expectedProvidedLabel, None)\n self.assertIs(self.expectedReportedState, None)\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_DONE)\n self.fakeTFTPBoot.validateConfiguredOnceForLocalBoot()\n self.assertIs(self.currentTimer, None)\n\n def inaugurationFailed(self, isLastAttemptBeforeRevertingToColdReclamation=False):\n self.assertIn(self.tested.state(), [hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED])\n self.assertIs(self.expectedProvidedLabel, None)\n self.assertIs(self.expectedReportedState, None)\n if isLastAttemptBeforeRevertingToColdReclamation:\n expectedReportedState = hoststatemachine.STATE_COLD_RECLAMATION\n else:\n expectedReportedState = hoststatemachine.STATE_SOFT_RECLAMATION\n self.expectedReportedState = expectedReportedState\n self.fakeTFTPBoot.expectToBeConfiguredForInaugurator()\n self.expectedDnsmasqAddIfNotAlready = True\n self.expectedSoftReclaim = True\n self.failureCallback(message=\"Some osmosis failure\")\n self.assertIs(self.expectedProvidedLabel, None)\n self.assertIs(self.expectedReportedState, None)\n self.assertEquals(self.tested.state(), expectedReportedState)\n self.fakeTFTPBoot.validateConfiguredOnceForInaugurator()\n\n def assign(self, label, hint):\n self.tested.assign(self.stateChangedCallback, label, hint)\n self.assertEquals(self.tested.imageLabel(), label)\n self.assertEquals(self.tested.imageHint(), hint)\n\n def test_vmLifeCycle_Normal(self):\n self.assertRegisteredForInauguration(self.hostImplementation.id())\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.assign(\"fake image label\", \"fake image hint\")\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED)\n self.inaugurationDone()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_DONE)\n self.assertRegisteredForInauguration(self.hostImplementation.id())\n\n def unassignCausesSoftReclaim(self):\n self.assertFalse(self.expectedSoftReclaim)\n self.expectedSoftReclaim = True\n self.fakeTFTPBoot.expectToBeConfiguredForInaugurator()\n self.expectedDnsmasqAddIfNotAlready = True\n self.tested.unassign()\n self.assertFalse(self.expectedSoftReclaim)\n self.assertFalse(self.expectedColdReclaim)\n self.fakeTFTPBoot.validateConfiguredOnceForInaugurator()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.assertRegisteredForInauguration(self.hostImplementation.id())\n\n def validateCallCausesColdReclamation(self, call):\n self.assertFalse(self.expectedColdReclaim)\n self.expectedColdReclaim = True\n self.fakeTFTPBoot.expectToBeConfiguredForInaugurator()\n self.expectedDnsmasqAddIfNotAlready = True\n call()\n self.assertFalse(self.expectedColdReclaim)\n self.fakeTFTPBoot.validateConfiguredOnceForInaugurator()\n self.assertFalse(self.expectedDnsmasqAddIfNotAlready)\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_COLD_RECLAMATION)\n self.assertRegisteredForInauguration(self.hostImplementation.id())\n\n def validateCallCausesSoftReclamation(self, call):\n self.assertFalse(self.expectedColdReclaim)\n self.expectedSoftReclaim = True\n self.fakeTFTPBoot.expectToBeConfiguredForInaugurator()\n self.expectedDnsmasqAddIfNotAlready = True\n call()\n self.assertFalse(self.expectedSoftReclaim)\n self.fakeTFTPBoot.validateConfiguredOnceForInaugurator()\n self.assertFalse(self.expectedDnsmasqAddIfNotAlready)\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.assertRegisteredForInauguration(self.hostImplementation.id())\n\n def validateCallCausesReclamationAndStateReport(self, call, state):\n self.assertIs(self.expectedReportedState, None)\n self.expectedReportedState = state\n if state == hoststatemachine.STATE_COLD_RECLAMATION:\n self.validateCallCausesColdReclamation(call)\n elif state == hoststatemachine.STATE_SOFT_RECLAMATION:\n self.validateCallCausesSoftReclamation(call)\n else:\n self.assertFalse(True, state)\n self.assertIs(self.expectedReportedState, None)\n\n def validateCallCausesSoftReclamationAndStateReport(self, call):\n self.validateCallCausesReclamationAndStateReport(call, hoststatemachine.STATE_SOFT_RECLAMATION)\n\n def validateCallCausesColdReclamationAndStateReport(self, call):\n self.validateCallCausesReclamationAndStateReport(call, hoststatemachine.STATE_COLD_RECLAMATION)\n\n def test_vmLifeCycle_OrderlyRelease(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.inaugurationDone()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_DONE)\n self.unassignCausesSoftReclaim()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.assertRegisteredForInauguration(self.hostImplementation.id())\n\n def test_vmLifeCycle_OrderlyRelease_QuickReclamationDidNotWork(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.inaugurationDone()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_DONE)\n self.unassignCausesSoftReclaim()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.validateCallCausesColdReclamation(self.softReclaimFailedCallback)\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_COLD_RECLAMATION)\n self.assertRegisteredForInauguration(self.hostImplementation.id())\n\n def validateAssignCallbackProvidesLabelImmediately(self, label, hint):\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_CHECKED_IN)\n self.assertIs(self.expectedProvidedLabel, None)\n self.expectedProvidedLabel = label\n self.assertIs(self.expectedReportedState, None)\n self.expectedReportedState = hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED\n self.assign(label, hint)\n self.validateProvidedLabel(expected=label)\n self.assertIs(self.expectedReportedState, None)\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED)\n\n def test_vmLifeCycle_Reuse_ReachedCheckeInBeforeReuse(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.inaugurationDone()\n self.unassignCausesSoftReclaim()\n self.checkInCallbackLingers()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_CHECKED_IN)\n self.validateAssignCallbackProvidesLabelImmediately(\"fake image label 2\", \"fake image hint 2\")\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED)\n self.inaugurationDone()\n self.unassignCausesSoftReclaim()\n self.assertRegisteredForInauguration(self.hostImplementation.id())\n\n def test_vmLifeCycle_Reuse_ReassignedBeforeReachingCheckeIn(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.inaugurationDone()\n self.unassignCausesSoftReclaim()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.assign(\"fake image label 2\", \"fake image hint 2\")\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label 2\")\n self.inaugurationDone()\n self.unassignCausesSoftReclaim()\n\n def checkInCallbackLingers(self):\n self.assertIn(self.tested.state(), [\n hoststatemachine.STATE_SOFT_RECLAMATION,\n hoststatemachine.STATE_COLD_RECLAMATION])\n self.checkInCallback()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_CHECKED_IN)\n self.assertIs(self.currentTimer, None)\n\n def test_vmLifeCycle_QuickReclamationFailedWhenAssigned_UserDecidesToUnassign(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.inaugurationDone()\n self.unassignCausesSoftReclaim()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.assign(\"fake image label\", \"fake image hint\")\n self.assertIsNot(self.softReclaimFailedCallback, None)\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.validateCallCausesColdReclamationAndStateReport(self.softReclaimFailedCallback)\n self.tested.unassign()\n self.checkInCallbackLingers()\n self.assertRegisteredForInauguration(self.hostImplementation.id())\n\n def test_vmLifeCycle_QuickReclamationFailedWithTimeoutWhenAssigned_UserDecidesToUnassign(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self.validateCallCausesColdReclamationAndStateReport(self.currentTimer)\n self.tested.unassign()\n self.checkInCallbackLingers()\n self.assertRegisteredForInauguration(self.hostImplementation.id())\n\n def test_coldReclamationSavesTheDay(self):\n self.validateCallCausesColdReclamation(self.currentTimer)\n self.checkInCallbackLingers()\n\n def validateTimerCausesSelfDestruct(self):\n self.assertFalse(self.expectedSelfDestruct)\n self.expectedSelfDestruct = True\n self.hostImplementation.expectedDestroy = True\n self.currentTimer()\n self.assertFalse(self.expectedSelfDestruct)\n self.assertFalse(self.hostImplementation.expectedDestroy)\n self.assertUnegisteredForInauguration(self.hostImplementation.id())\n\n def validateTimerCausesSelfDestructionAndStateReport(self):\n self.assertIs(self.expectedReportedState, None)\n self.expectedReportedState = hoststatemachine.STATE_DESTROYED\n self.validateTimerCausesSelfDestruct()\n self.assertIs(self.expectedReportedState, None)\n\n def validateDestructionOfHost(self, isAssigned):\n if isAssigned:\n validationMethod = self.validateCallCausesColdReclamationAndStateReport\n else:\n validationMethod = self.validateCallCausesColdReclamation\n klass = hoststatemachine.HostStateMachine\n for retryNr in range(1, klass.NR_CONSECUTIVE_ERRORS_BEFORE_DESTRUCTION + 1):\n if retryNr > klass.NR_CONSECUTIVE_ERRORS_BEFORE_HARD_RESET or retryNr == 1:\n self.expectedHardReset = True\n else:\n self.expectedHardReset = False\n if retryNr == klass.NR_CONSECUTIVE_ERRORS_BEFORE_CLEARING_DISK + 1:\n self.expectedClearDisk = True\n if retryNr == klass.NR_CONSECUTIVE_ERRORS_BEFORE_RECONFIGURING_BIOS + 1:\n self.expectReconfigureBIOS = True\n validationMethod(self.currentTimer)\n\n def validateTimeoutOnSoftReclamation(self, isLastAttemptBeforeRevertingToColdReclamation=False):\n self.expectedDnsmasqAddIfNotAlready = True\n self.expectedSoftReclaim = True\n if isLastAttemptBeforeRevertingToColdReclamation:\n expectedReportedState = hoststatemachine.STATE_COLD_RECLAMATION\n else:\n expectedReportedState = hoststatemachine.STATE_SOFT_RECLAMATION\n self.expectedReportedState = expectedReportedState\n self.fakeTFTPBoot.expectToBeConfiguredForInaugurator()\n self.currentTimer()\n self.assertIs(self.expectedProvidedLabel, None)\n self.assertIs(self.expectedReportedState, None)\n self.assertEquals(self.tested.state(), expectedReportedState)\n self.fakeTFTPBoot.validateConfiguredOnceForInaugurator()\n\n def _reachMaxInaugurationFailureCountByFailureReports(self, imageLabel):\n failureCallback = self.inaugurationFailed\n self._reachMaxInaugurationFailureCount(imageLabel, failureCallback)\n\n def _reachMaxInaugurationFailureCountBySoftReclamationTimeouts(self, imageLabel):\n failureCallback = self.validateTimeoutOnSoftReclamation\n self._reachMaxInaugurationFailureCount(imageLabel, failureCallback)\n\n def _reachMaxInaugurationFailureCount(self, imageLabel, failureCallback):\n nrRetries = hoststatemachine.HostStateMachine.MAX_NR_CONSECUTIVE_INAUGURATION_FAILURES\n for _ in xrange(nrRetries):\n self.validateCheckInCallbackProvidesLabelImmediately(imageLabel)\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED)\n failureCallback()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n\n def validateInaugurationDoneMessageReloadsSoftReclamationRetries(self, failureCallback):\n self.assign(\"fake image label\", \"fake image hint\")\n self._reachMaxInaugurationFailureCountByFailureReports(\"fake image label\")\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED)\n self.inaugurationDone()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_DONE)\n self.unassignCausesSoftReclaim()\n self.assign(\"fake image label\", \"fake image hint\")\n self._reachMaxInaugurationFailureCountByFailureReports(\"fake image label\")\n\n def test_vmLifeCycle_AllReclamationRetriesFail_NoUser(self):\n self.validateDestructionOfHost(isAssigned=False)\n self.validateTimerCausesSelfDestruct()\n\n def test_vmLifeCycle_AllReclamationRetriesFail_WithUser(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self.validateDestructionOfHost(isAssigned=True)\n self.validateTimerCausesSelfDestructionAndStateReport()\n self.assertUnegisteredForInauguration(self.hostImplementation.id())\n\n def test_lateInaugurationDoneMessageDoesNotChangeState(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.inaugurationDone()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_DONE)\n self.doneCallback()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_DONE)\n\n def test_checkInWhileNotReclaiming(self):\n label = \"fake image label\"\n self.assign(label, \"fake image hint\")\n self.validateCheckInCallbackProvidesLabelImmediately(label)\n self.assertIs(self.expectedReportedState, None)\n self.expectedReportedState = hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED\n self.assertIs(self.expectedProvidedLabel, None)\n self.checkInCallback()\n self.assertIs(self.expectedProvidedLabel, None)\n self.assertIs(self.expectedReportedState, None)\n\n def test_softReclamationFailureWhileDestroyedDoesNotChangeState(self):\n self.validateDestructionOfHost(isAssigned=False)\n self.validateTimerCausesSelfDestruct()\n self.assertUnegisteredForInauguration(self.hostImplementation.id())\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_DESTROYED)\n self.tested.softReclaimFailed()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_DESTROYED)\n\n def test_vmLifeCycle_notAFreshVM(self):\n self.currentTimer = None\n self.currentTimerTag = None\n self.checkInCallback = None\n self.doneCallback = None\n self.expectedDnsmasqAddIfNotAlready = True\n self.fakeTFTPBoot.expectToBeConfiguredForInaugurator()\n self.fakeDnsmasq.addIfNotAlready = mock.Mock()\n self.fakeTFTPBoot.configureForInaugurator = mock.Mock()\n self.expectedColdReclaim = True\n self.tested = hoststatemachine.HostStateMachine(\n hostImplementation=self.hostImplementation, inaugurate=self.fakeInaugurate,\n tftpboot=self.fakeTFTPBoot, dnsmasq=self.fakeDnsmasq, freshVMJustStarted=False,\n reclaimHost=self.fakeReclaimHost)\n self.tested.setDestroyCallback(self.destroyHost)\n self.assertIs(self.tested.hostImplementation(), self.hostImplementation)\n assert self.checkInCallback is not None\n assert self.doneCallback is not None\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_COLD_RECLAMATION)\n\n def test_vmLifeCycle_inauguratorProgress(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.cancelAllTimersByTag(self.tested)\n self.progressCallback(dict(percent=100))\n self.assertIs(self.currentTimerTag, None)\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED)\n self.cancelAllTimersByTag(self.tested)\n self.progressCallback(dict(percent=100))\n self.assertIs(self.currentTimerTag, None)\n self.progressCallback(dict(state='fetching', percent=100))\n self.assertIsNot(self.currentTimerTag, None)\n self.progressCallback(dict(state='whatisthisstate', percent=100))\n self.assertIsNot(self.currentTimerTag, None)\n self.inaugurationDone()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_DONE)\n self.cancelAllTimersByTag(self.tested)\n self.progressCallback(dict(percent=100))\n self.assertIs(self.currentTimerTag, None)\n self.unassignCausesSoftReclaim()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.validateCallCausesColdReclamation(self.softReclaimFailedCallback)\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_COLD_RECLAMATION)\n self.cancelAllTimersByTag(self.tested)\n self.progressCallback(dict(percent=100))\n self.assertIs(self.currentTimerTag, None)\n self.checkInCallback()\n self.cancelAllTimersByTag(self.tested)\n self.progressCallback(dict(percent=100))\n self.assertIs(self.currentTimerTag, None)\n\n def test_clearingOfDiskNotAllowed(self):\n hoststatemachine.HostStateMachine.ALLOW_CLEARING_OF_DISK = False\n self.expectedClearDisk = False\n self.validateCallCausesColdReclamation(self.currentTimer)\n self.expectedHardReset = False\n self.validateCallCausesColdReclamation(self.currentTimer)\n self.validateCallCausesColdReclamation(self.currentTimer)\n self.expectedHardReset = True\n self.validateCallCausesColdReclamation(self.currentTimer)\n\n def test_timeoutWhenWaitingForInaugurationCausesSoftReclamation(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED)\n self.validateCallCausesSoftReclamationAndStateReport(self.currentTimer)\n\n def test_failureDuringInaugurationCausesSoftReclamation(self):\n self.checkInCallback()\n self.expectedReportedState = hoststatemachine.STATE_INAUGURATION_LABEL_PROVIDED\n self.assign(\"fake image label\", \"fake image hint\")\n self.inaugurationFailed()\n\n def test_revertToColdReclamationByExhaustingSoftReclamationsDueToInaugurationFailures(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self._reachMaxInaugurationFailureCountByFailureReports(\"fake image label\")\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.expectedColdReclaim = True\n self.inaugurationFailed(isLastAttemptBeforeRevertingToColdReclamation=True)\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_COLD_RECLAMATION)\n\n def test_stayInSoftReclamationOnTimeoutAfterProvidingLabel(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self._reachMaxInaugurationFailureCountBySoftReclamationTimeouts(\"fake image label\")\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.expectedColdReclaim = False\n self.inaugurationFailed()\n self.assertEquals(self.tested.state(), hoststatemachine.STATE_SOFT_RECLAMATION)\n\n def test_coldReclamationBehavesNormallyAfterExhaustionOfSoftReclamationsDueToInaugurationFailures(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self._reachMaxInaugurationFailureCountByFailureReports(\"fake image label\")\n self.validateDestructionOfHost(isAssigned=True)\n\n def test_coldReclamationBehavesNormallyAfterExhaustionOfSoftReclamationsDueTimeouts(self):\n self.assign(\"fake image label\", \"fake image hint\")\n self._reachMaxInaugurationFailureCountBySoftReclamationTimeouts(\"fake image label\")\n self.validateDestructionOfHost(isAssigned=True)\n\n def test_unassigningDoesNotCauseDestruction(self):\n \"\"\"This was created specifically to validate that allocations that are being stopped before the\n inauguration is either done, failed or timed out (could be a user manually stopping the\n allocation, or a timeout value smaller in the test client than in Rackattack), do not cause the\n state machine to be destroyed. To be destroyed, it has to either notify failure or timeout.\"\"\"\n nrRetries = hoststatemachine.HostStateMachine.MAX_NR_CONSECUTIVE_INAUGURATION_FAILURES + \\\n hoststatemachine.HostStateMachine.NR_CONSECUTIVE_ERRORS_BEFORE_DESTRUCTION + 20\n for _ in xrange(nrRetries):\n self.assign(\"fake image label\", \"fake image hint\")\n self.validateCheckInCallbackProvidesLabelImmediately(\"fake image label\")\n self.unassignCausesSoftReclaim()\n\n def test_InaugurationDoneMessageReloadsSoftReclamationRetriesAfterInaugurationFailureReports(self):\n def failureCallback():\n self._reachMaxInaugurationFailureCountByFailureReports(\"fake image label\")\n self.validateInaugurationDoneMessageReloadsSoftReclamationRetries(failureCallback)\n\n def test_InaugurationDoneMessageReloadsSoftReclamationRetriesAfterSoftReclamationTimeouts(self):\n def failureCallback():\n self._reachMaxInaugurationFailureCountBySoftReclamationTimeouts(\"fake image label\")\n self.validateInaugurationDoneMessageReloadsSoftReclamationRetries(failureCallback)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"rackattack/common/tests/test_hoststatemachine.py","file_name":"test_hoststatemachine.py","file_ext":"py","file_size_in_byte":35682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"352851594","text":"from selenium import webdriver\nfrom time import sleep\nimport config\nimport json\n\n\ndef access_url(driver,url):\n driver.get(str(url))\n sleep(config.sleep_time)\n\n\ndef save_categories(path,categories):\n\twith open(path,'w') as f:\n\t\tfor cate in categories:\n\t\t\tf.write(str(cate)+'\\n')\n\n\ndef get_categories(driver):\n\tcategories = []\n\ti=0\n\twhile True:\n\t\ti+=1\n\t\ttry:\n\t\t\ta = driver.find_element_by_xpath(config.cateXpath.format(i))\n\t\t\tcategories.append(a.get_attribute('href'))\n\t\texcept:\n\t\t\tbreak\n\tsave_categories(config.category_path,categories)\n\n\ndef get_cate_name(cate):\n\tcate = cate.split('-')\n\tcate = cate[7:-3]\n\treturn ' '.join(cate)\n\n\ndef load_cates(path=config.category_path):\n\tcategories = []\n\twith open(path,'r') as f:\n\t\tfor cate in f.readlines():\n\t\t\tcategories.append(cate[:-1])\n\treturn categories[1:]\n\n\ndef get_item_links(driver,categories):\n\tdic = {}\n\tfor cate in load_cates():\n\t\tcate_name = get_cate_name(cate)\n\t\titem_links = []\n\t\taccess_url(driver,cate)\n\t\tpage_n = 0\n\t\twhile True:\n\t\t\tpage_n+=1\n\t\t\ttry:\n\t\t\t\tpage = driver.find_element_by_xpath(config.page_xpath.format(page_n))\n\t\t\t\tpage.click()\n\t\t\t\tsleep(config.sleep_time/2)\n\t\t\t\ti=1\n\t\t\t\twhile True:\n\t\t\t\t\ti+=1\n\t\t\t\t\ttry:\n\t\t\t\t\t\ta = driver.find_element_by_xpath(config.item_xpath.format(i))\n\t\t\t\t\t\titem_links.append(a.get_attribute('href'))\n\t\t\t\t\t\tsleep(config.sleep_time)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tbreak\n\t\t\texcept:\n\t\t\t\tbreak\n\t\tdic[cate_name]=item_links\n\n\twith open('item_links.json','w') as f:\n\t\tjson.dump(dic,f,indent=4)\n\n\n\nif __name__ == '__main__':\n\tdriver = webdriver.Chrome()\n\taccess_url(driver,config.main_web_url)\n\tget_categories(driver)\n\tcategories = load_cates()\n\tget_item_links(driver,categories)\n\n\n","sub_path":"crawler/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"108138680","text":"import music21 as m\nimport os\nimport csv\n\n\n#Creo una nuova classe con lo scopo di poter generare una lista di canzoni con il\n# parsing dell'MXL in string e vettore numerico di intervalli associato\nclass SongParse:\n def __init__(self, songName, songString):\n self.songName = songName\n self.songString = songString\n\nclass DurationObject:\n def __init__(self, d, cnt,perc):\n self.duration = d\n self.cntDuration = cnt\n self.percDuration = perc\n\n\nsongParseList=[]\nminimi=[]\n\n\ndef search_min(song):\n\n minArray = []\n partStream = song.parts.stream()\n lenOfPart = partStream[0].recurse().notesAndRests\n nlenOfPart = len(lenOfPart)\n it = iter(range(0, nlenOfPart))\n\n for i in it:\n a = song.recurse().notesAndRests[i]\n if (a.isNote):\n minArray.append(a.duration.quarterLength)\n if (a.isChord):\n pitchPrec=0\n for x in a._notes:\n if (x.pitch.ps > pitchPrec):\n pitchPrec = x.pitch.ps\n pitchPrecD = x.duration.quarterLength\n\n minArray.append(pitchPrecD)\n\n minimo=min(minArray)\n return minimo\n\ndef generateDurationArray(song,l):\n arrayDuration =[]\n c4=0\n c2=0\n c1=0\n c05=0\n c25=0\n c125=0\n cntGeneral=0\n it = iter(range(0, l))\n\n for i in it:\n a = song.recurse().notesAndRests[i]\n print(a)\n if(a.isRest):\n print('nulla')\n if (a.isNote):\n d = a.duration.quarterLength\n d=float(d)\n print(\"DURATA:\",d)\n if (d==4):\n c4=c4+1\n cntGeneral=cntGeneral+1\n if (d==2):\n c2=c2+2\n cntGeneral=cntGeneral+1\n if (d==1):\n c1=c1+1\n cntGeneral=cntGeneral+1\n if (d==0.5):\n c05=c05+1\n cntGeneral=cntGeneral+1\n if (d==0.25):\n c25=c25+1\n cntGeneral=cntGeneral+1\n if (d==0.125):\n c125=c125+1\n cntGeneral=cntGeneral+1\n\n if (a.isChord):\n pitchCorrente = 0;\n d=0;\n for x in a._notes:\n if (x.pitch.ps > pitchCorrente):\n pitchCorrente = x.pitch.ps\n d = x.duration.quarterLength\n if (d == 4):\n c4 = c4 + 1\n cntGeneral = cntGeneral + 1\n if (d == 2):\n c2 = c2 + 2\n cntGeneral = cntGeneral + 1\n if (d == 1):\n c1 = c1 + 1\n cntGeneral = cntGeneral + 1\n if (d == 0.5):\n c05 = c05 + 1\n cntGeneral = cntGeneral + 1\n if (d == 0.25):\n c25 = c25 + 1\n cntGeneral = cntGeneral + 1\n if (d == 0.125):\n c125 = c125 + 1\n cntGeneral = cntGeneral + 1\n\n print('CNTGENEARAL:',cntGeneral)\n print('C4',c4)\n\n\n perc4=c4/cntGeneral\n perc2=c2/cntGeneral\n perc1=c1/cntGeneral\n perc05=c05/cntGeneral\n perc25=c25/cntGeneral\n perc125=c125/cntGeneral\n\n arrayDuration.append(DurationObject(4,c4,perc4))\n arrayDuration.append(DurationObject(2,c2,perc2))\n arrayDuration.append(DurationObject(1,c1,perc1))\n arrayDuration.append(DurationObject(0.5,c05,perc05))\n arrayDuration.append(DurationObject(0.25,c25,perc25))\n arrayDuration.append(DurationObject(0.125,c125,perc125))\n\n\n return arrayDuration\n\ndef generateCSV():\n script_dir = os.path.dirname(__file__) # <-- absolute dir the script is in\n rel_path = 'datasetCouple.csv'\n abs_file_path = os.path.join(script_dir, rel_path) # <-- abbiamo così ottenuto un path funzionante\n with open(abs_file_path, 'w') as csvfile:\n filewriter = csv.writer(csvfile, delimiter=',',\n quotechar='|', quoting=csv.QUOTE_MINIMAL)\n filewriter.writerow(['N','SongName', 'SongString'])\n i=1\n for song in songParseList:\n filewriter.writerow([i,song.songName,song.songString])\n i=i+1\n\n script_dir2 = os.path.dirname(__file__) # <-- absolute dir the script is in\n rel_path2 = 'minimisoglia003.csv'\n abs_file_path2 = os.path.join(script_dir2, rel_path2) # <-- abbiamo così ottenuto un path funzionante\n with open(abs_file_path2, 'w') as csvfile2:\n filewriter = csv.writer(csvfile2, delimiter=',',\n quotechar='|', quoting=csv.QUOTE_MINIMAL)\n filewriter.writerow(['MINIMO'])\n i = 1\n for min in minimi:\n filewriter.writerow([min])\n i = i + 1\n\ndef folderRead(folderName):\n location = os.getcwd() # get present working directory location here\n counter = 0 # keep a count of all files found\n csvfiles = [] # list to store all csv files found at location\n filebeginwithhello = [] # list to keep all files that begin with 'hello'\n otherfiles = [] # list to keep any other file that do not match the criteria\n\n script_dir = os.path.dirname(__file__) # <-- da dove si trova lo script ovvero : Legacy\n rel_path = folderName\n abs_file_path = os.path.join(script_dir, rel_path) # <-- aggiungiamo parts -> Legacy/parts\n for file in os.listdir(abs_file_path):\n try:\n if file.endswith((\".mid\",\".mxl\",\".xml\")):\n print(\"mxl file found:\\t\", file)\n generateString(file,folderName);\n csvfiles.append(str(file))\n counter = counter + 1\n except Exception as e:\n raise e\n print(\"No files found here!\")\n\n print(\"Total files found:\\t\", counter)\n\n generateCSV();\n print(\"-------- END ----------\")\n\ndef generateSongArray(songString):\n for letter in songString:\n print(letter)\n\ndef getMusicProperties(x):\n s = '';\n t='';\n s = str(x.pitch) + \", \" + str(x.duration.type) + \", \" + str(x.duration.quarterLength);\n s += \", \"\n if x.tie != None:\n t = x.tie.type;\n s += t + \", \" + str(x.pitch.ps) + \", \" + str(x.octave); # + str(x.seconds) # x.seconds not always there\n return s\n\ndef pauseSearch(noteOrRests,ind,delete):\n if (ind<=-1):\n return -1;\n if (noteOrRests[ind].isNote):\n a=noteOrRests[ind]\n d=a.duration.quarterLength\n for i in range(0,len(delete)):\n if (d==delete[i]):\n pauseSearch(noteOrRests, ind - 1,delete)\n print(\"termina\")\n return ind\n if (noteOrRests[ind].isChord):\n print(\"termina\")\n return ind\n if (noteOrRests[ind].isRest):\n return pauseSearch(noteOrRests,ind-1,delete)\n\n\ndef pauseSearchForward(noteOrRests,ind,nlenOfPart):\n print(\"SONO NELLA RICORSIONE\")\n print(\"LUNGHEZZA : \",nlenOfPart)\n if(ind>=nlenOfPart):\n return -1\n if (noteOrRests[ind].isRest):\n return pauseSearchForward(noteOrRests,ind+1,nlenOfPart)\n if (noteOrRests[ind].isNote):\n print(\"termina\")\n return ind\n if (noteOrRests[ind].isChord):\n print(\"termina\")\n return ind\n\n\ndef generateString(songName,folderName):\n script_dir3 = os.path.dirname(__file__) # <-- absolute dir the script is in\n rel_path3 = folderName+\"/\"+songName\n abs_file_path3 = os.path.join(script_dir3, rel_path3) # <-- abbiamo così ottenuto un path funzionante\n path = abs_file_path3\n song = m.converter.parse(path)\n\n i = 0;\n\n s2 = '';\n s3='';\n # Snippet per recuperare il numero di note del primo spartito\n # partStream è l' array degli strumenti\n # parStream[0] rappresenta il primo spartito\n partStream = song.parts.stream()\n # print(partStream[0])\n # Questa riga sottostante permette di recuperare il numero di note del primo spartito (o primo strumento)\n # NB: nel numero totale sono incluse anche le pause (oltre le note effettive)\n lenOfPart = partStream[0].recurse().notesAndRests\n # print(len(lenOfPart))\n nlenOfPart = len(lenOfPart)\n # for p in partStream:\n # print(p.id)\n delete=[]\n durationArray=generateDurationArray(song,nlenOfPart)\n minD=0.125\n soglia=0.03\n print(durationArray)\n print(durationArray[0].duration,\" \",durationArray[0].cntDuration,\" \",durationArray[0].percDuration)\n print(durationArray[1].duration,\" \",durationArray[1].cntDuration,\" \",durationArray[1].percDuration)\n print(durationArray[2].duration,\" \",durationArray[2].cntDuration,\" \",durationArray[2].percDuration)\n print(durationArray[3].duration,\" \",durationArray[3].cntDuration,\" \",durationArray[3].percDuration)\n print(durationArray[4].duration, \" \", durationArray[4].cntDuration,\" \",durationArray[4].percDuration)\n print(durationArray[5].duration,\" \",durationArray[5].cntDuration,\" \",durationArray[5].percDuration)\n\n if (durationArray[5].percDuration>=soglia):\n minD=0.125\n else:\n delete.append(0.125)\n if (durationArray[4].percDuration>=soglia):\n minD = 0.25\n else:\n delete.append(0.25)\n if (durationArray[3].percDuration >= soglia):\n minD = 0.5\n else:\n delete.append(0.5)\n if (durationArray[2].percDuration >= soglia):\n minD = 1\n else:\n delete.append(1)\n if (durationArray[1].percDuration >= soglia):\n minD = 2\n else:\n delete.append(2)\n if (durationArray[0].percDuration >= soglia):\n minD = 4\n\n print(\"MIND: \",minD)\n\n minimi.append(minD)\n\n\n\n i = 0;\n\n s2 = '';\n s3='';\n # Snippet per recuperare il numero di note del primo spartito\n # partStream è l' array degli strumenti\n # parStream[0] rappresenta il primo spartito\n partStream = song.parts.stream()\n # print(partStream[0])\n # Questa riga sottostante permette di recuperare il numero di note del primo spartito (o primo strumento)\n # NB: nel numero totale sono incluse anche le pause (oltre le note effettive)\n lenOfPart = partStream[0].recurse().notesAndRests\n # print(len(lenOfPart))\n nlenOfPart = len(lenOfPart)\n # for p in partStream:\n # print(p.id)\n\n it = iter(range(0, nlenOfPart))\n\n print('pitch, duration_string, duration, tie, midi pitch, octave')\n for i in it:\n a = song.recurse().notesAndRests[i]\n\n if (i==1):\n #durationFirstNote\n d = a.duration.quarterLength\n # Calcola il numero di caratteri consecutivi da inserire dopo la differenza nell'intervallo\n # dividendo la durata della seconda nota della differenza per la durata minima dell'intero spartito\n\n cntB=d/minD\n\n cntB= int(cntB)\n sb = ''\n for j in range(0, cntB):\n sb = sb + 'b'\n\n s2=s2+sb\n\n # print(a)\n print('... ', i, ' ...')\n\n if (a.isRest):\n print(\"PAUSA\")\n\n d = a.duration.quarterLength\n cntB=d/minD\n\n cntB= int(cntB)\n sb = ''\n for j in range(0, cntB):\n sb = sb + 'b'\n\n s2=s2+'p'+sb\n\n\n indUtileForward = pauseSearchForward(song.recurse().notesAndRests, i + 1,nlenOfPart)\n print(\"indice utile: \", indUtileForward)\n if (indUtileForward<=-1):\n break\n #Dopo aver ricercato l'indice il programma salta direttamente alla prima nota utile dopo la pausa\n for j in range(i, indUtileForward - 1):\n next(it)\n i = indUtileForward\n\n if (a.isNote):\n\n if (a.tie != None):\n if(a.tie.type=='start'):\n print(a.tie.type)\n tieDuration=0\n d = a.duration.quarterLength\n if (d == 4):\n tieDuration=tieDuration+4\n if (d==3):\n tieDuration =tieDuration+ 3\n if (d == 2):\n tieDuration =tieDuration+ 2\n if (d==1.5):\n tieDuration = tieDuration+1.5\n if (d == 1):\n tieDuration = tieDuration+1\n if (d == 0.5):\n tieDuration = tieDuration+0.5\n if (d==0.75):\n tieDuration =tieDuration+0.75\n if (d == 0.25):\n tieDuration =tieDuration+ 0.25\n continue;\n\n if (a.tie != None):\n if(a.tie.type=='stop'):\n print(a.tie.type)\n d = a.duration.quarterLength\n if (d == 4):\n tieDuration=tieDuration+4\n if (d==3):\n tieDuration =tieDuration+ 3\n if (d == 2):\n tieDuration =tieDuration+ 2\n if (d==1.5):\n tieDuration = tieDuration+1.5\n if (d == 1):\n tieDuration = tieDuration+1\n if (d == 0.5):\n tieDuration = tieDuration+0.5\n if (d==0.75):\n tieDuration =tieDuration+ 0.75\n if (d == 0.25):\n tieDuration =tieDuration+ 0.25\n\n indUtile = i-3\n\n print(\"INDICE :\", indUtile)\n if (indUtile <= -1):\n print(\"NON FARE NULLA\")\n else:\n if (song.recurse().notesAndRests[indUtile].isChord):\n max = 0;\n maxDur = 0;\n for x in song.recurse().notesAndRests[indUtile]._notes:\n if (x.pitch.ps > max):\n max = x.pitch.ps\n maxD = x.duration.quarterLength\n\n pitchCorrente = a.pitch.ps\n\n d = a.duration.quarterLength\n d=int(d)\n tieDuration=tieDuration+d\n\n cntB = tieDuration / minD\n\n cntB = int(cntB)\n sb = ''\n for j in range(0, cntB):\n sb = sb + 'b'\n\n pitchPrec = max;\n pitchDiff = pitchCorrente - pitchPrec\n pitchDiff = round(pitchDiff)\n if (pitchDiff > 0):\n pitchDiffString = str(pitchDiff)\n pitchDiffString = '+' + pitchDiffString\n s2 = s2 + pitchDiffString + sb + '*';\n\n else:\n pitchDiff = str(pitchDiff)\n s2 = s2 + pitchDiff + sb + '*';\n\n if (song.recurse().notesAndRests[indUtile].isNote):\n cntB = tieDuration / minD\n\n cntB = int(cntB)\n sb = ''\n for j in range(0, cntB):\n sb = sb + 'b'\n\n pitchCorrente = a.pitch.ps\n pitchPrec = song.recurse().notesAndRests[indUtile].pitch.ps;\n print(\"OPERAZIONE: \", pitchCorrente, \" - \", pitchPrec)\n pitchDiff = pitchCorrente - pitchPrec\n # Cast from Float to String\n pitchDiff = round(pitchDiff)\n if (pitchDiff > 0):\n pitchDiffString = str(pitchDiff)\n pitchDiffString = '+' + pitchDiffString\n s2 = s2 + pitchDiffString + sb + '*';\n else:\n pitchDiff = str(pitchDiff)\n s2 = s2 + pitchDiff + sb + '*';\n if (a.tie == None):\n\n print(\"NOTA\")\n print(\"indice utile aggiornato in note: \", i)\n indUtile = pauseSearch(song.recurse().notesAndRests, i - 1,delete)\n print(\"INDICE :\", indUtile)\n if (indUtile <= -1):\n print(\"NON FARE NULLA\")\n else:\n if (song.recurse().notesAndRests[indUtile].isChord):\n max = 0;\n maxDur = 0;\n for x in song.recurse().notesAndRests[indUtile]._notes:\n if (x.pitch.ps > max):\n max = x.pitch.ps\n maxD = x.duration.quarterLength\n\n pitchCorrente = a.pitch.ps\n d = a.duration.quarterLength\n\n cntB = d / minD\n\n cntB = int(cntB)\n sb = ''\n for j in range(0, cntB):\n sb = sb + 'b'\n\n\n pitchPrec = max;\n pitchDiff = pitchCorrente - pitchPrec\n pitchDiff = round(pitchDiff)\n if (pitchDiff>0):\n pitchDiffString =str(pitchDiff)\n pitchDiffString='+'+pitchDiffString\n s2 = s2 + pitchDiffString +sb+ '*';\n\n else:\n pitchDiff = str(pitchDiff)\n s2 = s2 + pitchDiff +sb+ '*';\n\n if (song.recurse().notesAndRests[indUtile].isNote):\n d = a.duration.quarterLength\n\n cntB = d / minD\n\n cntB = int(cntB)\n sb = ''\n for j in range(0, cntB):\n sb = sb + 'b'\n\n\n pitchCorrente = a.pitch.ps\n pitchPrec = song.recurse().notesAndRests[indUtile].pitch.ps;\n print(\"OPERAZIONE: \", pitchCorrente, \" - \", pitchPrec)\n pitchDiff = pitchCorrente - pitchPrec\n # Cast from Float to String\n pitchDiff = round(pitchDiff)\n if (pitchDiff > 0):\n pitchDiffString = str(pitchDiff)\n pitchDiffString = '+' + pitchDiffString\n s2 = s2 + pitchDiffString +sb+ '*';\n else:\n pitchDiff = str(pitchDiff)\n s2 = s2 + pitchDiff +sb+ '*';\n\n x = a;\n s = getMusicProperties(x);\n print(s);\n\n if (a.isChord):\n print(\"ACCORDO\")\n for x in a._notes:\n s = getMusicProperties(x);\n print(s);\n\n indUtile = pauseSearch(song.recurse().notesAndRests, i - 1,delete)\n if (indUtile <= -1):\n print(\"NON FARE NULLA\")\n else:\n if (song.recurse().notesAndRests[indUtile].isChord):\n pitchPrec = 0;\n pitchPrecD = 0;\n for x in song.recurse().notesAndRests[indUtile]._notes:\n if (x.pitch.ps > pitchPrec):\n pitchPrec = x.pitch.ps\n pitchPrecD = x.duration.quarterLength\n notaChord = x\n\n pitchCorrente = 0;\n pitchCorrenteD = 0;\n for x in a._notes:\n if (x.pitch.ps > pitchCorrente):\n pitchCorrente = x.pitch.ps\n pitchCorrenteD = x.duration.quarterLength\n notaChord = x\n\n cntB = pitchCorrenteD / minD\n\n cntB = int(cntB)\n sb = ''\n for j in range(0, cntB):\n sb = sb + 'b'\n\n\n\n\n pitchDiff = pitchCorrente - pitchPrec\n pitchDiff = round(pitchDiff)\n if (pitchDiff > 0):\n pitchDiffString = str(pitchDiff)\n pitchDiffString = '+' + pitchDiffString\n s2 = s2 + pitchDiffString +sb +'*';\n else:\n pitchDiff = str(pitchDiff)\n s2 = s2 + pitchDiff + sb+'*';\n\n\n\n if (song.recurse().notesAndRests[indUtile].isNote):\n pitchCorrente = 0;\n pitchCorrenteD = 0;\n\n for x in a._notes:\n if (x.pitch.ps > pitchCorrente):\n pitchCorrente = x.pitch.ps\n pitchCorrenteD = x.duration.quarterLength\n notaChord = x\n\n cntB = pitchCorrenteD / minD\n\n cntB = int(cntB)\n sb = ''\n for j in range(0, cntB):\n sb = sb + 'b'\n\n pitchPrec = song.recurse().notesAndRests[indUtile].pitch.ps;\n\n pitchDiff = pitchCorrente - pitchPrec\n # Cast from Float to String\n pitchDiff = round(pitchDiff)\n if (pitchDiff > 0):\n pitchDiffString = str(pitchDiff)\n pitchDiffString = '+' + pitchDiffString\n s2 = s2 + pitchDiffString +sb+'*';\n else:\n pitchDiff = str(pitchDiff)\n s2 = s2 + pitchDiff +sb+ '*';\n\n\n\n\n # s2=s2.replace(\"p*p\",\"p\")\n # s2=s2.replace(\"p*p*p\",\"p\")\n # s2=s2.replace(\"p*p*p*p\",\"p\")\n s2= s2.replace(\"*\", \"\");\n #s2= s2.replace(\"+\", \"\");\n #s2= s2.replace(\"p\", \"\");\n\n print(s2)\n\n #generateSongArray(s2)\n\n #Aggiungo un nuovo elemento nella lista delle canzoni di cui ho effettuato il Parsing\n songParseList.append(SongParse(songName,s2))\n\n print(\"Done.\")\n\n\ndef music_parser_legacy(foldername='parts'):\n songParseList.clear() # All'inizio ripulisco le liste!!! Ecco cosa causava il problema\n minimi.clear()\n tieDuration = 0 # lo lascio perchè c'era da legacy, ma è inutile\n\n folderRead(foldername)\n\n\nif __name__ == '__main__':\n music_parser_legacy()\n","sub_path":"Server/webplagiarism/plagiarism_webapp/main/legacy/musicParser.py","file_name":"musicParser.py","file_ext":"py","file_size_in_byte":22887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"251041887","text":"from led.ledctl import LEDController\nfrom .default_devices import DEVICES\n\nconfig = {'pattern_dir': 'static/build/thumbs',\n 'build_dir': 'static/build',\n 'framerate': 30,\n 'num_lights': 180}\n\ndevices = DEVICES\n\ncontroller = LEDController(framerate=config['framerate'])\n","sub_path":"Web/app_globals.py","file_name":"app_globals.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"37114147","text":"import sys\n\n__author__ = 'gregortaube'\n\n\ndef my_min(values):\n min = values[0]\n for value in values:\n if valuemax:\n max=value\n return max\n\ndef my_range(values):\n min=my_min(values)\n max=my_max(values)\n return max-min\n\ndef printStatistics(case):\n while True:\n case+=1\n try:\n values = input()\n except:\n sys.exit()\n values = list(map(int,values.split()))\n values = values[1:] #first value is data_count\n print(\"Case %d: %d %d %d\" %(case,my_min(values),my_max(values),my_range(values)))\n\n\nprintStatistics(0)\n\n","sub_path":"intermediate2/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"642433571","text":"#!/usr/bin/python3\n\nfrom functools import wraps\nfrom timeit import default_timer as timer\n\n\ndef print_time(function):\n @wraps(function)\n def wrapper(*args, **kargs):\n start = timer()\n result = function(*args, **kargs)\n end = timer()\n print('The function {0} Cost {1:3f}s.\\n'.format(\n function.__name__, end-start))\n return result\n return wrapper\n\n\n@print_time\ndef main():\n print('test')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"wraps.py","file_name":"wraps.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"292613882","text":"from __future__ import division, print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport pdb\nimport sys\nplt.ion()\nif not '..' in sys.path:\n sys.path.insert(0,'..')\nfrom opticstools import knull\n\n#Start with a matrix that is all but the bright output of the 4 input coupler\n#mat = make_nuller_mat4(bracewell_design=False)[1:]\nmat = knull.other_nuller_mat4() # test with reformatted matrix\n\n#cov_elts is a list of either phases we want to be linearly independent of, or\n#pairs of phases we want to be independent of to 2nd order.\n#We can ignore one of the telescope phases here as a \"reference\" phase. \ncov_elts = [[1,1],[2,2],[3,3],[1,2],[1,3],[2,3]]\n\n#For 3 telescopes...\n#mat = make_nuller_mat4()[1:] \n#cov_elts = [[1,1],[2,2],[1,2]]\n\n#For a hypothetical phase matrix with e.g. 12 outputs:\n#Independence of amplitude would require a modification of the code\n#below (which has been checked for the simple 4 telescope case)\n#cov_elts = [[1],[2],[3],[1,1],[2,2],[3,3],[1,2],[1,3],[2,3]]\n\nncov = len(cov_elts) # number of covariance elements\nnout = mat.shape[0] # number of outputs\nntel = mat.shape[1] # number of sub-apertures\ndph = 0.01 # delta-phase (for numerical computation)\n\n#AA is an extension of the matrix \"A\" from the kernel-phase papers, where\n#we both include first and second-order phase differences in the pupil plane \n#phase vector. They are arranged according to cov_elts.\n#Output - Perfect_ouput = AA DOT (dph[0], dph[0]**2, dph[2], dph[1]*dph[3], etc...)\nAA = np.empty((ncov, nout))\n\n#We approximate in 2D the intensity as:\n#f(x,y) = a_x x + a_y y + b_xx x^2 + b_yy*y^2 + b_xy * xy\n\nfor ix, elt in enumerate(cov_elts):\n p1 = np.zeros(ntel, dtype=complex)\n p2 = np.zeros(ntel)\n \n p1[elt[0]] = dph\n \n if (len(elt) == 1):\n AA[ix] = 0.5 * (knull.odiff(mat, p1) - knull.odiff(mat, -p1)) / dph\n \n elif (elt[0] == elt[1]):\n AA[ix] = 0.5 * (knull.odiff(mat, p1) + knull.odiff(mat, -p1)) / dph**2\n\n else:\n p1[elt[1]] = dph\n p2[elt[0]] = dph\n p2[elt[1]] = -dph \n AA[ix] = 0.25 * (knull.odiff(mat, p1) + knull.odiff(mat, -p1) -\n knull.odiff(mat, p2) - knull.odiff(mat, -p2) ) / dph**2\n\nU, W, V = np.linalg.svd(AA.T)\n#Kernel-output matrix...\n# K = np.transpose(U[:,len(W):]) # Mike's version\nK = np.transpose(U[:,np.sum(W < 1e-3):]) #\n'''plt.figure(1)\nplt.clf()\nplt.plot(K.T)\nplt.plot(K.T,'o')'''\n\n\nprint(\"Shape of AA.T: \" + str(AA.T.shape))\nprint(np.round(AA.T, 3))\n\n# NOTE that 8 * AA.T (or AA) is filled with integer values!\n\nprint(\"Shape of K: \" + str(K.shape))\nprint(np.round(K, 2))\n\n#pdb.set_trace()\n\n\n\n\n\n\n#FIXME\n#Next step: Figure out now these kernel outputs relate to visibilities\n#and on-sky coordinates for simple telescope arrangements.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# ---------------------------------------\n# definition of the interferometric array\n# ---------------------------------------\napc = np.array([[0.0, 10.0, 40.0, 60.0], # start with an in-line interferometer\n [0.0, 0.0, 0.0, 0.0]]) # x-y coordinates of the apertures in meters\napc = np.array([[-9.925, 14.887, 44.915, 103.306], # VLTI\n [-20.335, 30.502, 66.183, 44.999]]) # VLTI\n\ncwavel = 3.6e-6 # wavelength of observation (in meters)\nalpha, delta = 5.0, 0.0 # coordinates of the off-axis companion in mas\ncon = 1.0e-2 # 100:1 companion contrat\noff_axis = knull.mas2rad(alpha * apc[0] + delta * apc[1])\n \n''' plt.figure(2)\nplt.clf()\nplt.plot(apc[0], apc[1], 'ro')\n\nplt.xlim([-10,50])\nplt.ylim([-10,50])\n'''\n\nMM0 = 0.5 * np.array([[1, 1, 1, 1], # the nuller matrix, alone\n [1, 1,-1,-1],\n [1,-1, 1,-1],\n [1,-1,-1, 1]])\n\n# ---------------------------------------------------\n# record the response of the system to random pistons\n# ---------------------------------------------------\nntest = 10000\n\npiston_record = [] # record of random pistons generated\nnuller_record = [] # record of the output of the nuller matrix alone\noutput_record = [] # record of the output of the nuller+sensor matrix\nkernel_record = [] # record of the kernel-output\n\nfor i in range(ntest):\n pistons = np.random.randn(4) * 50.0 # atmospheric pistons in nanometers\n pistons[0] = 0.0 # piston measured relative to first aperture\n piston_record.append(pistons)\n\n E_on = np.exp(-1j*2*np.pi/cwavel * pistons * 1e-9)\n E_off = np.exp(-1j*2*np.pi/cwavel * (pistons * 1e-9 + off_axis))\n\n output = knull.incoherent_sum(mat, E_on, E_off, con)\n\n output_record.append(output)\n kernel_record.append(K.dot(output))\n\n temp = knull.incoherent_sum(MM0, E_on, E_off, con)\n nuller_record.append(temp)\n\n# --------------------------------------------\n# record what the perfect output should be\n# --------------------------------------------\npistons[:] = 0.0\nE_on = np.exp(-1j*2*np.pi/cwavel * pistons * 1e-9)\nE_off = np.exp(-1j*2*np.pi/cwavel * (pistons * 1e-9 + off_axis))\n\ntemp = knull.incoherent_sum(MM0, E_on, E_off, con)\nperfect_null_data = temp.copy()\n\ntemp = knull.incoherent_sum(mat, E_on, E_off, con)\nperfect_kernel_data = temp.copy()\n\n# --------------------------------------------\n\noutput_record = np.array(output_record)\nkernel_record = np.array(kernel_record)\nnuller_record = np.array(nuller_record)\n\n'''\nf1 = plt.figure(3, figsize=(15,6))\nf1.clf()\nax1 = f1.add_subplot(121)\nax2 = f1.add_subplot(122)\nfor i in range(nout):\n try:\n ax1.plot(output_record[:100,i])\n except:\n pass\n \nfor i in range(3):\n try:\n ax2.plot(kernel_record[:100,i])\n except:\n pass\n\nrmax = 1.5e-2\nax1.set_ylim([0, rmax])\nax1.set_xlabel(\"observation index\", fontsize=14)\nax1.set_ylabel(\"raw nuller output\", fontsize=14)\n\nax2.set_ylim([-rmax/2, rmax/2])\nax2.set_xlabel(\"observation index\", fontsize=14)\nax2.set_ylabel(\"kernel nuller output\", fontsize=14)\n\nf1.set_tight_layout(True)\n#ax1.set_yscale('log')\n'''\nprint(\"------------------------------------------------------------\")\nprint(\"raw output variability: \", output_record.std(axis=0).round(4))\nprint(\"kernel variability: \", kernel_record.std(axis=0).round(4))\nprint(\"------------------------------------------------------------\")\n\n\n# ===============================================================\n# now looking at distribution of nulled outputs vs kernel-outputs\n# ===============================================================\nf0 = plt.figure(10, figsize=(18,5))\nplt.clf()\n\nax0 = f0.add_subplot(131)\nfor ii in range(3):\n plt.hist(nuller_record[:,ii+1], bins=100, range=[0,0.05], label=\"output #%d\" % (ii+1),\n histtype=\"step\")\nplt.ylabel(\"# of occurences\")\nplt.xlabel(\"Null-depth\")\nplt.xlim([0.0, 0.05])\nplt.legend(fontsize=11)\nplt.title(\"Classical nuller outputs distribution\")\n\nax1 = f0.add_subplot(132)\nfor ii in range(nout):\n plt.hist(output_record[:,ii], bins=100, range=[0.0, 0.05], label=\"output #%d\" % (ii+1,), histtype=\"step\")\nplt.ylabel(\"# of occurences\")\nplt.xlabel(\"Null-depth\")\nplt.xlim([0.0, 0.05])\nplt.legend(fontsize=11)\nplt.title(\"Modified nuller outputs distribution\")\n\nax2 = f0.add_subplot(133)\nfor ii in range(3):\n plt.hist(kernel_record[:,ii], bins=100, label=\"output #%d\" % (ii+1,), histtype=\"step\")\nplt.ylabel(\"# of occurences\")\nplt.xlabel(\"Kernel-Null\")\nplt.xlim([-0.025, 0.025])\nplt.legend(fontsize=11)\nplt.title(\"Kernel-outputs distribution\")\n\nf0.set_tight_layout(True)\n# ---------------------------------------------------\n# record the response of the system to variable pos\n# ---------------------------------------------------\nntest = 100\noutput_record2 = []\nkernel_record2 = []\n\npos = 20 * (np.arange(ntest)/float(ntest)-0.5) # position from -10 to 10 mas\ndirection = \"E-W\"\n\nfor i in range(ntest):\n pistons = np.random.randn(4) * 0.0 # atmospheric pistons in nanometers\n pistons[0] = 0.0 # piston measured relative to first aperture\n\n if direction == \"E-W\":\n off_axis = knull.mas2rad(pos[i] * apc[0] + delta * apc[1]) # along east-west axis\n else:\n off_axis = knull.mas2rad(0.0 * apc[0] + pos[i] * apc[1]) # along north-south axis\n \n E_on = np.exp(-1j*2*np.pi/cwavel * pistons * 1e-9)\n E_off = np.exp(-1j*2*np.pi/cwavel * (pistons * 1e-9 + off_axis))\n \n output = knull.incoherent_sum(mat, E_on, E_off, con)\n output_record2.append(output)\n kernel_record2.append(K.dot(output))\n\noutput_record2 = np.array(output_record2)\nkernel_record2 = np.array(kernel_record2)\n\n\n\nf2 = plt.figure(4, figsize=(15,6))\nf2.clf()\nax1 = f2.add_subplot(121)\nax2 = f2.add_subplot(122)\nfor i in range(nout):\n try:\n ax1.plot(pos, output_record2[:,i])\n except:\n pass\n\nfor i in range(3):\n try:\n ax2.plot(pos, kernel_record2[:,i])\n except:\n pass\n\nrmax = 1.5e-2\nax1.set_ylim([0, rmax])\nax1.set_xlabel(\"%s off-axis position (mas)\" % (direction,), fontsize=14)\nax1.set_ylabel(\"VLTI-UTs raw nuller output\", fontsize=14)\n\nax2.set_ylim([-rmax/2, rmax/2])\nax2.set_xlabel(\"%s off-axis position (mas)\" % (direction,), fontsize=14)\nax2.set_ylabel(\"VLTI-UTs kernel nuller output\", fontsize=14)\n\nf2.set_tight_layout(True)\n\n# =========================================\n# 1D-plot of the response of the nuller alone\n# =========================================\n'''\noutput_record3 = []\n\npos = 20 * (np.arange(ntest)/float(ntest)-0.5) # position from -10 to +10 mas\nfor i in range(ntest):\n pistons = np.random.randn(4) * 0.0 # atmospheric pistons in nanometers\n pistons[0] = 0.0 # piston measured relative to first apert\n\n if direction == \"E-W\":\n off_axis = mas2rad(pos[i] * apc[0] + delta * apc[1]) # along east-west axis\n else:\n off_axis = mas2rad(0.0 * apc[0] + pos[i] * apc[1]) # along north-south axis\n \n E_on = np.exp(-1j*2*np.pi/cwavel * pistons * 1e-9)\n E_off = np.exp(-1j*2*np.pi/cwavel * (pistons * 1e-9 + off_axis))\n output = incoherent_sum(MM0, E_on, E_off, con)\n \n output_record3.append(output)\n\noutput_record3 = np.array(output_record3)\n\nf3 = plt.figure(5, figsize=(8,6))\nf3.clf()\nax1 = f3.add_subplot(111)\nfor ii in range(1,4):\n ax1.plot(pos, output_record3[:,ii])\n'''\n\n\n\n\n# =========================================================================\n# 2D Kernel-output maps\n# =========================================================================\n\npos = 20 * (np.arange(ntest)/float(ntest)-0.5) # position from -10 to +10 mas\nxx, yy = np.meshgrid(pos,pos)\nfor ii in range(nout):\n exec(\"omap%d = np.zeros((ntest, ntest))\" % (ii+1,)) # maps of the SxNx outputs\n \nfor ii in range(3):\n exec(\"kmap%d = np.zeros((ntest, ntest))\" % (ii+1,)) # maps of the KxSxNx outputs\n\nfor ii in range(3):\n exec(\"nmap%d = np.zeros((ntest, ntest))\" % (ii+1,)) # maps of the Nx outputs\n\npistons[:] = 0.0 # no piston errors\nE_on = np.exp(-1j*2*np.pi/cwavel * pistons * 1e-9)\nfor ii in range(ntest):\n for jj in range(ntest):\n off_axis = knull.mas2rad(xx[ii,jj] * apc[0] + yy[ii,jj] * apc[1])\n E_off = np.exp(-1j*2*np.pi/cwavel * (pistons * 1e-9 + off_axis))\n \n output = knull.incoherent_sum(mat, E_on, E_off, con)\n kernel = K.dot(output)\n\n for kk in range(3):\n exec(\"kmap%d[ii,jj] = kernel[%d]\" % (kk+1, kk))\n \n for kk in range(nout):\n exec(\"omap%d[ii,jj] = output[%d]\" % (kk+1, kk))\n\n temp = knull.incoherent_sum(MM0, E_on, E_off, con)\n for kk in range(3):\n exec(\"nmap%d[ii,jj] = temp[%d]\" % (kk+1, kk+1))\n\n# ===============================================================\n# plot the 2D maps\n# ===============================================================\nf4 = plt.figure(6, figsize=(15,5))\nmmax = np.round(pos.max())\nmycmap = cm.magma\n\nfor kk in range(3):\n exec('ax%d = f%d.add_subplot(1,3,%d)' % (kk+1, 4, kk+1))\n exec('ax%d.imshow(kmap%d, extent=(-mmax, mmax, -mmax, mmax), cmap=mycmap)' % (kk+1, kk+1))\n exec('ax%d.set_xlabel(\"R.A. Kernel-output map #%d (mas)\")' % (kk+1, kk+1))\n exec('ax%d.set_ylabel(\"Dec. Kernel-output map #%d (mas)\")' % (kk+1, kk+1))\n\nf4.set_tight_layout(True)\n\n# =======\nf5 = plt.figure(7, figsize=(15,15/(nout/3)))\n\nfor kk in range(nout):\n exec('ax%d = f%d.add_subplot(%d,3,%d)' % (kk+1, 5, nout/3, kk+1))\n exec('ax%d.imshow(omap%d, extent=(-mmax, mmax, -mmax, mmax), cmap=mycmap)' % (kk+1, kk+1))\n exec('ax%d.set_xlabel(\"R.A. Modified output map #%d (mas)\")' % (kk+1, kk+1))\n exec('ax%d.set_ylabel(\"Dec. Modified output map #%d (mas)\")' % (kk+1, kk+1))\n\nf5.set_tight_layout(True)\n\n# =======\nf6 = plt.figure(8, figsize=(15,5))\n\nfor kk in range(3):\n exec('ax%d = f%d.add_subplot(1,3,%d)' % (kk+1, 6, kk+1))\n exec('ax%d.imshow(nmap%d, extent=(-mmax, mmax, -mmax, mmax), cmap=mycmap)' % (kk+1, kk+1))\n exec('ax%d.set_xlabel(\"R.A. Nuller output map #%d (mas)\")' % (kk+1, kk+1))\n exec('ax%d.set_ylabel(\"Dec. Nuller output map #%d (mas)\")' % (kk+1, kk+1))\n\nf6.set_tight_layout(True)\n\n","sub_path":"playground/frantz_nuller_test.py","file_name":"frantz_nuller_test.py","file_ext":"py","file_size_in_byte":13139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"86171938","text":"import copy\nimport webbrowser\nimport timeit\ncolored = {}\nbacktracking = 0\nsingleton = 0\ndfs_with_heuristic = 0\ndef check_valid(graph):\n \"Check the graph is valid i.e States are linked properly to each other\"\n for node,nexts in graph.items():\n assert(node not in nexts) # # no node linked to itself\n for next in nexts:\n assert(next in graph and node in graph[next]) # A linked to B implies B linked to A\n#DFS\n\ndef get_neighbours(state,country,country_colors):\n \"\"\n if dfs_with_heuristic == 0:\n return country[state]\n else:\n if singleton == 0:\n candts_with_add_info = [\n (\n -len({colored[neigh] for neigh in country[n] if neigh in colored}),#Minimum Remaining Value Hueristic\n -len({neigh for neigh in country[n] if neigh not in colored}),# Degree Heuristic\n n\n ) for n in country[state] if n not in colored]\n #Get Neighbours based on heuristic value\n else:\n candts_with_add_info = [\n (\n # For singleton Sort the neighbours based on their Colors Remaining\n -100 if (len(country_colors[n]) == 1) else 100,\n -len({colored[neigh] for neigh in country[n] if neigh in colored}), #Minimum Remaining Value Hueristic\n -len({neigh for neigh in country[n] if neigh not in colored}), # Degree Heuristic\n #then calculate the number of neighbours)\n n\n #\"Neigbours\"\n ) for n in country[state] if n not in colored]\n candts_with_add_info.sort()\n print(candts_with_add_info, \"--Sort - ()()()()()\")\n # Return Neighbours in an ordered way with given - heurisitc\n if singleton == 0:\n canddts= [n for _,_,n in candts_with_add_info]\n else:\n canddts = [n for _,_,_,n in candts_with_add_info]\n return canddts\n\ndef get_colors(state,country,country_colors):\n # Get Colours\n if dfs_with_heuristic == 0:\n return country_colors[state]\n else:\n # Get Colors based on Least Constraining Value\n a = []\n for color in country_colors[state]:\n no_of_colors = 0\n a.append([color])\n for neigh in country[state]:\n if color in country_colors[neigh]:\n no_of_colors = no_of_colors + len(country_colors[neigh]) - 1\n else:\n no_of_colors = no_of_colors + len(country_colors[neigh])\n a[a.index([color])].append(no_of_colors)\n a = sorted(a,key = lambda x:x[1],reverse = True)\n a = [x[0] for x in a]\n return a\n\n# Solve DFS\ndef solve_problem_DFS(state,country,country_colors):\n increment_color = 0\n flag = 0\n global backtracking\n # Loop on all the colors value\n for color in get_colors(state,country,country_colors):\n for neigh in country[state]:\n if neigh in colored and colored[neigh] == color:\n increment_color = 1\n break\n if increment_color == 1:\n increment_color = 0\n continue\n colored[state] = color\n print(\"Trying to give color %s to %s\" %(colored[state],state))\n # Calling the neighbour Value using DFS\n for neigh in get_neighbours(state,country,country_colors):\n if neigh not in colored:\n #DFS : - if no values found for child - pop the value and check for another value\n if (solve_problem_DFS(neigh, country, country_colors) == False):\n colored.pop(state)\n flag = 1\n break\n if flag == 0:\n print(\"Gave color %s to %s\" % (colored[state],state))\n return True\n else:\n flag = 0\n continue\n # If none of the values work then backtrack\n print(\"No Value for state%s: - Backtracking \"%(state))\n backtracking = backtracking + 1\n return False\n\n#DFS with Forward Chaining\n# Remove Colors from neighbours\ndef reduce_domain(state,country,cntry_colors):\n for j in country[state]:\n if colored[state] in cntry_colors[j]:\n cntry_colors[j].remove(colored[state])\n # print(\"Removed Color \")\n\n# check if with the given color no neighbour will have empty domain\ndef reduce_domain_forward_check(color,state,country,cntry_colors):\n p = copy.deepcopy(cntry_colors)\n for j in country[state]:\n if color in p[j] :\n p[j].remove(color)\n if not check_domain(j,p):\n return False\n return True\n\n# Check Color remaining for a given state is not empty\ndef check_domain(state,cntry_colors):\n if not (cntry_colors[state]) :\n return False\n return True\n\n# DFS with Forward Chaining and singleton\ndef solve_problem_DFS_FC(state,country,country_colors):\n flag = 0\n increment_color = 0\n b = copy.deepcopy(country_colors)\n global backtracking\n # Loop on all the colors value\n for color in get_colors(state,country,country_colors):\n # Taking Colours of Country into temporary Variable since it will be used for backtracking\n a = copy.deepcopy(b)\n for neigh in country[state]:\n if neigh in colored and colored[neigh] == color:\n country_colors[neigh] = b[neigh] = a[neigh] = [color]\n increment_color = 1\n break\n if increment_color == 1:\n increment_color = 0\n continue\n colored[state] = color\n print(\"Trying to give color %s to %s\" %(color,state))\n reduce_domain(state, country, a)\n print(\"Colors of all state after reducing their domain\\n\",a)\n a[state] = [color]\n if singleton == 1 and dfs_with_heuristic == 0:\n print(\"Neighbours of country(Singleton) %s - %s\"%(state,country[state]))\n country[state] = sorted(country[state],key = lambda x:len(country_colors[x]),reverse = False)\n print(\" After Sorting - Neighbours of country(Singleton) %s - %s\"%(state,country[state]))\n # Calling the neighbour Value using DFS\n for neigh in get_neighbours(state,country,a):\n if neigh not in colored:\n #DFS : - if no values found for child - pop the value and check for another value\n if (solve_problem_DFS_FC(neigh,country,a)) == False :\n colored.pop(state)\n flag = 1\n print(\"Cannot give color to\",state)\n break\n if flag == 0:\n print(\"Gave color %s to %s\" % (colored[state], state))\n return True\n else:\n # Check for another Value if Child values not found for current one\n flag = 0\n continue\n print(\"No Value for state%s: - Backtracking \"%(state))\n # If none of the values work then backtrack\n backtracking = backtracking + 1\n return False\n\nAUWA = 'AU-WA'\nAUNT = 'AU-NT'\nAUSA = 'AU-SA'\nAUQ = 'AU-QLD'\nAUNSW = 'AU-NSW'\nAUV = 'AU-VIC'\nAUT = 'AU-TAS'\n\naustralia = { \n AUT: {AUV},\n AUWA: {AUNT, AUSA},\n AUNT: {AUWA, AUQ, AUSA},\n AUSA: {AUWA, AUNT, AUQ, AUNSW, AUV},\n AUQ: {AUNT, AUSA, AUNSW},\n AUNSW: {AUQ, AUSA, AUV},\n AUV: {AUSA, AUNSW, AUT} \n}\n\nau_colors= { \n AUT: ['red','green','blue'],\n AUWA: ['red','green','blue'],\n AUNT: ['red','green','blue'],\n AUSA: ['red','green','blue'],\n AUQ: ['red','green','blue'],\n AUNSW:['red','green','blue'],\n AUV: ['red','green','blue']\n}\n\nAL = \"US-AL\"\nAK = \"US-AK\"\nAZ = \"US-AZ\"\nAR = \"US-AR\"\nCA = \"US-CA\"\nCO = \"US-CO\"\nCT = \"US-CT\"\nDE = \"US-DE\"\nFL = \"US-FL\"\nGA = \"US-GA\"\nHI = \"US-HI\"\nID = \"US-ID\"\nIL = \"US-IL\"\nIN = \"US-IN\"\nIA = \"US-IA\"\nKS = \"US-KS\"\nKY = \"US-KY\"\nLA = \"US-LA\"\nME = \"US-ME\"\nMD = \"US-MD\"\nMA = \"US-MA\"\nMI = \"US-MI\"\nMN = \"US-MN\"\nMS = \"US-MS\"\nMO = \"US-MO\"\nMT = \"US-MT\"\nNE = \"US-NE\"\nNV = \"US-NV\"\nNH = \"US-NH\"\nNJ = \"US-NJ\"\nNM = \"US-NM\"\nNY = \"US-NY\"\nNC = \"US-NC\"\nND = \"US-ND\"\nOH = \"US-OH\"\nOK = \"US-OK\"\nOR = \"US-OR\"\nPA = \"US-PA\"\nRI = \"US-RI\"\nSC = \"US-SC\"\nSD = \"US-SD\"\nTN = \"US-TN\"\nTX = \"US-TX\"\nUT = \"US-UT\"\nVT = \"US-VT\"\nVA = \"US-VA\"\nWA = \"US-WA\"\nWV = \"US-WV\"\nWI = \"US-WI\"\nWY = \"US-WY\"\n\nunited_states_of_america = {\n AL: {GA, FL, TN, MS},\n AK: {WA},\n AZ: {CA, NV, UT, CO, NM},\n AR: {MO, OK, TX, LA, TN, MS },\n CA: {OR, NV, AZ,HI},\n CO: {WY, NE, KS, OK, NM, AZ, UT},\n CT: {NY,RI,MA},\n DE: {MD,PA,NJ},\n FL: {AL, GA},\n GA: {SC, NC, TN, AL, FL},\n HI: {CA},\n ID: {WA, MT, OR, WY, UT, NV},\n IL: {WI, IA, MO, KY, IN, MI},\n IN: {MI, IL, KY, OH},\n IA: {MN, SD, NE, MO, WI, IL},\n KS: {NE, CO, OK, MO},\n KY: {IN, IL, MO, TN, OH, WV, VA},\n LA: {AR, TX, MS},\n ME: {NH},\n MD: {PA,WV,VA,DE},\n MA: {NY,VT,NH,CT,RI},\n MI: {IL, WI, IN, OH},\n MN: {ND, SD, IA, WI},\n MS: {TN, AR, LA, AL},\n MO: {IA, NE, KS, OK, AR, IL, KY, TN},\n MT: {ID, WY, SD, ND},\n NE: {SD, CO, WY, KS, MO, IA},\n NV: {OR, ID, UT, AZ, CA},\n NH: {ME,VT,MA},\n NJ: {NY,PA,DE},\n NM: {AZ, UT, CO, OK, TX},\n NY: {PA,NJ,CT,MA,VT},\n NC: {GA, TN, SC, VA},\n ND: {MT, SD, MN},\n OH: {MI, IN, KY, WV,PA},\n OK: {KS, CO, NM, TX, AR, MO},\n OR: {WA, ID, NV, CA},\n PA: {OH,WV,DE,NJ,NY,MD},\n RI: {CT,MA},\n SC: {GA, NC},\n SD: {ND, MT, WY, NE, MN, IA},\n TN: {KY,AR, MS, MO, AL, GA, NC,VA},\n TX: {OK, NM, AR, LA},\n UT: {ID, NV, WY, CO, AZ, NM},\n VT: {MA,NY,NH},\n VA: {WV, KY, NC,TN,MD},\n WA: {OR,ID,AK},\n WV: {OH, VA, KY,PA,MD},\n WI: {MN, IL, MI, IA},\n WY: {MT, SD,NE, CO, UT, ID},\n}\n\nus_colors = {\n AL: ['red', 'green', 'blue', 'yellow'],\n AK: ['red', 'green', 'blue', 'yellow'],\n AZ: ['red', 'green', 'blue', 'yellow'],\n AR: ['red', 'green', 'blue', 'yellow'],\n CA: ['red', 'green', 'blue', 'yellow'],\n CO: ['red', 'green', 'blue', 'yellow'],\n CT: ['red', 'green', 'blue', 'yellow'],\n DE: ['red', 'green', 'blue', 'yellow'],\n FL: ['red', 'green', 'blue', 'yellow'],\n GA: ['red', 'green', 'blue', 'yellow'],\n HI: ['red', 'green', 'blue', 'yellow'],\n ID: ['red', 'green', 'blue', 'yellow'],\n IL: ['red', 'green', 'blue', 'yellow'],\n IN: ['red', 'green', 'blue', 'yellow'],\n IA: ['red', 'green', 'blue', 'yellow'],\n KS: ['red', 'green', 'blue', 'yellow'],\n KY: ['red', 'green', 'blue', 'yellow'],\n LA: ['red', 'green', 'blue', 'yellow'],\n ME: ['red', 'green', 'blue', 'yellow'],\n MD: ['red', 'green', 'blue', 'yellow'],\n MA: ['red', 'green', 'blue', 'yellow'],\n MI: ['red', 'green', 'blue', 'yellow'],\n MN: ['red', 'green', 'blue', 'yellow'],\n MS: ['red', 'green', 'blue', 'yellow'],\n MO: ['red', 'green', 'blue', 'yellow'],\n MT: ['red', 'green', 'blue', 'yellow'],\n NE: ['red', 'green', 'blue', 'yellow'],\n NV: ['red', 'green', 'blue', 'yellow'],\n NH: ['red', 'green', 'blue', 'yellow'],\n NJ: ['red', 'green', 'blue', 'yellow'],\n NM: ['red', 'green', 'blue', 'yellow'],\n NY: ['red', 'green', 'blue', 'yellow'],\n NC: ['red', 'green', 'blue', 'yellow'],\n ND: ['red', 'green', 'blue', 'yellow'],\n OH: ['red', 'green', 'blue', 'yellow'],\n OK: ['red', 'green', 'blue', 'yellow'],\n OR: ['red', 'green', 'blue', 'yellow'],\n PA: ['red', 'green', 'blue', 'yellow'],\n RI: ['red', 'green', 'blue', 'yellow'],\n SC: ['red', 'green', 'blue', 'yellow'],\n SD: ['red', 'green', 'blue', 'yellow'],\n TN: ['red', 'green', 'blue', 'yellow'],\n TX: ['red', 'green', 'blue', 'yellow'],\n UT: ['red', 'green', 'blue', 'yellow'],\n VA: ['red', 'green', 'blue', 'yellow'],\n VT: ['red', 'green', 'blue', 'yellow'],\n WA: ['red', 'green', 'blue', 'yellow'],\n WV: ['red', 'green', 'blue', 'yellow'],\n WI: ['red', 'green', 'blue', 'yellow'],\n WY: ['red', 'green', 'blue', 'yellow'],\n}\n\n# Can't be bothered to complete the East part of the map - removing unused nodes (keeping them is also a good way to test your algorithm and see if still works)\nunited_states_of_america = {n:neigh for n,neigh in united_states_of_america.items() if neigh}\n\ndef makeBrowser(cname):\n global colored\n \n f = open('worldmap.html','w')\n\n message = \"\"\"\n \n \n \n IS Project 3 - Abhishek Fulzele & Rahul Patel\n \n \n \n \n\n \n\n \n \n \n\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n\n \n \n \n\n \n \n \n \n \n \n \n \n \n\n \n \n \n\n \n \n \n
\n \n \n \"\"\"\n\n x = str(cname)\n\n mainmessage = message + x + message1 + str(colored) + message2\n\n f.write(mainmessage)\n f.close()\n\n webbrowser.open_new_tab('worldmap.html')\n\n\nif __name__ == '__main__':\n\n print(\"1. America 2. Australia\")\n country_name = int(input(\"Which country would you like to select:\\n \"))\n\n cname = \"\"\n fullname = {}\n color = {}\n abbr = \"\"\n\n if country_name == 1:\n cname = \"us_aea_en\"\n fullname = united_states_of_america\n color = us_colors\n abbr = WV\n elif country_name == 2:\n cname = \"au_mill\"\n fullname = australia\n color = au_colors\n abbr = AUWA\n else:\n print(\"Enter a proper value\")\n exit(0)\n check_valid(united_states_of_america)\n print(\"----------------------\\n1. DFS\\n2. DFS with Forward Checking\\n3. DFS with Forward Checking and Singleton\\n4. DFS With Heuristic\\n5. DFS with Heuristic and Forward Checking\\n6. DFS with heuristic, Forward Checking and singleton\\n----------------------\")\n algo_name = int(input(\"Which algorithm would you like to select:\\n\"))\n\n start = timeit.default_timer()\n\n print(\"Starting with State\",abbr)\n\n if algo_name == 1:\n if (solve_problem_DFS(abbr, fullname, color)):\n print(colored)\n elif algo_name == 2:\n if (solve_problem_DFS_FC(abbr, fullname, color)):\n print(\"Count\",len(colored.keys()))\n print(colored)\n elif algo_name == 3:\n singleton = 1\n if solve_problem_DFS_FC(abbr, fullname, color):\n print(\"Count\",len(colored.keys()))\n print(colored)\n elif algo_name == 4:\n dfs_with_heuristic = 1\n if (solve_problem_DFS(abbr, fullname, color)):\n print(colored)\n elif algo_name == 5:\n dfs_with_heuristic = 1\n if (solve_problem_DFS_FC(abbr, fullname, color)):\n print(colored)\n elif algo_name == 6:\n dfs_with_heuristic = 1\n singleton = 1\n if (solve_problem_DFS_FC(abbr, fullname, color)):\n print(colored)\n else:\n print(\"Enter a proper value\")\n exit(0)\n stop = timeit.default_timer()\n print('\\nTime: ', stop - start)\n print(\"Number of Backtracking:-\",backtracking)\n makeBrowser(cname)\n colored.clear()\n","sub_path":"main/Depth First Search.py","file_name":"Depth First Search.py","file_ext":"py","file_size_in_byte":17659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"541151270","text":"#!/usr/bin/python\n\n\"\"\"\n # interacts with other devices connected to this device when receiving a packet\n\n @author: Al Zziwa \n @copyright: Oly Inc.\n @version: v1.0\n @date: 06/22/2016\n\n\n http://www.binarytides.com/programming-udp-sockets-in-python/\n\"\"\"\nimport os\nimport socket\nimport time\nimport config\nimport random\nfrom common.Queue import Queue\n\n\n\n\nclass ReceivingInterface:\n\n def __init__(self):\n \"\"\" initialize the class.\n \"\"\"\n self.sysReceivePort = config.RECEIVE_PORT\n\n\n\n def process_receive(self):\n \"\"\"\n CRON: receive the packets as they are being sent at the receiving port\n :return: success\n \"\"\"\n while True:\n # 1. receive the file - store quickly as a unique file and proceed to the next one\n socketObject = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n # use at least 2 x max-packet load size as buffer to receive packets\n (data, address) = socketObject.recvfrom(config.MAX_PACKET_SIZE * 2)\n\n incomingPacketFile = config.INCOMING_RAW_PACKETS_LOCATION + '.' + str(time.time()) + '-' + \\\n str(random.uniform(1.0, 9.0)) + '^' + address.join(':')\n\n # if real data is received, store quickly and move on to next packet\n if data:\n try:\n open(incomingPacketFile, 'w').write(data)\n except:\n pass\n\n # 2. add a job to the queue to process the raw incoming packet if data is received\n if os.path.getsize(incomingPacketFile) > 0:\n if data[:10] == config.BROADCAST_PACKET_MARKER:\n Queue('incoming-b').push(incomingPacketFile)\n else:\n Queue('incoming-1').push(incomingPacketFile)\n\n\n\n\n ","sub_path":"network/ReceivingInterface.py","file_name":"ReceivingInterface.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"73283480","text":"\"\"\"\n 用于Tie接触创建计算\n 1 确认接触单元的id\n 2 确认接触单元需调整方向的id\n\"\"\"\n\nimport os.path\nimport math\nimport sys\nimport os\n\ntry:\n dis_limit = int(sys.argv[1])\nexcept:\n dis_limit = 10\n\n\nfile_dir = os.path.dirname(__file__)\nloc_path = os.path.join(file_dir, '__temp_loc.txt')\nfem_path_base = os.path.join(file_dir, '__temp_base.fem')\nfem_path_target = os.path.join(file_dir, '__temp_target.fem')\n\nget_line_n = lambda line, n: line[8*n:8*(n+1)].strip()\n\n#\ndef str2float(str1):\n\n if '-' in str1[1:]:\n new_str1 = str1[0] + str1[1:].replace('-', 'e-')\n elif '+' in str1[1:]:\n new_str1 = str1[0] + str1[1:].replace('+', 'e+')\n else:\n new_str1 = str1\n\n return float(new_str1)\n\n\n\n# 读取&解析数据\ndef read_fem_path(fem_path):\n\n grid_dic = {}\n f = open(fem_path, 'r')\n while True:\n line = f.readline()\n if not line :break\n if \"$\" == line[0]: continue\n \n if \"GRID\" in line:\n g_id = get_line_n(line, 1)\n x = str2float(get_line_n(line, 3))\n y = str2float(get_line_n(line, 4))\n z = str2float(get_line_n(line, 5))\n grid_dic[g_id] = [x, y, z]\n continue\n \n return grid_dic\n\n\ndef read_loc_path(temp_path):\n\n with open(temp_path, 'r') as f:\n lines = [line for line in f.read().split('\\n') if line]\n\n base_locs = []\n for line in lines:\n loc = [float(v) for v in line.split(' ') if v]\n base_locs.append(loc)\n\n return base_locs\n\n\n# 区域扩展\ndef area_xyz(x, y, z):\n xs = [x+1, x, x-1]\n ys = [y+1, y, y-1]\n zs = [z+1, z, z-1]\n areas = []\n for x in xs:\n for y in ys:\n for z in zs:\n areas.append((x, y, z))\n\n return areas\n\n\ndef area_loc(locs):\n gain = 1\n\n areas = []\n for loc in locs:\n x = round(loc[0]/dis_limit*gain)\n y = round(loc[1]/dis_limit*gain)\n z = round(loc[2]/dis_limit*gain)\n key = (x, y, z)\n areas.append(key)\n\n return areas\n\n\n# 单元中心坐标计算及区域划分\ndef area_grid_loc(grid_dic):\n # 中心坐标计算\n\n elem_center_dic = {}\n area_2_elem_t = {}\n area_2_elem_b = {}\n elem_2_area = {}\n gain = 1\n\n area_2_grid = {}\n grid_2_area = {}\n\n for grid_id in grid_dic:\n loc = grid_dic[grid_id]\n x = round(loc[0]/dis_limit*gain)\n y = round(loc[1]/dis_limit*gain)\n z = round(loc[2]/dis_limit*gain)\n key = (x, y, z)\n if key not in area_2_grid:\n area_2_grid[key] = [grid_id]\n else:\n area_2_grid[key].append(grid_id) \n\n grid_2_area[grid_id] = key\n\n\n return area_2_grid, grid_2_area\n\n\nfun_loc_dis = lambda loc1, loc2 : sum([(v1-v2)**2 for v1, v2 in zip(loc1, loc2)])**0.5\nfun_loc_dis_list = lambda loc1, locs : [fun_loc_dis(loc1, loc2) for loc2 in locs]\n\n\nif __name__ == '__main__':\n\n # import time\n \n base_locs = read_loc_path(loc_path)\n grid_dic_base = read_fem_path(fem_path_base)\n grid_dic_target = read_fem_path(fem_path_target)\n \n area_2_grid_b, grid_2_area_b = area_grid_loc(grid_dic_base)\n area_2_grid_t, grid_2_area_t = area_grid_loc(grid_dic_target)\n\n \n result_strs = []\n loc_areas = area_loc(base_locs)\n for area, loc in zip(loc_areas, base_locs):\n ex_areas = area_xyz(*area)\n grid_ids_b, grid_ids_t = [], []\n for temp_area in ex_areas:\n if temp_area in area_2_grid_b: grid_ids_b.extend(area_2_grid_b[temp_area])\n if temp_area in area_2_grid_t: grid_ids_t.extend(area_2_grid_t[temp_area])\n\n grid_2_dis_b = {grid_id : fun_loc_dis(loc, grid_dic_base[grid_id]) for grid_id in grid_ids_b}\n grid_2_dis_t = {grid_id : fun_loc_dis(loc, grid_dic_target[grid_id]) for grid_id in grid_ids_t}\n for grid_id in grid_2_dis_t:\n if grid_id in grid_2_dis_b:\n del grid_2_dis_t[grid_id]\n\n grid_id_b = sorted(grid_2_dis_b, key=lambda x: grid_2_dis_b[x])[0]\n grid_id_t = sorted(grid_2_dis_t, key=lambda x: grid_2_dis_t[x])[0]\n if grid_id_b == grid_id_t:\n raise \"error grid_id_b == grid_id_t\"\n result_strs.append(\"*rigid {} {} 123456\".format(grid_id_b, grid_id_t))\n\n print('\\n'.join(result_strs))\n","sub_path":"02.hm/RigidSolidPointLinkShell/hmRigidSolidPointLinkShell.py","file_name":"hmRigidSolidPointLinkShell.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"328829610","text":"import sys\ntry:\n import xml.etree.cElementTree as ET\nexcept:\n import xml.etree.ElementTree as ET\nimport argparse\nimport os\nimport sys\nimport logging as log\n\n\ndef main():\n args = handleArgument()\n setupVerbosePrint(args.verbose)\n log.debug(args.stockList)\n log.debug(args.stockListPath)\n\n if os.path.exists('args.stockListPath'):\n updateStockXml(args.stockList, args.stockListPath)\n else:\n buildStockXml(args.stockList, args.stockListPath)\n\n\ndef updateStockXml(stockList, stockListPath):\n tree = ET.ElementTree(file=str(stockListPath))\n\n\ndef buildStockXml(stockList, stockListPath):\n stockListNode = ET.Element('stockList')\n for stock in stockList:\n stockNode = ET.SubElement(stockListNode, stock)\n root = ET.Element('root')\n root.extend((stockListNode))\n tree = ET.ElementTree(root)\n tree.write(sys.stdout)\n\n\ndef handleArgument():\n parser = argparse.ArgumentParser(description='Make a stock \\\nlist or append to old')\n parser.add_argument('-v',\n '--version',\n default=False,\n dest='verbose',\n action='store_true',\n help='Print verbose')\n parser.add_argument('-s',\n '--stocks',\n default=[],\n action='append',\n dest='stockList',\n nargs='+',\n help='List of Stocks, write the names of the \\\nstocks you would like to add')\n parser.add_argument('-p',\n '--path',\n action='store',\n default='data/stockList.xml',\n help='Path to stockList if want use a diffrent path',\n dest='stockListPath')\n return parser.parse_args()\n\n\ndef setupVerbosePrint(verbose):\n # set verbose logging level and out print if verbose arg is passed\n if verbose:\n log.basicConfig(format='%(levelname)s: %(message)s', level=log.DEBUG)\n else:\n log.basicConfig(format='%(levelname)s: %(message)s')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"buildStockList.py","file_name":"buildStockList.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"387214954","text":"import socket\nimport threading\n\n\ndef connection_scan(target_ip, target_port):\n \"\"\"Attempts to create a socket connection with the given IP address and port\"\"\"\n\n \"\"\"If successful, the port is open. If not, the port is closed\"\"\"\n try:\n conn_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n conn_socket.connect((target_ip, target_port))\n conn_socket.send(b'Banner_query\\r\\n')\n results = conn_socket.recv(100)\n print(\"[+] {}/tcp open\".format(target_port))\n print(\"[+] {}\\n\".format(str(results))) # Print banner grab results\n except OSError:\n print(\"[-] {}/tcp closed\\n\".format(target_port))\n finally:\n conn_socket.close() # Ensure the connections is closed\n\n\ndef port_scan(target, port_num):\n t = threading.Thread(target=connection_scan, args=(target, int(port_num)))\n t.start()","sub_path":"scan_ports_python.py","file_name":"scan_ports_python.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"461977276","text":"import turtle\r\nimport random\r\ncolors = ['red', 'green', 'blue', 'orange', 'purple', 'yellow', 'red']\r\nh = turtle.Turtle()\r\ndef house(x,y,wallColor,roofColor):\r\n h.penup()\r\n h.goto(x,y)\r\n h.setheading(0)\r\n h.pendown()\r\n h.begin_fill()\r\n h.color(wallColor)\r\n for i in range(4):\r\n h.right(90)\r\n h.forward(30)\r\n h.end_fill()\r\n h.backward(35)\r\n h.begin_fill()\r\n h.color(roofColor)\r\n h.left(60)\r\n h.forward(40)\r\n h.right(120)\r\n h.forward(40)\r\n h.right(120)\r\n h.forward(40)\r\n h.end_fill()\r\n\r\nfor i in range(10):\r\n x = random.randint(-200,200)\r\n y = random.randint(-200,200)\r\n wall = colors[random.randint(0,6)]\r\n roof = colors[random.randint(0,6)]\r\n house(x, y, wall, roof)\r\n","sub_path":"4-2 changing landscapes.py","file_name":"4-2 changing landscapes.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"171408003","text":"\"\"\"Tests for PyGeoOGC package.\"\"\"\nimport io\nimport sys\nimport zipfile\n\nimport pytest\nfrom shapely.geometry import Polygon\n\nimport pygeoogc\nfrom pygeoogc import WFS, WMS, ArcGISRESTful, MatchCRS, RetrySession, ServiceURL, utils\n\nDEF_CRS = \"epsg:4326\"\nALT_CRS = \"epsg:2149\"\n\n\n@pytest.fixture\ndef geometry_nat():\n return Polygon(\n [[-69.77, 45.07], [-69.31, 45.07], [-69.31, 45.45], [-69.77, 45.45], [-69.77, 45.07]]\n )\n\n\n@pytest.fixture\ndef geometry_urb():\n return Polygon(\n [\n [-118.72, 34.118],\n [-118.31, 34.118],\n [-118.31, 34.518],\n [-118.72, 34.518],\n [-118.72, 34.118],\n ]\n )\n\n\n@pytest.fixture\ndef wfs():\n return WFS(\n ServiceURL().wfs.waterdata,\n layer=\"wmadata:gagesii\",\n outformat=\"application/json\",\n version=\"2.0.0\",\n crs=\"epsg:4269\",\n )\n\n\n@pytest.mark.flaky(max_runs=3)\ndef test_restful_byid(geometry_nat):\n wbd2 = ArcGISRESTful(ServiceURL().restful.wbd)\n wbd2.layer = 1\n print(wbd2)\n wbd2.max_nrecords = 1\n wbd2.spatial_relation = \"esriSpatialRelIntersects\"\n wbd2.outformat = \"geojson\"\n wbd2.featureids = list(range(1, 6))\n fields = [f.lower() for f in wbd2.get_validfields()]\n wbd2.outfields = [\"huc2\", \"name\", \"areaacres\"]\n huc2 = wbd2.get_features()\n\n geom_type = utils.traverse_json(huc2, [\"features\", \"geometry\", \"type\"])\n\n assert (\n sum(len(h) for h in huc2) == 15 and [\"MultiPolygon\"] in geom_type and \"areaacres\" in fields\n )\n\n\n@pytest.mark.flaky(max_runs=3)\ndef test_restful_bygeom(geometry_nat):\n wbd8 = ArcGISRESTful(f\"{ServiceURL().restful.wbd}/4\")\n wbd8.n_threads = 4\n wbd8.oids_bygeom(geometry_nat.bounds)\n wbd8.oids_bygeom(geometry_nat)\n huc8_all = wbd8.get_features()\n wbd8.oids_bygeom(geometry_nat, sql_clause=\"areasqkm > 5000\")\n huc8_large = wbd8.get_features()\n assert len(huc8_all[0][\"features\"]) - len(huc8_large[0][\"features\"]) == 2\n\n\n@pytest.mark.flaky(max_runs=3)\ndef test_restful_bysql():\n hr = ArcGISRESTful(ServiceURL().restful.nhdplushr, outformat=\"json\")\n hr.layer = 1\n hr.layer = 2\n hr.oids_bysql(\"NHDPLUSID IN (5000500013223, 5000400039708, 5000500004825)\")\n resp_sql = hr.get_features(return_m=True)\n hr.oids_byfield(\"NHDPLUSID\", [5000500013223, 5000400039708, 5000500004825])\n resp_ids = hr.get_features()\n\n assert len(resp_sql[0][\"features\"]) == len(resp_ids[0][\"features\"])\n\n\n@pytest.mark.flaky(max_runs=3)\ndef test_wms(geometry_nat):\n url_wms = ServiceURL().wms.fws\n\n wms_111 = WMS(\n url_wms, layers=\"0\", outformat=\"image/tiff\", crs=DEF_CRS, version=\"1.1.1\", validation=False\n )\n r_dict_111 = wms_111.getmap_bybox(geometry_nat.bounds, 20, DEF_CRS)\n wms = WMS(url_wms, layers=\"0\", outformat=\"image/tiff\", crs=DEF_CRS)\n print(wms)\n r_dict = wms.getmap_bybox(geometry_nat.bounds, 20, DEF_CRS)\n assert (\n wms_111.get_validlayers()[\"0\"] == \"Wetlands_Raster\"\n and sys.getsizeof(r_dict_111[\"0_dd_0_0\"]) == 12536763\n and sys.getsizeof(r_dict[\"0_dd_0_0\"]) == 12536763\n )\n\n\n@pytest.mark.flaky(max_runs=3)\ndef test_wfsbyid(wfs):\n print(wfs)\n st = wfs.getfeature_byid(\"staid\", \"01031500\")\n assert st.json()[\"numberMatched\"] == 1\n\n\n@pytest.mark.flaky(max_runs=3)\ndef test_wfsbygeom(wfs, geometry_urb):\n r = wfs.getfeature_bygeom(geometry_urb, geo_crs=DEF_CRS, always_xy=False)\n assert len(r.json()[\"features\"]) == 7\n\n\n@pytest.mark.flaky(max_runs=3)\ndef test_wfsbybox(wfs, geometry_urb):\n bbox = geometry_urb.bounds\n r = wfs.getfeature_bybox(bbox, box_crs=DEF_CRS, always_xy=True)\n assert len(r.json()[\"features\"]) == 7\n\n\n@pytest.mark.flaky(max_runs=3)\ndef test_wfsbyfilter(wfs):\n wb = wfs.getfeature_byfilter(\"staid LIKE '010315%'\")\n assert len(utils.traverse_json(wb.json(), [\"features\", \"geometry\", \"coordinates\"])) == 2\n\n\ndef test_decompose(geometry_urb):\n bboxs = utils.bbox_decompose(geometry_urb.bounds, 10)\n assert bboxs[0][-1] == 2828\n\n\ndef test_matchcrs(geometry_urb):\n bounds = geometry_urb.bounds\n points = ((bounds[0], bounds[2]), (bounds[1], bounds[3]))\n coords = MatchCRS.coords(points, DEF_CRS, ALT_CRS)\n bbox = MatchCRS.bounds(geometry_urb.bounds, DEF_CRS, ALT_CRS)\n geom = MatchCRS.geometry(geometry_urb, DEF_CRS, ALT_CRS)\n assert (\n abs(geom.centroid.x * 1e-4 - (-362.099)) < 1e-3\n and abs(bbox[0] * 1e-4 - (-365.403)) < 1e-3\n and abs(coords[0][-1] * 1e-4 == (-287.707)) < 1e-3\n )\n\n\ndef test_esriquery():\n point = utils.ESRIGeomQuery((-118.72, 34.118), wkid=DEF_CRS).point()\n assert list(point.keys()) == [\"geometryType\", \"geometry\", \"inSR\"]\n\n\ndef test_ipv4():\n url = (\n \"https://edcintl.cr.usgs.gov/downloads/sciweb1/shared/uswem/web/conus\"\n + \"/eta/modis_eta/daily/downloads/det2004003.modisSSEBopETactual.zip\"\n )\n\n session = RetrySession()\n with session.onlyipv4():\n r = session.get(url)\n z = zipfile.ZipFile(io.BytesIO(r.content))\n fname = z.read(z.filelist[0].filename)\n\n assert sys.getsizeof(fname) == 4361682\n\n\ndef test_urls():\n urls = ServiceURL()\n assert (\n urls.restful.nwis == \"https://waterservices.usgs.gov/nwis\"\n and urls.restful.nldi == \"https://labs.waterdata.usgs.gov/api/nldi\"\n and urls.restful.daymet_point == \"https://daymet.ornl.gov/single-pixel/api/data\"\n and urls.restful.daymet_grid == \"https://thredds.daac.ornl.gov/thredds/ncss/ornldaac/1328\"\n and urls.restful.wbd == \"https://hydro.nationalmap.gov/arcgis/rest/services/wbd/MapServer\"\n and urls.restful.fws == \"https://www.fws.gov/wetlands/arcgis/rest/services\"\n and urls.restful.fema\n == \"https://hazards.fema.gov/gis/nfhl/rest/services/public/NFHL/MapServer\"\n and urls.wms.mrlc == \"https://www.mrlc.gov/geoserver/mrlc_download/wms\"\n and urls.wms.fema\n == \"https://hazards.fema.gov/gis/nfhl/rest/services/public/NFHLWMS/MapServer/WMSServer\"\n and urls.wms.nm_3dep\n == \"https://elevation.nationalmap.gov/arcgis/services/3DEPElevation/ImageServer/WMSServer\"\n and urls.wms.fws\n == \"https://www.fws.gov/wetlands/arcgis/services/Wetlands_Raster/ImageServer/WMSServer\"\n and urls.wfs.waterdata == \"https://labs.waterdata.usgs.gov/geoserver/wmadata/ows\"\n and urls.wfs.fema\n == \"https://hazards.fema.gov/gis/nfhl/services/public/NFHL/MapServer/WFSServer\"\n and urls.http.ssebopeta\n == \"https://edcintl.cr.usgs.gov/downloads/sciweb1/shared/uswem/web/conus/eta/modis_eta/daily/downloads\"\n )\n\n\ndef test_show_versions():\n f = io.StringIO()\n pygeoogc.show_versions(file=f)\n assert \"INSTALLED VERSIONS\" in f.getvalue()\n","sub_path":"tests/test_pygeoogc.py","file_name":"test_pygeoogc.py","file_ext":"py","file_size_in_byte":6702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"504207112","text":"from __future__ import absolute_import, division, print_function\n\nfrom collections import Iterable, defaultdict, deque\nfrom functools import reduce, partial\nimport numbers\nimport operator\n\nimport numpy as np\nimport scipy.sparse\n\nfrom .slicing import normalize_index\n\n# zip_longest with Python 2/3 compat\ntry:\n from itertools import zip_longest\nexcept ImportError:\n from itertools import izip_longest as zip_longest\n\ntry: # Windows compatibility\n int = long\nexcept NameError:\n pass\n\n\nclass COO(object):\n \"\"\" A Sparse Multidimensional Array\n\n This is stored in COO format. It depends on NumPy and Scipy.sparse for\n computation, but supports arrays of arbitrary dimension.\n\n Parameters\n ----------\n coords: np.ndarray (ndim, nnz)\n An array holding the index locations of every value\n Should have shape (number of dimensions, number of non-zeros)\n data: np.array (nnz,)\n An array of Values\n shape: tuple (ndim,), optional\n The shape of the array\n\n Examples\n --------\n >>> x = np.eye(4)\n >>> x[2, 3] = 5\n >>> s = COO(x)\n >>> s\n \n >>> s.data\n array([ 1., 1., 1., 5., 1.])\n >>> s.coords\n array([[0, 1, 2, 2, 3],\n [0, 1, 2, 3, 3]], dtype=uint8)\n\n >>> s.dot(s.T).sum(axis=0).todense()\n array([ 1., 1., 31., 6.])\n\n Make a sparse array by passing in an array of coordinates and an array of\n values.\n\n >>> coords = [[0, 0, 0, 1, 1],\n ... [0, 1, 2, 0, 3],\n ... [0, 3, 2, 0, 1]]\n >>> data = [1, 2, 3, 4, 5]\n >>> y = COO(coords, data, shape=(3, 4, 5))\n >>> y\n \n >>> tensordot(s, y, axes=(0, 1))\n \n\n Following scipy.sparse conventions you can also pass these as a tuple with\n rows and columns\n\n >>> rows = [0, 1, 2, 3, 4]\n >>> cols = [0, 0, 0, 1, 1]\n >>> data = [10, 20, 30, 40, 50]\n >>> z = COO((data, (rows, cols)))\n >>> z.todense()\n array([[10, 0],\n [20, 0],\n [30, 0],\n [ 0, 40],\n [ 0, 50]])\n\n You can also pass a dictionary or iterable of index/value pairs. Repeated\n indices imply summation:\n\n >>> d = {(0, 0, 0): 1, (1, 2, 3): 2, (1, 1, 0): 3}\n >>> COO(d)\n \n\n >>> L = [((0, 0), 1),\n ... ((1, 1), 2),\n ... ((0, 0), 3)]\n >>> COO(L).todense()\n array([[4, 0],\n [0, 2]])\n\n See Also\n --------\n COO.from_numpy\n COO.from_scipy_sparse\n \"\"\"\n __array_priority__ = 12\n\n def __init__(self, coords, data=None, shape=None, has_duplicates=True,\n sorted=False, cache=False):\n self._cache = None\n if cache:\n self.enable_caching()\n if data is None:\n # {(i, j, k): x, (i, j, k): y, ...}\n if isinstance(coords, dict):\n coords = list(coords.items())\n has_duplicates = False\n\n if isinstance(coords, COO):\n self.coords = coords.coords\n self.data = coords.data\n self.has_duplicates = coords.has_duplicates\n self.sorted = coords.sorted\n self.shape = coords.shape\n return\n\n if isinstance(coords, np.ndarray):\n result = COO.from_numpy(coords)\n self.coords = result.coords\n self.data = result.data\n self.has_duplicates = result.has_duplicates\n self.sorted = result.sorted\n self.shape = result.shape\n return\n\n # []\n if not coords:\n data = []\n coords = []\n\n # [((i, j, k), value), (i, j, k), value), ...]\n elif isinstance(coords[0][0], Iterable):\n if coords:\n assert len(coords[0]) == 2\n data = [x[1] for x in coords]\n coords = [x[0] for x in coords]\n coords = np.asarray(coords).T\n\n # (data, (row, col, slab, ...))\n else:\n data = coords[0]\n coords = np.stack(coords[1], axis=0)\n\n self.data = np.asarray(data)\n self.coords = np.asarray(coords)\n if self.coords.ndim == 1:\n self.coords = self.coords[None, :]\n\n if shape and not np.prod(self.coords.shape):\n self.coords = np.zeros((len(shape), 0), dtype=np.uint64)\n\n if shape is None:\n if self.coords.nbytes:\n shape = tuple((self.coords.max(axis=1) + 1).tolist())\n else:\n shape = ()\n\n if isinstance(shape, numbers.Integral):\n shape = (shape,)\n\n self.shape = tuple(shape)\n if self.shape:\n dtype = np.min_scalar_type(max(self.shape))\n else:\n dtype = np.int_\n self.coords = self.coords.astype(dtype)\n assert not self.shape or len(data) == self.coords.shape[1]\n self.has_duplicates = has_duplicates\n self.sorted = sorted\n\n def enable_caching(self):\n \"\"\" Enable caching of reshape, transpose, and tocsr/csc operations\n\n This enables efficient iterative workflows that make heavy use of\n csr/csc operations, such as tensordot. This maintains a cache of\n recent results of reshape and transpose so that operations like\n tensordot (which uses both internally) store efficiently stored\n representations for repeated use. This can significantly cut down on\n computational costs in common numeric algorithms.\n\n However, this also assumes that neither this object, nor the downstream\n objects will have their data mutated.\n\n Examples\n --------\n >>> x.enable_caching() # doctest: +SKIP\n >>> csr1 = x.transpose((2, 0, 1)).reshape((100, 120)).tocsr() # doctest: +SKIP\n >>> csr2 = x.transpose((2, 0, 1)).reshape((100, 120)).tocsr() # doctest: +SKIP\n >>> csr1 is csr2 # doctest: +SKIP\n True\n \"\"\"\n self._cache = defaultdict(lambda: deque(maxlen=3))\n return self\n\n @classmethod\n def from_numpy(cls, x):\n x = np.asanyarray(x)\n if x.shape:\n coords = np.where(x)\n data = x[coords]\n coords = np.vstack(coords)\n else:\n coords = np.empty((0, 1), dtype=np.uint8)\n data = np.array(x, ndmin=1)\n return cls(coords, data, shape=x.shape, has_duplicates=False,\n sorted=True)\n\n def todense(self):\n self.sum_duplicates()\n x = np.zeros(shape=self.shape, dtype=self.dtype)\n\n coords = tuple([self.coords[i, :] for i in range(self.ndim)])\n data = self.data\n\n if coords != ():\n x[coords] = data\n else:\n if len(data) != 0:\n x[coords] = data\n\n return x\n\n @classmethod\n def from_scipy_sparse(cls, x):\n x = scipy.sparse.coo_matrix(x)\n coords = np.empty((2, x.nnz), dtype=x.row.dtype)\n coords[0, :] = x.row\n coords[1, :] = x.col\n return COO(coords, x.data, shape=x.shape,\n has_duplicates=not x.has_canonical_format,\n sorted=x.has_canonical_format)\n\n @property\n def dtype(self):\n return self.data.dtype\n\n @property\n def ndim(self):\n return len(self.shape)\n\n @property\n def nnz(self):\n return self.coords.shape[1]\n\n @property\n def nbytes(self):\n return self.data.nbytes + self.coords.nbytes\n\n def __len__(self):\n \"\"\"\n Get \"length\" of array, which is by definition the size of the first\n dimension.\n\n Returns\n -------\n int\n The size of the first dimension.\n\n See Also\n --------\n numpy.ndarray.__len__ : Numpy equivalent property.\n\n Examples\n --------\n >>> x = np.zeros((10, 10))\n >>> s = COO.from_numpy(x)\n >>> len(s)\n 10\n \"\"\"\n return self.shape[0]\n\n def __sizeof__(self):\n return self.nbytes\n\n def __getitem__(self, index):\n if not isinstance(index, tuple):\n if isinstance(index, str):\n data = self.data[index]\n idx = np.where(data)\n coords = list(self.coords[:, idx[0]])\n coords.extend(idx[1:])\n\n return COO(coords, data[idx].flatten(),\n shape=self.shape + self.data.dtype[index].shape,\n has_duplicates=self.has_duplicates,\n sorted=self.sorted)\n else:\n index = (index,)\n\n last_ellipsis = len(index) > 0 and index[-1] is Ellipsis\n index = normalize_index(index, self.shape)\n if len(index) != 0 and all(not isinstance(ind, Iterable) and ind == slice(None) for ind in index):\n return self\n mask = np.ones(self.nnz, dtype=np.bool)\n for i, ind in enumerate([i for i in index if i is not None]):\n if not isinstance(ind, Iterable) and ind == slice(None):\n continue\n mask &= _mask(self.coords[i], ind, self.shape[i])\n\n n = mask.sum()\n coords = []\n shape = []\n i = 0\n for ind in index:\n if isinstance(ind, numbers.Integral):\n i += 1\n continue\n elif isinstance(ind, slice):\n step = ind.step if ind.step is not None else 1\n if step > 0:\n start = ind.start if ind.start is not None else 0\n start = max(start, 0)\n stop = ind.stop if ind.stop is not None else self.shape[i]\n stop = min(stop, self.shape[i])\n if start > stop:\n start = stop\n shape.append((stop - start + step - 1) // step)\n else:\n start = ind.start or self.shape[i] - 1\n stop = ind.stop if ind.stop is not None else -1\n start = min(start, self.shape[i] - 1)\n stop = max(stop, -1)\n if start < stop:\n start = stop\n shape.append((start - stop - step - 1) // (-step))\n\n dt = np.min_scalar_type(min(-(dim - 1) if dim != 0 else -1 for dim in shape))\n coords.append((self.coords[i, mask].astype(dt) - start) // step)\n i += 1\n elif isinstance(ind, Iterable):\n old = self.coords[i][mask]\n new = np.empty(shape=old.shape, dtype=old.dtype)\n for j, item in enumerate(ind):\n new[old == item] = j\n coords.append(new)\n shape.append(len(ind))\n i += 1\n elif ind is None:\n coords.append(np.zeros(n))\n shape.append(1)\n\n for j in range(i, self.ndim):\n coords.append(self.coords[j][mask])\n shape.append(self.shape[j])\n\n if coords:\n coords = np.stack(coords, axis=0)\n else:\n if last_ellipsis:\n coords = np.empty((0, np.sum(mask)), dtype=np.uint8)\n else:\n if np.sum(mask) != 0:\n return self.data[mask][0]\n else:\n return _zero_of_dtype(self.dtype)[()]\n shape = tuple(shape)\n data = self.data[mask]\n\n return COO(coords, data, shape=shape,\n has_duplicates=self.has_duplicates,\n sorted=self.sorted)\n\n def __str__(self):\n return \"\" % (\n self.shape, self.dtype, self.nnz, self.sorted,\n self.has_duplicates)\n\n __repr__ = __str__\n\n @staticmethod\n def _reduce(method, *args, **kwargs):\n assert len(args) == 1\n\n self = args[0]\n if isinstance(self, scipy.sparse.spmatrix):\n self = COO.from_scipy_sparse(self)\n\n return self.reduce(method, **kwargs)\n\n def reduce(self, method, axis=None, keepdims=False, **kwargs):\n zero_reduce_result = method.reduce([_zero_of_dtype(self.dtype)], **kwargs)\n\n if zero_reduce_result != _zero_of_dtype(np.dtype(zero_reduce_result)):\n raise ValueError(\"Performing this reduction operation would produce \"\n \"a dense result: %s\" % str(method))\n\n # Needed for more esoteric reductions like product.\n self.sum_duplicates()\n\n if axis is None:\n axis = tuple(range(self.ndim))\n\n if not isinstance(axis, tuple):\n axis = (axis,)\n\n if set(axis) == set(range(self.ndim)):\n result = method.reduce(self.data, **kwargs)\n if self.nnz != np.prod(self.shape):\n result = method(result, _zero_of_dtype(np.dtype(result))[()])\n else:\n axis = tuple(axis)\n neg_axis = tuple(ax for ax in range(self.ndim) if ax not in axis)\n\n a = self.transpose(neg_axis + axis)\n a = a.reshape((np.prod([self.shape[d] for d in neg_axis]),\n np.prod([self.shape[d] for d in axis])))\n a.sort_indices()\n\n result, inv_idx, counts = _grouped_reduce(a.data, a.coords[0], method, **kwargs)\n missing_counts = counts != a.shape[1]\n result[missing_counts] = method(result[missing_counts],\n _zero_of_dtype(result.dtype), **kwargs)\n\n a = COO(np.asarray([a.coords[0, inv_idx]]), result, shape=(np.prod(neg_axis),),\n has_duplicates=False, sorted=True)\n\n a = a.reshape([self.shape[d] for d in neg_axis])\n result = a\n\n if keepdims:\n result = _keepdims(self, result, axis)\n return result\n\n def sum(self, axis=None, keepdims=False, dtype=None, out=None):\n assert out is None\n return self.reduce(np.add, axis=axis, keepdims=keepdims, dtype=dtype)\n\n def max(self, axis=None, keepdims=False, out=None):\n assert out is None\n return self.reduce(np.maximum, axis=axis, keepdims=keepdims)\n\n def min(self, axis=None, keepdims=False, out=None):\n assert out is None\n return self.reduce(np.minimum, axis=axis, keepdims=keepdims)\n\n def prod(self, axis=None, keepdims=False, dtype=None, out=None):\n assert out is None\n return self.reduce(np.multiply, axis=axis, keepdims=keepdims, dtype=dtype)\n\n def transpose(self, axes=None):\n if axes is None:\n axes = list(reversed(range(self.ndim)))\n\n # Normalize all axe indices to posivite values\n axes = np.array(axes)\n axes[axes < 0] += self.ndim\n\n if np.any(axes >= self.ndim) or np.any(axes < 0):\n raise ValueError(\"invalid axis for this array\")\n\n if len(np.unique(axes)) < len(axes):\n raise ValueError(\"repeated axis in transpose\")\n\n if not len(axes) == self.ndim:\n raise ValueError(\"axes don't match array\")\n\n # Normalize all axe indices to posivite values\n try:\n axes = np.arange(self.ndim)[list(axes)]\n except IndexError:\n raise ValueError(\"invalid axis for this array\")\n\n if len(np.unique(axes)) < len(axes):\n raise ValueError(\"repeated axis in transpose\")\n\n if not len(axes) == self.ndim:\n raise ValueError(\"axes don't match array\")\n\n axes = tuple(axes)\n\n if axes == tuple(range(self.ndim)):\n return self\n\n if self._cache is not None:\n for ax, value in self._cache['transpose']:\n if ax == axes:\n return value\n\n shape = tuple(self.shape[ax] for ax in axes)\n result = COO(self.coords[axes, :], self.data, shape,\n has_duplicates=self.has_duplicates,\n cache=self._cache is not None)\n\n if self._cache is not None:\n self._cache['transpose'].append((axes, result))\n return result\n\n @property\n def T(self):\n return self.transpose(list(range(self.ndim))[::-1])\n\n def dot(self, other):\n return dot(self, other)\n\n def __matmul__(self, other):\n try:\n return dot(self, other)\n except NotImplementedError:\n return NotImplemented\n\n def __rmatmul__(self, other):\n try:\n return dot(other, self)\n except NotImplementedError:\n return NotImplemented\n\n def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):\n if method == '__call__':\n return COO._elemwise(ufunc, *inputs, **kwargs)\n elif method == 'reduce':\n return COO._reduce(ufunc, *inputs, **kwargs)\n else:\n return NotImplemented\n\n def linear_loc(self, signed=False):\n \"\"\" Index location of every piece of data in a flattened array\n\n This is used internally to check for duplicates, re-order, reshape,\n etc..\n \"\"\"\n return self._linear_loc(self.coords, self.shape, signed)\n\n @staticmethod\n def _linear_loc(coords, shape, signed=False):\n n = reduce(operator.mul, shape, 1)\n if signed:\n n = -n\n dtype = np.min_scalar_type(n)\n out = np.zeros(coords.shape[1], dtype=dtype)\n tmp = np.zeros(coords.shape[1], dtype=dtype)\n strides = 1\n for i, d in enumerate(shape[::-1]):\n # out += self.coords[-(i + 1), :].astype(dtype) * strides\n np.multiply(coords[-(i + 1), :], strides, out=tmp, dtype=dtype)\n np.add(tmp, out, out=out)\n strides *= d\n return out\n\n def reshape(self, shape):\n if self.shape == shape:\n return self\n if any(d == -1 for d in shape):\n extra = int(np.prod(self.shape) /\n np.prod([d for d in shape if d != -1]))\n shape = tuple([d if d != -1 else extra for d in shape])\n\n if self.shape == shape:\n return self\n\n if self._cache is not None:\n for sh, value in self._cache['reshape']:\n if sh == shape:\n return value\n\n # TODO: this np.prod(self.shape) enforces a 2**64 limit to array size\n linear_loc = self.linear_loc()\n\n max_shape = max(shape) if len(shape) != 0 else 1\n coords = np.empty((len(shape), self.nnz), dtype=np.min_scalar_type(max_shape - 1))\n strides = 1\n for i, d in enumerate(shape[::-1]):\n coords[-(i + 1), :] = (linear_loc // strides) % d\n strides *= d\n\n result = COO(coords, self.data, shape,\n has_duplicates=self.has_duplicates,\n sorted=self.sorted, cache=self._cache is not None)\n\n if self._cache is not None:\n self._cache['reshape'].append((shape, result))\n return result\n\n def to_scipy_sparse(self):\n assert self.ndim == 2\n result = scipy.sparse.coo_matrix((self.data,\n (self.coords[0],\n self.coords[1])),\n shape=self.shape)\n result.has_canonical_format = (not self.has_duplicates and self.sorted)\n return result\n\n def _tocsr(self):\n assert self.ndim == 2\n\n # Pass 1: sum duplicates\n self.sum_duplicates()\n\n # Pass 2: sort indices\n self.sort_indices()\n row, col = self.coords\n\n # Pass 3: count nonzeros in each row\n indptr = np.zeros(self.shape[0] + 1, dtype=np.int64)\n np.cumsum(np.bincount(row, minlength=self.shape[0]), out=indptr[1:])\n\n return scipy.sparse.csr_matrix((self.data, col, indptr), shape=self.shape)\n\n def tocsr(self):\n if self._cache is not None:\n try:\n return self._csr\n except AttributeError:\n pass\n try:\n self._csr = self._csc.tocsr()\n return self._csr\n except AttributeError:\n pass\n\n self._csr = csr = self._tocsr()\n else:\n csr = self._tocsr()\n return csr\n\n def tocsc(self):\n if self._cache is not None:\n try:\n return self._csc\n except AttributeError:\n pass\n try:\n self._csc = self._csr.tocsc()\n return self._csc\n except AttributeError:\n pass\n\n self._csc = csc = self.tocsr().tocsc()\n else:\n csc = self.tocsr().tocsc()\n\n return csc\n\n def sort_indices(self):\n if self.sorted:\n return\n\n linear = self.linear_loc(signed=True)\n\n if (np.diff(linear) > 0).all(): # already sorted\n self.sorted = True\n return self\n\n order = np.argsort(linear)\n self.coords = self.coords[:, order]\n self.data = self.data[order]\n self.sorted = True\n return self\n\n def sum_duplicates(self):\n # Inspired by scipy/sparse/coo.py::sum_duplicates\n # See https://github.com/scipy/scipy/blob/master/LICENSE.txt\n if not self.has_duplicates:\n return self\n if not np.prod(self.coords.shape):\n return self\n\n self.sort_indices()\n\n linear = self.linear_loc()\n unique_mask = np.diff(linear) != 0\n\n if unique_mask.sum() == len(unique_mask): # already unique\n self.has_duplicates = False\n return self\n\n unique_mask = np.append(True, unique_mask)\n\n coords = self.coords[:, unique_mask]\n (unique_inds,) = np.nonzero(unique_mask)\n data = np.add.reduceat(self.data, unique_inds, dtype=self.data.dtype)\n\n self.data = data\n self.coords = coords\n self.has_duplicates = False\n\n return self\n\n def __add__(self, other):\n return self.elemwise(operator.add, other)\n\n __radd__ = __add__\n\n def __neg__(self):\n return self.elemwise(operator.neg)\n\n def __sub__(self, other):\n return self.elemwise(operator.sub, other)\n\n def __rsub__(self, other):\n return -(self - other)\n\n def __mul__(self, other):\n return self.elemwise(operator.mul, other)\n\n __rmul__ = __mul__\n\n def __truediv__(self, other):\n return self.elemwise(operator.truediv, other)\n\n def __floordiv__(self, other):\n return self.elemwise(operator.floordiv, other)\n\n __div__ = __truediv__\n\n def __pow__(self, other):\n return self.elemwise(operator.pow, other)\n\n def __and__(self, other):\n return self.elemwise(operator.and_, other)\n\n def __xor__(self, other):\n return self.elemwise(operator.xor, other)\n\n def __or__(self, other):\n return self.elemwise(operator.or_, other)\n\n def __gt__(self, other):\n return self.elemwise(operator.gt, other)\n\n def __ge__(self, other):\n return self.elemwise(operator.ge, other)\n\n def __lt__(self, other):\n return self.elemwise(operator.lt, other)\n\n def __le__(self, other):\n return self.elemwise(operator.le, other)\n\n def __eq__(self, other):\n return self.elemwise(operator.eq, other)\n\n def __ne__(self, other):\n return self.elemwise(operator.ne, other)\n\n def __lshift__(self, other):\n return self.elemwise(operator.lshift, other)\n\n def __rshift__(self, other):\n return self.elemwise(operator.rshift, other)\n\n @staticmethod\n def _elemwise(func, *args, **kwargs):\n assert len(args) >= 1\n self = args[0]\n if isinstance(self, scipy.sparse.spmatrix):\n self = COO.from_numpy(self)\n elif np.isscalar(self) or (isinstance(self, np.ndarray)\n and self.ndim == 0):\n func = partial(func, self)\n other = args[1]\n if isinstance(other, scipy.sparse.spmatrix):\n other = COO.from_numpy(other)\n return other._elemwise_unary(func, *args[2:], **kwargs)\n\n if len(args) == 1:\n return self._elemwise_unary(func, *args[1:], **kwargs)\n else:\n other = args[1]\n if isinstance(other, COO):\n return self._elemwise_binary(func, *args[1:], **kwargs)\n elif isinstance(other, scipy.sparse.spmatrix):\n other = COO.from_scipy_sparse(other)\n return self._elemwise_binary(func, other, *args[2:], **kwargs)\n else:\n return self._elemwise_unary(func, *args[1:], **kwargs)\n\n def elemwise(self, func, *args, **kwargs):\n \"\"\"\n Apply a function to one or two arguments.\n\n Parameters\n ----------\n func\n The function to apply to one or two arguments.\n args : tuple, optional\n The extra arguments to pass to the function. If args[0] is a COO object\n or a scipy.sparse.spmatrix, the function will be treated as a binary\n function. Otherwise, it will be treated as a unary function.\n kwargs : dict, optional\n The kwargs to pass to the function.\n\n Returns\n -------\n COO\n The result of applying the function.\n \"\"\"\n return COO._elemwise(func, self, *args, **kwargs)\n\n def _elemwise_unary(self, func, *args, **kwargs):\n check = kwargs.pop('check', True)\n data_zero = _zero_of_dtype(self.dtype)\n func_zero = _zero_of_dtype(func(data_zero, *args, **kwargs).dtype)\n if check and func(data_zero, *args, **kwargs) != func_zero:\n raise ValueError(\"Performing this operation would produce \"\n \"a dense result: %s\" % str(func))\n\n data_func = func(self.data, *args, **kwargs)\n nonzero = data_func != func_zero\n\n return COO(self.coords[:, nonzero], data_func[nonzero],\n shape=self.shape,\n has_duplicates=self.has_duplicates,\n sorted=self.sorted)\n\n def _elemwise_binary(self, func, other, *args, **kwargs):\n assert isinstance(other, COO)\n check = kwargs.pop('check', True)\n self_zero = _zero_of_dtype(self.dtype)\n other_zero = _zero_of_dtype(other.dtype)\n func_zero = _zero_of_dtype(func(self_zero, other_zero, *args, **kwargs).dtype)\n if check and func(self_zero, other_zero, *args, **kwargs) != func_zero:\n raise ValueError(\"Performing this operation would produce \"\n \"a dense result: %s\" % str(func))\n self_shape, other_shape = self.shape, other.shape\n\n result_shape = self._get_broadcast_shape(self_shape, other_shape)\n self_params = self._get_broadcast_parameters(self.shape, result_shape)\n other_params = self._get_broadcast_parameters(other.shape, result_shape)\n combined_params = [p1 and p2 for p1, p2 in zip(self_params, other_params)]\n self_reduce_params = combined_params[-self.ndim:]\n other_reduce_params = combined_params[-other.ndim:]\n\n self.sum_duplicates() # TODO: document side-effect or make copy\n other.sum_duplicates() # TODO: document side-effect or make copy\n\n self_coords = self.coords\n self_data = self.data\n\n self_reduced_coords, self_reduced_shape = \\\n self._get_reduced_coords(self_coords, self_shape,\n self_reduce_params)\n self_reduced_linear = self._linear_loc(self_reduced_coords, self_reduced_shape)\n i = np.argsort(self_reduced_linear)\n self_reduced_linear = self_reduced_linear[i]\n self_coords = self_coords[:, i]\n self_data = self_data[i]\n\n # Store coords\n other_coords = other.coords\n other_data = other.data\n\n other_reduced_coords, other_reduced_shape = \\\n self._get_reduced_coords(other_coords, other_shape,\n other_reduce_params)\n other_reduced_linear = self._linear_loc(other_reduced_coords, other_reduced_shape)\n i = np.argsort(other_reduced_linear)\n other_reduced_linear = other_reduced_linear[i]\n other_coords = other_coords[:, i]\n other_data = other_data[i]\n\n # Find matches between self.coords and other.coords\n matched_self, matched_other = _match_arrays(self_reduced_linear,\n other_reduced_linear)\n\n # Start with an empty list. This may reduce computation in many cases.\n data_list = []\n coords_list = []\n\n # Add the matched part.\n matched_coords = self._get_matching_coords(self_coords[:, matched_self],\n other_coords[:, matched_other],\n self_shape, other_shape)\n\n data_list.append(func(self_data[matched_self],\n other_data[matched_other],\n *args, **kwargs))\n coords_list.append(matched_coords)\n\n self_func = func(self_data, other_zero, *args, **kwargs)\n # Add unmatched parts as necessary.\n if (self_func != func_zero).any():\n self_unmatched_coords, self_unmatched_func = \\\n self._get_unmatched_coords_data(self_coords, self_func, self_shape,\n result_shape, matched_self,\n matched_coords)\n\n data_list.extend(self_unmatched_func)\n coords_list.extend(self_unmatched_coords)\n\n other_func = func(self_zero, other_data, *args, **kwargs)\n\n if (other_func != func_zero).any():\n other_unmatched_coords, other_unmatched_func = \\\n self._get_unmatched_coords_data(other_coords, other_func, other_shape,\n result_shape, matched_other,\n matched_coords)\n\n coords_list.extend(other_unmatched_coords)\n data_list.extend(other_unmatched_func)\n\n # Concatenate matches and mismatches\n data = np.concatenate(data_list) if len(data_list) else np.empty((0,), dtype=self.dtype)\n coords = np.concatenate(coords_list, axis=1) if len(coords_list) else \\\n np.empty((0, len(result_shape)), dtype=self.coords.dtype)\n\n nonzero = data != func_zero\n data = data[nonzero]\n coords = coords[:, nonzero]\n\n return COO(coords, data, shape=result_shape, has_duplicates=False)\n\n @staticmethod\n def _get_unmatched_coords_data(coords, data, shape, result_shape, matched_idx,\n matched_coords):\n \"\"\"\n Get the unmatched coordinates and data - both those that are unmatched with\n any point of the other data as well as those which are added because of\n broadcasting.\n\n Parameters\n ----------\n coords : np.ndarray\n The coordinates to get the unmatched coordinates from.\n data : np.ndarray\n The data corresponding to these coordinates.\n shape : tuple[int]\n The shape corresponding to these coordinates.\n result_shape : tuple[int]\n The result broadcasting shape.\n matched_idx : np.ndarray\n The indices into the coords array where it matches with the other array.\n matched_coords : np.ndarray\n The overall coordinates that match from both arrays.\n\n Returns\n -------\n coords_list : list[np.ndarray]\n The list of unmatched/broadcasting coordinates.\n data_list : list[np.ndarray]\n The data corresponding to the coordinates.\n \"\"\"\n params = COO._get_broadcast_parameters(shape, result_shape)\n matched = np.zeros(len(data), dtype=np.bool)\n matched[matched_idx] = True\n unmatched = ~matched\n data_zero = _zero_of_dtype(data.dtype)\n nonzero = data != data_zero\n\n unmatched &= nonzero\n matched &= nonzero\n\n coords_list = []\n data_list = []\n\n unmatched_coords, unmatched_data = \\\n COO._get_expanded_coords_data(coords[:, unmatched],\n data[unmatched],\n params,\n result_shape)\n\n coords_list.append(unmatched_coords)\n data_list.append(unmatched_data)\n\n if shape != result_shape:\n broadcast_coords, broadcast_data = \\\n COO._get_broadcast_coords_data(coords[:, matched],\n matched_coords,\n data[matched],\n params,\n result_shape)\n\n coords_list.append(broadcast_coords)\n data_list.append(broadcast_data)\n\n return coords_list, data_list\n\n @staticmethod\n def _get_broadcast_shape(shape1, shape2, is_result=False):\n \"\"\"\n Get the overall broadcasted shape.\n\n Parameters\n ----------\n shape1, shape2 : tuple[int]\n The input shapes to broadcast together.\n is_result : bool\n Whether or not shape2 is also the result shape.\n\n Returns\n -------\n result_shape : tuple[int]\n The overall shape of the result.\n\n Raises\n ------\n ValueError\n If the two shapes cannot be broadcast together.\n \"\"\"\n # https://stackoverflow.com/a/47244284/774273\n if not all((l1 == l2) or (l1 == 1) or ((l2 == 1) and not is_result) for l1, l2 in\n zip(shape1[::-1], shape2[::-1])):\n raise ValueError('operands could not be broadcast together with shapes %s, %s' %\n (shape1, shape2))\n\n result_shape = tuple(max(l1, l2) for l1, l2 in\n zip_longest(shape1[::-1], shape2[::-1], fillvalue=1))[::-1]\n\n return result_shape\n\n @staticmethod\n def _get_broadcast_parameters(shape, broadcast_shape):\n \"\"\"\n Get the broadcast parameters.\n\n Parameters\n ----------\n shape : tuple[int]\n The input shape.\n broadcast_shape\n The shape to broadcast to.\n\n Returns\n -------\n params : list\n A list containing None if the dimension isn't in the original array, False if\n it needs to be broadcast, and True if it doesn't.\n \"\"\"\n params = [None if l1 is None else l1 == l2 for l1, l2\n in zip_longest(shape[::-1], broadcast_shape[::-1], fillvalue=None)][::-1]\n\n return params\n\n @staticmethod\n def _get_reduced_coords(coords, shape, params):\n \"\"\"\n Gets only those dimensions of the coordinates that don't need to be broadcast.\n\n Parameters\n ----------\n coords : np.ndarray\n The coordinates to reduce.\n params : list\n The params from which to check which dimensions to get.\n\n Returns\n -------\n reduced_coords : np.ndarray\n The reduced coordinates.\n \"\"\"\n reduced_params = [bool(param) for param in params]\n reduced_shape = tuple(l for l, p in zip(shape, params) if p)\n\n return coords[reduced_params], reduced_shape\n\n @staticmethod\n def _get_expanded_coords_data(coords, data, params, broadcast_shape):\n \"\"\"\n Expand coordinates/data to broadcast_shape. Does most of the heavy lifting for broadcast_to.\n Produces sorted output for sorted inputs.\n\n Parameters\n ----------\n coords : np.ndarray\n The coordinates to expand.\n data : np.ndarray\n The data corresponding to the coordinates.\n params : list\n The broadcast parameters.\n broadcast_shape : tuple[int]\n The shape to broadcast to.\n\n Returns\n -------\n expanded_coords : np.ndarray\n List of 1-D arrays. Each item in the list has one dimension of coordinates.\n expanded_data : np.ndarray\n The data corresponding to expanded_coords.\n \"\"\"\n first_dim = -1\n expand_shapes = []\n for d, p, l in zip(range(len(broadcast_shape)), params, broadcast_shape):\n if p and first_dim == -1:\n expand_shapes.append(coords.shape[1])\n first_dim = d\n\n if not p:\n expand_shapes.append(l)\n\n all_idx = COO._cartesian_product(*(np.arange(d, dtype=np.min_scalar_type(d - 1)) for d in expand_shapes))\n dt = np.result_type(*(np.min_scalar_type(l - 1) for l in broadcast_shape))\n\n false_dim = 0\n dim = 0\n\n expanded_coords = np.empty((len(broadcast_shape), all_idx.shape[1]), dtype=dt)\n expanded_data = data[all_idx[first_dim]]\n\n for d, p, l in zip(range(len(broadcast_shape)), params, broadcast_shape):\n if p:\n expanded_coords[d] = coords[dim, all_idx[first_dim]]\n else:\n expanded_coords[d] = all_idx[false_dim + (d > first_dim)]\n false_dim += 1\n\n if p is not None:\n dim += 1\n\n return np.asarray(expanded_coords), np.asarray(expanded_data)\n\n # (c) senderle\n # Taken from https://stackoverflow.com/a/11146645/774273\n # License: https://creativecommons.org/licenses/by-sa/3.0/\n @staticmethod\n def _cartesian_product(*arrays):\n \"\"\"\n Get the cartesian product of a number of arrays.\n\n Parameters\n ----------\n arrays : Iterable[np.ndarray]\n The arrays to get a cartesian product of. Always sorted with respect\n to the original array.\n\n Returns\n -------\n out : np.ndarray\n The overall cartesian product of all the input arrays.\n \"\"\"\n broadcastable = np.ix_(*arrays)\n broadcasted = np.broadcast_arrays(*broadcastable)\n rows, cols = np.prod(broadcasted[0].shape), len(broadcasted)\n dtype = np.result_type(*arrays)\n out = np.empty(rows * cols, dtype=dtype)\n start, end = 0, rows\n for a in broadcasted:\n out[start:end] = a.reshape(-1)\n start, end = end, end + rows\n return out.reshape(cols, rows)\n\n def broadcast_to(self, shape):\n \"\"\"\n Performs the equivalent of np.broadcast_to for COO.\n\n Parameters\n ----------\n shape : tuple[int]\n The shape to broadcast the data to.\n\n Returns\n -------\n The broadcasted sparse array.\n\n Raises\n ------\n ValueError\n If the operand cannot be broadcast to the given shape.\n \"\"\"\n result_shape = self._get_broadcast_shape(self.shape, shape, is_result=True)\n params = self._get_broadcast_parameters(self.shape, result_shape)\n coords, data = self._get_expanded_coords_data(self.coords, self.data, params, result_shape)\n\n return COO(coords, data, shape=result_shape, has_duplicates=self.has_duplicates,\n sorted=self.sorted)\n\n @staticmethod\n def _get_matching_coords(coords1, coords2, shape1, shape2):\n \"\"\"\n Takes in the matching coordinates in both dimensions (only those dimensions that\n don't need to be broadcast in both arrays and returns the coordinates that will\n overlap in the output array, i.e., the coordinates for which both broadcast arrays\n will be nonzero.\n\n Parameters\n ----------\n coords1, coords2 : np.ndarray\n shape1, shape2 : tuple[int]\n\n Returns\n -------\n matching_coords : np.ndarray\n The coordinates of the output array for which both inputs will be nonzero.\n \"\"\"\n result_shape = COO._get_broadcast_shape(shape1, shape2)\n params1 = COO._get_broadcast_parameters(shape1, result_shape)\n params2 = COO._get_broadcast_parameters(shape2, result_shape)\n\n matching_coords = []\n dim1 = 0\n dim2 = 0\n\n for p1, p2 in zip(params1, params2):\n if p1:\n matching_coords.append(coords1[dim1])\n else:\n matching_coords.append(coords2[dim2])\n\n if p1 is not None:\n dim1 += 1\n\n if p2 is not None:\n dim2 += 1\n\n return np.asarray(matching_coords)\n\n @staticmethod\n def _get_broadcast_coords_data(coords, matched_coords, data, params, broadcast_shape):\n \"\"\"\n Get data that matched in the reduced coordinates but still had a partial overlap because of\n the broadcast, i.e., it didn't match in one of the other dimensions.\n\n Parameters\n ----------\n coords : np.ndarray\n The list of coordinates of the required array. Must be sorted.\n matched_coords : np.ndarray\n The list of coordinates that match. Must be sorted.\n data : np.ndarray\n The data corresponding to coords.\n params : list\n The broadcast parameters.\n broadcast_shape : tuple[int]\n The shape to get the broadcast coordinates.\n\n Returns\n -------\n broadcast_coords : np.ndarray\n The broadcasted coordinates. Is sorted.\n broadcasted_data : np.ndarray\n The data corresponding to those coordinates.\n \"\"\"\n full_coords, full_data = COO._get_expanded_coords_data(coords, data, params, broadcast_shape)\n linear_full_coords = COO._linear_loc(full_coords, broadcast_shape)\n linear_matched_coords = COO._linear_loc(matched_coords, broadcast_shape)\n\n overlapping_coords, _ = _match_arrays(linear_full_coords, linear_matched_coords)\n mask = np.ones(full_coords.shape[1], dtype=np.bool)\n mask[overlapping_coords] = False\n\n return full_coords[:, mask], full_data[mask]\n\n def __abs__(self):\n return self.elemwise(abs)\n\n def exp(self, out=None):\n assert out is None\n return self.elemwise(np.exp)\n\n def expm1(self, out=None):\n assert out is None\n return self.elemwise(np.expm1)\n\n def log1p(self, out=None):\n assert out is None\n return self.elemwise(np.log1p)\n\n def sin(self, out=None):\n assert out is None\n return self.elemwise(np.sin)\n\n def sinh(self, out=None):\n assert out is None\n return self.elemwise(np.sinh)\n\n def tan(self, out=None):\n assert out is None\n return self.elemwise(np.tan)\n\n def tanh(self, out=None):\n assert out is None\n return self.elemwise(np.tanh)\n\n def sqrt(self, out=None):\n assert out is None\n return self.elemwise(np.sqrt)\n\n def ceil(self, out=None):\n assert out is None\n return self.elemwise(np.ceil)\n\n def floor(self, out=None):\n assert out is None\n return self.elemwise(np.floor)\n\n def round(self, decimals=0, out=None):\n assert out is None\n return self.elemwise(np.round, decimals)\n\n def rint(self, out=None):\n assert out is None\n return self.elemwise(np.rint)\n\n def conj(self, out=None):\n assert out is None\n return self.elemwise(np.conj)\n\n def conjugate(self, out=None):\n assert out is None\n return self.elemwise(np.conjugate)\n\n def astype(self, dtype, out=None):\n assert out is None\n return self.elemwise(np.ndarray.astype, dtype)\n\n def maybe_densify(self, allowed_nnz=1e3, allowed_fraction=0.25):\n \"\"\" Convert to a dense numpy array if not too costly. Err othrewise \"\"\"\n if reduce(operator.mul, self.shape) <= allowed_nnz or self.nnz >= np.prod(self.shape) * allowed_fraction:\n return self.todense()\n else:\n raise NotImplementedError(\"Operation would require converting \"\n \"large sparse array to dense\")\n\n\ndef tensordot(a, b, axes=2):\n # Much of this is stolen from numpy/core/numeric.py::tensordot\n # Please see license at https://github.com/numpy/numpy/blob/master/LICENSE.txt\n try:\n iter(axes)\n except TypeError:\n axes_a = list(range(-axes, 0))\n axes_b = list(range(0, axes))\n else:\n axes_a, axes_b = axes\n try:\n na = len(axes_a)\n axes_a = list(axes_a)\n except TypeError:\n axes_a = [axes_a]\n na = 1\n try:\n nb = len(axes_b)\n axes_b = list(axes_b)\n except TypeError:\n axes_b = [axes_b]\n nb = 1\n\n # a, b = asarray(a), asarray(b) # <--- modified\n as_ = a.shape\n nda = a.ndim\n bs = b.shape\n ndb = b.ndim\n equal = True\n if na != nb:\n equal = False\n else:\n for k in range(na):\n if as_[axes_a[k]] != bs[axes_b[k]]:\n equal = False\n break\n if axes_a[k] < 0:\n axes_a[k] += nda\n if axes_b[k] < 0:\n axes_b[k] += ndb\n if not equal:\n raise ValueError(\"shape-mismatch for sum\")\n\n # Move the axes to sum over to the end of \"a\"\n # and to the front of \"b\"\n notin = [k for k in range(nda) if k not in axes_a]\n newaxes_a = notin + axes_a\n N2 = 1\n for axis in axes_a:\n N2 *= as_[axis]\n newshape_a = (-1, N2)\n olda = [as_[axis] for axis in notin]\n\n notin = [k for k in range(ndb) if k not in axes_b]\n newaxes_b = axes_b + notin\n N2 = 1\n for axis in axes_b:\n N2 *= bs[axis]\n newshape_b = (N2, -1)\n oldb = [bs[axis] for axis in notin]\n\n at = a.transpose(newaxes_a).reshape(newshape_a)\n bt = b.transpose(newaxes_b).reshape(newshape_b)\n res = _dot(at, bt)\n if isinstance(res, scipy.sparse.spmatrix):\n if res.nnz > reduce(operator.mul, res.shape) / 2:\n res = res.todense()\n else:\n res = COO.from_scipy_sparse(res) # <--- modified\n res.has_duplicates = False\n if isinstance(res, np.matrix):\n res = np.asarray(res)\n return res.reshape(olda + oldb)\n\n\ndef dot(a, b):\n if not hasattr(a, 'ndim') or not hasattr(b, 'ndim'):\n raise NotImplementedError(\n \"Cannot perform dot product on types %s, %s\" %\n (type(a), type(b)))\n return tensordot(a, b, axes=((a.ndim - 1,), (b.ndim - 2,)))\n\n\ndef _dot(a, b):\n if isinstance(a, COO):\n a.sum_duplicates()\n if isinstance(b, COO):\n b.sum_duplicates()\n if isinstance(b, COO) and not isinstance(a, COO):\n return _dot(b.T, a.T).T\n aa = a.tocsr()\n\n if isinstance(b, (COO, scipy.sparse.spmatrix)):\n b = b.tocsc()\n return aa.dot(b)\n\n\ndef _keepdims(original, new, axis):\n shape = list(original.shape)\n for ax in axis:\n shape[ax] = 1\n return new.reshape(shape)\n\n\ndef _mask(coords, idx, shape):\n if isinstance(idx, numbers.Integral):\n return coords == idx\n elif isinstance(idx, slice):\n step = idx.step if idx.step is not None else 1\n if step > 0:\n start = idx.start if idx.start is not None else 0\n stop = idx.stop if idx.stop is not None else shape\n return (coords >= start) & (coords < stop) & \\\n (coords % step == start % step)\n else:\n start = idx.start if idx.start is not None else (shape - 1)\n stop = idx.stop if idx.stop is not None else -1\n return (coords <= start) & (coords > stop) & \\\n (coords % step == start % step)\n elif isinstance(idx, Iterable):\n mask = np.zeros(len(coords), dtype=np.bool)\n for item in idx:\n mask |= _mask(coords, item, shape)\n return mask\n\n\ndef concatenate(arrays, axis=0):\n arrays = [x if isinstance(x, COO) else COO(x) for x in arrays]\n if axis < 0:\n axis = axis + arrays[0].ndim\n assert all(x.shape[ax] == arrays[0].shape[ax]\n for x in arrays\n for ax in set(range(arrays[0].ndim)) - {axis})\n nnz = 0\n dim = sum(x.shape[axis] for x in arrays)\n shape = list(arrays[0].shape)\n shape[axis] = dim\n\n coords_dtype = np.min_scalar_type(max(shape) - 1) if len(shape) != 0 else np.uint8\n data = np.concatenate([x.data for x in arrays])\n coords = np.concatenate([x.coords for x in arrays], axis=1).astype(coords_dtype)\n\n dim = 0\n for x in arrays:\n if dim:\n coords[axis, nnz:x.nnz + nnz] += dim\n dim += x.shape[axis]\n nnz += x.nnz\n\n has_duplicates = any(x.has_duplicates for x in arrays)\n\n return COO(coords, data, shape=shape, has_duplicates=has_duplicates,\n sorted=(axis == 0) and all(a.sorted for a in arrays))\n\n\ndef stack(arrays, axis=0):\n assert len(set(x.shape for x in arrays)) == 1\n arrays = [x if isinstance(x, COO) else COO(x) for x in arrays]\n if axis < 0:\n axis = axis + arrays[0].ndim + 1\n data = np.concatenate([x.data for x in arrays])\n coords = np.concatenate([x.coords for x in arrays], axis=1)\n shape = list(arrays[0].shape)\n shape.insert(axis, len(arrays))\n\n coords_dtype = np.min_scalar_type(max(shape) - 1) if len(shape) != 0 else np.uint8\n\n nnz = 0\n dim = 0\n new = np.empty(shape=(coords.shape[1],), dtype=coords_dtype)\n for x in arrays:\n new[nnz:x.nnz + nnz] = dim\n dim += 1\n nnz += x.nnz\n\n has_duplicates = any(x.has_duplicates for x in arrays)\n coords = [coords[i].astype(coords_dtype) for i in range(coords.shape[0])]\n coords.insert(axis, new)\n coords = np.stack(coords, axis=0)\n\n return COO(coords, data, shape=shape, has_duplicates=has_duplicates,\n sorted=(axis == 0) and all(a.sorted for a in arrays))\n\n\ndef triu(x, k=0):\n \"\"\"\n Calculates the equivalent of np.triu(x, k) for COO.\n\n Parameters\n ----------\n x : COO\n The input array.\n k : int\n The diagonal below which elements are set to zero.\n\n Returns\n -------\n COO\n The output upper-triangular matrix.\n \"\"\"\n if not x.ndim >= 2:\n raise NotImplementedError('sparse.triu is not implemented for scalars or 1-D arrays.')\n\n mask = x.coords[-2] + k <= x.coords[-1]\n\n coords = x.coords[:, mask]\n data = x.data[mask]\n\n return COO(coords, data, x.shape, x.has_duplicates, x.sorted)\n\n\ndef tril(x, k=0):\n \"\"\"\n Calculates the equivalent of np.tril(x, k) for COO.\n\n Parameters\n ----------\n x : COO\n The input array.\n k : int\n The diagonal above which elements are set to zero.\n\n Returns\n -------\n COO\n The output lower-triangular matrix.\n \"\"\"\n if not x.ndim >= 2:\n raise NotImplementedError('sparse.tril is not implemented for scalars or 1-D arrays.')\n\n mask = x.coords[-2] + k >= x.coords[-1]\n\n coords = x.coords[:, mask]\n data = x.data[mask]\n\n return COO(coords, data, x.shape, x.has_duplicates, x.sorted)\n\n\ndef _zero_of_dtype(dtype):\n \"\"\"\n Creates a ()-shaped 0-sized array of a given dtype\n Parameters\n ----------\n dtype : np.dtype\n The dtype for the array.\n Returns\n -------\n The zero array.\n \"\"\"\n return np.zeros((), dtype=dtype)\n\n\n# (c) Paul Panzer\n# Taken from https://stackoverflow.com/a/47833496/774273\n# License: https://creativecommons.org/licenses/by-sa/3.0/\ndef _match_arrays(a, b):\n \"\"\"\n Finds all indexes into a and b such that a[i] = b[j]. The outputs are sorted\n in lexographical order.\n\n Parameters\n ----------\n a, b : np.ndarray\n The input 1-D arrays to match. If matching of multiple fields is\n needed, use np.recarrays. These two arrays must be sorted.\n\n Returns\n -------\n a_idx, b_idx : np.ndarray\n The output indices of every possible pair of matching elements.\n \"\"\"\n if len(a) == 0 or len(b) == 0:\n return np.array([], dtype=np.uint8), np.array([], dtype=np.uint8)\n asw = np.r_[0, 1 + np.flatnonzero(a[:-1] != a[1:]), len(a)]\n bsw = np.r_[0, 1 + np.flatnonzero(b[:-1] != b[1:]), len(b)]\n al, bl = np.diff(asw), np.diff(bsw)\n na = len(al)\n asw, bsw = asw, bsw\n abunq = np.r_[a[asw[:-1]], b[bsw[:-1]]]\n m = np.argsort(abunq, kind='mergesort')\n mv = abunq[m]\n midx = np.flatnonzero(mv[:-1] == mv[1:])\n ai, bi = m[midx], m[midx + 1] - na\n aic = np.r_[0, np.cumsum(al[ai])]\n a_idx = np.ones((aic[-1],), dtype=np.int_)\n a_idx[aic[:-1]] = asw[ai]\n a_idx[aic[1:-1]] -= asw[ai[:-1]] + al[ai[:-1]] - 1\n a_idx = np.repeat(np.cumsum(a_idx), np.repeat(bl[bi], al[ai]))\n bi = np.repeat(bi, al[ai])\n bic = np.r_[0, np.cumsum(bl[bi])]\n b_idx = np.ones((bic[-1],), dtype=np.int_)\n b_idx[bic[:-1]] = bsw[bi]\n b_idx[bic[1:-1]] -= bsw[bi[:-1]] + bl[bi[:-1]] - 1\n b_idx = np.cumsum(b_idx)\n return a_idx, b_idx\n\n\ndef _grouped_reduce(x, groups, method, **kwargs):\n # Partial credit to @shoyer\n # Ref: https://gist.github.com/shoyer/f538ac78ae904c936844\n flag = np.concatenate(([True] if len(x) != 0 else [], groups[1:] != groups[:-1]))\n inv_idx, = flag.nonzero()\n result = method.reduceat(x, inv_idx, **kwargs)\n counts = np.diff(np.concatenate((inv_idx, [len(x)])))\n return result, inv_idx, counts\n\n\ndef random(\n shape,\n density=0.01,\n canonical_order=False,\n random_state=None,\n data_rvs=None,\n):\n \"\"\" Generate a random sparse multidimensional array\n\n Parameters\n ----------\n shape: :obj:`tuple` of :obj:`int`\n Shape of the array\n density: :obj:`float`, optional\n Density of the generated array.\n canonical_order : bool, optional\n Whether or not to put the output :obj:`COO` object into canonical\n order. :code:`False` by default.\n random_state : {numpy.random.RandomState, int}, optional\n Random number generator or random seed. If not given, the\n singleton numpy.random will be used. This random state will be used\n for sampling the sparsity structure, but not necessarily for sampling\n the values of the structurally nonzero entries of the matrix.\n data_rvs : callable\n Data generation callback. Must accept one single parameter: number of\n :code:`nnz` elements, and return one single NumPy array of exactly\n that length.\n\n Returns\n -------\n COO\n The generated random matrix.\n\n See Also\n --------\n :obj:`scipy.sparse.rand`\n Equivalent Scipy function.\n\n Examples\n --------\n\n >>> from sparse import random\n >>> from scipy import stats\n >>> rvs = lambda x: stats.poisson(25, loc=10).rvs(x, random_state=np.random.RandomState(1))\n >>> S = random((2, 3, 4), density=0.25, random_state=np.random.RandomState(1), data_rvs=rvs)\n >>> S.todense()\n array([[[ 0, 0, 0, 0],\n [ 0, 34, 0, 0],\n [33, 34, 0, 29]],\n \n [[30, 0, 0, 34],\n [ 0, 0, 0, 0],\n [ 0, 0, 0, 0]]])\n\n \"\"\"\n # Copied, in large part, from scipy.sparse.random\n # See https://github.com/scipy/scipy/blob/master/LICENSE.txt\n\n elements = np.prod(shape)\n\n nnz = int(elements * density)\n\n if random_state is None:\n random_state = np.random\n elif isinstance(random_state, numbers.Integral):\n random_state = np.random.RandomState(random_state)\n if data_rvs is None:\n data_rvs = random_state.rand\n\n # Use the algorithm from python's random.sample for k < mn/3.\n if elements < 3 * nnz:\n ind = random_state.choice(elements, size=nnz, replace=False)\n else:\n ind = np.empty(nnz, dtype=np.min_scalar_type(elements - 1))\n selected = set()\n for i in range(nnz):\n j = random_state.randint(elements)\n while j in selected:\n j = random_state.randint(elements)\n selected.add(j)\n ind[i] = j\n\n data = data_rvs(nnz)\n\n ar = COO(ind[None, :], data, shape=nnz).reshape(shape)\n\n if canonical_order:\n ar.sum_duplicates()\n\n return ar\n","sub_path":"sparse/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":56322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"561677119","text":"\"\"\"Utils for visualization of data and comparison\n\"\"\"\nimport os\nimport math\nimport numpy as np\nimport numpy.testing as npt\nimport matplotlib.pyplot as plt\nfrom matplotlib.transforms import Bbox, TransformedBbox, blended_transform_factory\nfrom mpl_toolkits.axes_grid1.inset_locator import (\n BboxPatch,\n BboxConnector,\n BboxConnectorPatch,\n)\nimport mne\n\n\ndef plot_all_mne_data(raw, output_folder=os.path.expanduser(\"~\"), title=\"test\"):\n \"\"\"Standardized function to give save all comparison\"\"\"\n\n title_raw = title + \"_raw\"\n raw.plot(title=title_raw).savefig(os.path.join(output_folder, title_raw), dpi=192)\n plt.close()\n\n title_psd = title + \"_psd\"\n\n mne.viz.plot_raw_psd(raw, show=False).savefig(\n os.path.join(output_folder, title_psd), dpi=192\n )\n plt.close()\n\n title_dist = title + \"_dist\"\n\n data = raw.get_data()\n data = np.log(((1e6 * data + 1e-15) ** 2)) # log-normal instantaneous power\n Ne = data.shape[0]\n nb_columns = 6\n nb_rows = math.ceil(Ne / nb_columns)\n fig, ax = plt.subplots(\n nb_rows,\n nb_columns,\n sharex=True,\n sharey=True,\n gridspec_kw={\"hspace\": 0, \"wspace\": 0},\n )\n if len(ax.shape) < 2:\n ax = np.expand_dims(ax, axis=0)\n\n for n in range(Ne):\n n_row = math.floor(n / nb_columns)\n n_column = n - (n_row * nb_columns)\n ax[n_row, n_column].hist(data[n, :], 40, histtype=\"stepfilled\", color=\"gray\")\n ax[n_row, n_column].set_xlim([-3, 10])\n ax[n_row, n_column].set_xlabel(r\"log(µV$^2$)\")\n plt.savefig(os.path.join(output_folder, title_dist), dpi=192)\n plt.close()\n\n\ndef plot_time_dist(time_table, output_folder=os.path.expanduser(\"~\"), title=\"test\"):\n \"\"\"Standardized function to return computational cost given a time_table\"\"\"\n time_table = time_table * 1e3 # convert in ms\n title_file = title + \"_values.csv\"\n np.savetxt(os.path.join(output_folder, title_file), time_table, delimiter=\",\")\n\n title_dist = title + \"_dist\"\n plt.figure()\n # plot histogram\n plt.hist(time_table, bins=40, color=\"c\", edgecolor=\"k\", alpha=0.65)\n\n # plot mean\n plt.axvline(time_table.mean(), color=\"k\", linestyle=\"dashed\", linewidth=1)\n min_ylim, max_ylim = plt.ylim()\n plt.text(\n time_table.mean() * 1.1,\n max_ylim * 0.9,\n \"Mean: {:.1f}\".format(time_table.mean()),\n )\n\n # plot 99% quantile\n q99 = np.quantile(time_table, 0.99)\n plt.axvline(q99, color=\"k\", linestyle=\"dashed\", linewidth=1)\n min_ylim, max_ylim = plt.ylim()\n plt.text(q99 * 1.1, max_ylim * 0.9, \"0.99q: {:.1f}\".format(q99))\n plt.title(title_dist)\n plt.xlabel(r\"time per epoch ($ms$)\")\n plt.savefig(os.path.join(output_folder, title_dist), dpi=192)\n plt.close()\n\n\ndef plotTimeSeries(\n data, ch_names=None, sfreq=1, scalings=None, ax=None, offset=0, **kwargs\n):\n \"\"\"Advanced plotting of multidimensional time series from numpy ndarray in one single matplotlib ax\n Useful for physiological timeseries such as EEG, EMG, MEG, etc.\n\n Works better for centered time series (zero-mean) and with same order of magnitude variance. You can try to\n normalize if needed (e.g. subtracting mean and dividing by the variance of each individual channels).\n\n License: The MIT Licence\n Copyright: Louis Korczowski , 2020.\n\n Parameters\n ----------\n data: array-line, shape (n_samples, n_dimension)\n multidimensional time series\n ch_names: list | iterable, shape (n_dimension,) | None (default: None)\n the labels for the time series, if None the channels are named by their numerical index.\n sfreq: float (default: 1)\n sample rate (in Hz)\n scalings: float | None (default: None)\n value between two channels, If None, try to find the best scalings automatically.\n ax: a instance of ``matplotlib.pyplot.Axes`` (default: None)\n the axe where to save the fig. By default a new figure is generated.\n offset: float (default:0)\n offset for the xlabels in seconds (or samples if `sfreq=1`)\n e.g.: `offset=-2` the axis will starts at at -2\n **kwargs:\n parameters to pass to plt.plot()\n\n Returns\n -------\n fig: a `matplotlib.figure.Figure` instance\n the linked figure instance (if `ax=None` then it is a new figure)\n ax: a instance of ``matplotlib.pyplot.Axes`` (default: None)\n the linked axe\n\n Example\n -------\n The following example will output four channels timeseries into a unique ax using subplot (automatic scalings)\n\n >>> import numpy as np\n >>> import matplotlib.pyplot as plt\n >>> data = np.random.randn(200, 4)\n >>> ax = plt.subplot(212)\n >>> plotTimeSeries(data, ax=ax)\n >>> plt.show()\n\n The following example superpose two two channels timeseries for comparison.\n Note that automatic scalings is robust to artifacts because of the use of median.\n >>> data = np.random.randn(400, 2)\n >>> ax = plt.subplot(212)\n >>> plotTimeSeries(data, ax=ax, color=\"black\")\n >>> data[10, 1] += 100; data[150, 0] += 25; data[170, 1] += -1e9; # add artifacts\n >>> plotTimeSeries(data, ax=ax, ch_names=[\"Fz\", \"Cz\"], color=\"red\", zorder=0)\n >>> plt.legend([\"clean\", \"_nolegend_\", \"with artefacts\", \"_nolegend_\"]) # legend require to hide\n >>> plt.show()\n \"\"\"\n\n shapeD = data.shape\n if len(shapeD) == 1:\n n_channels = 1\n n_samples = shapeD[0]\n data = np.expand_dims(data, axis=1)\n elif len(shapeD) == 2:\n n_channels = shapeD[1]\n n_samples = shapeD[0]\n elif len(shapeD) > 2:\n raise ValueError(\"data should be two-dimensional\")\n\n ch_names = is_valid_ch_names(ch_names, n_channels)\n\n if ax is None:\n ax = plt.gca()\n fig = ax.figure\n elif isinstance(ax, plt.Axes):\n fig = ax.figure\n else:\n msg = \"`ax` must be a matplotlib Axes instance or None\"\n raise ValueError(msg)\n\n # remove median\n data = data - np.median(data, axis=0)\n\n if scalings is None:\n # distance between two lines: maximum of the 95% percentile of each channel\n scalings = np.max(np.quantile(np.abs(data), 0.975, axis=0))\n\n # calculate multidimensional shifts based on scalings\n shifts = np.linspace(0, 2 * scalings * (n_channels - 1), n_channels)\n\n # align timeseries with new offsets\n data = data - shifts\n times = np.linspace(offset, offset + (n_samples - 1) / sfreq, num=n_samples)\n\n # compute shift based on scalings\n ax.plot(times, data, **kwargs)\n plt.yticks(-shifts, ch_names)\n plt.xlim(np.min(times), np.max(times))\n plt.ylim(np.min(-shifts) - (1.5 * scalings), 1.5 * scalings)\n return fig, ax\n\n\ndef assert_y_labels_correct(data, expected_labels):\n \"\"\"Return assert error if the ax is not coming from data\n\n Parameters\n ----------\n data: array-line, shape (n_samples, n_dimension)\n multidimensional time series\n expected_labels: a list of str\n the expected label names\n \"\"\"\n # prepare data to double check\n data = data - np.median(data, axis=0)\n scalings = np.max(np.quantile(np.abs(data), 0.975, axis=0))\n\n # calculate multidimensional shifts based on scalings\n shifts = -np.linspace(0, 2 * scalings * (data.shape[1] - 1), data.shape[1])\n\n # check if label position and values are correct\n locs, labels = plt.yticks()\n npt.assert_equal(locs, shifts)\n for k, label in enumerate(labels):\n assert label.get_text() == expected_labels[k], \"labels are not the same\"\n\n\ndef plotAnnotations(annotations, ax=None, text_prop={}, **kwargs):\n \"\"\"Add a box for each annotation\n\n Parameters\n ----------\n annotations: a instance mne.Annotations | list of dictionary | dict\n a list of annotation or dictionary containing the following fields:\n {'onset': float (seconds), 'duration': float (seconds), 'description': str, orig_time': float (seconds)}\n Example:\n >>> # a list of two annotations starting after 0.5 and 1 second of duration 1.0 second named 'blink'\n >>> annotations = [{'onset': 0.5, 'duration': 1.0, 'description': \"blink\", 'orig_time': 0.0},\n >>> {'onset': 1., 'duration': 1.0, 'description': \"blink\", 'orig_time': 0.0}]\n or\n >>> # a list of two annotations starting after 0.5 and 1 second of duration 1.0 second named 'blink'\n >>> annotations = {'onset': [0.5, 1.0], 'duration': [1.0, 1.0],\n >>> 'description': [\"blink\", \"blink\"], 'orig_time': [0., 0.]}\n ax: a instance of ``matplotlib.pyplot.Axes`` (default: None)\n the axe where to save the fig. By default a new figure is generated.\n text_prop: dict\n parameters send to ``matplotlib.text.Text`` instance\n **kwargs\n Arguments passed to the patch constructor `mpl_toolkits.axes_grid1.inset_locator.BboxPatch`` (e.g. fc, ec).\n\n \"\"\"\n if isinstance(annotations, (np.ndarray, list)):\n for annotation in annotations:\n if not isinstance(annotation, dict):\n raise ValueError(\"annotations should contains dict\")\n else:\n for key in annotation.keys():\n if key not in [\"onset\", \"duration\", \"description\", \"orig_time\"]:\n raise ValueError(f\"{key} is an invalid key as annotation\")\n elif isinstance(annotations, mne.Annotations):\n pass\n else:\n raise ValueError(\"annotations should be a list or ndarray of dict\")\n\n if ax is None:\n ax = plt.gca()\n fig = ax.figure\n elif isinstance(ax, plt.Axes):\n fig = ax.figure\n else:\n msg = \"`ax` must be a matplotlib Axes instance or None\"\n raise ValueError(msg)\n\n if text_prop == {}:\n text_prop = {\"color\": \"red\"}\n if kwargs == {}:\n kwargs = {**text_prop, \"ec\": \"none\", \"alpha\": 0.2}\n\n for annotation in annotations:\n if annotation[\"orig_time\"] is None:\n annotation[\"orig_time\"] = 0.0\n xmin = annotation[\"orig_time\"] + annotation[\"onset\"]\n xmax = annotation[\"orig_time\"] + xmin + annotation[\"duration\"]\n trans = blended_transform_factory(ax.transData, ax.transAxes)\n\n bbox = Bbox.from_extents(xmin, 0, xmax, 1)\n mybbox = TransformedBbox(bbox, trans)\n\n bbox_patch = BboxPatch(mybbox, **kwargs)\n ax.add_patch(bbox_patch)\n ax.text(\n np.mean([xmin, xmax]),\n 1.05,\n annotation[\"description\"],\n transform=trans,\n horizontalalignment=\"center\",\n **text_prop,\n )\n\n\ndef connect_bbox(bbox1, bbox2, loc1a, loc2a, loc1b, loc2b, prop_lines, **prop_patches):\n \"\"\"Create patch and lines to connect two bbox instances' opposite corner together\n\n Parameters\n ----------\n bbox1, bbox2 : `matplotlib.transforms.Bbox`\n Bounding boxes to connect.\n\n loc1a, loc2a : {1, 2, 3, 4}\n Corners of *bbox1* and *bbox2* to draw the first line.\n Valid values are::\n\n 'upper right' : 1,\n 'upper left' : 2,\n 'lower left' : 3,\n 'lower right' : 4\n\n loc1b, loc2b : {1, 2, 3, 4}\n Corners of *bbox1* and *bbox2* to draw the second line.\n Valid values are::\n\n 'upper right' : 1,\n 'upper left' : 2,\n 'lower left' : 3,\n 'lower right' : 4\n\n propo_lines:\n Patch properties for the line drawn:\n %(Patch)s\n\n Returns\n -------\n c1 : a instance of mpl_toolkits.axes_grid1.inset_locator.BboxConnector\n c2 : a instance of mpl_toolkits.axes_grid1.inset_locator.BboxConnector\n bbox_patch1 : a instance of mpl_toolkits.axes_grid1.inset_locator.BboxPatch\n bbox_patch2 : a instance of mpl_toolkits.axes_grid1.inset_locator.BboxPatch\n p : a instance of mpl_toolkits.axes_grid1.inset_locator.BboxConnectorPatch\n\n Reference\n ---------\n https://matplotlib.org/3.1.1/gallery/subplots_axes_and_figures/axes_zoom_effect.html\n \"\"\"\n if prop_patches == {}:\n prop_patches = {\n **prop_lines,\n \"alpha\": prop_lines.get(\"alpha\", 1) * 0.2,\n }\n\n # build two lines\n c1 = BboxConnector(bbox1, bbox2, loc1=loc1a, loc2=loc2a, **prop_lines)\n c1.set_clip_on(False)\n c2 = BboxConnector(bbox1, bbox2, loc1=loc1b, loc2=loc2b, **prop_lines)\n c2.set_clip_on(False)\n\n #\n bbox_patch1 = BboxPatch(bbox1, **prop_patches)\n bbox_patch2 = BboxPatch(bbox2, **prop_patches)\n\n p = BboxConnectorPatch(\n bbox1, bbox2, loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b, **prop_lines\n )\n p.set_clip_on(False)\n\n return c1, c2, bbox_patch1, bbox_patch2, p\n\n\ndef zoom_effect(ax1, ax2, xmin=None, xmax=None, prop_lines={}, **kwargs):\n \"\"\"\n Connect *ax1* and *ax2*. The *xmin*-to-*xmax* range in both axes will be marked.\n\n Parameters\n ----------\n ax1\n The zoomed axes.\n ax2\n The main axes.\n xmin, xmax\n The limits of the colored area in both plot axes. If None, xmin & xmax will be taken from the ax1.viewLim.\n prop_lines: dict (default: {})\n Arguments passed to the line constructor ``mpl_toolkits.axes_grid1.inset_locator.BboxConnector``\n **kwargs\n Arguments passed to the patch constructor `mpl_toolkits.axes_grid1.inset_locator.BboxPatch`` (e.g. fc, ec).\n\n References\n ----------\n https://matplotlib.org/3.1.1/gallery/subplots_axes_and_figures/axes`_zoom_effect.html\n \"\"\"\n\n # with auto-xlim based on the x2 xlim\n if (xmin is None) and (xmax is None):\n tt = ax1.transScale + (ax1.transLimits + ax2.transAxes)\n trans = blended_transform_factory(ax2.transData, tt)\n mybbox1 = ax1.bbox\n mybbox2 = TransformedBbox(ax1.viewLim, trans)\n\n # with specific xlim\n elif isinstance(xmin, float) and isinstance(xmax, float):\n trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)\n trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)\n bbox = Bbox.from_extents(xmin, 0, xmax, 1)\n mybbox1 = TransformedBbox(bbox, trans1)\n mybbox2 = TransformedBbox(bbox, trans2)\n else:\n raise ValueError(\"xmin & xman should be None or float\")\n\n c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox(\n mybbox1,\n mybbox2,\n loc1a=3,\n loc2a=2,\n loc1b=4,\n loc2b=1,\n prop_lines=prop_lines,\n **kwargs,\n )\n ax1.add_patch(bbox_patch1)\n ax2.add_patch(bbox_patch2)\n ax2.add_patch(c1)\n ax2.add_patch(c2)\n p.set_clip_on(False)\n ax2.add_patch(p)\n\n return c1, c2, bbox_patch1, bbox_patch2, p\n\n\ndef is_valid_ch_names(ch_names, n_channels):\n \"\"\"Check if ch_names is correct or generate a numerical ch_names list\"\"\"\n if (ch_names is None) or (ch_names == []):\n ch_names = np.arange(0, n_channels)\n elif isinstance(ch_names, str):\n ch_names = [ch_names] * n_channels\n elif isinstance(ch_names, (np.ndarray, list)):\n if not len(ch_names) == n_channels:\n raise ValueError(\n \"`ch_names` should be same length as the number of channels of data\"\n )\n else:\n msg = \"`ch_names` must be a list or an iterable of shape (n_channels,) or None\"\n raise ValueError(msg)\n return ch_names\n\n\ndef assert_ax_equals_data(data, ax, sfreq=1, offset=0):\n \"\"\"Return assert error if the ax in figure does not correspond exactly to the data.\n\n Parameters\n ----------\n data: array-line, shape (n_samples, n_dimension)\n multidimensional time series\n ax: a instance of ``matplotlib.pyplot.Axes``\n the ax where the data were plotted\n sfreq: float (default: 1)\n sample rate (in Hz)\n\n Examples\n --------\n >>> data = np.random.randn(20, 4)\n >>> ax1 = plt.subplot(211)\n >>> ax1.plot(data)\n >>> assert_ax_equals_data(data, ax1) # values shown in ax1 of figure corresponds to data\n >>> ax2 = plt.subplot(212)\n >>> ax1.plot(data + 1e-4)\n >>> assert_ax_equals_data(data, ax2) # values shown in ax2 of figure does not correspond to data\n \"\"\"\n # check if correct values\n for n, line in enumerate(ax.get_lines()):\n x, y = line.get_data()\n # check if data correlated perfectly (there aren't equal due to transformation)\n npt.assert_approx_equal(\n np.corrcoef(y, data[:, n])[0][1], 1\n ) # data y-axis correlate to 1\n npt.assert_equal(\n x,\n np.linspace(\n offset + 0, offset + (data.shape[0] - 1) / sfreq, data.shape[0]\n ),\n ) # time x-axis match\n","sub_path":"timeflux_rasr/helpers/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":16612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"602360812","text":"### Copyright 2014, MTA SZTAKI, www.sztaki.hu\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\"\"\" OpenStack Nova implementation of the\n:class:`~occo.cloudhandler.cloudhandler.CloudHandler` class.\n\n.. moduleauthor:: Zoltan Farkas \n\"\"\"\n\nimport time\nimport uuid\nimport novaclient\nimport novaclient.client\nimport novaclient.auth_plugin\nimport urlparse\nimport occo.util.factory as factory\nfrom occo.util import wet_method, coalesce\nfrom occo.cloudhandler import CloudHandler, Command\nimport itertools as it\nimport logging\nimport occo.constants.status as status\n\n__all__ = ['NovaCloudHandler']\n\nPROTOCOL_ID = 'nova'\nSTATE_MAPPING = {\n 'BUILD' : status.PENDING,\n 'REBUILD' : status.PENDING,\n 'RESIZE' : status.PENDING,\n 'VERIFY_RESIZE' : status.PENDING,\n 'MIGRATING' : status.PENDING,\n 'ACTIVE' : status.READY,\n 'ERROR' : status.FAIL,\n 'DELETED' : status.SHUTDOWN,\n}\n\nlog = logging.getLogger('occo.cloudhandler.nova')\n\ndef setup_connection(target, auth_data, auth_type):\n \"\"\"\n Setup the connection to the Nova endpoint.\n \"\"\"\n auth_url = target['auth_url']\n tenant_name = target['tenant_name']\n if auth_type is None:\n user = auth_data['username']\n password = auth_data['password']\n nt = client.Client('2.0', user, password, tenant_name, auth_url)\n elif auth_type == 'voms':\n novaclient.auth_plugin.discover_auth_systems()\n auth_plugin = novaclient.auth_plugin.load_plugin(auth_type)\n auth_plugin.opts[\"x509_user_proxy\"] = auth_data\n nt = novaclient.client.Client('2.0', None, None, tenant_name, auth_url, auth_plugin=auth_plugin, auth_system=auth_type)\n return nt\n\ndef needs_connection(f):\n \"\"\"\n Sets up the conn member of the Command object upon calling this method.\n\n If this decorator is specified *inside* (after) ``@wet_method``, the\n connection will not be established upon dry run.\n \"\"\"\n import functools\n @functools.wraps(f)\n def g(self, cloud_handler, *args, **kwargs):\n self.conn = cloud_handler.get_connection()\n return f(self, cloud_handler, *args, **kwargs)\n\n return g\n\nclass CreateNode(Command):\n def __init__(self, resolved_node_definition):\n Command.__init__(self)\n self.resolved_node_definition = resolved_node_definition\n\n @wet_method(1)\n @needs_connection\n def _start_instance(self, cloud_handler, node_def):\n \"\"\"\n Start the VM instance.\n\n :param dict node_def: The resolved node definition to use.\n\n :Remark: This is a \"wet method\", the VM will not be started\n if the instance is in debug mode (``dry_run``).\n \"\"\"\n image_id = node_def['image_id']\n flavor_name = node_def['flavor_name']\n context = node_def['context']\n sec_groups = node_def.get('security_groups', None)\n key_name = node_def.get('key_name', None)\n server_name = str(uuid.uuid4())\n log.debug(\"[%s] Creating new server using image ID %r and flavor name %r\",\n cloud_handler.name, image_id, flavor_name)\n server = self.conn.servers.create(server_name, image_id, flavor_name,\n security_groups=sec_groups, key_name=key_name, userdata=context)\n log.debug('Reservation: %r, server ID: %r', server, server.id)\n return server\n\n def perform(self, cloud_handler):\n log.debug(\"[%s] Creating node: %r\",\n cloud_handler.name, self.resolved_node_definition['name'])\n\n server = self._start_instance(cloud_handler, self.resolved_node_definition)\n log.debug(\"[%s] Done; vm_id = %r\", cloud_handler.name, server.id)\n\n if 'floating_ip' in self.resolved_node_definition:\n floating_ip = self.conn.floating_ips.create()\n log.debug(\"[%s] Created floating IP: %r\", cloud_handler.name, floating_ip)\n attempts = 0\n while attempts < 10:\n try:\n log.debug(\"[%s] Adding floating IP to server...\", cloud_handler.name)\n server.add_floating_ip(floating_ip)\n except Exception as e:\n log.debug(e)\n time.sleep(1)\n attempts += 1\n else:\n log.debug(\"[%s] Added floating IP to server\", cloud_handler.name)\n break\n if attempts == 5:\n log.error(\"[%s] Failed to add floating IP to server\", cloud_handler.name)\n self.conn.floating_ips.delete(floating_ip)\n raise Exception('Failed to add floating IP')\n return server.id\n\nclass DropNode(Command):\n def __init__(self, instance_data):\n Command.__init__(self)\n self.instance_data = instance_data \n\n @wet_method()\n @needs_connection\n def _delete_vms(self, cloud_handler, *vm_ids):\n \"\"\"\n Terminate VM instances.\n\n :param vm_ids: The list of VM instance identifiers.\n :type vm_ids: str\n\n :Remark: This is a \"wet method\", termination will not be attempted\n if the instance is in debug mode (``dry_run``).\n \"\"\"\n server = self.conn.servers.get(vm_ids)\n floating_ips = self.conn.floating_ips.list()\n for floating_ip in floating_ips:\n if floating_ip.instance_id == server.id:\n log.debug(\"[%s] Removing floating IP %r allocated for the VM\",\n cloud_handler.name, floating_ip.ip)\n self.conn.floating_ips.delete(floating_ip)\n self.conn.servers.delete(server)\n\n def perform(self, cloud_handler):\n \"\"\"\n Terminate a VM instance.\n\n :param instance_data: Information necessary to access the VM instance.\n :type instance_data: :ref:`Instance Data `\n \"\"\"\n instance_id = self.instance_data['instance_id']\n log.debug(\"[%s] Dropping node %r\", cloud_handler.name,\n self.instance_data['node_id'])\n\n self._delete_vms(cloud_handler, instance_id)\n\n log.debug(\"[%s] Done\", cloud_handler.name)\n\nclass GetState(Command):\n def __init__(self, instance_data):\n Command.__init__(self)\n self.instance_data = instance_data\n\n @wet_method('ready')\n @needs_connection\n def perform(self, cloud_handler):\n log.debug(\"[%s] Acquiring node state %r\",\n cloud_handler.name, self.instance_data['node_id'])\n server = self.conn.servers.get(self.instance_data['instance_id'])\n inst_state = server.status\n try:\n retval = STATE_MAPPING[inst_state]\n except KeyError:\n raise NotImplementedError('Unknown Nova state', inst_state)\n else:\n log.debug(\"[%s] Done; nova_state=%r; status=%r\",\n cloud_handler.name, inst_state, retval)\n return retval\n\nclass GetIpAddress(Command):\n def __init__(self, instance_data):\n Command.__init__(self)\n self.instance_data = instance_data\n\n @wet_method('127.0.0.1')\n @needs_connection\n def perform(self, cloud_handler):\n log.debug(\"[%s] Acquiring IP address for %r\",\n cloud_handler.name,\n self.instance_data['node_id'])\n server = self.conn.servers.get(self.instance_data['instance_id'])\n floating_ips = self.conn.floating_ips.list()\n for floating_ip in floating_ips:\n if floating_ip.instance_id == server.id:\n return floating_ip.ip\n networks = self.conn.servers.ips(server)\n for tenant in networks.keys():\n for addre in networks[tenant]:\n return addre['addr'].encode('latin-1')\n return None\n\n@factory.register(CloudHandler, PROTOCOL_ID)\nclass NovaCloudHandler(CloudHandler):\n \"\"\" Implementation of the\n :class:`~occo.cloudhandler.cloudhandler.CloudHandler` class utilizing the\n OpenStack Nova interface.\n\n :param dict target: Definition of the EC2 endpoint. This must contain:\n\n * ``endpoint``: URL of the interface.\n * ``regionname``: The name of the EC2 region.\n\n :param str auth_type: The type of authentication plugin to use.\n :param dict auth_data: Authentication infomration for the connection.\n\n * ``username``: The access key.\n * ``password``: The secret key.\n\n :param str name: The name of this ``CloudHandler`` instance. If unset,\n ``target['endpoint']`` is used.\n :param bool dry_run: Skip actual resource aquisition, polling, etc.\n\n \"\"\"\n def __init__(self, target, auth_type, auth_data,\n name=None, dry_run=False,\n **config):\n self.dry_run = dry_run\n self.name = name if name else target['auth_url']\n self.target, self.auth_data, self.auth_type = target, auth_data, auth_type\n # The following is intentional. It is a constant yet, but maybe it'll\n # change in the future.\n self.resource_type = 'vm'\n\n def get_connection(self):\n return setup_connection(self.target, self.auth_data, self.auth_type)\n\n def cri_create_node(self, resolved_node_definition):\n return CreateNode(resolved_node_definition)\n\n def cri_drop_node(self, instance_data):\n return DropNode(instance_data)\n\n def cri_get_state(self, instance_data):\n return GetState(instance_data)\n\n def cri_get_address(self, instance_data):\n return GetIpAddress(instance_data)\n\n def cri_get_ip_address(self, instance_data):\n return GetIpAddress(instance_data)\n\n def perform(self, instruction):\n instruction.perform(self)\n","sub_path":"occo/plugins/cloudhandler/nova.py","file_name":"nova.py","file_ext":"py","file_size_in_byte":10149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"597327878","text":"import os\nimport csv\n\nnum_months = 0\n\nsum_Delta = float(0)\n\ntotal_PL = []\ndelta_PL = []\nmonths = []\n\nbudget_csv = os.path.join(\"Resources\", \"budget_data.csv\")\n\nwith open(budget_csv) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=\",\")\n\n csv_header = next(csv_file)\n previous_row = next(csv_file).split(\",\")\n num_months += 1\n total_PL.append(int(previous_row[1]))\n\n for row in csv_reader:\n num_months += 1\n months.append(row[0])\n total_PL.append(int(row[1]))\n delta_PL.append(int(row[1]) - int(previous_row[1]))\n sum_Delta = sum_Delta + (int(row[1]) - int(previous_row[1]))\n previous_row = row\n\nziplist = list(zip(months, delta_PL))\n\n\ndef max_pl(sequence):\n if not sequence:\n raise ValueError('empty sequence')\n\n maximum = sequence[0]\n\n for item in sequence:\n if item[1] > maximum[1]:\n maximum = item\n\n return maximum\n\n\ndef min_pl(sequence):\n if not sequence:\n raise ValueError('empty sequence')\n\n minimum = sequence[0]\n\n for item in sequence:\n if item[1] < minimum[1]:\n minimum = item\n\n return minimum\n\n\nincr = max_pl(ziplist)\ndecr = min_pl(ziplist)\n\nprint(\"Financial Analysis\")\nprint(\"____________________________________\")\n\nprint(\"Total Months: \" + str(num_months))\n\nprint(\"Total: \" + str(sum(total_PL)))\n\naverage = sum_Delta / (num_months - 1)\nprint(\"Average Change: \" + str(round(average, 2)))\n\nprint(\"Greatest Increase in Profits: \" + str(incr[0]) + \" ($\" + str(incr[1]) + \")\")\nprint(\"Greatest Decrease in Profits: \" + str(decr[0]) + \" ($\" + str(decr[1]) + \")\")\n\n\noutput_file = os.path.join(\"Analysis\", \"analysis.txt\")\nwith open(output_file, \"w\") as txt_file:\n\n txt_file.write(\"Financial Analysis\")\n\n txt_file.write(\"____________________________________\")\n\n txt_file.write(\"Total Months: \" + str(num_months))\n\n txt_file.write(\"Total: \" + str(sum(total_PL)))\n\n txt_file.write(\"Average Change: \" + str(round(average, 2)))\n\n txt_file.write(\"Greatest Increase in Profits: \" + str(incr[0]) + \" ($\" + str(incr[1]) + \")\")\n\n txt_file.write(\"Greatest Decrease in Profits: \" + str(decr[0]) + \" ($\" + str(decr[1]) + \")\")\n","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"562016115","text":"import TMB.adapters.repository as repo\nimport TMB.utilities.services as services\nfrom flask import Blueprint, url_for\n\n# Configure Blueprint.\nutilities_blueprint = Blueprint(\n 'utilities_bp', __name__)\n\n\ndef get_genres_and_urls():\n genre_names = services.get_genre_names(repo.repo_instance)\n genre_names.sort()\n genre_urls = dict()\n for genre_name in genre_names:\n genre_urls[genre_name] = url_for('news_bp.movies_by_genre', genre=genre_name)\n\n return genre_urls\n\n\ndef get_directors_and_urls():\n director_names = services.get_director_names(repo.repo_instance)\n director_names.sort()\n director_urls = dict()\n for director_name in director_names:\n director_urls[director_name] = url_for('news_bp.movies_by_director', director=director_name)\n\n return director_urls\n\n\ndef get_actors_and_urls():\n actor_names = services.get_actor_names(repo.repo_instance)\n actor_names.sort()\n actor_urls = dict()\n for actor_name in actor_names:\n actor_urls[actor_name] = url_for('news_bp.movies_by_actor', actor=actor_name)\n\n return actor_urls\n\n\ndef get_titles_and_urls():\n titles = services.get_titles(repo.repo_instance)\n title_urls = dict()\n for title in titles:\n title_urls[title] = url_for('news_bp.movies_by_title', title=title)\n\n return title_urls\n\n\ndef get_dates_and_urls():\n dates = services.get_dates(repo.repo_instance)\n date_urls = dict()\n for date in dates:\n date_urls[date] = url_for('news_bp.movies_by_date', date=date)\n\n return date_urls\n\n\ndef get_selected_movies(quantity=5):\n movies = services.get_random_movies(quantity, repo.repo_instance)\n\n for movie in movies:\n movie['hyperlink'] = url_for('news_bp.movies_by_date', date=movie['date'])\n return movies\n","sub_path":"TMB/utilities/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"384406672","text":"import os\nimport csv\nimport re\n\ncsv_path = r'D:\\Clouds\\YandexDisk\\Fests\\AtomCosCon2018\\zad.csv'\nnum_row = 'num'\ntarget_csv_path = r'D:\\Clouds\\YandexDisk\\Fests\\AtomCosCon2018\\zad_img.csv'\n\nimg_dir = r'D:\\Clouds\\YandexDisk\\Fests\\AtomCosCon2018\\img'\nid_regex = re.compile(r'^(\\d{3})\\.')\n\nempty_img_path = 'null.png' # http://www.1x1px.me/\n\n\nwith open(csv_path, 'r', encoding='utf-8') as f:\n reader = csv.reader(f)\n head = reader.__next__()\n data = {int(row[head.index(num_row)]): row for row in reader}\n\nrows_source = len(head)\nrows_target = 0\n\nfor file_name in os.listdir(img_dir):\n if os.path.isdir(file_name):\n continue\n\n res = re.search(id_regex, file_name)\n\n if res is None:\n print(\"[WARNING] Unknown file: '%s'\" % file_name)\n continue\n\n num, name = int(res.group(1)), file_name\n\n if num not in data:\n print(\"[WARNING] No row for: '%s'\" % file_name)\n continue\n\n data[num].append(os.path.join(img_dir, file_name))\n if len(data[num]) > rows_target:\n rows_target = len(data[num])\n\nrows_added = rows_target - rows_source\ndata = data.values()\n\nfor row in data:\n no_img = len(row) == rows_source\n if len(row) < rows_target:\n row += [os.path.abspath(empty_img_path)] * (rows_target - len(row))\n if no_img:\n print(\"[WARNING] No images for: '%s'\" % str(row))\n row += [\"false\"]\n else:\n row += [\"true\"]\n\n# from tabulate import tabulate\n# print(tabulate(data))\n\nwith open(target_csv_path, 'w', encoding='utf-8', newline='') as f:\n w = csv.writer(f, delimiter=',', quotechar='\"')\n w.writerow(head + [\"img%d_path\" % (i+1) for i in range(rows_added)] + [\"fade_on\"])\n w.writerows(data)\n","sub_path":"etc/gen-image-list.py","file_name":"gen-image-list.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"64111571","text":"\n\nclass TreeNode:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\n\n\"\"\"\n先序中序重建\n\"\"\"\ndef rebuildTree1(preOrder, inOrder):\n if (not preOrder) or (not inOrder):\n return None\n root = TreeNode(preOrder[0])\n index = inOrder.index(preOrder[0])\n root.left = rebuildTree1(preOrder[1:index + 1], inOrder[:index])\n root.right = rebuildTree1(preOrder[index + 1:], inOrder[index + 1:])\n return root\n\n\n\n\"\"\"\n后序中序重建\n\"\"\"\ndef rebuildTree2(inOrder, postOrder):\n if (not inOrder) or (not postOrder):\n return None\n root = TreeNode(postOrder[-1])\n index = inOrder.index(postOrder[-1])\n root.left = rebuildTree2(inOrder[:index], postOrder[:index])\n root.right = rebuildTree2(inOrder[index + 1:], postOrder[index:-1])\n return root","sub_path":"algorithm/binary_tree/rebuild_tree.py","file_name":"rebuild_tree.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"346328878","text":"from experiments.utils.gspread_access import get_api\n\ndef load_gspread(worksheet_name, num_set, num_qc, shift=4, key=None): \n gc = get_api()\n \n workbook = gc.open_by_key('1Tigim9_mWoMzgZidchelOQ52J589LjuXPIBgBfKOymE')\n if key: \n workbook = gc.open_by_key(key)\n\n worksheet = workbook.worksheet(worksheet_name) \n \n # cell_dict = worksheet.get_all_records(empty2zero=False, head=1, default_blank='')\n bench_list = []\n for i in range(num_set): \n row_list = worksheet.row_values(i+2)\n name_list = []\n for j in range(num_qc):\n name_list.append(row_list[j] + '_n' + row_list[j+shift])\n bench_list.append(name_list)\n return bench_list","sub_path":"scheduling/load_gspread.py","file_name":"load_gspread.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"318406435","text":"import requests\n\nfrom hubs.widgets.base import argument\n\nimport jinja2\n\n\nimport hubs.validators as validators\n\n\ntemplate = jinja2.Template(\"\"\"\n
\n{% for badge in assertions %}\n \n{%endfor%}\n
\n\"\"\")\n\nfrom hubs.widgets.chrome import panel\nchrome = panel(\"Badges\")\n\n\n@argument(name=\"username\",\n default=None,\n validator=validators.username,\n help=\"A FAS username.\")\ndef data(session, widget, username):\n url = \"https://badges.fedoraproject.org/user/{username}/json\"\n url = url.format(username=username)\n response = requests.get(url)\n return response.json()\n\n\ndef should_invalidate(message, session, widget):\n raise NotImplementedError\n","sub_path":"hubs/widgets/badges.py","file_name":"badges.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"540837650","text":"import time\n\nimport redis\nfrom flask import Flask, abort\n\napp = Flask(__name__)\ncache = redis.Redis(host='redis', port=6379)\n\n\ndef get_hit_count():\n retries = 5\n while True:\n try:\n return cache.incr('hits')\n except redis.exceptions.ConnectionError as exc:\n if retries == 0:\n raise exc\n retries -= 1\n time.sleep(0.5)\n\n\n@app.route('/')\ndef index():\n count = get_hit_count()\n return 'Hello World! I have been seen {} times.\\n'.format(count)\n\n\n@app.route('/error')\ndef error():\n abort(504)\n\n\n@app.route('/healthcheck')\ndef healthcheck():\n count = get_hit_count()\n return 'ok'\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"205749059","text":"import csv\nimport pandas as pd\nimport plotly.graph_objects as go\nimport plotly.express as px\nimport plotly.io as pio\n\nnames = []\nactual_name_count = 0\nwith open('names_collection.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n names.append(row[0])\n\n\nwith open('series_standings_NASCAR_iRacing_Series_-_Open_2019_Season1.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n irating_list = []\n club_list = []\n starts_dict = {}\n poles_dict = {}\n avg_incident_dict = {}\n avg_lap_incident_dict = {}\n avg_finish_dict = {}\n wins_dict = {}\n top5_dict = {}\n champ_point_dict = {}\n laps_led_dict = {}\n win_percent_dict = {}\n top5_percent_dict = {}\n\n line_count = 0\n for row in csv_reader:\n if line_count == 0:\n print(f'Column names are {\", \".join(row)}')\n line_count += 1\n else:\n if row[1] in names:\n actual_name_count += 1\n irating_list.append(int(row[6]))\n club_list.append(row[4])\n poles_dict[row[1]] = int(row[16])\n starts_dict[row[1]] = int(row[9])\n champ_point_dict[row[1]] = int(row[2])\n avg_finish_dict[row[1]] = int(row[7])\n top5_dict[row[1]] = int(row[8])\n laps_led_dict[row[1]] = int(row[10])\n wins_dict[row[1]] = int(row[11])\n win_percent_dict[row[1]] = round(int(row[11]) / int(row[9])*100, 2)\n top5_percent_dict[row[1]] = round(int(row[8]) / int(row[9])*100, 2)\n if int(row[9]) == 0:\n avg_incident_dict[row[1]] = 0\n avg_lap_incident_dict[row[1]] = 0\n\n else:\n avg_incident_dict[row[1]] = round(int(row[12]) / int(row[9]), 2)\n avg_lap_incident_dict[row[1]] = round(int(row[12]) / int(row[15]), 2)\n\n line_count += 1\n print(f'Processed {line_count} lines.\\n')\n\n avg_incident_dict_sorted = sorted(avg_incident_dict, key=avg_incident_dict.get, reverse=False)\n avg_lap_incident_dict_sorted = sorted(avg_lap_incident_dict, key=avg_lap_incident_dict.get, reverse=False)\n avg_finish_dict_sorted = sorted(avg_finish_dict, key=avg_finish_dict.get, reverse=False)\n wins_dict_sorted = sorted(wins_dict, key=wins_dict.get, reverse=True)\n wins_percent_dict_sorted = sorted(win_percent_dict, key=win_percent_dict.get, reverse=True)\n top5_percent_dict_sorted = sorted(top5_percent_dict, key=top5_percent_dict.get, reverse=True)\n top5_dict_sorted = sorted(top5_dict, key=top5_dict.get, reverse=True)\n champ_point_dict_sorted = sorted(champ_point_dict, key=champ_point_dict.get, reverse=True)\n laps_led_dict_sorted = sorted(laps_led_dict, key=laps_led_dict.get, reverse=True)\n starts_dict_sorted = sorted(starts_dict, key=starts_dict.get, reverse=True)\n poles_dict_sorted = sorted(poles_dict, key=poles_dict.get, reverse=True)\n\n dict_list_sorted = [avg_incident_dict_sorted, avg_finish_dict_sorted, wins_dict_sorted, top5_dict_sorted,\n champ_point_dict_sorted, laps_led_dict_sorted, avg_lap_incident_dict_sorted,\n wins_percent_dict_sorted, top5_percent_dict_sorted, starts_dict_sorted, poles_dict_sorted]\n\n dict_list = [avg_incident_dict, avg_finish_dict, wins_dict, top5_dict,\n champ_point_dict, laps_led_dict, avg_lap_incident_dict, win_percent_dict,\n top5_percent_dict, starts_dict, poles_dict]\n\n dict_list_desc = [\"Avg Inc/Race\", \"Avg Finish\", \"Top 5 Wins\", \"Top 5 Finishes\",\n \"Championship Points\", \"Laps Led\", \"Avg Inc/Lap\", \"Win Percentage\", \"Top 5 Percentage\",\n \"Starts\", \"Poles\"]\n\n dict_list_desc_unit = [\"Incidents/Race\", \"Average Finish\", \"Wins\", \"Top 5 Finishes\", \"Points\", \"Laps\",\n \"Incidents/Lap\", \"Win Percentage\", \"Top 5 Percentage\", \"Starts\", \"Poles\"]\n\n for i in range(0, dict_list.__len__()):\n data = []\n label = []\n print(dict_list_desc[i], \"\\n\")\n for j in range(0, actual_name_count):\n data.append(dict_list[i][dict_list_sorted[i][j]])\n label.append(dict_list_sorted[i][j])\n print(dict_list_sorted[i][j], dict_list[i][dict_list_sorted[i][j]], dict_list_desc_unit[i])\n print(\"\\n\")\n df = pd.DataFrame(list(zip(label, data)), columns=['Driver', dict_list_desc_unit[i]])\n test_fig = px.bar(df, x=\"Driver\", y=dict_list_desc_unit[i], color=dict_list_desc_unit[i], color_continuous_scale=\"Jet\")\n test_fig.update_layout(title_text=\"BFM 2019 NiS Open - \"+dict_list_desc[i])\n test_fig.show()\n # fig = go.Figure(\n # go.Bar(y=data, x=label, textposition=\"inside\"),\n # layout_title_text = dict_list_desc[i]\n # )\n # fig.show()","sub_path":"csvtest.py","file_name":"csvtest.py","file_ext":"py","file_size_in_byte":4920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"82066620","text":"\nfrom prac_08.taxi import Taxi\n\n\ndef main():\n\n # Create New Taxi\n taxi_1 = Taxi(\"Prius 1\", 100)\n\n # Drive the taxi 40km\n taxi_1.drive(40)\n\n # Print details and the current fare\n print(taxi_1)\n print(\"Price for ride: $\", taxi_1.get_fare())\n\n # Start new fare and drive 100km\n taxi_1.start_fare()\n taxi_1.drive(100)\n\n # Print the details and current fare\n print(taxi_1)\n print(\"Price for ride: $\", taxi_1.get_fare())\n\n\nmain()\n","sub_path":"prac_08/taxi_test.py","file_name":"taxi_test.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"195136835","text":"#!/usr/bin/env python3.6\n\nimport argparse\nimport json\nfrom pprint import pprint\nimport html\nimport datetime\nimport re\nimport sys\nimport unicodedata\nfrom fuzzywuzzy import fuzz\n\n#duration_regex = re.compile(r'([^.]*)(\\.\\d+)')\n\n\ndef parse_duration(duration):\n parts = duration.split(':')\n parts.reverse()\n seconds_parts = parts[0].split('.', 1)\n return datetime.timedelta(microseconds=int(seconds_parts[1], base=10) if len(seconds_parts) > 1 else 0,\n seconds=int(seconds_parts[0], base=10) if len(seconds_parts) > 0 else 0,\n minutes=int(parts[1], base=10) if len(parts) > 1 else 0,\n hours=int(parts[2], base=10) if len(parts) > 2 else 0)\n\n #match = duration_regex.fullmatch(duration)\n #if match is not None:\n # return match.group(1)\n #else:\n # return duration\n\n\ndef do_durations_match(duration1, duration2):\n return abs((parse_duration(duration1) - parse_duration(duration2)).total_seconds()) < 1.5\n\n\ndef escape(instr):\n return html.escape(instr).encode(\"ascii\", \"xmlcharrefreplace\").decode(\"ascii\")\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('type', metavar='MEDIA_TYPE', choices=['section', 'movie', 'show'],\n help='One of section, movie, or show')\nparser.add_argument('FILES', nargs=\"+\")\nargs = parser.parse_args()\n\nprint('')\nprint('''\n\n''')\n\nprint('')\n\nfile_data = []\ndup_guids = set()\nfor file_name in args.FILES:\n with open(file_name, 'rb') as fp:\n data = json.loads(fp.read())\n by_guid = {}\n others = []\n for item in data:\n if \"guid\" in item and item[\"guid\"]:\n guid = item[\"guid\"]\n if guid in by_guid:\n if by_guid[guid] is not None:\n others.append(by_guid[guid])\n by_guid[guid] = None\n others.append(item)\n dup_guids.add(guid)\n else:\n by_guid[guid] = item\n else:\n others.append(item)\n file_data.append((dict([(k,v) for k,v in by_guid.items() if v is not None]), others, file_name))\n\nfor d in file_data:\n for guid in dup_guids:\n if guid in d[0]:\n d[1].append(d[0][guid])\n del d[0][guid]\n\nguids = [x[0].keys() for x in file_data]\nallguids = set(guids[0]).union(*guids[1:])\ncommon_guids = set()\nfor g in allguids:\n if sum([1 if g in guidlist else 0 for guidlist in guids]) > 1:\n common_guids.add(g)\n# common_guids = set(guids[0]).intersection(*guids[1:])\nunmatched_guids = [set(x) - common_guids for x in guids]\nunmatched_items = []\nfor i, data in enumerate(file_data):\n unmatched_items.append([v for k, v in data[0].items() if k in unmatched_guids[i]] +\n data[1])\nprint('''\n\n\n''')\nprint('
(.+?)
')\nprint('')\nfor d in file_data:\n print(f'')\nprint('')\n\n\ndef compare(lists):\n lengths = set([len(x) for x in lists if x is not None])\n if len(lengths) != 1:\n print(\"Invalid lists to compare \" + str(lists), file=sys.stderr)\n return\n first_col = None\n for col in lists:\n if col is not None:\n first_col = col\n break\n hasdiff = False\n for idx in range(lengths.pop()):\n values = [x[idx][\"value\"] if x is not None else None for x in lists]\n if \"duration\" in first_col[idx]:\n sec_values = [parse_duration(x).total_seconds() for x in values if x is not None]\n min_value = min(sec_values)\n max_value = max(sec_values)\n cls = ''\n if max_value - min_value > 1.5:\n hasdiff = True\n cls = 'minordiff'\n if max_value - min_value > 60:\n cls ='diff'\n for x in lists:\n if x is not None:\n x[idx][\"class\"] = cls\n else:\n if len(set([unicodedata.normalize('NFC', str(x)) for x in values if x is not None])) != 1:\n for x in lists:\n if x is not None and x[idx] is not None:\n x[idx][\"class\"] = \"minordiff\"\n hasdiff = True\n if len([x for x in lists if x is not None]) != len(lists):\n hasdiff = True\n return hasdiff\n\n\ndef get_row_str(row_info, hasdiff=True):\n row_str = f''\n first_col = None\n for col in row_info:\n if col is not None:\n first_col = col\n break\n for col in row_info:\n if col is None:\n #row_str += f''\n row_str += f''\n continue\n row_str += ''\n row_str += ''\n return row_str\n\n\ntable_rows = []\nif args.type == 'movie':\n for guid in common_guids:\n guid_link = \"\"\n imdb = \"\"\n if guid.startswith(\"com.plexapp.agents.imdb://\"):\n guid_link = re.sub(r'^com.plexapp.agents.imdb://([^?]*)(\\?.*)?', r'https://www.imdb.com/title/\\1', guid)\n all_items = [x[0].get(guid) for x in file_data]\n\n row_info = [[{\"value\": item[\"title\"]},\n {\"value\": item[\"resolution\"]},\n {\"value\": item[\"duration\"], \"duration\": True},\n {\"value\": '=' + item[\"guid\"], \"link\": guid_link}] if item is not None else None for item in all_items]\n sortby = [x for x in row_info if x is not None]\n hasdiff = compare(row_info)\n row_str = get_row_str(row_info, hasdiff)\n\n table_rows.append({\"hasdiff\": hasdiff, \"sort\": sortby.pop()[0][\"value\"], \"html\": row_str})\n\n for col_idx in range(len(unmatched_items)):\n col = unmatched_items[col_idx]\n for item in col:\n # Try and find a fuzzy match in other columns\n matches = [None for x in unmatched_items]\n for m_col_idx, m_col in enumerate(unmatched_items):\n if m_col_idx == col_idx:\n continue\n remove_item_idx = None\n for item_idx, m_item in enumerate(m_col):\n if fuzz.ratio(m_item.get(\"title\"), item.get(\"title\")) > 90 and do_durations_match(m_item.get(\"duration\"), item.get(\"duration\")):\n matches[m_col_idx] = m_item\n remove_item_idx = item_idx\n break\n if remove_item_idx is not None:\n unmatched_items[m_col_idx] = [x for i, x in enumerate(m_col) if i != remove_item_idx]\n matches[col_idx] = item\n row_info = [[{\"value\": item[\"title\"]},\n {\"value\": item[\"resolution\"]},\n {\"value\": item[\"duration\"], \"duration\": True},\n {\"value\": item[\"guid\"], \"link\": re.sub(r'^com.plexapp.agents.imdb://([^?]*)(\\?.*)?', r'https://www.imdb.com/title/\\1', item[\"guid\"])}]\n if item is not None else None for item in matches]\n hasdiff = compare(row_info)\n row_str = get_row_str(row_info, hasdiff)\n table_rows.append({\"hasdiff\": hasdiff, \"sort\": item.get(\"title\"), \"html\": row_str})\nelif args.type == 'show':\n for guid in common_guids:\n guid_link = \"\"\n # if guid.startswith(\"com.plexapp.agents.thetvdb://\"):\n # https://www.thetvdb.com/?tab=episode&seriesid=341483&seasonid=747980&id=6617433&lid=7\n # guid_link = re.sub(r'^com.plexapp.agents.thetvdb://(\\d*)/(\\d*)/(\\d*)(\\?.*)?',\n # r'https://www.thetvdb.com/?tab=episode&seriesid=\\1&seasonid=\\2&id=\\3',\n # guid)\n all_items = [x[0][guid] for x in file_data]\n row_info = [[{\"value\": f'{item[\"show\"]} s{item[\"season\"]:02d}e{item[\"episode\"]:02d} - {item[\"episode_name\"]}'},\n {\"value\": item[\"resolution\"]},\n {\"value\": item[\"duration\"], \"duration\": True}] for item in all_items]\n hasdiff = compare(row_info)\n row_str = get_row_str(row_info, hasdiff)\n\n table_rows.append({\"hasdiff\": hasdiff, \"sort\": row_info[0][0][\"value\"], \"html\": row_str})\n\n for idx, col in enumerate(unmatched_items):\n for item in col:\n # Try and find a fuzzy match in other columns\n matches = [None for x in unmatched_items]\n for m_idx, m_col in enumerate(unmatched_items):\n if m_idx == idx:\n continue\n remove_item_idx = None\n for item_idx, m_item in enumerate(m_col):\n if m_item.get(\"show\") == item.get(\"show\") and \\\n do_durations_match(m_item.get(\"duration\"), item.get(\"duration\")) and \\\n m_item.get(\"episode_name\") == item.get(\"episode_name\"):\n matches[m_idx] = m_item\n remove_item_idx = item_idx\n break\n if remove_item_idx is not None:\n unmatched_items[m_idx] = [x for i, x in enumerate(m_col) if i != remove_item_idx]\n matches[idx] = item\n row_info = [[{\"value\": f'{item[\"show\"]} s{item[\"season\"]:02d}e{item[\"episode\"]:02d} - {item[\"episode_name\"]}'},\n {\"value\": item[\"resolution\"]},\n {\"value\": item[\"duration\"], \"duration\": True},\n {\"value\": item[\"guid\"], \"link\": re.sub(r'^com.plexapp.agents.imdb://([^?]*)(\\?.*)?', r'https://www.imdb.com/title/\\1', item[\"guid\"])}]\n if item is not None else None for item in matches]\n hasdiff = compare(row_info)\n row_str = get_row_str(row_info, hasdiff)\n first_col = None\n for m_col in row_info:\n if m_col is not None:\n first_col = m_col\n break\n table_rows.append({\"hasdiff\": hasdiff, \"sort\": first_col[0][\"value\"], \"html\": row_str})\n\ntable_rows.sort(key=lambda x: x[\"sort\"])\nfor row_data in table_rows:\n print(row_data[\"html\"])\nprint('
{d[2]}
  1. {escape(first_col[0][\"value\"])}
  1.  
    '\n for d in col:\n #for d in col if hasdiff else col[0:1]:\n row_str += f'
  1. '\n myvalue = html.escape(d[\"value\"]).encode(\"ascii\", \"xmlcharrefreplace\").decode(\"ascii\")\n if \"link\" in d and d[\"link\"]:\n row_str += f'{myvalue}'\n else:\n row_str += myvalue\n row_str += '
')\nprint('')\nprint('')\n","sub_path":"compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":11572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"504592586","text":"\n# calculate frequency unit q, also named by k'-k\n# q = 2*sin(theta/2)/lamda\ndef cal_q(detd, lamda=None, det_r=None, pixsize=None):\n\t# input: detd (mm) , lamda (A), det_r (pixel), pixsize (mm)\n\timport numpy as np\n\tif type(detd)!=float and type(detd)!=int:\n\t\tprint(\"This function is used to calculate frequency unit q, also defined by k'-k\")\n\t\tprint(\" -> q = 2*sin(theta/2)/lamda\")\n\t\tprint(\" -> Input: detd (mm) , lamda (A), det_r (pixel), pixsize (mm)\")\n\t\treturn\n\tlamda = lamda/10.0\n\tr = np.arange(det_r).astype(float) * pixsize\n\ttheta = np.arctan(r/detd)\n\tq = 2*np.sin(theta/2.0)/lamda\n\treturn q\n\ndef cal_r(qlist, detd=None, lamda=None, det_r=None, pixsize=None):\n\timport numpy as np\n\tif type(qlist)!=np.ndarray:\n\t\tprint(\"This function is inverse calculation of cal_q\")\n\t\tprint(\" -> Input : qlist (numpy.ndarray, shape=(Nr,))\")\n\t\tprint(\" detd (mm) , lamda (A), det_r (pixel), pixsize (mm)\")\n\t\treturn\n\tlamda = lamda/10.0\n\ttheta = 2*np.arcsin(qlist*lamda/2.0)\n\trlist = np.tan(theta)*detd\n\treturn rlist\n","sub_path":"analyse/q.py","file_name":"q.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"249288655","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 5 13:12:05 2019\n\n@author: v-catsai\n\"\"\"\nfrom table import Hamming_Dist\nfrom Control_line_2 import Control_lines\n\nclass Node:\n def __init__(self, i, bit_len):\n self.id = i\n self.pre = set([])\n self.de = set([])\n self.traversed = False\n self.bit_len= bit_len\n self.cline_removed=False\n def __del__(self):\n #print('del')\n del self.de\n del self.pre\n def add_pre(self, node):\n self.pre.add(node)\n def add_all_pre(self, lib):\n point = 1\n for i in range(self.bit_len):\n if point|self.id == self.id:\n aim = (point|self.id) - point\n #print(aim, self.id)\n if not aim in lib: \n #print('add')\n lib[aim]= Node(aim, self.bit_len) \n lib[aim].add_all_pre(lib)\n lib[aim].add_de(self)\n #print(lib[aim].de)\n #print(aim, point, self.id, lib[aim].de)\n point *= 2\n def add_de(self, node):\n self.de.add(node)\n node.add_pre(self)\n def remove_from_clines(self, all_c_lines):\n self.cline_removed=True\n all_c_lines.remove(self.id)\n for n in self.pre:\n if not n.cline_removed: n.remove_from_clines(all_c_lines)\n def traverse_add(self, all_c_lines, rm_frm_clines):\n self.traversed = True\n if rm_frm_clines: self.remove_from_clines(all_c_lines) #if removed might be faster\n add = set([])\n for n in self.de:\n if n.traversed: continue\n block = True\n for m in n.pre: \n if not m.traversed:\n block =False\n break\n if block: add.add(n.id)\n return add\n def __str__(self):\n string = '[' +str(self.id) + ' precending: '\n for n in self.pre: \n string = string + str(n.id) + ','\n string = string + ';decending: '\n for n in self.de: \n string = string + str(n.id) + ','\n string = string + ']'\n return string\n \n \n \n \n \nclass Traverse_Map:\n def __init__(self, bit_len):\n self.bit_len = bit_len\n self.nodes = {}\n n = Node(0, self.bit_len)\n self.nodes[0] = n\n self.available = Control_lines(bit_len)\n \n def traverse(self, idx, all_c_lines, rm_frm_clines=True):\n point = 1\n for i in range(self.bit_len):\n if point&idx != point and not point|idx in self.nodes: \n #print(point)\n self.nodes[point|idx]= Node(point|idx, self.bit_len)\n self.nodes[point|idx].add_all_pre(self.nodes)\n point *= 2\n #print(self.nodes[idx]) \n new = self.nodes[idx].traverse_add(all_c_lines, rm_frm_clines)\n if new:\n self.available.union(new, Hamming_Dist(idx,0,self.bit_len)+1)\n self.available.pop(idx)\n \n def __del__(self):\n for i in self.nodes: del i\n ","sub_path":"Traverse_Map.py","file_name":"Traverse_Map.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"425986653","text":"# 利用 time 函数,生成两个函数\r\n# 顺序调用\r\n# 计算总的运���时间\r\n# 练习带参数的多线程启动方法\r\nimport time\r\n# 导入多线程包\r\nimport threading\r\n\r\ndef loop1(in1):\r\n # ctime 得到当前时间\r\n print(\"Start loop 1 at :\",time.ctime())\r\n # 把参数打印出来\r\n print(\"我是参数 \",in1)\r\n # 睡眠多长时间,单位是秒\r\n time.sleep(4)\r\n print(\"End loop 1 at:\",time.ctime())\r\n\r\n\r\ndef loop2(in1, in2):\r\n # ctime 得到当前时间\r\n print(\"Start loop 2 at :\",time.ctime())\r\n # 把参数 in1 和 in2 打印出来代表使用\r\n print(\"我是参数 \", in1, \"和参数 \", in2)\r\n # 睡眠多长时间,单位是秒\r\n time.sleep(2)\r\n print(\"End loop 2 at:\",time.ctime())\r\n\r\ndef main():\r\n print(\"Starting at:\",time.ctime())\r\n # 启动多线程的意思是用多线程去执行某个函数\r\n # 生成 threading.Thread实例\r\n t1 = threading.Thread(target=loop1, args=(\"shen\",))\r\n t1.start()\r\n\r\n t2 = threading.Thread(target=loop2, args=(\"meng\",\"yao\",))\r\n t2.start()\r\n\r\n t1.join()\r\n t2.join()\r\n\r\n print(\"All done at:\",time.ctime())\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"242084988","text":"# 코인리스트에서 볼린저값을 구해 현재값이 lower보다 낮으면 마켓가로 매수\n# upper값보다 크면 마켓가로 매도\n# 문제점 : 원하는 매수가에 매수를 못함, 240원에 사서 매도조건이 만족되어 240원에 팔수도잇음\n# - 수수료만 내야함\n\n#추가 - > 현재가를 호가창에서 팔고하자하는 가격을 현재가, 그리고 매도할때는 사고하자는 가격을\n#현재가로 지정\n\n#추가 -> 조건식에서 매수잔량과 매도잔량이 0이상있을때 매수,매도주문\n\n#7-27 추가 -> 호가창에서 물량이 사고자하거나 팔고자하는 만큼 남아있는지 확인 후 매수,매도\n\n#8-05 추가 -> 매수주문이 들어가는 즉시 목표가격에 지정가주문을 걸고 만약 팔아야하는 시점이 오면 지정가 주문이 채결이 안되어있다면 취소하고 판매\n\n#8-07 추가 -> 매도를 했다면 coin_rebuy에 매도된 가격을 넣고 다음 주문에서 매도한가격보다 낮을때만 매수하도록 변경\n\n#8-12 추가 -> 텔레그렘 봇을 이용하여 거래 내용을 텔레그램으로 정보 받기\nimport pyupbit\nimport time\nimport talib\n\nimport datetime\nimport pprint\nimport datetime\nimport telegram\n\naccess_key = \"bRRqsFuM83Gy3xV3gaFP6cJbDFvkKxL5uIE10lUh\"\nsecret_key = \"0LWSzW60DFFB7o3bB8wDuvHvVUgZznkRdsX8JgFv\"\n\nticker = \"KRW-XEM\"\ncoinlist =[\"KRW-ADA\",\"KRW-XEM\",\"KRW-SC\",\"KRW-MLK\",\"KRW-UPP\",\"KRW-BORA\"]\n\ncoin_rebuy = [0 for i in range(len(coinlist))] # 매도한 후 매도가격보다 낮으면 다시 매수가능\nbuy = False\n\nupbit = pyupbit.Upbit(access_key, secret_key)\n\ndef getsize(coinlist):\n current = pyupbit.get_current_price(coinlist)\n\n if current >=2000000:\n return 1000\n elif current>=1000000:\n return 500\n elif current>=500000:\n return 100\n elif current>=100000:\n return 50\n elif current>=10000:\n return 10\n elif current>=1000:\n return 5\n elif current>=100:\n return 1\n elif current>=10:\n return 0.1\n else:\n return 0.01\ndef findTicker(coinlist):\n krw = upbit.get_balance(\"KRW\")\n while True:\n\n for i in range(len(coinlist)):\n df = pyupbit.get_ohlcv(coinlist[i], interval=\"minute5\")\n upper, middle, lower = talib.BBANDS(df['close'], 20, 2)\n df['lower'] = lower\n Df = df.iloc[-1]\n\n orderbook = pyupbit.get_orderbook(tickers=coinlist[i])\n current_price = orderbook[0]['orderbook_units'][0]['ask_price']\n if coin_rebuy[i] ==0 or coin_rebuy[i] > current_price: #8/8 오류수정\n\n if current_price < Df['lower'] and orderbook[0]['orderbook_units'][0]['ask_size'] >= krw / current_price:\n return coinlist[i]\n #print(coinlist[i])\n time.sleep(0.05)\n\n\n\n\nnow = datetime.datetime.now()\nnowDate = now.strftime('%Y-%m-%d %H:%M:%S')\nprint(\"Trading STart!!!\")\nprint(\"Time :\", nowDate)\n\nif upbit.get_balance(\"KRW\") > 1:\n buy = False\n print(\"Trading Situation : \", buy)\n pprint.pprint(upbit.get_balances())\nelse:\n buy = True\n balance = upbit.get_balances(ticker)\n buy_price = float(balance[0][1]['avg_buy_price'])\n ticker = \"KRW-\" + balance[0][1]['currency']\n print(\"Trading Situation : \", buy)\n print(\"Coin Name :\", ticker)\n print(\"Coin Price : \", buy_price)\n print(\"Coin balance :\", float(balance[0][1]['balance']))\n\nprint()\n\n\ntarget_per = 1.01\ntarget_sellper = 0.982\n\ntelegram_token = \"1933596461:AAHAMmGniaCtEUUSdgKYrWnrlsFpXz8-nHo\"\ntelegram_chat_id = 1665697222\nbot = telegram.Bot(token = telegram_token)\n\n\nwhile True:\n krw = upbit.get_balance(\"KRW\") # 잔고A\n try:\n if buy == False:\n\n ticker = findTicker(coinlist)\n\n buy_result = upbit.buy_market_order(ticker, upbit.get_balance(\"KRW\") * 0.9995) # B\n\n bot.sendMessage(chat_id=telegram_chat_id, text=\"[Buy_Result]\")\n bot.sendMessage(chat_id=telegram_chat_id, text=buy_result)\n\n print(\"Coin Founded!\")\n print()\n\n time.sleep(1)\n balance = upbit.get_balances(ticker) # A\n buy_price = float(balance[0][1]['avg_buy_price'])\n\n print(\"@@@ Buy Order @@@\")\n pprint.pprint(buy_result)\n print(\"Coin Name : \", ticker, \"Buy Price : \", buy_price)\n buy = True\n\n size = getsize(ticker)\n price = int((buy_price*target_per)/size) *size # 8/7 오류 수정\n\n if price < buy_price*target_per:\n price +=size\n\n\n sell = upbit.sell_limit_order(ticker, price, upbit.get_balance(ticker)) # limitorder . price , count , 8/8 오류 수정\n bot.sendMessage(chat_id=telegram_chat_id, text=\"[Limit_Sell]\")\n bot.sendMessage(chat_id=telegram_chat_id, text=sell)\n coin_rebuy = [0 for i in range(len(coinlist))] # 8/7 추가 coin_rebuy리스트 초기화\n time.sleep(1)\n\n print(\"@@@ LIMIT SEll ORDER @@@\")\n print(\"Coin Name : \", ticker)\n print(\"Limit Sell Price :\",price )\n pprint.pprint(sell)\n print(\"-----------------------------------\")\n\n\n else:\n df = pyupbit.get_ohlcv(ticker, interval=\"minute5\") # B\n upper, middle, lower = talib.BBANDS(df['close'], 20, 2)\n df['upper'] = upper\n Df = df.iloc[-1]\n\n orderbook = pyupbit.get_orderbook(tickers=ticker)\n\n current_bidprice = orderbook[0]['orderbook_units'][0]['bid_price']\n\n if upbit.get_balance(\"KRW\") >= 5000:\n buy = False\n print(\"Limit Order Complete!!\")\n print()\n time.sleep(0.5)\n for i in range(len(coinlist)):\n if coinlist[i] == ticker:\n m=upbit.get_order(ticker, state=\"done\")[0]['uuid']\n coin_rebuy[i] = float(upbit.get_order(m)['trades'][0]['price'])\n\n elif (current_bidprice <= (buy_price * target_sellper) or\n current_bidprice >= Df['upper']) and buy == True and orderbook[0]['orderbook_units'][0]['bid_size'] >= upbit.get_balance(ticker):\n\n #limi order cancel\n print(\"Limit Order Cancel!!!\")\n limit = upbit.get_order(ticker)\n if limit:\n upbit.cancel_order(limit[0]['uuid'])\n time.sleep(0.05)\n # A\n sell_result = upbit.sell_market_order(ticker, upbit.get_balance(ticker))\n print(\"@@@ Sell Order @@@\")\n print(\"Present Price :\", current_bidprice, \"Bollinger Upper :\", Df['upper'])\n bot.sendMessage(chat_id=telegram_chat_id, text=\"[Sell_Result]\")\n bot.sendMessage(chat_id=telegram_chat_id, text=sell_result)\n\n pprint.pprint(sell_result)\n\n time.sleep(1)\n buy = False\n print(\"My Balance : \", upbit.get_balance(\"KRW\"))\n # A\n\n for i in range(len(coinlist)):\n if coinlist[i]==ticker:\n m = upbit.get_order(ticker, state=\"done\")[0]['uuid']\n coin_rebuy[i] = float(upbit.get_order(m)['trades'][0]['price']) # 8/7 추가\n\n\n\n time.sleep(0.05)\n\n except Exception as e:\n print(e)\n print(\"Error Occurred\")\n time.sleep(1)\n\n","sub_path":"8-5 tradingbot.py","file_name":"8-5 tradingbot.py","file_ext":"py","file_size_in_byte":7444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"39046880","text":"# https://atcoder.jp/contests/abc144/tasks/abc144_f\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\ndef resolve():\n n,m=map(int,input().split())\n edges=[[] for _ in range(n)]\n for _ in range(m):\n s,t=map(int,input().split())\n s-=1; t-=1\n edges[s].append(t)\n\n # 確率DP\n p=[0]*n\n p[0]=1.0\n for v in range(n):\n for nv in edges[v]:\n p[nv]+=p[v]/len(edges[v])\n\n # 期待値DP\n E=[0]*n\n for v in range(n-2,-1,-1):\n for nv in edges[v]:\n E[v]+=E[nv]\n E[v]=1+E[v]/len(edges[v])\n\n ans=E[0]\n for v in range(n):\n if(len(edges[v])<=1): continue\n # 各vに対して、辺vwのうちE[w]が最大のものを削除する\n w=max(*((E[w],w) for w in edges[v]))[1]\n dE=0\n deg=len(edges[v])\n for nv in edges[v]:\n if(nv==w): dE-=E[nv]/deg\n else: dE+=E[nv]/(deg-1)/deg\n ans=min(ans,E[0]+p[v]*dE)\n\n print(ans)\nresolve()\n","sub_path":"ABC144/f_fork_in_the_road.py","file_name":"f_fork_in_the_road.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"346891409","text":"\"\"\"\n requirements:\n pip install boto3\n pip install paramiko\n\n Sample call:\n python mmtl_aws.py --mode launch_and_run --aws_access_key_id xxx --aws_secret_access_key xxx --keypath ~/.ssh/personalkeyncalifornia.pem --config aws_config\n\n Sample output:\n /usr/local/lib/python3.6/site-packages/paramiko/kex_ecdh_nist.py:39: CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePublicNumbers and will be emoved in a future version. Please use EllipticCurvePublicKey.public_bytes to obtain both compressed and uncompressed point encoding.\n m.add_string(self.Q_C.public_numbers().encode_point())\n /usr/local/lib/python3.6/site-packages/paramiko/kex_ecdh_nist.py:39: CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePublicNumbers and will be emoved in a future version. Please use EllipticCurvePublicKey.public_bytes to obtain both compressed and uncompressed point encoding.\n m.add_string(self.Q_C.public_numbers().encode_point())\n /usr/local/lib/python3.6/site-packages/paramiko/kex_ecdh_nist.py:96: CryptographyDeprecationWarning: Support for unsafe construction of public numbers from encoded data will beremoved in a future version. Please use EllipticCurvePublicKey.from_encoded_point\n self.curve, Q_S_bytes\n /usr/local/lib/python3.6/site-packages/paramiko/kex_ecdh_nist.py:111: CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePublicNumbers and will beremoved in a future version. Please use EllipticCurvePublicKey.public_bytes to obtain both compressed and uncompressed point encoding.\n hm.add_string(self.Q_C.public_numbers().encode_point())\n /usr/local/lib/python3.6/site-packages/paramiko/kex_ecdh_nist.py:96: CryptographyDeprecationWarning: Support for unsafe construction of public numbers from encoded data will beremoved in a future version. Please use EllipticCurvePublicKey.from_encoded_point\n self.curve, Q_S_bytes\n /usr/local/lib/python3.6/site-packages/paramiko/kex_ecdh_nist.py:111: CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePublicNumbers and will beremoved in a future version. Please use EllipticCurvePublicKey.public_bytes to obtain both compressed and uncompressed point encoding.\n hm.add_string(self.Q_C.public_numbers().encode_point())\n Putting file secret -> secret\n Putting file secret -> secret\n Getting file secret -> output/i-04c1e57c76aaff218/yoman\n Getting file secret -> output/i-09b38dd9e71d3474a/yoman\n i-04c1e57c76aaff218 testing 42\n i-09b38dd9e71d3474a testing 42\n\"\"\"\n\nimport argparse\nimport datetime\nimport importlib\nimport inspect\nimport multiprocessing\nimport os\nimport sys\nimport time\nfrom stat import S_ISDIR\n\nimport boto3\nimport paramiko\n\nfrom metal.mmtl.aws import grid_search_mmtl\n\n# IMAGE_ID = \"ami-0c82a5c425d9da154\" # For West\n# IMAGE_ID = \"ami-04f2030e810b07ced\" # For East\n# IMAGE_ID = \"ami-0507d23ab4a37c611\" # For East (02-18-2019)\n# IMAGE_ID = \"ami-01b22f90823e1b2af\" # For East w/ Apex (02-21-2019)\n# IMAGE_ID = \"ami-0334863e514e3c3df\" # For ensemble GLUE datasets (03-04-2019)\n# IMAGE_ID = \"ami-0be2f9acd392d909a\" # For ensemble GLUE datasets (03-13-2019) with MNLI fixed.\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"--mode\",\n choices=[\n \"list\",\n \"launch\",\n \"launch_and_run\",\n \"run\",\n \"shutdown\",\n \"shutdown_all\",\n \"run_and_shutdown\",\n ],\n)\nparser.add_argument(\"--aws_access_key_id\", required=True)\nparser.add_argument(\"--aws_secret_access_key\", required=True)\nparser.add_argument(\"--region\", default=\"us-east-1\")\nparser.add_argument(\"--n_machines\", default=2, type=int)\nparser.add_argument(\"--n_trials\", default=None, type=int)\nparser.add_argument(\"--keypath\", required=True)\nparser.add_argument(\"--outputpath\", default=\"output\")\nparser.add_argument(\"--instance_type\", default=\"t2.medium\")\nparser.add_argument(\"--only_print_commands\", default=0)\nparser.add_argument(\n \"--run_name\",\n default=datetime.datetime.fromtimestamp(time.time()).strftime(\"%Y_%m_%d_%H_%M_%S\"),\n)\nparser.add_argument(\n \"--configpath\", required=True, type=str, help=\"path to config dicts\"\n)\nparser.add_argument(\n \"--commit_hash\", required=True, type=str, help=\"git commit hash to run with\"\n)\nparser.add_argument(\"--ami\", required=True, type=str, help=\"ami id to run with\")\n\n\ndef create_dummy_command_dict2():\n COMMAND_PREFIX = (\n \"source activate pytorch_p36;\"\n \"python -m spacy download en;\" # TODO: add to env by default\n \"rm -rf metal;\"\n \"git clone https://github.com/HazyResearch/metal.git;\"\n \"git checkout 868fb01a48e4031b8f1ac568e3bd0b413c904541;\"\n \"cd metal; source add_to_path.sh;\"\n \"pwd;\"\n )\n COMMAND = \"python metal/mmtl/aws_test.py\"\n\n return {\"cmd\": COMMAND_PREFIX + COMMAND, \"files_to_put\": [], \"files_to_get\": []}\n\n\ndef create_dummy_command_dict():\n\n COMMAND_PREFIX = \"\"\n COMMAND = \"cat secret\"\n\n return {\n \"cmd\": COMMAND_PREFIX + COMMAND,\n \"files_to_put\": [(\"secret\", \"secret\")],\n \"files_to_get\": [(\"secret\", \"yoman\")],\n }\n\n\ndef run_command(args, instance, cmd_dict, output, run_id):\n\n # Helper for downloading directory\n def download_dir(sftp, remote_dir, local_dir):\n os.path.exists(local_dir) or os.makedirs(local_dir)\n dir_items = sftp.listdir_attr(remote_dir)\n for item in dir_items:\n # assuming the local system is Windows and the remote system is Linux\n # os.path.join won't help here, so construct remote_path manually\n remote_path = remote_dir + \"/\" + item.filename\n local_path = os.path.join(local_dir, item.filename)\n if S_ISDIR(item.st_mode):\n download_dir(sftp, remote_path, local_path)\n else:\n sftp.get(remote_path, local_path)\n\n key = paramiko.RSAKey.from_private_key_file(args.keypath)\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n cmd = cmd_dict[\"cmd\"]\n files_to_put, files_to_get, dirs_to_get = [], [], []\n if \"files_to_put\" in cmd_dict:\n files_to_put = cmd_dict[\"files_to_put\"]\n if \"files_to_get\" in cmd_dict:\n files_to_get = cmd_dict[\"files_to_get\"]\n if \"dirs_to_get\" in cmd_dict:\n dirs_to_get = cmd_dict[\"dirs_to_get\"]\n\n assert os.path.exists(args.outputpath)\n instance_output_path = \"%s/%s/\" % (args.outputpath, run_id)\n if not os.path.exists(instance_output_path):\n os.makedirs(instance_output_path)\n\n try:\n client.connect(\n hostname=instance[\"public_ip_address\"], username=\"ubuntu\", pkey=key\n )\n\n # Put files\n sftp = client.open_sftp()\n for (localpath, remotepath) in files_to_put:\n print(\"Putting %s -> %s\" % (localpath, remotepath))\n sftp.put(localpath, remotepath)\n\n # Execute a command(cmd) after connecting/ssh to an instance\n print(\"Machine: %s Running: %s\" % (instance[\"public_ip_address\"], cmd))\n stdin, stdout, stderr = client.exec_command(cmd)\n output[run_id] = stdout.read().decode(\"utf-8\")\n\n # Save stdout and stderr to instance path\n with open(instance_output_path + \"stderr\", \"w\") as f:\n f.write(stderr.read().decode(\"utf-8\"))\n with open(instance_output_path + \"stdout\", \"w\") as f:\n f.write(output[run_id])\n\n # Get files\n for (remotepath, localpath) in files_to_get:\n print(\n \"Getting file %s -> %s\" % (remotepath, instance_output_path + localpath)\n )\n sftp.get(remotepath, instance_output_path + localpath)\n\n # Get directories\n for (remotepath, localpath) in dirs_to_get:\n print(\n \"Getting dir %s -> %s\" % (remotepath, instance_output_path + localpath)\n )\n download_dir(sftp, remotepath, instance_output_path + localpath)\n\n # close the client connection once the job is done\n sftp.close()\n client.close()\n\n except Exception as e:\n print(e)\n\n return output\n\n\ndef create_ec2_client(args):\n ec2_client = boto3.client(\n \"ec2\",\n aws_access_key_id=args.aws_access_key_id,\n aws_secret_access_key=args.aws_secret_access_key,\n region_name=args.region,\n )\n ec2_resource = boto3.resource(\n \"ec2\",\n aws_access_key_id=args.aws_access_key_id,\n aws_secret_access_key=args.aws_secret_access_key,\n region_name=args.region,\n )\n return ec2_client, ec2_resource\n\n\ndef get_user(instance):\n if instance.tags is not None:\n for tag in instance.tags:\n if \"Key\" in tag and \"Value\" in tag:\n if tag[\"Key\"] == \"user\":\n return tag[\"Value\"]\n return \"UNKNOWN\"\n\n\ndef get_instances(args, filter_by_user=True):\n ec2_client, ec2_resource = create_ec2_client(args)\n instances = ec2_resource.instances.filter()\n if filter_by_user:\n instances = [\n x\n for x in instances\n if get_user(x) == os.environ[\"USER\"] + \"_\" + args.run_name\n ]\n return instances\n\n\ndef get_all_instances(args, filter_by_user=True):\n ec2_client, ec2_resource = create_ec2_client(args)\n instances = ec2_resource.instances.filter()\n if filter_by_user:\n instances = [x for x in instances if os.environ[\"USER\"] in get_user(x)]\n return instances\n\n\ndef describe_instances(args):\n\n instances = get_instances(args, filter_by_user=False)\n for instance in instances:\n print(\n \"%s, state: %s, user: %s, type: %s\\n\\t\"\n # \"ssh -i %s ubuntu@%s\"\n \"eval `ssh-agent` && cat %s | ssh-add -k - && ssh -i %s ubuntu@%s\"\n % (\n instance.id,\n instance.state[\"Name\"],\n get_user(instance),\n instance.instance_type,\n args.keypath,\n args.keypath,\n instance.public_ip_address,\n )\n )\n\n\ndef launch(args):\n ec2_client, ec2_resource = create_ec2_client(args)\n instances = ec2_resource.create_instances(\n ImageId=args.ami,\n MinCount=args.n_machines,\n MaxCount=args.n_machines,\n KeyName=os.path.basename(args.keypath).split(\".\")[0],\n InstanceType=args.instance_type,\n )\n\n # Tag with user\n ec2_client.create_tags(\n Resources=[x.id for x in instances],\n Tags=[{\"Key\": \"user\", \"Value\": os.environ[\"USER\"] + \"_\" + args.run_name}],\n )\n\n print(\"Waiting for instances: %s\" % str([x.id for x in instances]))\n for instance in instances:\n instance.wait_until_running()\n instance.reload()\n\n # This is sometimes necessary to avoid ssh errors\n time.sleep(180)\n\n describe_instances(args)\n\n return instances\n\n\ndef shutdown(args):\n instances = get_instances(args)\n for instance in instances:\n instance.terminate()\n describe_instances(args)\n\n\ndef shutdown_all_by_user(args):\n instances = get_all_instances(args)\n for instance in instances:\n instance.terminate()\n describe_instances(args)\n\n\ndef worker_job(\n args, instance_dicts, command_dict, return_output, process_id_mapping, run_id\n):\n\n # Get process id and map to instance\n current = str(multiprocessing.current_process())\n wid = process_id_mapping[current]\n instance_dict = instance_dicts[wid]\n print(\"Worker %s -> %s\" % (wid, instance_dict[\"public_ip_address\"]))\n\n # Run command on instance\n run_command(args, instance_dict, command_dict, return_output, run_id)\n\n\ndef initialize_process_ids(wid, process_id_mapping):\n current = str(multiprocessing.current_process())\n process_id_mapping[current] = wid\n print(\"Process %s => %s\" % (current, str(wid)))\n\n\ndef run(args, launch_args, search_space, instances=None):\n\n # By default run command on all running machines\n if instances is None:\n instances = [x for x in get_instances(args) if x.state[\"Name\"] == \"running\"]\n\n # Append the current date to the outputpath\n ts = time.time()\n timestamp_str = datetime.datetime.fromtimestamp(ts).strftime(\"%Y_%m_%d_%H_%M_%S\")\n args.outputpath = args.outputpath + \"/\" + timestamp_str + \"/\"\n if not os.path.exists(args.outputpath):\n os.makedirs(args.outputpath)\n\n manager = multiprocessing.Manager()\n\n # Generate commands\n return_output = manager.dict()\n process_id_mapping = manager.dict()\n command_dicts = grid_search_mmtl.generate_configs_and_commands(\n args, launch_args, search_space, args.n_trials\n )\n instance_dicts = [\n {str(k): str(v) for k, v in dict(inspect.getmembers(instance)).items()}\n for instance in instances\n ]\n data = [\n (args, instance_dicts, x, return_output, process_id_mapping, i)\n for i, x in enumerate(command_dicts)\n ]\n\n p = multiprocessing.Pool(args.n_machines)\n\n # Map processes to indices in the range 0 to n (todo(maxlam): DANGEROUS)\n initialization_args = [\n (x, process_id_mapping) for x in list(range(args.n_machines))\n ]\n p.starmap(initialize_process_ids, initialization_args)\n\n # Main work\n if args.only_print_commands:\n for cmd_dict in command_dicts:\n print(\"-\" * 50)\n for x in cmd_dict[\"files_to_put\"]:\n print(\"cp %s %s\" % x)\n print(cmd_dict[\"cmd\"])\n print(\"-\" * 50)\n else:\n p.starmap(worker_job, data)\n\n print(\"Results\")\n print(\"-\" * 100)\n for k, v in return_output.items():\n with open(args.outputpath + \"/\" + str(k) + \".out\", \"w\") as f:\n f.write(str(v))\n\n\ndef launch_and_run(args, launch_args, search_space):\n instances = launch(args)\n run(args, launch_args, search_space, instances=instances)\n shutdown(args)\n\n\nif __name__ == \"__main__\":\n\n args = parser.parse_args()\n # importing from config\n from importlib.machinery import SourceFileLoader\n\n config_dicts = SourceFileLoader(\"config_dicts\", args.configpath).load_module()\n # config_dicts = importlib.import_module(args.configpath)\n search_space = config_dicts.search_space\n launch_args = config_dicts.launch_args\n if args.mode == \"list\":\n describe_instances(args)\n if args.mode == \"launch\":\n launch(args)\n if args.mode == \"launch_and_run\":\n launch_and_run(args, launch_args, search_space)\n if args.mode == \"run\":\n run(args, launch_args, search_space)\n if args.mode == \"shutdown\":\n shutdown(args)\n if args.mode == \"run_and_shutdown\":\n run(args, launch_args, search_space)\n shutdown(args)\n if args.mode == \"shutdown_all\":\n shutdown_all_by_user(args)\n","sub_path":"metal/mmtl/aws/mmtl_aws.py","file_name":"mmtl_aws.py","file_ext":"py","file_size_in_byte":14682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"106878773","text":"from flask import Flask, request, Markup, render_template, redirect, url_for, make_response, flash\nfrom jinja2 import Environment, PackageLoader, select_autoescape\nfrom functools import wraps\n\nimport scraper_app.config as config\nimport scraper_app.validators as validators\nimport scraper_app.services as services\nfrom scraper_app.app_constants import (\n empty_signin_form,\n empty_login_form,\n tab_list,\n list_table_columns,\n list_table_column_keys,\n tab_label_map)\n\napp = Flask(__name__)\napp.secret_key = bytes(config.SESSION_SECRET, encoding='utf8')\n\n\n@app.route('/')\ndef root_page():\n return redirect(url_for('home_page'))\n\n\n@app.route('/home', methods=['GET'])\n@app.route('/home/', methods=['GET'])\ndef home_page(tab_name=None):\n authentication_info = services.authenticate_user(\n request.cookies.copy().to_dict(flat=True))\n\n if authentication_info == 'token_invalid':\n return redirect(url_for('login_page'))\n\n if ('status' in authentication_info) and (\n authentication_info['status'] == 'token_expired'):\n return redirect(url_for('refresh_tokens', tab_name=tab_name))\n\n if request.method == 'GET':\n scraped_list = ''\n if tab_name:\n scraped_list = services.get_scraped_list(tab_name)\n if ('movie_list' not in scraped_list) or len(scraped_list['movie_list']) < 1:\n flash(\n f'Could not load the list for {tab_label_map[tab_name]}', 'error')\n return render_template('home.html',\n user_is_logged_in=True,\n user=authentication_info['user'],\n tab_list=tab_list,\n selected_tab=tab_name,\n tab_label_map=tab_label_map,\n list_table_columns=list_table_columns,\n list_table_column_keys=list_table_column_keys,\n scraped_list=scraped_list)\n\n\n@app.route('/scrape/', methods=['GET'])\ndef scrape_list(list_name=None):\n authentication_info = services.authenticate_user(\n request.cookies.copy().to_dict(flat=True))\n\n if authentication_info == 'token_invalid':\n return redirect(url_for('login_page'))\n\n if list_name in tab_label_map.keys():\n try:\n services.scrape(list_name)\n flash(\n f'{tab_label_map[list_name]} scraped successfully!', 'success')\n except Exception as error:\n flash(\n f'Could not scrape {tab_label_map[list_name]} due to some internal errors!', 'error')\n\n return redirect(url_for('home_page', tab_name=list_name))\n else:\n flash(f'Invalid request!', 'error')\n return redirect(url_for('home_page'))\n\n\n@app.route('/refresh', methods=['GET'])\ndef refresh_tokens():\n if request.method == 'GET':\n new_tokens_info = services.refresh_tokens(\n request.cookies.copy().to_dict(flat=True))\n\n if new_tokens_info in ['token_expired', 'token_invalid', 'token_refresh_error']:\n refresh_response = make_response(redirect(url_for('login_page')))\n refresh_response.set_cookie('access_token', '',\n path='/', httponly=True, max_age=0)\n refresh_response.set_cookie('refresh_token', '',\n path='/refresh', httponly=True, max_age=0)\n\n return refresh_response\n\n query_params = request.args.copy().to_dict(flat=True)\n tab_name = ''\n if 'tab_name' in query_params:\n tab_name = query_params['tab_name']\n response = make_response(\n redirect(url_for('home_page', tab_name=tab_name)))\n response.set_cookie('access_token', new_tokens_info['access_token'],\n path='/', httponly=True, max_age=config.COOKIE_LIFE)\n response.set_cookie('refresh_token', new_tokens_info['refresh_token'],\n path='/refresh', httponly=True, max_age=config.COOKIE_LIFE)\n\n return response\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login_page():\n authentication_info = services.authenticate_user(\n request.cookies.copy().to_dict(flat=True))\n\n if ('status' in authentication_info) and (\n authentication_info['status'] == 'token_expired'):\n return redirect(url_for('refresh_tokens'))\n\n if 'user' in authentication_info:\n return redirect(url_for('home_page'))\n\n if request.method == 'GET':\n return render_template('login.html', form_data=empty_login_form)\n\n if request.method == 'POST':\n validation = validators.validate_login_form(request.form)\n\n if validation['has_error']:\n return render_template('login.html', form_data=request.form, error=validation['error'])\n\n try:\n tokens = services.log_in_user(\n request.form.copy().to_dict(flat=True))\n\n response = make_response(redirect(url_for('home_page')))\n response.set_cookie('access_token', tokens['access_token'],\n path='/', httponly=True, max_age=config.COOKIE_LIFE)\n response.set_cookie('refresh_token', tokens['refresh_token'],\n path='/refresh', httponly=True, max_age=config.COOKIE_LIFE)\n\n return response\n except Exception as error:\n error_dict = error.args[0]\n resp = make_response(render_template(\n 'login.html', form_data=request.form, error=error_dict), error_dict['code'])\n return resp\n\n\n@app.route('/signin', methods=['GET', 'POST'])\ndef signin_page():\n authentication_info = services.authenticate_user(\n request.cookies.copy().to_dict(flat=True))\n\n if ('status' in authentication_info) and (\n authentication_info['status'] == 'token_expired'):\n return redirect(url_for('refresh_tokens'))\n\n if 'user' in authentication_info:\n return redirect(url_for('home_page'))\n\n if request.method == 'GET':\n return render_template('signin.html', form_data=empty_signin_form)\n\n if request.method == 'POST':\n validation = validators.validate_signin_form(request.form)\n\n if validation['has_error']:\n resp = make_response(render_template(\n 'signin.html', form_data=request.form, error=validation['error']), 400)\n return resp\n\n try:\n services.create_new_user(\n request.form.copy().to_dict(flat=True))\n flash('You were signed in successfully!', 'success')\n\n return redirect(url_for('login_page'))\n except Exception as error:\n error_dict = error.args[0]\n resp = make_response(render_template(\n 'signin.html', form_data=request.form, error=error_dict), error_dict['code'])\n return resp\n\n\n@app.route('/logout', methods=['GET'])\ndef logout_page():\n authentication_info = services.authenticate_user(\n request.cookies.copy().to_dict(flat=True))\n\n if 'user' in authentication_info:\n services.log_out_user(authentication_info['user'])\n\n response = make_response(redirect(url_for('login_page')))\n response.set_cookie('access_token', '',\n path='/', httponly=True, max_age=0)\n response.set_cookie('refresh_token', '',\n path='/refresh', httponly=True, max_age=0)\n\n return response\n","sub_path":"Python/RanjanPaudel/scraper/scraper_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"23941392","text":"#!/usr/bin/env python3\n\nimport rclpy\nfrom geometry_msgs.msg import PoseWithCovarianceStamped\n\nflag = 1\n\ndef main():\n global mypub\n rclpy.init()\n myfirstpublisher = rclpy.create_node('publisher')\n mypub = myfirstpublisher.create_publisher(PoseWithCovarianceStamped, '/initialpose', 1)\n myfirstpublisher.create_timer(0.1, mytimercallback)\n try:\n rclpy.spin_once(myfirstpublisher)\n except KeyboardInterrupt:\n pass\n\n myfirstpublisher.destroy_node()\n rclpy.shutdown()\n\ndef mytimercallback():\n global mypub\n global flag\n mymsg = PoseWithCovarianceStamped()\n #mymsg.header.stamp = publisher.get_clock().now().to_msg()\n mymsg.header.frame_id = 'map'\n mymsg.pose.pose.position.x = -1.93\n mymsg.pose.pose.position.y = -0.73\n mymsg.pose.pose.position.z = 0.0\n mymsg.pose.pose.orientation.x = 0.0\n mymsg.pose.pose.orientation.y = 0.0\n mymsg.pose.pose.orientation.z = 0.0\n mymsg.pose.pose.orientation.w = 1.0\n if flag:\n \tmypub.publish(mymsg)\n \tflag = 0\n\nif __name__ == '__main__':\n main()","sub_path":"robot_ws/src/my_vacuum_cleaner/my_vacuum_cleaner/set_initial_pose.py","file_name":"set_initial_pose.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"633011484","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport copy\nimport math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n__author__ = 'fyabc'\n\n\ndef clones(module, N):\n \"\"\"Produce N identical layers.\"\"\"\n return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])\n\n\nclass LayerNorm(nn.Module):\n \"\"\"Construct a layernorm module (See citation for details).\"\"\"\n\n def __init__(self, features, eps=1e-6):\n super(LayerNorm, self).__init__()\n self.a_2 = nn.Parameter(torch.ones(features))\n self.b_2 = nn.Parameter(torch.zeros(features))\n self.eps = eps\n\n def forward(self, x):\n mean = x.mean(-1, keepdim=True)\n std = x.std(-1, keepdim=True)\n return self.a_2 * (x - mean) / (std + self.eps) + self.b_2\n\n\nclass SublayerConnection(nn.Module):\n \"\"\"\n A residual connection followed by a layer norm.\n Note for code simplicity the norm is first as opposed to last.\n \"\"\"\n\n def __init__(self, size, dropout):\n super(SublayerConnection, self).__init__()\n self.norm = LayerNorm(size)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x, sublayer):\n \"\"\"Apply residual connection to any sublayer with the same size.\"\"\"\n return x + self.dropout(sublayer(self.norm(x)))\n\n\ndef subsequent_mask(size, pad_id=0):\n \"\"\"Mask out subsequent positions.\"\"\"\n attn_shape = (1, size, size)\n mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')\n return torch.from_numpy(mask) == pad_id\n\n\nclass PositionwiseFeedForward(nn.Module):\n \"\"\"Implements FFN equation.\"\"\"\n def __init__(self, d_model, d_ff, dropout=0.1):\n super(PositionwiseFeedForward, self).__init__()\n self.w_1 = nn.Linear(d_model, d_ff)\n self.w_2 = nn.Linear(d_ff, d_model)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n return self.w_2(self.dropout(F.relu(self.w_1(x))))\n\n\nclass Embeddings(nn.Module):\n def __init__(self, d_model, vocab):\n super(Embeddings, self).__init__()\n self.lut = nn.Embedding(vocab, d_model)\n self.d_model = d_model\n\n def forward(self, x):\n return self.lut(x) * math.sqrt(self.d_model)\n\n\nclass PositionalEncoding(nn.Module):\n \"\"\"Implement the PE function.\"\"\"\n\n def __init__(self, d_model, dropout, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n # Compute the positional encodings once in log space.\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2) *\n -(math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + Variable(self.pe[:, :x.size(1)],\n requires_grad=False)\n return self.dropout(x)\n\n\ndef fix_batch(batch, pad_id):\n \"\"\"Fix the batch from NAS4Text style to Annotated Transformer style.\"\"\"\n\n net_input = batch['net_input']\n src_tokens, trg_tokens = net_input['src_tokens'], net_input['trg_tokens']\n net_input['src_mask'] = (src_tokens != pad_id).unsqueeze(-2)\n trg_mask = (trg_tokens != pad_id).unsqueeze(-2)\n net_input['trg_mask'] = trg_mask & subsequent_mask(trg_tokens.size(-1), pad_id=pad_id).type_as(trg_mask)\n","sub_path":"libs/annotated_transformer/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"103629481","text":"from app import app, db\nfrom app.models import Review\nfrom flask import render_template, request, flash, redirect, url_for\nimport sys\nimport json\n\n@app.route('/', methods=['GET', 'POST'])\ndef session():\n if request.method == 'GET':\n reviews = Review.query.all()\n reviews.reverse()\n return render_template('home.html', reviews=reviews, staff=0)\n\n@app.route('/staff', methods=['GET', 'POST'])\ndef staff():\n if request.method == 'GET':\n reviews = Review.query.all()\n reviews.reverse()\n return render_template('home.html', reviews=reviews, staff=1)\n \n# Login for staff users\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'GET':\n return render_template('login.html')\n if request.method == 'POST':\n if request.form[\"username\"] == 'staff' and request.form[\"password\"] == 'shravan':\n return redirect(url_for('staff')) # This staff does not give value to the parameter (when used as session, staff=1)\n else:\n flash(\"Incorrect username or password. Try again!\")\n return render_template('login.html')\n \n@app.route('/review', methods=['GET', 'POST'])\ndef review():\n if request.method == 'GET':\n return render_template('contactus.html')\n elif request.method == 'POST':\n message = Review(\n name = request.form[\"name\"],\\\n roomnumber = request.form[\"roomnumber\"],\\\n admissionnumber = request.form[\"admissionnumber\"],\\\n mobile = request.form[\"mobile\"],\\\n review = request.form[\"review\"]\n )\n try:\n db.session.add(message)\n db.session.commit()\n flash('Your review has been sent to the concerned authorities!')\n except Exception as e:\n print(\"\\n FAILED entry\")\n print(e)\n sys.stdout.flush()\n reviews = Review.query.all()\n reviews.reverse()\n return redirect(url_for('session'))\n\n@app.route('/review/delete/', methods=['POST'])\ndef reviewdelete(id):\n if request.method == 'POST':\n db.session.query(Review).filter_by(id=id).delete()\n db.session.commit()\n \n reviews = Review.query.all()\n reviews.reverse()\n return redirect(url_for('staff'))","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"254849594","text":"# -*- coding: utf-8 -*-\n# 第一行加这个后,就可以加中文注释了\n'''\nCreated on 2017年5月21日\n\n@author: tony\n''' \nfrom html.parser import HTMLParser\nfrom util import CommonUtil\nimport re\n\n''' \n提取链接,返回一个链接数组\n'''\ndef extractLink(html):\n html = CommonUtil.toUtf8(html)\n reg = r'(.*?)'\n groups = re.findall(reg, html, re.S|re.M)\n links = []\n for group in groups:\n link = group[1] #找到匹配的链接group\n if(link.strip() != ''): #链接不为空的时候再返回\n links.append(link)\n return links\n\n'''\n提取豆瓣首页里面的新闻链接地址和标题\n'''\ndef extractDoubanNews(html):\n html = CommonUtil.toUtf8(html)\n reg = r'class=\"notes\">(.*?)'\n news = re.findall(reg, html, re.S|re.M)\n if(len(news) == 1):\n return extractItems(news[0])\n return None\n\n'''\n提取豆瓣首页里面的新闻链接地址和标题\n'''\ndef extractItems(content):\n reg = r'
  • (.*?)
  • '\n linkReg = re.compile(reg)\n linkList = re.findall(linkReg, content)\n news = []\n for link in linkList:\n itemReg = re.compile('(.*?)')\n match = itemReg.match(link)\n if match:\n item = []\n item.append(match.group(1))\n item.append(match.group(2))\n news.append(item)\n return news \n\n'''\n提取新闻里面的内容\n'''\ndef extractMeta(html):\n meta = {}\n meta['title'] = ''\n meta['author'] = ''\n meta['pubTime'] = ''\n meta['content'] = ''\n \n #1. 提取标题\n titleReg = r'

    (.*?)

    '\n titles = re.findall(titleReg, html, re.S|re.M)\n if titles:\n meta['title'] = titles[0]\n \n #2. 提取作者\n authorReg = r'class=\"note-author\">(.*?)'\n authors = re.findall(authorReg, html, re.S|re.M)\n if authors:\n meta['author'] = authors[0]\n \n #3. 提取时间\n timeReg = r'class=\"pub-date\">(.*?)'\n times = re.findall(timeReg, html, re.S|re.M)\n if authors:\n meta['pubTime'] = times[0]\n \n #4. 提取内容\n contentReg = r'id=\"link-report\">(.*?)
    '\n contents = re.findall(contentReg, html, re.S|re.M)\n if contents:\n meta['content'] = strip_tags(contents[0])\n return meta\n\n'''\n提取文本\n'''\ndef strip_tags(html): \n html = html.replace(\"\\\\/\", \"/\")\n result = [''] \n parser = HTMLParser() \n parser.handle_data = result.append \n parser.feed(html) \n parser.close() \n return ''.join(result).strip() \n\n\n'''\n提取微博内容\n'''\ndef extractWeiboContent(html):\n weibos = []\n #1. 提取每个微博内容区域正则表达式\n reg = r'
    (.*?)
    (.*?)<\\\\/p>'\n texts = re.findall(textReg, item, re.S|re.M|re.U)\n if texts and len(texts) > 0:\n weibo['author'] = CommonUtil.unicode2chinese(texts[0][1]) #第二个下标是微博作者\n weibo['text'] = CommonUtil.unicode2chinese(strip_tags(texts[0][2])) #第三个下标是微博内容\n #3. 提取微博发布时间\n dateReg = r'\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}'\n dates = re.findall(dateReg, item, re.S|re.M|re.U)\n if dates and len(dates) > 0:\n weibo['pubTime'] = dates[0]\n weibos.append(weibo)\n return weibos\n","sub_path":"src/util/HtmlExtract.py","file_name":"HtmlExtract.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"573225983","text":"from bs4 import BeautifulSoup\nimport dryscrape\nimport sys\n\n\nURL = 'https://www.forbes.com/powerful-brands/list/'\n\n\ndef response():\n if 'linux' in sys.platform:\n # start xvfb in case no X is running. Make sure xvfb \n # is installed, otherwise this won't work!\n dryscrape.start_xvfb()\n session = dryscrape.Session()\n session.visit(URL)\n session.render(1024, 8000)\n return session.body()\n\n\ndef parse(response):\n soup = BeautifulSoup(response, 'lxml')\n return [str(item.a.text) for item in soup.find_all('td', class_='name')]\n\n\nif __name__ == '__main__':\n with open('list.txt', 'w') as f:\n f.write(','.join(parse(response())))\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"422928126","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: C:\\Devel\\OctoPrint\\OctoPrint\\src\\octoprint\\plugins\\softwareupdate\\util.py\n# Compiled at: 2020-02-26 04:08:42\n# Size of source mod 2**32: 1212 bytes\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n__author__ = 'Gina Häußge '\n__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'\n__copyright__ = 'Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License'\nfrom .exceptions import ScriptError\nimport logging\n\ndef execute(command, cwd=None, evaluate_returncode=True, **kwargs):\n do_async = kwargs.get('do_async', kwargs.get('async', False))\n import sarge\n p = None\n try:\n p = sarge.run(command, cwd=cwd, stdout=(sarge.Capture()), stderr=(sarge.Capture()), async_=do_async)\n except Exception:\n logging.getLogger(__name__).exception('Error while executing command: {}'.format(command))\n returncode = p.returncode if p is not None else None\n stdout = p.stdout.text if (p is not None and p.stdout is not None) else ''\n stderr = p.stderr.text if (p is not None and p.stderr is not None) else ''\n raise ScriptError(returncode, stdout, stderr)\n\n if evaluate_returncode:\n if p.returncode != 0:\n raise ScriptError(p.returncode, p.stdout.text, p.stderr.text)\n else:\n return do_async or (\n p.returncode, p.stdout.text, p.stderr.text)","sub_path":"pycfiles/OctoPrint-1.4.0-py2.py3-none-any/util.cpython-37.py","file_name":"util.cpython-37.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"215352559","text":"\"\"\" Base module for Management Systems classes. \"\"\"\n\nfrom abc import ABCMeta, abstractmethod\nfrom pysphere import *\nfrom pysphere.resources.vi_exception import VIException\nfrom pysphere.resources import VimService_services as VI\nfrom pysphere.vi_task import VITask\nfrom ovirtsdk.api import API\n\nclass MgmtSystemAPIBase(object):\n '''\n Base interface class for Management Systems.\n '''\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def start_vm(self, vm_name):\n '''\n Starts a vm.\n\n :param vm_name: name of the vm to be started\n :type vm_name: str\n :return: whether vm action has been initiated properly\n :rtype: boolean\n '''\n raise NotImplementedError('start_vm not implemented.')\n\n @abstractmethod\n def stop_vm(self, vm_name):\n '''\n Stops a vm.\n\n :param vm_name: name of the vm to be stopped\n :type vm_name: str\n :return: whether vm action has been initiated properly\n :rtype: boolean\n '''\n raise NotImplementedError('stop_vm not implemented.')\n\n @abstractmethod\n def create_vm(self, vm_name):\n '''\n Creates a vm.\n\n :param vm_name: name of the vm to be created\n :type vm_name: str\n :return: whether vm action has been initiated properly\n :rtype: boolean\n '''\n raise NotImplementedError('create_vm not implemented.')\n\n @abstractmethod\n def delete_vm(self, vm_name):\n '''\n Deletes a vm.\n\n :param vm_name: name of the vm to be deleted\n :type vm_name: str\n :return: whether vm action has been initiated properly\n :rtype: boolean\n '''\n raise NotImplementedError('delete_vm not implemented.')\n\n @abstractmethod\n def restart_vm(self, vm_name):\n '''\n Restart a vm.\n\n :param vm_name: name of the vm to be restarted\n :type vm_name: str\n :return: whether vm stop/start have been initiated properly\n :rtype: boolean\n '''\n raise NotImplementedError('restart_vm not implemented.')\n\n @abstractmethod\n def list_vm(self, **kwargs):\n '''\n Returns a list of vm names.\n\n :return: list of vm names\n :rtype: list\n '''\n raise NotImplementedError('list_vm not implemented.')\n\n @abstractmethod\n def info(self):\n '''\n Returns basic information about the mgmt system.\n\n :return: string representation of name/version of mgmt system.\n :rtype: str\n '''\n raise NotImplementedError('info not implemented.')\n\n @abstractmethod\n def disconnect(self):\n '''\n Disconnect the API from mgmt system.\n '''\n raise NotImplementedError('disconnect not implemented.')\n\n\nclass VMWareSystem(MgmtSystemAPIBase):\n \"\"\"\n Client to Vsphere API\n\n This class piggy backs off pysphere.\n\n Benefits of pysphere:\n - Don't need intimate knowledge w/ vsphere api itself.\n Detriments of pysphere:\n - Response often are not detailed enough. \n \"\"\"\n def __init__(self, hostname='localhost', username='root', password='rootpwd'):\n \"\"\" Initialize VMWareSystem \"\"\" \n # sanitize hostname\n if hostname.startswith('https://'):\n hostname.replace('https://', '')\n elif hostname.startswith('http://'):\n hostname.replace('http://', '')\n\n if hostname.endswith('/api'):\n hostname.replace('/api', '')\n\n self.api = VIServer()\n self.api.connect(hostname, username, password)\n\n def start_vm(self, vm_name):\n \"\"\" VMWareSystem implementation of start_vm. \"\"\"\n if vm_name is None:\n raise Exception('Could not find a VM named %s.' % vm_name)\n else:\n try:\n vm = self.api.get_vm_by_name(vm_name)\n except VIException as ex:\n raise Exception(ex)\n\n if vm.is_powered_on():\n raise Exception('Could not start %s because it\\'s already running.' % vm_name)\n else:\n vm.power_on()\n ack = vm.get_status()\n if ack == 'POWERED ON':\n return True\n return False\n\n def stop_vm(self, vm_name):\n \"\"\" VMWareSystem implementation of stop_vm. \"\"\"\n if vm_name is None:\n raise Exception('Could not find a VM named %s.' % vm_name)\n else:\n try:\n vm = self.api.get_vm_by_name(vm_name)\n except VIException as ex:\n raise Exception(ex)\n\n if vm.is_powered_off():\n raise Exception('Could not stop %s because it\\'s not running.' % vm_name)\n else:\n vm.power_off()\n ack = vm.get_status()\n if ack == 'POWERED OFF':\n return True\n return False\n\n def delete_vm(self, vm_name):\n \"\"\" VMWareSystem implementation of delete_vm. \"\"\"\n if vm_name is None:\n raise Exception('Could not find a VM named %s.' % vm_name)\n else:\n try:\n vm = self.api.get_vm_by_name(vm_name)\n except VIException as ex:\n raise Exception(ex)\n\n if vm.is_powered_on():\n raise Exception('Could not stop %s because it\\'s still running.' % vm_name)\n else:\n # When pysphere moves up to 0.1.8, we can just do:\n # vm.destroy()\n request = VI.Destroy_TaskRequestMsg()\n _this = request.new__this(vm._mor)\n _this.set_attribute_type(vm._mor.get_attribute_type())\n request.set_element__this(_this)\n rtn = self.api._proxy.Destroy_Task(request)._returnval\n\n task = VITask(rtn, self.api)\n status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])\n if status == task.STATE_SUCCESS:\n return True\n return False\n\n def create_vm(self, vm_name):\n \"\"\" VMWareSystem implementation of create_vm. \"\"\"\n #Unfortunately, there are not enough smurf slaves in the village to build this functionality yet. \n pass\n\n def restart_vm(self, vm_name):\n \"\"\" VMWareSystem implementation of restart_vm. \"\"\"\n if not self.stop_vm(vm_name):\n return False\n else:\n return self.start_vm(vm_name)\n\n def list_vm(self, **kwargs):\n \"\"\" VMWareSystem implementation of list_vm. \"\"\"\n vm_list = self.api.get_registered_vms(**kwargs)\n return [vm.split(']', 1)[-1].strip() for vm in vm_list]\n\n def info(self):\n \"\"\" VMWareSystem implementation of info. \"\"\"\n return '%s %s' % (self.api.get_server_type(), self.api.get_api_version())\n\n def disconnect(self):\n \"\"\" VMWareSystem implementation of disconnect. \"\"\"\n self.api.disconnect()\n\n\nclass RHEVMSystem(MgmtSystemAPIBase):\n \"\"\"\n Client to RHEVM API\n\n This class piggy backs off ovirtsdk.\n\n Benefits of ovirtsdk: \n - Don't need intimite knowledge w/ RHEVM api itself. \n Detriments of ovirtsdk:\n - Response to most quaries are returned as an object rather than a string. \n This makes it harder to do simple stuff like getting the status of a vm.\n - Because of this, it makes listing VMs based on **kwargs impossible \n since ovirtsdk relies on re class to find matches. \n\n I.E. List out VM with this name (positive case)\n Ideal: self.api.vms.list(name='test_vm')\n Underneath the hood: \n - ovirtsdk fetches list of all vms [ovirtsdk.infrastructure.brokers.VM object, ...]\n - ovirtsdk then tries to filter the result using re.\n - tries to look for 'name' attr in ovirtsdk.infrastructure.brokers.VM object\n - found name attribute, in this case, the type of the value of the attribute is string.\n - match() succeed in comparing the value to 'test_vm'\n\n I.E. List out VM with that's powered on (negative case)\n Ideal: self.api.vms.list(status='up')\n Underneath the hood: \n - '^same step as above except^'\n - found status attribute, in this case, the type of the value of the attribute is .\nvirtsdk.xml.params.Status\n - match() failed because class is compared to string 'up'\n\n This problem should be attributed to how RHEVM api was designed rather than how ovirtsdk handles RHEVM api responses. \n\n - Obj. are not updated after action calls.\n - I.E. \n vm = api.vms.get(name='test_vm')\n vm.status.get_state() # returns 'down'\n vm.start()\n # wait a few mins\n vm.status.get_state() # returns 'down'; wtf?\n\n vm = api.vms.get(name='test_vm')\n vm.status.get_state() # returns 'up'\n \"\"\"\n def __init__(self, hostname='localhost', username='root', password='rootpwd'):\n \"\"\" Initialize RHEVMSystem \"\"\" \n # sanitize hostname\n if not hostname.startswith('https://'):\n hostname = 'https://%s' % hostname\n if not hostname.endswith('/api'):\n hostname = '%s/api' % hostname\n\n self.api = API(url=hostname, username=username, password=password, insecure=True)\n\n def start_vm(self, vm_name=None):\n \"\"\" RHEVMSystem implementation of start_vm. \"\"\"\n if vm_name is None:\n raise Exception('Could not find a VM named %s.' % vm_name)\n else:\n vm = self.api.vms.get(name=vm_name)\n if vm is None:\n raise Exception('Could not find a VM named %s.' % vm_name)\n if vm.status.get_state() == 'up':\n raise Exception('Could not start %s because it\\'s already running.' % vm_name)\n else:\n ack = vm.start()\n if ack.get_status().get_state() == 'complete':\n return True\n return False\n\n def stop_vm(self, vm_name):\n \"\"\" RHEVMSystem implementation of stop_vm. \"\"\"\n if vm_name is None:\n raise Exception('Could not find a VM named %s.' % vm_name)\n else:\n vm = self.api.vms.get(name=vm_name)\n if vm is None:\n raise Exception('Could not find a VM named %s.' % vm_name)\n if vm.status.get_state() == 'down':\n raise Exception('Could not stop %s because it\\'s not running.' % vm_name)\n else:\n ack = vm.stop()\n if ack.get_status().get_state() == 'complete':\n return True\n return False\n\n def delete_vm(self, vm_name):\n \"\"\" RHEVMSystem implementation of delete_vm. \"\"\"\n if vm_name is None:\n raise Exception('Could not find a VM named %s.' % vm_name)\n else:\n vm = self.api.vms.get(name=vm_name)\n if vm is None:\n raise Exception('Could not find a VM named %s.' % vm_name)\n if vm.status.get_state() == 'up':\n raise Exception('Could not delete %s because it\\'s still running.' % vm_name)\n else:\n ack = vm.delete()\n if ack.get_status().get_state() == '':\n return True\n return False\n\n def create_vm(self, vm_name):\n \"\"\" RHEVMSystem implementation of create_vm. \"\"\"\n #Unfortunately, there are not enough smurf slaves in the village to build this functionality yet. \n pass\n\n def restart_vm(self, vm_name):\n \"\"\" RHEVMSystem implementation of restart_vm. \"\"\"\n if not self.stop_vm(vm_name):\n return False\n else:\n return self.start_vm(vm_name)\n\n def list_vm(self, **kwargs):\n \"\"\" RHEVMSystem implementation of list_vm. \"\"\"\n # list vm based on kwargs can be buggy\n # i.e. you can't return a list of powered on vm\n # but you can return a vm w/ a matched name\n vm_list = self.api.vms.list(**kwargs)\n return [vm.name for vm in vm_list]\n\n def info(self):\n \"\"\" RHEVMSystem implementation of info. \"\"\"\n # and we got nothing!\n pass\n\n def disconnect(self):\n \"\"\" RHEVMSystem implementation of disconnect. \"\"\"\n self.api.disconnect()\n","sub_path":"tests/common/MgmtSystem.py","file_name":"MgmtSystem.py","file_ext":"py","file_size_in_byte":12187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"509215404","text":"# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\nimport scrapy\nimport os\nfrom itemadapter import ItemAdapter\nfrom scrapy.pipelines.images import ImagesPipeline\nfrom urllib.parse import urlparse\nfrom pymongo import MongoClient\n\n\nclass LeruamerlenparserPipeline:\n \"\"\"Leroymerlin parser spider pipeline.\"\"\"\n\n def __init__(self):\n \"\"\"Constructor.\"\"\"\n client = MongoClient()\n self.mongo_base = client.goods\n\n\n def process_item(self, item, spider):\n \"\"\"Process item.\"\"\"\n collection = self.mongo_base[spider.query]\n\n collection.update_one(item, {'$setOnInsert': item}, upsert=True)\n\n return item\n\n\nclass LeroyMerlinPhotosPipeline(ImagesPipeline):\n \"\"\"Leroymerlin parser photos download pipeline.\"\"\"\n\n def get_media_requests(self, item, info):\n if item['photos']:\n for img in item['photos']:\n try:\n yield scrapy.Request(img)\n except Exception as e:\n print(e)\n\n\n def file_path(self, request, response=None, info=None, *, item=None):\n \"\"\"File path.\"\"\"\n if item:\n return f\"{item['name']}/\" + os.path.basename(urlparse(request.url).path)\n\n\n def item_completed(self, results, item, info):\n \"\"\"Item completed.\"\"\"\n if results:\n item['photos'] = [itm[1] for itm in results if itm[0]]\n\n return item\n","sub_path":"lesson_7/leruamerlenparser/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"472192370","text":"import numpy as np\nimport pandas as pd\n\nfrom statsmodels.tsa.api import VAR as _VAR\nimport statsmodels.tsa.vector_ar.util as var_util\n\n\ndef AAFT(ts, random=np.random.uniform, random_state=None):\n \"\"\"Amplitude Adjusted Fourier Transform Baseline Generator.\"\"\"\n # set random seed\n np.random.seed(random_state)\n # 2d time-series format\n _ts = ts.reshape(len(ts), -1)\n # Odd number of samples\n if len(_ts) % 2 != 0:\n _ts = _ts[1:, :]\n # Generated time-series\n ts_gen = np.empty_like(_ts)\n for i, tsi in enumerate(_ts.T):\n # Fourier Transaformation (real-valued signal)\n F_tsi = np.fft.rfft(tsi)\n # Randomization of Phase\n rv_phase = np.exp(random(0, np.pi, len(F_tsi)) * 1.0j)\n # Generation of new time-series\n F_tsi_new = F_tsi * rv_phase\n # Inverse Fourier Transformation\n ts_gen[:, i] = np.fft.irfft(F_tsi_new)\n return ts_gen\n\n\ndef VAR(ts, max_order=15):\n \"\"\"Vector Autoregressive Baseline Generator.\"\"\"\n # VAR model\n if isinstance(ts, pd.DataFrame):\n var = _VAR(ts.values)\n elif isinstance(ts, np.ndarray):\n var = _VAR(ts)\n # optimal order\n order = var.select_order(max_order)['aic']\n # fit model\n model = var.fit(order)\n # simulation\n ts_gen = var_util.varsim(model.coefs, model.intercept,\n model.sigma_u, steps=len(ts.values))\n return ts_gen\n","sub_path":"qtrader/envs/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"40196305","text":"# %load q02_country_operations/build.py\n# default imports\nimport pandas as pd\nfrom greyatomlib.olympics_project_new.q01_rename_columns.build import q01_rename_columns\n#Previous Functions\npath = './data/olympics.csv'\nOlympicsDF=q01_rename_columns(path) \n\ndef q02_country_operations(data):\n \n testing_col = data['Country']\n temp_result = []\n for value in testing_col:\n temp_result.append(value.split()[0])\n\n data['Country_Name'] = pd.Series(temp_result)\n \n return data\n\n\nq02_country_operations(OlympicsDF)\n\n\n\n","sub_path":"q02_country_operations/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"490307981","text":"# Program: calculadorDeImpostosCap03.py\n# Author: Ramon R. Valeriano\n# Description: Faremos os calculos de impostos aqui.\n# Developed: 22/04/2021 - 08:36\n\nfrom impostosCap03 import ISS, ICMS, ICPP, IKCV\nfrom orcamentoCap03 import Item, Orcamento\n\nclass Calculador_de_impostos:\n\n def realiza_calcula(self, orcamento, imposto):\n\n imposto_calculado = imposto.calcula(orcamento)\n\n return imposto_calculado\n\n\nif __name__ == '__main__':\n\n calculador = Calculador_de_impostos()\n orcamento = Orcamento()\n\n orcamento.adiciona_item(Item('ITEM - 1', 50))\n orcamento.adiciona_item(Item('ITEM - 1', 200))\n orcamento.adiciona_item(Item('ITEM - 1', 250))\n\n # ISS, ICMS\n resutado1 = calculador.realiza_calcula(orcamento, ISS())\n resutado2 = calculador.realiza_calcula(orcamento, ICMS())\n\n # ISS, ICMS\n resutado3 = calculador.realiza_calcula(orcamento, ICPP())\n resutado4 = calculador.realiza_calcula(orcamento, IKCV())\n\n print('ISS, ICMS')\n print(f'O imposto calculuado inicialmente(ISS) é R$ {resutado1}')\n print(f'O imposto calculuado inicialmente(ICMS) é R$ {resutado2}')\n\n print('ICPP, IKCV')\n print(f'O imposto calculuado inicialmente(ICPP) é R$ {resutado3}')\n print(f'O imposto calculuado inicialmente(IKCV) é R$ {resutado4}')\n\n","sub_path":"Cursos/Alura/DesignPatternsPython1/Capitulo03/Exercicios/calculadorDeImpostosCap03.py","file_name":"calculadorDeImpostosCap03.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"3029023","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n[module name here]\n~~~~~~~~~~~~~~~~~\n\n[Description here]\n\n\"\"\"\n\nfrom flask import Blueprint, render_template, g\nfrom flask.ext.login import login_required\n\nhome = Blueprint('home', __name__, template_folder='templates')\n\n\n@home.route('/')\n@home.route('/index')\n@login_required\ndef index():\n user = g.user\n posts = [\n {\n 'author': {'nickname': 'John'},\n 'body': 'Beautiful day in Portland!'\n },\n {\n 'author': {'nickname': 'Susan'},\n 'body': 'The Avengers movie was so cool!'\n }\n ]\n return render_template('index.html',\n title='Home',\n user=user,\n posts=posts)\n","sub_path":"escalante/mod_home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"466756610","text":"import re\nfrom os import getenv\nfrom time import sleep\n\nimport sqlalchemy\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\n\nfrom config import DB_CHECK_INTERVAL\n\nBase = automap_base()\nengine = create_engine(getenv('DB_URI'))\nBase.prepare(engine, reflect=True)\nOrders = Base.classes.orders\nsession = Session(engine)\n\n\ndef format_phone_number(number):\n # returns a number in the format: 9291112233\n _number = ''.join(re.findall(r'\\d+', number))\n return _number[1:] if len(_number) == 11 else _number\n\n\ndef format_phones_in_db(query):\n for order in query.yield_per(100):\n phone = format_phone_number(order.contact_phone)\n order.contact_phone_formatted = phone\n session.commit()\n\n\ndef run_db_query(func, *args, attempts=2):\n for _ in range(attempts):\n try:\n return func(*args)\n except sqlalchemy.exc.DBAPIError as exc:\n if attempts and exc.connection_invalidated:\n session.rollback()\n else:\n raise\n\n\nif __name__ == '__main__':\n run_db_query(format_phones_in_db, session.query(Orders))\n while True:\n sleep(int(DB_CHECK_INTERVAL))\n query = session.query(Orders).filter(Orders.contact_phone_formatted == None)\n run_db_query(format_phones_in_db, query)\n","sub_path":"format_phones_in_db.py","file_name":"format_phones_in_db.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"487995475","text":"import numpy as np\nimport os\nimport errno\nimport matplotlib.pyplot as plt\nfrom glob import glob\nimport librosa as lr\nimport librosa.display\n\ndata_dir = 'C:/Users/MADHUKAR/Desktop/sample/*.wav'\naudio_files = glob(data_dir)\nlen(audio_files)\nprint(audio_files)\noutput_dir = 'C:/Users/MADHUKAR/Desktop/graph'\n\naccess_rights = 0o777\n\ntry:\n os.makedirs(output_dir, access_rights, exist_ok=True)\nexcept OSError as exc:\n if exc.errno != errno.EEXIST:\n raise\n print(\"Creation of the directory %s failed\" % output_dir)\n pass\n\nelse:\n print(\"Successfully created the directory %s\" % output_dir)\n\nfor file in range(0, len(audio_files), 1):\n\n y, sr = lr.load(lr.util.example_audio_file())\n tempo, beats = librosa.beat.beat_track(y=y, sr=sr)\n\n onset_env = lr.onset.onset_strength(y, sr=sr, aggregate = np.median)\n tempo, beats = librosa.beat.beat_track(onset_envelope=onset_env, sr = sr)\n\n hop_length = 512\n plt.figure(figsize=(8, 4))\n times = lr.times_like(onset_env, sr=sr, hop_length=hop_length)\n plt.plot(times, lr.util.normalize(onset_env), label = 'Onset strength')\n plt.vlines(times[beats], 0, 1, alpha=0.5, color='r', linestyle = '--', label = 'Beats')\n plt.legend(frameon=True, framealpha=0.75)\n\n plt.xlim(15, 30)\n plt.gca().xaxis.set_major_formatter(lr.display.TimeFormatter())\n plt.tight_layout()\n plt.savefig(f'{output_dir}/Graph_{file}.png', format=\"PNG\")\n plt.show()\n\nprint(\"Done\")\n","sub_path":"Junk_Code/beat.py","file_name":"beat.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"24394627","text":"# Copyright (c) 2020 Horizon Robotics. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nfrom alf.data_structures import ActionTimeStep\nfrom .optimizer import Optimizer\n\n\nclass RandomOptimizer(Optimizer):\n def __init__(self,\n solution_dim,\n population_size,\n upper_bound=None,\n lower_bound=None):\n \"\"\"Creates a Random Optimizer\n\n Args:\n solution_dim (int): The dimensionality of the problem space\n population_size (int): The number of candidate solutions to be\n sampled at every iteration\n upper_bound (int|tf.Tensor): upper bounds for elements in solution\n lower_bound (int|tf.Tensor): lower bounds for elements in solution\n \"\"\"\n super().__init__()\n self._solution_dim = solution_dim\n self._population_size = population_size\n self._upper_bound = upper_bound\n self._lower_bound = lower_bound\n\n def obtain_solution(self, time_step: ActionTimeStep, state):\n \"\"\"Minimize the cost function provided\n\n Args:\n time_step (ActionTimeStep): the initial time_step to start rollout\n state: input state to start rollout\n \"\"\"\n init_obs = time_step.observation\n batch_size = init_obs.shape[0]\n solutions = tf.random.uniform(\n [batch_size, self._population_size, self._solution_dim],\n self._lower_bound, self._upper_bound)\n costs = self.cost_function(time_step, state, solutions)\n min_ind = tf.cast(tf.argmin(costs, axis=-1), tf.int32)\n population_ind = tf.expand_dims(min_ind, 1)\n batch_ind = tf.expand_dims(tf.range(tf.shape(solutions)[0]), 1)\n ind = tf.concat([batch_ind, population_ind], axis=1)\n solution = tf.gather_nd(solutions, ind)\n return solution\n","sub_path":"alf/optimizers/random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"225278658","text":"import logging\r\nimport argparse\r\nimport os\r\n\r\nimport boto3\r\nfrom botocore.handlers import disable_signing\r\nimport sqlalchemy as sa\r\nfrom schema import metadata, staging_ratings\r\n\r\n# Constants\r\nS3_BUCKET_NAME = 'hinge-homework'\r\nS3_KEY_FILTER = 'director-data-engineering/ratings/*'\r\nPG_HOSTNAME = 'localhost'\r\nPG_URL = f'postgresql://postgres:postgres@{PG_HOSTNAME}:5432/postgres'\r\nLOGGING_LEVEL = 'INFO'\r\nSQL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sql')\r\n\r\n\r\ndef setup_logging(log_level):\r\n \"\"\"\r\n Setup the logger\r\n :param log_level: Valid log_level for logging level.\r\n \"\"\"\r\n logging.basicConfig(\r\n level=logging.getLevelName(log_level),\r\n format='%(asctime)s %(message)s',\r\n datefmt='%m/%d/%Y %I:%M:%S %p',\r\n handlers=[logging.StreamHandler()]\r\n )\r\n\r\n\r\ndef setup_resources(pg_url):\r\n \"\"\"\r\n Setup the S3 and Postgres resources\r\n :param pg_url: url for postgres\r\n :return: tuple of s3 resource and pg engine\r\n \"\"\"\r\n # Setup s3 resource\r\n s3r = boto3.resource('s3')\r\n s3r.meta.client.meta.events.register('choose-signer.s3.*', disable_signing) # Don't need credentials\r\n # Setup sa engine\r\n engine = sa.create_engine(pg_url)\r\n # Ensure metadata is there\r\n metadata.create_all(engine)\r\n return s3r, engine\r\n\r\n\r\ndef load_raw(s3r, engine, s3_bucket_name, s3_key_filter):\r\n \"\"\"\r\n Load all of the raw data from an s3 bucket into a staging PG schema\r\n :param s3r: s3 resource\r\n :param engine: pg engine\r\n :param s3_bucket_name: name of the s3 bucket\r\n :param s3_key_filter: the key to use for filtering\r\n \"\"\"\r\n # Filtering on items in the key; will allow for unexpected file names\r\n for obj_summary in s3r.Bucket(s3_bucket_name).objects.filter(Marker=s3_key_filter):\r\n logging.info('Processing file %s', obj_summary.key)\r\n # Go through each line and prepare for insertion (for this exercise, not considering memory implications of\r\n # large dataset)\r\n obj_values = []\r\n for line in obj_summary.get()['Body'].iter_lines():\r\n line_arr = line.decode('utf-8').split('\\t') # For this exercise, assuming utf-8\r\n line_arr.append(obj_summary.key)\r\n obj_values.append(line_arr)\r\n with engine.begin() as transaction:\r\n transaction.execute(staging_ratings.insert().values(obj_values))\r\n\r\n\r\ndef create_ratings_fact(engine):\r\n \"\"\"\r\n Perform a transformation to create a fact table for the ratings data.\r\n :param engine: pg engine\r\n \"\"\"\r\n logging.info('Running fact creation')\r\n sql_file = open(os.path.join(SQL_DIR, 'ratings_fact.sql'), 'r')\r\n with engine.begin() as transaction:\r\n transaction.execute(sql_file.read())\r\n sql_file.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('-l', '--log', type=str, help='set level of logging', default=LOGGING_LEVEL,\r\n choices=list(logging._levelToName.values()), action='store')\r\n parser.add_argument('-nr', '--noraw', help=\"pass flag to turn off raw loading\", action=\"store_true\")\r\n args = parser.parse_args()\r\n\r\n setup_logging(args.log)\r\n s3, pg_engine = setup_resources(PG_URL)\r\n # If you want to skip loading the raw data, you can!\r\n if not args.noraw:\r\n load_raw(s3, pg_engine, S3_BUCKET_NAME, S3_KEY_FILTER)\r\n create_ratings_fact(pg_engine)\r\n","sub_path":"docker/code/transform_ratings.py","file_name":"transform_ratings.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"589563529","text":"#Alexander_Máni_Einarsson\r\n#06/11/19\r\n#Skilaverkefni\r\nimport random\r\n\r\non = True\r\nwhile on:\r\n print()\r\n print(\"=-=-=-> Æfingaverkefni 10 listar <-=-=-=\")\r\n print()\r\n print(\"1. Innkaupalisti \")\r\n print(\"2. Random tölur \")\r\n print(\"3. Fyrsta og síðasta \")\r\n print(\"4. Nemendur \")\r\n print(\"5. Hætta \")\r\n val = int(input(\"Veldu: \"))\r\n if val == 1:\r\n listi= []\r\n svar = \"j\"\r\n while svar != \"J\" or svar !=\"j\":\r\n print()\r\n k = input(\"Hverju viltu bæta við á listan: \")\r\n listi.append(k)\r\n svar = input(\"viltu hætta? J/N: \")\r\n listi.sort()\r\n print(listi)\r\n\r\n elif val == 2:\r\n print()\r\n listi=[]\r\n sum = 0\r\n for x in range(15):\r\n random_tala = random.randint(5, 25)\r\n sum = random_tala + sum\r\n listi.append(random_tala)\r\n listi.sort()\r\n print(\"Raðaður listi: \", listi)\r\n print(\"Hæsta stakið er: \", max(listi))\r\n print(\"Lægsta stakið er: \", min(listi))\r\n print(\"Summan er: \",sum)\r\n print(\"lengd listans er: \", len(listi))\r\n\r\n elif val == 3:\r\n print()\r\n listi = []\r\n for x in range(20):\r\n random_tala = random.randint(1, 20)\r\n print(x)\r\n listi.append(random_tala)\r\n nylisti = []\r\n nylisti.append(listi[0])\r\n nylisti.append(listi[-1])\r\n print(listi)\r\n print(nylisti)\r\n\r\n elif val == 4:\r\n print()\r\n sum = 0\r\n listi=[]\r\n while sum < 10:\r\n nafn = input(\"Skrafaðu nafn: \")\r\n if nafn in listi:\r\n print(\"Mátt ekki slá inn sama nafnið tvisvar\")\r\n else:\r\n listi.append(nafn)\r\n sum = sum +1\r\n print(listi)\r\n\r\n\r\n\r\n elif val == 5:\r\n print(\"Nú verður foritinu hætt\")\r\n quit()\r\n else:\r\n print(\"Villa hefur komið upp\")","sub_path":"py_projects/forritun/aefingaverkefni/æfingaverkefni_10(listar).py","file_name":"æfingaverkefni_10(listar).py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"615374258","text":"# to list all the primes\n\ndef showPrimes(n):\n\t\"\"\" return the list of primes\"\"\"\n\tfor i in range(2, int(n)):\n\t\tif (n % i) == 0:\n\t\t\treturn [i] + showPrimes(n/i)\n\treturn [int(n)]\n\nprint(showPrimes(12))\n\ndef sumOfPrimes(n):\n\tif n <= 1:\n\t\treturn 0 # for temporary exception handling\n\tli = showPrimes(n)\n\td = {x:li.count(x) for x in li}\n\tprint(n, \" : \" , d)\n\tkeys = d.keys()\n\tvalues = d.values()\n\toutput = 1\n\tfor k, v in zip(keys, values):\n\t\toutput *= (k**(v+1) - 1)/(k-1)\n\treturn output-n\n\ndef findAmicable(n):\n\tli = []\n\tfor i in range(2, n+1):\n\t\tpair = sumOfPrimes(i)\n\t\tif i!=pair and i == sumOfPrimes(pair): # i should not be same as pair\n\t\t\tli.append(i)\n\tprint(li)\n\tprint(sum(li))\n\nfindAmicable(10000)","sub_path":"AmicableNumbers.py","file_name":"AmicableNumbers.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"530466695","text":"\nprint(\"What is your first number?\")\ninput1 = input()\nx = int(input1)\n# May fail!\n\nprint(\"What is your second number?\")\ninput2 = input()\ny = int(input2)\n# May fail!\n\n#######################################################\n# Complete the code that calculates the product of the two numbers, and print out the statement:\n# \"The product of the two numbers is ______.\"\n\n\n\n\n\n\n\n\n\n\n\ninput(\"Press Enter to continue.\")\n","sub_path":"Lesson02/Folder02/File02-ex01.py","file_name":"File02-ex01.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"206197139","text":"import sys\nimport os\nimport time\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\nfrom csw.EventSubscriber import EventSubscriber\nfrom csw.EventPublisher import EventPublisher\nfrom csw.Parameter import Parameter\nfrom csw.Event import SystemEvent\n\n\nclass TestEventPublisher:\n count = 0\n\n # Simple test that publishes an event and subscribes to it\n # Requires that CSW services are running.\n def test_pub_sub(self):\n pub = EventPublisher()\n sub = EventSubscriber()\n\n prefix = \"CSW.assembly\"\n eventName = \"test_event\"\n eventKey = prefix + \".\" + eventName\n keyName = \"testEventValue\"\n keyType = 'IntKey'\n values = [42]\n param = Parameter(keyName, keyType, values)\n paramSet = [param]\n event = SystemEvent(prefix, eventName, paramSet)\n\n thread = sub.subscribe([eventKey], self.callback)\n pub.publish(event)\n time.sleep(1)\n e = sub.get(eventKey)\n assert (e == event)\n assert (self.count == 1)\n sub.unsubscribe([eventKey])\n thread.stop()\n\n def callback(self, systemEvent):\n self.count = self.count + 1\n print(f\"Received system event '{systemEvent.eventName}'\")\n for i in systemEvent.paramSet:\n print(f\" with values: {i.keyName}: {i.values}\")\n if systemEvent.isInvalid():\n print(\" Invalid\")\n if systemEvent.exists(\"testEventValue\"):\n p = systemEvent.get(\"testEventValue\")\n if p is not None:\n print(f\"Found: {p.keyName}\")\n","sub_path":"tests/test_event_publisher.py","file_name":"test_event_publisher.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"12897775","text":"import time\nimport matplotlib as mpl\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nmpl.use('Agg') # use Agg backend\nimport matplotlib.pyplot as plt\n\n# Import example dataset loader and SchNet model\nfrom kgcnn.data.datasets.qm9 import QM9Dataset\nfrom kgcnn.literature.Schnet import make_schnet as make_schnet\nfrom kgcnn.utils.learning import LinearLearningRateScheduler\nfrom kgcnn.utils.data import ragged_tensor_from_nested_numpy\n\n# Download and generate dataset.\n# QM9 has about 200 MB of data\n# You need at least 10 GB of RAM to load and process full dataset into memory.\ndatasets = QM9Dataset()\nlabels, nodes, edges, edge_indices, graph_state = datasets.get_graph(max_mols=10000) # max is 133885\n\n# Select LUMO as target and convert into eV from H\n# Standardize output with scikit-learn std-scaler\nlabels = labels[:, 7:8] * 27.2114\ndata_unit = 'eV'\n\n# Train Test split\nlabels_train, labels_test, nodes_train, nodes_test, edges_train, edges_test, edge_indices_train, edge_indices_test, graph_state_train, graph_state_test = train_test_split(\n labels, nodes, edges, edge_indices, graph_state, test_size=0.10, random_state=42)\ndel labels, nodes, edges, edge_indices, graph_state # Free memory after split, if possible\n\n# Convert to tf.RaggedTensor or tf.tensor\n# a copy of the data is generated by ragged_tensor_from_nested_numpy()\nnodes_train, edges_train, edge_indices_train, graph_state_train = ragged_tensor_from_nested_numpy(\n nodes_train), ragged_tensor_from_nested_numpy(edges_train), ragged_tensor_from_nested_numpy(\n edge_indices_train), tf.constant(graph_state_train)\n\nnodes_test, edges_test, edge_indices_test, graph_state_test = ragged_tensor_from_nested_numpy(\n nodes_test), ragged_tensor_from_nested_numpy(edges_test), ragged_tensor_from_nested_numpy(\n edge_indices_test), tf.constant(graph_state_test)\n\n# Standardize output with scikit-learn std-scaler\nscaler = StandardScaler(with_std=False, with_mean=True)\nlabels_train = scaler.fit_transform(labels_train)\nlabels_test = scaler.transform(labels_test)\n\n# Define input and output data\nxtrain = nodes_train, edges_train, edge_indices_train\nxtest = nodes_test, edges_test, edge_indices_test\nytrain = labels_train\nytest = labels_test\n\n# Get Model with matching input and output properties\nmodel = make_schnet(\n # Input\n input_node_shape=[None],\n input_edge_shape=[None, 20],\n input_embedding={\"nodes\": {\"input_dim\": 10, \"output_dim\": 128}},\n # Output\n output_mlp={\"use_bias\": [True, True],\n \"units\": [128, 64],\n \"activation\": ['kgcnn>shifted_softplus', 'kgcnn>shifted_softplus']},\n output_dense={\"units\": 1, \"activation\": 'linear', \"use_bias\": True},\n output_embedding={'output_mode': 'graph'},\n # Model specific\n depth=4,\n out_scale_pos=0,\n interaction_args={\"units\": 128,\n \"use_bias\": True,\n \"activation\": 'kgcnn>shifted_softplus',\n \"cfconv_pool\": \"segment_sum\",\n \"is_sorted\": False,\n \"has_unconnected\": True\n },\n)\n\n# Define learning rate and epochs\nlearning_rate_start = 0.5e-3\nlearning_rate_stop = 1e-5\nepo = 500\nepomin = 400\nepostep = 10\n\n# Compile model with optimizer and learning rate\n# The scaled metric is meant to display the inverse-scaled mae values (optional)\noptimizer = tf.keras.optimizers.Adam(lr=learning_rate_start)\ncbks = LinearLearningRateScheduler(learning_rate_start, learning_rate_stop, epomin, epo)\nmodel.compile(loss='mean_squared_error',\n optimizer=optimizer,\n metrics=['mean_absolute_error'])\nprint(model.summary())\n\n# Start training\nstart = time.process_time()\nhist = model.fit(xtrain, ytrain,\n epochs=epo,\n batch_size=128,\n callbacks=[cbks],\n validation_freq=epostep,\n validation_data=(xtest, ytest),\n verbose=2\n )\nstop = time.process_time()\nprint(\"Print Time for taining: \", stop - start)\n\n# Extract training statistics\ntrainloss = np.array(hist.history['mean_absolute_error'])\ntestloss = np.array(hist.history['val_mean_absolute_error'])\n\n# Predict lumo with model\npred_test = scaler.inverse_transform(model.predict(xtest))\ntrue_test = scaler.inverse_transform(ytest)\nmae_valid = np.mean(np.abs(pred_test - true_test))\n\n# Plot loss vs epochs\nplt.figure()\nplt.plot(np.arange(trainloss.shape[0]), trainloss, label='Training Loss', c='blue')\nplt.plot(np.arange(epostep, epo + epostep, epostep), testloss, label='Test Loss', c='red')\nplt.scatter([trainloss.shape[0]], [mae_valid], label=\"{0:0.4f} \".format(mae_valid) + \"[\" + data_unit + \"]\", c='red')\nplt.xlabel('Epochs')\nplt.ylabel('Loss ' + \"[\" + data_unit + \"]\")\nplt.title('SchNet Loss')\nplt.legend(loc='upper right', fontsize='x-large')\nplt.savefig('schnet_loss.png')\nplt.show()\n\n# Predicted vs Actual\nplt.figure()\nplt.scatter(pred_test, true_test, alpha=0.3, label=\"MAE: {0:0.4f} \".format(mae_valid) + \"[\" + data_unit + \"]\")\nplt.plot(np.arange(np.amin(true_test), np.amax(true_test), 0.05),\n np.arange(np.amin(true_test), np.amax(true_test), 0.05), color='red')\nplt.xlabel('Predicted')\nplt.ylabel('Actual')\nplt.legend(loc='upper left', fontsize='x-large')\nplt.savefig('schnet_predict.png')\nplt.show()\n","sub_path":"examples/train_schnet_qm9_lumo.py","file_name":"train_schnet_qm9_lumo.py","file_ext":"py","file_size_in_byte":5402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"461879748","text":"import FWCore.ParameterSet.Config as cms\n\nfrom Configuration.Generator.PythiaUEZ2starSettings_cfi import *\n\ngenerator = cms.EDFilter(\"Pythia6GeneratorFilter\",\n pythiaHepMCVerbosity = cms.untracked.bool(False),\n maxEventsToPrint = cms.untracked.int32(0),\n pythiaPylistVerbosity = cms.untracked.int32(0),\n filterEfficiency = cms.untracked.double(1.0),\n comEnergy = cms.double(13000.0),\n PythiaParameters = cms.PSet(\n pythiaUESettingsBlock,\n processParameters = cms.vstring('MSEL = 0 ! User defined processes', \n 'MSUB(81) = 1 ! qqbar to QQbar', \n 'MSUB(82) = 1 ! gg to QQbar', \n 'MSTP(7) = 6 ! flavour = top', \n 'PMAS(6,1) = 175. ! top quark mass',\n 'MDME(190,1) = 0 !W decay into dbar u',\n 'MDME(191,1) = 0 !W decay into dbar c',\n 'MDME(192,1) = 0 !W decay into dbar t',\n 'MDME(194,1) = 0 !W decay into sbar u',\n 'MDME(195,1) = 0 !W decay into sbar c',\n 'MDME(196,1) = 0 !W decay into sbar t',\n 'MDME(198,1) = 0 !W decay into bbar u',\n 'MDME(199,1) = 0 !W decay into bbar c',\n 'MDME(200,1) = 0 !W decay into bbar t',\n 'MDME(205,1) = 0 !W decay into bbar tp',\n 'MDME(206,1) = 1 !W decay into e+ nu_e',\n 'MDME(207,1) = 1 !W decay into mu+ nu_mu',\n 'MDME(208,1) = 1 !W decay into tau+ nu_tau'),\n # This is a vector of ParameterSet names to be read, in this order\n parameterSets = cms.vstring('pythiaUESettings', \n 'processParameters')\n ),\n ExternalDecays = cms.PSet(\n Tauola = cms.untracked.PSet(\n UseTauolaPolarization = cms.bool(True),\n InputCards = cms.PSet\n ( \n pjak1 = cms.int32(0),\n pjak2 = cms.int32(0), \n mdtau = cms.int32(0) \n )\n ),\n parameterSets = cms.vstring('Tauola')\n )\n)\n","sub_path":"Configuration/Generator/python/TTbarLepton_Tauola_13TeV_cfi.py","file_name":"TTbarLepton_Tauola_13TeV_cfi.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"481214056","text":"import time\nimport random\nimport itertools\nstart = time.time()\na = map(\"\".join, itertools.product('RGB', repeat=9))\n# print(len(a))\ndef triangle(row):\n for _ in range(len(row)-1):\n r =\"\"\n for c1, c2 in zip(row[:-1], row[1:]):\n if c1+c2 in (\"BG\", \"GB\", \"RR\"): r+=\"R\"\n elif c1+c2 in (\"GR\", 'RG', \"BB\"): r+=\"B\"\n elif c1+c2 in (\"BR\", 'RB', \"GG\"): r+=\"G\"\n row = r\n return row\n\n\ncash = {}\nfor i in a:\n cash[i] = triangle(i)\n\n\ndef big_triagle(row):\n while len(row)>9:\n r =\"\"\n for c in zip(row[:-1], row[1:], row[2:], row[3:], row[4:], row[5:], row[6:], row[7:], row[8:]):\n r += str(cash[\"\".join(c)])\n row = r\n if len(row)>1:\n res = triangle(row)\n print(res)\n return res\n else:\n print(row)\n return row\n\n\n\nlist = [\"B\",\"G\",\"R\"]\nrow = random.choices(list, k=20000)\n\nbig_triagle(row)\nend = time.time()\nprint(end-start)\n\n# triangle(row)\n\n# print(cash)","sub_path":"triagle/last_triangles_for_visual.py","file_name":"last_triangles_for_visual.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"36965462","text":"#封装主页面标签部分的方法和元素\nimport random\n\nfrom framework.basic_method.base_page import Basepage\nfrom appium import webdriver\nimport time,os,logging\nimport logging.config\n\nfrom framework.basic_method.desired_caps import appium_desired\n\nclass MainPage(Basepage):\n\n CON_LOG = os.path.abspath(os.path.dirname(os.getcwd())) + '\\\\config\\\\log.conf'\n logging.config.fileConfig(CON_LOG)\n logging = logging.getLogger()\n\n jiugui_name=\"id=>com.wineworld.winecabinetdevice:id/main_TV_WineCabinetName\" #酒柜名称\n\n # 读取酒柜名称\n def get_jiugui_name(self):\n sll=self.get_text(self.jiugui_name)\n logging.info(sll)\n return sll\n\n jiugui_name_setting_btn=\"id=>com.wineworld.winecabinetdevice:id/cabinetDevice_BT_editWineCabinetName\" #酒柜名称设置按钮\n\n #点击酒柜名称设置按钮\n def click_jiugui_name_setting_btn(self):\n self.click(self.jiugui_name_setting_btn)\n time.sleep(2)\n\n jiugui_name_input=\"id=>com.wineworld.winecabinetdevice:id/searchWine_ET_InputWineName\" #酒柜名称输入框\n jiugui_name_input02 = \"//*[@resource-id = 'com.wineworld.winecabinetdevice:id/cabinetDevice_layout_inputName_WineCabinetNameEdit']/android.widget.LinearLayout/android.widget.EditText\"\n\n #输入酒柜名称\n def type_jiugui_name_input(self,text):\n self.clear(self.jiugui_name_input02)\n self.type(self.jiugui_name_input02,text)\n\n jiugui_name_submit=\"id=>com.wineworld.winecabinetdevice:id/searchWine_TV_searchWineSub\" #酒柜名称提交\n\n #提交酒柜名称\n def click_jiugui_name_submit(self):\n self.click(self.jiugui_name_submit)\n time.sleep(2)\n\n def click_jiugui_name_submit_01(self):\n self.click(self.jiugui_name_submit)\n\n\n jiugui_name_x=\"id=>com.wineworld.winecabinetdevice:id/searchWine_IV_cleanContent\" #酒柜名称输入清空\n\n # 点击酒柜名称输入清空\n def click_jiugui_name_x(self):\n self.click(self.jiugui_name_x)\n\n #设置酒柜名称\n def set_jiugui_name(self,text):\n self.click_jiugui_name_setting_btn()\n self.type_jiugui_name_input(text)\n self.click_jiugui_name_submit()\n\n def set_jiugui_name_01(self,text):\n self.type_jiugui_name_input(text)\n self.click_jiugui_name_submit_01()\n\n notice_list_btn=\"id=>com.wineworld.winecabinetdevice:id/mainHeader_IV_msg\" #通知单标签\n\n # 点击通知单标签\n def click_notice_list_btn(self):\n self.click(self.notice_list_btn)\n time.sleep(2)\n\n notice_list_title=\"id=>com.wineworld.winecabinetdevice:id/titleGroup_TV_titleFirst\" #通知单\n notice_list_close = \"id=>com.wineworld.winecabinetdevice:id/dialogNotification_layout_close\" # 关闭通知单\n\n\n\n #读取通知单标题\n def get_notice_list_title(self):\n sll=self.get_text(self.notice_list_title)\n logging.info(sll)\n return sll\n\n # 关闭\n def click_notice_list_close_btn(self):\n self.click(self.notice_list_close)\n time.sleep(2)\n\n wine_list_btn=\"id=>com.wineworld.winecabinetdevice:id/mianWSLTAL_TV_wineSelectionList\" #选酒单按钮\n wine_list_btn_navator = \"com.wineworld.winecabinetdevice:id/cabinetDeviceWSLTAL_TV_chooseWineList\" #\n wine_list_btn_02 = \"com.wineworld.winecabinetdevice:id/wineActionList_TV_takeOut\"\n\n def get_wine_list_clickable_status(self):\n status = self.get_clickable(self.wine_list_btn_navator)\n return status\n\n #点击选酒单按钮\n def click_wine_list_btn(self):\n status = self.get_wine_list_clickable_status()\n if status:\n self.click(self.wine_list_btn_navator)\n time.sleep(2)\n else:\n self.clicks(self.wine_list_btn_02,3)\n time.sleep(2)\n\n wine_list_title=\"android.widget.TextView\" #选酒单标题\n wine_list_title02 = \"xpath=>//*[@resource-id='com.wineworld.winecabinetdevice:id/DLchooseWLLocal_layout_Base']/android.widget.LinearLayout/android.widget.LinearLayout[1]/android.widget.TextView\"\n wine_list_title03 = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/DLchooseWLLocal_layout_allWineCount_DLtitle\"]/../android.widget.TextView'\n wine_list_close = \"com.wineworld.winecabinetdevice:id/DLchooseWLLocal_close\"\n\n\n # 读取选酒单标题\n def get_wine_list_title(self):\n # pt=self.driver.find_elements_by_class_name(self.wine_list_title)\n # sll=pt[0].text\n sll = self.get_text(self.wine_list_title03)\n logging.info(sll)\n return sll\n\n def click_wine_list_close_btn(self):\n self.click(self.wine_list_close)\n time.sleep(2)\n\n wine_name=\"com.wineworld.winecabinetdevice:id/wine_TV_name\" #酒款中文名称\n wine_name_eng=\"com.wineworld.winecabinetdevice:id/wine_TV_nameEn\" #酒款英文名称\n wine_chanqu = \"com.wineworld.winecabinetdevice:id/wine_TV_area\" # 酒款产区\n wine_num=\"\" #酒款数量\n wine_take_label=\"com.wineworld.winecabinetdevice:id/wineActionList_TV_takeOut\" #选酒标签\n wine_price = \"com.wineworld.winecabinetdevice:id/wine_TV_price\" # 价格标签\n wine_pirce_list = \"com.wineworld.winecabinetdevice:id/wine_LL_priceView\" # 价格组标签\n\n #点击酒款链接\n def click_wine_link(self,num):\n nu=num-1\n el = self.driver.find_elements_by_id(self.wine_name)\n el[nu].click()\n time.sleep(3)\n self.wait(15)\n\n # 读取酒款名称\n def get_wine_name(self, num):\n nu = num - 1\n pt = self.driver.find_elements_by_id(self.wine_name)\n sll = pt[nu].text\n logging.info(sll)\n return sll\n\n # 读取酒款英文名称\n def get_wine_name_eng(self, num):\n nu=num-1\n pt = self.driver.find_elements_by_id(self.wine_name_eng)\n sll = pt[nu].text\n logging.info(sll)\n return sll\n\n # 读取酒款产区\n def get_wine_chanqu(self, num):\n nu = num - 1\n pt = self.driver.find_elements_by_id(self.wine_chanqu)\n sll = pt[nu].text\n tll = sll.split(\"»\")\n l=len(tll)\n i=0\n while i0:\n num_04=self.get_wine_num(2)\n if num==num_04:\n self.swipe_left()\n time.sleep(5)\n self.wait(15)\n else:\n break\n logging.info(num_04)\n return num_04\n\n\n\n #���取酒款年份\n def get_wine_year_01(self):\n n=2\n flag=\"N\"\n sll = \"\"\n while n>0:\n el=self.driver.find_elements_by_id(self.wine_name)\n l=len(el)\n i=0\n while i0:\n year1 = self.get_wine_year_01()\n if year1==year:\n self.swipe_left()\n time.sleep(1)\n self.wait(15)\n else:\n break\n return year1\n\n def get_wine_price_01(self):\n n = 0\n price = 0\n while True:\n el = self.driver.find_elements_by_id(self.wine_price)\n if len(el) <= 0:\n self.swipe_left()\n n = n+1\n if n > 20:\n logging.error(\"无可用价格\")\n return False\n time.sleep(8)\n else:\n a = []\n for i in range(len(el)):\n price = el[i].text\n if '年' in price and '套装' not in price:\n a.append(price)\n if len(a) > 0:\n price = a[-1]\n break\n else:\n self.swipe_left()\n time.sleep(8)\n return price\n\n def get_wine_price_02(self,price):\n\n for i in range(2):\n self.swipe_left()\n time.sleep()\n while True:\n sec_price = self.get_wine_price_01()\n if sec_price == price:\n self.swipe_left()\n time.sleep(8)\n else:\n break\n return sec_price\n\n def get_list_wine_price_status(self):\n status = self.is_element_exist(self.wine_price)\n return status\n\n wine_num_sort = 'id=>com.wineworld.winecabinetdevice:id/sortlist_LL_sortTypeCount' # 存酒数量排序\n wine_year_sort = 'id=>com.wineworld.winecabinetdevice:id/sortlist_LL_sortTypeYear' # 年份排序\n wine_price_sort = 'id=>com.wineworld.winecabinetdevice:id/sortlist_LL_sortTypePrice' # 价格排序\n shaixuan_btn = 'id=>com.wineworld.winecabinetdevice:id/sortlist_LL_filter' # 筛选按钮\n\n # 点击存酒数量排序\n def click_wine_num_sort(self):\n self.click(self.wine_num_sort)\n time.sleep(2)\n self.wait(15)\n\n # 点击年份排序\n def click_wine_year_sort(self):\n self.click(self.wine_year_sort)\n time.sleep(2)\n self.wait(15)\n\n # 点击价格排序\n def click_wine_price_sort(self):\n self.click(self.wine_price_sort)\n time.sleep(5)\n self.wait(15)\n\n # 点击筛选按钮\n def click_shaixuan_btn(self):\n self.click(self.shaixuan_btn)\n time.sleep(10)\n self.wait(15)\n\n red_wine_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"红葡萄酒\"]' # 红葡萄酒标签\n white_wine_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"白葡萄酒\"]' # 白葡萄酒标签\n sweet_wine_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"甜酒\"]' # 甜酒标签\n qipao_wine_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"起泡酒\"]' # 起泡酒标签\n\n # 点击红葡萄酒标签\n def click_red_wine_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.red_wine_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击白葡萄酒标签\n def click_white_wine_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.white_wine_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击甜酒标签\n def click_sweet_wine_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.sweet_wine_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击起泡酒标签\n def click_qipao_wine_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.qipao_wine_label)\n time.sleep(2)\n self.wait(20)\n\n France_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"法国\"]' # 法国标签\n Italy_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"意大利\"]' # 意大利标签\n American_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"美国\"]' # 美国标签\n New_zealand_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"新西兰\"]' # 新西兰标签\n Chile_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"智利\"]' # 智利标签\n Spanish_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"西班牙\"]' # 西班牙标签\n German_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"德国\"]' # 德国标签\n Australian_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"澳大利亚\"]' # 澳大利亚标签\n\n # 点击法国标签\n def click_France_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.France_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击意大利标签\n def click_Italy_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.Italy_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击美国标签\n def click_American_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.American_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击新西兰标签\n def click_New_zealand_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.New_zealand_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击智利标签\n def click_Chile_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.Chile_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击西班牙标签\n def click_Spanish_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.Spanish_label)\n time.sleep(3)\n self.wait(20)\n\n # 点击德国标签\n def click_German_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.German_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击澳大利亚标签\n def click_Australian_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.Australian_label)\n time.sleep(2)\n self.wait(20)\n\n heipinuo_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"黑皮诺\"]' # 黑皮诺标签\n meiluo_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"梅洛\"]' # 梅洛标签\n chixiazhu_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"赤霞珠\"]' # 赤霞珠标签\n pinlizhu_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"品丽珠\"]' # 品丽珠标签\n weierduo_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"味而多\"]' # 味而多标签\n leisiling_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"雷司令\"]' # 雷司令标签\n xila_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"西拉\"]' # 雷司令标签\n\n # 点击黑皮诺标签\n def click_heipinuo_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.heipinuo_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击梅洛标签\n def click_meiluo_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.meiluo_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击赤霞珠标签\n def click_chixiazhu_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.chixiazhu_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击品丽珠标签\n def click_pinlizhu_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.pinlizhu_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击味而多标签\n def click_weierduo_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.weierduo_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击雷司令标签\n def click_leisiling_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.leisiling_label)\n time.sleep(2)\n self.wait(20)\n\n # 点击西拉标签\n def click_xila_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.xila_label)\n time.sleep(2)\n self.wait(20)\n\n below_300_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"300以下\"]' # 300以下标签\n between_300_600_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"300~600\"]' # 300~600标签\n between_600_1000_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"600~1000\"]' # 600~1000标签\n between_1000_2000_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"1000~2000\"]' # 1000~2000下标签\n between_2000_5000_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"2000~5000\"]' # 2000~5000标签\n up_5000_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"5000以上\"]' # 5000以上标签\n\n # 点击300以下标签\n def click_below_300_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.below_300_label)\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n time.sleep(2)\n self.wait(20)\n\n # 300~600标签\n def click_between_300_600_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.between_300_600_label)\n time.sleep(2)\n self.wait(20)\n\n # 600~1000标签\n def click_between_600_1000_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.between_600_1000_label)\n time.sleep(2)\n self.wait(20)\n\n # 1000~2000下标签\n def click_between_1000_2000_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.between_1000_2000_label)\n time.sleep(2)\n self.wait(20)\n\n # 2000~5000标签\n def click_between_2000_5000_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.between_2000_5000_label)\n time.sleep(2)\n self.wait(20)\n\n # 5000以上标签\n def click_up_5000_label(self):\n # el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.up_5000_label)\n time.sleep(2)\n self.wait(20)\n\n def shai_xuan_swip_up(self):\n self.driver.swipe(1630, 900, 1630, 200, 500)\n time.sleep(2)\n self.wait(20)\n\n x85_per_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"85分以上\"]' # 85分以上标签\n x90_per_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"90分以上\"]'\n x95_per_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"95分以上\"]'\n full_mark_label = 'xpath=>//*[@resource-id=\"com.wineworld.winecabinetdevice:id/itemFilter_TV_name\" and @text=\"满分\"]'\n\n # 点击85分以上标签\n def click_x85_per_label(self):\n self.click(self.x85_per_label)\n time.sleep(2)\n self.wait(20)\n\n def click_x90_per_label(self):\n self.click(self.x90_per_label)\n time.sleep(2)\n self.wait(20)\n\n def click_x95_per_label(self):\n self.click(self.x95_per_label)\n time.sleep(2)\n self.wait(20)\n\n def click_full_mark_label(self):\n self.click(self.full_mark_label)\n time.sleep(2)\n self.wait(20)\n\n shai_xuan_confirm = \"id=>com.wineworld.winecabinetdevice:id/dialogWFC_TV_filter\" # 筛选确认按键\n shaixuan_remark_button = \"id=>com.wineworld.winecabinetdevice:id/dialogWFC_TV_remake\" # 重置按键\n\n\n # 点击筛选确认按键\n def click_shai_xuan_confirm(self):\n # el=el=WebDriverWait(self.driver,50,5).until(lambda x:x.find_element_by_xpath(self.shai_xuan_result))\n self.click(self.shai_xuan_confirm)\n time.sleep(8)\n\n # 点击重置按键\n def click_shaixuan_remark_button(self):\n self.click(self.shaixuan_remark_button)\n time.sleep(8)\n\n wine_page_title = \"id=>com.wineworld.winecabinetdevice:id/toptitle_TV_Title\" # 酒款页面标题\n wine_page_name = \"id=>com.wineworld.winecabinetdevice:id/wineinfo_TV_name\" # 酒款页面酒款名称\n wine_page_chanqu = \"id=>com.wineworld.winecabinetdevice:id/wineinfo_TV_area\" # 酒款页面产区\n wine_page_grape = \"id=>com.wineworld.winecabinetdevice:id/wineinfo_TV_grape\" # 酒款页面葡萄\n wine_page_price = \"id=>com.wineworld.winecabinetdevice:id/wineinfo_TV_wineWorldPrice\" # 酒款页面价格\n wine_page_name_eng = \"id=>com.wineworld.winecabinetdevice:id/wineinfo_TV_nameEN\" # 酒款页面英文名称\n wine_page_type = \"id=>com.wineworld.winecabinetdevice:id/wineinfo_TV_type\" # 酒款页面类型\n\n # 读取酒款页面标题\n def get_wine_page_title(self):\n sll = self.get_text(self.wine_page_title)\n logging.info(sll)\n return sll\n\n # 读取酒款页面酒款名称\n def get_wine_page_name(self):\n sll = self.get_text(self.wine_page_name)\n logging.info(sll)\n return sll\n\n # 酒款页面英文名称\n def get_wine_page_name_eng(self):\n sll = self.get_text(self.wine_page_name_eng)\n logging.info(sll)\n return sll\n\n # 读取酒款页面产区\n def get_wine_page_chanqu(self):\n sll = self.get_text(self.wine_page_chanqu)\n tll = sll.split('»')\n l=len(tll)\n i=0\n while icom.wineworld.winecabinetdevice:id/wineInfoPsTitle_RB_gradeAwardData\" # 酒款页面评分页面\n\n def click_wine_page_grade_page(self):\n self.click(self.wine_page_grade_page)\n time.sleep(2)\n self.wait(15)\n\n wine_page_score = \"com.wineworld.winecabinetdevice:id/itemScore_TV_scoreMark\" # 酒款评分\n\n def get_wine_page_score(self):\n self.click_wine_page_grade_page()\n pt = self.driver.find_elements_by_id(self.wine_page_score)\n l = len(pt)\n pp = []\n i = 0\n while i < l:\n sll = pt[i].text\n pp.append(sll)\n i = i + 1\n # logging.info(pp)\n i = 0\n while i < l:\n if \"-\" in pp[i]:\n pp[i] = pp[i].split('-')[1]\n if \"+\" in pp[i]:\n pp[i] = pp[i].split('+')[0]\n i = i + 1\n\n logging.info(pp)\n return pp\n\n def get_wine_detail_page_score(self):\n self.click_wine_page_grade_page()\n pt = self.driver.find_elements_by_id(self.wine_page_score)\n l = len(pt)\n score_list = [i.text.split(\"/\")[0].strip(\"+\") for i in l]\n pp = [i.split(\"-\")[0] if \"-\" in i else i for i in score_list]\n for i in score_list:\n if \"-\" in i:\n pp.extend(i.split(\"-\").strip())\n else:\n pp.append(i)\n logging.info(pp)\n return pp\n\n def compare_wine_page_score_sec(self, score_list, fen):\n if fen in score_list:\n return \"OK\"\n else:\n return \"NOT\"\n\n def compare_wine_page_score(self, score, fen):\n l = len(score)\n pp = []\n if fen == 100:\n i = 0\n while i < l:\n if float(score[i]) == fen:\n pp.append(\"OK\")\n else:\n pp.append(\"NOT\")\n i = i + 1\n else:\n i = 0\n while i < l:\n if float(score[i]) >= fen:\n pp.append(\"OK\")\n else:\n pp.append(\"NOT\")\n i = i + 1\n # logging.info(pp)\n if 'OK' in pp:\n result = \"OK\"\n else:\n result = \"NOT\"\n return result\n\n\n search_input=\"id=>com.wineworld.winecabinetdevice:id/searchWine_ET_InputWineName\" #搜索输入框\n search_icon=\"id=>com.wineworld.winecabinetdevice:id/searchWine_IV_searchIcon\" #搜索图标\n\n\n #输入关键词\n def type_search_input(self,text):\n self.clear(self.search_input)\n self.type(self.search_input,text)\n\n #执行搜索操作\n def operate_search_action(self,text):\n self.type_search_input(text)\n self.click(self.search_icon)\n time.sleep(2)\n self.wait(15)\n\n #读取关键词\n def get_name(self,data):\n text=data['关键词']\n logging.info(text)\n return text\n\n shitu_1_btn=\"id=>com.wineworld.winecabinetdevice:id/mianWSLTAL_layout_winePageView\" #视图1\n shitu_2_btn=\"id=>com.wineworld.winecabinetdevice:id/mianWSLTAL_layout_wineLayerView\" #视图2\n column_list = \"xpath=>//*[@resource-id = 'com.wineworld.winecabinetdevice:id/mian_layout_body_CabinetInfo']/android.widget.LinearLayout/android.widget.TextView\"\n filter_text = \"com.wineworld.winecabinetdevice:id/sortlist_TV_filter\"\n\n #点击视图1\n def click_shitu_1_btn(self):\n self.click(self.shitu_1_btn)\n time.sleep(3)\n\n def get_shaixuan_text(self):\n text = self.get_text(self.filter_text)\n logging.info(text)\n\n\n #点击视图2\n def click_shitu_2_btn(self):\n self.click(self.shitu_2_btn)\n time.sleep(3)\n\n\n def get_samll_view_column_index(self, num):\n a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\n if(num > len(a)-1):\n return False\n text = self.find_elements(self.column_list)[num].text\n return text\n\n\n hidden_price_btn = \"com.wineworld.winecabinetdevice:id/cabinetDeviceWSLTAL_IV_winePriceShowOrHideView\"\n hidden_price_confirm = \"\"\n hidden_price_cancel = \"\"\n no_more_tips_check_box = \"\"\n tiptool_box = \"\"\n\n def click_hide_price_btn(self):\n self.click(self.hidden_price_btn)\n time.sleep(1)\n\n def click_hidden_price_confirm(self):\n pass\n\n def click_hidden_price_cancel(self):\n pass\n\n def click_no_more_tips_check_box(self):\n pass\n\n def get_tiptool_box_element(self):\n element = self.find_element(self.tiptool_box)\n return element\n'''\n\n shitu_1_btn=\"id=>com.wineworld.winecabinetdevice:id/mianWSLTAL_layout_winePageView\" #视图1\n shitu_2_btn=\"id=>com.wineworld.winecabinetdevice:id/mianWSLTAL_layout_wineLayerView\" #视图2\n\n #点击视图1\n def click_shitu_1_btn(self):\n self.click(self.shitu_1_btn)\n time.sleep(3)\n\n #点击视图2\n def click_shitu_2_btn(self):\n self.click(self.shitu_2_btn)\n time.sleep(3)\n\n'''\n\n\n","sub_path":"PycharmProjects/Reptile/jiugui_00/pageobjects/main_page.py","file_name":"main_page.py","file_ext":"py","file_size_in_byte":30127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"57671958","text":"import calendar\nimport logging\nimport os.path\nimport time\nimport urllib.parse\nimport urllib.request\nfrom collections import OrderedDict\nfrom contextlib import contextmanager\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom typing import Any\nfrom typing import Iterable\nfrom typing import Iterator\nfrom typing import Optional\nfrom typing import Tuple\n\nimport feedparser # type: ignore\nimport requests\nfrom typing_extensions import Protocol\n\nimport reader\nfrom ._requests_utils import SessionHooks\nfrom ._requests_utils import SessionWrapper\nfrom ._types import EntryData\nfrom ._types import FeedData\nfrom ._types import ParsedFeed\nfrom ._types import ParserType\nfrom .exceptions import _NotModified\nfrom .exceptions import ParseError\nfrom .types import Content\nfrom .types import Enclosure\n\n\nlog = logging.getLogger('reader')\n\n\ndef _datetime_from_timetuple(tt: time.struct_time) -> datetime:\n return datetime.utcfromtimestamp(calendar.timegm(tt))\n\n\ndef _get_updated_published(\n thing: Any, is_rss: bool\n) -> Tuple[Optional[datetime], Optional[datetime]]:\n def convert(key: str) -> Any:\n # feedparser.FeedParserDict.get('updated') defaults to published\n # for historical reasons; \"key in thing\" bypasses that\n value = thing[key] if key in thing else None\n return _datetime_from_timetuple(value) if value else None\n\n updated = convert('updated_parsed')\n published = convert('published_parsed')\n\n if published and not updated and is_rss:\n updated, published = published, None\n\n return updated, published\n\n\ndef _make_entry(\n feed_url: str, entry: Any, is_rss: bool\n) -> EntryData[Optional[datetime]]:\n id = entry.get('id')\n\n # (entry.id) is not actually required for RSS;\n # is, so we fall back to it.\n # https://github.com/lemon24/reader/issues/170\n # http://www.詹姆斯.com/blog/2006/08/rss-dup-detection\n if not id and is_rss:\n id = entry.get('link')\n log.debug(\n \"parse %s: RSS entry does not have (gu)id, falling back to link\", feed_url\n )\n\n if not id:\n raise ParseError(feed_url, message=\"entry with no id or link fallback\")\n\n updated, published = _get_updated_published(entry, is_rss)\n\n content = []\n for data in entry.get('content', ()):\n data = {k: v for k, v in data.items() if k in ('value', 'type', 'language')}\n content.append(Content(**data))\n\n enclosures = []\n for data in entry.get('enclosures', ()):\n data = {k: v for k, v in data.items() if k in ('href', 'type', 'length')}\n if 'length' in data:\n try:\n data['length'] = int(data['length'])\n except (TypeError, ValueError):\n del data['length']\n enclosures.append(Enclosure(**data))\n\n return EntryData(\n feed_url,\n id,\n updated,\n entry.get('title'),\n entry.get('link'),\n entry.get('author'),\n published,\n entry.get('summary'),\n tuple(content),\n tuple(enclosures),\n )\n\n\n# https://pythonhosted.org/feedparser/character-encoding.html#handling-incorrectly-declared-encodings\n_THINGS_WE_CARE_ABOUT_BUT_ARE_SURVIVABLE = (\n feedparser.CharacterEncodingOverride,\n feedparser.NonXMLContentType,\n)\n\n\ndef _process_feed(\n url: str, d: Any\n) -> Tuple[FeedData, Iterable[EntryData[Optional[datetime]]]]:\n\n if d.get('bozo'):\n exception = d.get('bozo_exception')\n if isinstance(exception, _THINGS_WE_CARE_ABOUT_BUT_ARE_SURVIVABLE):\n log.warning(\"parse %s: got %r\", url, exception)\n else:\n raise ParseError(url, message=\"error while parsing feed\") from exception\n\n if not d.version:\n raise ParseError(url, message=\"unknown feed type\")\n\n is_rss = d.version.startswith('rss')\n updated, _ = _get_updated_published(d.feed, is_rss)\n\n feed = FeedData(\n url, updated, d.feed.get('title'), d.feed.get('link'), d.feed.get('author'),\n )\n # This must be a list, not a generator expression,\n # otherwise the user may get a ParseError when calling\n # next(parse_result.entries), i.e. after parse() returned.\n entries = [_make_entry(url, e, is_rss) for e in d.entries]\n\n return feed, entries\n\n\ndef parse_feed(\n url: str, *args: Any, **kwargs: Any\n) -> Tuple[FeedData, Iterable[EntryData[Optional[datetime]]]]:\n \"\"\"Like feedparser.parse(), but return a feed and entries,\n and re-raise bozo_exception as ParseError.\n\n url is NOT passed to feedparser; args and kwargs are.\n\n \"\"\"\n # feedparser content sanitization and relative link resolution should be ON.\n # https://github.com/lemon24/reader/issues/125\n # https://github.com/lemon24/reader/issues/157\n result = feedparser.parse(\n *args, resolve_relative_uris=True, sanitize_html=True, **kwargs,\n )\n return _process_feed(url, result)\n\n\nclass Parser:\n\n user_agent = (\n f'python-reader/{reader.__version__} (+https://github.com/lemon24/reader)'\n )\n\n def __init__(self) -> None:\n self.parsers: 'OrderedDict[str, ParserType]' = OrderedDict()\n self.session_hooks = SessionHooks()\n\n def mount_parser(self, prefix: str, parser: ParserType) -> None:\n self.parsers[prefix] = parser\n keys_to_move = [k for k in self.parsers if len(k) < len(prefix)]\n for key in keys_to_move:\n self.parsers[key] = self.parsers.pop(key)\n\n def get_parser(self, url: str) -> ParserType:\n for prefix, parser in self.parsers.items():\n if url.lower().startswith(prefix.lower()):\n return parser\n raise ParseError(url, message=\"no parser for URL\")\n\n def __call__(\n self,\n url: str,\n http_etag: Optional[str] = None,\n http_last_modified: Optional[str] = None,\n ) -> ParsedFeed:\n return self.get_parser(url)(url, http_etag, http_last_modified)\n\n def make_session(self) -> SessionWrapper:\n session = SessionWrapper(hooks=self.session_hooks.copy())\n if self.user_agent:\n session.session.headers['User-Agent'] = self.user_agent\n return session\n\n\n@contextmanager\ndef wrap_exceptions(url: str, when: str) -> Iterator[None]:\n try:\n yield\n except (ParseError, _NotModified):\n # reader exceptions are pass-through\n raise\n except OSError as e:\n # requests.RequestException is also a subclass of OSError\n raise ParseError(url, message=f\"error {when}\") from e\n except Exception as e:\n raise ParseError(url, message=f\"unexpected error {when}\") from e\n\n\n@dataclass\nclass FileParser:\n\n \"\"\"Bare path and file:// URI parser, with support for feed roots,\n per https://github.com/lemon24/reader/issues/155\n\n \"\"\"\n\n feed_root: str\n\n def __post_init__(self) -> None:\n # give feed_root checks a chance to fail early\n self._normalize_url('known-good-feed-url')\n\n def __call__(self, url: str, *args: Any, **kwargs: Any) -> ParsedFeed:\n try:\n normalized_url = self._normalize_url(url)\n except ValueError as e:\n raise ParseError(url, message=str(e)) from None\n\n with wrap_exceptions(url, \"while reading feed\"):\n with open(normalized_url, 'rb') as file:\n feed, entries = parse_feed(url, file)\n\n return ParsedFeed(feed, entries)\n\n def _normalize_url(self, url: str) -> str:\n path = _extract_path(url)\n if self.feed_root:\n path = _resolve_root(self.feed_root, path)\n if _is_windows_device_file(path):\n raise ValueError(\"path must not be a device file\")\n return path\n\n\ndef _extract_path(url: str) -> str:\n \"\"\"Transform a file URI or a path to a path.\"\"\"\n\n url_parsed = urllib.parse.urlparse(url)\n\n if url_parsed.scheme == 'file':\n if url_parsed.netloc not in ('', 'localhost'):\n raise ValueError(\"unknown authority for file URI\")\n # TODO: maybe disallow query, params, fragment too, to reserve for future uses\n\n return urllib.request.url2pathname(url_parsed.path)\n\n if url_parsed.scheme:\n # on Windows, drive is the drive letter or UNC \\\\host\\share;\n # on POSIX, drive is always empty\n drive, _ = os.path.splitdrive(url)\n\n if not drive:\n # should end up as the same type as \"no parsers were found\", maybe\n raise ValueError(\"unknown scheme for file URI\")\n\n # we have a scheme, but we're on Windows and url looks like a path\n return url\n\n # no scheme, treat as a path\n return url\n\n\ndef _is_abs_path(path: str) -> bool:\n \"\"\"Return True if path is an absolute pathname.\n\n Unlike os.path.isabs(), return False on Windows if there's no drive\n (e.g. \"\\\\path\").\n\n \"\"\"\n is_abs = os.path.isabs(path)\n has_drive = os.name != 'nt' or os.path.splitdrive(path)[0]\n return all([is_abs, has_drive])\n\n\ndef _is_rel_path(path: str) -> bool:\n \"\"\"Return True if path is a relative pathname.\n\n Unlike \"not os.path.isabs()\", return False on windows if there's a drive\n (e.g. \"C:path\").\n\n \"\"\"\n is_abs = os.path.isabs(path)\n has_drive = os.name == 'nt' and os.path.splitdrive(path)[0]\n return not any([is_abs, has_drive])\n\n\ndef _resolve_root(root: str, path: str) -> str:\n \"\"\"Resolve a path relative to a root, and normalize the result.\n\n This is a path computation, there's no checks perfomed on the arguments.\n\n It works like os.normcase(os.path.normpath(os.path.join(root, path))),\n but with additional restrictions:\n\n * root must be absolute.\n * path must be relative.\n * Directory traversal above the root is not allowed;\n https://en.wikipedia.org/wiki/Directory_traversal_attack\n\n Symlinks are allowed, as long as they're under the root.\n\n Note that the '..' components are collapsed with no regard for symlinks.\n\n \"\"\"\n\n # this implementation is based on the requirements / notes in\n # https://github.com/lemon24/reader/issues/155#issuecomment-672324186\n\n if not _is_abs_path(root):\n raise ValueError(f\"root must be absolute: {root!r}\")\n if not _is_rel_path(path):\n raise ValueError(f\"path must be relative: {path!r}\")\n\n root = os.path.normcase(os.path.normpath(root))\n\n # we normalize the path **before** symlinks are resolved;\n # i.e. it behaves as realpath -L (logical), not realpath -P (physical).\n # https://docs.python.org/3/library/os.path.html#os.path.normpath\n # https://stackoverflow.com/questions/34865153/os-path-normpath-and-symbolic-links\n path = os.path.normcase(os.path.normpath(os.path.join(root, path)))\n\n # this means we support symlinks, as long as they're under the root\n # (the target itself may be outside).\n\n # if we want to prevent symlink targets outside root,\n # we should do it here.\n\n if not path.startswith(root):\n raise ValueError(f\"path cannot be outside root: {path!r}\")\n\n return path\n\n\n# from https://github.com/pallets/werkzeug/blob/b45ac05b7feb30d4611d6b754bd94334ece4b1cd/src/werkzeug/utils.py#L40\n_windows_device_files = (\n \"CON\",\n \"AUX\",\n \"COM1\",\n \"COM2\",\n \"COM3\",\n \"COM4\",\n \"LPT1\",\n \"LPT2\",\n \"LPT3\",\n \"PRN\",\n \"NUL\",\n)\n\n\ndef _is_windows_device_file(path: str) -> bool:\n if os.name != 'nt':\n return False\n filename = os.path.basename(os.path.normpath(path)).upper()\n return filename in _windows_device_files\n\n\nclass _MakeSession(Protocol):\n # https://github.com/python/mypy/issues/708#issuecomment-647124281 workaround\n def __call__(self) -> SessionWrapper: # pragma: no cover\n ...\n\n\ndef caching_get(\n session: SessionWrapper,\n url: str,\n http_etag: Optional[str] = None,\n http_last_modified: Optional[str] = None,\n **kwargs: Any,\n) -> Tuple[requests.Response, Optional[str], Optional[str]]:\n headers = dict(kwargs.pop('headers', {}))\n if http_etag:\n headers.setdefault('If-None-Match', http_etag)\n if http_last_modified:\n headers.setdefault('If-Modified-Since', http_last_modified)\n\n response = session.get(url, headers=headers, **kwargs)\n\n try:\n response.raise_for_status()\n except Exception as e:\n raise ParseError(url, message=\"bad HTTP status code\") from e\n\n if response.status_code == 304:\n raise _NotModified(url)\n\n http_etag = response.headers.get('ETag', http_etag)\n http_last_modified = response.headers.get('Last-Modified', http_last_modified)\n\n return response, http_etag, http_last_modified\n\n\n@dataclass\nclass HTTPParser:\n\n \"\"\"\n http(s):// parser that uses Requests.\n\n Following the implementation in:\n https://github.com/kurtmckee/feedparser/blob/develop/feedparser/http.py\n\n \"Porting\" notes:\n\n No need to add Accept-encoding (requests seems to do this already).\n\n No need to add Referer / User-Agent / Authorization / custom request\n headers, as they are not exposed in the Parser.__call__() interface\n (not yet, at least).\n\n We should add:\n\n * If-None-Match (http_etag)\n * If-Modified-Since (http_last_modified)\n * Accept (feedparser.(html.)ACCEPT_HEADER)\n * A-IM (\"feed\")\n\n \"\"\"\n\n make_session: _MakeSession\n\n def __call__(\n self,\n url: str,\n http_etag: Optional[str] = None,\n http_last_modified: Optional[str] = None,\n ) -> ParsedFeed:\n request_headers = {'Accept': feedparser.http.ACCEPT_HEADER, 'A-IM': 'feed'}\n\n # TODO: maybe share the session in the parser?\n # TODO: timeouts!\n\n with self.make_session() as session:\n with wrap_exceptions(url, \"while getting feed\"):\n response, http_etag, http_last_modified = caching_get(\n session,\n url,\n http_etag,\n http_last_modified,\n headers=request_headers,\n stream=True,\n )\n\n response_headers = response.headers.copy()\n response_headers.setdefault('content-location', response.url)\n\n # Some feeds don't have a content type, which results in\n # feedparser.NonXMLContentType being raised. There are valid feeds\n # with no content type, so we set it anyway and hope feedparser\n # fails in some other way if the feed really is broken.\n # https://github.com/lemon24/reader/issues/108\n response_headers.setdefault('content-type', 'text/xml')\n\n # The content is already decoded by requests/urllib3.\n response_headers.pop('content-encoding', None)\n response.raw.decode_content = True\n\n with wrap_exceptions(url, \"while reading feed\"), response:\n feed, entries = parse_feed(\n url, response.raw, response_headers=response_headers,\n )\n\n return ParsedFeed(feed, entries, http_etag, http_last_modified)\n\n\ndef default_parser(feed_root: Optional[str] = None) -> Parser:\n parser = Parser()\n http_parser = HTTPParser(parser.make_session)\n parser.mount_parser('https://', http_parser)\n parser.mount_parser('http://', http_parser)\n if feed_root is not None:\n # empty string means catch-all\n parser.mount_parser('', FileParser(feed_root))\n return parser\n","sub_path":"src/reader/_parser.py","file_name":"_parser.py","file_ext":"py","file_size_in_byte":15292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"116450499","text":"from textwrap import dedent\nimport json\nimport os\nimport subprocess\nimport sublime # pylint: disable=import-error\nimport sublime_plugin # pylint: disable=import-error\n\nIMPORT_JS_ENVIRONMENT = {}\nDAEMON = None\nEXECUTABLE = 'importjsd'\n\n\ndef extract_path():\n if 'SHELL' in os.environ:\n # We have to delimit the PATH output with markers because\n # text might be output during shell startup.\n out = subprocess.Popen(\n [os.environ['SHELL'], '-l', '-c', 'echo \"__SUBL_PATH__${PATH}__SUBL_PATH__\"'],\n env=os.environ,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n ).communicate()[0].decode()\n path = out.split('__SUBL_PATH__', 2)\n\n if len(path) > 1:\n return path[1]\n\n return ''\n else:\n return os.environ['PATH']\n\ndef plugin_loaded():\n global IMPORT_JS_ENVIRONMENT\n\n IMPORT_JS_ENVIRONMENT = dict(os.environ).copy()\n IMPORT_JS_ENVIRONMENT.update({\n 'LC_ALL': 'en_US.UTF-8',\n 'LC_CTYPE': 'UTF-8',\n 'LANG': 'en_US.UTF-8',\n })\n\n path_env_variable = extract_path()\n\n settings = sublime.load_settings('ImportJS.sublime-settings')\n setting_paths = settings.get('paths')\n if setting_paths:\n path_env_variable = ':'.join(setting_paths) + ':' + path_env_variable\n\n IMPORT_JS_ENVIRONMENT.update({\n 'PATH': path_env_variable,\n })\n\n print('ImportJS loaded with environment:')\n print(IMPORT_JS_ENVIRONMENT)\n\ndef plugin_unloaded():\n global DAEMON\n print('Stopping ImportJS daemon process')\n DAEMON.terminate()\n DAEMON = None\n\ndef no_executable_error(executable):\n return dedent('''\n Couldn't find executable {executable}.\n\n Make sure you have the `{executable}` binary installed (`npm install\n import-js -g`).\n\n If it is installed but you still get this message, and you are using\n something like nvm or nodenv, you probably need to configure your PATH\n correctly. Make sure that the code that sets up your PATH for these\n tools is located in .bash_profile, .zprofile, or the equivalent file\n for your shell.\n\n Alternatively, you might have to set the `paths` option in your\n ImportJS package user settings. Example:\n\n {{\n \"paths\": [\"/Users/USERNAME/.nvm/versions/node/v4.4.3/bin\"]\n }}\n\n To see where the {executable} binary is located, run `which {executable}`\n from the command line in your project's root.\n '''.format(executable=executable)).strip()\n\n\nclass ImportJsReplaceCommand(sublime_plugin.TextCommand):\n def run(self, edit, characters):\n self.view.replace(edit, sublime.Region(0, self.view.size()), characters)\n\n\nclass ImportJsCommand(sublime_plugin.TextCommand):\n def project_root(self):\n return self.view.window().extract_variables()['folder']\n\n def start_or_get_daemon(self):\n global DAEMON\n if DAEMON is not None:\n return DAEMON\n\n is_windows = os.name == 'nt'\n\n try:\n DAEMON = subprocess.Popen(\n [EXECUTABLE, 'start', '--parent-pid', str(os.getppid())],\n cwd=self.project_root(),\n env=IMPORT_JS_ENVIRONMENT,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=is_windows\n )\n # The daemon process will print one line at startup of the command,\n # something like \"DAEMON active. Logs will go to [...]\". We need to\n # ignore this line so that we can expect json output when running\n # commands.\n DAEMON.stdout.readline()\n\n return DAEMON\n except FileNotFoundError as exception:\n if str(exception).find(EXECUTABLE) > -1:\n # If the executable is in the error message, then we believe\n # that the executable cannot be found and show a more helpful\n # message.\n sublime.error_message(no_executable_error(EXECUTABLE))\n else:\n # Something other than the executable cannot be found, so we\n # pass through the original message.\n sublime.error_message(exception.strerror)\n raise exception\n\n def run(self, edit, **args):\n current_file_contents = self.view.substr(\n sublime.Region(0, self.view.size()))\n\n cmd = args.get('command')\n payload = {\n \"command\": cmd,\n \"pathToFile\": self.view.file_name(),\n \"fileContent\": current_file_contents,\n }\n\n if(cmd == 'word' or cmd == 'goto'):\n payload[\"commandArg\"] = self.view.substr(\n self.view.word(self.view.sel()[0]))\n\n if cmd == 'add':\n payload[\"commandArg\"] = args.get('imports')\n\n\n print(payload)\n process = self.start_or_get_daemon()\n process.stdin.write((json.dumps(payload) + '\\n').encode('utf-8'))\n process.stdin.flush()\n result_json = process.stdout.readline().decode('utf-8')\n print(result_json)\n\n result = json.loads(result_json)\n\n if result.get('error'):\n sublime.error_message(\n 'Error when executing importjs:\\n\\n' + result.get('error'))\n return\n\n if result.get('messages'):\n sublime.status_message('\\n'.join(result.get('messages')))\n if result.get('unresolvedImports'):\n def handle_resolved_imports(resolved_imports):\n args['command'] = 'add'\n args['imports'] = resolved_imports\n self.run(edit, **args)\n self.view.run_command(\"import_js_replace\",\n {\"characters\": result.get('fileContent')})\n self.ask_to_resolve(result.get('unresolvedImports'),\n handle_resolved_imports)\n return\n\n if cmd == 'goto':\n self.view.window().open_file(result.get('goto'))\n else:\n self.view.run_command(\"import_js_replace\",\n {\"characters\": result.get('fileContent')})\n\n def ask_to_resolve(self, unresolved_imports, on_resolve):\n resolved = {}\n unresolved_iter = iter(unresolved_imports)\n\n def ask_recurse(word):\n if not word:\n on_resolve(resolved)\n return\n\n def on_done(i):\n if i > -1:\n resolved[word] = unresolved_imports[word][i]['data']\n ask_recurse(next(unresolved_iter, None))\n\n self.view.show_popup_menu(\n list(map(lambda imp: imp.get('displayName'),\n unresolved_imports[word])),\n on_done\n )\n\n ask_recurse(next(unresolved_iter, None))\n","sub_path":"import-js.py","file_name":"import-js.py","file_ext":"py","file_size_in_byte":6873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"529653343","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 20 16:12:38 2020\n\n@author: Miyazaki\n\"\"\"\n\nimport os, cv2\nimport sys\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as pat\nfrom tkinter import filedialog\nimport tkinter \nfrom tkinter import messagebox\nimport os.path\nimport time \nimport numpy as np\nfrom tqdm import tqdm\nimport scipy.stats\nimport datetime\nfrom PIL import Image, ImageTk\nfrom keras.models import load_model\nfrom keras.preprocessing.image import img_to_array, load_img\nfrom keras import backend as K \nfrom keras.preprocessing.image import array_to_img, img_to_array, load_img\n\n\n####functions####\ndef rgb_to_gray(src):\n # obtain individual values\n b, g, r = src[:,:,0], src[:,:,1], src[:,:,2]\n # RGB to gray\n return np.array(0.2989 * r + 0.5870 * g + 0.1140 * b, dtype='float32')\n\ndef sliding_window(img, patch_size =[100, 100], istep =25, jstep=25, scale =1.0):\n Ni, Nj=[int(scale*s) for s in patch_size]\n #リスト内包表記でスケール変換\n for i in range(0, img.shape[0] - Ni, istep):\n #ここではスライディングウィンドウを横に何個設けるか計算してiに代入\n for j in range(0, img.shape[1]- Ni, jstep):\n #同じく縦にいくつか\n patch = img[i:i + Ni, j:j+Nj]\n #一つのパッチ\n #if scale != 1:\n #patch = transform.resize(patch, patch_size)\n PILpatch = Image.fromarray(np.uint8(patch))\n yield (i, j), patch, PILpatch\n \n \ndef csv_file_read(filepath):\n file_dir, file_name = os.path.split(filepath)\n base, ext = os.path.splitext(file_name)\n if ext == '.csv':\n data = pd.read_csv(filepath, index_col = 0)\n return data\n else:\n return messagebox.showinfo('error',\n 'selected file is not csv file')\n \n \ndef Grad_Cam(input_model, x, layer_name):\n\n # 前処理\n X = np.expand_dims(x, axis=0)\n X = X.astype('float32')\n preprocessed_input = X / 255.0\n # 予測クラスの算出\n predictions = model.predict(preprocessed_input)\n class_idx = np.argmax(predictions[0])\n class_output = model.output[:, class_idx]\n # 勾配を取得\n conv_output = model.get_layer(layer_name).output # layer_nameのレイヤーのアウトプット\n grads = K.gradients(class_output, conv_output)[0] # gradients(loss, variables) で、variablesのlossに関しての勾配を返す\n gradient_function = K.function([model.input], [conv_output, grads]) # model.inputを入力すると、conv_outputとgradsを出力する関数\n output, grads_val = gradient_function([preprocessed_input])\n output, grads_val = output[0], grads_val[0]\n # 重みを平均化して、レイヤーのアウトプットに乗じる\n weights = np.mean(grads_val, axis=(0, 1))\n cam = np.dot(output, weights)\n # 画像化してヒートマップにして合成\n cam = cv2.resize(cam, (100, 100), cv2.INTER_LINEAR) # 画像サイズは200で処理したので\n cam = np.maximum(cam, 0) \n cam = cam / cam.max()\n jetcam = cv2.applyColorMap(np.uint8(255 * cam), cv2.COLORMAP_JET) # モノクロ画像に疑似的に色をつける\n jetcam = cv2.cvtColor(jetcam, cv2.COLOR_BGR2RGB) # 色をRGBに変換\n jetcam = (np.float32(jetcam) + x / 2) # もとの画像に合成\n return jetcam\n\n#################################################\n \n \n\n####2-1 select ROI csv file####\nroot = tkinter.Tk()\nroot.withdraw()\n#initial directory\ndir = \"C:/Users/miyas/desktop\"\nmessagebox.showinfo('selectfiles', 'select csvfile for ROI setting')\nROI_file_path = tkinter.filedialog.askopenfilename(initialdir = dir)\nROI_file_dir = os.path.dirname(ROI_file_path)\n\nif ROI_file_path == \"\":\n messagebox.showinfo('cancel', 'stop before ROI setting')\n sys.exit()\n\n\n\n####ROI setting###\nroi_data = csv_file_read(ROI_file_path)\nroi_data['left'] = roi_data['BX']\nroi_data['right'] = roi_data['BX'] + roi_data['Width']\nroi_data['low'] = roi_data['BY'] \nroi_data['high'] = roi_data['BY'] + roi_data['Height']\n\nworm1_roi = roi_data.loc[1]['left':'high']\nworm2_roi = roi_data.loc[2]['left':'high']\nworm3_roi = roi_data.loc[3]['left':'high']\nROI_list = list([worm1_roi, worm2_roi, worm3_roi])\n\n###2-2 select images###\nmessagebox.showinfo('selectfiles', 'select analyzing image')\nimage_file_path = tkinter.filedialog.askopenfilename(initialdir = ROI_file_dir)\nimage_directory = os.path.dirname(image_file_path)\n\nif image_file_path == \"\":\n messagebox.showinfo('cancel', 'Can not do image subtraction')\n sys.exit()\n\n###2-3, select model###\nmessagebox.showinfo('selectfiles', 'select your trained model')\nmodel_file_path = tkinter.filedialog.askopenfilename(initialdir = dir)\nmodel=load_model(model_file_path)\n\n\n####get filelist####\nos.chdir(image_directory)\nfilelist = os.listdir('.')\nfilelist = [i for i in filelist if os.path.splitext(i)[1] == '.jpg' \\\n or os.path.splitext(i)[1] == '.png']\n\nt1 = time.time() \n\n#worm detection \nfor n in tqdm(range(len(filelist)-1)):\n image1 = cv2.imread(filelist[n])\n for m in ROI_list:\n subimage_crop = 0\n left, right, low, high = int(m['left']),\\\n int(m['right']),int(m['low']),int(m['high'])\n subimage_crop = image1[low:high,left:right]\n indices,cvpatch,patches = zip(*sliding_window(subimage_crop))\n labels = []\n for o in tqdm(patches):\n img_nad = img_to_array(o)/255\n #transform to 4D\n img_nad = img_nad[None, ...]\n pred = model.predict(img_nad)\n label = model.predict_classes(img_nad)\n label = int(label[0][0])\n labels.append(label)\n labels = np.array(labels)\n fig, ax = plt.subplots()\n ax.imshow(subimage_crop, cmap = 'gray')\n ax.axis('off')\n Ni, Nj = [100,100]\n indices = np.array(list(indices))\n for p, q in tqdm(indices[labels == 1]):\n centerx = q + Nj/2\n centery = p + Ni/2\n c = pat.Circle((centerx,centery), radius=2, fc='g', ec='r')\n ax.add_patch(c)\n for k in cvpatch:\n test_image = cv2.resize(k, (100, 100))\n imagea = Grad_Cam(model, test_image, 'conv2d_12') \n weight = rgb_to_gray(imagea)\n weight -= np.mean(weight)\n plt.imshow(weight)\nt2 = time.time()\nelapsed_time = t2-t1\nprint(f\"経過時間:{elapsed_time}\")","sub_path":"Image_analysis/Background_Subtraction/keras_worm_detector_cropped_ver0.1.py","file_name":"keras_worm_detector_cropped_ver0.1.py","file_ext":"py","file_size_in_byte":6458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"173309851","text":"###################################################################################\r\n### merge.crispr.gi.py ###\r\n###################################################################################\r\n# curate weissman's cell paper of dual crispr knockout\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\nimport utility as util\r\n\r\n\r\nproj_path = 'D:/projects/DLCell'\r\nnbt_path = os.path.join(proj_path, 'data/curated/crispr.doubleKO.nbt3834.geno.pheno.norm.dense.csv')\r\ncell_path = os.path.join(proj_path, 'data/curated/crispr.doubleKO.cell.geno.pheno.norm.dense.csv')\r\nout_dir = os.path.join(proj_path, 'data/curated')\r\n\r\n############################## function #############################\r\ndef mergeScoreTable(neg2keep, **scores):\r\n '''\r\n Merge phenotype score table from different datasets.\r\n '''\r\n names = scores.keys()\r\n scoretable = []\r\n for name in names:\r\n scoretable.append(scores[name] if neg2keep == name else util.rmNegative(scores[name]))\r\n return pd.concat(scoretable, axis=0, ignore_index=True)\r\n\r\n\r\n############################## main #############################\r\ncrispr_nbt = pd.read_csv(nbt_path)\r\ncrispr_cell = pd.read_csv(cell_path)\r\ncrispr_merge = mergeScoreTable(neg2keep='cell', nbt=crispr_nbt, cell=crispr_cell)\r\n# util.plotDist(merge=crispr_merge)\r\ncrispr_merge_sparse, duptable = util.createTrainingTable(crispr_merge, duplicate='average')\r\ncrispr_merge_sparse.to_csv(os.path.join(out_dir, 'crispr.doubleKO.merged.geno.pheno.norm.sparse.csv'), index=None)\r\nduptable.to_csv(os.path.join(out_dir, 'crispr.doubleKO.merged.duplicate.csv'), index=None)","sub_path":"code/preprocess/curate.crispr.gi/merge.crispr.gi.py","file_name":"merge.crispr.gi.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"197224335","text":"import logging\nimport socket\nimport json\n\nimport boto\nimport boto.s3.connection\n\nlogger = logging.getLogger(__name__)\n\n\ndef make_boto_dict(s3_args):\n \"\"\"Create a dict of keyword parameters suitable for passing into a boto.connect_s3 call using the supplied args.\"\"\"\n return {\"host\": s3_args.s3_host,\n \"port\": s3_args.s3_port,\n \"is_secure\": False,\n \"calling_format\": boto.s3.connection.OrdinaryCallingFormat()}\n\n\ndef get_s3_connection(boto_dict):\n \"\"\"Test the connection to S3 as described in the args, and return\n the current user id and the connection object.\n In general we are more concerned with informing the user why the\n connection failed, rather than raising exceptions. Users should always\n check the return value and make appropriate decisions.\n If set, fail_on_boto will not suppress boto exceptions. Used when verifying\n credentials.\n Returns\n -------\n s3_conn : S3Connection\n A connection to the s3 endpoint. None if a connection error occurred.\n \"\"\"\n s3_conn = boto.connect_s3(**boto_dict)\n try:\n s3_conn.get_canonical_user_id()\n # reliable way to test connection and access keys\n return s3_conn\n except socket.error as e:\n logger.error(\"Failed to connect to S3 host %s:%i. Please check network and host address. (%s)\",\n s3_conn.host, s3_conn.port, e)\n raise\n except boto.exception.S3ResponseError as e:\n if e.error_code == \"InvalidAccessKeyId\":\n logger.error(\"Supplied access key %s is not for a valid S3 user.\", redact_key(s3_conn.access_key))\n if e.error_code == \"SignatureDoesNotMatch\":\n logger.error(\"Supplied secret key is not valid for specified user.\")\n if e.status == 403 or e.status == 409:\n logger.error(\"Supplied access key (%s) has no permissions on this server.\", redact_key(s3_conn.access_key))\n raise\n return None\n\n\ndef redact_key(s3_key):\n redacted_key = s3_key[:3] + \"############\" + s3_key[-3:]\n return redacted_key\n\n\ndef s3_create_anon_access_policy(bucket_name):\n \"\"\"Create a bucket policy for anonymous read access and anonymous bucket listing.\n Returns\n -------\n anon_access_policy: A json formatted s3 bucket policy\n \"\"\"\n anon_policy_dict = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"AddPerm\",\n \"Effect\": \"Allow\",\n \"Principal\": \"*\",\n \"Action\": [\"s3:GetObject\"],\n \"Resource\": [\"arn:aws:s3:::%s/*\" % bucket_name]\n },\n {\n \"Sid\": \"AddPerm\",\n \"Effect\": \"Allow\",\n \"Principal\": \"*\",\n \"Action\": [\"s3:ListBucket\"],\n \"Resource\": [\"arn:aws:s3:::%s\" % bucket_name]\n }\n ]\n }\n anon_access_policy = json.dumps(anon_policy_dict)\n return anon_access_policy\n","sub_path":"katsdpdata/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"94543843","text":"#!/usr/bin/python3\nimport datetime,os,re,time\nimport pandas\nfrom busyday import get_seq\nfrom mark import tip\nfrom status import *\nfrom exchange import get_xchg\nfrom attach import write,read,xls\n\nedge='15:30:00'\n\ndef store_xchg(day):\n info,rst=get_xchg(day)\n path=tus_raw+str(day)\n info['full']=sum([v for v in info.values()])\n if not rst.empty:\n write(path,rst)\n info['size']=os.path.getsize(path)\n else:\n info['size']=0\n info['date']=day\n print(info['full'])\n return info\n\ndef load_xchg(day):\n path=tus_raw+str(day)\n if os.access(path,os.F_OK):\n return read(path)\n else:\n print('File is Not Access')\n return None\n\ndef daily_xchg():\n days=[i for i in os.listdir(tus_raw) if re.match('\\d{8}',i)]\n days.sort(reverse=True)\n for i in days:\n yield i,load_xchg(i)\n\n#def check_xchg(day,rst):\n# rst.symbol=rst.apply(lambda x:regular(day,x.symbol),axis=1)\n# idx=rst[pandas.isna(rst.symbol)].index\n# if any(idx):\n# tip(day,',',idx)\n# rst.drop(idx,inplace=True)\n\ndef available():\n now=datetime.datetime.now()\n start=datetime.datetime.strptime(edge,'%H:%M:%S').time()\n rst=now.time()>start and now or now-datetime.timedelta(days=1)\n return rst.date().strftime('%Y%m%d')\n\ndef body(st,ed):\n rows=[]\n for i in get_seq(st,ed,reverse=False):\n print(i,'=',end='')\n rst=store_xchg(i)\n rows.append(rst)\n rows=pandas.DataFrame(rows,columns=pillar)\n return rows\n\ndef present(day=None,end=None):\n if day is None:\n day=max([i for i in os.listdir(tus_raw) if re.match('\\d{8}',i)])\n if end is None:end=available()\n info=body(day,end)\n if not info.empty:\n for i in range(int(day[:4]),int(end[:4])+1):\n k=str(i)\n rst=info[info.apply(lambda x:x.date[:4]==k,axis=1)]\n rst=pandas.concat([daily.read(k),rst])\n daily.write(rst,k)\n\ndef init():\n for i in range(2017,2019):\n ed=str(i+1)+'0101'\n if ed>stop:ed=stop\n daily.write(body(str(i)+'0101',ed),str(i))\n for j in range(60):\n print('.',end='')\n time.sleep(1)\n print('')\n\npillar=['date','dce','czce','shfe','full','size']\nstop=available()\ndaily=xls('daily_info')\n\nif __name__==\"__main__\":\n# rows=daily.read('2018')\n# a={'full':123}\n# b={'full':321}\n# rows=rows.append(b,ignore_index=True)\n# daily.write(rows,'2018')\n present()\n\n\n","sub_path":"datalog/workday/routine.py","file_name":"routine.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"603561120","text":"import os\nimport shutil\nfrom pygments import highlight\nfrom pygments.lexers import get_lexer_by_name\nfrom pygments.formatters import HtmlFormatter, RtfFormatter\nimport cloudconvert\n# Needs pygments and cloudconvert\nroot_dir = '.'\n\nout_dir = 'prints'\nif os.path.exists(out_dir):\n shutil.rmtree(out_dir)\nos.makedirs(out_dir)\nos.makedirs(os.path.join(out_dir, 'html'))\nos.makedirs(os.path.join(out_dir, 'rtf'))\n\npy = get_lexer_by_name('python')\njs = get_lexer_by_name('js')\nhtml = get_lexer_by_name('html+jinja')\ncss = get_lexer_by_name('css')\njava = get_lexer_by_name('java')\nxml = get_lexer_by_name('xml')\n\nendings = {'.py': py, '.js': js, '.html': html, '.css': css, '.java': java, '.xml':xml}\n\nfull_file_content = ''\nfull_output_file = 'full_code.html'\n\nexclude_dirs = ['.', out_dir, 'build']\nexclude_files = [full_output_file, 'print_files', '.pdf']\n\nfor subdir, dirs, files in os.walk(root_dir, topdown=True):\n dirs[:] = [d for d in dirs if all([d.startswith(string) is False for string in exclude_dirs]) is True]\n\n files[:] = [f for f in files if f[0] != '.' and all((string in f) is False for string in exclude_files) is True]\n\n for f in files:\n full_path = os.path.join(subdir, f)\n # print(full_path)\n name, filetype = os.path.splitext(f)\n lexer = endings.get(filetype, None)\n relative_path = os.path.relpath(full_path, '.')\n p = '_'.join(relative_path.split(os.sep))\n p_html = out_dir+r\"\\html\\_\"+p.split('.')[0]\n p_rtf = out_dir+r\"\\rtf\\_\"+p.split('.')[0]\n #p_html = os.path.join(out_dir, 'html', p.split('.')[0])\n #p_rtf = os.path.join(out_dir, 'rtf', p.split('.')[0])\n # print(p_html)\n if lexer:\n with open(full_path, 'r') as read_file, open(p_html+'.html', 'w') as write_file_html, open(p_rtf+'.rtf','w') as write_file_rtf:\n try:\n source = read_file.read()\n except:\n source = 'None'\n print(full_path)\n heading_html = '

    '+full_path+'

    '\n code_html = heading_html+highlight(source, lexer, HtmlFormatter(noclasses=True))\n full_file_content += code_html+'
    '\n write_file_html.write(code_html)\n\n heading_rtf = full_path+'\\n'\n code_rtf = highlight(heading_rtf+source, lexer, RtfFormatter())\n write_file_rtf.write(code_rtf)\n\n\nwith open('full_code.html', 'w') as final:\n final.write(full_file_content)\n\napi = cloudconvert.Api('ovnSmHPCubqsa2n4mJRNFUDXbe6MaAdr9qQOD0A7zOPbHryiOM2wafxwrWUX4Z5bRt1VJmvWujKIQsuQxTNhBw')\n\noutput_format = \"rtf\"\n\nprocess = api.convert({\n \"inputformat\": \"html\",\n \"outputformat\": output_format,\n \"input\": \"upload\",\n \"timeout\": 0,\n \"file\": open(full_output_file, 'rb')\n})\nprocess.wait()\nprocess.download()\n","sub_path":"print_files.py","file_name":"print_files.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"99739718","text":"# fim_dir_cd.py\nimport os\n\npath = os.getcwd()\nprint(path)\n\ndirs = os.listdir(path +'/repo')\n\n# This would print all the files and directories\nfor file in dirs:\n print(file)\n\nos.chdir(path +'/repo')\n\nprint(os.getcwd())\n\nfor file in [item for item in os.listdir('.') if os.path.isfile(item)]:\n print(file)\n","sub_path":"Janus/python-base-unit_06/FIM/fim_dir_cd.py","file_name":"fim_dir_cd.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"163427612","text":"import sys\nimport os\nsys.path.append(\"/n/home13/jbischof/word_rate_prj/wordratemodels/exec/\")\nfrom parse_lda_data import *\n\nmain_dir = \"/n/airoldifs2/lab/jbischof/word_rate_output/\"\nfake_data_dir = main_dir + \"fake_data/\"\n\ninfilename_lda = fake_data_dir + \"fake_data_ldaformat.txt\"\noutfilename_doclength = fake_data_dir + \"doc_length_table.txt\"\noutfilename_margwc = fake_data_dir + \"marg_wc_table.txt\"\noutfilename_doctopic = fake_data_dir + \"doc_topic_list.RData\"\noutfilename_docwc = fake_data_dir + \"doc_word_count_list.RData\"\noutfilename_featwc = fake_data_dir + \"feature_word_count_list.RData\"\n\n## Parse LDA data into format that R can read\nparse_lda_data(infilename_lda,outfilename_doclength, \\\noutfilename_margwc,outfilename_docwc,outfilename_featwc, \\\ndocwc_dictname=\"doc.count.list\", featwc_dictname=\"feature.count.list\", \\\ndoc_ids_inc=True,items_skip=0)","sub_path":"preprocess_fake_data/process_fake_lda_data.py","file_name":"process_fake_lda_data.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"102013047","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 1 15:55:13 2019\n\n@author: kareem\n@title: reduce dimensions\n@description: reduce dimensions for all files \n\"\"\"\n\nfrom scipy.io import arff\nimport os\nimport pandas as pd\nimport numpy as np\n\ndef main():\n ## Collect names of music files\n path = r\"./data/train/\"\n music_files = [path+file for file in os.listdir(path) if 'music' in file]\n ## Collect name of speech files\n speech_files = [path+file for file in os.listdir(path) if 'speech' in file]\n print(\"Running... No worries!\")\n i=0\n for file in music_files:\n try:\n with open(file, 'r') as f:\n data, meta = arff.loadarff(f)\n i+=1\n print(file, \"has\", len(data), \"training examples\")\n dataset = pd.DataFrame(data)\n X = dataset.iloc[:,:-1].values\n X.tofile('data/train(X_y)/{}.music_X{}.dat'.format(i, X.shape))\n y = np.array([1 if str(w, 'utf-8')=='music' else 0 for w in dataset.iloc[:,-1]])\n y.tofile('data/train(X_y)/{}.music_y.dat'.format(i))\n X_opt = backward_elimination(y, X)\n X_opt.tofile('data/train(X_y)/{}.music_X_opt{}.dat'.format(i, X_opt.shape))\n except EOFError:\n print(\"File is unreadable!\")\n print()\n i=0\n for file in speech_files:\n try:\n with open(file, 'r') as f:\n data, meta = arff.loadarff(f)\n i+=1\n print(file, \"has\", len(data), \"training examples\")\n dataset = pd.DataFrame(data)\n X = dataset.iloc[:,:-1].values\n X.tofile('data/train(X_y)/{}.speech_X.dat{}'.format(i, X.shape))\n y = np.array([1 if str(w, 'utf-8')=='speech' else 0 for w in dataset.iloc[:,-1]])\n y.tofile('data/train(X_y)/{}.speech_y.dat'.format(i))\n X_opt = backward_elimination(y, X)\n X_opt.tofile('data/train(X_y)/{}.speech_X_opt{}.dat'.format(i, X_opt.shape))\n except EOFError:\n print(\"File is unreadable!\")\n\ndef backward_elimination(y, X, sl=0.05):\n \"\"\"\n performs variable Backward Elimination on a dataframe or 2d Numpy array. And returns\n optimized array where only variables with low p-value are present.\n \n Params:\n ______\n X: Matrix of features from which you want to remove insignificant variables \n (Datafram or 2d numpy.ndarray).\n sl: Significance Level (float), the threshold where no variables with higher p-values \n are considered in the optimized matrix.\n returns: *X_opt* (2d numpy.ndarray) an optimized array of X where X holds only significant variables \n \"\"\"\n from statsmodels.formula import api as sm\n variables_indices = np.arange(X.shape[1])\n model_nr = 0\n if isinstance(X, pd.DataFrame):\n X = X.iloc[:,:].values # Convert to numpy arrays\n while True:\n print(model_nr)\n model_nr+=1\n X_opt = X[:, variables_indices]\n classifier_OLS = sm.OLS(y, X_opt).fit()\n ## remove the variable with hihest p-value\n highest_pvalue = np.max(classifier_OLS.pvalues)\n if highest_pvalue > 0.05:\n indices_to_remove = []\n for j in range(classifier_OLS.pvalues.shape[0]):\n if classifier_OLS.pvalues[j] == highest_pvalue:\n indices_to_remove.append(j)\n variables_indices = np.delete(variables_indices, indices_to_remove)\n else:\n break\n return X_opt\n\nif __name__ == '__main__':\n main()\n ","sub_path":"Code/draft/reduce_dimensions.py","file_name":"reduce_dimensions.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"275505308","text":"from flask import Response, request\nfrom database.models import Result_progress, Person\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\nfrom flask_restful import Resource\nfrom mongoengine.errors import FieldDoesNotExist, NotUniqueError, DoesNotExist, ValidationError, InvalidQueryError\nfrom resources.errors import InternalServerError, SchemaValidationError, FieldAlreadyExistsError, UpdatingFieldError, DeletingFieldError, FieldNotExistsError, \\\n EmailAlreadyExistsError, UnauthorizedError\n\n# Endpoint which accepts 'GET' + 'POST' requests\nclass ResultsApi(Resource):\n def get(self):\n query = Result_progress.objects()\n results = Result_progress.objects().to_json()\n return Response(results, mimetype=\"application/json\", status=200)\n\n @jwt_required\n def post(self):\n try:\n person_id = get_jwt_identity()\n body = request.get_json()\n person = Person.objects.get(id=person_id)\n result = Result_progress(**body, added_by=person)\n result.save()\n person.update(push__results=result)\n person.save()\n id = result.id\n return {'id': str(id)}, 200\n # Error handling field not ext and validation error\n except (FieldDoesNotExist, ValidationError):\n # Given message from module errors.py\n raise SchemaValidationError\n # Error handling field not unique\n except NotUniqueError:\n # Given message from module errors.py\n raise FieldAlreadyExistsError\n # Error handling for everything that is not defined in error.py\n except Exception as error:\n # Given message from module errors.py\n raise InternalServerError\n\n# Endpoint which accepts 'GET' + 'PUT' + 'DELETE' requests\nclass ResultApi(Resource):\n @jwt_required\n # Methode 'PUT'\n def put(self, id):\n try:\n person_id = get_jwt_identity()\n result = Result_progress.objects.get(id=id, added_by=person_id)\n body = request.get_json()\n Result_progress.objects.get(id=id).update(**body)\n return Response('Edit status: OK', status=200)\n # Error handling for invalid query\n except InvalidQueryError:\n # Given message from module errors.py\n raise SchemaValidationError\n # Error handling field not exist\n except DoesNotExist:\n # Given message from module errors.py\n raise UpdatingFieldError\n # Error handling for everything that is not defined in error.py\n except Exception:\n # Given message from module errors.py\n raise InternalServerError \n \n @jwt_required\n # Methode 'DELETE'\n def delete(self, id):\n try:\n person_id = get_jwt_identity()\n result = Result_progress.objects.get(id=id, added_by=person_id)\n result.delete()\n return Response('Delete status is: OK', status=200)\n except DoesNotExist:\n raise DeletingFieldError\n except Exception:\n raise InternalServerError \n\n def get(self, id):\n try:\n results = Result_progress.objects.get(id=id).to_json()\n return Response(results, mimetype=\"application/json\", status=200)\n # Error handling field not exist\n except DoesNotExist:\n # Given message from module errors.py\n raise UpdatingFieldError \n # Error handling for everything that is not defined in error.py\n except Exception:\n # Given message from module errors.py\n raise InternalServerError \n","sub_path":"resources/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"379830710","text":"from setuptools import setup\n\nlong_description = \"\"\"\nSimple library for complex projects with a need for a\nsimple and persistent configurations.\n\"\"\"\n\ndef main():\n setup(\n name='configmgr',\n description='simple configuration management',\n long_description=long_description,\n version='0.0',\n author='grantor61',\n author_email='grantor61@gmail.com',\n url='https://bitbucket.org/grantor61/configmgr',\n license='MIT license',\n platforms=['linux', 'win32'],\n install_requires=['appdirs', 'py'],\n classifiers=['Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: POSIX',\n 'Operating System :: Microsoft :: Windows',\n 'Topic :: Software Development :: Libraries',\n 'Topic :: Utilities',\n 'Programming Language :: Python'],\n py_modules=['configmgr'],\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pypi_install_script/configmgr-0.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"579902957","text":"import torch\nfrom torch import nn\n\n\nclass ConvBlock(nn.Module):\n def __init__(self, in_dim=3, out_dim=3, kernel=3, pool=True):\n super(ConvBlock, self).__init__()\n\n block = [\n nn.Conv2d(in_dim, out_dim, kernel, stride=1, padding=kernel // 2),\n # nn.BatchNorm2d(out_dim),\n nn.LeakyReLU(),\n nn.Conv2d(\n out_dim, out_dim, kernel, stride=2 if pool else 1, padding=kernel // 2\n ),\n # nn.BatchNorm2d(out_dim),\n nn.LeakyReLU(),\n ]\n\n self.block = nn.Sequential(*block)\n\n def forward(self, x):\n return self.block(x)\n\n\nclass DeconvBlock(nn.Module):\n def __init__(self, in_dim=3, out_dim=3, kernel=3):\n super(DeconvBlock, self).__init__()\n\n self.transpose = nn.ConvTranspose2d(\n in_dim, out_dim, kernel, stride=2, padding=kernel // 2\n )\n block = [\n # nn.BatchNorm2d(out_dim),\n nn.Conv2d(out_dim, out_dim, kernel, stride=1, padding=kernel // 2),\n # nn.BatchNorm2d(out_dim),\n nn.LeakyReLU(),\n nn.Conv2d(out_dim, out_dim, kernel, stride=1, padding=kernel // 2),\n # nn.BatchNorm2d(out_dim),\n nn.LeakyReLU(),\n ]\n\n self.block = nn.Sequential(*block)\n\n def forward(self, x, add=None):\n x = self.transpose(x, output_size=add.shape if add is not None else None)\n out = self.block(x)\n out = out if add is None else torch.cat((out, x), dim=1)\n return out\n\n\nclass DownsampleBlock(nn.Module):\n def __init__(self):\n super(DownsampleBlock, self).__init__()\n\n self.conv32 = ConvBlock(in_dim=4, out_dim=32)\n self.conv64 = ConvBlock(in_dim=32, out_dim=64)\n self.conv128 = ConvBlock(in_dim=64, out_dim=128)\n self.conv256 = ConvBlock(in_dim=128, out_dim=256)\n self.conv512 = ConvBlock(in_dim=256, out_dim=512)\n\n def forward(self, x) -> [torch.Tensor]:\n conv32 = self.conv32(x)\n # print(conv32.shape)\n conv64 = self.conv64(conv32)\n # print(conv64.shape)\n conv128 = self.conv128(conv64)\n # print(conv128.shape)\n conv256 = self.conv256(conv128)\n # print(conv256.shape)\n conv512 = self.conv512(conv256)\n # print(conv512.shape)\n\n return [conv512, conv256, conv128, conv64, conv32, x]\n\n\nclass UpsampleBlock(nn.Module):\n def __init__(self):\n super(UpsampleBlock, self).__init__()\n\n self.conv512 = DeconvBlock(in_dim=512, out_dim=256)\n self.conv256 = DeconvBlock(in_dim=256 * 2, out_dim=128)\n self.conv128 = DeconvBlock(in_dim=128 * 2, out_dim=64)\n self.conv64 = DeconvBlock(in_dim=64 * 2, out_dim=32)\n self.conv32 = DeconvBlock(in_dim=32 * 2, out_dim=32)\n self.final_scale = nn.ConvTranspose2d(32 * 2, 32, 3, stride=2, padding=1)\n\n def forward(self, samples):\n u512, u256, u128, u64, u32, orig = samples\n\n # print(\"UPSAMPLING\")\n x = self.conv512(u512, add=u256)\n # print(x.shape)\n x = self.conv256(x, add=u128)\n # print(x.shape)\n x = self.conv128(x, add=u64)\n # print(x.shape)\n x = self.conv64(x, add=u32)\n # print(x.shape)\n x = self.conv32(x, add=orig)\n # x = self.final_scale(x, output_size=[orig.shape[2], orig.shape[3]])\n\n return x\n\n\nclass KoalaNet(nn.Module):\n def __init__(self):\n super(KoalaNet, self).__init__()\n\n layers = [\n DownsampleBlock(),\n UpsampleBlock(),\n nn.Conv2d(32 * 2, 32, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(),\n nn.Conv2d(32, 12, kernel_size=3, stride=1, padding=1),\n nn.PixelShuffle(2)\n ]\n\n self.net = nn.Sequential(*layers)\n\n def forward(self, images):\n output = self.net(images)\n # return output\n # print(output.shape)\n return output\n","sub_path":"koalanet/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"459753223","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\nimport zipfile\nimport logging\nimport logging.handlers\nimport requests\nimport threading\nimport re\nimport os\nimport sys\n# tested w/ Python 2.7.5\n\n# log to /var/log/messages or syslog\nsyslogger = logging.getLogger()\nsyslogger.setLevel(logging.INFO) # setup the logger \nsyslog_handler = logging.handlers.SysLogHandler(address=\"/dev/log\", facility='user')\nformatter = logging.Formatter('%(name)s: %(levelname)s %(module)s %(message)r')\nsyslog_handler.setFormatter(formatter)\n\nsyslogger.addHandler(syslog_handler)\n\n# this builds the header range \ndef buildRange(value, numsplits):\n lst = []\n for i in range(numsplits):\n if i == 0:\n lst.append('%s-%s' % (i, int(round(1 + i * value/(numsplits*1.0) + value/(numsplits*1.0)-1, 0))))\n else:\n lst.append('%s-%s' % (int(round(1 + i * value/(numsplits*1.0),0)), int(round(1 + i * value/(numsplits*1.0) + value/(numsplits*1.0)-1, 0))))\n return lst\n\ndef download (url):\n filename = ''\n try:\n r = requests.get(url)\n # fast regex list comprehension for non repeating zip files within html containing numbers\n dats = [x for x in list(set(re.findall(\"([-\\w]+\\.(?:zip))\", r.text, re.IGNORECASE))) if (re.search(r'\\d', x))]\n dats.sort() # .sort() by it's self is fastest\n filename = dats[-1]\n\n syslogger.info('datfile url verison {}'.format(filename))\n total_bytes = requests.get(url+filename,headers={'Accept-Encoding': 'identity'}, stream=True).headers['Content-length']\n\n dataDict = {}\n # split total num bytes into ranges\n ranges = buildRange(int(total_bytes), 4)\n \n def RequestChunk(idx, irange):\n try:\n special = {'Range' : 'bytes={}'.format(irange)}\n r = requests.get(url+filename, headers=special, stream=True, timeout=None)\n\n chunk = b'' # empty byte object \n for partial in r.iter_content(chunk_size=1024): \n if partial: # filter out keep-alive new chunks\n chunk += partial\n\n dataDict[idx] = chunk\n except requests.exceptions.RequestException as e: # correct syntax for requests\n syslogger.warning('request-chunk attempt {}'.format(e))\n\n downloaders = [threading.Thread(target=RequestChunk,args=(idx, irange),) for idx,irange in enumerate(ranges)]\n\n # start threads, let run in parallel, wait for all to finish\n for th in downloaders:\n th.start()\n for th in downloaders:\n th.join()\n \n bytes_recieved = sum((len(chunk) for chunk in dataDict.values()))\n \n if (int(total_bytes) == int(bytes_recieved)):\n\n try:\n os.remove('/tmp/'+filename) \n except OSError:\n pass\n \n try:\n # reassemble file in correct order \n with open('/usr/local/uvscan/'+filename, 'wb') as filestream:\n for _idx,chunk in sorted(dataDict.iteritems()):\n filestream.write(chunk)\n filestream.close()\n\n zip_ref = zipfile.ZipFile('/usr/local/uvscan/'+filename, 'r')\n zip_ref.extractall('/usr/local/uvscan/')\n zip_ref.close()\n\n except OSError as e:\n syslogger.warning(e)\n\n try:\n os.remove('/usr/local/uvscan/'+filename) \n except OSError:\n pass\n \n except requests.exceptions.RequestException as e: # correct syntax for requests\n syslogger.warning('content-length attempt {}'.format(e))\n\ndef main (url):\n syslogger.info('started av update')\n download(url)\n cmd_line = os.popen(\"/usr/local/uvscan/uvscan --version | grep version\").read() # load dats\n cmd_line = ' '.join(cmd_line.splitlines()) # mangle the return string \n syslogger.info(cmd_line)\n\n## main fuction ## \nif __name__ == '__main__':\n # try local then backup\n if len(sys.argv) == 3:\n try:\n syslogger.info('trying main {}'.format(sys.argv[1]))\n main(sys.argv[1])\n except:\n syslogger.warning('trying backup {}'.format(sys.argv[2]))\n main(sys.argv[2])\n","sub_path":"update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"313125562","text":"# Databricks notebook source\ndbutils.widgets.text(\"schmNm\", \"\", \"\")\ndbutils.widgets.text(\"tblNm\", \"\", \"\")\n\ndbutils.widgets.text(\"deltaTS\", \"\", \"\")\ndbutils.widgets.text(\"initFlg\", \"\", \"\")\n\ndbutils.widgets.text(\"dbrxPath\", \"\", \"\")\n\ndeltaTS = dbutils.widgets.get(\"deltaTS\")\n#deltaTS = getArgument(\"deltaTS\")\n\ninitFlg = dbutils.widgets.get(\"initFlg\")\n#initFlg = getArgument(\"initFlg\")\nprint(initFlg)\n\nschmNm = dbutils.widgets.get(\"schmNm\")\n#schmNm = getArgument(\"schmNm\")\nprint(schmNm)\n\ntblNm = dbutils.widgets.get(\"tblNm\")\n#tblNm = getArgument(\"tblNm\")\nprint(tblNm)\n\ndbrxPath = dbutils.widgets.get(\"dbrxPath\")\n#dbrxPath = getArgument(\"dbrxPath\")\n\ndeltaTS=deltaTS.replace(\"T\",\" \")\nprint(deltaTS)\n\n# COMMAND ----------\n\nfrom datetime import * \nimport pytz\nfrom pytz import *\n\ntoday = datetime.now(tz=pytz.utc)\ndeltaTS =(today.astimezone(timezone('US/Pacific'))+ timedelta(days=-6))\nprint(deltaTS)\n\n# COMMAND ----------\n\nsqlQuery = \"\"\"CREATE OR REPLACE TEMPORARY VIEW TEMP_DATA AS\nselect COITM,\nCOLITM,\nCOAITM,\nCOMCU,\nCOLOCN,\nCOLOTN,\nCOLOTG,\nCOLEDG,\nCOUNCS,\nCOCSPO,\nCOCSIN,\nCOURCD,\nCOURDT,\nCOURAT,\nCOURAB,\nCOURRF,\nCOUSER,\nCOPID,\nCOJOBN,\nCOUPMJ,\nCOTDAY,\nEDW_CRT_TS,\nEDW_UPDT_TS,\nEDW_ACTV_FLG,\nCOACTN,\nCOUSI,\nCOPGM\nfrom edw_lnd_jde_view.f4105 where EDW_UPDT_TS >= '{0}'\"\"\".format(deltaTS)\nspark.sql(sqlQuery)\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW f4105 AS\n# MAGIC select COITM,\n# MAGIC COLITM,\n# MAGIC COAITM,\n# MAGIC COMCU,\n# MAGIC COLOCN,\n# MAGIC COLOTN,\n# MAGIC COLOTG,\n# MAGIC COLEDG,\n# MAGIC COUNCS,\n# MAGIC COCSPO,\n# MAGIC COCSIN,\n# MAGIC COURCD,\n# MAGIC COURDT,\n# MAGIC COURAT,\n# MAGIC COURAB,\n# MAGIC COURRF,\n# MAGIC COUSER,\n# MAGIC COPID,\n# MAGIC COJOBN,\n# MAGIC COUPMJ,\n# MAGIC COTDAY,\n# MAGIC EDW_CRT_TS,\n# MAGIC EDW_UPDT_TS,\n# MAGIC EDW_ACTV_FLG,\n# MAGIC COACTN,\n# MAGIC COUSI,\n# MAGIC COPGM\n# MAGIC from TEMP_DATA\n\n# COMMAND ----------\n\ndbutils.notebook.run(\"/Shared/QA/CONTROL/adw_integration_write\", 10000, {\"schemaNm\": \"EDW_INTG\", \"tableNm\": \"F4105\", \"dbrxTable\": \"F4105\", \"writeMode\": \"overwrite\"})\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC drop view global_temp.f4105\n\n# COMMAND ----------\n\n\n","sub_path":"C1-SIT3/entpr_intg/F4105.py","file_name":"F4105.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"340820188","text":"'''\nTheano computation graph that defines the hybrid GMM objectives for semi-\nsupervised learning for DPLR covariance matrices from [1].\n\n[1] Roth W., Peharz R., Tschiatschek S., Pernkopf F., Hybrid generative-\n discriminative training of Gaussian mixture models, Pattern Recognition\n Letters 2018, (accepted)\n\n@author Wolfgang Roth\n'''\n\nimport numpy as np\nimport theano\nimport theano.tensor as T\n\nfrom theanoOpLogDetPSD import logdet_psd\n\nclass GMMClassifierSSL:\n def __init__(self, C, D, K, S, rng_state=None, epsilon=1e-2, use_precision=True, tradeoff_hybrid=0.5, tradeoff_ssl=0.9, gamma=1, eta=10, init_params=None):\n '''\n Constructs the Theano computation graph for the given parameters\n \n C: Number of classes\n D: Number of input features\n K: List of length C containing the number of components per class\n S: Number of dimensions of the low-rank approximation of the DPLR matrix\n structure. Note that this parameter is actually called 'R' in the\n paper.\n rng_state: Random number generator seed to use if the parameters should\n be initialized randomly. This parameter is ignored if 'init_params' is\n given.\n epsilon: Regularizer for the diagonal of the covariance matrices.\n use_precision: Determines if precisions or covariances should be used.\n The precision is the inverse of the covariance matrix.\n tradeoff_hybrid: The lambda parameter of the hybrid objective. Close to\n 1 means very generative, close to 0 means very discriminative.\n tradeoff_ssl: The kappa parameter of the hybrid objective for semi-\n supervised learning. Close to 1 puts more weight onto the labeled\n samples, close to 0 puts more weights onto the unlabeled samples.\n gamma: The gamma parameter of the MM/LM objective.\n eta: The parameter for the softmax approximation.\n init_params: Use this to provide initial parameters. Usually parameters\n obtained with the EM algorithm are provided here. init_params must be\n a five-tuple containing\n - mu_vals (K_all x D): Mean values for each component\n - s_vals (K_all x D x S): Low-rank matrices for each component\n - d_rho_vals (D x K_all): Diagonal variances for each component (inverse softplus values)\n - prior_k_rho_vals (K_all): Logits of the component priors\n - prior_c_rho_vals (C): Logits of the class priors\n with K_all = sum(K). The component parameters are stored linearly for\n all classes. E.g. the first K[0] entries correspond to components of\n class 0. If precisions are used instead of covariances, the use of\n s_vals and d_rho_vals changes accordingly.\n '''\n self.x = T.matrix('x')\n self.t = T.ivector('t')\n self.tradeoff_hybrid = tradeoff_hybrid\n self.tradeoff_ssl = tradeoff_ssl\n self.gamma = gamma\n self.eta = eta\n self.epsilon = epsilon\n\n K_all = np.sum(K)\n \n if init_params is None:\n rng = np.random.RandomState(rng_state)\n mu_vals = rng.normal(0., 1., size=(K_all, D))\n s_vals = rng.normal(0., 1., size=(K_all, D, S))\n d_rho_vals = rng.normal(0, 0.1, size=(D, K_all))\n prior_k_rho_vals = np.zeros((np.sum(K),))\n prior_c_rho_vals = np.zeros((C,))\n else:\n assert len(init_params) == 5\n mu_vals, s_vals, d_rho_vals, prior_k_rho_vals, prior_c_rho_vals = init_params\n assert mu_vals.shape == (K_all, D)\n assert s_vals.shape == (K_all, D, S)\n assert d_rho_vals.shape == (D, K_all)\n assert prior_k_rho_vals.shape == (K_all,)\n assert prior_c_rho_vals.shape == (C,)\n\n mu_vals = np.asarray(mu_vals, dtype=theano.config.floatX)\n s_vals = np.asarray(s_vals, dtype=theano.config.floatX)\n d_rho_vals = np.asarray(d_rho_vals, dtype=theano.config.floatX)\n prior_k_rho_vals = np.asarray(prior_k_rho_vals, dtype=theano.config.floatX)\n prior_c_rho_vals = np.asarray(prior_c_rho_vals, dtype=theano.config.floatX)\n \n # Shared variables\n self.means = theano.shared(mu_vals, name='means', borrow=True) \n self.s = theano.shared(s_vals, name='s', borrow=True)\n self.d_rho = theano.shared(d_rho_vals, name='d_rho', borrow=True)\n self.prior_k_rho = theano.shared(prior_k_rho_vals, name='prior_k_rho', borrow=True)\n self.prior_c_rho = theano.shared(prior_c_rho_vals, name='prior_c_rho', borrow=True)\n self.params = [self.means, self.s, self.d_rho, self.prior_k_rho, self.prior_c_rho]\n\n self.d = T.nnet.softplus(self.d_rho) + self.epsilon\n if use_precision == True:\n # s and d are used to represent precision matrices\n self.exponent = T.dot(self.x ** 2, self.d) #xDx\n self.exponent -= 2 * T.dot(self.x, self.d * self.means.T) #-2xDm\n self.exponent += T.sum(self.means ** 2 * self.d.T, axis=1) # mDm\n self.exponent += T.sum(T.dot(self.x, self.s) ** 2, axis=2) # xSSx\n self.exponent -= 2 * T.sum(T.dot(self.x, self.s) * T.sum(self.s * self.means[:,:,None], axis=1)[None,:,:], axis=2) # -2xSSm\n self.exponent += T.sum(T.sum(self.s * self.means[:,:,None], axis=1) ** 2, axis=1) # mSSm\n self.exponent *= -0.5\n \n eye_S = T.eye(S, dtype=theano.config.floatX)\n self.aux_matrix = T.batched_tensordot(self.s / self.d.T[:,:,None], self.s, axes=(1, 1)) + eye_S\n self.aux_logdet, _ = theano.scan(fn=lambda aux: logdet_psd(aux),\n outputs_info=None,\n sequences=self.aux_matrix,\n non_sequences=None)\n self.logdet = T.sum(T.log(self.d), axis=0) + self.aux_logdet\n \n # logpK contains all log probabilities of all components in an (N x sum(K)) array\n # Note that the log component priors are not added yet\n self.logpK = -0.5 * D * T.log(2. * np.pi) + 0.5 * self.logdet + self.exponent\n else:\n # s and d are used to represent covariance matrices\n if S == 1:\n self.aux_matrix = T.sum(self.s[:,:,0] / self.d.T * self.s[:,:,0], axis=1).reshape((K_all, 1, 1)) + 1.\n else:\n # Since the latest Cuda/Theano update, the following two lines\n # cause an error in the case of S=1.\n eye_S = T.eye(S, dtype=theano.config.floatX)\n self.aux_matrix = T.batched_tensordot(self.s / self.d.T[:,:,None], self.s, axes=(1, 1)) + eye_S\n (self.aux_inv, self.aux_logdet), _ = theano.scan(fn=lambda aux: [T.nlinalg.matrix_inverse(aux), logdet_psd(aux)],\n outputs_info=None,\n sequences=[self.aux_matrix],\n non_sequences=None)\n self.logdet = T.sum(T.log(self.d), axis=0) + self.aux_logdet\n\n # Product inv(d) * s for all K --> K x D x S\n self.rs = self.s / self.d.T[:,:,None]\n # Product inv(d) * s * aux_inv for all K --> K x D x S\n self.ls = T.batched_dot(self.rs, self.aux_inv)\n\n # s and d are used to represent covariance matrices\n self.exponent = T.dot(self.x ** 2, 1. / self.d) #xDx\n self.exponent -= 2 * T.dot(self.x, (1. / self.d) * self.means.T) #-2xDm\n self.exponent += T.sum(self.means ** 2 * (1. / self.d.T), axis=1) # mDm\n self.exponent -= T.sum(T.dot(self.x, self.ls) * T.dot(self.x, self.rs), axis=2) # -x ls rs x\n self.exponent += 2 * T.sum(T.dot(self.x, self.ls) * T.sum(self.rs * self.means[:,:,None], axis=1)[None,:,:], axis=2) # 2x ls rs m\n self.exponent -= T.sum(T.sum(self.ls * self.means[:,:,None], axis=1) * T.sum(self.rs * self.means[:,:,None], axis=1), axis=1) # -m ls rs m\n self.exponent *= -0.5\n\n # logpK contains all log probabilities of all components in an (N x sum(K)) array\n # Note that the log component priors are not added yet\n self.logpK = -0.5 * D * T.log(2. * np.pi) - 0.5 * self.logdet + self.exponent\n\n # logpC contains the log joint probabilities p(x,c) in an (N x C) array\n self.logpC = self.logpK\n self.logpC_list = []\n for c in range(C):\n k1 = int(np.sum(K[:c]))\n k2 = int(k1 + K[c])\n self.logpC_list.append(self.logpC[:, k1:k2])\n aux_max = T.max(self.prior_k_rho[k1:k2]) # Compute log-probabilities without division\n log_prior_k = self.prior_k_rho[k1:k2] - T.log(T.sum(T.exp(self.prior_k_rho[k1:k2] - aux_max))) - aux_max\n self.logpC_list[c] += log_prior_k\n aux_max = T.max(self.logpC_list[c], axis=1, keepdims=True)\n self.logpC_list[c] = T.log(T.sum(T.exp(self.logpC_list[c] - aux_max), axis=1)) + aux_max.flatten()\n self.logpC = T.stack(self.logpC_list, axis=1)\n aux_max = T.max(self.prior_c_rho) # Compute log-probabilities without division\n log_prior_c = self.prior_c_rho - T.log(T.sum(T.exp(self.prior_c_rho - aux_max))) - aux_max\n self.logpC += log_prior_c \n\n # mm and cll objective are only for labeled data\n # logl objective is slightly different for labeled and unlabeled data\n idx_sv = T.ge(self.t, 0).nonzero()\n idx_usv = T.lt(self.t, 0).nonzero()\n self.logpC_sv = self.logpC[idx_sv]\n self.logpC_usv = self.logpC[idx_usv]\n is_sv_empty = T.eq(self.logpC_sv.shape[0], 0)\n is_usv_empty = T.eq(self.logpC_usv.shape[0], 0)\n \n # If there are no supervised/unsupervised samples create a dummy entry\n # to avoid problems. The corresponding costs are set to 0 later. We set\n # the number of rows to 2 because 1 results in an error.\n # The problems appear to be CUDNN related if for instance a sum over an\n # empty tensor is computed.\n self.logpC_sv = theano.ifelse.ifelse(is_sv_empty, T.zeros((2,C), theano.config.floatX), self.logpC_sv)\n self.t_sv = theano.ifelse.ifelse(is_sv_empty, T.zeros((2,), 'int32') , self.t[idx_sv])\n self.logpC_usv = theano.ifelse.ifelse(is_usv_empty, T.zeros((2,C), theano.config.floatX), self.logpC_usv)\n \n # Compute mean divisor since T.mean causes divisions by zero if there\n # are no labeled or unlabeled data in the minibatch. Therefore, we\n # compute T.mean with T.sum()/N\n self.aux_mean_divisor_sv = T.switch(is_sv_empty, 1., self.logpC_sv.shape[0])\n self.aux_mean_divisor_usv = T.switch(is_usv_empty, 1., self.logpC_usv.shape[0])\n\n # Create cost functions\n\n # Compute the log of the softmax of logpc which gives the log of the conditional likelihood\n self.cll_max_tmp = T.max(self.logpC_sv, axis=1, keepdims=True)\n self.cll_logsumexp = T.log(T.sum(T.exp(self.logpC_sv - self.cll_max_tmp), axis=1)) + T.reshape(self.cll_max_tmp, (self.cll_max_tmp.shape[0],))\n self.cost_cll = theano.ifelse.ifelse(is_sv_empty, 0., -T.sum(self.logpC_sv[T.arange(self.logpC_sv.shape[0]), self.t_sv] - self.cll_logsumexp))\n self.cost_cll_normalized = self.cost_cll / self.aux_mean_divisor_sv\n \n # Negative log-likelihood of labeled data\n self.cost_nll_sv = theano.ifelse.ifelse(is_sv_empty, 0., -T.sum(self.logpC_sv[T.arange(self.t_sv.shape[0]), self.t_sv]))\n self.cost_nll_sv_normalized = self.cost_nll_sv / self.aux_mean_divisor_sv\n \n # Negative log-likelihood of unlabeled data\n self.logpC_usv_max = T.max(self.logpC_usv, axis=1, keepdims=True)\n self.logpC_usv_logsumexp = T.log(T.sum(T.exp(self.logpC_usv - self.logpC_usv_max), axis=1)) + T.reshape(self.logpC_usv_max, (self.logpC_usv.shape[0],))\n self.cost_nll_usv = theano.ifelse.ifelse(is_usv_empty, 0., -T.sum(self.logpC_usv_logsumexp))\n self.cost_nll_usv_normalized = self.cost_nll_usv / self.aux_mean_divisor_usv\n \n # Total negative log-likelihood\n self.cost_nll = self.cost_nll_sv + self.cost_nll_usv\n self.cost_nll_normalized = self.cost_nll / self.x.shape[0]\n \n self.margin_start = self.gamma + self.logpC_sv - T.reshape(self.logpC_sv[T.arange(self.t_sv.shape[0]), self.t_sv], (self.t_sv.shape[0], 1))\n self.margin = self.gamma + self.logpC_sv - T.reshape(self.logpC_sv[T.arange(self.t_sv.shape[0]), self.t_sv], (self.t_sv.shape[0], 1))\n self.margin *= self.eta\n self.margin = T.set_subtensor(self.margin[T.arange(self.t_sv.shape[0]), self.t_sv], -np.inf)\n \n # Log-sum-exp trick\n self.margin_max_tmp = T.max(self.margin, axis=1, keepdims=True)\n self.max_margin = T.log(T.sum(T.exp(self.margin - self.margin_max_tmp), axis=1)) + T.reshape(self.margin_max_tmp, (self.margin.shape[0],))\n self.max_margin /= self.eta\n\n # The cast in the following statement resolves an error that says that\n # both paths of ifelse must be of equal type. Setting the dtype argument\n # of T.sum did not solve the problem.\n self.cost_mm = theano.ifelse.ifelse(is_sv_empty, 0., T.cast(T.sum(T.nnet.relu(self.max_margin)), theano.config.floatX))\n self.cost_mm_normalized = self.cost_mm / self.aux_mean_divisor_sv\n \n # Note: The division by self.x.shape[0] in the following two expressions\n # ensures that gradients of minibatches are unbiased.\n\n # Cost with CLL criterion\n self.cost_hybrid_cll = (self.tradeoff_hybrid * (self.tradeoff_ssl * self.cost_nll_sv + (1. - self.tradeoff_ssl) * self.cost_nll_usv) + (1. - self.tradeoff_hybrid) * self.cost_cll) / (self.x.shape[0])\n\n # Cost with MM criterion \n self.cost_hybrid_mm = (self.tradeoff_hybrid * (self.tradeoff_ssl * self.cost_nll_sv + (1. - self.tradeoff_ssl) * self.cost_nll_usv) + (1. - self.tradeoff_hybrid) * self.cost_mm) / (self.x.shape[0])\n\n # Predictions and classification errors\n self.y = T.argmax(self.logpC, axis=1)\n self.y_sv = self.y[idx_sv]\n self.y_usv = self.y[idx_usv]\n self.ce = theano.ifelse.ifelse(is_sv_empty, 0., T.mean(T.neq(self.y_sv, self.t_sv), dtype=theano.config.floatX))\n\n def getParameters(self):\n params = {'mu' : self.means.get_value(borrow=True),\n 'd_rho' : self.d_rho.get_value(borrow=True),\n 'prior_k_rho' : self.prior_k_rho.get_value(borrow=True),\n 'prior_c_rho' : self.prior_c_rho.get_value(borrow=True)}\n return params\n\n","sub_path":"models/GMMClassifierSSL.py","file_name":"GMMClassifierSSL.py","file_ext":"py","file_size_in_byte":14808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"533259172","text":"n = int(input()) # 배달해야 하는 설탕 kg 수\n\nresult = 0 # 봉지 수\nwhile n >= 0:\n if n % 5 == 0: # 5의 배수인 경우\n result += n // 5 # 5로 나눈 몫\n print(result)\n break\n n -= 3 # 설탕 kg 수가 5의 배수가 될 때까지 반복\n result += 1 # 봉지 추가\nelse:\n print(-1) # while 조건문이 거짓이 되면 -1 출력\n","sub_path":"BOJ/Steps/Step8/2839.py","file_name":"2839.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"628638875","text":"from django.contrib import admin\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\npath('', views.home, name='home'),\n\npath('base/',views.base,name='base'),\npath('base/add',views.add,name='add'),\npath('update//',views.update,name='update'),\npath('register', views.register, name='register'),\npath('delete//', views.delete, name='delete'),\n\n]","sub_path":"Gbrenterprises/mywebsite/GBR/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"47560778","text":"import pandas as pd\nfrom PyQt5 import QtCore, QtWidgets, QtGui\nfrom PyQt5.QtCore import Qt\n\nfrom components import Settings, TableModel, Utilities\nimport json\n\nfrom components.scenario import Section\nfrom scripts.htest import MultiIndexHeaderView, HorizontalHeaderDataRole, VerticalHeaderDataRole\n\n\nclass ScheduleParser:\n # Section / Room View\n # Subject Name + Instructor\n # Instructor View\n # Subject Name + Instructor + Section\n\n # table = QTableView, data = []\n def __init__(self, scenario, table, data):\n self.scenario = scenario\n self.table = table\n self.settings = settings = Settings.getSettings()\n self.build_model()\n MultiIndexHeaderView(Qt.Horizontal, table)\n MultiIndexHeaderView(Qt.Vertical, table)\n table.horizontalHeader().setSectionsMovable(True) # reorder DataFrame columns manually\n\n # Set data\n table.setModel(self.model)\n table.resizeColumnsToContents()\n table.resizeRowsToContents()\n table.setFocusPolicy(QtCore.Qt.NoFocus)\n table.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)\n self.parseData(data)\n\n # data = [{'color': None, 'text': '', 'instances': [[day, startingTS, endingTS]]}]\n def parseData(self, data):\n view = self.table\n model = self.model\n for entry in data:\n entry['color'] = Utilities.colorGenerator()\n for instance in entry['instances']:\n index = model.index(instance[1], instance[0])\n view.setSpan(instance[1], instance[0], instance[2] - instance[1], 1)\n item = QtGui.QStandardItem(entry['text'])\n item.setBackground(QtGui.QBrush(QtGui.QColor(*entry['color'])))\n item.setForeground(QtGui.QBrush(QtGui.QColor(*Utilities.textColor(entry['color']))))\n model.setData(index, item)\n\n def subjectGenerator(self):\n print(self.settings['starting_time'])\n\n def build_model(self):\n days = ['Mo', 'Di', 'Mi', 'Do', 'Fr']\n with open('timeslots.json') as json_file:\n self.timeslots = timeslots = json.load(json_file)['timeslots']\n col_header = []\n total_timeslots = 0\n for day in days:\n for slot in timeslots[self.settings['starting_time']:self.settings['ending_time'] + 1]:\n col_header.append(f\"{day}_{slot}\")\n total_timeslots = total_timeslots + 1\n section: Section\n row_header = []\n temporaryData = []\n for id, section in self.scenario.sections.items():\n row_header.append(f\"{section.name}\")\n temp = [\"\" for i in range(total_timeslots)]\n temporaryData.append(temp)\n header = [col_header, row_header]\n self.model = ScheduleParserModel(header, temporaryData)\n\n\nclass ScheduleParserModel(TableModel.TableModel):\n def __init__(self, header, table_data):\n super().__init__(header, table_data)\n\n def setData(self, index, value, role=None):\n if not index.isValid():\n return False\n elif role is None:\n self.table_data[index.row()][index.column()] = value\n self.dataChanged.emit(index, index)\n return True\n\n def data(self, index, role):\n row, col = index.row(), index.column()\n if role == QtCore.Qt.TextAlignmentRole:\n return QtCore.Qt.AlignCenter\n elif role in (Qt.DisplayRole, Qt.ToolTipRole):\n return \"Test\" #QtCore.QVariant()\n elif role in (HorizontalHeaderDataRole, VerticalHeaderDataRole):\n hm = QtGui.QStandardItemModel()\n hm.appendRow(QtGui.QStandardItem(\"Test2\"))\n return hm\n #return self.table_data[index.row()][index.column()].text()\n","sub_path":"components/ScheduleParser.py","file_name":"ScheduleParser.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"625012912","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom kuorimo.misc.database import Database, iter_db_results\nfrom kuorimo.misc.text_wrap import wrap_customer\n\n\ndef show_customers(d, size=20):\n cursor = d.get_cursor()\n db_result = cursor.execute(\"\"\"SELECT * FROM customer ORDER by number ASC\"\"\")\n iter_db_results(db_result, size, wrap_func=wrap_customer)\n cursor.close()\n\n\ndef get_customers(d):\n cursor = d.get_cursor()\n db_result = cursor.execute(\"\"\"SELECT * FROM customer ORDER by name ASC\"\"\")\n r = list(db_result)\n cursor.close()\n return r\n\n\ndef show_customer(d, number):\n cursor = d.get_cursor()\n db_result = cursor.execute(\"SELECT * FROM customer WHERE number=?\", (number, ))\n count = iter_db_results(db_result, 1, wrap_func=wrap_customer)\n cursor.close()\n return count\n\n\ndef get_customer_name(d, number):\n cursor = d.get_cursor()\n db_result = cursor.execute(\"SELECT name FROM customer WHERE number=?\", (number,))\n name = db_result.fetchone().get('name').encode('utf8')\n cursor.close()\n return name\n\n\ndef insert_customer(d, customer_number, customer_name):\n cursor = d.get_cursor()\n cursor.execute(\"INSERT INTO customer VALUES (?,?)\", (customer_number, customer_name.decode('utf-8')))\n cursor.close()\n d.commit()\n\n\ndef edit_customer_by_number(d, customer_number, customer_name):\n cursor = d.get_cursor()\n cursor.execute(\"UPDATE customer SET name=? WHERE number=?\", (customer_name.decode('utf-8'), customer_number))\n cursor.close()\n d.commit()\n\n\ndef delete_customer_by_number(d, customer_number):\n cursor = d.get_cursor()\n cursor.execute(\"DELETE FROM customer WHERE number=?\", (customer_number, ))\n cursor.close()\n d.commit()\n\n\nif __name__ == '__main__':\n d = Database()\n\n insert_customer(d, 29, 'Pori')\n #delete_customer_by_number(d, 26)\n\n show_customers(d)\n\n\n\n\n","sub_path":"src/kuorimo/api/customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"423776192","text":"\nfrom smtplib import SMTP\nfrom email.mime.text import MIMEText\nfrom json import load\nfrom requests import get\nfrom os.path import exists\nfrom shutil import copyfile\n\n\nclass MorningMail:\n\n def __init__(self):\n self.weather_data = {}\n\n print(\"Loading config file...\")\n self._load_config()\n\n def _load_config(self):\n\n if exists(\"config.json\"):\n with open(\"config.json\") as config:\n self.config = load(config)\n else:\n print(r\"Please add your config to config.json and restart.\")\n copyfile(\"config-template.json\", \"config.json\")\n exit(1)\n\n def send_mail(self):\n print(\"Sending mail...\")\n weather_data = get(\n r\"http://api.openweathermap.org/data/2.5/weather\",\n params=dict(\n q=','.join(self.config[\"location\"]),\n appid=self.config[\"openweathermap\"][\"api_key\"]\n )\n ).json()\n\n conversions = {\n \"temperature\": {\n \"key\": \"temperature\",\n \"default\": \"Farenheit\",\n \"convert\": {\n \"f\": 1.8 * weather_data[\"main\"][\"temp\"] - 459.67,\n \"c\": weather_data[\"main\"][\"temp\"] - 273.15,\n \"k\": weather_data[\"main\"][\"temp\"]\n }\n },\n \"distance\": {\n \"key\": \"wind_speed\",\n \"default\": \"miles\",\n \"convert\": {\n \"m\": weather_data[\"wind\"][\"speed\"],\n \"k\": weather_data[\"wind\"][\"speed\"] / 0.62137\n }\n }\n }\n\n for unit, data in conversions.items():\n if self.config[\"units\"][unit][0].lower() not in data[\"convert\"]:\n print(\"{} is not a valid unit. Defaulting to {}.\".format(\n self.config[\"units\"][unit]), data[\"default\"])\n self.config[\"units\"][unit] = data[\"default\"]\n self.weather_data[data[\"key\"]] = data[\"convert\"][\n self.config[\"units\"][unit][0].lower()]\n\n self.weather_data[\"humidity\"] = weather_data[\"main\"][\"humidity\"]\n\n body = \"\"\"\n {text[greeting]}\n\n The temperature is {weather[temperature]:.2f} °{units[temperature]}!\n The wind speed is {weather[wind_speed]:.2f} {units[distance]}/h!\n The humidity is {weather[humidity]:.0f}%!\n\n {text[inspiration]}\n \"\"\".format(\n text=self.config[\"text\"],\n weather=self.weather_data,\n units=self.config[\"units\"]\n )\n\n message = MIMEText(body)\n message['Subject'] = self.config[\"text\"][\"subject\"]\n message['From'] = self.config[\"email\"][\"auth\"][\"user\"]\n message['To'] = ', '.join(self.config[\"recipients\"])\n\n session = SMTP(**self.config[\"email\"][\"config\"])\n session.starttls()\n session.login(**self.config[\"email\"][\"auth\"])\n session.sendmail(\n self.config[\"email\"][\"auth\"][\"user\"],\n self.config[\"recipients\"],\n message.as_string()\n )\n session.quit()\n print(\"Mail sent!\")\n\nMorningMail().send_mail()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"468891395","text":"from datetime import date, datetime, timedelta\n\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom smart_selects.db_fields import ChainedForeignKey, GroupedForeignKey\n\nfrom Einsatzmittel.models import Bus\n\n\nclass Tour(models.Model):\n klient = models.ForeignKey('Klienten.Klienten', related_name='klient', on_delete=models.CASCADE)\n bus = models.ForeignKey('Einsatzmittel.Bus', related_name='bus2', on_delete=models.CASCADE)\n datum = models.ForeignKey('Einsatztage.Fahrtag', related_name='datum2', on_delete=models.CASCADE)\n uhrzeit = models.TimeField(verbose_name=\"Abholzeit\")\n termin = models.TimeField(blank=True, null=True, verbose_name=\"Termin\")\n abholklient = models.ForeignKey('Klienten.Klienten', null=True, related_name='abholort', verbose_name=\"Wo\",\n help_text=\"Bei wem soll der Fahrgast abgeholt werden?\", on_delete=models.CASCADE)\n zielklient = models.ForeignKey('Klienten.Klienten', null=True, related_name='zielort', verbose_name=\"Wohin\",\n help_text=\"Zu wem soll der Fahrgast gebracht werden?\", on_delete=models.CASCADE)\n entfernung = models.CharField(max_length=100, blank=True, null=True)\n ankunft = models.TimeField(blank=True, null=True)\n bemerkung = models.TextField(max_length=200, blank=True, null=True)\n personenzahl = models.IntegerField(default=1, verbose_name=\"Personen\")\n zustieg = models.BooleanField(default=False)\n konflikt = models.TextField(max_length=200, blank=True, null=True)\n konflikt_richtung = models.CharField(max_length=2, blank=True, null=True)\n konflikt_zeiten = models.TextField(max_length=20, blank=True, null=True)\n archiv = models.BooleanField(default=False)\n created_on = models.DateTimeField(auto_now_add=True, null=True)\n created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name=\"+\", on_delete=models.SET_NULL)\n updated_on = models.DateTimeField(auto_now=True, blank=True, null=True)\n updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,\n related_name=\"+\", on_delete=models.SET_NULL)\n\n @property\n def abholort(self):\n if (self.klient == self.abholklient):\n return '\\n'.join([self.abholklient.ort.ort, self.abholklient.strasse.strasse + \" \"+self.abholklient.hausnr])\n else:\n return '\\n'.join([self.abholklient.name, self.abholklient.ort.ort, self.abholklient.strasse.strasse + \" \" +\n self.abholklient.hausnr, self.abholklient.telefon])\n\n @property\n def zielort(self):\n if (self.klient == self.zielklient):\n return '\\n'.join([self.zielklient.ort.ort, self.zielklient.strasse.strasse + \" \"+self.zielklient.hausnr])\n else:\n return '\\n'.join([self.zielklient.name, self.zielklient.ort.ort, self.zielklient.strasse.strasse + \" \"+self.zielklient.hausnr, self.zielklient.telefon])\n\n @property\n def fahrgast(self):\n return self.klient\n\n @property\n def is_today(self):\n return date.today() == self.datum.datum\n\n @property\n def has_markup_text(self):\n return len(set(settings.MARKUP_TEXT.lower().split(',')).intersection(set(self.bemerkung.lower().split()))) > 0\n\n @property\n def has_conflict(self):\n return self.konflikt != ''\n\n @property\n def hat_abhol_qr(self):\n if self.abholklient.latitude == 0:\n return False\n if self.abholklient.longitude == 0:\n return False\n return self.bus.qr_code\n\n @property\n def hat_ziel_qr(self):\n if self.zielklient.latitude == 0:\n return False\n if self.zielklient.longitude == 0:\n return False\n return self.bus.qr_code\n\n def einsatz_bus(self):\n rows = Fahrtag.objects.filter(datum=self.datum.datum).values_list('team', flat=True)\n einsatz_bus = [row for row in rows]\n return 'Bus '+str(einsatz_bus[0])\n\n @property\n def datum_bus(self):\n return ' '.join([str(self.datum.datum), str(self.klient.bus)])\n\n @property\n def wochentag(self):\n wochentage = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']\n return wochentage[self.datum.weekday()]\n\n def __unicode__(self):\n return self.name\n\n def __str__(self):\n return ' '.join([self.klient.name, str(self.klient.bus), str(self.datum), str(self.uhrzeit)])\n\n class Meta():\n verbose_name_plural = \"Touren\"\n verbose_name = \"Tour\"\n constraints = [models.UniqueConstraint(fields=['bus', 'datum', 'uhrzeit'], name='unique_tour')]\n","sub_path":"Tour/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"143558697","text":"import csv\nimport numpy as np\n\n\ndef RankFetcher(RollNo, FileName):\n\n reader=csv.reader(open(FileName, 'r'))\n\n rank_vs_marks=dict()\n count=dict()\n\n for row in reader:\n k, v = row\n rank_vs_marks[int(k)]=float(v)\n count[float(v)]=count.get(float(v), 0)+1\n\n marks=rank_vs_marks[RollNo]\n tie=count[marks]\n rank= [i+1 for i, value in enumerate(sorted(count.items(), reverse=True)) if value == (marks, tie)]\n\n return marks, tie, rank[0]\n\nData_file='marksheet.csv'\n\nwhile(True):\n Student_roll_no=input('Enter Roll Number: ')\n\n if Student_roll_no == \"stop\":\n break\n\n else:\n Student_roll_no=int(Student_roll_no)\n student_marks, tie_between, student_rank = RankFetcher(Student_roll_no, Data_file)\n\n print('Marks: {}, Rank: {}, Tied Between: {}'.format(student_marks, student_rank, tie_between))\n\n","sub_path":"Fetch My Rank/Fetch_My_rank.py","file_name":"Fetch_My_rank.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"62436542","text":"import tkinter as tk\nimport bluetooth as bt\nimport sys\nimport os\n\ndef connect():\n if socket != None:\n return\n print (\"Searching for service...\")\n uuid = \"00001101-0000-1000-8000-00805F9B34FB\"\n services = bt.find_service(uuid=uuid, address=sys.argv[1])\n if (len(services) == 0):\n print(\"Could not find service\")\n else:\n service = services[0] \n port = service[\"port\"]\n name = service[\"name\"]\n host = service[\"host\"]\n\n print (\"Connecting to\",name,\"on\",host)\n global_list = globals()\n global_list[\"socket\"] = bt.BluetoothSocket(bt.RFCOMM)\n try:\n global_list[\"socket\"].connect((sys.argv[1], port))\n except:\n return\n print (\"Connected to\", name)\n for button in btns.values():\n button[\"state\"] = tk.NORMAL\n\ndef send(message):\n if socket != None:\n try:\n socket.send(message)\n print(\"'\"+message+\"' sent\")\n except:\n disconnect()\n\n\ndef disconnect():\n if socket != None:\n print (\"Closing socket...\")\n global_list = globals()\n global_list[\"socket\"].close()\n global_list[\"socket\"] = None\n print (\"Socket closed\")\n for button in btns.values():\n button[\"state\"] = tk.DISABLED\n\ndef keydown(e):\n key = e.keysym.lower()\n message = key + \"_pressed\"\n send(message)\n\ndef keyup(e):\n key = e.keysym.lower()\n message = key + \"_released\"\n send(message)\n\ndef close():\n disconnect()\n os.system('xset r on')\n window.destroy()\n\nif __name__ == '__main__':\n socket = None\n os.system(\"xset r off\")\n window = tk.Tk()\n window.title(\"Bluetooth controller\")\n window.geometry(\"120x120\")\n window.bind('', keydown)\n window.bind('', keyup)\n window.protocol('WM_DELETE_WINDOW', close)\n \n btns = {\n \"up\": tk.Button(window, text=\"↑\", state=tk.DISABLED, command=lambda:send('up')),\n \"down\": tk.Button(window, text=\"↓\", state=tk.DISABLED, command=lambda:send('down')),\n \"right\": tk.Button(window, text=\"→\", state=tk.DISABLED, command=lambda:send('right')),\n \"left\": tk.Button(window, text=\"←\", state=tk.DISABLED, command=lambda:send('left')),\n \"a\": tk.Button(window, text=\"A\", state=tk.DISABLED, command=lambda:send('a')),\n \"b\": tk.Button(window, text=\"B\", state=tk.DISABLED, command=lambda:send('b')),\n }\n\n btn_disconnect = tk.Button(window, text=\"x\", command=disconnect)\n btn_connect = tk.Button(window, text=\"o\", command=connect)\n\n btns[\"up\"].grid(column=1,row=0)\n btns[\"down\"].grid(column=1,row=3)\n btns[\"right\"].grid(column=2,row=2)\n btns[\"left\"].grid(column=0,row=2)\n btns[\"a\"].grid(column=0,row=3)\n btns[\"b\"].grid(column=2,row=3)\n btn_disconnect.grid(column=0, row=4)\n btn_connect.grid(column=1, row=4)\n \n window.mainloop()\n\n","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"649095652","text":"import scrapy\nimport argh\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy.settings import Settings\n\nUSER_AGENTS = [\n \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)\",\n \"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)\",\n \"Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)\",\n \"Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)\",\n \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)\",\n \"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)\",\n \"Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)\",\n \"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)\",\n \"Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6\",\n \"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1\",\n \"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0\",\n \"Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5\",\n \"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20\",\n \"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52\",\n]\n\nclass BHarianListingSpider(scrapy.Spider):\n\n\n allowed_domains = ['bharian.com.my']\n\n\n def parse(self, response):\n for newslead in response.css('.view-section-listing > .view-content > .row'):\n title = newslead.css('h2 > a::text').extract_first() or ''\n url = newslead.css('h2 > a::attr(href)').extract_first() or ''\n summary = newslead.css('p.lead::text').extract_first() or ''\n postdate = newslead.css('small::text').extract_first() or ''\n yield {'title': title.strip(), \n 'summary': summary.strip(), \n 'postdate': postdate.strip(),\n 'type': self._type, \n 'url': response.urljoin(url)}\n\n nextpage = response.css('.pager .pager-next a::attr(href)').extract_first()\n if nextpage:\n yield scrapy.Request(response.urljoin(nextpage), self.parse)\n\nclass CrimeNewsSpider(BHarianListingSpider):\n name = 'BHarian Crime News Scraper'\n\n _type = 'crime'\n\n start_urls = [\n 'http://www.bharian.com.my/jenayah'\n ]\n\nclass BusinessNewsSpider(BHarianListingSpider):\n name = 'BHarian Business News Scraper'\n\n _type = 'business'\n\n start_urls = [\n 'http://www.bharian.com.my/bisnes'\n ]\n\nclass PoliticsNewsSpider(BHarianListingSpider):\n name = 'BHarian Political News Scraper'\n\n _type = 'politics'\n\n start_urls = [\n 'http://www.bharian.com.my/politik'\n ]\n\n\nclass Runner(object):\n\n def __init__(self, output, spider):\n self.output = output\n self.spider = spider\n\n def run(self):\n process = CrawlerProcess({\n 'FEED_URI': self.output,\n 'FEED_FORMAT': 'jsonlines',\n 'USER_AGENTS': USER_AGENTS,\n 'DOWNLOAD_DELAY': 3,\n 'AUTOTHROTTLE_ENABLED': True,\n 'AUTOTHROTTLE_START_DELAY': 3,\n 'AUTOTHROTTLE_MAX_DELAY': 60\n })\n\n process.crawl(self.spider)\n process.start()\n\n\n@argh.arg('output', help='Output file')\ndef crime(output):\n runner = Runner(output, CrimeNewsSpider)\n runner.run()\n\n@argh.arg('output', help='Output file')\ndef business(output):\n runner = Runner(output, BusinessNewsSpider)\n runner.run()\n\n\n@argh.arg('output', help='Output file')\ndef politics(output):\n runner = Runner(output, PoliticsNewsSpider)\n runner.run()\n\nparser = argh.ArghParser()\nparser.add_commands([crime, business, politics])\n\ndef main():\n parser.dispatch()\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"src/drsa/scrapers/bharian_scraper.py","file_name":"bharian_scraper.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"329682012","text":"# Usage: python import_weights.py netfile layer1.h5 layer2.h5 ... output\n# Will create a file with caffemodel extension.\n\n# Once created the caffemodel can be tested with:\n# caffe.bin test -model dev.net -weights dev.caffemodel -gpu 0 -iterations 600\n\n# Using dir() to figure out the interface:\n# net: Net\n# net.params: OrderedDict\n# net.params['fc1']: BlobVec\n# net.params['fc1'][0]: Blob\n# net.params['fc1'][0].data: array\n# net.params['fc1'][0].diff: array\n# net.params['fc1'][0].data.shape: (1, 1, 20000, 1326)\n# net.params['fc1'][1].data.shape: (1, 1, 1, 20000)\n\nimport sys\nimport h5py\nimport caffe\n\nnet=caffe.Net(sys.argv[1], caffe.TRAIN)\nargi=2\n\nfor k,v in net.params.iteritems():\n f = h5py.File(sys.argv[argi], 'r')\n v[0].data[...] = f['w'][...].transpose().reshape(v[0].data.shape)\n v[1].data[...] = f['b'][...].reshape(v[1].data.shape)\n f.close()\n argi += 1\n\nnet.save(sys.argv[argi])\n","sub_path":"test/.deprecated/import_weights.py","file_name":"import_weights.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"236679258","text":"#!/usr/bin/python3\n'''\n* Copyright (C) 2019-2020 Intel Corporation.\n*\n* SPDX-License-Identifier: BSD-3-Clause\n'''\n\nfrom urllib.parse import urljoin\nimport json\nimport time\nimport os\nimport sys\nimport requests\nfrom results_watcher import ResultsWatcher\nfrom vaserving.pipeline import Pipeline\n\nSERVER_ADDRESS = \"http://localhost:8080/\"\nRESPONSE_SUCCESS = 200\nTIMEOUT = 30\nSLEEP_FOR_STATUS = 0.5\nWATCHER_POLL_TIME = 0.01\n#nosec skips pybandit hits\nREQUEST_TEMPLATE = {\n \"source\": {\n \"uri\": \"\",\n \"type\": \"uri\"\n },\n \"destination\": {\n \"metadata\": {\n \"type\": \"file\",\n \"path\": \"/tmp/results.jsonl\", # nosec\n \"format\": \"json-lines\"\n }\n }\n}\n\nRTSP_TEMPLATE = {\n \"frame\": {\n \"type\": \"rtsp\",\n \"path\": \"\"\n }\n}\nSERVER_CONNECTION_FAILURE_MESSAGE = \"Unable to connect to server, check if the vaserving microservice is running\"\n\ndef run(args):\n request = REQUEST_TEMPLATE\n update_request_options(request, args)\n try:\n watcher = None\n started_instance_id = start_pipeline(request,\n args.pipeline,\n verbose=args.verbose,\n show_request=args.show_request)\n if started_instance_id is None:\n sys.exit(1)\n try:\n if request['destination']['metadata']['type'] == 'file'and \\\n os.path.exists(request['destination']['metadata']['path']):\n watcher = ResultsWatcher(request['destination']['metadata']['path'])\n watcher.watch()\n except KeyError:\n pass\n print_fps(wait_for_pipeline_completion(args.pipeline, started_instance_id))\n except KeyboardInterrupt:\n print()\n if started_instance_id:\n stop_pipeline(args.pipeline, started_instance_id)\n print_fps(wait_for_pipeline_completion(args.pipeline, started_instance_id))\n finally:\n if watcher:\n watcher.stop()\n\ndef start(args):\n request = REQUEST_TEMPLATE\n update_request_options(request, args)\n start_pipeline(request,\n args.pipeline,\n verbose=args.verbose,\n show_request=args.show_request)\n\ndef stop(args):\n stop_pipeline(args.pipeline, args.instance, args.show_request)\n print_fps(get_pipeline_status(args.pipeline, args.instance))\n\ndef wait(args):\n try:\n pipeline_status = get_pipeline_status(args.pipeline, args.instance, args.show_request)\n if pipeline_status is not None and \"state\" in pipeline_status:\n print(pipeline_status[\"state\"])\n else:\n print(\"Unable to fetch status\")\n print_fps(wait_for_pipeline_completion(args.pipeline,\n args.instance))\n except KeyboardInterrupt:\n print()\n stop_pipeline(args.pipeline, args.instance)\n print_fps(wait_for_pipeline_completion(args.pipeline,\n args.instance))\n\ndef status(args):\n pipeline_status = get_pipeline_status(args.pipeline, args.instance, args.show_request)\n if pipeline_status is not None and \"state\" in pipeline_status:\n print(pipeline_status[\"state\"])\n else:\n print(\"Unable to fetch status\")\n\ndef list_pipelines(args):\n _list(\"pipelines\", args.show_request)\n\ndef list_models(args):\n _list(\"models\", args.show_request)\n\ndef update_request_options(request,\n args):\n if hasattr(args, 'uri'):\n request[\"source\"][\"uri\"] = args.uri\n if hasattr(args, 'destination') and args.destination:\n request['destination']['metadata'].update(args.destination)\n if hasattr(args, 'parameters') and args.parameters:\n request[\"parameters\"] = dict(args.parameters)\n if hasattr(args, 'parameter_file') and args.parameter_file:\n with open(args.parameter_file, 'r') as parameter_file:\n request.update(json.load(parameter_file))\n if hasattr(args, 'tags') and args.tags:\n request[\"tags\"] = dict(args.tags)\n if hasattr(args, 'rtsp_path') and args.rtsp_path:\n rtsp_template = RTSP_TEMPLATE\n rtsp_template['frame']['path'] = args.rtsp_path\n request['destination'].update(rtsp_template)\n\ndef start_pipeline(request,\n pipeline,\n verbose=True,\n show_request=False):\n \"\"\"Launch requested pipeline\"\"\"\n try:\n if request['destination']['metadata']['type'] == 'file':\n output_file = request['destination']['metadata']['path']\n os.remove(os.path.abspath(output_file))\n except KeyError:\n pass\n except FileNotFoundError:\n pass\n except OSError:\n raise OSError(\"Unable to delete destination metadata file {}\".format(output_file))\n if verbose and not show_request:\n print(\"Starting pipeline...\")\n\n pipeline_url = urljoin(SERVER_ADDRESS,\n \"pipelines/\" + pipeline)\n instance_id = post(pipeline_url, request, show_request)\n if instance_id:\n if verbose:\n print(\"Pipeline running: {}, instance = {}\".format(pipeline, instance_id))\n else:\n print(instance_id)\n return instance_id\n if verbose:\n print(\"Pipeline failed to start\")\n\n return None\n\ndef stop_pipeline(pipeline, instance_id, show_request=False):\n if not show_request:\n print(\"Stopping Pipeline...\")\n stop_url = urljoin(SERVER_ADDRESS,\n \"/\".join([\"pipelines\",\n pipeline,\n str(instance_id)]))\n status_code = delete(stop_url, show_request)\n if status_code == RESPONSE_SUCCESS:\n print(\"Pipeline stopped\")\n else:\n print(\"Pipeline NOT stopped\")\n\ndef wait_for_pipeline_completion(pipeline,\n instance_id):\n status = {\"state\" : \"RUNNING\"}\n while status and not Pipeline.State[status[\"state\"]].stopped():\n status = get_pipeline_status(pipeline,\n instance_id)\n time.sleep(SLEEP_FOR_STATUS)\n if status and status[\"state\"] == \"ERROR\":\n raise ValueError(\"Error in pipeline, please check vaserving log messages\")\n\n return status\n\ndef get_pipeline_status(pipeline, instance_id, show_request=False):\n status_url = urljoin(SERVER_ADDRESS,\n \"/\".join([\"pipelines\",\n pipeline,\n str(instance_id),\n \"status\"]))\n return get(status_url, show_request)\n\ndef _list(list_name, show_request=False):\n url = urljoin(SERVER_ADDRESS, list_name)\n response = get(url, show_request)\n if response is None:\n print(\"Got empty response retrieving {}\".format(list_name))\n return\n print_list(response)\n\ndef post(url, body, show_request=False):\n try:\n if show_request:\n print('POST {}\\nBody:{}'.format(url, body))\n sys.exit(0)\n launch_response = requests.post(url, json=body, timeout=TIMEOUT)\n if launch_response.status_code == RESPONSE_SUCCESS:\n instance_id = int(launch_response.text)\n return instance_id\n print(\"Got unsuccessful status code: {}\".format(launch_response.status_code))\n print(launch_response.text)\n except requests.exceptions.ConnectionError:\n raise ConnectionError(SERVER_CONNECTION_FAILURE_MESSAGE)\n return None\n\ndef get(url, show_request=False):\n try:\n if show_request:\n print('GET {}'.format(url))\n sys.exit(0)\n status_response = requests.get(url, timeout=TIMEOUT)\n if status_response.status_code == RESPONSE_SUCCESS:\n return json.loads(status_response.text)\n print(\"Got unsuccessful status code: {}\".format(status_response.status_code))\n print(status_response.text)\n except requests.exceptions.ConnectionError:\n raise ConnectionError(SERVER_CONNECTION_FAILURE_MESSAGE)\n return None\n\ndef delete(url, show_request=False):\n try:\n if show_request:\n print('DELETE {}'.format(url))\n sys.exit(0)\n stop_response = requests.delete(url, timeout=TIMEOUT)\n if stop_response.status_code != RESPONSE_SUCCESS:\n print(\"Unsuccessful status code {} - {}\".format(stop_response.status_code, stop_response.text))\n return stop_response.status_code\n except requests.exceptions.ConnectionError:\n raise ConnectionError(SERVER_CONNECTION_FAILURE_MESSAGE)\n return None\n\ndef print_fps(status):\n if status and 'avg_fps' in status:\n print('avg_fps: {:.2f}'.format(status['avg_fps']))\n\ndef print_list(item_list):\n for item in item_list:\n print(\" - {}/{}\".format(item[\"name\"], item[\"version\"]))\n","sub_path":"vaclient/vaclient.py","file_name":"vaclient.py","file_ext":"py","file_size_in_byte":8894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"417622192","text":"import netomaton as ntm\n\nif __name__ == '__main__':\n rule_table, actual_lambda, quiescent_state = ntm.random_rule_table(lambda_val=0.37, k=4, r=2,\n strong_quiescence=True, isotropic=True)\n\n adjacency_matrix = ntm.network.cellular_automaton(n=128, r=2)\n\n initial_conditions = ntm.init_random(128, k=4, n_randomized=20)\n\n # evolve the cellular automaton for 200 time steps\n activities, _ = ntm.evolve(initial_conditions, adjacency_matrix, timesteps=200,\n activity_rule=lambda ctx: ntm.table_rule(ctx, rule_table))\n\n ntm.plot_grid(activities)\n","sub_path":"demos/langtons_lambda/rule_table_demo.py","file_name":"rule_table_demo.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"356558453","text":"'''you are given with ‘arasu’ series(shown in example).\nYou have to understand it and you will be given a number ‘n’ ,you have to print the series till n numbers.\nSample Input :\n4\nSample Output :\n2 5 10 17\n'''\nnth_term=int(input())\nlast_term=nth_term+1\nfor number in range(1,last_term):\n if nth_term!=number:\n print((number**2)+1,end=' ')\n else:\n print((number**2)+1)\n","sub_path":"Python/Mathematics/541.py","file_name":"541.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"367745322","text":"\"\"\"Basic functionality for rest-service\n\"\"\"\nfrom typing import Optional\n\nfrom flask import abort, jsonify\nfrom flask.views import MethodView\n\nfrom ..database import db_session\nfrom . import bp\n\n\ndef register_api(view: MethodView, endpoint: str, url: str,\n pk: str = 'id', pk_type: str = 'int'):\n \"\"\"Add url rules for rest-api endpoint\n\n Args:\n view: view with get/post/put/delete methods\n endpoint: name of view\n url: endpoint url\n pk: primary key name\n pk_type: primary key type\n \"\"\"\n view_func = view.as_view(endpoint)\n bp.add_url_rule(url, defaults={pk: None},\n view_func=view_func, methods=['GET',])\n bp.add_url_rule(url, view_func=view_func, methods=['POST',])\n bp.add_url_rule(f'{url}<{pk_type}:{pk}>', view_func=view_func,\n methods=['GET', 'PUT', 'DELETE'])\n\n\ndef get_record_or_404(model, pk):\n \"\"\"Get row from database by primary key\n\n Args:\n model: database model (table)\n pk: primary key value\n\n Returns:\n instance of model\n\n Raises:\n HTTPError(404) if row is not found in table\n \"\"\"\n record = model.query.get(pk)\n if record is None:\n abort(404)\n return record\n\n\nclass BaseAPI(MethodView):\n \"\"\"Common class for description rest api\n\n Attributes:\n mode: base database model for enpoint\n namespace: name of endpoint\n \"\"\"\n model = None\n namespace = None\n\n def get(self, pk: Optional[int] = None):\n \"\"\"GET //\n\n Returns:\n 200, object or list of objects\n \"\"\"\n if pk is None:\n return self.get_list()\n\n return jsonify(get_record_or_404(self.model, pk).to_dict())\n\n def get_list(self):\n \"\"\"GET //\n\n Returns:\n 200, list of objects\n \"\"\"\n recordset = [\n record.to_dict()\n for record in self.model.query.all()\n ]\n\n return jsonify({self.namespace: recordset})\n\n def post(self):\n \"\"\"POST //\n\n Returns:\n 201, Created object\n \"\"\"\n record = self.create_record()\n\n db_session.add(record)\n db_session.commit()\n\n return (jsonify(record.to_dict()), 201)\n\n def put(self, pk: int):\n \"\"\"PUT //\n\n Returns:\n 200, changed object\n \"\"\"\n record = get_record_or_404(self.model, pk)\n record = self.update_record(record)\n\n db_session.commit()\n return jsonify(record.to_dict())\n\n def delete(self, pk: int):\n \"\"\"DELETE //\n\n Returns:\n 204\n \"\"\"\n record = get_record_or_404(self.model, pk)\n db_session.delete(record)\n db_session.commit()\n\n return ('', 204)\n\n def create_record(self):\n \"\"\"Create record (POST-method)\n \"\"\"\n raise NotImplementedError\n\n def update_record(self, record):\n \"\"\"Update record (PUT-method)\n\n Args:\n record: source object\n \"\"\"\n raise NotImplementedError\n","sub_path":"rest_service/api/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"198038270","text":"from flask import (\n render_template, request, jsonify, escape\n)\n\nfrom app import app, db\nfrom .models import Note\nfrom counter import count_unique_words\n\n\"\"\"\nI think templates are good solution for this task, because\nwe don't need to build SPA (according to the task description\nsite should contain two pages: one with adding form, second\nshows all the notes, so we don't need to build real-time \nnotes adding without refreshing of the page on a client).\nBut you can add multiple notes on adding page without refreshing\nof the page (client sends ajax request to the server and shows if\nadding was successful). Also notes deleting works without refreshing\nof the page (client also sends ajax request and clear notes section).\nAlso we have added trailing slash to routes that return html to avoid \nreturning 404 page when user adds slash to the route.\n\"\"\"\n\n\n@app.route('/', methods=['GET'])\n@app.route('/notes/', methods=['GET'])\ndef notes_get():\n \"\"\"\n Page with notes which are ordered by\n number of unique words in each note\n \"\"\"\n return render_template(\n 'notes.html',\n notes=Note.ordered_all(),\n title='Sorted notes'\n )\n\n\n@app.route('/notes/add/', methods=['GET'])\ndef notes_add_get():\n \"\"\"\n Page with form for adding a new note\n \"\"\"\n return render_template(\n 'add_note.html',\n title='Add new note'\n )\n\n# #############################################\n# ###### API ############\n# #############################################\n\n\n@app.route('/api/notes', methods=['DELETE'])\ndef notes_delete():\n \"\"\"\n Delete all the notes from database\n \"\"\"\n rows_deleted = Note.query.delete()\n db.session.commit()\n return jsonify(\n {'status': 'OK - {0} rows was deleted'.format(rows_deleted)}\n ), 200\n\n\n@app.route('/api/notes', methods=['POST'])\ndef notes_post():\n \"\"\"\n Add new note to database\n \"\"\"\n try:\n text = request.form['text']\n except KeyError:\n return jsonify({'status': 'there is no text field in the note'}), 400\n\n try:\n note = Note(\n # text will be escaped automatically while rendering\n text=text,\n unique_count=count_unique_words(text)\n )\n except ValueError as e: # failed validation\n return jsonify({'status': str(e)}), 400\n else:\n db.session.add(note)\n db.session.commit()\n\n # return created item (helpful while testing server from console)\n return jsonify(\n {\n 'status': 'OK - created a new note',\n 'note': {\n 'id': note.id,\n 'text': note.text,\n 'unique_count': note.unique_count\n }\n }\n ), 201\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"410232006","text":"import ilearn_scraper.filter_functions as ifilter\nfrom bs4 import BeautifulSoup\nfrom ilearn_scraper.request_functions import get_ilearn_page, get_ereserves_page\n\n\n##! Need a way to not get hidden resources\nclass _IlearnCourseSection:\n\n def __init__(self, section_content, section_id):\n self.section_id = section_id\n self.section_content = section_content\n self.section_summary = ifilter.get_section_summary(section_content)\n\n self.raw_section_links = (self.section_id, ifilter.get_section_links(section_content))\n self.section_resources = ifilter.sort_for_content_links(self.raw_section_links)\n self.suspect_links = []\n\n\nclass IlearnCoursePage:\n\n def __init__(self, page_id):\n self.page_id = page_id\n self.raw_course_page_html = get_ilearn_page(self.page_id)\n self.parsed_html = BeautifulSoup(self.raw_course_page_html, \"html.parser\")\n self.course_sections = [_IlearnCourseSection(content[0], content[1]) for content\n in ifilter.get_section_content(self.parsed_html)\n if content]\n self.course_name = self.parsed_html.find('title', text=True).text[8:]\n self.course_heading = self.parsed_html.find('h1', text=True)\n self.eReserve_files = self.check_eReserves()\n\n def get_all_resource_links(self):\n links_to_return = []\n for section in self.course_sections:\n for resource in section.section_resources:\n links_to_return.append(resource.resource_link)\n return links_to_return\n\n def get_sections(self):\n sections_to_return = []\n for section in self.course_sections:\n sections_to_return.append(section)\n return sections_to_return\n\n def get_sect_dict(self):\n section_dict = dict(zip([x.section_id for x in self.course_sections],\n [x.section_resources for x in self.course_sections]))\n return section_dict\n\n def check_eReserves(self):\n eReserve_block = self.parsed_html.find('aside', {'data-block': 'ereserves'})\n if eReserve_block:\n ereserves_link = ifilter.construct_ereserves_request_link(eReserve_block)\n ereserves_page = BeautifulSoup(get_ereserves_page(ereserves_link), \"html.parser\")\n ereserves_main_content = ereserves_page.find('div', {'role':'main'})\n ereserves_page_links = ifilter.get_section_links(ereserves_main_content)\n ereserve_content = ifilter.sort_for_content_links((None, ereserves_page_links))\n return ereserve_content\n\n else:\n return None\n\n def get_all_content(self):\n return_list = []\n for IlearnCourseSection in self.course_sections:\n\n section = {\"section\": IlearnCourseSection.section_id, \"resources\": []}\n\n for resource in IlearnCourseSection.section_resources:\n section[\"resources\"].append(resource())\n\n return_list.append(section)\n return return_list\n\n def get_staged_content(self):\n return_list = []\n\n for IlearnCourseSection in self.course_sections:\n\n section = {\"section\": IlearnCourseSection.section_id, \"resources\": []}\n\n for resource in IlearnCourseSection.section_resources:\n section[\"resources\"].append(resource)\n\n return_list.append(section)\n\n return return_list\n\n def __len__(self):\n return len(self.course_sections)\n","sub_path":"ilearn_scraper/moodle_core_objects.py","file_name":"moodle_core_objects.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"344013824","text":"# Import all needed libraries\nimport tensorflow as tf\nimport numpy as np\nimport time\nimport aux_funcs as aux\n\n\n# Function to sample text using a model trained on a certain text corpus\ndef sample(sample_length, session):\n seed = aux.encode([int(np.random.uniform(0, vocab_size))], vocab_size)\n seed = np.array([seed])\n _char_state = np.zeros((2, batch_size, hidden_dim))\n txt = ''\n for i in range(sample_length):\n char_probs, _char_state = session.run([probabilities, current_state],\n feed_dict={x: seed, init_state: _char_state})\n pred = np.random.choice(range(vocab_size), p=char_probs[0])\n seed = np.expand_dims(aux.encode([pred], vocab_size), axis=0)\n character = idx_to_char[pred]\n txt += character\n return txt\n\n\n############\n### Main ###\n############\n# hyperparameters\nlearning_rate = 1e-2\nseq_length = 100\nhidden_dim = 500\nbatch_size = 1\n\n# load data\ndata_name = 'shakespeare'\ninput_file = data_name +'.txt'\ndata, char_to_idx, idx_to_char, vocab_size = aux.load(input_file)\nprint('data has %d characters, %d unique.' % (len(data), vocab_size))\nprint(\"First 4 characters are: \", idx_to_char[0], idx_to_char[1], idx_to_char[2], idx_to_char[3])\n\n# Create data generator\ndata_feed = aux.tf_gen(data, seq_length, char_to_idx, vocab_size)\n\n# TensorFlow input variables\nx = tf.placeholder(\"float\", [None, batch_size, vocab_size], name=\"x\")\ny = tf.placeholder(\"float\", [None, batch_size, vocab_size], name=\"y\")\ninit_state = tf.placeholder(tf.float32, [2, batch_size, hidden_dim], name=\"init_state\")\n# model architecture\n# lstm layer\nlstm_cell = tf.nn.rnn_cell.LSTMCell(hidden_dim, state_is_tuple=True, name=\"celula\")\nrnn_tuple_state = tf.nn.rnn_cell.LSTMStateTuple(init_state[0], init_state[1])\n# dense layer parameters\ndense_weights = tf.get_variable(\"out_w\", shape=[hidden_dim, vocab_size])\ndense_bias = tf.get_variable(\"out_b\", shape=[vocab_size])\n# model\nh_states, current_state = tf.nn.dynamic_rnn(lstm_cell, x, initial_state=rnn_tuple_state,\n time_major=True, dtype=tf.float32)\nlogits = tf.matmul(h_states[:, 0, :], dense_weights) + dense_bias\nprobabilities = tf.nn.softmax(logits, name=\"probabilities\")\n\n# model evaluation\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=logits)\nloss = tf.reduce_mean(cross_entropy, name=\"loss\")\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n# optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\ntraining = optimizer.minimize(loss, name=\"training\")\n# Defining variables initializer\ninit_op = tf.global_variables_initializer()\n\n# Bookkeeping variables\nsave_path = 'tensor_model/'\nloss_hist = [-np.log(1.0 / vocab_size)] # loss at iteration 0\nsmooth_loss = loss_hist.copy()\nit = 0\nit_per_epoch = len(data) / seq_length\np = (it % it_per_epoch) * seq_length\nelapsed_time = 0\nstart = time.time()\n\n# Saver\nsaver = tf.train.Saver()\n\nrestore = True\n\n# Training\nwith tf.Session() as sess:\n if restore:\n saver.restore(sess, save_path + \"model\")\n else:\n sess.run(init_op)\n _current_state = np.zeros((2, batch_size, hidden_dim))\n for p in range(501):\n # show progress and bookkeeping\n if p % 100 == 0:\n print('\\niter %d, loss: %f' % (p, smooth_loss[-1])) # print progress\n print(sample(600, sess))\n saver.save(sess, save_path + 'model')\n aux.plot(loss_hist, smooth_loss, it, it_per_epoch, base_name=save_path + \"tensor\")\n\n # collect data for next step\n inputs, targets = (next(data_feed))\n _loss, _, _current_state = sess.run([loss, training, current_state],\n feed_dict={x: inputs,\n y: targets,\n init_state: _current_state})\n loss_hist.append(_loss)\n smooth_loss.append(smooth_loss[-1] * 0.999 + loss_hist[-1] * 0.001)\n\nend = time.time()\nprint(\" Training time: \", end - start, \"\\n\")\n\n# Restore\nprint(\"Restoring the trained variables\\n\")\n\nwith tf.Session() as sess:\n # If saver.restore(...) commented -> 'Error: Attempting to use uninitialized value out_w'\n # can be corrected with sess.run(init_op), but training is forgotten\n saver.restore(sess, save_path + \"model\")\n print(sample(600, sess))\n","sub_path":"tf-lstm-char_full.py","file_name":"tf-lstm-char_full.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"226533283","text":"import bpy\nimport math\nimport bmesh\n\n# okay, so to refresh, because I lost everything I was doing on the blender\n#thing :(\n# okay: the pick is 0.1\n#the teeth I had at 0.15\nz_ = [0,0,1] #unit vector in z direction\n\npick_height = 0.04\nteeth_width = 0.05\nteeth_gap = 0.01\nteeth_length = 3\nteeth_thickness = 0.03\nno_teeth = 18\ncomb_height = teeth_width*no_teeth + teeth_gap*(no_teeth-1)\npick_radius_modifier = 1.8 #to vary the width of the pick relative to the tooth_width\npick_radius = teeth_width/(2*pick_radius_modifier)\n\ngear_width = 0.4\ngear_gap = 0.2\ntop_gap = 0.1\n\ncylinder_height_modifier = gear_width + gear_gap + top_gap\ncylinder_height = comb_height + cylinder_height_modifier\n\npick_gap = 0.08\n\n\n\n\nnotes = [[\"1a&1b&1c&2f\", 1], [\"1c\",1], [\"2c\", 0.5], [\"1g&2c\", 0.5],[\"1a&2c&0c\", 0.5], [\"2c\",0.5], [\"1c\", 0.5], [\"1g&0e\", 2],[\"1a&1b&2c\", 1], [\"1c\",1], [\"0c\", 0.5], [\"0g&0e\", 2],[\"1a&1b&2c\", 1], [\"2c\",1], [\"2c\", 0.5], [\"1g&0e\", 2],[\"1a&1b&0c\", 1], [\"0c\",1], [\"1c\", 0.5], [\"1g&2e\", 2],[\"1a&2b&2c\", 1], [\"0c\",1], [\"0c\", 0.5], [\"0g&0e\", 2],[\"1a&1b&1c&2f\", 1], [\"1c\",1], [\"2c\", 0.5], [\"1g&1e\", 2],[\"1a&1b&0c\", 1], [\"2c\",1], [\"1c\", 0.5], [\"1g&0e\", 2],[\"1a&1b&2c\", 1], [\"1c\",1], [\"0c\", 0.5], [\"0g&0e\", 2],[\"1a&1b&2c\", 1], [\"2c\",1], [\"2c\", 0.5], [\"1g&0e\", 2],[\"1a&1b&0c\", 1], [\"0c\",1], [\"1c\", 0.5], [\"1g&2e\", 2],[\"1a&2b&2c\", 1], [\"0c\",1], [\"0c\", 0.5], [\"0g&0e\", 2]]\n\nprint(len(notes), \"No_notes\")\n\nkey = {} # json of the notes, to improve this: make this json be generated from musicXML, and make that be generated from PDFs\n\n\n#maths functions\n\ndef get_vector_angle(v):\n return math.atan(v[1]/v[0])\n\n#can't get the vector library to work in blender, so this is just a quick rotation about the z axis function \ndef Rz(angle, v1): \n #takes an array with 3 entries for v1. angle is in radians\n Rz = [[math.cos(angle), -math.sin(angle), 0],[math.sin(angle), math.cos(angle), 0], [0,0,1]]\n v2 = [(Rz[0][0]*v1[0] + Rz[0][1]*v1[1] + Rz[0][2]*v1[2]), (Rz[1][0]*v1[0] + Rz[1][1]*v1[1] + Rz[1][2]*v1[2]), (Rz[2][0]*v1[0] + Rz[2][1]*v1[1] + Rz[2][2]*v1[2])]\n return v2\n\n#get orthogonal vector on x,y\n\ndef add(v1, v2):\n assert(len(v1) == len(v2))\n new_v = []\n for i in range(len(v1)):\n temp = v1[i] + v2[i]\n new_v.append(temp)\n return new_v\n\ndef x_by_scalar(scalar, v):\n new_v = []\n for i in v:\n new_v.append(i*scalar)\n return new_v\n\n\ndef magnitude(v):\n length = 0\n \n for i in v:\n length += i**2\n return math.sqrt(length)\n\ndef normalise(v):\n length = magnitude(v)\n return x_by_scalar(1/length, v)\n\n#note: returns a unit vector with z component = 0\ndef get_orthogonal(vector):\n return normalise([-vector[1], vector[0], 0])\n\ndef dot_product(vector1, vector2):\n dot_product = 0\n if not len(vector1) == len(vector2):\n raise(\"Dot product requires that both vectors are the same size\")\n for i in range(len(vector1)):\n dot_product += vector1[i]*vector2[i]\n return dot_product\n\n#get vector component of vector1 along vector2\ndef proj(vector1, vector2):\n dot_product = dot_product(vector1, vector2)\n mag = magnitude(vector2)**2\n scalar_component = dot_product/mag\n proj = x_by_scalar(scalar_component, vector2)\n return proj\n\ndef angle_between(vector1, vector2):\n #get the angle between two vectors\n d_product = dot_product(vector1, vector2)\n v1_magnitude = magnitude(vector1)\n v2_magnitude = magnitude(vector2)\n theta = math.acos(d_product/(v1_magnitude * v2_magnitude))\n \n return theta\n#get angle between x-axis and vector\ndef angle(vector):\n return math.atan(vector[1]/vector[0])\n\n#reflect a vector about a given vector -- NOTE only reflects about the Z axis\ndef reflect(vector, pre_image):\n angle_between_vectors = angle_between(vector, pre_image)\n #angle between the vector and the x-axis\n angle_vector = angle(vector)\n \n\n #angle between the pre_image and the x-axis\n angle_pre_image = angle(pre_image)\n\n reflection_angle = angle_vector - angle_pre_image\n\n reflected_vector = Rz(2*reflection_angle, pre_image)\n return reflected_vector\n\ndef get_smallest_note(notes):\n smallest = notes[0][1]\n for i in notes:\n if i[1] < smallest:\n smallest = i[1]\n return smallest\n\n\ndef populate_key(key):\n global no_teeth\n global teeth_notes\n for c in range(no_teeth): \n x = 97 + (c+2)%7 #c + 2 mod 7 so that it cycles between c and a on the ascii table\n fl = math.floor((c+2)/7)\n newKey = str(fl) + chr(x)\n key[newKey] = c\n\n\npopulate_key(key)\n\n\n\n#get the number of beats in the notes array\ndef get_no_beats(notes):\n total_beats = 0\n for i in notes:\n total_beats+= i[1]\n\n return total_beats\n\nno_beats = get_no_beats(notes)\n\n#no_beats = 80\ncylinder_circumference_modifier = 0.5 #To add some space between the final note and the first note\n#cylinder_circumference = (pick_gap+(pick_radius))*no_beats + cylinder_circumference_modifier\nshortest_note = get_smallest_note(notes)\ncylinder_circumference = (pick_gap/shortest_note)*no_beats + len(notes)*(2*pick_radius) + cylinder_circumference_modifier#(remember that no_beats is (n1 + n2 + n3... + nn)\ncylinder_radius = cylinder_circumference/(2*math.pi)\n\npick_gap_angle = (pick_gap+(pick_radius))/(cylinder_radius)\ncylinder_vertices = 100\n\ndef generate_main_cylinder():\n \n bpy.ops.mesh.primitive_cylinder_add(radius=cylinder_radius,vertices = cylinder_vertices, depth=cylinder_height, enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))\n \n bpy.ops.object.move_to_collection(collection_index=0, is_new=True, new_collection_name='mainCylinder')\n bpy.context.active_object.name = 'main_cylinder'\n bpy.context.object.location[2] = cylinder_height/2\n \n \n\ndef make_pick(angle, pos, note):\n #make the pick\n bpy.ops.mesh.primitive_cylinder_add(radius=pick_radius, depth=pick_height, enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))\n bpy.context.object.name = 'pick'\n #rotate the pick pi/2 relative to y\n bpy.context.object.rotation_euler[1] = 1.5708\n #rotate the pick angle radians relative to z\n bpy.context.object.rotation_euler[2] = angle\n # move the pick to the location\n bpy.context.object.location[0] = pos[0]\n bpy.context.object.location[1] = pos[1]\n bpy.context.object.location[2] = pos[2] + pick_radius\n col = bpy.data.collections.get(\"mainCylinder\")\n col.objects.link(bpy.context.active_object)\n \n#cylinder is not a perfect circle, so if I position things at cylinder_radius\n#away from center I end up with floating objects. This function calculates the \n#largest gap\ndef calc_pick_height_modifier():\n h = cylinder_radius*math.cos(math.pi/cylinder_vertices)\n return cylinder_radius - h\ndef generate_picks(notes):\n #loop through notes\n global pick_gap_angle\n global pick_height\n cumulative_angle = 0\n maximum_gap = calc_pick_height_modifier()\n pick_height += maximum_gap\n pos_vector = [cylinder_radius - maximum_gap + pick_height/2, 0, 0]\n shortest_note = get_smallest_note(notes)\n for c,i in enumerate(notes):\n chord = i[0].split(\"&\")\n if c == 0:\n angle = 0\n else:\n angle = ((2*pick_radius) + (pick_gap*(i[1]/shortest_note)))/cylinder_radius\n cumulative_angle += angle\n assert(cumulative_angle < math.pi*2)\n pos_vector = Rz(angle, pos_vector)\n \n pick_rotation_angle = get_vector_angle(pos_vector)\n for x in chord:\n pos_vector[2] = key[x]*(teeth_width + teeth_gap) + cylinder_height_modifier - top_gap\n \n make_pick(pick_rotation_angle, pos_vector, chord)#pick_height_modifier)\n# col = bpy.data.collections.get(\"mainCylinder\")\n # bpy.ops.object.select_all(action='SELECT')\n # bpy.ops.object.join()\n \n\ndef join_objects(collection):\n col = bpy.data.collections.get(collection)\n bpy.ops.object.select_all(action='SELECT')\n sel_objs = bpy.context.selected_objects\n objs_in_col = [obj for obj in col.objects if obj in sel_objs]\n bpy.ops.object.join()\n\n\n#gears functions and classes\n\n#find the desired module of the gear, using 32 teeth total as the ideal:\n\ndef render(v1,v2):\n vertices = [v1,v2]\n edges = [[0,1]]\n \n name = 'test'\n mesh = bpy.data.meshes.new(name)\n faces = []\n obj = bpy.data.objects.new(name, mesh)\n\n col = bpy.data.collections.get(\"Collection\")\n col.objects.link(obj)\n bpy.context.view_layer.objects.active = obj\n mesh.from_pydata(vertices,edges, faces)\n\n\nclass Gear():\n def __init__(self,**kwargs):\n no_points = 10\n self.__dict__.update(**kwargs)\n self.root_radius = self.get_root_radius()\n self.pitch = self.get_pitch()\n self.z_component = [0,0,self.diameters['face_width']]\n \n self.tooth_pitch = self.pitch/2\n self.pitch_angle = self.pitch/self.get_pitch_radius()\n self.pitch_angle_root = self.pitch/self.root_radius\n self.tooth_pitch_angle = self.pitch_angle/2\n \n self.profile_angle = self.tooth_pitch_angle/2\n self.involute_range = self.calculate_involute_range(no_points)\n involute_angle = self.involute_range['angle']\n \n self.tooth_pitch_angle_root = self.pitch_angle_root/2\n \n involute_curve_profile = self.generate_involute_profile([self.get_tip_radius(),0,0], no_points, self.involute_range) \n self.tip_angle = involute_curve_profile['tip_range']\n self.pitch_angle_root = self.pitch/self.root_radius\n \n involute_curve_vertices = involute_curve_profile['vertices']\n \n tip_start_vector = involute_curve_profile['tip_start_vector']\n tip_vertices = self.generate_tip_vertices(self.tip_angle, no_points, tip_start_vector)\n self.vertices = {'involute_curve' : involute_curve_vertices, 'tip' : tip_vertices} \n #1) calculate root diameter, dedendum and addendum\n def get_pitch(self):\n pitch = (self.diameters['pitch']*math.pi)/self.diameters['no_teeth']\n print(pitch, \"LLL\")\n return pitch \n #return self.diameters['module']\n \n \n def get_circles(self):\n return self.diameters\n def get_root_radius(self):\n return self.diameters['root']/2\n def get_pitch_radius(self):\n return self.diameters['pitch']/2\n def get_tip_radius(self):\n return self.diameters['tip']/2\n def get_involute_curve_vertices(self):\n return self.involute_curve_vertices\n def get_tip_vertices(self):\n return self.tip_vertices \n def get_vertices(self, part, position):\n vertices = []\n \n for i in range(len(self.vertices[part])):\n temp_verts = [] \n for c in self.vertices[part][i]:\n vert = Rz(position, c)\n temp_verts.append(vert)\n vertices.append(temp_verts)\n \n return vertices\n \n def calculate_tip_angle(self, involute_sector_angle, no_points):\n tip_angle = (self.pitch_angle/2 - involute_sector_angle*2)\n #tip_angle = (self.pitch_angle/2 - (involute_sector_angle*2))\n return tip_angle\n \n def generate_tip_vertices(self, tip_angle, no_points, start_vector):\n no_points = round(no_points)\n inter_angle = tip_angle/(no_points)\n top_tip_vertex = add(start_vector, self.z_component)\n vertices = [[start_vector], [top_tip_vertex]]\n for i in range(no_points):\n start_vector = Rz(inter_angle, start_vector)\n \n vertices[0].append(start_vector)\n top_tip_vertex = add(start_vector, self.z_component)\n \n vertices[1].append(top_tip_vertex)\n \n return vertices\n #calculates the angle and minimum iterant used in deriving the points for the involute curve\n \n def calculate_involute_sector(self, no_points, angle, min_it):\n \n \n #rotate pos_vector to the start of min_it*angle\n arc_length = angle*self.root_radius\n start_vector = [self.root_radius,0,0]\n end_vector = Rz(angle*min_it, start_vector)\n end_vector_orth = get_orthogonal(end_vector)\n end_vector_orth = x_by_scalar(-min_it*arc_length, end_vector_orth)\n point = add(end_vector, end_vector_orth)\n involute_curve_sector = angle_between(start_vector, point)\n \n \n return involute_curve_sector\n \n \n def calculate_involute_range(self, no_points):\n #no_points refers to the number of points along the involute curve to be used in the spline\n #the involute curve is generated from the root circle!\n \n tip_radius = self.get_tip_radius()\n pitch_radius = self.get_pitch_radius()\n \n root_radius_vector = [0,self.root_radius, 0]\n root_radius_vector_orth = get_orthogonal(root_radius_vector)\n \n \n #calculate the scalar required to lengthen a unit vector tangent to the root circle to the tip circle\n tip_scale_factor = math.sqrt((tip_radius**2 - root_radius_vector[0]**2 - root_radius_vector[1]**2)/(root_radius_vector_orth[0]**2 + root_radius_vector_orth[1]**2))\n #calculate the scalar required to lengthen a unit vector tangent to the root circle to the pitch circle\n pitch_scale_factor = math.sqrt((pitch_radius**2 - root_radius_vector[0]**2 - root_radius_vector[1]**2)/(root_radius_vector_orth[0]**2 + root_radius_vector_orth[1]**2))\n \n #tip_scale_factor is made up of no_points * length of segment\n theta = tip_scale_factor/(no_points*self.root_radius)\n #using theta to calculate the minimum iterant for rendering the addendum of the involute curve:\n min_it = math.floor(pitch_scale_factor/(theta*self.root_radius))\n involute_sector = self.calculate_involute_sector(no_points, theta, min_it)\n return {'angle' : theta, 'min_it' : min_it, 'involute_sector_angle' : involute_sector}\n \n #account for error coming from the rendering of the circle being an approximation of a circle - not uniform radius\n def calc_maximum_gap(self, root_radius, cylinder_vertices):\n h = root_radius*math.cos(math.pi/cylinder_vertices)\n\n return root_radius - h\n \n #generate the vertices of the involute curve profile of the gear tooth\n \n def generate_involute_profile(self, mid_vector, no_points, involute_range):\n \n #z vector\n radius_modifier = self.root_radius - self.calc_maximum_gap(self.root_radius, cylinder_vertices) #account for error in positioning teeth\n \n #create a vector that is in line with mid_vector, with magnitude 1\n start_vector = normalise(mid_vector) \n #lengthen start_vector to length radius_modifier\n start_vector = x_by_scalar(radius_modifier, start_vector)\n #rotate start_vector so it points to where the involute curve starts\n start_vector = Rz(-(self.tooth_pitch_angle_root/2 + self.involute_range['involute_sector_angle']), start_vector)\n \n angle = involute_range['angle']\n #min_it = involute_range['min_it']\n \n min_it = 0 #setting this to zero so the cruve gets rendered from the root circle, since I am too pressed for time to model a fillet\n \n #rotate pos_vector to the start of min_it*angle\n pos_vector = Rz(angle*min_it, start_vector)\n arc_length = angle*self.root_radius\n vertices = [[],[],[],[],[],[]]\n \n for i in range(min_it, no_points + 1):\n pos_vector_orth = get_orthogonal(pos_vector)\n pos_vector_orth = x_by_scalar(-i*arc_length, pos_vector_orth)\n point = add(pos_vector, pos_vector_orth)\n z_vertex = add(self.z_component, point)\n vertices[0].append(point)\n vertices[1].append(z_vertex) \n vertices[4].append(point)\n \n reflected_point = reflect(mid_vector, point)\n vertices[5].append(reflected_point)\n z_vertex = add(self.z_component, reflected_point)\n \n vertices[3].append(reflected_point)\n vertices[2].append(z_vertex)\n \n if (i < no_points):\n pos_vector = Rz(angle, pos_vector)\n #vertices.append([0,0,0])\n #vertices.append([0,self.get_tip_radius(),0])\n tip_range = angle_between(point, reflected_point)\n #calculate angle between start and end of profile\n involute_curve_range = angle_between(start_vector, point)\n return {'vertices' : vertices, 'tip_start_vector' : point, 'tip_range' : tip_range, 'involute_curve_range' : involute_curve_range}\n \n \n def generate_involute_vertices(self, no_points, involute_range):\n #start with mid_vector of [0,tip_radius,0]\n #generate involute_profile \n pass \n\n#takes the relevant circle diameters and calculates vertices for all points\n#of the tooth (fillet, clearance, face, tip, + extruding 2d profile to gear_width \n\n#steps are: get involute curve vectors.Use these vectors to map out\n#parameters. interpolate the curve described by the points\n#use this formula to calculate the intersection of the curve with the tip_circle\n#the intercection + all below it form the vertices for the face\n\n#add some clearance\n#look into blender curves to make the fillet curve tangent to the root_circle\n#tip: follow line of tip_circle. blender issue.\n\n#mirror these vectors across the y_axis, then give every vertex a twin at cylinder_width in the z_direction.\n\n#Then connect the faces using something like rendering_info\n\n#add a \"gear with hole\" boolean check when in the gear class. That way you can actually\n#just call a gear class and plug in your diameters, then you can use a gear_renderer class to just make a gear\n\nclass Gear_Tooth():\n def __init__(self, modulus, pitch_diameter, **kwargs):\n self.__dict__.update(kwargs)\n \n \n \nclass Renderer():\n \n def render_gear_teeth(self, gear):\n pitch = gear.diameters['module']*math.pi\n angle = pitch/(gear.get_pitch_radius())\n for i in range(gear.diameters['no_teeth']):\n self.render_tooth(gear, angle*i, i)\n \n \n def render_tooth(self, gear, position, tooth_no):\n self.render_part(gear, 'involute_curve', position, tooth_no)\n self.render_part(gear, 'tip', position, tooth_no)\n \n def render_construction_circles(self,gear):\n bpy.ops.curve.primitive_bezier_circle_add(radius=gear.get_root_radius(), enter_editmode=True, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))\n bpy.ops.curve.subdivide(number_cuts=100)\n bpy.ops.curve.primitive_bezier_circle_add(radius=gear.get_pitch_radius(), enter_editmode=True, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))\n bpy.ops.curve.subdivide(number_cuts=100)\n bpy.ops.curve.primitive_bezier_circle_add(radius=gear.get_tip_radius(), enter_editmode=True, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))\n bpy.ops.curve.subdivide(number_cuts=100)\n \n def render_teeth(self,gear):\n pitch = gear.diameters['module']*math.pi\n angle = pitch/(gear.get_pitch_radius())\n \n cylinder_h = gear.get_tip_radius() - gear.get_root_radius()\n cylinder_rad = pitch/2\n pos_vector = [gear.get_root_radius() + cylinder_h/2,0,0]\n \n for i in range(gear.diameters['no_teeth']):\n bpy.ops.mesh.primitive_cylinder_add(radius=cylinder_rad, depth=cylinder_h, enter_editmode=False, align='WORLD', location=(pos_vector[0], pos_vector[1], 0), scale=(1, 1, 1))\n bpy.context.object.rotation_euler[1] = 1.5708\n bpy.context.object.rotation_euler[2] = angle*i\n pos_vector = Rz(angle, pos_vector)\n def render_involute_vertices(self, gear):\n vertices = gear.get_involute_curve_vertices()\n edges = []\n for i in range(len(vertices)-1):\n edges.append([i, i+1])\n \n name = 'tooth'\n mesh = bpy.data.meshes.new(name)\n faces = []\n obj = bpy.data.objects.new(name, mesh)\n\n col = bpy.data.collections.get(\"Collection\")\n col.objects.link(obj)\n bpy.context.view_layer.objects.active = obj\n mesh.from_pydata(vertices,edges, faces)\n \n def render_side(self, vert1, vert2, part, tooth_no):\n vertices = []\n faces = []\n edges = []\n if not (len(vert1) == len(vert2)):\n raise(\"to render a face using render_side(), both sets of vertices must be the same size\")\n \n for i in range(len(vert1)-1):\n \n vertices.append(vert1[i])\n \n vertices.append(vert1[i+1])\n vertices.append(vert2[i+1])\n vertices.append(vert2[i])\n \n i_mod = 4*i\n faces.append([i_mod, i_mod+1, i_mod+2, i_mod+3])\n \n \n name = 'tooth' + part + str(tooth_no)\n mesh = bpy.data.meshes.new(name)\n \n obj = bpy.data.objects.new(name, mesh)\n\n col = bpy.data.collections.get(\"Collection\")\n col.objects.link(obj)\n bpy.context.view_layer.objects.active = obj\n mesh.from_pydata(vertices,edges, faces)\n \n \n def render_part(self, gear, part, position, tooth_no):\n vertices = gear.get_vertices(part, position)\n \n for i in range(len(vertices)-1):\n self.render_side(vertices[i], vertices[i+1], part, tooth_no)\n \n #for c in range(len(vertices)):\n # edges = []\n \n\n# for i in range(len(vertices[c])-1):\n # edges.append([i, i+1])\n # \n # name = 'tooth' + part + str(tooth_no)\n # mesh = bpy.data.meshes.new(name)\n # faces = []\n # obj = bpy.data.objects.new(name, mesh)\n#\n # col = bpy.data.collections.get(\"Collection\")\n # col.objects.link(obj)\n # bpy.context.view_layer.objects.active = obj\n # mesh.from_pydata(vertices[c],edges, faces)\n \nclass Gear_System():\n def __init__(self, angle, cylinder_radius, face_width, gear_ratio_ar, no_teeth, **kwargs):\n #fcalculate modulus\n self.__dict__.update(kwargs)\n self.pressure_angle = angle\n self.gear_ratio = gear_ratio_ar[0]/gear_ratio_ar[1]\n self.gear_ratio_ar = gear_ratio_ar\n self.face_width = face_width\n # if (self.gear_ratio*no_teeth + no_teeth < 32):\n # raise Exception(\"number of teeth and gear ratio supplied will result in undercut\")\n \n \n \n gear1_pitch_diameter = self.calculate_pitch_diameter(cylinder_radius)\n \n self.module = self.calculate_module(gear1_pitch_diameter, no_teeth) \n \n gear2_pitch_diameter = self.gear_ratio*gear1_pitch_diameter\n \n \n gear1_tip_diameter = self.calculate_tip_diameter(gear1_pitch_diameter)\n gear2_tip_diameter = self.calculate_tip_diameter(gear2_pitch_diameter)\n \n gear1_root_diameter = 2*cylinder_radius\n gear2_root_diameter = self.calculate_root_diameter(gear2_pitch_diameter)\n \n gear1_no_teeth = no_teeth\n gear2_no_teeth = int(self.gear_ratio*no_teeth)\n \n gear1 = {'pitch' : gear1_pitch_diameter, 'tip' : gear1_tip_diameter, 'root' : gear1_root_diameter, 'module' : self.module, 'no_teeth' : no_teeth, 'face_width' : face_width}\n gear2 = {'pitch' : gear2_pitch_diameter, 'tip' : gear2_tip_diameter, 'root' : gear2_root_diameter, 'module' : self.module, 'no_teeth' : no_teeth, 'face_width' : face_width}\n \n \n #todo: don't put this all in diameters\n self.gear1 = Gear(diameters = gear1)\n self.gear2 = Gear(diameters = gear2)\n \n self.gear_list = [self.gear1, self.gear2] \n \n def getGears(self):\n return self.gear_list \n \n def gear_info(self, request):\n if request == 'all':\n return self._dict__\n else:\n return self.__dict__[request]\n \n def calculate_module(self, pitch_diameter, no_teeth):\n return pitch_diameter/no_teeth\n \n \n def calculate_pitch(self):\n return (self.pitch_diameter*math.pi)/self.no_teeth\n \n def calculate_pitch_diameter(self, radius):\n return 2*radius/math.cos(self.pressure_angle*(math.pi/180))\n #return self.module*no_teeth\n \n \n \n def calculate_tip_diameter(self, pitch_diameter):\n return pitch_diameter + 2*self.module\n def calculate_root_diameter(self, pitch_diameter):\n return pitch_diameter*math.cos(self.pressure_angle*(math.pi/180))\n\n\n\n \ndef generate_completed_cylinder(notes):\n generate_main_cylinder()\n generate_picks(notes)\n join_objects(\"mainCylinder\")\n\n\n\n#comb functions\n\ndef add_tooth(pos_vector, tooth_thickness,tooth_width, tooth_length, note):\n # make mesh\n \n #get related vectors\n orth_vec = x_by_scalar(tooth_thickness, get_orthogonal(pos_vector)) \n tooth_width_vector = x_by_scalar(tooth_width, z_)\n tooth_length_vector = x_by_scalar(tooth_length, normalise([pos_vector[0], pos_vector[1], 0]))\n \n \n #vertex 1 and 2\n \n vertices = [add(pos_vector, x_by_scalar(1/2,orth_vec)), add(pos_vector, x_by_scalar(1/2,x_by_scalar(-1, orth_vec)))]\n #vertex 3\n vertices.append(add(vertices[0], tooth_width_vector))\n #vertex 4\n vertices.append(add(vertices[1], tooth_width_vector))\n #vertex 5\n vertices.append(add(vertices[0], tooth_length_vector))\n #vertex 6\n vertices.append(add(vertices[1], tooth_length_vector))\n #vertex 7\n vertices.append(add(vertices[2], tooth_length_vector))\n #vertex 8\n vertices.append(add(vertices[3], tooth_length_vector))\n \n edges = [[0,1], [0,2], [1,3], [3,2], [0,4],[1,5],[3,7],[2,6], [4,5],[4,6],[5,7], [6,7]]\n \n #faces: front and back\n faces = [[0,1,3,2], [4,5,7,6]]\n #side`\n faces.append([0,4,6,2])\n #side2\n faces.append([1,5,7,3])\n #top\n faces.append([2,3,7,6])\n #botto\n faces.append([0,1,5,4])\n \n \n name = \"tooth_\" + str(note)\n mesh = bpy.data.meshes.new(name)\n \n obj = bpy.data.objects.new(name, mesh)\n\n col = bpy.data.collections.get(\"Collection\")\n col.objects.link(obj)\n bpy.context.view_layer.objects.active = obj\n mesh.from_pydata(vertices,edges, faces)\n\n\n\ndef generate_teeth(no_teeth, teeth_width, teeth_length, teeth_thickness, teeth_gap):\n #pos_vector, tooth_thickness,tooth_width, tooth_length, note):\n lowest_pick_z = cylinder_height_modifier - top_gap - (teeth_width - pick_radius*2)/2\n tooth_rot = (pick_radius + teeth_thickness)/cylinder_radius\n pos_vector = Rz(-tooth_rot, [cylinder_radius + pick_height/2,0,0])\n pos_vector[2] = lowest_pick_z\n for i in range(no_teeth):\n add_tooth(pos_vector, teeth_thickness, teeth_width, teeth_length, 1)\n pos_vector[2] += teeth_width + teeth_gap\n\n#x = Gear_System(20,cylinder_radius,gear_width, [1,2], 28)\nx = Gear_System(20,cylinder_radius,gear_width, [1,2], 50)\ny = Renderer()\n#y.render_construction_circles(x.gear2)\ny.render_gear_teeth(x.gear1)\n#y.render_gear_teeth(x.gear1)\n#y.render_involute_vertices(x.gear2)\n#y.render_part(x.gear2,'involute_curve',math.pi,1)\n#y.render_part(x.gear1, 'tip',0,1)\ngenerate_completed_cylinder(notes)\n#generate_teeth(no_teeth, teeth_width, teeth_length, teeth_thickness, teeth_gap)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":27610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"25159274","text":"\n#!/usr/bin/env python\n#\n# Copyright (C) 2019 Sean D'Epagnier\n#\n# This Program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public\n# License as published by the Free Software Foundation; either\n# version 3 of the License, or (at your option) any later version. \n\nfrom signalk.values import Value\n\nimport sys, multiprocessing, select\nimport tensorflow as tf\nsys.path.append('..')\nfrom autopilot import AutopilotPilot, AutopilotGain\nfrom signalk.values import *\nfrom signalk.pipeserver import NonBlockingPipe\n\nsamples = 50 # 5 seconds at 10hz\nnum_inputs = 12\n\nclass History(object):\n def __init__(self):\n self.data = []\n\n def put(self, data, samples): # store new data discarding old\n self.data = ([data]+self.data)[:samples]\n\ndef BuildModel():\n input = tf.keras.layers.Input(shape=(samples, num_inputs), name='input_layer')\n flatten = tf.keras.layers.Flatten()(input)\n hidden = tf.keras.layers.Dense(16, activation='relu')(flatten)\n output = tf.keras.layers.Dense(1, activation='tanh')(hidden)\n model = tf.keras.Model(inputs=input, outputs=output)\n model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])\n return model\n\nimport random\nimport numpy as np\ndef PreTrain(model):\n train_x=[]\n train_y=[]\n for i in range(10000):\n x = []\n for j in range(int(samples)):\n y = []\n for k in range(int(num_inputs)):\n p = (random.random()-.5)*10\n y.append(p)\n x.append(y)\n\n y = x[0][0]*.05 + x[0][1]*.1\n train_x.append(x)\n train_y.append(y)\n\n print(\"pretrain\")\n model.fit(train_x, train_y, epochs=4)\n# print('eval ')\n# model.evaluate(train_x, train_y, verbose=2)\n \ndef LoadModel():\n print('load mode')\n model = BuildModel()\n try:\n self.model.load_weights('~/.pypilot/learning_weights')\n except:\n return model\n \ndef LearningProcess(pipe, model_pipe):\n uid = 0\n def Convert(model, pipe):\n converter = tf.lite.TFLiteConverter.from_keras_model(model)\n tflite_model = converter.convert()\n global uid\n uid += 1\n pipe.send((tflite_model, uid))\n \n model = LoadModel()\n PreTrain(model)\n Convert(model, model_pipe)\n\n poller = select.poll()\n poller.register(pipe, select.POLLIN)\n\n history = History()\n\n import psutil\n ps = psutil.Process(os.getpid())\n print('learn process')\n batch_size = 600 # 60 seconds\n train_x, train_y = [], []\n while True:\n # find cpu usage of training process\n cpu = ps.cpu_percent()\n if cpu > 50:\n print('learning cpu very high', cpu)\n\n # train model from error\n time.sleep(.005)\n\n if not poller.poll(0.001):\n continue\n \n data = pipe.recv()\n if data['uid'] != uid:\n print('received training sample from old model', uid, data['uid'], time.time())\n continue\n \n d, e = data['input'], data['error']\n history.put(d, samples)\n if len(history.data) == samples:\n h = history.data\n train_x.append(h)\n train_y.append([e])\n \n if len(train_x) >= batch_size:\n p = model.predict(train_x)\n y = p + train_y\n y = list(map(lambda x : [min(max(x[0], -.8), .8)], y))\n model.fit(train_x, y, epochs=4)\n\n Convert(model, model_pipe)\n train_x, train_y = [], []\n\n \nclass LearningPilot(AutopilotPilot):\n def __init__(self, ap):\n super(LearningPilot, self).__init__('learning', ap)\n # create filters\n timestamp = self.ap.server.TimeStamp('ap')\n\n # create simple pid filter\n self.P = self.Register(AutopilotGain, 'P', .001, .0001, .01)\n self.D = self.Register(AutopilotGain, 'D', .03, .01, .1)\n\n self.lag = self.Register(RangeProperty, 'lag', 1, 0, 5)\n \n timestamp = self.ap.server.TimeStamp('ap')\n self.dt = self.Register(SensorValue, 'dt', timestamp)\n self.initialized = False\n self.start_time = time.time()\n self.model_uid = 0\n\n def reset(self):\n PreTrain(self.model)\n\n def initialize(self):\n # Build model\n self.history = History()\n\n self.learning_pipe, pipe = NonBlockingPipe('learning_pipe')\n model_pipe, self.model_pipe = NonBlockingPipe('learning_model_pipe')\n self.model_pipe_poller = select.poll()\n self.model_pipe_poller.register(pipe, select.POLLIN)\n\n self.fit_process = multiprocessing.Process(target=LearningProcess, args=(pipe,model_pipe))\n self.fit_process.start()\n print('start training')\n self.initialized = True\n \n def process(self, reset):\n ap = self.ap\n\n if not self.initialized:\n if time.time() - self.start_time < 2:\n return\n self.initialize()\n\n P = ap.heading_error.value\n D = ap.boatimu.SensorValues['headingrate_lowpass'].value\n accel = ap.boatimu.SensorValues['accel'].value\n gyro = ap.boatimu.SensorValues['gyro'].value\n wind = ap.sensors.wind\n\n # input data\n data = [P, D] + list(accel) + list(gyro)\n data += [ap.servo.voltage.value/24, ap.servo.current.value/20]\n data += [wind.direction.value/360, wind.speed.value/60]\n\n # training data\n lag_samples = int(self.lag.value/self.ap.boatimu.rate.value)\n self.history.put(data, samples + lag_samples)\n\n learning_history = self.history.data[lag_samples:]\n if len(learning_history) == samples:\n #error = 0\n #for d in self.history.data[:lag_samples]:\n # error += d[0]*self.P.value + d[1]*self.D.value # calculate error from current state\n #error /= lag_samples\n d = self.history.data[0]\n e = d[0]*self.P.value + d[1]*self.D.value # calculate error from current state\n\n # see what our command was to find the better command\n data = {'input': learning_history[0], 'error': e, 'uid': self.model_uid}\n self.learning_pipe.send(data)\n\n history = self.history.data[:samples]\n if len(history) == samples:\n if self.model_pipe_poller.poll():\n tflite_model, self.model_uid = self.model_pipe.recv()\n open('converted.tflite', 'wb').write(tflite_model)\n\n if self.model_uid:\n t0 = time.time()\n interpreter = tf.lite.Interpreter(model_path=\"converted.tflite\")\n t1 = time.time()\n interpreter.allocate_tensors()\n t2 = time.time()\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n t3 = time.time()\n input_shape = input_details[0]['shape']\n print ('input details', input_details)\n t4 = time.time()\n interpreter.set_tensor(input_details[0]['index'], np.array(history))\n interpreter.invoke()\n t5 = time.time()\n output_data = interpreter.get_tensor(output_details[0]['index'])\n t6 = time.time()\n print('interpreter timings', t1-t0, t2-t1, t3-t2, t4-t3, t5-t4, t6-t5)\n \n if ap.enabled.value and len(self.history.data) >= samples:\n ap.servo.command.set(command)\n\npilot = LearningPilot\n\nif __name__ == '__main__':\n learning_pipe, pipe = NonBlockingPipe('learning_pipe')\n fit_process = multiprocessing.Process(target=LearningProcess, args=(pipe,))\n fit_process.start()\n x = 0\n while True:\n P = math.sin(x)\n D = math.sin(x+3)\n x += .01\n\n inp = [0] * num_inputs \n inp[0] = P\n inp[1] = D\n \n \n error = math.sin(x-1)\n data = {'input': inp,\n 'error': error}\n learning_pipe.send(data)\n time.sleep(.1)\n","sub_path":"pypilot/pilots/learning.py","file_name":"learning.py","file_ext":"py","file_size_in_byte":7350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"466733594","text":"from . import transform\nfrom . import material\nfrom OpenGL.GL import *\nimport numpy\nimport math\nimport re\n\n##\n## Calculates the surface normal of 3 points\n##\ndef calcSurfaceNormal(x, y, z):\n\tu = [b - a for a, b in zip(x, y)] # U = Vb - Va\n\tv = [c - a for a, c in zip(x, z)] # V = Vc - Va\n\tnorm = [0.0] * 3\n\tnorm[0] = (u[1] * v[2]) - (u[2] * v[1]) # X = UyVz - UzVy\n\tnorm[1] = (u[2] * v[0]) - (u[0] * v[2]) # Y = UzVx - UxVz\n\tnorm[2] = (u[0] * v[1]) - (u[1] * v[0]) # Z = UxVy - UyVx\n\treturn norm\n\n##\n## Facilitates the reading of an OBJ file\n##\ndef getOBJData(meshFile):\n\tverts = []\n\tnormals = []\n\ttexcoords = []\n\tvertexElements = []\n\tnormalElements = []\n\ttextureElements = []\n\n\t## Regex programs\n\tvProg = re.compile(\"v\\s([-]?\\d.+)\\s([-]?\\d.+)\\s([-]?\\d.+)\")\n\tnProg = re.compile(\"vn\\s([-]?\\d.+)\\s([-]?\\d.+)\\s([-]?\\d.+)\")\n\ttcProg = re.compile(\"vt\\s([-]?\\d.+)\\s([-]?\\d.+)\\s([-]?\\d.+)\")\n\n\tfVProg = re.compile(\"\\s?(\\d+)\\s?\")\n\tfVNProg = re.compile(\"\\s?(\\d+)//(\\d+)\\s?\")\n\tfVTProg = re.compile(\"\\s?(\\d+)/(\\d+)/\\s?\")\n\tfVTNProg = re.compile(\"\\s?(\\d+)/(\\d+)/(\\d+)\\s?\")\n\n\t## Parse file, loading into data stores\n\twith open(meshFile) as f:\n\t\tfor l in f: # Loop line-by-line through file\n\t\t\t## Face definiton\n\t\t\tif l.startswith(\"f \"):\n\t\t\t\t## Vertex, texture, and normal\n\t\t\t\tif re.search(fVTNProg, l):\n\t\t\t\t\tmatch = re.findall(fVTNProg, l)\n\t\t\t\t\t## Add values to data store\n\t\t\t\t\tfor (ve, te, ne) in match:\n\t\t\t\t\t\tvertexElements += [ve]\n\t\t\t\t\t\ttextureElements += [te]\n\t\t\t\t\t\tnormalElements += [ne]\n\t\t\t\t## Vertex and normal\n\t\t\t\telif re.search(fVNProg, l):\n\t\t\t\t\tmatch = re.findall(fVNProg, l)\n\t\t\t\t\t## Add values to data store\n\t\t\t\t\tfor (ve, ne) in match:\n\t\t\t\t\t\tvertexElements += [ve]\n\t\t\t\t\t\tnormalElements += [ne]\n\t\t\t\t## Vertex and texture\n\t\t\t\telif re.search(fVTProg, l):\n\t\t\t\t\tmatch = re.findall(fVTProg, l)\n\t\t\t\t\t## Add values to data store\n\t\t\t\t\tfor (ve, te) in match:\n\t\t\t\t\t\tvertexElements += [ve]\n\t\t\t\t\t\ttextureElements += [te]\n\t\t\t\t## Only vertex\n\t\t\t\telif re.search(fVProg, l):\n\t\t\t\t\tmatch = re.findall(fVProg, l)\n\t\t\t\t\t## Add values to data store\n\t\t\t\t\tfor (ve) in match:\n\t\t\t\t\t\tvertexElements += [ve]\n\t\t\t## Vertex\n\t\t\tif re.search(vProg, l):\n\t\t\t\tmatch = re.findall(vProg, l)\n\t\t\t\tfor (x, y, z) in match:\n\t\t\t\t\tverts += [[float(x), float(y), float(z)]]\n\t\t\t## Normal vector\n\t\t\telif re.search(nProg, l):\n\t\t\t\tmatch = re.findall(nProg, l)\n\t\t\t\tfor (x, y, z) in match:\n\t\t\t\t\tnormals += [[float(x), float(y), float(z)]]\n\t\t\t## Texture coordinate vector\n\t\t\telif re.search(tcProg, l):\n\t\t\t\tmatch = re.findall(tcProg, l)\n\t\t\t\tfor (x, y, z) in match:\n\t\t\t\t\ttexcoords += [[float(x), float(y), float(z)]]\n\treturn (\n\t\tverts, normals, texcoords,\n\t\tvertexElements, normalElements, textureElements)\n\nclass Mesh:\n\t__vao = -1\n\t__vertVBO = -1\n\t__normVBO = -1\n\t__instanceOffsetVBO = -1\n\t__numElems = 0\n\t__material = None\n\t__transform = None\n\t__instances = 1\n\n\tdef __init__(self, meshFile, smooth):\n\t\tself.__material = material.Material()\n\t\tself.__transform = transform.Transform()\n\n\t\t(verts, normals, texcoords,\n\t\tvertexElements, normalElements, textureElements) = getOBJData(meshFile)\n\n\t\t## Set up mesh state\n\t\tself.__vao = glGenVertexArrays(1)\n\t\tself.__vertVBO = glGenBuffers(1)\n\t\tself.__normVBO = glGenBuffers(1)\n\t\tself.__instanceOffsetVBO = glGenBuffers(1)\n\t\tself.__numElems = len(vertexElements)\n\n\t\t## Loop through vertex elements\n\t\tfor i in range(0, len(vertexElements)):\n\t\t\tvertexElements[i] = int(vertexElements[i]) - 1\n\n\t\torderedVerts = []\n\t\torderedNorms = []\n\t\tfinalNorms = []\n\n\t\tvertNorms = dict()\n\n\t\t## Order vertices\n\t\tfor x in vertexElements: orderedVerts += verts[x]\n\t\t## Calculate surface normals\n\t\tfor i in range(0, len(vertexElements), 3):\n\t\t\te0, e1, e2 = vertexElements[i:i+3]\n\t\t\tv0, v1, v2 = verts[e0], verts[e1], verts[e2]\n\t\t\tsurfNorm = calcSurfaceNormal(v0, v1, v2)\n\t\t\tif smooth:\n\t\t\t\tif str(v0) not in vertNorms:\n\t\t\t\t\tvertNorms[str(v0)] = [[0.0, 0.0, 0.0], 0]\n\t\t\t\tif str(v1) not in vertNorms:\n\t\t\t\t\tvertNorms[str(v1)] = [[0.0, 0.0, 0.0], 0]\n\t\t\t\tif str(v2) not in vertNorms:\n\t\t\t\t\tvertNorms[str(v2)] = [[0.0, 0.0, 0.0], 0]\n\t\t\t\tv0e = vertNorms[str(v0)]\n\t\t\t\tv1e = vertNorms[str(v1)]\n\t\t\t\tv2e = vertNorms[str(v2)]\n\n\t\t\t\t## Add surface normal to vertex dictionary\n\t\t\t\tv0e[0][0] += surfNorm[0]\n\t\t\t\tv0e[0][1] += surfNorm[1]\n\t\t\t\tv0e[0][2] += surfNorm[2]\n\t\t\t\tv1e[0][0] += surfNorm[0]\n\t\t\t\tv1e[0][1] += surfNorm[1]\n\t\t\t\tv1e[0][2] += surfNorm[2]\n\t\t\t\tv2e[0][0] += surfNorm[0]\n\t\t\t\tv2e[0][2] += surfNorm[2]\n\t\t\t\tv2e[0][1] += surfNorm[1]\n\n\t\t\t\t## Increment vertex normal count\n\t\t\t\tv0e[1] += 1\n\t\t\t\tv1e[1] += 1\n\t\t\t\tv2e[1] += 1\n\t\t\telse:\n\t\t\t\torderedNorms += [surfNorm] * 3\n\t\tif smooth:\n\t\t\t## Loop through vertex/normal/amount triplets and\n\t\t\t## calculate smoothed vertex normals\n\t\t\tfor e in vertexElements:\n\t\t\t\tvert = verts[e]\n\t\t\t\t## If vertex has no normals, skip\n\t\t\t\tif vertNorms[str(vert)][1] == 0:\n\t\t\t\t\tfinalNorms += [[0.0, 0.0, 0.0]]\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\t## Normalize normal\n\t\t\t\t\tv = vertNorms[str(vert)]\n\t\t\t\t\tnX = v[0][0] / v[1]\n\t\t\t\t\tnY = v[0][1] / v[1]\n\t\t\t\t\tnZ = v[0][2] / v[1]\n\t\t\t\t\tfinalNorms += [[nX, nY, nZ]]\n\n\t\t## Bind VAO\n\t\tglBindVertexArray(self.__vao)\n\n\t\t## Enable attributes\n\t\tglEnableVertexAttribArray(0) # Attrib 0 -> Vert Pos\n\t\tglEnableVertexAttribArray(1) # Attrib 1 -> Vert Norm\n\t\tglEnableVertexAttribArray(2) # Attrib 2 -> Instance Offset\n\n\t\t## Set up vertex VBO\n\t\tglBindBuffer(GL_ARRAY_BUFFER, self.__vertVBO)\n\t\tglBufferData(\n\t\t\tGL_ARRAY_BUFFER,\n\t\t\tnumpy.array(\n\t\t\t\torderedVerts,\n\t\t\t\tdtype=\"float32\").flatten(),\n\t\t\tGL_STATIC_DRAW)\n\t\tglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)\n\t\tglBindBuffer(GL_ARRAY_BUFFER, 0)\n\n\t\t## Set up normal VBO\n\t\tglBindBuffer(GL_ARRAY_BUFFER, self.__normVBO)\n\t\tglBufferData(\n\t\t\tGL_ARRAY_BUFFER,\n\t\t\tnumpy.array(\n\t\t\t\tfinalNorms if smooth else orderedNorms,\n\t\t\t\tdtype=\"float32\").flatten(),\n\t\t\tGL_STATIC_DRAW)\n\t\tglVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None)\n\t\tglBindBuffer(GL_ARRAY_BUFFER, 0)\n\n\t\t## Set up default instance offset VBO\n\t\tglBindBuffer(GL_ARRAY_BUFFER, self.__instanceOffsetVBO)\n\t\tglBufferData(\n\t\t\tGL_ARRAY_BUFFER,\n\t\t\tnumpy.array(\n\t\t\t\t[0.0, 0.0, 0.0],\n\t\t\t\tdtype=\"float32\").flatten(),\n\t\t\tGL_DYNAMIC_DRAW)\n\t\tglVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, None)\n\t\tglVertexAttribDivisor(2, 1)\n\t\tglBindBuffer(GL_ARRAY_BUFFER, 0)\n\n\t\t## Unbind VAO\n\t\tglBindVertexArray(0)\n\n\t##\n\t## Re-buffer the instance positions for the\n\t## mesh to be drawn with.\n\t##\n\tdef setInstanceOffsets(self, positions):\n\t\tself.__instances = len(positions)\n\t\tglBindVertexArray(self.__vao)\n\n\t\tglBindBuffer(GL_ARRAY_BUFFER, self.__instanceOffsetVBO)\n\t\tglBufferData(\n\t\t\tGL_ARRAY_BUFFER,\n\t\t\tnumpy.array(\n\t\t\t\tpositions, dtype=\"float32\").flatten(),\n\t\t\tGL_STREAM_DRAW)\n\t\tglVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, None)\n\t\tglVertexAttribDivisor(2, 1)\n\t\tglBindBuffer(GL_ARRAY_BUFFER, 0)\n\n\t\tglBindVertexArray(0)\n\n\t##\n\t## Set the material of the mesh\n\t##\n\tdef setMaterial(self, mat): self.__material = mat\n\n\t##\n\t## Get the material of the mesh\n\t##\n\tdef getMaterial(self): return self.__material\n\n\t##\n\t## Set the transform of the mesh\n\t##\n\tdef setTransform(self, trans): self.__transform = trans\n\n\t##\n\t## Get the transform of the mesh\n\t##\n\tdef getTransform(self): return self.__transform\n\n\t##\n\t## Set the number of instances of the mesh to draw\n\t##\n\tdef setInstances(self, instances): self.__instances = instances\n\n\t##\n\t## Return the number of instances of the mesh to draw\n\t##\n\tdef getInstances(self): return self.__instances\n\n\t##\n\t## Draw the mesh\n\t##\n\tdef draw(self, delta):\n\t\tglBindVertexArray(self.__vao)\n\t\t## Draw n triangles\n\t\tglDrawArraysInstanced(\n\t\t\tGL_TRIANGLES, # Draw array of triangl verts\n\t\t\t0, # Start at 0\n\t\t\tself.__numElems, # N triangles in array\n\t\t\tself.__instances) # Number of instances to draw\n\t\tglBindVertexArray(0)\n\n\t##\n\t## Dispose of the mesh\n\t##\n\tdef dispose(self):\n\t\ttry:\n\t\t\tglDeleteVertexArrays(1, self.__vao)\n\t\t\tglDeleteBuffers(1, self.__vertVBO)\n\t\t\tglDeleteBuffers(1, self.__normVBO)\n\t\t\tglDeleteBuffers(1, self.__instanceOffsetVBO)\n\t\texcept: pass\n","sub_path":"main/render/mesh.py","file_name":"mesh.py","file_ext":"py","file_size_in_byte":7870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"92607953","text":"import random\nfrom defs import Person, Spell, Item\n\nprompt = \">>> \"\n\nclass_choosen = False\n\nwhile not class_choosen:\n print(\"Choose your class: Mage or Warrior\")\n rpg_class=input(prompt)\n\n if rpg_class == \"warrior\":\n #set player to warrior\n player_class = \"warrior\"\n class_choosen = True\n\n elif rpg_class == \"mage\":\n #set player to mage\n\n player_class = \"mage\"\n class_choosen = True\n \n else:\n print(\"This class does not exist, try again.\")\n\nprint(\"Welcome to Dungeon\")\n\n\n\n# Create Damage \"Spells\"\nfire = Spell(\"Fire\", 25, 600, \"ability\")\nember = Spell(\"ember\", 25, 600, \"ability\")\nflamethrower = Spell(\"flamethrower\", 40, 1200, \"ability\")\neruption = Spell(\"eruption\", 60, 2000, \"ability\")\nslash = Spell(\"Sword Slash\", 25, 600, \"ability\")\njstrike = Spell(\"Jaizhenju Strike\", 35, 1000, \"ability\")\nblade = Spell(\"Seeking Blade\", 60, 2000, \"ability\")\n\n# Create white Magic\ncure = Spell(\"Small Heal\", 25, 620, \"white\")\ncure2 = Spell(\"Heal\", 32, 1500, \"white\")\n\n\n# Create some Items\npotion = Item(\"Potion\", \"potion\", \"Heals 50 HP\", 50)\nhipotion = Item(\"Hi-Potion\", \"potion\", \"Heals 100 HP\", 100)\nsuperpotion = Item(\"Super Potion\", \"potion\", \"Heals 1000 HP\", 1000)\nelixer = Item(\"Hyper-Elixer\", \"elixer\", \"Fully restores HP/MP of one party member\", 9999)\nhielixer = Item(\"Team-Elixer\", \"elixer\", \"Fully restores party's HP/MP\", 9999)\n\n\nenemy_spells = [fire, flamethrower, cure2]\nplayer_items = [{\"item\": potion, \"quantity\": 15}, {\"item\": hipotion, \"quantity\": 5},\n {\"item\": superpotion, \"quantity\": 5}, {\"item\": elixer, \"quantity\": 5},\n {\"item\": hielixer, \"quantity\": 2},]\n\n\n# Instantiate People\nif player_class == \"warrior\":\n player_spells = [slash, jstrike, blade, eruption, cure, cure2]\n player1 = Person(\"Vamirio:\", 3260, 132, 300, 34, player_spells, player_items)\nelif player_class == \"mage\":\n player_spells = [fire, ember, flamethrower, eruption, cure, cure2]\n player1 = Person(\"Vamirio:\", 3260, 132, 300, 34, player_spells, player_items)\nelse:\n print(\"\"\"Error in class selection. Loading Backupclass.\n Godclass loaded.\"\"\")\n player_spells = [fire, ember, flamethrower, eruption, slash, jstrike, blade, cure, cure2]\n player1 = Person(\"Vamirio:\", 3260, 132, 300, 34, player_spells, player_items) \n\n\nenemy1 = Person(\"Goblin\", 1250, 130, 560, 325, enemy_spells, [])\nenemy2 = Person(\"Hobgoblin\", 5000, 701, 525, 25, enemy_spells, [])\n\n\nplayers = [player1]\nenemies = [enemy1, enemy2]\n\nplayer_nr = len(players)\nenemy_nr = len(enemies)\n\nrunning = True\ni = 0\n\nprint(\"AN ENEMY ATTACKS!\")\n\nwhile running:\n print(\"======================\")\n\n print(\"\\n\\n\")\n print(\"NAME HP MP\")\n for player in players:\n player.get_stats()\n\n print(\"\\n\")\n\n for enemy in enemies:\n enemy.get_enemy_stats()\n\n for player in players:\n\n player.choose_action()\n choice = input(\" Choose action: \")\n index = int(choice) - 1\n\n if index == 0:\n dmg = player.generate_damage()\n enemy = player.choose_target(enemies)\n\n enemies[enemy].take_damage(dmg)\n print(\"You attacked \" + enemies[enemy].name.replace(\" \", \"\") + \" for\", dmg, \"points of damage.\")\n\n if enemies[enemy].get_hp() == 0:\n print(enemies[enemy].name.replace(\" \", \"\") + \" has died.\")\n del enemies[enemy]\n\n elif index == 1:\n player.choose_magic()\n magic_choice = int(input(\" Choose magic: \")) - 1\n\n if magic_choice == -1:\n continue\n\n spell = player.magic[magic_choice]\n magic_dmg = spell.generate_damage()\n\n current_mp = player.get_mp()\n\n if spell.cost > current_mp:\n print(\"\\nNot enough MP\\n\")\n continue\n\n player.reduce_mp(spell.cost)\n\n if spell.type == \"white\":\n player.heal(magic_dmg)\n print(\"\\n\" + spell.name + \" heals for\", str(magic_dmg), \"HP.\")\n elif spell.type == \"ability\":\n\n enemy = player.choose_target(enemies)\n\n enemies[enemy].take_damage(magic_dmg)\n\n print(\"\\n\" + spell.name + \" deals\", str(magic_dmg), \"points of damage to \" + enemies[enemy].name.replace(\" \", \"\"))\n\n if enemies[enemy].get_hp() == 0:\n print(enemies[enemy].name.replace(\" \", \"\") + \" has died.\")\n del enemies[enemy]\n\n elif index == 2:\n player.choose_item()\n item_choice = int(input(\" Choose item: \")) - 1\n\n if item_choice == -1:\n continue\n\n item = player.items[item_choice][\"item\"]\n\n if player.items[item_choice][\"quantity\"] == 0:\n print(\"\\n\" + \"None left...\")\n continue\n\n player.items[item_choice][\"quantity\"] -= 1\n\n if item.type == \"potion\":\n player.heal(item.prop)\n print(\"\\n\" + item.name + \" heals for\", str(item.prop), \"HP\")\n elif item.type == \"elixer\":\n\n if item.name == \"MegaElixer\":\n for i in players:\n i.hp = i.maxhp\n i.mp = i.maxmp\n else:\n player.hp = player.maxhp\n player.mp = player.maxmp\n print(\"\\n\" + item.name + \" fully restores HP/MP\")\n elif item.type == \"attack\":\n enemy = player.choose_target(enemies)\n enemies[enemy].take_damage(item.prop)\n\n print(\"\\n\" + item.name + \" deals\", str(item.prop), \"points of damage to \" + enemies[enemy].name)\n\n if enemies[enemy].get_hp() == 0:\n print(enemies[enemy].name.replace(\" \", \"\") + \" has died.\")\n del enemies[enemy]\n\n # Check if battle is over\n defeated_enemies = 0\n defeated_players = 0\n\n for enemy in enemies:\n if enemy.get_hp() == 0:\n defeated_enemies += 1\n\n for player in players:\n if player.get_hp() == 0:\n defeated_players += 1\n\n # Check if Player won\n if defeated_enemies == enemy_nr:\n print(\"You win!\")\n running = False\n\n # Check if Enemy won\n elif defeated_players == player_nr:\n print(\"Your enemies have defeated you!\")\n running = False\n\n print(\"\\n\")\n # Enemy attack phase\n for enemy in enemies:\n enemy_choice = random.randrange(0, 1)\n\n if enemy_choice == 0:\n # Chose attack\n target = random.randrange(0, player_nr)\n enemy_dmg = enemy.generate_damage()\n\n players[target].take_damage(enemy_dmg)\n print(enemy.name.replace(\" \", \"\") + \" attacks \" + players[target].name.replace(\" \", \"\") + \" for\", enemy_dmg)\n\n elif enemy_choice == 1:\n spell, magic_dmg = enemy.choose_enemy_spell()\n enemy.reduce_mp(spell.cost)\n\n if spell.type == \"white\":\n enemy.heal(magic_dmg)\n print(spell.name + \" heals \" + enemy.name + \" for\", str(magic_dmg), \"HP.\" )\n elif spell.type == \"ability\":\n\n target = random.randrange(0, 3)\n\n players[target].take_damage(magic_dmg)\n\n print(\"\\n\" + enemy.name.replace(\" \", \"\") + \"'s \" + spell.name + \" deals\", str(magic_dmg), \"points of damage to \" + players[target].name.replace(\" \", \"\"))\n\n if players[target].get_hp() == 0:\n print(players[target].name.replace(\" \", \"\") + \" has died.\")\n del players[player]\n #print(\"Enemy chose\", spell, \"damage is\", magic_dmg)\n","sub_path":"Game/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":7753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"552256902","text":"from server_stats import get_server_status, get_players\nfrom influxdb import InfluxDBClient\nimport json\nimport datetime\nimport time\nimport socket\n\nclass ServerStatistics():\n\n influx_client = None\n\n def __init__(self, SERVER_ADDRESS, SERVER_DOMAIN, INFLUXDB_HOST, INFLUXDB_PORT, INFLUXDB_DATABASE):\n self.SERVER_ADDRESS = SERVER_ADDRESS\n self.SERVER_DOMAIN = SERVER_DOMAIN\n\n self.INFLUXDB_HOST = INFLUXDB_HOST\n self.INFLUXDB_PORT = INFLUXDB_PORT\n self.INFLUXDB_DATABASE = INFLUXDB_DATABASE\n self.INFLUXDB_HOSTNAME = socket.gethostname()\n\n def start_influx(self):\n self.influx_client = InfluxDBClient(host=self.INFLUXDB_HOST, port=self.INFLUXDB_PORT)\n database_list = self.influx_client.get_list_database()\n\n self._influxdb_exists(database_list, self.INFLUXDB_DATABASE)\n\n if self._influxdb_exists(database_list, self.INFLUXDB_DATABASE) is False:\n self.influx_client.create_database(self.INFLUXDB_DATABASE)\n\n self.influx_client.switch_database(self.INFLUXDB_DATABASE)\n\n\n def run(self):\n self.start_influx()\n\n while True:\n server_status = int(get_server_status(self.SERVER_ADDRESS))\n server_players = int(get_players(self.SERVER_ADDRESS))\n timestamp = datetime.datetime.now().isoformat()\n\n if server_status is not None and server_players is not None:\n self._insert_data(server_status, server_players, timestamp)\n\n print(f\"Server status: {server_status} - Player count: {server_players}\")\n time.sleep(5)\n\n def _insert_data(self, server_status, server_players, timestamp):\n data = [\n {\n \"measurement\": \"valheim-server-statistics\",\n \"tags\": {\n \"host\": self.INFLUXDB_HOSTNAME,\n },\n \"time\": datetime.datetime.now().isoformat(),\n \"fields\": {\n \"server_status\": server_status,\n \"player_count\": server_players\n }\n }\n ]\n\n self.influx_client.write_points(data)\n\n def _influxdb_exists(self, database, search):\n for db in database:\n if db['name'] == search:\n return True\n \n return False\n","sub_path":"app/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"579881237","text":"fname = \"mbox-short.txt\"\nfhand = open(fname)\ncounts = dict()\nfor line in fhand: \n words = line.split()\n if len(words) < 3: continue\n if words[0] != \"From\": continue\n find = words[1].find(\"@\")\n address = words[1][find+1:]\n if address not in counts:\n counts[domain] = 1\n else:\n counts[address] += 1\nprint(counts) ","sub_path":"Exercise_9_4.py","file_name":"Exercise_9_4.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"343675045","text":"import re\nimport shlex\nimport socket\nfrom os import (\n getcwd,\n mkdir,\n path,\n)\nfrom random import randrange\nfrom shutil import copy\nfrom subprocess import call as exe\nfrom threading import (\n Thread,\n Timer,\n)\nfrom time import sleep\n\nfrom pwn import process\n\n\nclass Validator:\n def __init__(self, submission, filename, user, subs, tmp):\n self.user = user\n self.tag = subs\n self.tmp = tmp\n self.submission = submission\n self.filename = filename\n\n def recv(self):\n len = int(self.conn.recv(8))\n return self.conn.recv(len)\n\n def replace(self, old, new, filename):\n buf = open(filename).read().replace(old, new)\n open(filename, 'w').write(buf)\n\n def check(self):\n self.vport = randrange(10000, 65530)\n sock = socket.socket(\n socket.AF_INET,\n socket.SOCK_STREAM,\n )\n sock.setsockopt(\n socket.SOL_SOCKET,\n socket.SO_REUSEADDR,\n 1,\n )\n sock.bind((\"\", self.vport))\n sock.listen(10)\n self.conn, _ = sock.accept()\n status = self.recv().decode()\n return status\n\n def container(self):\n copy(\n \"tasks.yaml\",\n path.join(self.tmp.name, \"templates\", \"tasks.yaml\")\n )\n copy(\n path.join(\"models\", \"templates\", \"Dockerfile\"),\n path.join(self.tmp.name, path.join(\"templates\", \"Dockerfile\"))\n )\n copy(\n path.join(\"models\", \"templates\", \"runner.py\"),\n path.join(self.tmp.name, \"templates\", \"runner.py\")\n )\n copy(\n path.join(\"models\", \"templates\", \"requirements.txt\"),\n path.join(self.tmp.name, \"templates\", \"requirements.txt\")\n )\n self.replace(\n \"SEDMYZIP\",\n path.join(getcwd(), self.filename),\n path.join(self.tmp.name, \"templates\", \"Dockerfile\")\n )\n self.replace(\n \"SEDMYSUBMISSION\",\n repr(self.submission),\n path.join(self.tmp.name, \"templates\", \"Dockerfile\")\n )\n try:\n self.replace(\n \"SEDMYPORT\",\n str(self.vport),\n path.join(self.tmp.name, \"templates\", \"Dockerfile\")\n )\n except AttributeError:\n sleep(0.5)\n self.replace(\n \"SEDMYPORT\",\n str(self.vport),\n path.join(self.tmp.name, \"templates\", \"Dockerfile\")\n )\n exe([\"docker\", \"build\", \"--tag\", \"{}.{}\"\n .format(\n re.sub(r'[^0-9a-zA-Z]+', '', self.user).lower(),\n self.tag\n ), path.join(self.tmp.name, \"templates\")])\n exe([\"docker\", \"run\", \"-t\", \"-i\", \"--rm\", \"--net=host\",\"{}.{}\"\n .format(\n re.sub(r'[^0-9a-zA-Z]+', '', self.user).lower(),\n self.tag,\n )])\n\n def validate(self):\n cnt = Thread(target=self.container)\n cnt.start()\n report = self.check()\n exe([\"docker\", \"image\", \"rm\", \"-f\", \"{}.{}\"\n .format(\n re.sub(r'[^0-9a-zA-Z]+', '', self.user).lower(),\n self.tag\n )])\n return report\n","sub_path":"core/validator/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"624107152","text":"# Copyright (c) 2017, PyTorch contributors\n# Modifications copyright (C) Microsoft Corporation\n# Licensed under the BSD license\n# From https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html\n\nimport argparse\nimport copy\nimport os\nimport time\n\nimport mlflow\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torchvision import datasets\nfrom torchvision import models\nfrom torchvision import transforms\n\n\ndef load_data(data_dir):\n \"\"\"Load the train/val data.\"\"\"\n\n # Data augmentation and normalization for training\n # Just normalization for validation\n data_transforms = {\n \"train\": transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]),\n \"val\": transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]),\n }\n\n image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),\n data_transforms[x])\n for x in [\"train\", \"val\"]}\n dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x],\n batch_size=4,\n shuffle=True, num_workers=4)\n for x in [\"train\", \"val\"]}\n dataset_sizes = {x: len(image_datasets[x]) for x in [\"train\", \"val\"]}\n class_names = image_datasets[\"train\"].classes\n\n return dataloaders, dataset_sizes, class_names\n\n\ndef train_model(model, criterion, optimizer, scheduler, num_epochs, data_dir):\n \"\"\"Train the model.\"\"\"\n\n # load training/validation data\n dataloaders, dataset_sizes, class_names = load_data(data_dir)\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(f\"Using device {device}\")\n\n since = time.time()\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n\n for epoch in range(num_epochs):\n print(\"Epoch {}/{}\".format(epoch, num_epochs - 1))\n print(\"-\" * 10)\n\n # Each epoch has a training and validation phase\n for phase in [\"train\", \"val\"]:\n if phase == \"train\":\n model.train() # Set model to training mode\n else:\n model.eval() # Set model to evaluate mode\n\n running_loss = 0.0\n running_corrects = 0\n\n # Iterate over data.\n for inputs, labels in dataloaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n # track history if only in train\n with torch.set_grad_enabled(phase == \"train\"):\n outputs = model(inputs)\n _, preds = torch.max(outputs, 1)\n loss = criterion(outputs, labels)\n\n # backward + optimize only if in training phase\n if phase == \"train\":\n loss.backward()\n optimizer.step()\n scheduler.step()\n\n # statistics\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects.double() / dataset_sizes[phase]\n\n print(\"{} Loss: {:.4f} Acc: {:.4f}\".format(\n phase, epoch_loss, epoch_acc))\n\n # deep copy the model\n if phase == \"val\" and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n\n # log the best val accuracy to AML run\n mlflow.log_metric(\"best_val_acc\", float(best_acc))\n\n print()\n\n time_elapsed = time.time() - since\n print(\"Training complete in {:.0f}m {:.0f}s\".format(\n time_elapsed // 60, time_elapsed % 60))\n print(\"Best val Acc: {:4f}\".format(best_acc))\n\n # load best model weights\n model.load_state_dict(best_model_wts)\n return model\n\n\ndef get_device():\n return torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef fine_tune_model(num_epochs, data_dir, learning_rate, momentum):\n \"\"\"Load a pretrained model and reset the final fully connected layer.\"\"\"\n\n # log the hyperparameter metrics to the AML run\n mlflow.log_metric(\"lr\", float(learning_rate))\n mlflow.log_metric(\"momentum\", float(momentum))\n\n model_ft = models.resnet152(pretrained=True)\n num_ftrs = model_ft.fc.in_features\n model_ft.fc = nn.Linear(num_ftrs, 2) # only 2 classes to predict\n\n device = get_device()\n model_ft = model_ft.to(device)\n\n criterion = nn.CrossEntropyLoss()\n\n # Observe that all parameters are being optimized\n optimizer_ft = optim.SGD(model_ft.parameters(),\n lr=learning_rate, momentum=momentum)\n\n # Decay LR by a factor of 0.1 every 7 epochs\n exp_lr_scheduler = lr_scheduler.StepLR(\n optimizer_ft, step_size=7, gamma=0.1)\n\n model = train_model(model_ft, criterion, optimizer_ft,\n exp_lr_scheduler, num_epochs, data_dir)\n\n return model\n\n\ndef main():\n from datetime import datetime\n print(f\"Starting training @{datetime.now()}\")\n print(f\"Torch version: {torch.__version__}\")\n\n # get command-line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--num-epochs\", type=int, default=1,\n help=\"number of epochs to train\")\n parser.add_argument(\"--data-dir\", type=str, default=\"data/\",\n help=\"input directory\")\n parser.add_argument(\"--output-dir\", type=str, default=\"outputs/\",\n help=\"output directory\")\n parser.add_argument(\"--learning-rate\", type=float,\n default=0.01, help=\"learning rate\")\n parser.add_argument(\"--momentum\", type=float, default=0.9, help=\"momentum\")\n args, _ = parser.parse_known_args()\n\n print(\"Data directory is: \" + args.data_dir)\n with mlflow.start_run() as _:\n model = fine_tune_model(args.num_epochs, args.data_dir,\n args.learning_rate, args.momentum)\n os.makedirs(args.output_dir, exist_ok=True)\n model_path = os.path.join(args.output_dir, \"model.pt\")\n # dummy_input = torch.randn(1, 3, 224, 224, device=get_device())\n # torch.onnx.export(model, dummy_input, model_path)\n torch.save(model, model_path)\n # mlflow.pytorch.log_model(model, \"model\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/birds/train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":6955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"13024469","text":"import numpy as np \nimport matplotlib.pyplot as plt \nimport os\nimport time\nimport tensorflow as tf\n\narray_sizes = [100,1000,4000,8000]\n\n#numpy implementation \nnumpy_per = []\ntf_per = []\n\nfor array in array_sizes:\n\ttest_matrix = np.random.random((array,array))\n\n\tstart = time.time()\n\ttest_result = np.log(test_matrix)\n\tend = time.time()\n\n\tnumpy_per.append(end - start)\n\n\ttf_input = tf.constant(test_matrix, dtype=tf.float64)\n\n\ttf_start = time.time()\n\ttf_result = tf.compat.v1.log(tf_input)\n\ttf_end = time.time()\n\n\ttf_per.append(tf_end- tf_start)\n\nfor i in range(len(array_sizes)):\n\tprint('Size:',array_sizes[i],' numpy performance:', \"%.5f\" % numpy_per[i],' tensorflow performance:',\"%.5f\" % tf_per[i])\n\t#print('tensorflow performance :', tf_per)\nplt.figure(figsize = (5,5))\nplt.plot(array_sizes,numpy_per,color = 'green', label = 'numpy')\nplt.plot(array_sizes, tf_per, color = 'blue', label = 'tensorflow')\nplt.title('Tensorflow vs Numpy : Log')\nplt.savefig('Log.png')","sub_path":"Performance_Testing/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"90510302","text":"import numpy as np\nimport pandas as pd\nimport torch\nfrom torch.autograd import Variable\nfrom math import sqrt, sin, cos, pi, asin\n\n#import deepgravity\n\n\ndef earth_distance(lat_lng1, lat_lng2):\n \"\"\"\n Compute the distance (in km) along earth between two lat/lon pairs\n :param lat_lng1: tuple\n the first lat/lon pair\n :param lat_lng2: tuple\n the second lat/lon pair\n\n :return: float\n the distance along earth in km\n \"\"\"\n lat1, lng1 = [l*pi/180 for l in lat_lng1]\n lat2, lng2 = [l*pi/180 for l in lat_lng2]\n dlat, dlng = lat1-lat2, lng1-lng2\n ds = 2 * asin(sqrt(sin(dlat/2.0) ** 2 + cos(lat1) * cos(lat2) * sin(dlng/2.0) ** 2))\n return 6371.01 * ds # spherical earth...\n\n\ndef common_part_of_commuters(values1, values2, numerator_only=False):\n \"\"\"\n Compute the common part of commuters for two pairs of fluxes.\n\n :param values1: the values for the first array\n :type values1: numpy array\n\n :param values2: the values for the second array\n :type values1: numpy array\n\n :return: float\n the common part of commuters\n \"\"\"\n if numerator_only:\n tot = 1.0\n else:\n tot = (np.sum(values2) + np.sum(values2))\n if tot > 0:\n return 2.0 * np.sum(np.minimum(values1, values2)) / tot\n else:\n return 0.0\n\n# Generate synthetic flows to test algorithms\n\ndef Eucl_Dist(A, B):\n \"\"\"\n Euclidean distance between points A=(x1,y1) and B=(x2,y2).\n \"\"\"\n return np.hypot( A[0]-B[0], A[1]-B[1])\n\n\ndef generate_synthetic_flows_scGM(n_locations, weights, coordinates,\\\n tot_outflows, deterrence_function, distfunc=Eucl_Dist):\n \"\"\"\n Generate synthetic data accoding to the assumptions:\n 1. Assume $n$ locations are randomly and uniformy distributed\n 2. generate a random array of $w_i = T_i$\n 3. generate the distance matrix $r_{ij}$\n 4. generate the matrix $p_{ij}$\n 5. generate a sample of $T_{ij}$ according to the multinomial distribution\n\n Returns:\n r : matrix of distances between all pairs of locations\n p : matrix of probabilities of one trip between all pairs of locations\n x : matrix of flows (one realization of the process)\n\n\n Example:\n\n n = 30\n n_locations = n\n R_true = 50.\n L = 500.0\n\n weights = 1.*np.random.randint(100,10000, size=n)\n coordinates = L*np.random.random(size=(n,2))\n tot_outflows = (1.-np.random.random(n)*0.5)*weights #200*np.ones(n)\n\n # exponential deterrence function\n deterrence_function = (lambda x: np.exp(-x**1./R_true) )\n # power law deterrence function\n # deterrence_function = (lambda x: np.power(x,3.) )\n\n rr, probs, flows = generate_synthetic_flows_scGM(n_locations, weights, coordinates,\\\n tot_outflows, deterrence_function, distfunc=Eucl_Dist)\n\n np.round(p[:5,:5],2)\n np.round(x[:5,:5],2)\n\n \"\"\"\n n = n_locations\n w = weights\n ll= coordinates\n\n r = np.zeros(shape=(n,n))\n for i in range(n):\n for j in range(n):\n r[i,j] = distfunc(ll[i],ll[j])\n\n p = deterrence_function(r)\n p -= np.eye(n)*np.diag(p)\n\n tpw = np.transpose(p*w)\n p = np.transpose(tpw/sum(tpw))\n np.putmask(p,np.isnan(p),0.0)\n\n x = np.array([np.random.multinomial(tot_outflows[i], p[i]) for i in range(n)])\n\n return r, p, x\n\n\nclass GLM_MultinomialRegression(torch.nn.Module):\n\n def __init__(self, dim_w, device=torch.device(\"cpu\")):\n super(GLM_MultinomialRegression, self).__init__()\n\n self.device = device\n self.linear1 = torch.nn.Linear(dim_w, 1)\n\n def forward(self, vX):\n out = self.linear1(vX)\n return out\n\n def loss(self, out, vT):\n lsm = torch.nn.LogSoftmax(dim=1)\n return -( vT * lsm(torch.squeeze(out, dim=-1)) ).sum()\n\n def negative_loglikelihood(self, tX, tT):\n return self.loss(self.forward(tX), tT).item()\n\n def train_one(self, optimizer, tX, tY):\n \"\"\"\n tX and tY are lists of numpy arrays (that can have variable dimensions)\n\n \"\"\"\n # Reset gradient\n optimizer.zero_grad()\n\n NlogL = 0.\n\n num_batches = len(tX)\n for k in range(num_batches):\n # x = Variable(torch.FloatTensor(tX[k]), requires_grad=False)\n # y = Variable(torch.FloatTensor(tY[k]), requires_grad=False)\n if 'cuda' in self.device.type:\n x = Variable(torch.from_numpy(np.array(tX[k])).cuda(), requires_grad=False)\n y = Variable(torch.from_numpy(np.array(tY[k])).cuda(), requires_grad=False)\n else:\n x = Variable(torch.from_numpy(np.array(tX[k])), requires_grad=False)\n y = Variable(torch.from_numpy(np.array(tY[k])), requires_grad=False)\n\n # Forward\n fx = self.forward(x)\n NlogL += self.loss(fx, y)\n\n # Backward\n NlogL.backward()\n\n # Update parameters\n optimizer.step()\n\n return NlogL.item() #NlogL.data[0]\n\n def predict_proba(self, x):\n sm = torch.nn.Softmax(dim=1)\n #probs = sm(torch.squeeze(self.forward(x), dim=2))\n probs = sm(torch.squeeze(self.forward(x), dim=-1))\n if 'cuda' in self.device.type:\n return probs.cpu().detach().numpy()\n else:\n return probs.detach().numpy()\n\n def average_OD_model(self, tX, tT):\n p = self.predict_proba(tX)\n if 'cuda' in self.device.type:\n #tot_out_trips = tT.sum(dim=1).cpu().detach().numpy()\n tot_out_trips = tT.sum(dim=-1).cpu().detach().numpy()\n else:\n #tot_out_trips = tT.sum(dim=1).detach().numpy()\n tot_out_trips = tT.sum(dim=-1).detach().numpy()\n model_od = (p.T * tot_out_trips).T\n return model_od\n\n def predict(self, x_val):\n x = Variable(x_val, requires_grad=False)\n output = self.forward(x)\n #return output.data.numpy().argmax(axis=1)\n return output.data.argmax(axis=1)\n\n\ndef get_features_original_gravity(oa_origin, oa_destination, oa2features, oa2centroid, df='exponential'):\n dist_od = earth_distance(oa2centroid[oa_origin], oa2centroid[oa_destination])\n #if df == 'powerlaw':\n # return [np.log(oa2features[oa_destination])] + [np.log(dist_od)]\n if df == 'exponential':\n return [np.log(oa2features[oa_destination])] + [dist_od]\n elif df == 'exponential_all':\n return oa2features[oa_origin] + oa2features[oa_destination] + [dist_od]\n\n\n\ndef get_flow(oa_origin, oa_destination, o2d2flow):\n try:\n # return od2flow[(oa_origin, oa_destination)]\n return o2d2flow[oa_origin][oa_destination]\n except KeyError:\n return 0\n\n\ndef get_destinations(oa, size_train_dest, all_locs_in_train_region, o2d2flow, frac_true_dest=0.5):\n try:\n true_dests_all = list(o2d2flow[oa].keys())\n except KeyError:\n true_dests_all = []\n size_true_dests = min(int(size_train_dest * frac_true_dest), len(true_dests_all))\n size_fake_dests = size_train_dest - size_true_dests\n # print(size_train_dest, size_true_dests, size_fake_dests, len(true_dests_all))\n\n true_dests = np.random.choice(true_dests_all, size=size_true_dests, replace=False)\n fake_dests_all = list(set(all_locs_in_train_region) - set(true_dests))\n fake_dests = np.random.choice(fake_dests_all, size=size_fake_dests, replace=False)\n\n dests = np.concatenate((true_dests, fake_dests))\n np.random.shuffle(dests)\n return dests\n\n\nclass NN_OriginalGravity(GLM_MultinomialRegression):\n\n def __init__(self, dim_input, df='exponential', device=torch.device(\"cpu\")):\n \"\"\"\n dim_input = 2\n dim_hidden = 20\n \"\"\"\n super(GLM_MultinomialRegression, self).__init__()\n # super().__init__(self)\n self.device = device\n self.df = df\n self.dim_input = dim_input\n self.linear_out = torch.nn.Linear(dim_input, 1)\n\n def forward(self, vX):\n out = self.linear_out(vX)\n return out\n\n def get_features(self, oa_origin, oa_destination, oa2features, oa2centroid, df):\n return get_features_original_gravity(oa_origin, oa_destination, oa2features, oa2centroid, df=df)\n\n def get_X_T(self, origin_locs, dest_locs, oa2features, oa2centroid, o2d2flow, verbose=False):\n \"\"\"\n origin_locs : list 1 X n_orig, IDs of origin locations\n dest_locs : list n_orig X n_dest, for each origin, IDs of destination locations\n \"\"\"\n\n #print(origin_locs)s\n\n # n_locs = len(origin_locs)\n X, T = [], []\n for en, i in enumerate(origin_locs):\n if verbose:\n pass\n # clear_output(wait=True)\n # print('%s of %s...'%(en, n_locs))\n\n X += [[]]\n T += [[]]\n for j in dest_locs[en]:\n if self.df == 'exponential' or self.df == 'exponential_all':\n X[-1] += [self.get_features(i, j, oa2features, oa2centroid, self.df)]\n else:\n X[-1] += [self.get_features(i, j, oa2features, oa2centroid, self.df, self.distances, self.k)]\n #X[-1] += [self.get_features(i, j, oa2features, oa2centroid, 'deepgravity_people')]\n # X[-1] += [get_features(o_lalo, o_feats, j, oa2features, oa2centroid)]\n T[-1] += [get_flow(i, j, o2d2flow)]\n\n if 'cuda' in self.device.type:\n teX = torch.from_numpy(np.array(X)).float().cuda()\n teT = torch.from_numpy(np.array(T)).float().cuda()\n else:\n teX = torch.from_numpy(np.array(X)).float()\n teT = torch.from_numpy(np.array(T)).float()\n\n return teX, teT\n\n def get_cpc(self, teX, teT, numerator_only=False):\n if 'cuda' in self.device.type:\n flatten_test_observed = teT.cpu().detach().numpy().flatten()\n else:\n flatten_test_observed = teT.detach().numpy().flatten()\n model_OD_test = self.average_OD_model(teX, teT)\n flatten_test_model = model_OD_test.flatten()\n cpc_test = common_part_of_commuters(flatten_test_observed, flatten_test_model, \n numerator_only=numerator_only)\n return cpc_test\n","sub_path":"deepgravity/od_models.py","file_name":"od_models.py","file_ext":"py","file_size_in_byte":10274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"645899918","text":"import numpy as np\nimport pandas as pd\n\nfrom .pesticide_calculator import pesticide_calculator\n\n\nclass Sam(object):\n def __init__(self, pd_obj, dummy_param=None):\n super(Sam, self).__init__()\n self.pd_obj = pd_obj\n self.pd_obj_out = pd.DataFrame(data=np.array([[0, 0], [0, 0]]), columns=['foo', 'bar'])\n\n def execute_model(self):\n self.pd_obj_out = pesticide_calculator(self.pd_obj)\n\ndef main(build=False):\n \"\"\" This is what gets run when running straight from Python \"\"\"\n if build:\n from .dev.test_inputs import atrazine_json_mtb_build as input_dict\n else:\n from .dev.test_inputs import atrazine_json_mtb as input_dict\n print('Running pesticide calculator...')\n sam = Sam(input_dict)\n sam.execute_model()\n\n","sub_path":"sam_exe_local.py","file_name":"sam_exe_local.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"619603608","text":"#made by J-VdS on 18-06-2018\r\n\r\nfrom PIL import Image\r\nimport os, glob\r\n\r\nnamefolder = input('give name of folder you want to make. ')\r\nos.mkdir(namefolder)\r\n\r\nfor name in glob.glob('*.png'):\r\n a = Image.open(name)\r\n w, h= a.size\r\n a.resize((30*w//8,30*h//8)).save(namefolder+'/'+name[:-4]+'.gif')\r\n\r\n\r\n","sub_path":"pngtogif.py","file_name":"pngtogif.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"578440568","text":"\n# coding: utf-8\n\n\nimport pandas as pd\n\n\npublications = pd.read_csv(\"teaching.csv\", header=0)\n\npublications = publications.fillna('')\n\n\n# ## Escape special characters\n# \n# YAML is very picky about how it takes a valid string, so we are replacing single and double quotes (and ampersands) with their HTML encoded equivilents. This makes them look not so readable in raw format, but they are parsed and rendered nicely.\n\nhtml_escape_table = {\n \"&\": \"&\",\n '\"': \""\",\n \"'\": \"'\"\n }\n\ndef html_escape(text):\n \"\"\"Produce entities within text.\"\"\"\n return \"\".join(html_escape_table.get(c,c) for c in text)\n\n\n# ## Creating the markdown files\n# \n# This is where the heavy lifting is done. This loops through all the rows in the TSV dataframe, then starts to concatentate a big string (```md```) that contains the markdown for each type. It does the YAML metadata first, then does the description for the individual page. If you don't want something to appear (like the \"Recommended citation\")\n\n\nimport os\nfor row, item in publications.iterrows():\n \n md_filename = str(item.date) + \"-\" + item.course_name + \".md\"\n html_filename = str(item.date) + \"-\" + item.course_name\n year = item.when[:4]\n \n ## YAML variables\n \n md = \"---\\ncourse_name: \\\"\" + item.course_name + '\"\\n'\n \n md += \"\"\"collection: teaching\"\"\"\n \n md += \"\"\"\\npermalink: /teaching/\"\"\" + html_filename\n \n md += \"\\ndescription: '\" + html_escape(item.course_description) + \"'\"\n \n md += \"\\nwhen: '\" + str(item.when) +\"'\"\n\n md += \"\\ndate: \" + str(item.date)\n \n md += \"\\nrole: '\" + html_escape(item.course_role) + \"'\"\n \n md += \"\\n---\"\n \n ## Markdown description for individual page\n \n \n md_filename = os.path.basename(md_filename)\n \n with open(\"../../_teaching/\" + md_filename, 'w') as f:\n f.write(md)\n","sub_path":"markdown_generator/teaching/teaching.py","file_name":"teaching.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"466202717","text":"\"\"\"\r\n Copyright (c) 2016- by Dietmar W Weiss\r\n\r\n This is free software; you can redistribute it and/or modify it\r\n under the terms of the GNU Lesser General Public License as\r\n published by the Free Software Foundation; either version 3.0 of\r\n the License, or (at your option) any later version.\r\n\r\n This software is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n Lesser General Public License for more details.\r\n\r\n You should have received a copy of the GNU Lesser General Public\r\n License along with this software; if not, write to the Free\r\n Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\r\n 02110-1301 USA, or see the FSF site: http://www.fsf.org.\r\n\r\n Version:\r\n 2018-06-25 DWW\r\n\"\"\"\r\n\r\n\r\ndef isFunction(x):\r\n \"\"\"\r\n Checks if argument x is callable\r\n\r\n Args:\r\n x (any type):\r\n instance to be checked\r\n\r\n Returns:\r\n (bool):\r\n True if x is callable\r\n \"\"\"\r\n return x is not None and hasattr(x, '__call__')\r\n\r\n\r\n# Examples ####################################################################\r\n\r\nif __name__ == '__main__':\r\n ALL = 1\r\n\r\n if 0 or ALL:\r\n def f():\r\n return 0.0\r\n\r\n class C(object):\r\n def f(self): pass\r\n c = C()\r\n\r\n for x in [f, lambda a: 1.0, c.f, c]:\r\n print('x:', str(x)[:str(x).index('at')-1] + str(x)[-1],\r\n '=> isFunction:', isFunction(x))\r\n print()\r\n\r\n n = None\r\n i = 1\r\n b = True\r\n d = 1.0\r\n l = [1, 2]\r\n t = (1, 2)\r\n s = 'abc'\r\n for x in [n, i, b, d, l, t, s]:\r\n print('x:', x, '=> isFunction:', isFunction(x))\r\n","sub_path":"coloredlids/tools/isfunction.py","file_name":"isfunction.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"32320946","text":"from time import gmtime, strftime\nimport sys\nimport re\nimport os\n\ndef iter_brackets(file, mainstart):\n 'returns an iteration of bracktes in a file'\n # get main end\n iterate = []\n m = []\n mm = []\n with open(file) as f:\n m = f.read().split('\\n')\n m = m[mainstart:]\n # strip out comments\n for l in m:\n # NOTE: changing from [] to ()\n if re.search('(//)+.*[{|}]+', l) is not None:\n l = re.sub('(//)+.*[{|}]+.*', '//--', l)\n # padd\n l = l.replace('{', '\\n{\\n')\n l = l.replace('}', '\\n}\\n')\n l.split('\\n')\n for part in l:\n mm.append(part + '\\n')\n # iterate\n get = re.finditer('{|}', str(mm))\n iterate = iter(get)\n return iterate\n \ndef file_len(fname):\n 'returns the length of a file'\n with open(fname) as f:\n for i, l in enumerate(f):\n pass\n return i + 1\n\ndef swap(org_main, new_main):\n 'locates and strips the main out of one file and inserts another file in its\\' place'\n \n # main start and end are the lines above the actual starting/ending line\n mainstart = 0\n mainend = 0\n temp_main = 'swapmain.c'\n length = file_len(org_main)\n \n log = '''-------------------------------\n---{0}---\nswaping mains\n{1}\\n{2}\n-file length: {3}\n'''.format(strftime(\"%a, %d %b %Y %H:%M:%S\", gmtime()), org_main, new_main, length)\n \n # get main start\n with open(org_main) as f:\n for i, l in enumerate(f):\n if re.search('[//]+.*main[\\t| ]*\\(.*\\)', l):\n pass\n elif re.search('(?= last_bracket:\n mainend = mainstart + i\n break\n log = log + '-main end: {0}\\n'.format(mainend)\n \n # swap main\n #original_file = open(org_main, 'r')\n #swap_file = open(temp_main,'w')\n #new_main = open(new_main,'r')\n #m = original_file.read().split('\\n')\n #\n #for l in m[:mainstart]:\n # line = '{0}\\n'.format(l.strip())\n # swap_file.write(line)\n #insert = new_main.read()\n #swap_file.write(insert)\n #for l in m[mainend+1:]:\n # line = '{0}\\n'.format(l)\n # swap_file.write(line.strip())\n ## add trailing new line for linux\n #swap_file.write('\\n')\n #\n #original_file.close()\n #swap_file.close()\n #new_main.close()\n \n update = 'mv {0} {1}'.format(temp_main, org_main)\n os.system(update)\n \n return log\n","sub_path":"comperio/codeparser/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"203538401","text":"import argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport yaml\n\n\ndef compute_autocorr(data, max_lag):\n m, n = data.shape\n\n mu = data.mean(axis=0)[None, :]\n\n autocorr = np.zeros((max_lag + 1, n), dtype=np.double)\n for k in range(max_lag + 1):\n autocorr[k, :] = \\\n ((data[k:, :] - mu) * (data[:m - k, :] - mu)).mean(axis=0) / \\\n ((data - mu)**2).mean(axis=0)\n\n return autocorr\n\n\ndef main(data_dir, sgd_step_list, burn_in, max_lag):\n os.makedirs('{}/plots/'.format(data_dir), exist_ok=True)\n\n for sgd_step in sgd_step_list:\n samples = np.loadtxt('{}/samples/step_{}.txt'.format(data_dir,\n sgd_step))\n m, n = samples.shape\n\n # trace plot\n for j in range(n):\n fig, ax = plt.subplots()\n ax.plot(np.arange(m), samples[:, j])\n ax.set_xlabel('MCMC Step')\n ax.set_ylabel('State[{}]'.format(j))\n fig.savefig('{}/plots/step_{}_trace_{}.pdf'.format(data_dir,\n sgd_step, j))\n plt.close(fig)\n\n # autocorrelation\n autocorr = compute_autocorr(samples[burn_in:, :], max_lag)\n\n fig, ax = plt.subplots()\n ax.plot(np.arange(max_lag + 1), autocorr)\n ax.set_xlabel('Lag')\n ax.set_ylabel('Autocorrelation')\n fig.savefig('{}/plots/step_{}_autocorr.pdf'.format(data_dir, sgd_step))\n plt.close(fig)\n\n\nif __name__ == '__main__':\n # parse arguments\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '--config_file',\n type=str,\n help='path to config file generated by vmcsolver'\n )\n parser.add_argument(\n '--max_lag',\n type=int,\n help='maximum lag used in autocorrelation computation'\n )\n parser.add_argument(\n '--sgd_step',\n type=int,\n default=None,\n help='samples from SGD step to analyze'\n )\n\n args = parser.parse_args()\n\n # read config\n with open(args.config_file, 'r') as file:\n config = yaml.safe_load(file)\n\n # setup\n data_dir = config['output']['prefix']\n\n if args.sgd_step is None:\n sgd_step_list = np.arange(\n start=0, stop=config['gradient_descent']['num_steps'] + 1,\n step=config['output']['frequency'])\n else:\n sgd_step_list = np.array([args.sgd_step])\n\n burn_in = config['metropolis']['warm_steps']\n\n # call main routine\n main(data_dir, sgd_step_list, burn_in, args.max_lag)\n","sub_path":"utils/analyze_samples.py","file_name":"analyze_samples.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"326084733","text":"# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file.\n\"\"\"\nselenium ui tests for storage.service component\n\"\"\"\n\nfrom flask import url_for\n\nfrom sner.server.extensions import db\nfrom sner.server.storage.models import Service\nfrom tests.selenium import dt_inrow_delete, dt_rendered\nfrom tests.selenium.storage import check_annotate, check_service_endpoint_dropdown\n\n\ndef test_service_list_route(live_server, sl_operator, service): # pylint: disable=unused-argument\n \"\"\"simple test ajaxed datatable rendering\"\"\"\n\n sl_operator.get(url_for('storage.service_list_route', _external=True))\n dt_rendered(sl_operator, 'service_list_table', service.comment)\n\n\ndef test_service_list_route_inrow_delete(live_server, sl_operator, service): # pylint: disable=unused-argument\n \"\"\"delete service inrow button\"\"\"\n\n service_id = service.id\n db.session.expunge(service)\n\n sl_operator.get(url_for('storage.service_list_route', _external=True))\n dt_inrow_delete(sl_operator, 'service_list_table')\n\n assert not Service.query.get(service_id)\n\n\ndef test_service_list_route_annotate(live_server, sl_operator, service): # pylint: disable=unused-argument\n \"\"\"test annotation from list route\"\"\"\n\n sl_operator.get(url_for('storage.service_list_route', _external=True))\n dt_rendered(sl_operator, 'service_list_table', service.comment)\n check_annotate(sl_operator, 'abutton_annotate_dt', service)\n\n\ndef test_service_list_route_service_endpoint_dropdown(live_server, sl_operator, service): # pylint: disable=unused-argument\n \"\"\"service endpoint uris dropdown test\"\"\"\n\n sl_operator.get(url_for('storage.service_list_route', _external=True))\n dt_rendered(sl_operator, 'service_list_table', service.comment)\n check_service_endpoint_dropdown(sl_operator, sl_operator.find_element_by_id('service_list_table'), service.port)\n","sub_path":"tests/selenium/storage/test_service.py","file_name":"test_service.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"351336130","text":"import functools\n\nimport torch\nimport torch.nn as nn\n\nclass UnetGenerator(nn.Module):\n def __init__(self, input_nc, output_nc, num_downs, ngf=64,\n norm_layer=nn.BatchNorm2d, use_dropout=False, output_function=nn.Sigmoid):\n super(UnetGenerator, self).__init__()\n # construct unet structure\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True)\n for i in range(num_downs - 5):\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)\n unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer,\n output_function=output_function)\n\n self.model = unet_block\n\n def forward(self, input):\n return self.model(input)\n\nclass UnetSkipConnectionBlock(nn.Module):\n def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d,\n use_dropout=False, output_function=nn.Sigmoid):\n super(UnetSkipConnectionBlock, self).__init__()\n self.outermost = outermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n down = [downconv]\n if output_function == nn.Tanh:\n up = [uprelu, upconv, nn.Tanh()]\n else:\n up = [uprelu, upconv, nn.Sigmoid()]\n model = down + [submodule] + up\n elif innermost:\n upconv = nn.ConvTranspose2d(inner_nc, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = down + up\n else:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv, downnorm]\n up = [uprelu, upconv, upnorm]\n\n if use_dropout:\n model = down + [submodule] + up + [nn.Dropout(0.5)]\n else:\n model = down + [submodule] + up\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n if self.outermost:\n return self.model(x)\n else:\n return torch.cat([x, self.model(x)], 1)\n\nclass RevealNet(nn.Module):\n def __init__(self, nc=3, nhf=64, output_function=nn.Sigmoid):\n super(RevealNet, self).__init__()\n # input is (3) x 256 x 256\n self.main = nn.Sequential(\n nn.Conv2d(nc, nhf, 3, 1, 1),\n nn.BatchNorm2d(nhf),\n nn.ReLU(True),\n nn.Conv2d(nhf, nhf * 2, 3, 1, 1),\n nn.BatchNorm2d(nhf*2),\n nn.ReLU(True),\n nn.Conv2d(nhf * 2, nhf * 4, 3, 1, 1),\n nn.BatchNorm2d(nhf*4),\n nn.ReLU(True),\n nn.Conv2d(nhf * 4, nhf * 2, 3, 1, 1),\n nn.BatchNorm2d(nhf*2),\n nn.ReLU(True),\n nn.Conv2d(nhf * 2, nhf, 3, 1, 1),\n nn.BatchNorm2d(nhf),\n nn.ReLU(True),\n nn.Conv2d(nhf, nc, 3, 1, 1),\n output_function()\n )\n\n def forward(self, input):\n output=self.main(input)\n return output\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"486749778","text":"\"\"\"\nread state from obstacle avoidance sensor using callback functions\n\n\"\"\"\nimport RPi.GPIO as GPIO\nimport time\n\noutPin = 15 # out connected to D15\nenPin = 16 # EN connected to D16\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(outPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\ndef eventObstacleSensor(e):\n\tprint(\"Obstacle found!\")\n\tprint(e)\n\nGPIO.add_event_detect(outPin, GPIO.FALLING, bouncetime = 200, callback = eventObstacleSensor)\n\nwhile(True):\n\ttime.sleep(0.1)","sub_path":"sensor-obstacle/obstacle.py","file_name":"obstacle.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"549258791","text":"\"\"\"Add relationship\n\nRevision ID: 8cc9557c4f82\nRevises: 5356a9089d2e\nCreate Date: 2018-02-13 19:08:31.386204\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '8cc9557c4f82'\ndown_revision = '5356a9089d2e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('blogs', sa.Column('comment_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'blogs', 'comments', ['comment_id'], ['id'])\n op.drop_constraint('comments_blog_id_fkey', 'comments', type_='foreignkey')\n op.drop_column('comments', 'blog_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('comments', sa.Column('blog_id', sa.INTEGER(), autoincrement=False, nullable=True))\n op.create_foreign_key('comments_blog_id_fkey', 'comments', 'blogs', ['blog_id'], ['id'])\n op.drop_constraint(None, 'blogs', type_='foreignkey')\n op.drop_column('blogs', 'comment_id')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/8cc9557c4f82_add_relationship.py","file_name":"8cc9557c4f82_add_relationship.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"89739755","text":"import logging\nimport inspect\nfrom pytest_reportportal import RPLogger, RPLogHandler\n\ndef customLogger(rp=False ,logLevel=logging.DEBUG):\n\n if rp is True:\n\n logging.setLoggerClass(RPLogger)\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.DEBUG)\n # Create handler for Report Portal.\n rp_handler = RPLogHandler()\n # Set INFO level for Report Portal handler.\n rp_handler.setLevel(logging.INFO)\n # Add handler to the logger.\n logger.addHandler(rp_handler)\n\n else:\n\n loggerName = inspect.stack()[1][3]\n logger = logging.getLogger(loggerName)\n logger.setLevel(logging.DEBUG)\n fileHandler = logging.FileHandler(\"webautopy.log\", mode='a')\n fileHandler.setLevel(logLevel)\n formatter = logging.Formatter('%(asctime)s: -%(name)s - %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\n fileHandler.setFormatter(formatter)\n logger.addHandler(fileHandler)\n\n return logger","sub_path":"utilities/custom_logger.py","file_name":"custom_logger.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"78136951","text":"#!/usr/bin/env python3\n\nimport signal, logging, sys, os, pickle, gzip, qdarkstyle\n# code to handle Ctrl+C, convenience method for command line tools\ndef signal_handler( signal, frame ):\n print( \"You pressed Ctrl+C. Exiting...\")\n sys.exit( 0 )\nsignal.signal( signal.SIGINT, signal_handler )\nfrom functools import reduce\nmainDir = reduce(lambda x,y: os.path.dirname( x ), range(2),\n os.path.abspath( __file__ ) )\nsys.path.append( mainDir )\nfrom optparse import OptionParser\nfrom plexcore import plexcore\nfrom plextmdb import plextmdb_totgui\nfrom PyQt5.QtWidgets import QApplication\n\ndef main(info = False, doLocal = True, doLarge = False,\n verify = True ):\n testDir = os.path.expanduser( '~/.config/plexstuff/tests' )\n app = QApplication([])\n app.setStyleSheet( qdarkstyle.load_stylesheet_pyqt5( ) )\n movie_data_rows = pickle.load( gzip.open(\n os.path.join( testDir, 'movie_data_rows.pkl.gz' ), 'rb' ) )\n if info: logging.basicConfig( level = logging.INFO )\n fullURL, token = plexcore.checkServerCredentials(\n doLocal = doLocal, verify = verify )\n tmdb_totgui = plextmdb_totgui.TMDBTotGUI(\n fullURL, token, movie_data_rows = movie_data_rows,\n doLarge = doLarge, verify = verify )\n result = app.exec_( )\n\nif __name__=='__main__':\n parser = OptionParser( )\n parser.add_option('--local', dest='do_local', action='store_true',\n default = False, help = 'Check for locally running plex server.')\n parser.add_option('--info', dest='do_info', action='store_true',\n default = False, help = 'Run info mode if chosen.')\n parser.add_option('--noverify', dest='do_verify', action='store_false',\n default = True, help = 'Do not verify SSL transactions if chosen.') \n opts, args = parser.parse_args( )\n main( info = opts.do_info, doLocal = opts.do_local, verify = opts.do_verify,\n doLarge = False )\n","sub_path":"tests/test_tmdb_totgui.py","file_name":"test_tmdb_totgui.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"216163546","text":"from airtest.core.api import *\nfrom poco.drivers.android.uiautomation import AndroidUiautomationPoco\nimport logging\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom base64 import b64decode\n# import io\n# import numpy\nimport time\n\nair_log = logging.getLogger(\"airtest\")\nair_log.setLevel('WARNING')\npoco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)\n\n\ndef snap():\n content, afix = poco.snapshot()\n return b64decode(content)\n\n\ndef get_sc():\n temp = snap()\n # hash = hashlib.md5(temp).hexdigest()\n with open('temp.jpg', 'wb') as f:\n f.write(temp)\n \n\n\n#\n# img_con = snap()\n# buffer = io.BytesIO(img_con)\n# img = plt.imread(buffer, 0)\n\n\ntep_list = ['blue0.jpg', 'red0.jpg', 'brown0.jpg']\n\ntouch_list = [[0.2, 0.8], [0.5, 0.8], [0.8, 0.8]]\n\n\ndef is_match(tep_num):\n imgcon = cv2.imread('temp.jpg', 0)\n realImg = imgcon[100:1300,180:540]\n template = cv2.imread(tep_list[tep_num], 0)\n w, h = template.shape[::-1]\n\n res = cv2.matchTemplate(realImg, template, cv2.TM_CCOEFF)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n top_left = max_loc\n bottom_right = (top_left[0] + w, top_left[1] + h)\n cv2.rectangle(realImg, top_left, bottom_right, 255, thickness=2)\n # pos = [top_left[0] + w / 2, top_left[1] + h / 2]\n\n print(max_val)\n plt.subplot(223), plt.imshow(res, cmap=\"gray\")\n plt.title('Matching Result'), plt.xticks([]), plt.yticks([])\n # plt.subplot(224), plt.imshow(realImg, cmap=\"gray\")\n # plt.title('Detected Point'), plt.xticks([]), plt.yticks([])\n # plt.show()\n\n if max_val < 20000000:\n return False\n else:\n return True\n\n\nwhile True:\n get_sc()\n for i in range(0, 3):\n if is_match(i):\n poco.click(touch_list[i])\n time.sleep(0.6)","sub_path":"poco(副本).py","file_name":"poco(副本).py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"438273715","text":"import pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom sklearn.tree import export_graphviz\nfrom sklearn.externals.six import StringIO \nfrom IPython.display import Image \nfrom scipy import sparse\n\n\n'''\nGenerates a decision tree using the sklearn implementation. In order to \ntrain the decision tree, data is generated using normal perturbation of \ncollected sample scores. The normal perturbation of the feature is \ndistributed as N(0,Var(Feature)), that is to say, we assume the sample \nfeatures match the true mean of the scores, the scores are normally distributed\nand their variance is proportional to the sample variance. This assumption \nis accurate under certain assumptions, but we hope to have true training data \nin future implementations.\n'''\n\n#Dictionary renaming the possible categories.\nRENAME_DIC={\n 'NATURE_PARKS': 'Parks',\n 'TOURS': 'Organized tours',\n 'COLD_OUTDOOR': 'Cold weather',\n 'SIGHTS_AND_LANDMARKS': 'Sightseeing',\n 'AMUSEMENT_PARKS': 'Entertainment',\n 'SHOPPING': 'Shopping',\n 'LAND_OUTDOOR': 'The outdoors',\n 'ZOOS': 'Animals',\n 'GROUND_NATURE': 'Nature',\n 'CASINOS': 'Nightlife',\n 'OUTDOOR_ACTIVITIES': 'Sports and recreation',\n 'HISTORIC': 'History',\n 'SEA_NATURE': 'Oceans and marine life',\n 'SEA_OUTDOOR': 'The beach',\n 'CONCERTS_SHOWS': 'Music and theater',\n 'FOOD_DRINK': 'Restaurants and bars',\n 'MUSEUMS': 'Culture and museums'\n }\n\n#Reads in previously computed scores for each country.\nscores = pd.read_csv('full_country_score.csv')\n\n#Computes mean and standard deviation for each score category.\nSTD_DICT=dict(scores.std(axis=0,skipna=True))\nMEAN_DICT=dict(scores.mean(axis=0,skipna=True))\nRANGE_DICT={}\n\n#Perturb scores to randomly generate training data.\nfor k,v in STD_DICT.items():\n RANGE_DICT[k]=(MEAN_DICT[k]-2*v, MEAN_DICT[k]-v, MEAN_DICT[k], \\\n MEAN_DICT[k]+v,MEAN_DICT[k]+2*v)\n\n\nfor col in [col for col in scores.columns if col!='city']:\n scores[col]=(scores[col]-scores[col].min()) / \\\n (scores[col].max()-scores[col].min())*10\n\nall_scores = pd.DataFrame().append([scores]*200)\nfeature_cols = scores.columns[1:] \nscores[feature_cols] = np.sqrt(scores[feature_cols])\nvariance = pd.DataFrame([scores.var(axis = 0)])\nfor columns in feature_cols:\n all_scores[columns] += np.random.normal( \\\n 0, np.sqrt(variance[columns] / 2), len(all_scores))\n\nX = all_scores[feature_cols] \n\ny = all_scores['city']\n\nX_train , X_test , y_train, y_test = train_test_split(X, y, test_size=0.3, \\\n random_state = 1)\n\nclf = DecisionTreeClassifier(max_depth = 12, criterion='entropy', \\\n min_samples_leaf = 5)\nclf = clf.fit(X_train,y_train)\n\ny_pred = clf.predict(X_test)\n\n# The actual tree structure.\ntree_ = clf.tree_ \n# Child structure : leftchild[i] is the left child to node with absolute \n# path i. etc.\nn_nodes = clf.tree_.node_count \nchildren_left = clf.tree_.children_left\nchildren_right = clf.tree_.children_right\n# Features: Feature[i] returns the column number/feature on which node i \n# is being split.\nfeature = clf.tree_.feature \n# Threshold: The value at which the split occurs.\nthreshold = clf.tree_.threshold \n\n# Gives names to feature columns rather than numbers.\nfeature_names = [feature_cols[i] for i in feature]#\n\n#Identifies all the possible leaf nodes of the dataset.\nleave_id = clf.apply(X_test) \n\n\ndef add_noise(dictionary):\n '''\n Adds noise to sample data to generate traning data.\n '''\n\n for k,v in dictionary.items():\n dictionary[k]=dictionary[k]+np.random.normal(0,STD_DICT[k]/2)\n\n\ndef look_for_city2(node, dictionary):\n '''\n Helper function for look_for_city that only adds noise once.\n '''\n\n add_noise(dictionary)\n return look_for_city(node, dictionary)\n\n\ndef look_for_city(node, dictionary):\n '''\n Recursively over the outputted sklearn tree to find the correct node/class/\n city based on user preferences. Sklearn trees are rather odd in their\n implementation. Nodes are given absolute numerical values rather than\n some numerical structure, and one can find nodes and their children \n through an array lookup structure, as seen above.\n '''\n\n if node in leave_id or children_left[node] == -1 or children_right[node] == -1:\n return (False, clf.classes_[np.argmax(tree_.value[node])])\n else:\n if feature_names[node] in dictionary:\n response=dictionary[feature_names[node]]\n if response <= threshold[node]:\n return look_for_city(node = children_left[node], \\\n dictionary=dictionary)\n else:\n return look_for_city(node = children_right[node], \\\n dictionary=dictionary)\n else:\n return(True, feature_names[node])\n","sub_path":"oursite/question/vacation_id3_attempt_2.py","file_name":"vacation_id3_attempt_2.py","file_ext":"py","file_size_in_byte":5213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"592888902","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom products.views.categories import *\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nrutes = [\n path('category/',include('products.routtes.category'))\n]\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',include('main.urls')),\n path('api/',include(rutes)),\n path('products/', include('products.urls.products')),\n path('categories/', include('products.urls.categories')),\n path('account/', include('account.urls')),\n]\n\nif settings.DEBUG:\n urlpatterns +=static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)","sub_path":"greekbrains_django/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"61159580","text":"#\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# Copyright (C) 2018-2019 UAVCAN Development Team \n# This software is distributed under the terms of the MIT License.\n#\n\"\"\"\n Filters for generating C++. All filters in this\n module will be available in the template's global namespace as ``cpp``.\n\"\"\"\n\nimport io\nimport re\nimport typing\n\nimport pydsdl\n\nfrom ... import SupportsTemplateEnv, templateEnvironmentFilter\nfrom ..c import (C_RESERVED_IDENTIFIERS, C_RESERVED_PATTERNS,\n VariableNameEncoder, _CFit)\nfrom ...lang import LanguageContext\nfrom ._support import IncludeGenerator\n\n\n# Taken from https://en.cppreference.com/w/cpp/keyword\nCPP_RESERVED_IDENTIFIERS = frozenset([\n *C_RESERVED_IDENTIFIERS,\n 'alignas',\n 'alignof',\n 'and',\n 'and_eq',\n 'asm',\n 'atomic_cancel',\n 'atomic_commit',\n 'atomic_noexcept',\n 'auto',\n 'bitand',\n 'bitor',\n 'bool',\n 'break',\n 'case',\n 'catch',\n 'char',\n 'char8_t',\n 'char16_t',\n 'char32_t',\n 'class',\n 'compl',\n 'concept',\n 'const',\n 'consteval',\n 'constexpr',\n 'constinit',\n 'const_cast',\n 'continue',\n 'co_await',\n 'co_return',\n 'co_yield',\n 'decltype',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'dynamic_cast',\n 'else',\n 'enum',\n 'explicit',\n 'export',\n 'extern',\n 'false',\n 'float',\n 'for',\n 'friend',\n 'goto',\n 'if',\n 'inline',\n 'int',\n 'long',\n 'mutable',\n 'namespace',\n 'new',\n 'noexcept',\n 'not',\n 'not_eq',\n 'nullptr',\n 'operator',\n 'or',\n 'or_eq',\n 'private',\n 'protected',\n 'public',\n 'reflexpr',\n 'register',\n 'reinterpret_cast',\n 'requires',\n 'return',\n 'short',\n 'signed',\n 'sizeof',\n 'static',\n 'static_assert',\n 'static_cast',\n 'struct',\n 'switch',\n 'synchronized',\n 'template',\n 'this',\n 'thread_local',\n 'throw',\n 'true',\n 'try',\n 'typedef',\n 'typeid',\n 'typename',\n 'union',\n 'unsigned',\n 'using',\n 'virtual',\n 'void',\n 'volatile',\n 'wchar_t',\n 'while',\n 'xor',\n 'xor_eq',\n 'override',\n 'final',\n 'import',\n 'module',\n 'transaction_safe',\n 'transaction_safe_dynamic',\n '_Pragma',\n 'if',\n 'elif',\n 'else',\n 'endif',\n 'ifdef',\n 'ifndef',\n 'define',\n 'undef',\n 'include',\n 'line',\n 'error',\n 'pragma',\n 'defined',\n '__has_include',\n '__has_cpp_attribute'\n])\n\nCPP_RESERVED_PATTERNS = frozenset([*C_RESERVED_PATTERNS])\n\nCPP_NO_DOUBLE_DASH_RULE = re.compile(r'(__)')\n\n\ndef filter_id(instance: typing.Any, stropping_prefix: str = '_', encoding_prefix: str = 'ZX') -> str:\n \"\"\"\n Filter that produces a valid C and/or C++ identifier for a given object. The encoding may not\n be reversable.\n\n .. invisible-code-block: python\n\n from nunavut.lang.cpp import filter_id\n\n\n .. code-block:: python\n\n # Given\n I = 'I like c++'\n\n # and\n template = '{{ I | id }}'\n\n # then\n rendered = 'I_like_cZX002BZX002B'\n\n\n .. invisible-code-block: python\n\n jinja_filter_tester(filter_id, template, rendered, I=I)\n\n\n .. code-block:: python\n\n # Given\n I = 'if'\n\n # and\n template = '{{ I | id }}'\n\n # then\n rendered = '_if'\n\n\n .. invisible-code-block: python\n\n jinja_filter_tester(filter_id, template, rendered, I=I)\n\n\n .. code-block:: python\n\n # Given\n I = 'if'\n\n # and\n template = '{{ I | id(\"stropped_\") }}'\n\n # then\n rendered = 'stropped_if'\n\n .. invisible-code-block: python\n\n jinja_filter_tester(filter_id, template, rendered, I=I)\n\n\n .. code-block:: python\n\n # Given\n I = '_Reserved'\n\n # and\n template = '{{ I | id }}'\n\n # then\n rendered = '_reserved'\n\n .. invisible-code-block: python\n\n jinja_filter_tester(filter_id, template, rendered, I=I)\n\n :param any instance: Any object or data that either has a name property or can be converted\n to a string.\n :param str stropping_prefix: String prepended to the resolved instance name if the encoded value\n is a reserved keyword in C or C++.\n :param str encoding_prefix: The string to insert before any four digit unicode number used to represent\n an illegal character.\n Note that the caller must ensure the prefix itself consists of only valid\n characters for C and C++ identifiers.\n :returns: A token that is a valid identifier for C and C++, is not a reserved keyword, and is transformed\n in a deterministic manner based on the provided instance.\n \"\"\"\n if hasattr(instance, 'name'):\n raw_name = str(instance.name) # type: str\n else:\n raw_name = str(instance)\n\n vne = VariableNameEncoder(stropping_prefix, '', encoding_prefix)\n out = vne.strop(raw_name, CPP_RESERVED_IDENTIFIERS, CPP_RESERVED_PATTERNS)\n return CPP_NO_DOUBLE_DASH_RULE.sub('_' + vne.encode_character('_'), out)\n\n\ndef filter_open_namespace(full_namespace: str,\n bracket_on_next_line: bool = True,\n linesep: str = '\\n',\n stropping: bool = True) -> str:\n \"\"\"\n Emits c++ opening namspace syntax parsed from a pydsdl \"full_namespace\",\n dot-seperated value.\n\n .. invisible-code-block: python\n\n from nunavut.lang.cpp import filter_open_namespace\n T = lambda : None;\n setattr(T, 'full_namespace)', '')\n\n .. code-block:: python\n\n # Given\n T.full_namespace = 'uavcan.foo'\n\n # and\n template = '{{ T.full_namespace | open_namespace }}'\n\n # then\n rendered = '''namespace uavcan\n {\n namespace foo\n {\n '''\n\n .. invisible-code-block: python\n\n jinja_filter_tester(filter_open_namespace, template, rendered, T=T)\n\n :param str full_namespace: A dot-seperated namespace string.\n :param bool bracket_on_next_line: If True (the default) then the opening\n brackets are placed on a newline after the namespace keyword.\n :param str linesep: The line-seperator to use when emitting new lines.\n By default this is ``\\\\n``.\n\n :returns: C++ namespace declarations with opening brackets.\n \"\"\"\n\n with io.StringIO() as content:\n for name in full_namespace.split('.'):\n content.write('namespace ')\n if stropping:\n content.write(filter_id(name))\n else:\n content.write(name)\n if bracket_on_next_line:\n content.write(linesep)\n else:\n content.write(' ')\n content.write('{')\n content.write(linesep)\n return content.getvalue()\n\n\ndef filter_close_namespace(full_namespace: str,\n omit_comments: bool = False,\n linesep: str = '\\n',\n stropping: bool = True) -> str:\n \"\"\"\n Emits c++ closing namspace syntax parsed from a pydsdl \"full_namespace\",\n dot-seperated value.\n\n .. invisible-code-block: python\n\n from nunavut.lang.cpp import filter_close_namespace\n T = lambda : None;\n setattr(T, 'full_namespace)', '')\n\n .. code-block:: python\n\n # Given\n T.full_namespace = 'uavcan.foo'\n\n # and\n template = '{{ T.full_namespace | close_namespace }}'\n\n # then\n rendered = '''} // namespace foo\n } // namespace uavcan\n '''\n\n .. invisible-code-block: python\n\n jinja_filter_tester(filter_close_namespace, template, rendered, T=T)\n\n\n :param str full_namespace: A dot-seperated namespace string.\n :param bool omit_comments: If True then the comments following the closing\n bracket are omitted.\n :param str linesep: The line-seperator to use when emitting new lines.\n By default this is ``\\\\n``\n\n :returns: C++ namespace declarations with opening brackets.\n \"\"\"\n with io.StringIO() as content:\n for name in reversed(full_namespace.split('.')):\n content.write('}')\n if not omit_comments:\n content.write(' // namespace ')\n if stropping:\n content.write(filter_id(name))\n else:\n content.write(name)\n content.write(linesep)\n return content.getvalue()\n\n\ndef filter_full_reference_name(t: pydsdl.CompositeType, stropping: bool = True) -> str:\n \"\"\"\n Provides a string that is the full namespace, typename, major, and minor version for a given composite type.\n\n .. invisible-code-block: python\n\n from nunavut.lang.cpp import filter_full_reference_name\n from unittest.mock import MagicMock\n import pydsdl\n\n my_obj = MagicMock()\n my_obj.parent_service = None\n my_obj.version = MagicMock()\n\n .. code-block:: python\n\n # Given a type with illegal characters for C++\n my_obj.full_name = 'any.int.2Foo'\n my_obj.version.major = 1\n my_obj.version.minor = 2\n\n # and\n template = '{{ my_obj | full_reference_name }}'\n\n # then, with stropping enabled\n rendered = 'any::_int::_2Foo_1_2'\n\n .. invisible-code-block: python\n\n my_obj.short_name = my_obj.full_name.split('.')[-1]\n jinja_filter_tester(filter_full_reference_name, template, rendered, my_obj=my_obj)\n\n my_obj = MagicMock()\n my_obj.version = MagicMock()\n my_obj.parent_service = None\n\n .. code-block:: python\n\n # Given a type with illegal characters for C++\n my_obj.full_name = 'any.int.2Foo'\n my_obj.version.major = 1\n my_obj.version.minor = 2\n\n # and\n template = '{{ my_obj | full_reference_name(stropping=False) }}'\n\n # then, with stropping disabled\n rendered = 'any::int::2Foo_1_2'\n\n .. invisible-code-block: python\n\n my_obj.short_name = my_obj.full_name.split('.')[-1]\n jinja_filter_tester(filter_full_reference_name, template, rendered, my_obj=my_obj)\n\n .. invisible-code-block: python\n\n my_obj = MagicMock(spec=pydsdl.CompositeType)\n my_obj.version = MagicMock()\n my_service = MagicMock(spec=pydsdl.ServiceType)\n my_service.parent_service = None\n my_service.version = MagicMock()\n my_service.attributes = { 'Request': my_obj }\n my_obj.parent_service = my_service\n\n Note that for service types\n\n .. code-block:: python\n\n # Given a service type\n my_service.full_name = 'my.Service'\n my_service.version.major = 1\n my_service.version.minor = 8\n\n # and\n template = '{{ my_service.attributes[\"Request\"] | full_reference_name }}'\n\n # then\n rendered = 'my::Service_1_8::Request'\n\n .. invisible-code-block: python\n\n my_service.short_name = my_service.full_name.split('.')[-1]\n my_obj.short_name = 'Request'\n my_obj.full_name = my_service.full_name + '.' + my_obj.short_name\n\n jinja_filter_tester(filter_full_reference_name, template, rendered, my_service=my_service)\n\n :param pydsdl.CompositeType t: The DSDL type to get the fully-resolved reference name for.\n :param bool stropping: If True then the :func:`filter_id` filter is applied to each component in the identifier.\n \"\"\"\n ns_parts = t.full_name.split('.')\n if stropping:\n ns = list(map(filter_id, ns_parts[:-1]))\n else:\n ns = ns_parts[:-1]\n\n if t.parent_service is not None:\n assert len(ns) > 0 # Well-formed DSDL will never have a request or response type that isn't nested.\n ns = ns[:-1] + [filter_short_reference_name(t.parent_service, stropping=stropping)]\n\n full_path = ns + [filter_short_reference_name(t, stropping)]\n return '::'.join(full_path)\n\n\ndef filter_short_reference_name(t: pydsdl.CompositeType, stropping: bool = True) -> str:\n \"\"\"\n Provides a string that is a shorted version of the full reference name. This type is unique only within its\n namespace.\n\n .. invisible-code-block: python\n\n from nunavut.lang.cpp import filter_short_reference_name\n from unittest.mock import MagicMock\n import pydsdl\n\n my_type = MagicMock(spec=pydsdl.StructureType)\n my_type.version = MagicMock()\n my_type.parent_service = None\n\n .. code-block:: python\n\n # Given a type with illegal C++ characters\n my_type.short_name = '2Foo'\n my_type.version.major = 1\n my_type.version.minor = 2\n\n # and\n template = '{{ my_type | short_reference_name }}'\n\n # then, with stropping enabled\n rendered = '_2Foo_1_2'\n\n .. invisible-code-block: python\n\n jinja_filter_tester(filter_short_reference_name, template, rendered, my_type=my_type)\n\n my_type = MagicMock(spec=pydsdl.StructureType)\n my_type.version = MagicMock()\n my_type.parent_service = None\n\n .. code-block:: python\n\n # Given a type with illegal C++ characters\n my_type.short_name = '2Foo'\n my_type.version.major = 1\n my_type.version.minor = 2\n\n # and\n template = '{{ my_type | short_reference_name(stropping=False) }}'\n\n # then\n rendered = '2Foo_1_2'\n\n .. invisible-code-block: python\n\n jinja_filter_tester(filter_short_reference_name, template, rendered, my_type=my_type)\n\n :param pydsdl.CompositeType t: The DSDL type to get the reference name for.\n \"\"\"\n if t.parent_service is None:\n short_name = '{short}_{major}_{minor}'.format(short=t.short_name, major=t.version.major, minor=t.version.minor)\n else:\n short_name = t.short_name\n if stropping:\n return filter_id(short_name)\n else:\n return short_name\n\n\n@templateEnvironmentFilter\ndef filter_includes(env: SupportsTemplateEnv,\n t: pydsdl.CompositeType,\n sort: bool = True,\n prefer_system_includes: bool = False,\n use_standard_types: bool = True,\n stropping: bool = True) -> typing.List[str]:\n \"\"\"\n Returns a list of all include paths for a given type.\n\n :param pydsdl.CompositeType t: The type to scan for dependencies.\n :param bool sort: If true the returned list will be sorted.\n :param bool strop: If true the list will contained stropped identifiers.\n :return: a list of include headers needed for a given type.\n \"\"\"\n\n include_gen = IncludeGenerator(t, filter_id, filter_short_reference_name, use_standard_types, stropping)\n return include_gen.generate_include_filepart_list(LanguageContext.get_from_globals(\n env.globals).get_output_extension(),\n sort,\n prefer_system_includes)\n\n\ndef filter_declaration(instance: pydsdl.Any, use_standard_types: bool = True) -> str:\n \"\"\"\n Emit a declaration statement for the given instance.\n \"\"\"\n if isinstance(instance, pydsdl.PrimitiveType) or isinstance(instance, pydsdl.VoidType):\n return filter_type_from_primitive(instance, use_standard_types)\n elif isinstance(instance, pydsdl.VariableLengthArrayType):\n return 'std::vector<{}>'.format(filter_declaration(instance.element_type, use_standard_types))\n elif isinstance(instance, pydsdl.ArrayType):\n return 'std::Array<{}>'.format(filter_declaration(instance.element_type, use_standard_types))\n else:\n return filter_full_reference_name(instance)\n\n\ndef filter_definition_begin(instance: pydsdl.CompositeType) -> str:\n \"\"\"\n Emit the start of a definition statement for a composite type.\n\n .. invisible-code-block: python\n\n from nunavut.lang.cpp import filter_definition_begin\n from unittest.mock import MagicMock\n import pytest\n import pydsdl\n\n my_type = MagicMock(spec=pydsdl.StructureType)\n my_type.version = MagicMock()\n my_type.parent_service = None\n\n with pytest.raises(ValueError):\n jinja_filter_tester(filter_definition_begin, '{{ my_type | definition_begin }}', '', my_type=MagicMock())\n\n .. code-block:: python\n\n # Given a pydsdl.CompositeType \"my_type\":\n my_type.short_name = 'Foo'\n my_type.version.major = 1\n my_type.version.minor = 0\n\n # and\n template = '{{ my_type | definition_begin }}'\n\n # then\n rendered = 'struct Foo_1_0'\n\n .. invisible-code-block: python\n\n jinja_filter_tester(filter_definition_begin, template, rendered, my_type=my_type)\n\n my_union_type = MagicMock(spec=pydsdl.UnionType)\n my_union_type.version = MagicMock()\n my_union_type.parent_service = None\n\n .. code-block:: python\n\n # Also, given a pydsdl.UnionType \"my_union_type\":\n my_union_type.short_name = 'Foo'\n my_union_type.version.major = 1\n my_union_type.version.minor = 0\n\n # and\n union_template = '{{ my_union_type | definition_begin }}'\n\n # then\n rendered = 'union Foo_1_0'\n\n .. invisible-code-block: python\n\n jinja_filter_tester(filter_definition_begin, union_template, rendered, my_union_type=my_union_type)\n\n my_service_type = MagicMock(spec=pydsdl.ServiceType)\n my_service_type.version = MagicMock()\n my_service_type.parent_service = None\n\n .. code-block:: python\n\n # Finally, given a pydsdl.Servicetype \"my_service_type\":\n my_service_type.short_name = 'Foo'\n my_service_type.version.major = 1\n my_service_type.version.minor = 0\n\n # and\n template = '{{ my_service_type | definition_begin }}'\n\n # then\n rendered = 'namespace Foo_1_0'\n\n .. invisible-code-block: python\n\n jinja_filter_tester(filter_definition_begin, template, rendered, my_service_type=my_service_type)\n\n \"\"\"\n short_name = filter_short_reference_name(instance)\n if isinstance(instance, pydsdl.StructureType):\n return 'struct {}'.format(short_name)\n elif isinstance(instance, pydsdl.UnionType):\n return 'union {}'.format(short_name)\n elif isinstance(instance, pydsdl.ServiceType):\n return 'namespace {}'.format(short_name)\n else:\n raise ValueError('{} types cannot be redefined.'.format(type(instance).__name__))\n\n\ndef filter_definition_end(instance: pydsdl.CompositeType) -> str:\n \"\"\"\n Emit the end of a definition statement for a composite type.\n\n .. invisible-code-block: python\n\n from nunavut.lang.cpp import filter_definition_end\n from unittest.mock import MagicMock\n import pytest\n import pydsdl\n\n\n with pytest.raises(ValueError):\n jinja_filter_tester(filter_definition_end, '{{ my_type | definition_end }}', '', my_type=MagicMock())\n\n my_type = MagicMock(spec=pydsdl.StructureType)\n my_type.version = MagicMock()\n my_type.short_name = 'Foo'\n my_type.version.major = 1\n my_type.version.minor = 0\n\n jinja_filter_tester(filter_definition_end, '{{ my_type | definition_end }}', ';', my_type=my_type)\n\n my_type = MagicMock(spec=pydsdl.UnionType)\n my_type.version = MagicMock()\n my_type.short_name = 'Foo'\n my_type.version.major = 1\n my_type.version.minor = 0\n\n jinja_filter_tester(filter_definition_end, '{{ my_type | definition_end }}', ';', my_type=my_type)\n\n my_type = MagicMock(spec=pydsdl.ServiceType)\n my_type.version = MagicMock()\n my_type.parent_service = None\n my_type.short_name = 'Foo'\n my_type.version.major = 1\n my_type.version.minor = 0\n\n jinja_filter_tester(filter_definition_end,\n '{{ my_type | definition_end }}',\n ' // namespace Foo_1_0',\n my_type=my_type)\n\n \"\"\"\n if isinstance(instance, pydsdl.StructureType) or isinstance(instance, pydsdl.UnionType):\n return ';'\n elif isinstance(instance, pydsdl.ServiceType):\n return ' // namespace {}'.format(filter_short_reference_name(instance))\n else:\n raise ValueError('{} types cannot be redefined.'.format(type(instance).__name__))\n\n\ndef filter_type_from_primitive(value: pydsdl.PrimitiveType, use_standard_types: bool = True) -> str:\n return _CFit.get_best_fit(value.bit_length).to_c_type(value, use_standard_types)\n","sub_path":"src/nunavut/lang/cpp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":20594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"591310580","text":"import abc\n\nimport gtimer as gt\nfrom rlkit.core import logger\nfrom rlkit.core.rl_algorithm import BaseRLAlgorithm\nfrom rlkit.data_management.replay_buffer import ReplayBuffer\nfrom rlkit.samplers.data_collector import PathCollector\nimport numpy as np\n\n\nclass LifetimeRLAlgorithm(BaseRLAlgorithm, metaclass=abc.ABCMeta):\n def __init__(\n self,\n trainer,\n exploration_env,\n evaluation_env,\n exploration_data_collector: PathCollector,\n evaluation_data_collector: PathCollector,\n replay_buffer: ReplayBuffer,\n batch_size,\n max_path_length,\n num_epochs,\n # param not used but kept for consistency\n num_eval_steps_per_epoch,\n # this is really eval steps since eval = expl\n num_expl_steps_per_train_loop,\n num_trains_per_train_loop,\n num_train_loops_per_epoch=1,\n min_num_steps_before_training=0,\n **kwargs\n ):\n super().__init__(\n trainer,\n exploration_env,\n evaluation_env,\n exploration_data_collector,\n evaluation_data_collector,\n replay_buffer,\n **kwargs\n )\n self.batch_size = batch_size\n self.max_path_length = max_path_length\n self.num_epochs = num_epochs\n self.num_trains_per_train_loop = num_trains_per_train_loop\n self.num_train_loops_per_epoch = num_train_loops_per_epoch\n self.num_expl_steps_per_train_loop = num_expl_steps_per_train_loop\n self.min_num_steps_before_training = min_num_steps_before_training\n self.evaluation_env = evaluation_env\n\n def train(self, start_epoch=0, **kwargs):\n self._start_epoch = start_epoch\n self._train(**kwargs)\n \n def _train(self, minigrid=True):\n if self.min_num_steps_before_training > 0:\n init_eval_path = self.eval_data_collector.collect_new_paths(\n self.max_path_length,\n self.min_num_steps_before_training,\n discard_incomplete_paths=False,\n continuing=False\n )\n self.replay_buffer.add_paths([init_eval_path])\n self.eval_data_collector.end_epoch(-1)\n\n if np.any(init_eval_path['terminals']):\n return\n\n done = False\n num_loops = 0\n while not done:\n num_loops += 1\n if hasattr(self.evaluation_env, 'health'):\n print(\n 'Steps: %d, health: %d' % (num_loops * self.num_expl_steps_per_train_loop, self.evaluation_env.health))\n new_eval_path = self.eval_data_collector.collect_new_paths(\n self.max_path_length,\n self.num_expl_steps_per_train_loop,\n discard_incomplete_paths=False,\n continuing=True\n )\n\n gt.stamp('exploration sampling', unique=False)\n\n self.replay_buffer.add_paths([new_eval_path])\n gt.stamp('data storing', unique=False)\n\n self.training_mode(True)\n for _ in range(self.num_trains_per_train_loop):\n train_data = self.replay_buffer.random_batch(\n self.batch_size)\n self.trainer.train(train_data)\n gt.stamp('training', unique=False)\n self.training_mode(False)\n done = num_loops >= self.num_epochs\n\n print('Ending epoch')\n self._end_epoch(num_loops - 1, incl_expl=False, minigrid=minigrid)\n","sub_path":"rlkit/core/lifetime_rl_algorithm.py","file_name":"lifetime_rl_algorithm.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"181308144","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.http import Request\nfrom JobBoLeArticle.utils.common import get_md5\nimport re\nimport datetime\nfrom scrapy.loader import ItemLoader\n\nfrom JobBoLeArticle.items import JobbolearticleItem, ArticleItemLoader\n\n\nclass ArticleSpider(scrapy.Spider):\n name = 'article'\n allowed_domains = ['blog.jobbole.com']\n start_urls = ['http://blog.jobbole.com/all-posts/']\n\n def parse(self, response):\n\n # 获取文章url和图片url\n nodes = response.css(\"#archive .post-thumb\")\n for node in nodes:\n article_url = node.css('a::attr(href)').extract()[0]\n image_url = node.css('a img::attr(src)').extract()[0]\n # print(article_url, image_url)\n yield Request(article_url, meta={'image_url': image_url}, callback=self.parse_detail)\n\n # 获取下一页url\n # next_page_url = response.css(\".navigation a.next::attr(href)\").extract_first(\"\")\n # if next_page_url:\n # print(next_page_url)\n # yield Request(next_page_url, callback=self.parse)\n\n def parse_detail(self, response):\n\n # item = JobbolearticleItem()\n #\n # # 文章标题\n # item['title'] = response.css(\".entry-header h1::text\").extract_first(\"\")\n #\n # # 文章url\n # item['url'] = response.url\n #\n # item['image_url'] = [response.meta.get('image_url', '')]\n #\n # # url进行md5加密\n # item['url_object_id'] = get_md5(response.url)\n #\n # # 文章创建时间\n # create_date = response.css(\".entry-meta p::text\").extract_first().strip()[:-2]\n # try:\n # create_date = datetime.datetime.strptime(create_date, '%Y/%m/%d').date()\n #\n # except Exception as e:\n # create_date = datetime.datetime.now().date()\n #\n # item['create_date'] = create_date\n #\n # # 文章标签\n # tags_list = response.css(\".entry-meta a::text\").extract()\n # tags_list = [tag for tag in tags_list if not tag.strip().endswith(\"评论\")]\n # item['tags'] = \",\".join(tags_list)\n #\n # # 点赞数\n # item['vote_nums'] = response.css(\"vote_nums\").extract_first(\"\")\n #\n # # 收藏数\n # fav_nums = response.css(\".post-adds .bookmark-btn::text\").extract_first(\"\")\n # item['fav_nums'] = self.match_re(fav_nums)\n #\n # # 评论数\n # comments = response.css(\".post-adds a[href='#article-comment'] span::text\").extract_first(\"\")\n # item['comment_nums'] = self.match_re(comments)\n #\n # # 文章内容\n # item['content'] = response.css(\".entry\").extract_first(\"\")\n\n # 通过itemloader加载item item_loader.add_xpath() item_loader.add_value()\n item_loader = ArticleItemLoader(item=JobbolearticleItem(), response=response)\n item_loader.add_css('title', '.entry-header h1::text')\n item_loader.add_value('url', response.url)\n item_loader.add_value('url_object_id', get_md5(response.url))\n item_loader.add_css('create_date', '.entry-meta p::text')\n item_loader.add_value('image_url', [response.meta.get('image_url', '')])\n item_loader.add_css('vote_nums', '.vote-post-up h10::text')\n item_loader.add_css('fav_nums', '.post-adds .bookmark-btn::text')\n item_loader.add_css('comment_nums', \".post-adds a[href='#article-comment'] span::text\")\n item_loader.add_css('tags', '.entry-meta a::text')\n item_loader.add_css('content', '.entry')\n\n article_item = item_loader.load_item()\n\n\n\n # yield item\n yield article_item\n\n def match_re(self, string):\n match_re = re.search('.*?(\\d+).*', string)\n if match_re:\n return int(match_re.group(1))\n else:\n return 0","sub_path":"JobBoLeArticle/JobBoLeArticle/spiders/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":3850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"199514975","text":"import numpy\nimport scipy\nimport gensim\nimport nltk\nimport codecs\nimport collections\n\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom numpy import zeros\nfrom scipy.linalg import svd\nfrom collections import defaultdict\nfrom gensim import corpora, similarities\nfrom gensim import models\n\nstoplist = set(stopwords.words('english'))\n\ndef getwords(x):\n\twith codecs.open(x, \"r\", encoding='utf-8', errors='ignore') as f:\n\t\tline = f.read()\n\t\telement = nltk.word_tokenize(line)\n\treturn element\n\n\n\n\nfiles = []\na = getwords('input.txt')#mention file names in input.txt\nfor i in a:\n\tfiles.append(i)\n#print files\n\nj = 0\ndocuments = []\nfor i in files:\n\tdocuments.append(getwords(files[j]))\n\tj = j + 1\n\n#print documents\n\n\n\ndocuments = [[word for word in document if word not in stoplist] for document in documents]\n\nfrequency = defaultdict(int)\nfor text in documents:\n for token in text:\n frequency[token] += 1\n\ntexts = [[token for token in text if frequency[token] > 1]\n for text in documents]\n\n\n\ndictionary = corpora.Dictionary(texts)\n\n\ncorpus = [dictionary.doc2bow(text) for text in texts]\n\n\n#----------------------------------------------\n\ntfidf = models.TfidfModel(corpus)\n\ncorpus_tfidf = tfidf[corpus]\n\n\n#lsi\nno_of_topic=raw_input(\"enter no of topic\")\nlsi = models.LdaModel(corpus_tfidf, id2word=dictionary, num_topics=no_of_topic)\ncorpus_lsi = lsi[corpus_tfidf]\n#x=lsi.print_topics(5)\nlsi.save('/tmp/model.lsi')\ndictionary.save('/tmp/deerwester.dict')\n#print x\n\n#index = similarities.MatrixSimilarity(lsi[corpus])\n\n#_test=open('001.txt','r')\n#F=_test.read()\n#F=F.strip()\n#F=F.split()\n#doc = ['Human' , 'computer' , 'Interaction']\n#doc=F\n#vec_bow = dictionary.doc2bow(doc)\n#vec_lsi = lsi[vec_bow] # convert the query to LSI space\n#print vec_lsi\n#sims = index[vec_lsi]\n#sims = sorted(enumerate(sims), key=lambda item: -item[1])\n#print sims\n#count=0\n#for i in sims:\n# print i\n# count=count+1\n# if count > 5:\n# break\n\n\n","sub_path":"project/code/lda.py","file_name":"lda.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"48142605","text":"# 선형회귀 모형 계산\n\nimport tensorflow as tf\nimport numpy as np\n\nx = [1.,2.,3.,4.,5.] #feature\ny = [1.2,2.0,3.0,3.5,5.5] #\n\nw= tf.Variable(tf.random.normal((1,)))\nb= tf.Variable(tf.random.normal((1,)))\n\nopti = tf.keras.optimizers.SGD()\n\ndef train_step(x,y):\n with tf.GradientTape() as tape:\n hypo = tf.add(tf.multiply(w,x),b)\n loss = tf.reduce_mean(tf.square(tf.subtract(hypo,y)))\n \n grad = tape.gradient(loss,[w,b])\n opti.apply_gradients(zip(grad,[w,b]))\n return loss\n\nw_val = []\nloss_vals = []\nfor i in range(100):\n loss_val = train_step(x, y)\n loss_vals.append(loss_val.numpy())\n w_val.append(w.numpy())\n #print(loss_val)\n \nprint(w_val)\nprint(loss_vals)\n \nimport matplotlib.pyplot as plt\nplt.plot(w_val,loss_vals,'o')\n\nplt.show()\n\n\n\n ","sub_path":"py_tensorflow/pack/tf2/케라스4_선형회귀모형계산.py","file_name":"케라스4_선형회귀모형계산.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"361637648","text":"## filter.py\n# B(E)3M33UI - Support script for the 1st semestral task\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.datasets import load_files\nfrom sklearn.metrics import confusion_matrix, make_scorer\n\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.model_selection import learning_curve\nfrom sklearn.model_selection import ShuffleSplit\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\n\nfrom sklearn.naive_bayes import BernoulliNB\nfrom sklearn.naive_bayes import MultinomialNB\n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.dummy import DummyClassifier\n\nfrom sklearn.linear_model import PassiveAggressiveClassifier\nfrom sklearn.linear_model import SGDClassifier\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.linear_model import LogisticRegression\n\nTR_DATA = '/Users/yigit/Desktop/AI/AI project spam filter/spam-data/spam-data-1'\nTST_DATA = '/Users/yigit/Desktop/AI/AI project spam filter/spam-data/spam-data-2'\n\n\ndef our_accuracy(y, y_pred):\n \"\"\"Return a modified accuracy score with larger weight of false positives.\"\"\"\n cm = confusion_matrix(y, y_pred)\n if cm.shape != (2, 2):\n raise ValueError('The ground thruth values and the predictions may contain at most 2 values (classes).')\n return float(cm[0, 0] + cm[1, 1]) / (cm[0, 0] + cm[1, 1] + 10 * cm[0, 1] + cm[1, 0])\n\n\nour_scorer = make_scorer(our_accuracy, greater_is_better=True)\n\n\ndef train_filter(X, y, clf, grid=False):\n \"\"\"Return a trained spam filter.\"\"\"\n pipe = Pipeline(steps=[\n ('vectorizer', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('classifier', clf)])\n\n # AdaBoost has better results without frequencies\n if clf is AdaBoostClassifier:\n pipe = Pipeline(steps=[\n ('vectorizer', CountVectorizer()),\n ('classifier', clf)])\n\n if grid:\n params = {}\n if pipe.get_params().has_key('classifier__alpha'):\n alpha_range = np.linspace(0.001, 0.04, 30)\n params['classifier__alpha'] = alpha_range\n\n if pipe.get_params().has_key('classifier__fit_prior'):\n params['classifier__fit_prior'] = (True, False)\n\n if pipe.get_params().has_key('classifier__n_estimators'):\n params['classifier__n_estimators'] = range(100, 250, 20)\n\n if pipe.get_params().has_key('classifier__max_depth'):\n params['classifier__max_depth'] = range(5, 20)\n\n if pipe.get_params().has_key('classifier__gamma'):\n params['classifier__gamma'] = np.linspace(0, 1, 50)\n\n\n\n grid_fit_clf = GridSearchCV(\n pipe, params,\n cv=5, n_jobs=2, verbose=2\n )\n grid_fit_clf.fit(X, y)\n print(grid_fit_clf.best_params_)\n return grid_fit_clf\n else:\n pipe.fit(X, y)\n return pipe\n\n\ndef predict(filter, X):\n \"\"\"Produce predictions for X using given filter.\"\"\"\n return filter.predict(X)\n\n\n# Taken from:\n# http://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html#sphx-glr-auto-examples-model-selection-plot-learning-curve-py\ndef plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,\n n_jobs=2, train_sizes=np.linspace(.1, 1.0, 5)):\n \"\"\"\n Generate a simple plot of the test and training learning curve.\n\n Parameters\n ----------\n estimator : object type that implements the \"fit\" and \"predict\" methods\n An object of that type which is cloned for each validation.\n\n title : string\n Title for the chart.\n\n X : array-like, shape (n_samples, n_features)\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y : array-like, shape (n_samples) or (n_samples, n_features), optional\n Target relative to X for classification or regression;\n None for unsupervised learning.\n\n ylim : tuple, shape (ymin, ymax), optional\n Defines minimum and maximum yvalues plotted.\n\n cv : int, cross-validation generator or an iterable, optional\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n - None, to use the default 3-fold cross-validation,\n - integer, to specify the number of folds.\n - An object to be used as a cross-validation generator.\n - An iterable yielding train/test splits.\n\n For integer/None inputs, if ``y`` is binary or multiclass,\n :class:`StratifiedKFold` used. If the estimator is not a classifier\n or if ``y`` is neither binary nor multiclass, :class:`KFold` is used.\n\n Refer :ref:`User Guide ` for the various\n cross-validators that can be used here.\n\n n_jobs : integer, optional\n Number of jobs to run in parallel (default 1).\n \"\"\"\n plt.figure()\n plt.title(title)\n if ylim is not None:\n plt.ylim(*ylim)\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n plt.grid()\n\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color=\"r\")\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\",\n label=\"Training score\")\n plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\",\n label=\"Cross-validation score\")\n\n plt.legend(loc=\"best\")\n return plt\n\n\nroc_figure = plt.figure(1)\nplt.grid()\nplt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')\nplt.xlim([-0.01, 1.01])\nplt.ylim([-0.01, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic')\nplt.xlabel('Training set size')\nplt.ylabel('Training score')\nplt.title('Receiver operating characteristic')\n\n# Demonstration how the filter will be used.\nif __name__ == '__main__':\n\n # Load training data\n print('Loading training data ...')\n data_tr = load_files(TR_DATA, encoding='utf-8')\n X_tr = data_tr.data\n y_tr = data_tr.target\n\n # Load testing data\n print('Loading testing data ...')\n data_tst = load_files(TST_DATA, encoding='utf-8')\n X_tst = data_tst.data\n y_tst = data_tst.target\n\n print('size of train:', len(X_tr), 'size of test:', len(X_tst))\n\n clfs = {\n \"BernoulliNB\": BernoulliNB(0.04, fit_prior=False),\n \"MultinomialNB\": MultinomialNB(0.1, fit_prior=False),\n \"SVM - linear\": SVC(C=1,kernel='linear', probability=True),\n \"AdaBoostClassifier\": AdaBoostClassifier(random_state=0, n_estimators=9),\n \"Logistic Regression\":LogisticRegression(solver='liblinear'),\n\n \"Dummy\": DummyClassifier()\n }\n\n train_sizes = {}\n train_scores = {}\n valid_scores = {}\n\n for name_clf, clf in clfs.items():\n # Train the filter\n print('-------------------')\n print('Training filter {}'.format(name_clf))\n filter = train_filter(X_tr, y_tr, clf, grid=False)\n\n # Compute predictions for training data and report our accuracy\n print('Classifying training data ...')\n y_tr_pred = predict(filter, X_tr)\n print('Modified accuracy on training data:')\n print(our_accuracy(y_tr, y_tr_pred))\n\n # Compute predictions for testing data and report our accuracy\n print('Classifying testing data ...')\n y_tst_pred = predict(filter, X_tst)\n print('Modified accuracy on testing data:')\n print(our_accuracy(y_tst, y_tst_pred))\n\n y_score = filter.predict_proba(X_tst)\n\n fpr, tpr, _ = roc_curve(y_tst, y_tst_pred)\n #fpr, tpr, _ = roc_curve(y_tst, y_score[:, 1])\n roc_auc = auc(fpr, tpr)\n\n plt.figure(roc_figure.number)\n plt.plot(fpr, tpr,lw=2, label='{}, ROC area = {})'.format(name_clf, roc_auc))\n plt.legend(loc=\"lower right\")\n\n cv = ShuffleSplit(n_splits=10, test_size=0.2, random_state=0)\n plot_learning_curve(filter, name_clf, X_tr, y_tr, cv=cv)\n #\n plt.show()\n\n\n\n\n\n","sub_path":"SpamFilter/SpamFilter2.py","file_name":"SpamFilter2.py","file_ext":"py","file_size_in_byte":8657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"567122353","text":"from flask import Flask, render_template, request\nfrom kafka import KafkaProducer\nfrom kafka.admin import KafkaAdminClient, NewTopic\nfrom kafka.errors import KafkaError\n\napp = Flask(__name__)\n\nTOPIC_NAME = \"messages\"\nKAFKA_PORT = 29092\nKAFKA_ADDRESS = \"kafka-kafka-1\" #\"127.0.0.1\"\n\n# adminClient = KafkaAdminClient(\n# bootstrap_servers=[f\"{KAFKA_ADDRESS}:{KAFKA_PORT}\"],\n# client_id=\"admin_client\",\n# )\n\n# topics = []\n# topics.append(NewTopic(TOPIC_NAME, num_partitions=1, replication_factor=1))\n# adminClient.create_topics(new_topics=topics, validate_only=False)\n\nproducer = KafkaProducer(\n bootstrap_servers=[f\"{KAFKA_ADDRESS}:{KAFKA_PORT}\"]\n)\n\n@app.route(\"/\")\ndef main_page():\n return render_template('main.html')\n\n@app.route(\"/message\", methods=[\"GET\", \"POST\"])\ndef receive_message():\n if request.method == \"POST\":\n print(\"Request content: \" + request.form[\"message\"], flush=True)\n # put msg into topic\n future = producer.send(TOPIC_NAME, bytes(request.form['message'], 'utf-8'))\n return main_page()\n else:\n print(\"GET request received\", flush=True)\n return main_page()","sub_path":"testing/server/server_main.py","file_name":"server_main.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"134326526","text":"import os\nimport subprocess\nimport six\nimport shlex\nimport shutil\n\nfrom nmtwizard.framework import Framework\nfrom nmtwizard.logger import get_logger\n\nlogger = get_logger(__name__)\n\nclass NematusFramework(Framework):\n\n def __init__(self):\n super(NematusFramework, self).__init__()\n self._nematus_dir = os.getenv('NEMATUS_DIR', '/root/nematus')\n\n def train(self,\n config,\n src_file,\n tgt_file,\n model_path=None,\n gpuid=0):\n options = _getTrainingOptions(config, gpuid=gpuid)\n options[\"datasets\"] = src_file + \" \" + tgt_file\n\n src_vocab_file = src_file\n tgt_vocab_file = tgt_file\n if (\"src_vocab\" in options and\n \"tgt_vocab\" in options and\n os.path.isfile(options[\"src_vocab\"]) and\n os.path.isfile(options[\"tgt_vocab\"])):\n src_vocab_file = self._data_dir+\"/src.vocab.txt\"\n tgt_vocab_file = self._data_dir+\"/tgt.vocab.txt\"\n shutil.copy(options[\"src_vocab\"], src_vocab_file)\n shutil.copy(options[\"tgt_vocab\"], tgt_vocab_file)\n\n if \"src_vocab\" in options:\n del(options[\"src_vocab\"])\n if \"tgt_vocab\" in options:\n del(options[\"tgt_vocab\"])\n\n # generate dictionary\n self._run_command(None, [\"python\", \"data/build_dictionary.py\", src_vocab_file])\n self._run_command(None, [\"python\", \"data/build_dictionary.py\", tgt_vocab_file])\n options[\"dictionaries\"] = \" \".join([src_vocab_file + \".json\", tgt_vocab_file + \".json\"])\n\n if model_path is not None:\n options[\"reload\"] == \"true\"\n options[\"model\"] = model_path\n else:\n options[\"model\"] = self._output_dir\n options[\"model\"] += \"/model.npz\"\n\n env, options = _buildCommandLineOptions(options)\n\n self._run_command(env, [\"python\", \"nematus/nmt.py\"] + options)\n\n models = {}\n models[\"model.npz\"] = self._output_dir + \"model.npz\"\n models[\"model.npz.gradinfo.npz\"] = self._output_dir + \"model.npz.gradinfo.npz\"\n models[\"model.npz.json\"] = self._output_dir + \"model.npz.json\"\n models[\"model.npz.progress.json\"] = self._output_dir + \"model.npz.progress.json\"\n\n return models\n\n def trans(self, config, model_path, input, output, gpuid=0):\n model_file = os.path.join(model_path, 'model.npz')\n options = _getTranslationOptions(config, model_file, gpuid=gpuid)\n options['input'] = input\n options['output'] = output\n env, options = _buildCommandLineOptions(options)\n self._run_command(env, [\"python\", \"nematus/translate.py\"] + options)\n\n def _run_command(self, env, cmd):\n run_env = os.environ.copy()\n if env is not None:\n for k, v in six.iteritems(env):\n logger.debug(\"ENV %s\", k + \"=\" + str(v))\n run_env[k] = str(v)\n\n logger.debug(\"RUN %s\", \" \".join(cmd))\n subprocess.call(shlex.split(\" \".join(cmd)), cwd=self._nematus_dir, env=run_env)\n\n\ndef _getTheanoOptions(config, options=None, gpuid=0):\n assert options is None\n options = {}\n options_theano = {}\n\n if 'options' in config and isinstance(config['options'], dict):\n opt = config['options']\n # Theano options first\n if 'theano' in opt and isinstance(opt['theano'], dict):\n options_theano.update(opt['theano'])\n\n theano_value = \"\"\n for k, v in six.iteritems(options_theano):\n if k == \"device\":\n if gpuid == 0:\n theano_value += k + \"=\" + \"cpu\" + \",\"\n else:\n theano_value += k + \"=\" + \"gpu\" + \",\"\n elif k == \"default\":\n theano_value += v\n else:\n theano_value += k + \"=\" + v + \",\"\n theano_value = theano_value[:-1]\n\n options['theano'] = theano_value\n options['gpuid'] = gpuid\n return options\n\ndef _getTrainingOptions(config, options=None, gpuid=0):\n options = _getTheanoOptions(config, options=options, gpuid=gpuid)\n if 'options' in config and isinstance(config['options'], dict):\n opt = config['options']\n # Maybe overridden by training specific options\n if 'train' in opt and isinstance(opt['train'], dict):\n options.update(opt['train'])\n if not 'max_epochs' in options:\n options['max_epochs'] = 1\n return options\n\ndef _getTranslationOptions(config, model_t7, options=None, gpuid=0):\n options = _getTheanoOptions(config, options=options, gpuid=gpuid)\n if 'options' in config and isinstance(config['options'], dict):\n opt = config['options']\n # Maybe overridden by translation specific options\n if 'trans' in config and isinstance(config['trans'], dict):\n options.update(opt['trans'])\n # Misc \"hard-coded\" options\n options['models'] = model_t7\n return options\n\ndef _buildCommandLineOptions(options):\n env = {}\n opts = []\n for k, v in six.iteritems(options):\n if k == \"theano\":\n env[\"THEANO_FLAGS\"] = v\n elif k == \"gpuid\":\n if v != 0:\n # to be consistent with LUA GPUID\n v -= 1\n env[\"CUDA_VISIBLE_DEVICES\"] = v\n elif k is not None:\n if v != \"false\":\n opts.append('--%s' % k)\n if v != \"true\":\n opts.append(str(v))\n return env, opts\n\n\nif __name__ == \"__main__\":\n NematusFramework().run()\n","sub_path":"frameworks/nematus/entrypoint.py","file_name":"entrypoint.py","file_ext":"py","file_size_in_byte":5463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"132671049","text":"import tkinter as tk\nimport camera as cam\n\n\nroot = tk.Tk()\nframe = tk.Frame(root)\nframe.pack()\n\nvalue = tk.StringVar()\nvalue.set(\"Numbers of reps\")\nentree = tk.Entry(frame, text=\"\", width=30)\nentree.focus_set()\nentree.pack()\n\n\ndef onClickTraining():\n if entree.get() == \"\" :\n return\n cam.openCamera(repetition = entree.get())\n root.destroy()\n\ndef onClickExit():\n root.destroy()\n\nbutton = tk.Button(frame, text=\"START TRAINING\", fg=\"black\", command=onClickTraining)\nbutton.pack(side=tk.LEFT)\n\nbutton = tk.Button(frame, text=\"EXIT TRAINING\", fg=\"black\", command=onClickExit)\nbutton.pack(side=tk.RIGHT)\nroot.mainloop()","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"196748336","text":"# Monte Carlo estimation\nfrom random import randint\n\n\ndef pi():\n \"\"\"\n input : Takes the no of digit after decimal place.An integer.\n return : The estimated value of pi\n \"\"\"\n try:\n precision = int(input('Enter the number of decimal places : '))\n except ValueError:\n print(\"The enter digit don't seems to be integer.\")\n return 'The operation has been terminated'\n else:\n return f'The estimation value of pi by Monte Carlo method is : {_avg_val():.{precision}f}'\n\n\ndef _estimating_pi(loop):\n \"\"\"\n :param loop: Total no. of points\n :return: The value of pi for one instance\n \"\"\"\n\n radius = randint(500, 1000)\n total_point_inside_circle = 0\n # probability of point inside the circle equals pi/4 == point_inside_circle/total pint\n for i in range(loop):\n x = randint(-radius, radius)\n y = randint(-radius, radius)\n is_point_inside_circle = (x**2)+(y**2) <= radius**2\n if is_point_inside_circle:\n total_point_inside_circle += 1\n\n return 4 * (total_point_inside_circle/loop)\n\n\ndef _iterating(no_of_iteration):\n for i in range(no_of_iteration):\n yield _estimating_pi(randint(500, 10000))\n\n\ndef _avg_val():\n no_of_iteration = randint(10, 100)\n total_sum = sum(_iterating(no_of_iteration))\n return total_sum / no_of_iteration\n\n\nprint(pi())\n","sub_path":"Project Code/PI to the Nth Digit.py","file_name":"PI to the Nth Digit.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"108051302","text":"import types\n\n\nclass SessionCreator(object):\n \"\"\"Creator for session\"\"\"\n\n def __init__(self, classobj):\n \"\"\"Classobj for session\"\"\"\n self.classobj = classobj\n \"\"\"Classobj for proxy\"\"\"\n self.proxy = None\n \"\"\"Dict that contains keys and funcs or values, used like a key dictionary when creates session object\"\"\"\n self.kwargs = None\n\n def create_session(self):\n \"\"\"Creates session object\n :rtype: Session\n :raises: Exception\n \"\"\"\n\n kwargs = {}\n for key in self.kwargs:\n if callable(self.kwargs[key]):\n kwargs[key] = self.kwargs[key]()\n else:\n kwargs[key] = self.kwargs[key]\n\n if self.classobj and isinstance(self.classobj, types.ObjectType):\n if self.proxy and isinstance(self.proxy, types.ObjectType):\n return self.proxy(self.classobj(**kwargs))\n else:\n return self.classobj(**kwargs)\n else:\n raise Exception('SessionCreator', 'Incorrect classobj for session \\'{0}\\''.format(self.classobj))\n","sub_path":"cloudshell/cli/session/session_creator.py","file_name":"session_creator.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"560951405","text":"\"\"\".. Line to protect from pydocstyle D205, D400.\n\nBedgraph conversion\n-------------------\n\nConvert from BED6 to bedGraph format.\n\n\"\"\"\nimport logging\n\nimport pybedtools\n\nimport iCount\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef bed2bedgraph(bed, bedgraph, name='User Track', description='User Supplied Track'):\n \"\"\"\n Convert from BED6 to bedGraph format.\n\n For further explanation of ``name`` and ``description`` parameters\n (and also others, that are not yet supported) see:\n https://genome.ucsc.edu/goldenPath/help/customTrack.html#TRACK\n\n Parameters\n ----------\n bed : str\n Input BED6 file.\n bedgraph : str\n Output bedGraph file.\n name : str\n Track label. Can consist of up to 15 characters.\n description : str\n Track description. Can consist of up to 60 characters.\n\n Returns\n -------\n None\n\n \"\"\"\n iCount.log_inputs(LOGGER, level=logging.INFO) # pylint: disable=protected-access\n LOGGER.info('Checking input parameters...')\n assert bed.endswith(('.bed', '.bed.gz'))\n\n header = [\n 'track',\n 'type=bedGraph',\n 'name=\"{}\"'.format(name[:15]),\n 'description=\"{}\"'.format(description[:60]),\n ]\n\n LOGGER.info('Converting %s to %s', bed, bedgraph)\n with open(bedgraph, 'wt') as outfile:\n outfile.write(' '.join(map(str, header)) + '\\n')\n for line in pybedtools.BedTool(bed):\n bg_line = [line.chrom, line.start, line.stop, '{}{}'.format(line.strand, line.score)]\n outfile.write('\\t'.join(map(str, bg_line)) + '\\n')\n LOGGER.info('Done.')\n","sub_path":"iCount/files/bedgraph.py","file_name":"bedgraph.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"359181523","text":"\"\"\"\nApplying HMR to Handtool videos.\n\nNote that HMR requires the bounding box of the person in the image. The best performance is obtained when max length of the person in the image is roughly 150px.\nRealtime-Pose [Cao et al 17] output is required to figure out the bbox and the right scale factor.\n\nSample usage:\n\npython demo_handtools.py --tool_name hammer --video_name hammer_0001 \\\n--frame_start 0 --frame_end 98 \\\n--video_dir /Users/zoli/Work/100_handtool_videos \\\n--save_dir /Users/zoli/Work/contact/baseline/hmr \\\n--vis True\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport h5py\nimport numpy as np\nimport cPickle as pk\nfrom absl import flags\nfrom os import makedirs, remove\nfrom os.path import join, exists, abspath, dirname, basename, isfile\n\nimport skimage.io as io\nimport tensorflow as tf\n\nfrom src.util import renderer as vis_util\nfrom src.util import image as img_util\nfrom src.util import openpose as op_util\nimport src.config\nfrom src.RunModel import RunModel\n\nflags.DEFINE_string('tool_name', 'hammer', 'tool name')\nflags.DEFINE_string('video_name', 'hammer_0001', 'video name')\nflags.DEFINE_integer('frame_start', '0', 'frame start')\nflags.DEFINE_integer('frame_end', '-1', 'frame end')\nflags.DEFINE_string('video_dir', '/Users/zoli/Work/100_handtool_videos', 'path to handtool videos')\nflags.DEFINE_string('save_dir', '/Users/zoli/Work/contact/baseline/hmr', 'output path')\nflags.DEFINE_boolean('vis', False, 'Turn on visualization.')\nflags.DEFINE_boolean('run_bbox_only', False, 'save bounding box and stop execution')\n\ndef visualize(img, proc_param, joints, verts, cam, save_path=None):\n \"\"\"\n Renders the result in original image coordinate frame.\n \"\"\"\n cam_for_render, vert_shifted, joints_orig, trans = vis_util.get_original(\n proc_param, verts, cam, joints, img_size=img.shape[:2])\n # Render results\n skel_img = vis_util.draw_skeleton(img, joints_orig)\n rend_img_overlay = renderer(\n vert_shifted, cam=cam_for_render, img=img, do_alpha=True)\n rend_img = renderer(\n vert_shifted, cam=cam_for_render, img_size=img.shape[:2])\n rend_img_vp1 = renderer.rotated(\n vert_shifted, 60, cam=cam_for_render, img_size=img.shape[:2])\n rend_img_vp2 = renderer.rotated(\n vert_shifted, -60, cam=cam_for_render, img_size=img.shape[:2])\n\n import matplotlib.pyplot as plt\n # plt.ion()\n plt.figure(1, figsize=(16,12))\n plt.clf()\n plt.subplot(221)\n plt.imshow(skel_img)\n plt.title('joint projection')\n plt.axis('off')\n plt.subplot(222)\n plt.imshow(rend_img_overlay)\n plt.title('3D Mesh overlay')\n plt.axis('off')\n plt.subplot(223)\n plt.imshow(rend_img)\n plt.title('3D mesh')\n plt.axis('off')\n plt.subplot(224)\n plt.imshow(rend_img_vp2)\n plt.title('diff vp')\n plt.axis('off')\n plt.draw()\n #plt.show()\n # import ipdb\n # ipdb.set_trace()\n if save_path is not None:\n plt.savefig(save_path)\n return cam_for_render, trans\n\ndef get_bbox_realtime_pose(j2d_pose, vis_thr=0.2):\n # use one bbox for all frames, using Openpose outputs\n # j2d_pose: nf x nj x 3\n nf = j2d_pose.shape[0]\n max_person_height = 0.\n center = np.zeros(2)\n scale = 1.\n for i in range(nf):\n kp = j2d_pose[i]\n vis = kp[:, 2] > vis_thr\n vis_kp = kp[vis, :2]\n min_pt = np.min(vis_kp, axis=0)\n max_pt = np.max(vis_kp, axis=0)\n person_height = np.linalg.norm(max_pt - min_pt)\n if person_height > max_person_height:\n center = (min_pt + max_pt) / 2.\n scale = 150. / person_height\n max_person_height = person_height\n return scale, center\n\n'''def get_bbox_realtime_pose(j2d_pose, vis_thr=0.2):\n # use one bbox for all frames, using Openpose outputs\n # j2d_pose: nf x nj x 3\n nf = j2d_pose.shape[0]\n min_pt = 66666*np.ones(2)\n max_pt = -66666*np.ones(2)\n for i in range(nf):\n kp = j2d_pose[i]\n vis = kp[:, 2] > vis_thr\n vis_kp = kp[vis, :2]\n min_pt_fi = np.min(vis_kp, axis=0)\n max_pt_fi = np.max(vis_kp, axis=0)\n min_pt = np.min(np.vstack((min_pt_fi, min_pt)), axis=0)\n max_pt = np.max(np.vstack((max_pt_fi, max_pt)), axis=0)\n person_height = np.linalg.norm(max_pt - min_pt)\n if person_height == 0:\n print('bad!')\n import ipdb\n ipdb.set_trace()\n center = (min_pt + max_pt) / 2.\n scale = 150. / person_height\n return scale, center'''\n\n'''def get_bbox_realtime_pose(j2d_pose, vis_thr=0.2):\n # use different bbox for different frames\n kp = j2d_pose\n vis = kp[:, 2] > vis_thr\n vis_kp = kp[vis, :2]\n min_pt = np.min(vis_kp, axis=0)\n max_pt = np.max(vis_kp, axis=0)\n person_height = np.linalg.norm(max_pt - min_pt)\n if person_height == 0:\n print('bad!')\n import ipdb\n ipdb.set_trace()\n center = (min_pt + max_pt) / 2.\n scale = 150. / person_height\n return scale, center'''\n\ndef preprocess_image(img_path, scale, center, crop_path=None):\n img = io.imread(img_path)\n # scale and crop\n crop, proc_param = img_util.scale_and_crop(img, scale, center,\n config.img_size)\n # saving image patch containing target person\n if crop_path is not None:\n io.imsave(crop_path, crop)\n # Normalize image to [-1, 1]\n crop = 2 * ((crop / 255.) - 0.5)\n return crop, proc_param, img\n\n'''def preprocess_image(img_path, j2d_pose, crop_path=None):\n # use different bbox for different frames\n img = io.imread(img_path)\n # get bounding box from Openpose output\n scale, center = get_bbox_realtime_pose(j2d_pose)\n # scale and crop\n crop, proc_param = img_util.scale_and_crop(img, scale, center,\n config.img_size)\n # saving image patch containing target person\n if crop_path is not None:\n io.imsave(crop_path, crop)\n # Normalize image to [-1, 1]\n crop = 2 * ((crop / 255.) - 0.5)\n return scale, center, crop, proc_param, img'''\n\nif __name__ == '__main__':\n config = flags.FLAGS\n config(sys.argv)\n # Using pre-trained model, change this to use your own.\n config.load_path = src.config.PRETRAINED_MODEL\n config.batch_size = 1\n tool_name = config.tool_name\n video_name = config.video_name\n frame_start = config.frame_start\n frame_end = config.frame_end\n video_dir = config.video_dir\n save_dir = config.save_dir\n vis = config.vis\n run_bbox_only = config.run_bbox_only\n print(\"****** inputs ******\")\n print(\"tool_name: {}\".format(tool_name))\n print(\"video_name: {}\".format(video_name))\n print(\"frame_start: {0}\".format(frame_start))\n print(\"frame_end: {}\".format(frame_end))\n print(\"video_dir: {}\".format(video_dir))\n print(\"save_dir: {}\".format(save_dir))\n print(\"vis: {}\".format(vis))\n print(\"run_bbox_only: {}\".format(run_bbox_only))\n print(\"****** inputs:end ******\")\n\n # SMPL renderer\n renderer = vis_util.SMPLRenderer(face_path=config.smpl_face_path)\n\n # load video info\n video_info_path = join(video_dir, tool_name, 'videos_info.pkl')\n with open(video_info_path, 'r') as finfo:\n info_data = pk.load(finfo)\n nframes = info_data[video_name]['nframes']\n gender = info_data[video_name]['gender']\n fps = info_data[video_name]['fps']\n\n frame_end = nframes if frame_end==-1 else frame_end\n nf = frame_end-frame_start\n\n # load realtime pose results\n j2d_path = join(video_dir, tool_name, 'realtime_pose', 'realtime_pose.pkl')\n with open(j2d_path, 'r') as fpose:\n pose_data = pk.load(fpose)\n j2d_pose = pose_data[video_name][frame_start:frame_end]\n\n # load pretrained model\n sess = tf.Session()\n model = RunModel(config, sess=sess)\n\n pred_thetas = np.zeros((nf, 85))\n pred_cams = np.zeros((nf, 3))\n pred_trans = np.zeros((nf, 3))\n pred_poses = np.zeros((nf, 72))\n pred_shapes = np.zeros((nf, 10))\n bbox_fids = np.zeros(nf).astype(int)\n bbox_scales = np.zeros(nf)\n bbox_centers = np.zeros((nf, 2))\n\n if not exists(join(save_dir, video_name)):\n makedirs(join(save_dir, video_name))\n if not exists(join(save_dir, video_name, 'bbox_vis')):\n makedirs(join(save_dir, video_name, 'bbox_vis'))\n if not exists(join(save_dir, video_name, 'vis')):\n makedirs(join(save_dir, video_name, 'vis'))\n\n # use same bbox for all frames, using Openpose outputs\n scale, center = get_bbox_realtime_pose(j2d_pose)\n\n for i in range(nf):\n fid = frame_start + i\n print(\"i = {0} (fid {1})\".format(i, fid))\n img_path = join(video_dir, tool_name, 'frames', video_name, \"%06d.jpg\" % fid)\n crop_path = join(save_dir, video_name, 'bbox_vis', \"%06d.jpg\" % fid)\n ## use different bbox for different frames\n #scale, center, input_img, proc_param, img = preprocess_image(\n # img_path, j2d_pose[i], crop_path)\n # use same bbox for all frames\n input_img, proc_param, img = preprocess_image(img_path, scale, center, crop_path)\n\n bbox_fids[i] = fid\n bbox_scales[i] = scale\n bbox_centers[i] = center.copy()\n\n if not run_bbox_only:\n # Add batch dimension: 1 x D x D x 3\n input_img = np.expand_dims(input_img, 0)\n\n joints, verts, cams, joints3d, theta = model.predict(\n input_img, get_theta=True)\n\n if vis:\n save_path = join(save_dir, video_name, \"vis\", \"%06d.jpg\" % fid)\n cam_for_render, trans = visualize(img, proc_param, joints[0], verts[0], cams[0], save_path)\n\n theta = theta.reshape(-1)\n pred_thetas[i] = theta.copy()\n pred_cams[i] = cam_for_render.copy() # note that theta[:3] is the cam for cropped image 224 x 224\n pred_trans[i] = trans.copy()\n pred_poses[i] = theta[3:75].copy()\n pred_shapes[i] = theta[75:].copy()\n\n if run_bbox_only:\n # saving bbox in hdf5 format\n h5_path = join(save_dir, video_name, 'bbox_2d.h5')\n if exists(h5_path):\n remove(h5_path)\n print(\"old file removed: {}\".format(h5_path))\n fh5 = h5py.File(h5_path, \"w\")\n fh5.create_dataset(\"fids\", dtype='i', data=bbox_fids)\n fh5.create_dataset(\"scales\", dtype='f', data=bbox_scales)\n fh5.create_dataset(\"centers\", dtype='f', data=bbox_centers)\n else:\n pkl_path = join(save_dir, video_name, 'pose_3d.pkl')\n dict_res = {'thetas': pred_thetas,\n 'cams': pred_cams,\n 'trans': pred_trans,\n 'poses': pred_poses,\n 'shapes': pred_shapes,\n 'frame_start': frame_start,\n 'frame_end': frame_end}\n with open(pkl_path, 'w') as fsave:\n pk.dump(dict_res, fsave)\n print('results saved to {}'.format(pkl_path))\n\n print('done.')\n","sub_path":"demo_handtools.py","file_name":"demo_handtools.py","file_ext":"py","file_size_in_byte":10984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"139744368","text":"import numpy as np\nimport pandas as pd\nfrom pandas import Series\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport tensorflow as tf\n\nplt.style.use('seaborn')\nsns.set(font_scale=2.5)\nimport plotly.offline as py\nimport plotly.graph_objs as go\nimport plotly.tools as tls\n\n#ignore warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n\ndf_train = pd.read_csv('train.csv')\ndf_test = pd.read_csv('test.csv')\ndf_train['FamilySize'] = df_train['SibSp'] + df_train['Parch'] + 1 # 자신을 포함해야하니 1을 더합니다\ndf_test['FamilySize'] = df_test['SibSp'] + df_test['Parch'] + 1 # 자신을 포함해야하니 1을 더합니다\n\ndf_test.loc[df_test.Fare.isnull(), 'Fare'] = df_test['Fare'].mean()\n\ndf_train['Fare'] = df_train['Fare'].map(lambda i: np.log(i) if i > 0 else 0)\ndf_test['Fare'] = df_test['Fare'].map(lambda i: np.log(i) if i > 0 else 0)\n\ndf_train['Initial'] = 0\nfor i in df_train:\n df_train['Initial'] = df_train.Name.str.extract('([A-Za-z]+)\\.') # lets extract the Salutations\n\ndf_test['Initial'] = 0\nfor i in df_test:\n df_test['Initial'] = df_test.Name.str.extract('([A-Za-z]+)\\.') # lets extract the Salutations\n\npd.crosstab(df_train['Initial'], df_train['Sex']).T.style.background_gradient(cmap='summer_r') #Checking the Initials with the Sex\n\ndf_train['Initial'].replace(['Mlle','Mme','Ms','Dr','Major','Lady','Countess','Jonkheer','Col','Rev','Capt','Sir','Don', 'Dona'],\n ['Miss','Miss','Miss','Mr','Mr','Mrs','Mrs','Other','Other','Other','Mr','Mr','Mr', 'Mr'],inplace=True)\n\ndf_test['Initial'].replace(['Mlle','Mme','Ms','Dr','Major','Lady','Countess','Jonkheer','Col','Rev','Capt','Sir','Don', 'Dona'],\n ['Miss','Miss','Miss','Mr','Mr','Mrs','Mrs','Other','Other','Other','Mr','Mr','Mr', 'Mr'],inplace=True)\ndf_train.groupby('Initial').mean()\n\ndf_train.groupby('Initial')['Survived'].mean().plot.bar()\n\ndf_all = pd.concat([df_train, df_test])\ndf_all.groupby('Initial').mean()\n\ndf_train.loc[(df_train.Age.isnull())&(df_train.Initial=='Mr'),'Age']=33\ndf_train.loc[(df_train.Age.isnull())&(df_train.Initial=='Mrs'),'Age']=37\ndf_train.loc[(df_train.Age.isnull())&(df_train.Initial=='Master'),'Age']=5\ndf_train.loc[(df_train.Age.isnull())&(df_train.Initial=='Miss'),'Age']=22\ndf_train.loc[(df_train.Age.isnull())&(df_train.Initial=='Other'),'Age']=45\n\ndf_test.loc[(df_test.Age.isnull())&(df_test.Initial=='Mr'),'Age']=33\ndf_test.loc[(df_test.Age.isnull())&(df_test.Initial=='Mrs'),'Age']=37\ndf_test.loc[(df_test.Age.isnull())&(df_test.Initial=='Master'),'Age']=5\ndf_test.loc[(df_test.Age.isnull())&(df_test.Initial=='Miss'),'Age']=22\ndf_test.loc[(df_test.Age.isnull())&(df_test.Initial=='Other'),'Age']=45\n\ndf_train['Embarked'].fillna('S', inplace=True)\n\n\ndef category_age(x):\n if x < 10:\n return 0\n elif x < 20:\n return 1\n elif x < 30:\n return 2\n elif x < 40:\n return 3\n elif x < 50:\n return 4\n elif x < 60:\n return 5\n elif x < 70:\n return 6\n else:\n return 7\n\n\ndf_train['Age_cat_2'] = df_train['Age'].apply(category_age)\n\ndf_train.drop(['Age', 'Age_cat_2'], axis=1, inplace=True)\ndf_test.drop(['Age'], axis=1, inplace=True)\n\ndf_train['Initial'] = df_train['Initial'].map({'Master': 0, 'Miss': 1, 'Mr': 2, 'Mrs': 3, 'Other': 4})\ndf_test['Initial'] = df_test['Initial'].map({'Master': 0, 'Miss': 1, 'Mr': 2, 'Mrs': 3, 'Other': 4})\n\ndf_train['Embarked'].unique()\n\ndf_train['Embarked'].value_counts()\n\ndf_train['Embarked'] = df_train['Embarked'].map({'C': 0, 'Q': 1, 'S': 2})\ndf_test['Embarked'] = df_test['Embarked'].map({'C': 0, 'Q': 1, 'S': 2})\n\ndf_train['Embarked'].isnull().any()\n\ndf_train['Sex'] = df_train['Sex'].map({'female': 0, 'male': 1})\ndf_test['Sex'] = df_test['Sex'].map({'female': 0, 'male': 1})\n\nheatmap_data = df_train[['Survived', 'Pclass', 'Sex', 'Fare', 'Embarked', 'FamilySize', 'Initial']]\n\ncolormap = plt.cm.RdBu\nplt.figure(figsize=(14, 12))\nplt.title('Pearson Correlation of Features', y=1.05, size=15)\nsns.heatmap(heatmap_data.astype(float).corr(), linewidths=0.1, vmax=1.0,\n square=True, cmap=colormap, linecolor='white', annot=True, annot_kws={\"size\": 16})\n\ndel heatmap_data\n\ndf_train = pd.get_dummies(df_train, columns=['Initial'], prefix='Initial')\ndf_test = pd.get_dummies(df_test, columns=['Initial'], prefix='Initial')\ndf_train.head()\n\ndf_train = pd.get_dummies(df_train, columns=['Embarked'], prefix='Embarked')\ndf_test = pd.get_dummies(df_test, columns=['Embarked'], prefix='Embarked')\n\ndf_train.drop(['PassengerId', 'Name', 'SibSp', 'Parch', 'Ticket', 'Cabin'], axis=1, inplace=True)\ndf_test.drop(['PassengerId', 'Name', 'SibSp', 'Parch', 'Ticket', 'Cabin'], axis=1, inplace=True)\ndf_train.head()\n\nX_train = df_train.drop('Survived', axis=1).values\n\nfor i in range(len(X_train)):\n X_train[i] = X_train[i].tolist()\nX_train = X_train.tolist()\nprint(X_train)\n\nY_train = df_train['Survived'].values\nY_train = Y_train.tolist()\nprint(Y_train)\n\nX_test = df_test.values\nfor i in range(len(X_test)):\n X_test[i] = X_test[i].tolist()\nX_test = X_test.tolist()\nprint(X_test)\n\ntf.set_random_seed(777) # for reproducibility\nlearning_rate = 1.0\n\nX_train = np.array(X_train, dtype=np.float32)\nY_train = np.array(Y_train, dtype=np.float32)\nX_test = np.array(X_test, dtype=np.float32)\n\nX = tf.placeholder(tf.float32)\nY = tf.placeholder(tf.float32)\n\nW1 = tf.Variable(tf.random_normal([12, 12]), name='weight1')\nb1 = tf.Variable(tf.random_normal([12]), name='bias1')\nlayer1 = tf.sigmoid(tf.matmul(X, W1) + b1)\n\nW2 = tf.Variable(tf.random_normal([12, 1]), name='weight2')\nb2 = tf.Variable(tf.random_normal([1]), name='bias2')\nhypothesis = tf.sigmoid(tf.matmul(layer1, W2) + b2)\n\ncost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) *\n tf.log(1 - hypothesis))\n\ntrain = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)\n\npredicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)\naccuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))\n\nwith tf.Session() as sess:\n # Initialize TensorFlow variables\n sess.run(tf.global_variables_initializer())\n\n for step in range(10001):\n sess.run(train, feed_dict={X: X_train, Y: Y_train})\n if step % 100 == 0:\n print(step, sess.run(cost, feed_dict={\n X: X_train, Y: Y_train}), sess.run([W1, W2]))","sub_path":"Kaggle/Titanic/source/Titanic.py","file_name":"Titanic.py","file_ext":"py","file_size_in_byte":6354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"294824082","text":"#!/usr/bin/python3\n__author__ = 'kumaran'\n\n\nclass Solution:\n\n def __init__(self):\n self.integers = []\n\n\n def numBits(self, n):\n count = 0\n while n:\n n &= n-1\n count += 1\n return count\n\n def getIntegers(self, num, bits):\n output = []\n\n for i in range(bits):\n if num & (1 << i):\n output.append(self.integers[i])\n\n return output\n\n\n # @return a list of lists of integers\n def combine(self, n, k):\n output = []\n # n is num bits\n self.integers = [i for i in range(1,n+1)]\n # iterate throuh 1 to 2**n\n for i in range(1, (2**n)):\n # if number of bits set in i is k, (n_c_k)\n if self.numBits(i) == k:\n # get corresponding output\n output.append(self.getIntegers(i, n))\n\n return output\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.combine(4,3))\n\n\n\n\n\n\n\nif __name__ == '__main__':\n s = Solution()\n \n","sub_path":"Algos/Maths/Combination.py","file_name":"Combination.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"429423459","text":"\"\"\"\n`ipso_messages`\n====================================================\n\nIPSO Communicatations driver for generating payload data\nto publish sensor data to myDevices using Cayenne LPP\n\n* Author(s): virtualguy\n\"\"\"\nimport time, math\nfrom micropython import const\nimport struct\nimport json\n\nLPP_DIGITAL_INPUT = const(0) # 1 byte\nLPP_DIGITAL_OUTPUT = const(1) # 1 byte\nLPP_ANALOG_INPUT = const(2) # 2 bytes, 0.01 signed\nLPP_ANALOG_OUTPUT = const(3) # 2 bytes, 0.01 signed\nLPP_LUMINOSITY = const(101) # 2 bytes, 1 lux unsigned\nLPP_PRESENCE = const(102) # 1 byte, 1\nLPP_TEMPERATURE = const(103) # 2 bytes, 0.1°C signed\nLPP_RELATIVE_HUMIDITY = const(104) # 1 byte, 0.5% unsigned\nLPP_ACCELEROMETER = const(113) # 2 bytes per axis, 0.001G\nLPP_BAROMETRIC_PRESSURE = const(115) # 2 bytes 0.1 hPa Unsigned\nLPP_GYROMETER = const(134) # 2 bytes per axis, 0.01 °/s\nLPP_GPS = const(136) # 3 byte lon/lat 0.0001 °, 3 bytes alt 0.01m\n\nclass Messages:\n def build_short_status(battery, status_flags):\n \"\"\"Generate message 0x01 - Short Status\"\"\"\n for v in battery, status_flags:\n v = clamp(v, 0, 255)\n\n payload = struct.pack(\"BBhBBHBBhBBHBBBBBhhh\",\n 0x01, LPP_ANALOG_INPUT, battery,\n 0x02, LPP_BAROMETRIC_PRESSURE, pressure,\n 0x03, LPP_TEMPERATURE, temperature,\n 0x04, LPP_LUMINOSITY, light,\n 0x05, LPP_RELATIVE_HUMIDITY, humidity,\n 0x06, LPP_ACCELEROMETER, acceleration_x, acceleration_y, acceleration_z)\n\n return payload\n\ndef clamp(n, minn, maxn):\n \"\"\"Ensure n falls between range\"\"\"\n n = int(n)\n return max(min(maxn, n), minn)\n","sub_path":"device/ipso_messages.py","file_name":"ipso_messages.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"331668746","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 24 23:41:57 2020\n\n@author: qizhao\n\"\"\"\nfrom functools import wraps\n\n\ndef require_axis(func):\n \"\"\"check if object of function has axis and next_axis\n here, sel_axis is the dimension that we need to split in \n next time\n \"\"\"\n \n @wraps(func)\n def _wrapper(self, *args, **kwargs):\n if None in (self.axis, self.sel_axis):\n raise ValueError('%(func_name) requires the node %(node)s '\n 'to have an axis and a sel_axis function' %\n dict(func_name=func.__name__, node=repr(self)))\n return func(self, *args, **kwargs)\n \n return _wrapper\n\n\n\n\ndef check_dimensionality(point_list, dims=None):\n dims = dims or len(point_list[0])\n \n for point in point_list:\n if len(point) != dims:\n raise ValueError('Allpoints in point_list must have the '\n 'the same dimensionality')\n return dims\n\n\n\n\nclass Node(object):\n \"\"\"A node of k-d_tree\n \n A tree is represented by its root node, end every node represents \n its substree\n \"\"\"\n def __init__(self, data=None, left=None, right=None):\n \"\"\"\n \n\n Parameters\n ----------\n data : TYPE, optional\n DESCRIPTION. The default is None.\n left : TYPE, optional\n DESCRIPTION. The default is None.\n right : TYPE, optional\n DESCRIPTION. The default is None.\n\n \"\"\"\n self.data = data\n self.left = left\n self.right = right\n \n \n \n def __repr__(self):\n \"\"\"transform class into a str\n \"\"\"\n return '<%(cls)s, %(data)s>' % \\\n dict(cls=self.__class__.__name__, data=repr(self.data))\n \n \n def __nonezero__(self):\n \"\"\"check if data is not None \"\"\"\n return self.data is not None\n \n __bool__ = __nonezero__\n \n \n def __eq__(self, other):\n \"\"\"make sur two class are same tuple type\n \"\"\"\n \n if isinstance(other, tuple):\n return self.data == other\n else:\n return self.data == other.data\n \n \n def __hash__(self):\n return id(self)\n \n \n \n @property\n def children(self):\n \"\"\"returns an iterator for the non-empty child of the node\n Children are returned as a tuple of (node, position) where \n position is 0 for the left subnode and 1 for right subnode \n \n\n Returns\n -------\n iterator of a tuple (node, position).\n\n \"\"\"\n if self.left and self.left.data is not None:\n yield self.left, 0\n \n if self.right and self.right.data is not None:\n yield self.right, 1\n\n\n \n @property\n def is_leaf(self):\n \"\"\"Rtuen true if a node has na subnode \n \n >>> Node().is_leaf()\n True\n \n >>> Node(1, left=Node(2)).is_leaf()\n False\n \n \n Returns\n -------\n Bool\n \"\"\"\n return (not self.data) or \\\n (all(not bool(node) for node, position in self.children))\n\n \n def preorder(self):\n \"\"\"\n iterator for nodes: root, left, right\n\n Returns\n -------\n node.\n\n \"\"\"\n if not self:\n return \n \n # firstly iterat root \n yield self\n \n if self.left:\n for x in self.left.preorder:\n yield x\n \n if self.right:\n for x in self.right.preorder:\n yield x\n \n def inorder(self):\n \"\"\"iterator for nodes: left, root, right\n\n Returns\n -------\n Node.\n\n \"\"\"\n if not self:\n return \n\n if self.left:\n for x in self.left.preorder:\n yield x\n \n\n yield self\n\n\n if self.right:\n for x in self.right.preorder:\n yield x\n \n def postorder(self):\n \"\"\"iterator for nodes: left, right, root\n\n Returns\n -------\n Node.\n\n \"\"\"\n\n if not self:\n return \n\n if self.left:\n for x in self.left.preorder:\n yield x\n\n if self.right:\n for x in self.right.preorder:\n yield x\n \n yield self\n \n def set_child(self, index, child):\n \"\"\"set one of the node's children\n \n\n Parameters\n ----------\n index : int\n index 0 refers to the left, \n index 1 refers to right child.\n child : node class\n child node.\n\n \"\"\"\n if index == 0:\n self.left = child\n \n else:\n self.right = child\n \n def height(self):\n \"\"\"rturn the height of the subtree without considering \n empty leaf-node\n \"\"\"\n # check if empty leaf-node \n min_h = int(bool(self))\n \n return max([min_h] + [node.height() + 1 for node, position in self.children])\n\n\n def get_child_pos(self, child):\n \"\"\"return the position of given child node\n \n\n Parameters\n ----------\n child : Node class object\n child node.\n\n Returns\n -------\n the position.\n\n \"\"\"\n \n for node, position in self.children:\n if child == node:\n return position\n\n\n\nclass KDNode(Node):\n \"\"\" A Node that contains kd-tree specific data and methods \"\"\"\n \n def __init__(self, data=None, left=None, right=None, axis=None, \n next_axis=None, dims=None):\n \n \"\"\"create a new node for KD tree\n \n if the node will be used within a tree, the axis and next_axis \n should be applied. \n \n The next_axis(axis) is used used when creating subnodes \n of the current node. It receives the axis of the parent node and \n returns the axis of the child node.\n \n next_axis = (axis + 1) % dims\n \n \n \n \"\"\"\n super(KDNode, self).__init__(data, left, right)\n \n self.axis = axis\n self.next_axis = next_axis\n self.dims = dims\n \n \n @require_axis\n def add(self, point):\n \"\"\"Add points to the current node or iteratively descends to one \n of its children\n \n Users should call add() only to the topmost tree.\n \"\"\"\n cur_node = self\n \n while True:\n check_dimensionality([point], dims=cur_node.dims)\n \n # Adding has hit an empty leaf-node, add here\n if cur_node.data is None:\n cur_node.data = point\n return cur_node\n \n \n # split on self.axis\n if point[cur_node.axis] < cur_node.data[cur_node.axis]:\n # make sur current left node is not null\n # else create a newnode as current left node \n if cur_node.left is None:\n cur_node.left = cur_node.create_subnode(point)\n return cur_node.left\n else:\n # if not null, set current node is left node\n cur_node = cur_node.left\n else:\n \n if cur_node.right is None:\n cur_node.right = cur_node.create_subnode(point)\n return cur_node.right\n else:\n # if not null, set current node is left node\n cur_node = cur_node.right\n \n \n \n \n \n @require_axis\n def create_subnode(self, data):\n \"\"\"create a subnode for the current node\"\"\"\n \n return self.__class__(data, \n axis=self.next_axis(self.axis), \n next_axis=self.axis, \n dims=self.dims)\n \n\n\n\n def should_remove(self, point, node):\n \"\"\"ckeck if self points matches, return False if match, it shouldn't \n be removed. if not is True, we nned to romve self \n \"\"\"\n \n if self.data == point:\n return False\n \n return (node is None) or (node is self)\n \n \n @require_axis\n def remove(self, point, node=None):\n \"\"\"remove the node with the given point from the tree\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":"neighbors/_kd_tree.py","file_name":"_kd_tree.py","file_ext":"py","file_size_in_byte":8633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"466987296","text":"from collections import namedtuple\nfrom collections import OrderedDict\nfrom enum import Enum\nfrom matplotlib import pyplot as plt\nimport os\nimport csv\nimport numpy as np\nimport copy\nimport random\nimport time\n\n# class Value:\n# \"\"\"\n# Creates a Value that updates all instances as it changes.\n#\n# Examples\n# --------\n# >>> v1 = Value(1)\n# >>> v2 = Value(2)\n#\n# >>> d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}\n# >>> d['a'].v += 1\n#\n# >>> d['b'].v == 2 # True\n#\n# References\n# ----------\n# .. [#] dictionary with multiple keys to one value. StackOverflow.\n# http://stackoverflow.com/questions/10123853/how-do-i-make-a-dictionary-with-multiple-keys-to-one-value\n#\n#\n# \"\"\"\n# def __init__(self, v=None):\n# self.v = v\n\nclass slicee:\n \"\"\"\n Creates an array of start and stop value pairs (with optional step\n values)\n\n Examples\n --------\n >>> slicee()[0, 1:2, ::5, ...]\n # '(0, slice(1, 2, None), slice(None, None, 5), Ellipsis)'\n\n References\n ----------\n .. [#] Python's slice notation. StackOverflow.\n http://stackoverflow.com/questions/509211/explain-pythons-slice-notation\n\n\n \"\"\"\n def __getitem__(self, item):\n return item\n\n# set model parameters\nn_cells = 100 # must be square number\nn_bots = 10\nmax_food_per_cell = 40\nindividual_food_cell_value = \"max_food_per_cell\" # \"random\", \"max_food_per_cell\"\nset_number_agents_on_food = True\nn_agents_on_food = 2\nuse_trophallaxis = True # use trophallaxis mechanism\nfood_map_style = \"new_map\" # \"existing_map\", \"new_map\"\nbot_map_style = \"random_map\" # \"existing_map\", \"new_map\", \"random_map\" # \"random_map\"\n\n\nif food_map_style == \"new_map\": # set dimensions of single food patch:\n y_range = slicee()[1:2, 4:6]\n x_range = slicee()[1:2, 4:6]\n\nif food_map_style == \"existing_map\": # input names of previous data\n bot_map_dir = \"Data.07-02-2016_00_25_05_JST\"\n food_map_dir = \"Data.07-02-2016_00_25_05_JST\"\n bot_map_name = \"Data.07-02-2016_00_25_05_JST\"\n food_map_name = \"Data.07-02-2016_00_25_05_JST\"\n\nplot_output = True # plots and saves output data\nshow_plot = False # displays data during simulation\n\nEremoved_perFeed__Estored_init = 12\nEth_store__Eth_troph = 0\n\nBOT_DEFAULTS = OrderedDict([\n (\"base_metabolism\", 0),\n (\"Eremoved_perFeed\", Eremoved_perFeed__Estored_init),\n (\"Estored_init\", Eremoved_perFeed__Estored_init),\n (\"Ecost_perStep\", 1),\n (\"Eth_explore\", 12),\n (\"Eth_store\", Eth_store__Eth_troph),\n (\"Eth_troph\", Eth_store__Eth_troph),\n (\"Eth_battFull\", 0),\n (\"Estored_max\", 30),\n (\"senseRange\", 1),\n (\"troph\", use_trophallaxis),\n (\"trophMode\", \"cautious\"), # \"equalise\", \"cautious\", \"selfless\"\n (\"eff_E_conversion\", 1),\n (\"t_steps_to_charge\", 4),\n])\n\n\"\"\"dict: Default values for bot construction.\"\"\"\n\nSENSING_TARGETS = {\n \"on_food\": 2,\n \"not_on_food\": 1,\n \"neighbouring_recruits\" : 1,\n \"neighbouring_bot\" : 1,\n \"neighbouring_space\": 0,\n}\n\"\"\"dict: Potential targets that can be sensed.\"\"\"\n\n# random seed is random choice\nseed_np = np.random.randint(0, 2**32 - 1)\nseed_random = np.random.randint(0, 2**32 - 1)\n# or\n# random seed is selected for np and random libraries\n# seed_np, seed_random = (26, 300) nice example\nnp.random.seed(seed_np)\nrandom.seed(seed_random)\n\n# setup output data files\ndateStr = time.strftime('%Y-%m-%d')\ntimeStr = time.strftime('%Y-%m-%d_%H_%M_%S')\ndirname = \"output_data/\" + dateStr\nif use_trophallaxis == True:\n troph = \"_troph\"\nelse:\n troph = \"\"\nsubdirname = timeStr + troph\nos.makedirs(dirname + \"/\"+ subdirname + \"/figures\")\ndataTimestep = dirname + \"/\"+ subdirname + \"/\" + subdirname + '_dataTimestep.csv'\ndataSummary = dirname + \"/\"+ subdirname + \"/\" + subdirname + '_dataSummary.csv'\n\ndata_per_timestep = [\"count\",\n \"total_food\",\n \"food_patches\",\n \"bots_with_Estored\",\n \"area_covered\",\n \"total_steps_taken\",\n ]\n\nstart_time = time.time()\n\ncount = 0\nstep_count = 0\nplot_number = 1\n\nLocation = namedtuple(\"Location\", (\"x\", \"y\"))\n\nclass Food(object):\n \"\"\"\n Maps the distribution of food over the grid space.\n\n Parameters\n ----------\n food_map_style :\n The name of the methid used to construct the food map.\n n_cells : int\n The number of cells with individual values that the food map is\n discretised into.\n max_food_per_cell : int\n The maximum value of a food cell.\n\n Attributes\n ----------\n n_cells : int\n The number of cells with individual values that the food map is\n discretised into.\n map_size : int\n The length of each side of the food map in grid cells.\n max_food_per_cell : int\n The maximum value of a food cell.\n food_map : array\n The distribution of food across the grid space, food cell discretisation.\n\n \"\"\"\n def __init__(self):\n\n self.food_map_style = food_map_style\n self.n_cells = n_cells\n self.map_size = int(np.sqrt(self.n_cells))\n self.max_food_per_cell = max_food_per_cell\n self.food_map = np.zeros(self.n_cells)\n\n print(\"food_setup\")\n\n if food_map_style == \"existing_map\":\n\n self.food_map = np.load(food_map_dir + \"/\" + food_map_name\n + \"/\" + food_map_name + \"_food.npy\")\n food_map_name = dirname + \"/\"+ subdirname + \"/\" + food_map_name\n\n if food_map_style == \"new_map\":\n\n self._new_map()\n\n food_map_name = dirname + \"/\" + subdirname + \"/\" + subdirname\n\n np.save(food_map_name + \"_food\", self.food_map)\n self.total_food_initial = np.sum(self.food_map)\n self.total_food_cells_initial = len(np.argwhere(self.food_map))\n\n plt.matshow(self.food_map)\n plt.show()\n print(self.food_map)\n\n\n def _new_map(self):\n self.food_map = np.reshape(self.food_map,\n (self.map_size, self.map_size))\n\n for y, x in zip(y_range, x_range):\n self.food_map[y, x] = 1\n\n # food on each cell\n y, x = np.nonzero(self.food_map)\n for X, Y in zip(x, y):\n\n if individual_food_cell_value == \"max_food_per_cell\":\n self.food_map[X, Y] = self.max_food_per_cell\n\n if individual_food_cell_value == \"random\":\n #set limits\n food_cell_values = range(BOT_DEFAULTS['Ein_perFeed'],\n self.max_food_per_cell + 1,\n BOT_DEFAULTS['Ein_perFeed'])\n self.food_map[X, Y] = random.choice(food_cell_values)\n\n def __repr__(self):\n return \"Food({}, {}, {})\".format(\n self.n_cells,\n self.map_size,\n self.max_food_per_cell,)\n\n def __str__(self):\n return str(self.food_map)\n\nclass Bot(object):\n \"\"\"\n Robot agents that travel around the grid space, eating the food.\n\n Parameters\n ----------\n base_metabolism : int\n The base energy consumption per simulation step of each bot\n Eremoved_perFeed : int\n The amount of energy removed from the cell on the food map on which a\n bot is located every time athe bot feeds.\n Estored_init : float\n The amount of stored energy the bots are initialised with.\n Ecost_perStep : int\n The energy consumed by the bot for each step of size = one grid space.\n Eth_explore : int\n The stored energy threshold that prompts bots to change their task from\n storing energy to exploring.\n Eth_store : int\n The stored energy threshold that prompts bots to change their task from\n exploring to storing energy and aggregating bots around the\n source of energy.\n Eth_troph : int\n The stored energy threshold at which the bot begins sharing energy with\n others.\n Eth_battFull : int\n The stored energy threshold at which a bot stops receiving energy during\n trophallaxis.\n Estored_max : int.\n The value of stored energy above which feeding does not increase the\n senseRange, : int\n The thickness of the border around the bot location within which\n cells are considered in sensing operations.\n troph : logical\n Boolean value for whether bots feed each other or not.\n trophMode : string\n The name of the method the bot uses when feeding bots.\n eff_E_conversion : int\n The efficency (maximum = 1) with which energy removed from the food\n map is converted to stored energy.\n t_steps_to_charge : int\n The number of time steps the bot takes for the converted energy to be\n stored.\n\n Attributes\n ----------\n base_metabolism : int\n The base energy consumption per simulation step of each bot\n Eremoved_perFeed : int\n The amount of energy removed from the cell on the food map on which a\n bot is located every time athe bot feeds.\n Estored_init : float\n The amount of stored energy the bots are initialised with.\n Ecost_perStep : int\n The energy consumed by the bot for each step of size = one grid space.\n Eth_explore : int\n The stored energy threshold that prompts bots to change their task from\n storing energy to exploring.\n Eth_store : int\n The stored energy threshold that prompts bots to change their task from\n exploring to storing energy and aggregating bots around the\n source of energy.\n Eth_troph : int\n The stored energy threshold at which the bot begins sharing energy with\n others.\n Eth_battFull : int\n The stored energy threshold at which a bot stops receiving energy during\n trophallaxis.\n Estored_max : int.\n The value of stored energy above which feeding does not increase the\n senseRange, : int\n The thickness of the border around the bot location within which\n cells are considered in sensing operations.\n troph : logical\n Boolean value for whether bots feed each other or not.\n trophMode : string\n The name of the method the bot uses when feeding bots.\n eff_E_conversion : int\n The efficency (maximum = 1) with which energy removed from the food\n map is converted to stored energy.\n t_steps_to_charge : int\n The number of time steps the bot takes for the converted energy to be\n stored.\n E_stored : float\n The cumulative energy from feeding less the energy consumed.\n location : tuple\n The x, y coordinates of the bot location on the bot map.\n new_location_generator : string\n The name of the method the bot uses to choose a new location on the bot\n map to attempt to move to.\n new_location_generators : dictionary\n The possible new location generators used by the bot.\n target_location : tuple\n The x, y coordinates of the location on the bot map that the bot will\n attempt to move to.\n\n\n\n\n bots : list\n A list of all the bots that exist.\n sense_kernel : array\n A kernel of values used in bot operations that \"sense\" the cells\n surrounding the bot, with the footprint of the sensed cells equal to the\n dimensions of the kernel.\n\n \"\"\"\n bots = []\n\n sense_kernel = np.zeros((2 * BOT_DEFAULTS[\"senseRange\"]+ 1) ** 2)\n sense_kernel[(len(sense_kernel) // 2)] = 1\n kernel_size = np.sqrt(len(sense_kernel))\n sense_kernel = np.reshape(sense_kernel, (kernel_size, kernel_size))\n\n def __init__(self, world, *,\n base_metabolism,\n Eremoved_perFeed,\n Estored_init,\n Ecost_perStep,\n Eth_explore,\n Eth_store,\n Eth_troph,\n Eth_battFull,\n Estored_max,\n senseRange,\n troph,\n trophMode,\n eff_E_conversion,\n t_steps_to_charge):\n\n # self.sense_kernel = np.zeros((2 * BOT_DEFAULTS[\"senseRange\"]\n # + 1) ** 2)\n # self.sense_kernel[(len(self.sense_kernel) // 2)] = 1\n # kernel_size = np.sqrt(len(self.sense_kernel))\n # self.sense_kernel = np.reshape(self.sense_kernel,\n # (kernel_size, kernel_size))\n\n self.base_metabolism = base_metabolism\n self.Ein_perFeed = Eremoved_perFeed\n self.Estored_init = Estored_init\n self.Ecost_perStep = Ecost_perStep\n self.Eth_explore = Eth_explore\n self.Eth_store = Eth_store\n self.Eth_troph = Eth_troph\n self.Eth_battFull = Eth_battFull\n self.Estored_max = Estored_max\n self.senseRange = senseRange\n self.troph = troph\n self.trophMode = trophMode\n self.eff_E_conversion = eff_E_conversion\n self.t_steps_to_charge = t_steps_to_charge\n\n self.Estored = Estored_init\n self.location = None\n self.new_location_generator = None\n self.target_location = None\n self.bots.append(self)\n\n self.new_location_generators = {\n \"random\": self.new_location_random,\n }\n\n def sense(self, map, sensing_target):\n \"\"\"\n Checks if bot has any neighbouring bots/ spaces/ recruits\n Parameters\n ----------\n map : array\n The map whose contents are ebing sensed.\n sensing_target : string\n The item to search for.\n\n Returns\n -------\n list[Location]\n The location of all neighbours of the target type.\n\n \"\"\"\n # top left hand corner of kernel = i, j\n i = self.location.y - BOT_DEFAULTS[\"senseRange\"]\n j = self.location.x - BOT_DEFAULTS[\"senseRange\"]\n k = np.shape(Bot.sense_kernel)[0]\n\n neighbours = np.argwhere(map[i:i + k, j:j + k]\n - Bot.sense_kernel ==\n SENSING_TARGETS[sensing_target])\n\n return [Location(x + j, y + i) for y, x in neighbours]\n\n def evaluate_neighbours(self, world):\n \"\"\"\n\n Parameters\n ----------\n world : object\n The world in which the bots live\n\n Returns\n -------\n\n \"\"\"\n location = self.location\n\n neighbours = self.sense(np.ma.make_mask(world.bot_map) * 1,\n \"neighbouring_bot\")\n\n bot_on_food = bool((np.ma.make_mask(world.food_map) * 1)\n [location[::-1]])\n\n if neighbours == []:\n neighbours = {}\n\n else:\n neighbours = {}\n\n not_on_food_map = np.ma.make_mask(world.bot_map) * 1 - \\\n np.ma.make_mask(world.food_map) * 1\n\n on_food_map = np.ma.make_mask(world.bot_map) * 1 + \\\n np.ma.make_mask(world.food_map) * 1\n\n\n neighbours[\"bot1_neighbour0\"] = \\\n self.sense(not_on_food_map, \"on_food\")\n\n\n #self.sense(not_on_food_map, \"on_food\")\n\n if bot_on_food:\n\n neighbours[\"bot1_neighbour0\"] = \\\n self.sense(not_on_food_map, \"not_on_food\")\n\n neighbours[\"bot1_neighbour1\"] = \\\n self.sense(on_food_map, \"on_food\")\n\n else: # if food cell empty\n\n neighbours[\"bot0_neighbour0\"] = \\\n self.sense(not_on_food_map,\"not_on_food\")\n\n neighbours[\"bot0_neighbour1\"] = \\\n self.sense(on_food_map, \"on_food\")\n\n return neighbours #neighbours_food\n\n\n\n\n\n def new_location_random(self, location, world):\n \"\"\"\n Determines the next space the bot will attempt to move to.\n\n Parameters\n ----------\n initial_location: named tuple\n The x,y coordinates of position the bot will attempt to move from.\n\n Returns\n -------\n new_location : name tuple\n The x,y coordinates of next position the bot will attempt to move to.\n \"\"\"\n\n new_location = Location(\n np.clip(location.x + random.randint(-1, 1), 1,\n world.bot_map_size - 2),\n np.clip(location.y + random.randint(-1, 1), 1,\n world.bot_map_size - 2))\n\n return new_location\n\nclass World(object):\n \"\"\"\n Maps the distribution of food over the grid space.\n\n Parameters\n ----------\n n_bots : int\n The number of bots\n _food : Food\n The food distribution across the grid space.\n\n Attributes\n ----------\n n_bots : int\n The number of bots\n _food : object\n The food distribution across the grid space.\n n_cells :\n The number of food cells\n map_size : int\n The length of each side of the food map.\n food_map : np.ndarray\n The distribution of food across the grid space.\n bot_map : np.ndarray\n The distribution of bots across the grid space.\n bot_map_size : int\n The length of each side of the bot map in grid units.\n _bots_on_food : int\n The number of bots located on a cell containing food\n Estored_map : np.ndarray\n The map of cumulative energy stored by each bot.\n Acovered_map : np.ndarray\n A map showing the number of times a grid cell has been entered by a bot.\n trajectory_coords : Dictionary\n Coordinates of start and end point that define robots motion vector\n\n \"\"\"\n\n def __init__(self, food):\n self.n_bots = n_bots\n self._food = food\n self.n_cells = n_cells\n self.map_size = self._food.map_size\n self.food_map, self.food_map_size = self._pad_map(\n self._food.food_map, BOT_DEFAULTS['senseRange'])\n\n self.bot_map = None\n self.bot_map_size = None\n self._populate_bot_map()\n self._bots_on_food = None\n\n self.Estored_map = np.ma.make_mask(self.bot_map) \\\n * BOT_DEFAULTS[\"Estored_init\"]\n\n self.Acovered_map = np.ma.make_mask(self.bot_map) * 1\n\n self.charge_mode_map = np.multiply( np.ma.make_mask(self.bot_map) * 1,\n np.ma.make_mask(self.food_map) * 1)\n\n self.trajectory_coords = {\"x_preMove\" : None,\n \"y_preMove\" : None,\n \"y_postMove\": None,\n \"x_postMove\": None}\n\n def _pad_map(self, map_to_pad, _border_width):\n \"\"\"\n Creates a border of width = _border_width around the map as dictated by\n the sense range of the bots. This is to prevent errors generated by\n functions that use elements of a window around each bot, the size of\n which is defined by the robot sense range.\n\n Parameters\n ----------\n map_to_pad : array\n The map to pad.\n\n _border_width :\n The border width in grid units\n \"\"\"\n _full_map_size = int(self.map_size + 2*_border_width)\n\n if map_to_pad.dtype == object:\n _full_map = np.empty(\n (_full_map_size) ** 2, dtype=object).reshape(_full_map_size,\n _full_map_size)\n\n else:\n _full_map = np.zeros(\n (_full_map_size) ** 2).reshape(_full_map_size,_full_map_size)\n\n _full_map[_border_width:(\n _border_width + self.map_size),\n _border_width:(_border_width + self.map_size)] = map_to_pad\n\n return _full_map, _full_map_size\n\n def _populate_bot_map(self):\n\n\n \"\"\"\n Distributes n_bots start locations randomly over the grid space\n\n \"\"\"\n\n\n if bot_map_style == \"existing_map\":\n self.bot_map = np.load(dirname + \"/\"+ bot_map_dir + \"/\"\n + bot_map_name + \"bots.npy\")\n self.bot_map_size = np.shape(self.bot_map)[0]\n bot_map_name = dirname + \"/\"+ subdirname + \"/\" + bot_map_name\n\n else:\n\n if bot_map_style == \"new_map\":\n pass\n\n # if bot_map_style == \"random_half_map\":\n # self.bot_map = np.empty(self.n_cells, dtype=object)\n # self.bot_map = np.reshape(self.bot_map,\n # (self.map_size, self.map_size))\n # _bot_map = self.bot_map.ravel()\n # for bot in range(self.n_bots):\n # _bot_map[bot] = Bot(self, **BOT_DEFAULTS)\n # np.random.shuffle(_bot_map[:0.5 * self.n_cells])\n # self.bot_map = np.transpose(self.bot_map)\n\n if bot_map_style == \"random_map\":\n\n\n self._random_map()\n\n if set_number_agents_on_food == True:\n\n while len(self._bots_on_food) != n_agents_on_food:\n self._random_map()\n\n # give each bot a location identity\n y, x = np.where(self.bot_map)\n for Y, X in zip(y, x):\n self.bot_map[Y, X].location = Location(X, Y)\n\n bot_map_name = (dirname + \"/\" + subdirname +\n \"/\" + subdirname)\n\n np.save(bot_map_name + \"bots\", self.bot_map)\n\n print(np.ma.make_mask(self.bot_map)*1)\n\n def _random_map(self):\n\n self.bot_map = np.empty(self.n_cells, dtype=object)\n\n for i in range(self.n_bots):\n self.bot_map[i] = Bot(self, **BOT_DEFAULTS)\n\n np.random.shuffle(self.bot_map)\n self.bot_map = np.reshape(self.bot_map, (self.map_size, self.map_size)) # record index of each bot on a food patch\n\n self.bot_map, self.bot_map_size = self._pad_map(\n self.bot_map, BOT_DEFAULTS['senseRange'])\n\n self._bots_on_food = np.where(\n (np.ma.make_mask(self.bot_map) * 1 > 0) &\n (self.food_map > 0))\n\n print(len(self._bots_on_food))\n\n def save_data_per_timestep(self):\n\n # log data to data per cycle\n with open(dataTimestep, 'a') as c:\n writer = csv.writer(c)\n writer.writerow([\n\n # count\n count,\n\n # total food\n np.sum(self.food_map),\n\n # number of food patches\n len(np.where(self.food_map)[0]),\n\n # _bots_with_Estored\n len(np.where(self.Estored_map)[0]),\n\n # total area covered\n len(np.where(self.Acovered_map)[0]),\n\n # total steps taken\n step_count,\n\n ])\n\n def save_data_init(self, food_map):\n\n \"\"\"\n Creates a dictionary of the attributes of the World object and the\n default properties of the bots. Saves these and other global data and\n parameters of the World object to a new csv file.\n Defines heaidings of parameters to be recorded at each timestep to a new\n csv file and calculates and saves initial values.\n\n Parameters\n ----------\n food_map : array\n An attribute to remove from the dictionary.\n \"\"\"\n\n attributes = food_map.__dict__\n del attributes[\"food_map\"]\n attributes.update(BOT_DEFAULTS)\n\n # write data to data summary\n with open(dataSummary, 'w') as s:\n writer = csv.writer(s)\n for key, value in attributes.items():\n writer.writerow([key, value])\n writer.writerow([\"n_bots\", self.n_bots])\n writer.writerow([\"seed np:\", seed_np])\n writer.writerow([\"seed random:\", seed_random])\n\n # setup data per timestep file\n with open(dataTimestep, 'w') as c:\n writer = csv.writer(c)\n #writer.writerow(self.data_to_log)\n writer.writerow(data_per_timestep)\n\n self.save_data_per_timestep()\n\n def plot(self, plot_trajectory):\n\n global plot_number\n\n f, ax = plt.subplots()\n\n # plot food\n ax.matshow(self.food_map,\n cmap='Greens',\n vmin=0,\n vmax=self._food.max_food_per_cell)\n\n # plot stored energy\n y, x = np.where(self.bot_map)\n ax.scatter(\n x, y, 70,\n c = self.Estored_map[y, x],\n cmap = \"Reds\",\n vmin = 0,\n # vmax=self.e_threshold_explore)\n vmax = BOT_DEFAULTS[\"Estored_max\"])\n\n # vectors showing bot trajectory\n if plot_trajectory == True:\n for y_pre, x_pre, y_post, x_post in zip(\n self.trajectory_coords[\"y_preMove\"],\n self.trajectory_coords[\"x_preMove\"],\n self.trajectory_coords[\"y_postMove\"],\n self.trajectory_coords[\"x_postMove\"]\n ):\n ax.plot([x_pre, x_post], [y_pre, y_post], c='r')\n\n plt.ylim((0, self.bot_map_size ))\n plt.xlim((0, self.bot_map_size))\n\n plotname = dirname + \"/\" + subdirname \\\n + \"/figures/\" + str(plot_number).zfill(4)\n\n plot_number += 1\n\n f.savefig(plotname + '.pdf', orientation='landscape')\n f.savefig(plotname + '.png', orientation='landscape')\n\n\n def feed(self):\n \"\"\"\n Decreases food map by 1 unit in every grid cell newly occupied by a bot\n Updates the bot charging map with new occupants\n Updates the stored energy map of all charging bots with the energy from\n feeding divided by the number of time steps taken to charge.\n \"\"\"\n _food_consumed = BOT_DEFAULTS[\"Eremoved_perFeed\"]\n\n _newcharge_bot_map = np.multiply(np.ma.make_mask(self.bot_map) * 1,\n np.ma.make_mask(self.food_map) * 1) \\\n - self.charge_mode_map\n\n self.charge_mode_map += _newcharge_bot_map\n\n np.clip(self.food_map - (_newcharge_bot_map * _food_consumed),\n 0, float(\"inf\"),\n self.food_map)\n\n #self.charge(_food_consumed)\n\n def charge(self, _food_consumed):\n \"\"\"\n Updates the stored energy map of all charging bots with the energy from\n feeding divided by the number of time steps taken to charge.\n\n \"\"\"\n food_consumed = _food_consumed\n eff_E_conversion = BOT_DEFAULTS[\"eff_E_conversion\"]\n t_steps_to_charge = BOT_DEFAULTS[\"t_steps_to_charge\"]\n\n # self.Estored_map = np.add(self.Estored_map,\n # (self.charge_mode_map\n # * eff_E_conversion\n # * food_consumed\n # / _t_steps_to_charge))\n\n # self.Estored_map = np.clip(self.Estored_map\n # + (_food_consumed_map * food_consumed),\n # 0, BOT_DEFAULTS[\"Estored_max\"],\n # self.Estored_map)\n\n self.Estored_map = np.clip(self.Estored_map\n + (self.charge_mode_map\n * eff_E_conversion\n * food_consumed\n / t_steps_to_charge),\n 0, BOT_DEFAULTS[\"Estored_max\"],\n self.Estored_map)\n\n def base_metabolism(self):\n \"\"\"\n\n \"\"\"\n np.clip(\n self.Estored_map - BOT_DEFAULTS[\"base_metabolism\"],\n 0, float(\"inf\"), self.Estored_map)\n\n def functioning_bots(self):\n\n functioning_bots = []\n\n incapacitated_bots = self.incapacitated_bots()\n _bots = np.copy(self.bot_map)\n _bots[incapacitated_bots] = None\n _functioning_bots = np.argwhere(_bots)\n for _functioning_bot in _functioning_bots:\n bot = self.bot_map[_functioning_bot[0], _functioning_bot[1]]\n functioning_bots.append(bot)\n\n return functioning_bots\n\n\n def incapacitated_bots(self):\n incapacitated_bots = np.where((self.bot_map != None)\n and self.Estored_map == 0)\n return incapacitated_bots\n\n\n#\n# def feed_hungry_neighbour(self, location_bot_feed, location_bot_receive):\n#\n# \"\"\"\n# Transfers stored energy from one bot to another.\n#\n# Parameters\n# ----------\n# location_bot_feed : tuple\n# The x,y coordinates of the bot which is the energy donor.\n#\n# location_bot_receive : tuple\n# The x,y coordinates of the bot which is the energy recipiant.\n# \"\"\"\n# # TODO: include energy transfer effiency\n#\n# # global trophallaxis_count_explore\n# # global trophallaxis_count_store\n#\n# if self.Estored_map[location_bot_feed[::-1]] \\\n# > BOT_DEFAULTS[\"e_threshold_trophallaxis\"]:\n#\n# _e_donor = copy.copy(\n# int(self.Estored_map[location_bot_feed[::-1]]))\n# #_e_recipiant = self.Estored_map[location_bot_receive[::-1]]\n# _e_recipiant = copy.copy(\n# int(self.Estored_map[location_bot_receive[::-1]]))\n#\n# if BOT_DEFAULTS[\"trophallaxis_mode\"] == \"equalise\":\n# if ( _e_donor - (np.average([_e_donor, _e_recipiant])) > 0):\n# food_transferred = int(_e_donor - (\n# np.average([_e_donor, _e_recipiant])))\n# # if food_transferred:\n# # if self.explore_mode_map[location_bot_feed[::-1]]:\n# # trophallaxis_count_explore += 1\n# # else:\n# # trophallaxis_count_store += 1\n# else:\n# food_transferred = 0\n#\n# if BOT_DEFAULTS[\"trophallaxis_mode\"] == \"top_up_recipiant_cautious\":\n#\n# _e_desired = np.clip((BOT_DEFAULTS[\"e_threshold_full\"] -\n# _e_recipiant),\n# 0, float(\"inf\"))\n#\n# _e_available = np.clip((_e_donor -\n# BOT_DEFAULTS[\"e_threshold_trophallaxis\"]),\n# 0, float(\"inf\"))\n#\n# food_transferred = int(np.clip(_e_desired, 0, _e_available))\n# # if food_transferred:\n# # if self.explore_mode_map[location_bot_feed[::-1]]:\n# # trophallaxis_count_explore += 1\n# # else:\n# # trophallaxis_count_store += 1\n# else:\n# food_transferred = 0\n#\n# #print(\"food_transferred\", food_transferred)\n#\n# self.Estored_map[location_bot_feed[::-1]] -= food_transferred\n# self.Estored_map[location_bot_receive[::-1]] += food_transferred\n#\n# # _e_donor = self.Estored_map[location_bot_feed[::-1]]\n# # _e_recipiant = self.Estored_map[location_bot_receive[::-1]]\n# #\n# # print(\"feed\", location_bot_feed, _e_donor)\n# # print(\"receive\",location_bot_receive, _e_recipiant )\n#\n# # if the bot is on the bot move map, decrease the number of steps it\n# # should take.\n# if self.bot_move_map[location_bot_feed[::-1]]:\n# self.bot_move_map[location_bot_feed[::-1]] = np.clip(\n# (self.bot_move_map[location_bot_feed[::-1]] -\n# int(food_transferred * BOT_DEFAULTS[\"e_cost_per_step\"])\n# ), 0, float(\"inf\"))\n#\n# # if bot was fed, and not by robot in chain...\n# if food_transferred:\n#\n# # if ((self.bot_map[location_bot_receive[::-1]].chain == None) and\n# # (self.bot_map[location_bot_receive[::-1]].relay_chain == None)):\n#\n# # if the bot had energy when fed, move towards the feeder\n# # if _e_recipiant > 0:\n#\n# _heading = \\\n# Location((location_bot_feed.x - location_bot_receive.x),\n# (location_bot_feed.y - location_bot_receive.y))\n#\n# self.setup_move(\"step_towards_feeder\", location_bot_receive,\n# _heading)\n#\n# # otherwise, if bot being fed on start-up move away from donor\n# # else: # if _e_recipiant == 0\n# #\n# # # if (self.bot_map[location_bot_feed[::-1]].relay_chain or\n# # # self.bot_map[location_bot_feed[::-1]].chain or\n# # # self.food_map[location_bot_feed[::-1]]):\n# #\n# # _heading = \\\n# # Location((location_bot_receive.x - location_bot_feed.x),\n# # (location_bot_receive.y - location_bot_feed.y))\n# #\n# # print(\"move away from feeder\")\n# # self.setup_move(\"step_towards_feeder\",\n# # location_bot_receive,\n# # _heading)\n# # else:\n# #\n# # _heading = \\\n# # Location((location_bot_feed.x - location_bot_receive.x),\n# # (location_bot_feed.y - location_bot_receive.y))\n# #\n# # self.setup_move(\"step_towards_feeder\",\n# # location_bot_receive,\n# # _heading)\n#\n# # self.setup_move(\"new_location_random\",\n# # location_bot_receive,\n# # None,\n# # np.clip(self.Estored_map[\n# # location_bot_receive[::-1]],\n# # 0, float(\"inf\")))\n#\n# def setup_move(self, new_location_generator,\n# location, target_location,\n# units_moved = 1):\n#\n# print(\"location1\", location)\n# print(\"target location1\", target_location)\n#\n# if (location and target_location\n# and (int(location.x) == int(target_location.x))\n# and (int(location.y) == int(target_location.y))):\n#\n# print(\"already at target loc.\", location)\n# pass\n#\n# else:\n#\n# self.bot_map[location[::-1]]. \\\n# new_location_generator = new_location_generator\n#\n# self.bot_move_map[location[::-1]] = units_moved\n#\n# if (self.bot_map[location[::-1]].\n# new_location_generator == \"new_location_towards_neighbour\" or\n# self.bot_map[location[::-1]].\n# new_location_generator == \"new_location_towards_signal\"):\n#\n# # # if there is energy to move\n# # if self.Estored_map[location[::-1]]:\n#\n# self.bot_map[location[::-1]].target_location = target_location\n#\n# # elif self.bot_map[location[::-1]]. \\\n# # new_location_generator == \"step_to_explore\":\n#\n# elif (self.bot_map[location[::-1]].\n# new_location_generator == \"step_to_explore\" or\n# self.bot_map[location[::-1]].\n# new_location_generator == \"step_towards_feeder\"):\n#\n# self.bot_map[location[::-1]].target_location = \\\n# Location(location.x + target_location.x,\n# location.y + target_location.y)\n#\n#\n#\n# # def attempt_connect_neighbours(self, location, equal_neighbour):\n# # #print(\"attempting connnection\")\n# #\n# # def connect_chains(_chain, _other_chain, max_to_add):\n# # _chain.chain_map = _chain.chain_map + _other_chain.chain_map\n# #\n# # for Y, X in zip(y, x):\n# # _chain.chain_map[Y, X] += max_to_add\n# #\n# # #_chain.connected_bots += _other_chain.connected_bots\n# # #print(\"_chain.connected_bots\", _chain.connected_bots)\n# # _chain.connected_bots.extend(_other_chain.connected_bots[:])\n# # #print(\"_chain.connected_bots\", _chain.connected_bots)\n# # # for bot in _other_chain.connected_bots:\n# # for bot in _chain.connected_bots:\n# # bot.chain = _chain\n# # #print(bot)\n# # #print(bot.chain)\n# #\n# # _other_chain.chain_map = []\n# # #print(\"remaining chains\")\n# # Chain.chains.remove(_other_chain)\n# #\n# # #_other_chain.dissolve_chain() - THIS RESETS ALL NEW CHAIN MEMBERS' bot.chain value to 0\n# # # Chain.chains.remove(_other_chain)\n# # # print(\"connected chain to chain\", _chain)\n# #\n# # # case 1: two single bots\n# # if not self.bot_map[location[::-1]].chain \\\n# # and not self.bot_map[equal_neighbour[::-1]].chain:\n# # #print(\"case 1: two single bots\")\n# # #print(\"connected single bots\", self.bot_map[location[::-1]].chain)\n# # Chain(self.food_map, [self.bot_map[location[::-1]],\n# # self.bot_map[equal_neighbour[::-1]]])\n# #\n# # # case 2: connect single bot to bot in chain\n# # elif bool(self.bot_map[location[::-1]].chain) != \\\n# # bool(self.bot_map[equal_neighbour[::-1]].chain):\n# # #print(\"case 2: connect single bot to bot in chain\")\n# #\n# # if self.bot_map[location[::-1]].chain:\n# # _chain = self.bot_map[location[::-1]].chain\n# # _bot = location\n# # _other_bot = equal_neighbour\n# #\n# # else:\n# # _chain = self.bot_map[equal_neighbour[::-1]].chain\n# # _bot = equal_neighbour\n# # _other_bot = location\n# #\n# # # connect to min of chain\n# # if _chain.chain_map[_bot[::-1]] == \\\n# # np.min(_chain.chain_map[np.nonzero(_chain.chain_map)]):\n# # y, x = np.nonzero(_chain.chain_map)\n# # _chain.chain_map[y, x] += 1\n# # # add new bot at min of chain\n# # _chain.chain_map[_other_bot[::-1]] = 1\n# # _chain.connected_bots.append(self.bot_map[_other_bot[::-1]])\n# # self.bot_map[_other_bot[::-1]].chain = _chain\n# #\n# # # connect to max of chain\n# # if _chain.chain_map[_bot[::-1]] == \\\n# # np.max(_chain.chain_map[np.nonzero(_chain.chain_map)]):\n# # # add new bot at max of chain\n# # _chain.chain_map[_other_bot[::-1]] = \\\n# # np.max(_chain.chain_map[np.nonzero(_chain.chain_map)]) + 1\n# # _chain.connected_bots.append(self.bot_map[_other_bot[::-1]])\n# # self.bot_map[_other_bot[::-1]].chain = _chain\n# # #print(\"connected single to chain\")\n# #\n# # # case 3: both bots in chains\n# # # TODO: simpler decision matrix\n# # elif self.bot_map[location[::-1]].chain \\\n# # and self.bot_map[equal_neighbour[::-1]].chain:\n# # # and it is not the same chain\n# # if (self.bot_map[location[::-1]].chain.connected_bots !=\n# # self.bot_map[equal_neighbour[::-1]].chain.connected_bots):\n# #\n# # #print(\"case 3: both bots in different chains\")\n# #\n# # _bot = location\n# # _other_bot = equal_neighbour\n# # _chain = self.bot_map[location[::-1]].chain\n# # _other_chain = self.bot_map[equal_neighbour[::-1]].chain\n# #\n# # # min of chain to max of other chain\n# # if (_chain.chain_map[_bot[::-1]] == np.min(_chain.chain_map\n# # [np.nonzero(\n# # _chain.chain_map)])\n# # and _other_chain.chain_map\n# # [_other_bot[::-1]]\n# # == np.max(_other_chain.chain_map\n# # [np.nonzero(\n# # _other_chain.chain_map)])):\n# # y, x = np.nonzero(_chain.chain_map)\n# # max_to_add = np.max(_other_chain.chain_map\n# # [np.nonzero(_other_chain.chain_map)])\n# # connect_chains(_chain, _other_chain, max_to_add)\n# #\n# # # print(\"min of chain to max of other chain\", _chain)\n# #\n# # # max of chain to min of other chain\n# #\n# # if (_chain.chain_map[_bot[::-1]] == np.max(_chain.chain_map\n# # [np.nonzero(\n# # _chain.chain_map)])\n# # and _other_chain.chain_map[\n# # _other_bot[::-1]]\n# # == np.min(_other_chain.chain_map[np.nonzero(\n# # _other_chain.chain_map)])):\n# # # print(\"max of chain to min of other chain\")\n# #\n# # y, x = np.nonzero(_other_chain.chain_map)\n# # max_to_add = np.max(_chain.chain_map[np.nonzero(\n# # _chain.chain_map)])\n# # connect_chains(_chain, _other_chain, max_to_add)\n# #\n# # # min of chain to min of other chain\n# #\n# # if (_chain.chain_map[_bot[::-1]] ==\n# # np.min(_chain.chain_map[np.nonzero(\n# # _chain.chain_map)])\n# # and\n# # _other_chain.chain_map[_other_bot[::-1]] ==\n# # np.min(_chain.chain_map[np.nonzero(\n# # _chain.chain_map)])):\n# #\n# # # print(\"min of chain to min of other chain\")\n# #\n# # y, x = np.nonzero(_other_chain.chain_map)\n# #\n# # max_to_add = np.max(_other_chain.chain_map[np.nonzero(\n# # _other_chain.chain_map)])\n# #\n# # # reverse order of other_chain\n# # for Y, X in zip(y, x):\n# # _other_chain.chain_map[Y, X] = max_to_add + 1 - \\\n# # _other_chain.chain_map[\n# # Y, X]\n# #\n# # y, x = np.nonzero(_chain.chain_map)\n# # connect_chains(_chain, _other_chain, max_to_add)\n# #\n# # # max of chain to max of other chain\n# #\n# # if _chain.chain_map[_bot[::-1]] == \\\n# # np.max(_chain.chain_map\n# # [np.nonzero(_chain.chain_map)]) \\\n# # and \\\n# # _other_chain.chain_map[\n# # _other_bot[::-1]] == np.max(\n# # _other_chain.chain_map[np.nonzero(\n# # _other_chain.chain_map)]):\n# #\n# # # print(\"max of chain to max of other chain\")\n# #\n# # y, x = np.nonzero(_other_chain.chain_map)\n# #\n# # max_to_add = np.max(_other_chain.chain_map\n# # [np.nonzero(\n# # _other_chain.chain_map)])\n# #\n# # # reverse order of other_chain\n# # for Y, X in zip(y, x):\n# # _other_chain.chain_map[Y, X] = max_to_add + 1 - \\\n# # _other_chain.chain_map[\n# # Y, X]\n# #\n# # y, x = np.nonzero(_chain.chain_map)\n# # connect_chains(_chain, _other_chain, max_to_add)\n#\n\n#\n# def save_data_init(self, food_map):\n#\n# attributes = food_map.__dict__\n# del attributes[\"food_map\"]\n# attributes.update(BOT_DEFAULTS)\n#\n# # write data to data summary\n# with open(data_summary, 'w') as s:\n# writer = csv.writer(s)\n# for key, value in attributes.items():\n# writer.writerow([key, value])\n# writer.writerow([\"n_bots\", self.n_bots])\n# writer.writerow([\"seed np:\", seed_np])\n# writer.writerow([\"seed random:\", seed_random])\n#\n# # self.data_to_log = [\"count\", \"bots_alive\",\n# # \"bots_on_food_left\", \"bots_on_food_right\",\n# # \"total_food_on_left\", \"total_food_on_right\",\n# # \"food_patches\", \"total_food\",\n# # \"bots_in_chain\", \"bots_in_relay_chain\"]\n#\n# # count\n# # bots alive before / after move\n# # total food n_cells\n# # total food\n# # bots on food before move that do not move (stop on food) bots on food not on move map\n# # bots on food before move that do move (walk explore) bots on food not on move map OR transitioning explore bots\n# # explore bots that moved in last run tht end up not on food (stop not on food)\n# # explore bots that moved in last run tht end up not on food (stop not on food)\n# # fed bots\n# # occupied food cells depleted\n# # fed bots + occupied food cells depleted\n#\n# self.data_to_log = [\"count\", \"total_food\", \"food_patches\",\n# \"_bots_with_Estored\", \"bots_alive_after_move\",\n# #\"bots_on_food_move\", \"bots_on_food_no_move\",\n# \"troph_by_storers\", \"troph_by_explorers\",\n# \"success_forage_storers\",\n# \"success_forage_explorers\",\n# \"successful_forage_dont_stop\",\n# \"unsuccessful_foragers\",\n# \"depleted_food_cells\",\n# #\"moved_to_food\", \"moved_to_empty\",\n# \"area_covered\",\n# \"nbots_walk_search\", \"nbots_walk_explore\",\n# \"nbots_stop_on_food\", \"nbots_stop_off_food\",\n# \"transition_to_store_count\",\n# \"transition_to_explore_count\",\n# # \"bots_in_chain\", \"bots_in_relay_chain\"\n# ]\n#\n# with open(data_per_timestep, 'w') as c:\n# writer = csv.writer(c)\n# writer.writerow(self.data_to_log)\n#\n# _bots_with_Estored = len(np.where(self.Estored_map)[0])\n#\n# _food_cells = np.copy(\n# len(np.where(np.ma.make_mask(self.food_map) * 1)[0]))\n#\n#\n# nbots_walk_search = len(np.where(\n# (np.ma.make_mask(self.store_mode_map) * 1 > 0)\n# & (np.ma.make_mask(self.bot_move_map) * 1 < 1)\n# )[0])\n# nbots_walk_explore = len(np.where(\n# (np.ma.make_mask(self.explore_mode_map) > 0)\n# )[0])\n# nbots_stop_on_food = len(np.where(\n# (np.ma.make_mask(self.bot_map) * 1 > 0)\n# & (np.ma.make_mask(self.food_map) * 1 > 0)\n# & (np.ma.make_mask(self.bot_move_map) * 1 < 1)\n# )[0])\n#\n# nbots_stop_off_food = len(np.where(\n# (np.ma.make_mask(self.bot_map) * 1 > 0)\n# & (np.ma.make_mask(self.food_map) * 1 < 1)\n# & (np.ma.make_mask(self.bot_move_map) * 1 < 1)\n# )[0])\n#\n# self.save_data_per_timestep(_bots_with_Estored,\n# # 0,\n# # 0,\n# _food_cells,\n# nbots_walk_search,\n# nbots_walk_explore,\n# nbots_stop_on_food,\n# nbots_stop_off_food)\n#\n\n#\n# def save_data_final(self):\n#\n# if np.any(self.Estored_map):\n# s = csv.writer(open(data_summary, 'a'))\n# s.writerow([\"area_covered\",\n# len(np.argwhere(self.area_covered_map))])\n# s.writerow([\"count\", count])\n# s.writerow([\"all food eaten\"])\n# s.writerow(\n# [\"bots_still_alive\", len(np.argwhere(self.Estored_map))])\n# print(\"all food eaten\")\n#\n# elif np.any(self.food_map):\n# s = csv.writer(open(data_summary, 'a'))\n# s.writerow([\"area_covered\",\n# len(np.argwhere(self.area_covered_map))])\n# s.writerow([\"count\", count])\n# s.writerow([\"all_bots_dead\"])\n# s.writerow(\n# [\"total_food_end\", np.sum(self.food_map)])\n# s.writerow(\n# [\"n_food_cells_end\", len(np.argwhere(self.food_map))])\n# print(\"all bots dead\")\n#\n# def plot_data_per_time_step(self):\n#\n# data = np.genfromtxt(data_per_timestep, delimiter=',',\n# skip_header=2, skip_footer=0,\n# names= self.data_to_log)\n#\n# fig, ax1 = plt.subplots()\n# ax2 = ax1.twinx()\n#\n# lns1 = ax2.plot(data['count'], data['bots_alive'], marker='o',\n# linestyle='-', color='k', label='Robots alive')\n# lns3 = ax2.plot(data['count'], data['bots_on_food_left'], marker='.',\n# linestyle='-', color='k', label='Robots on food, left')\n# lns5 = ax2.plot(data['count'], data['bots_on_food_right'], marker='^',\n# linestyle='-', color='k', label='Robots on food, right')\n# lns7 = ax1.plot(data['count'], data['total_food'], marker='x',\n# linestyle='-', color='k', label='Total Food Remaining')\n#\n# lns = lns1 + lns3 + lns5 + lns7\n# labels = [l.get_label() for l in lns]\n# ax1.legend(lns, labels, loc=0, frameon=False)\n# ax1.set_xlabel('Cycles')\n# ax1.set_ylabel('Total Food Units')\n# ax2.set_ylabel('Number of Robots')\n#\n# plotname = dirname + \"/\"+ subdirname + \"/\" \\\n# + subdirname + '_per_timestep'\n#\n# fig.savefig(plotname + '.pdf', orientation='landscape')\n\n\n\ndef main():\n\n global count\n\n food_map = Food()\n\n # # populate world with agents\n world = World(food_map)\n\n world.save_data_init(food_map)\n\n if plot_output:\n world.plot(False)\n\n # loop until all bots incapacitated by hunger OR all food removed\n while (np.any(world.Estored_map) and np.any(world.food_map)):\n count += 1\n print (count)\n\n # energy in\n world.feed()\n\n # energy out\n world.base_metabolism()\n\n functioning_bots = world.functioning_bots()\n\n if functioning_bots != []:\n\n random.shuffle(functioning_bots)\n\n for bot in functioning_bots:\n\n #world.state_transition()\n\n neighbours = bot.sense(np.ma.make_mask(world.bot_map) * 1,\n \"neighbouring_bot\")\n\n # TODO: better name\n neighbours = bot.evaluate_neighbours(world)\n\n # if no neighbours\n if bool(neighbours) == False:\n pass\n #print(\"neighbours\" , neighbours)\n # if neighbours\n else:\n pass\n #print(\"neighbours\" , neighbours)\n # if bool(neighbours[\"bot1_neightbour_1\"] != []:\n # do something\n\n\n\n # if neighbours_less_food:\n # for neighbour in neighbours_less_food:\n # if BOT_DEFAULTS[\"trophallaxis\"] == True:\n # world.feed_hungry_neighbour(location, neighbour)\n\n # if neighbours_same_food_none:\n # if world.explore_mode_map[location[::-1]]:\n # for neighbour in neighbours_same_food_none:\n # print(\"hungry explorer:try to feed hungry neighbour\")\n\n # if BOT_DEFAULTS[\"trophallaxis\"] == True:\n # world.feed_hungry_neighbour(location, neighbour)\n #\n # else:\n # print(\n # \" store bot neighbour has same food (empty): random walk\",\n # location)\n # world.setup_move(\"new_location_random\",\n # location, None,\n # np.clip(world.stored_energy_map[\n # location[::-1]],\n # 0, float(\"inf\")))\n\n # note: random walk command comes first so that it is overidden by\n # command to move to fed nieghbour if neighbours are available\n\n # if neighbours_more_food:\n # neighbour = random.choice(neighbours_more_food)\n #\n # # # if bot is not explorer\n # if not world.explore_mode_map[location[::-1]]:\n # if world.stored_energy_map[location[::-1]]:\n # world.setup_move(\"new_location_towards_neighbour\",\n # location, neighbour)\n\n\n\n\n # bot = world.bot_map[functioning_bot[0], functioning_bot[1]]\n # location = bot.location\n # neighbours = bot.sense(np.ma.make_mask(world.bot_map) * 1,\n # \"neighbouring_bot\")\n\n\n\nif __name__ == '__main__':\n try:\n main()\n finally:\n print(\"end\")\n #print(\"count:\", count)\n","sub_path":"misc_backups/PycharmProjects_backup/disused_backups/trophallaxis_model_backup_170222/multi_agent_tropahllaxis.py","file_name":"multi_agent_tropahllaxis.py","file_ext":"py","file_size_in_byte":54553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"230736216","text":"import uuid\nfrom termcc.helper.logger import Config, inject_basic, inject_color\nfrom flask import request\n\ndef inject_flask(record):\n inject_basic(record)\n try:\n record.extra['trace_id'] = request.headers.get('trace-id') or uuid.uuid1().hex\n record.extra['ip'] = request.remote_addr or None\n record.extra['method'] = request.method or None\n record.extra['path'] = request.path or None\n except:\n record.extra['ip'] = None\n record.extra['method'] = None\n record.extra['trace_id'] = None\n record.extra['path'] = None\n\n\ndef inject_flask_color(record):\n inject_flask(record)\n inject_color(record)\n\n\ndef setup_logger():\n lc = Config(inject=inject_flask_color)\n lc.setup_format(\n lc.basic_format(color=True),\n lc.time_format(),\n lc.process_format(),\n lc.trace_format(),\n logger_names=['stream-out'])\n lc.push(logger_names=['stream-out'])","sub_path":"openapi/utils/log_handle.py","file_name":"log_handle.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"210933721","text":"from __future__ import absolute_import\nfrom flask import url_for, render_template, redirect, abort, flash, request,\\\n Blueprint, current_app\nfrom flask_babel import gettext, lazy_gettext\nfrom flask_login import login_required, fresh_login_required, current_user\nfrom flask_wtf import Form\nimport six\nfrom six.moves import map\nfrom sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound\nfrom wtforms.fields import StringField, SubmitField, HiddenField, SelectField,\\\n Label\nfrom wtforms.validators import InputRequired, AnyOf, NumberRange\n\nfrom ..models import db\nfrom ..auth import PermissionType\nfrom ..auth.models import Division, Permission, Entity\nfrom ..util import jsonify, varies\n\n\nblueprint = Blueprint('divisions', __name__)\n\n\n@blueprint.route('/')\n@fresh_login_required\ndef permissions():\n \"\"\"Show a page listing all divisions.\n \"\"\"\n if current_user.admin:\n return render_template('divisions.html',\n divisions=Division.query.all())\n if current_user.has_permission(PermissionType.admin):\n admin_permissions = current_user.permissions.filter_by(\n permission=PermissionType.admin).values(Permission.division_id)\n admin_permissions = map(lambda x: x[0], admin_permissions)\n divisions = db.session.query(Division).\\\n filter(Division.id.in_(admin_permissions))\n return render_template('divisions.html', divisions=divisions)\n return render_template('permissions.html')\n return abort(403)\n\n\nclass AddDivisionForm(Form):\n # TRANS: On a form for creating a new division, this is a label for the\n # TRANS: name of the division.\n name = StringField(lazy_gettext(u'Division Name'),\n validators=[InputRequired()])\n\n # TRANS: On a form for creating a new division, this is a button for\n # TRANS: creating a new division (by submitting the form).\n submit = SubmitField(lazy_gettext(u'Create Division'))\n\n\n@blueprint.route('/add/', methods=['GET', 'POST'])\n@fresh_login_required\ndef add_division():\n \"\"\"Present a form for adding a division and also process that form.\n\n Only accesible to adminstrators.\n \"\"\"\n if not current_user.admin:\n return abort(403)\n form = AddDivisionForm()\n if form.validate_on_submit():\n division = Division(form.name.data)\n db.session.add(division)\n db.session.commit()\n return redirect(url_for('.get_division_details',\n division_id=division.id))\n return render_template('form.html', form=form,\n # TRANS: The title for a page for creating new divisions.\n title=gettext(u'Create Division'))\n\n\nclass ChangeEntity(Form):\n form_id = HiddenField(default='entity')\n id_ = HiddenField()\n name = StringField()\n permission = HiddenField(validators=[AnyOf(list(PermissionType.values()))])\n action = HiddenField(validators=[AnyOf(('add', 'delete'))])\n\n\n#: List of tuples enumerating attributes that can be transformed/linked.\n#: Mainly used as the choices argument to :py:class:`~.SelectField`\ntransformer_choices = [\n ('', u''),\n # TRANS: Label for fields showing the name of a pilot.\n ('pilot', lazy_gettext(u'Pilot')),\n # TRANS: Label for the corporation a pilot is in.\n ('corporation', lazy_gettext(u'Corporation')),\n # TRANS: Label for the alliance a pilot is in.\n ('alliance', lazy_gettext(u'Alliance')),\n # TRANS: Label for the solar system a loss occured in.\n ('system', lazy_gettext(u'Solar System')),\n # TRANS: Label for the constellation a loss occured in.\n ('constellation', lazy_gettext(u'Constellation')),\n # TRANS: Label for the region a loss occured in.\n ('region', lazy_gettext(u'Region')),\n # TRANS: Label for the type of ship that was lost.\n ('ship_type', lazy_gettext(u'Ship')),\n # TRANS: Label for the status a request is in (ex: Unevaluated, Approved)\n ('status', lazy_gettext(u'Request Status')),\n]\n\n\nclass ChangeTransformer(Form):\n form_id = HiddenField(default='transformer')\n\n # TRANS: The a label for a selection field for selecting which attribute\n # TRANS: to transform. See the translation for 'Attribute Transformer'.\n attribute = SelectField(lazy_gettext(u'Attribute'),\n choices=transformer_choices)\n\n # TRANS: The label for a selection field for selecting the transformer for\n # TRANS: an attribute. See the translation for 'Attribute Transformer'.\n transformer = SelectField(lazy_gettext(u'Transformer'), choices=[])\n\n\ndef transformer_choices(attr):\n \"\"\"Conveniece function for generating a list of transformer option tuples.\n\n :param attr str: the name of the attribute to make a list for.\n :return: A list of tuples suitable for the choices argument of\\\n :py:class:`StringField`\n :rtype: list\n \"\"\"\n default_transformers = [\n ('none', 'None'),\n ]\n choices = default_transformers\n if attr in current_app.url_transformers:\n for transformer in current_app.url_transformers[attr]:\n choices.append((transformer, transformer))\n return choices\n\n\n@blueprint.route('//', methods=['GET'])\n@fresh_login_required\n@varies('Accept', 'X-Requested-With')\ndef get_division_details(division_id=None, division=None):\n \"\"\"Generate a page showing the details of a division.\n\n Shows which groups and individuals have been granted permissions to each\n division.\n\n Only accesible to administrators.\n\n :param int division_id: The ID number of the division\n \"\"\"\n if division is None:\n division = Division.query.get_or_404(division_id)\n if not current_user.admin and not \\\n current_user.has_permission(PermissionType.admin, division):\n abort(403)\n if request.is_json or request.is_xhr:\n return jsonify(division._json(True))\n return render_template(\n 'division_detail.html',\n division=division,\n entity_form=ChangeEntity(formdata=None),\n transformer_form=ChangeTransformer(formdata=None),\n )\n\n\ndef _modify_division_entity(division):\n \"\"\"Handle POST requests for adding/removing entities form a Division.\"\"\"\n form = ChangeEntity()\n if form.validate():\n entity = None\n if form.id_.data != '':\n current_app.logger.debug(\"Looking up entity by ID: {}\".format(\n form.id_.data))\n entity = Entity.query.get(form.id_.data)\n if entity is None:\n # TRANS: This is an error message when there's a problem \n # TRANS: granting a permission to a user or group\n # TRANS: (collectively called 'entities'). The '#' is not\n # TRANS: special, but the '%s(in_num)d' will be replaced with\n # TRANS: the ID number that was attempted to be added.\n flash(gettext(u\"No entity with ID #%(id_num)d.\",\n id_num=form.id_.data),\n category=u'error')\n else:\n current_app.logger.debug(u\"Looking up entity by name: '{}'\"\\\n .format(form.name.data))\n try:\n entity = Entity.query.filter_by(\n name=form.name.data).one()\n except NoResultFound:\n # TRANS: Error message when a user or group with a given name\n # TRANS: cannot be found.\n flash(gettext(u\"No entities with the name '%(name)s' found.\",\n name=form.name.data),\n category=u'error')\n except MultipleResultsFound:\n # TRANS: Error message when multiple users and/or groups are\n # TRANS: found with a given name.\n flash(gettext(\n u\"Multiple entities with the name '%(name)s' found.\",\n name=form.name.data),\n category=u'error')\n else:\n current_app.logger.debug(\"entity lookup success\")\n if entity is None:\n return get_division_details(division=division), 404, None\n # The entity has been found, create the query for the requested\n # Permission.\n permission_type = PermissionType.from_string(\n form.permission.data)\n permission_query = Permission.query.filter_by(\n division=division,\n entity=entity,\n permission=permission_type)\n # The response for both add and delete actions depends on whether the\n # Permission is found, so look it up first.\n try:\n permission = permission_query.one()\n except NoResultFound:\n if form.action.data == 'add':\n db.session.add(\n Permission(division, permission_type, entity))\n # TRANS: Message show when granting a permission to a user or\n # TRANS: group.\n flash(gettext(u\"%(name)s is now a %(role)s.\",\n name=entity,\n role=permission_type.description.lower()),\n category=u\"info\")\n elif form.action.data == 'delete':\n # TRANS: Message shown when trying to remove a permission from\n # TRANS: a user, but that user didn't have that permission\n # TRANS: already.\n flash(gettext(u\"%(name)s is not a %(role)s.\",\n name=entity,\n role=permission_type.description.lower()),\n category=u\"warning\")\n else:\n if form.action.data == 'delete':\n permission_query.delete()\n # TRANS: Confirmation message shown when revoking a permission\n # TRANS: from a user or group.\n flash(gettext(u\"%(name)s is no longer a %(role)s.\",\n name=entity,\n role=permission_type.description.lower()),\n category=u\"info\")\n elif form.action.data == 'add':\n flash(gettext(u\"%(name)s is now a %(role)s.\",\n name=entity,\n role=permission_type.description.lower()),\n category=u\"info\")\n db.session.commit()\n else:\n for field_name, errors in six.iteritems(form.errors):\n errors = u\", \".join(errors)\n # TRANS: Error message that is shown when one or more fields of a\n # TRANS: form are shown.\n flash(gettext(u\"Errors for %(field_name)s: %(error)s.\",\n field_name=field_name, error=errors), u'error')\n current_app.logger.info(\"Malformed entity permission POST: {}\".format(\n form.errors))\n return get_division_details(division=division)\n\n\ndef _modify_division_transformer(division):\n \"\"\"Handle POST requests for changing the Transformers for a Division.\"\"\"\n form = ChangeTransformer()\n # Set the form's choices\n attr = form.attribute.data\n form.transformer.choices = transformer_choices(attr)\n # Check form and go from there\n if form.validate():\n name = form.transformer.data\n if name == 'none':\n division.transformers[attr] = None\n else:\n # Get the specific map of transformers for the attribute\n attr_transformers = current_app.url_transformers[attr]\n # Get the new transformer\n division.transformers[attr] = attr_transformers[name]\n # Explicitly add the TransformerRef to the session\n db.session.add(division.division_transformers[attr])\n db.session.commit()\n # TRANS: Confirmation message shown when a transformer for an\n # TRANS: attribute has been set.\n flash(gettext(u\"'%(attribute)s' set to '%(transformer)s'.\",\n attribute=attr, transformer=name), u'message')\n else:\n for field_name, errors in six.iteritems(form.errors):\n errors = u\", \".join(errors)\n # TRANS: Generic error message shown for the fields in a form.\n flash(gettext(u\"Errors for %(field_name)s: %(error)s.\",\n field_name=field_name, error=errors), u'error')\n current_app.logger.info(\"Malformed division transformer POST: {}\".\n format(form.errors))\n return get_division_details(division=division)\n\n\n@blueprint.route('//', methods=['POST'])\n@fresh_login_required\ndef modify_division(division_id):\n \"\"\"Dispatches modification requests to the specialized view function for\n that operation.\n \"\"\"\n division = Division.query.get_or_404(division_id)\n if not current_user.admin and not \\\n current_user.has_permission(PermissionType.admin, division):\n abort(403)\n form_id = request.form.get('form_id')\n if form_id == 'entity':\n return _modify_division_entity(division)\n elif form_id == 'transformer':\n return _modify_division_transformer(division)\n else:\n current_app.logger.warn(\"Invalid division modification POST: {}\"\n .format(request.form))\n abort(400)\n\n\n@blueprint.route('//transformers/')\n@blueprint.route('//transformers//')\n@login_required\ndef list_transformers(division_id, attribute=None):\n \"\"\"API method to get a list of transformers for a division.\n\n :param division_id int: the ID of the division to look up\n :param attribute str: a specific attribute to look up. Optional.\n :return: JSON\n \"\"\"\n division = Division.query.get_or_404(division_id)\n if not current_user.admin and not \\\n current_user.has_permission(PermissionType.admin, division):\n abort(403)\n if attribute is None:\n attrs = six.iterkeys(current_app.url_transformers)\n else:\n attrs = (attribute,)\n choices = {}\n for attr in attrs:\n raw_choices = transformer_choices(attr)\n current = division.transformers.get(attr, None)\n if current is not None:\n choices[attr] = \\\n [(c[0], c[1], c[1] == current.name) for c in raw_choices]\n else:\n choices[attr] = \\\n [(c[0], c[1], False) for c in raw_choices]\n return jsonify(choices)\n","sub_path":"src/evesrp/views/divisions.py","file_name":"divisions.py","file_ext":"py","file_size_in_byte":14237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"442577891","text":"from abc import ABC, abstractmethod\nfrom sympy import *\n\nt = Symbol('t')\n\n\nclass Joint(ABC):\n\n @abstractmethod\n def __init__(self, parent, child, xy):\n self.name = parent.name + '_' + child.name + '_joint'\n self.parent = parent\n self.child = child\n\n fx, fy, tau = symbols('fx_%s, fy_%s, tau_%s' %\n (self.name, self.name, self.name))\n\n self.fx = fx\n self.fy = fy\n self.tau = tau\n\n self.link1_offset_x, self.link1_offset_y = self.parent.xy_offset(xy)\n self.link2_offset_x, self.link2_offset_y = self.child.xy_offset(xy)\n # (dist1 - self.parent.length / 2) * sympy.cos(self.parent.theta(t))\n # self.link1_offset_y = (dist1 - self.parent.length / 2) * sympy.sin(self.parent.theta(t))\n # self.link2_offset_x = (dist2 - self.child.length / 2) * sympy.cos(self.child.theta(t))\n # self.link2_offset_y = (dist2 - self.child.length / 2) * sympy.sin(self.child.theta(t))\n\n self.mat_symbol1 = Symbol('parent_mat_%s' % self.name, commutative=False)\n self.mat_symbol2 = Symbol('child_mat_%s' % self.name, commutative=False)\n\n self._mat1 = None\n self.mat2 = None\n\n\nclass Hinge2D(Joint):\n\n def __init__(self, parent, child, dist1, dist2):\n super().__init__(parent, child, (0, 0))\n self.dist1 = dist1\n self.dist2 = dist2\n\n self.link1_offset_x = (dist1 - self.parent.length / 2) * cos(self.parent.theta(t))\n self.link1_offset_y = (dist1 - self.parent.length / 2) * sin(self.parent.theta(t))\n self.link2_offset_x = (dist2 - self.child.length / 2) * cos(self.child.theta(t))\n self.link2_offset_y = (dist2 - self.child.length / 2) * sin(self.child.theta(t))\n\n self.mat1 = Matrix([[1., 0., cos(self.parent.theta(t) + pi/2) / (self.parent.length / 2)],\n [0., 1., sin(self.parent.theta(t) + pi/2) / (self.parent.length / 2)],\n [-self.link1_offset_y, self.link1_offset_x, 0.25]])\n self.mat2 = Matrix([[-1., 0., -cos(self.child.theta(t) + pi/2) / (self.child.length / 2)],\n [0., -1., -sin(self.child.theta(t) + pi/2) / (self.child.length / 2)],\n [self.link2_offset_y, -self.link2_offset_x, -0.25]])\n","sub_path":"controls/joint.py","file_name":"joint.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"404868552","text":"__author__ = 'skv'\n\n\nimport talib\nimport yfinance as yf\nfrom patterns import candlestick_patterns\n\nimport matplotlib.pyplot as plt\nimport pandas\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\nbu_pt = [\"CDLHAMMER\", #looks good\n \"CDLINVERTEDHAMMER\", #looks good\n \"CDLPIERCING\",\n \"CDLENGULFING\",\n \"CDLHARAMI\", #detection not good\n \"CDLMORNINGDOJISTAR\"]\n\nbe_pt = ['CDLDOJISTAR', 'CDLHANGINGMAN', 'CDLSHOOTINGSTAR', 'CDLDARKCLOUDCOVER', 'CDLENGULFING', 'CDLEVENINGSTAR',\n 'CDLLONGLEGGEDDOJI', 'CDLTAKURI', \"CDLHARAMI\" ]\n\nselec_pt = [\n 'CDLHAMMER',\n 'CDLINVERTEDHAMMER',\n 'CDLDRAGONFLYDOJI',\n 'CDLENGULFING',\n 'CDLDARKCLOUDCOVER',\n 'CDLMORNINGDOJISTAR',\n 'CDLDOJI',\n 'CDLDOJISTAR',\n 'CDLEVENINGDOJISTAR',\n 'CDLEVENINGSTAR',\n 'CDLHANGINGMAN',\n 'CDLHARAMI',\n 'CDLLONGLEGGEDDOJI',\n 'CDLPIERCING',\n 'CDLSHOOTINGSTAR',\n 'CDLTAKURI'\n ]\n\ndef chart_with_volume(symbol, df, cs_patters, skip_bulls = False, skip_bears=True):\n\n candlestick = go.Candlestick(x=df['Date'], open=df['Open'], high=df['High'], low=df['Low'], close=df['Close'])\n\n #######################################################\n #ADD VOLUME\n\n #SET VOLUME COLORS\n INCREASING_COLOR = 'Green'\n DECREASING_COLOR = 'Red'\n\n colors = []\n\n for i in range(len(df.Close)):\n if i != 0:\n if df.Volume[i] > df.Volume[i - 1]:\n colors.append(INCREASING_COLOR)\n else:\n colors.append(DECREASING_COLOR)\n else:\n colors.append(DECREASING_COLOR)\n\n volume = go.Bar( x=df['Date'], y=df['Volume'] , marker_color=colors, name='Volume')\n #avg_volume = go.Scatter( x=df['Date'], y=df['AVG_VOLUME'],line=dict(color='royalblue', width=1), mode='lines', name='AvgVolume')\n\n ema13 = go.Scatter( x=df['Date'], y=df['EMA_13'],line=dict(color='red', width=2), mode='lines', name='ema13')\n ema26 = go.Scatter( x=df['Date'], y=df['EMA_26'],line=dict(color='green', width=2), mode='lines', name='ema26')\n\n MACD = go.Scatter( x=df['Date'], y=df['MACD'], line=dict(color='red', width=2), mode='lines', name='MACD')\n MACD_HIST = go.Bar( x=df['Date'], y=df['MACD_HIST'],name='MACD_HIST')\n\n #######################################################\n # Adding annotations for the high and low of the day.\n annotations = []\n\n count = 0\n arrow_color = {}\n for p in cs_patters:\n #if not p in selec_pt: continue\n #print(f\"p={p}\")\n\n x_vals_bull = df[\"Date\"][df[p] > 0]\n y_vals_bull = df[\"High\"][df[p] > 0]\n x_vals_bear = df[\"Date\"][df[p] < 0]\n y_vals_bear = df[\"High\"][df[p] < 0]\n\n if not skip_bulls:\n for x_val, y_val in zip(x_vals_bull, y_vals_bull):\n count +=1\n annotations.append(go.layout.Annotation(x=x_val,\n y=y_val,\n showarrow=True,\n arrowhead=3,\n arrowcolor='green',\n arrowsize=2,\n arrowwidth=1,\n text=f\"{p[3:]}\"))\n\n if not skip_bears:\n for x_val, y_val in zip(x_vals_bear, y_vals_bear):\n count +=1\n annotations.append(go.layout.Annotation(x=x_val,\n y=y_val,\n showarrow=True,\n arrowhead=3,\n arrowcolor='red',\n arrowsize=2,\n arrowwidth=1,\n text=f\"{p[3:]}\"))\n\n layout = dict(\n title=f'{symbol}',\n xaxis_rangeslider_visible=False,\n xaxis2_rangeslider_visible=False,\n xaxis3_rangeslider_visible=False,\n annotations=annotations,\n xaxis=dict(zerolinecolor='black', showticklabels=False),\n xaxis2=dict(showticklabels=False),\n xaxis3=dict(showticklabels=True),\n\n )\n\n fig = make_subplots(vertical_spacing=0, rows=3, cols=1, row_heights=[1, .3 , .3], shared_xaxes=True)\n\n fig.add_trace(candlestick, row=1, col=1)\n fig.add_trace(ema13, row=1, col=1)\n fig.add_trace(ema26, row=1, col=1)\n fig.add_trace(volume, row=3, col=1)\n #fig.add_trace(avg_volume, row=3, col=1)\n fig.add_trace(MACD_HIST, row=2, col=1)\n fig.add_trace(MACD, row=2, col=1)\n\n fig.update_layout(layout)\n\n fig.layout.xaxis.type = 'category' #disables weekends\n fig.layout.xaxis2.type = 'category' # disables weekends\n fig.layout.xaxis3.type = 'category' # disables weekends\n\n fig.show()\n #print(f'annotations = {count}')\n\ndef find_portfolio_one_cs():\n portfolio = [\"AMZN\", \"COF\", \"BA\", \"AAPL\", \"GOOG\"]\n dataframes = {}\n for symbol in portfolio:\n #df = yf.download(symbol, start=\"2020-01-01\", end=\"2020-08-01\")\n df = pandas.read_csv('datasets/daily/{}'.format(f'{symbol}.csv'))\n for pattern in selec_pt: #candlestick_patterns:\n #for pattern in bu_pt:\n pattern_function = getattr(talib, pattern)\n df[pattern] = pattern_function(df['Open'], df['High'], df['Low'], df['Close'])\n print(f\"-----------{pattern} days:-------\")\n p_days = df[df[pattern] != 0]\n print(df.loc[df[pattern] != 0].Date)\n print(p_days[pattern])\n dataframes[symbol] = df\n\n for pattern in selec_pt:\n print(f'showing {pattern}')\n for symbol in portfolio:\n print(f' -> of {symbol}')\n chart_with_volume(symbol, dataframes[symbol], [pattern])\n input('Type OK to go to next CS')\n\ndef find_all_on_single_stock():\n dataframes = {}\n symbol = \"SPY\"\n df = pandas.read_csv('datasets/3Yrs/{}'.format(f'{symbol}1.csv'))\n p_list = []\n\n for pattern in bu_pt: #candlestick_patterns:\n pattern_function = getattr(talib, pattern)\n df[pattern] = pattern_function(df['Open'], df['High'], df['Low'], df['Close'])\n print(f\"-----------{pattern} days:-------\")\n #print(pattern, \" : \", df[df[pattern] != 0][pattern])\n p_days = df[df[pattern] != 0]\n print(df.loc[df[pattern] != 0].Date)\n print(p_days[pattern])\n p_list.append(pattern)\n\n chart_with_volume(symbol, df, p_list)\n\n\ndef find_working_bulls_on_single_stock():\n symbol = \"AMZN\"\n df = pandas.read_csv('datasets/2018_2020Aug/{}'.format(f'{symbol}.csv'))\n p_list = []\n count =0\n for pattern in candlestick_patterns: #bu_pt\n pattern_function = getattr(talib, pattern)\n df[pattern] = pattern_function(df['Open'], df['High'], df['Low'], df['Close'])\n p_days = df[df[pattern] > 0]\n\n if len(p_days) >0:\n print(f\"\\n{pattern[3:]}, {symbol}({len(p_days)})\\n\")\n chart_with_volume(symbol, df, [pattern])\n count += 1\n if count%10==0:\n input(\"--More--\")\n\n\n\ndef find_all_bulls_on_single_stock():\n bull_patterns = [\"CDLENGULFING\", \"CDLBREAKAWAY\", \"CDL3OUTSIDE\",\n \"CDL3INSIDE\", \"CDLSTICKSANDWICH\", \"CDLPIERCING\",\n \"CDLMORNINGSTAR\",\"CDLGAPSIDESIDEWHITE\", \"CDLUNIQUE3RIVER\"]\n symbol = \"TWTR\"\n df = pandas.read_csv('datasets/daily/{}'.format(f'{symbol}.csv'))\n p_list = []\n patterns_found = []\n count = 0\n for pattern in bull_patterns: #bu_pt\n pattern_function = getattr(talib, pattern)\n df[pattern] = pattern_function(df['Open'], df['High'], df['Low'], df['Close'])\n p_days = df[df[pattern] > 0]\n if len(p_days) >0:\n patterns_found.append(pattern)\n print(f\"\\n{pattern[3:]}, {symbol}({len(p_days)})\\n\")\n chart_with_volume(symbol, df, patterns_found)\n\n\ndef finding_working_bears_on_single_stock():\n bear_paterns = [\"EVENINGDOJISTAR\", \"ENGULFING\", \"CLOSINGMARUBOZU\",\n \"HARAMICROSS\", \"EVENINGSTAR\", \"SPINNINGTOP\"]\n\n\n symbols = ['MSFT', 'TSLA', 'UBER', 'V', 'WMT']\n for symbol in symbols:\n df = pandas.read_csv('datasets/2018_2020Aug/{}'.format(f'{symbol}.csv'))\n count =0\n for pattern in candlestick_patterns:\n if pattern[3:] not in bear_paterns: continue\n\n pattern_function = getattr(talib, pattern)\n df[pattern] = pattern_function(df['Open'], df['High'], df['Low'], df['Close'])\n p_days = df[df[pattern] < 0]\n\n if len(p_days) > 0:\n print(f\"\\n{pattern[3:]} {symbol}({len(p_days)})\\n\")\n chart_with_volume(symbol, df, [pattern], skip_bulls=True, skip_bears=False)\n count += 1\n if count%10==0:\n input(\"--More--\")\n\n\n\ndef VPA_Candles():\n \"\"\"\n Chapter 6:\n • a rising market with falling volume is also a classic sign of weakness.\n\n 3 Main Candles:\n 1. Shooting Star - upper wick long, narrow body. weekness - increasing volume - 3 candles\n If the first candle was an initial sign of weakness, then the second, with increased volume\n is confirming this weakness further. If a third appears then this is adding yet more bearish sentiment.\n\n -only one stock found n had no impact\n\n 2. Hammer - reverse of shooting star - a low volume candle is indicating minor weakness,\n average volume suggests stronger signs of a possible reversal, whilst ultra high signals\n the insiders buying heavily, as part of the buying climax.\n\n Hanging man - same as hammer but at the top of bullish trend\n\n 3. Long Legged Doji - can signal a reversal from bearish to bullish, or bullish to bearish, and the change in\n direction depends on the preceding price action.\n should always be validated by a minimum of average volume, and preferably high or ultra high.\n If it is low, then it is an anomaly and therefore a trap set by the insiders.\n If the volume is high, we must be patient and wait for the subsequent price action to unfold.\n We may see further doji candles before the trend is established, so as always patience is required following\n their appearance. Wait for direction to be confirmed and established.\n\n\t4. Wide Spread Candles Price action – strong market sentiment\n 5. Narrow Spread Candles Price action – weak market sentiment\n 6. The Hanging Man Candle Price action – potential weakness after bullish trend\n The hanging man is validated if it is followed by the appearance of a shooting star in the next few candles,\n particularly if associated with above average or high volume. The key here is validation.\n On its own it is not a strong signal, but merely gives us early warning of a possible change.\n\n 6. Stopping Volume Price action - strength\n - falling and price spreads are narrows and volume is rising - bearish to bullish reversal\n\t7. Topping Out Volume Price action - weakness\n reverse of previous one - rising but narrowing, volume rising - bullish to bearish\n\n \"\"\"\n vpa_patterns = [\"CDLHAMMER\", \"CDLSHOOTINGSTAR\" , \"CDLHANGINGMAN\", \"CDLLONGLEGGEDDOJI\"]\n vpa_patterns1 = [\"CDLSHOOTINGSTAR\"]\n\n\n #symbols = ['AMZN', 'COF', 'MSFT', 'TSLA', 'UBER', 'V', 'WMT']\n symbols = ['SPY']\n\n for symbol in symbols:\n #df = pandas.read_csv('datasets/2018_2020Aug/{}'.format(f'{symbol}.csv'))\n df = pandas.read_csv('datasets/3Yrs/{}'.format(f'{symbol}.csv'))\n pattern_found = []\n pattern_function = getattr(talib, pattern)\n df[pattern] = pattern_function(df['Open'], df['High'], df['Low'], df['Close'])\n p_days = df[df[pattern] != 0]\n\n for pattern in candlestick_patterns:\n if pattern not in vpa_patterns1: continue\n\n pattern_function = getattr(talib, pattern)\n df[pattern] = pattern_function(df['Open'], df['High'], df['Low'], df['Close'])\n p_days = df[df[pattern] != 0]\n\n if len(p_days) > 0:\n pattern_found.append(pattern)\n print(f\"\\n{pattern[3:]} {symbol}({len(p_days)})\\n\")\n if len(pattern_found)>0:\n chart_with_volume(symbol, df, pattern_found, skip_bulls=False, skip_bears=False)\n\n\n\ndef detect_multiple_cs_with_rising_volume(df, pattern, req_stint):\n max_stint = 0\n stint = 0\n c = df.columns.get_loc(pattern)\n\n for i in range(1, len(df.Close)):\n if df[pattern][i] != 0 and \\\n df[pattern][i-1] !=0 and \\\n df.Volume[i] >= df.Volume[i-1] and \\\n df['Volume'][i] > df['AVG_VOLUME'][i]:\n stint += 1\n if stint > max_stint:\n max_stint = stint\n if max_stint>= req_stint: print(df['Date'][i], max_stint)\n else:\n # remove candles\n if i 0:\n max_stint, df = detect_multiple_cs_with_rising_volume(df, pattern, req_stint=3)\n if max_stint >= 2:\n print(f\"{symbol} - {pattern} found with max sting = {max_stint}\")\n pattern_found.append(pattern)\n if len(pattern_found)>0:\n chart_with_volume(symbol, df, pattern_found, skip_bulls=False, skip_bears=False)\n cnt +=1\n if cnt % 10 == 0:\n input(\"--More--\")\n\ndef detect_cs_with_rising_volume(factor, pattern, df):\n c = df.columns.get_loc(pattern)\n\n result = False\n for i in range(1, len(df.Close)):\n if df[pattern][i] != 0:\n if df['Volume'][i] >= df['AVG_VOLUME'][i]*factor and \\\n df['Volume'][i]>=df['Volume'][i-1]:\n result = True\n else: # remove candles\n df.iloc[i, c] = 0\n\n return result, df\n\ndef find_working_patterns_with_volume():\n bull_patterns = [\"CDLENGULFING\", \"CDLBREAKAWAY\", \"CDL3OUTSIDE\",\n \"CDL3INSIDE\", \"CDLSTICKSANDWICH\", \"CDLPIERCING\",\n \"CDLMORNINGSTAR\", \"CDLGAPSIDESIDEWHITE\", \"CDLUNIQUE3RIVER\"]\n bear_paterns = [\"CDLEVENINGDOJISTAR\", \"CDLENGULFING\", \"CDLCLOSINGMARUBOZU\",\n \"CDLHARAMICROSS\", \"CDLEVENINGSTAR\", \"CDLSPINNINGTOP\"]\n all_patterns = bull_patterns + bear_paterns\n\n \"\"\"\n symbols = []\n with open('datasets/symbols.csv') as f:\n for line in f:\n symbol = line.strip()\n symbols.append(symbol)\n\n \"\"\"\n symbols = ['NVDA', 'AMZN', 'COF']\n #['AMZN', 'COF',\n #'MSFT', 'TSLA', 'UBER', 'V', 'WMT', 'GOOG', 'AAPL',\n #'AAL', 'ADBE', 'BA', 'MGM', 'NVDA', 'ORCL', 'SBX', 'TWTR', 'FB']\n\n from os import path\n cnt = 0\n\n for symbol in symbols:\n file_path = f'datasets/daily/{symbol}.csv'\n if not path.exists(file_path):\n print(f\"data for {symbol} not found\")\n continue\n df = pandas.read_csv(file_path)\n if df.empty:\n print(f\"data for {symbol} is empty\")\n continue\n\n pattern_found = []\n\n df['AVG_VOLUME'] = df['Volume'].rolling(window=13).mean()\n\n #df['SMA_13'] = df['Close'].rolling(window=13).mean()\n #df['SMA_26'] = df['Close'].rolling(window=26).mean()\n df['EMA_13'] = talib.EMA(df['Close'], 13)\n df['EMA_26'] = talib.EMA(df['Close'], 26)\n macd, macdsignal, macdhist = talib.MACD(df['Close']) #default: fastperiod=12, slowperiod=26, signalperiod=9)\n df['MACD'] = macd\n df['MACD_HIST'] = macdhist\n\n\n #pattern_found = []\n for pattern in all_patterns:\n pattern_function = getattr(talib, pattern)\n df[pattern] = pattern_function(df['Open'], df['High'], df['Low'], df['Close'])\n p_days = df[df[pattern] != 0]\n if len(p_days) > 0:\n found, df = detect_cs_with_rising_volume(3, pattern, df)\n if found: pattern_found.append(pattern)\n chart_with_volume(symbol, df, pattern_found, skip_bulls=False, skip_bears=False)\n cnt +=1\n if cnt % 10 == 0:\n input(\"--More--\")\n\n\ndef chart_without_indicators(symbol, df, cs_patters, skip_bulls = False, skip_bears=False):\n\n candlestick = go.Candlestick(x=df['Date'], open=df['Open'], high=df['High'], low=df['Low'], close=df['Close'])\n\n #######################################################\n #ADD VOLUME\n\n #SET VOLUME COLORS\n INCREASING_COLOR = 'Green'\n DECREASING_COLOR = 'Red'\n\n colors = []\n\n for i in range(len(df.Close)):\n if i != 0:\n if df.Volume[i] > df.Volume[i - 1]:\n colors.append(INCREASING_COLOR)\n else:\n colors.append(DECREASING_COLOR)\n else:\n colors.append(DECREASING_COLOR)\n\n volume = go.Bar( x=df['Date'], y=df['Volume'] , marker_color=colors, name='Volume')\n\n\n #######################################################\n # Adding annotations for the high and low of the day.\n annotations = []\n\n count = 0\n arrow_color = {}\n for p in cs_patters:\n #if not p in selec_pt: continue\n #print(f\"p={p}\")\n\n x_vals_bull = df[\"Date\"][df[p] > 0]\n y_vals_bull = df[\"High\"][df[p] > 0]\n x_vals_bear = df[\"Date\"][df[p] < 0]\n y_vals_bear = df[\"High\"][df[p] < 0]\n\n if not skip_bulls:\n for x_val, y_val in zip(x_vals_bull, y_vals_bull):\n count +=1\n annotations.append(go.layout.Annotation(x=x_val,\n y=y_val,\n showarrow=True,\n arrowhead=3,\n arrowcolor='green',\n arrowsize=2,\n arrowwidth=1,\n text=f\"{p[3:]}\"))\n\n if not skip_bears:\n for x_val, y_val in zip(x_vals_bear, y_vals_bear):\n count +=1\n annotations.append(go.layout.Annotation(x=x_val,\n y=y_val,\n showarrow=True,\n arrowhead=3,\n arrowcolor='red',\n arrowsize=2,\n arrowwidth=1,\n text=f\"{p[3:]}\"))\n\n layout = dict(\n title=f'{symbol}',\n xaxis_rangeslider_visible=False,\n xaxis2_rangeslider_visible=False,\n xaxis3_rangeslider_visible=False,\n annotations=annotations,\n xaxis=dict(zerolinecolor='black', showticklabels=False),\n xaxis2=dict(showticklabels=True),\n xaxis3=dict(showticklabels=True),\n\n )\n\n fig = make_subplots(vertical_spacing=0, rows=2, cols=1, row_heights=[1, .3], shared_xaxes=True)\n\n fig.add_trace(candlestick, row=1, col=1)\n fig.add_trace(volume, row=2, col=1)\n fig.update_layout(layout)\n\n fig.layout.xaxis.type = 'category' #disables weekends\n fig.layout.xaxis2.type = 'category' # disables weekends\n\n fig.show()\n #print(f'annotations = {count}')\n\ndef finding_cs_pattern():\n from commons import get_data\n from datetime import date, timedelta\n\n today = date.today().strftime(\"%m-%d-%Y\")\n print(today)\n a_year = (date.today() - timedelta(days=12 * 30)).strftime(\"%m-%d-%Y\")\n\n cs_patterns = [\"CDLHAMMER\", \"CDLINVERTEDHAMMER\"]\n symbols = ['SPY']\n #symbols = ['SPY', 'JPM','COF', 'UBER', 'TSLA', 'AMZN', 'NVDA', 'AAPL', 'WMT','GOOG', 'MSFT'] #, 'AMZN', 'COF', 'MSFT', 'TSLA', 'UBER', 'V', 'WMT', 'GOOG', 'AAPL']\n\n for symbol in symbols:\n #df = pandas.read_csv('datasets/daily/{}'.format(f'{symbol}.csv'))\n #df = get_data(symbol, a_year, today, show=False)\n df = yf.download(\"SPY\", start=\"2020-01-01\", end=\"2020-08-01\")\n\n count =0\n for pattern in cs_patterns: #bu_pt: #\n pattern_function = getattr(talib, pattern)\n print(pattern_function)\n df[pattern] = pattern_function(df['Open'], df['High'], df['Low'], df['Close'])\n\n p_days = df[df[pattern] < 0]\n\n if len(p_days) > 0:\n print(f\"\\n{pattern[3:]} {symbol}({len(p_days)})\\n\")\n chart_without_indicators(symbol, df, [pattern], skip_bulls=False, skip_bears=False)\n count += 1\n if count%10==0:\n input(\"--More--\")\n else:\n print(f\"{pattern[3:]} {symbol} not found\")\n\n\ndef finding_cs_pattern2():\n from commons import get_data\n from datetime import date, timedelta\n\n today = date.today().strftime(\"%m-%d-%Y\")\n print(today)\n a_year = (date.today() - timedelta(days=12 * 30)).strftime(\"%m-%d-%Y\")\n\n #cs_patterns = [\"CDLHAMMER\", \"CDLINVERTEDHAMMER\"]\n cs_patterns = [\"CDLHAMMER\"]\n\n symbols = ['ROKU']\n #symbols = ['SPY', 'JPM','COF', 'UBER', 'TSLA', 'AMZN', 'NVDA', 'AAPL', 'WMT','GOOG', 'MSFT'] #, 'AMZN', 'COF', 'MSFT', 'TSLA', 'UBER', 'V', 'WMT', 'GOOG', 'AAPL']\n\n for symbol in symbols:\n #df = pandas.read_csv('datasets/daily/{}'.format(f'{symbol}.csv'))\n df = get_data(symbol, a_year, today, show=False)\n for pattern in bu_pt: #cs_patterns:\n print(pattern)\n pattern_function = getattr(talib, pattern)\n df[pattern] = pattern_function(df['Open'], df['High'], df['Low'], df['Close'])\n\n count = 0\n p_days = df[df[pattern] != 0]\n print(p_days)\n if len(p_days) > 0:\n print(f\"\\n{pattern[3:]} {symbol}({len(p_days)})\\n\")\n chart_without_indicators(symbol, df, [pattern], skip_bulls=False, skip_bears=False)\n count += 1\n if count % 10 == 0:\n input(\"--More--\")\n else:\n print(f\"{pattern[3:]} {symbol} not found\")\n\n\n\nif __name__ == \"__main__\":\n #finding_working_bears_on_single_stock()\n #find_working_patterns_with_volume()\n finding_cs_pattern2()\n","sub_path":"mine_find_patterns.py","file_name":"mine_find_patterns.py","file_ext":"py","file_size_in_byte":24338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"489373818","text":"import unittest\n\n\ndef build_linked_list(x):\n\n if x == 0:\n l = ListNode(0)\n return l\n\n digit = 10\n values = []\n while x != 0:\n n = x % digit\n values.append(n)\n x = x // 10\n\n l = h = ListNode(values[0])\n if values[1:]:\n for i in values[1:]:\n l1 = ListNode(i)\n l.next = l1\n l = l1\n return h\n\n\nclass TestCase(unittest.TestCase):\n def test_input1(self):\n\n # l1 = build_linked_list(0)\n # l2 = build_linked_list(0)\n # r = Solution().addTwoNumbers(l1, l2)\n # import ipdb; ipdb.set_trace()\n\n # l1 = build_linked_list(342)\n # l2 = build_linked_list(465)\n # r = Solution().addTwoNumbers(l1, l2)\n # #self.assertEqual(807, r)\n\n l1 = build_linked_list(81)\n l2 = build_linked_list(0)\n\n self.assertEqual(499,\n Solution().addTwoNumbers(l1, l2))\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n\n def create_stack(self, l):\n s = []\n while l:\n s.append(l.val)\n l = l.next\n return s[::-1]\n\n def addTwoNumbers(self, l1, l2):\n import ipdb; ipdb.set_trace()\n s1 = self.create_stack(l1)\n s2 = self.create_stack(l2)\n import ipdb; ipdb.set_trace()\n digit = 1\n total = 0\n while s1 and s2:\n x1 = s1.pop()\n x2 = s2.pop()\n\n total = total + ((x1 + x2) * digit)\n digit *= 10\n\n remaining_stack = s1 or s2\n for i in remaining_stack[::-1]:\n total += (i * digit)\n digit *= 10\n return build_linked_list(total)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"leetcode/2_add_two_numbers.py","file_name":"2_add_two_numbers.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"168546910","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nTransform PDF to non-segmented-paragraph text.\n\nCreated on Tue Aug 28 2018\n\n@author: dang\n\nExample: (remember to put file names with space in double quote)\npython pdf2txt_dang.py \"A.\\ Lightman\\ -\\ Einstein\\'s\\ Dreams.pdf\" Einstein_Dreams.txt\n\"\"\"\n\nimport sys\nimport os\nimport re\n\nsearch_series = [u'’', \n u'“',\n u'”',\n u'•',\n u'ÃŒ']\nreplace_series = [u'’',\n u'“',\n u'”',\n u'•',\n u'ü']\n\nsource_file = str(sys.argv[1])\nif len(sys.argv) >= 3:\n result_file = str(sys.argv[2])\n\nconvert_command = 'pdftotext ' + source_file + ' ' + result_file\nprint(convert_command)\nos.system(convert_command)\n\nwith open(result_file,'rt') as text_file:\n text = text_file.read().decode('utf-8')\n\nprint('Replacing special characters...')\nfor k in range(len(search_series)):\n text = text.replace(search_series[k], replace_series[k])\n\n#print('Removing page numbers...')\n#page_number_pattern = r'(\\s{2,}[0-9]+\\/203\\s{2,})'\f\n#text = re.sub(page_number_pattern, ' ', text)\n\nprint('Correcting diary dates...')\ndate_pattern = r'(\\d+) *\\.\\s+([A-Z]+)\\s+([I1]9[O0]5)'\ntext = re.sub(date_pattern, '* \\g<1>. \\g<2> 1905', text)\n\nprint('Re-joining sentences by deleting unnecessary line breaks...')\nreplace_pattern = r'([^\\.\\d\\n])\\n+(.)'\ntext = re.sub(replace_pattern, '\\g<1> \\g<2>', text)\n\nwith open(result_file,'wt') as new_text_file:\n new_text_file.write(text.encode('utf-8'))\nprint('Done')\n","sub_path":"python/songngu_data/rework_dang_einsteinsdream_de.py","file_name":"rework_dang_einsteinsdream_de.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"4310130","text":"import sys\nimport matplotlib.pyplot as plt\nimport logging\nlogger = logging.getLogger(__name__)\nsys.path.append('./')\nimport os\nimport time\nimport numpy as np\nfrom collections import namedtuple\nimport yaml\nimport random\nimport faulthandler\n\nimport utils\nfrom solver.gpr_dc import VFI_iter\nfrom models.dc_simple import DCSimple\n\n_ITER_LOG_STR = \"\"\"\n===============================================================\nComputation of a lifetime consumption with retirement model\nfinished after %d steps\n===============================================================\n\"\"\"\n\n\ndef diagnostic_plots(X, y_f, y_u, V, P, t, plot_out, lb=0.1, ub=500):\n fig = plt.figure(figsize=(10, 25))\n\n # Value Function\n ax = plt.subplot(3, 1, 1)\n ax.set_title('Value Function (T=%d)' % t)\n utils.plot.plot_function(V, 0.01, 500, 'Assets', 'Value', None, True)\n utils.plot.plot_vals(X, y_f, 'Assets', 'Value', None, True)\n\n # Plot Policy Worker\n ax = plt.subplot(3, 1, 2)\n ax.set_title('Policy for Worker')\n utils.plot.plot_function(P, lb, ub, 'Assets', 'Consumption', 1, False)\n utils.plot.plot_vals(X, y_u, 'Assets', 'Consumption', 1, False)\n\n # Plot Policy Retired\n ax = plt.subplot(3, 1, 3)\n ax.set_title('Policy for Retiree')\n utils.plot.plot_function(P, lb, ub, 'Assets', 'Consumption', 0, False)\n utils.plot.plot_vals(X, y_u, 'Assets', 'Consumption', 0, False)\n\n fig.tight_layout()\n plt.savefig(plot_out)\n plt.close()\n\n\ndef configure_run(run_config):\n utils.plot.configure()\n utils.make_directory(run_config['odir'])\n\n with open(os.path.join(run_config['odir'], 'run_config.yaml'), 'w') as fp:\n yaml.dump(run_config, fp, default_flow_style=False)\n\n log_level = logging.DEBUG if run_config['debug'] else logging.INFO\n if not run_config['terminal']:\n logging.basicConfig(\n filename=os.path.join(run_config['odir'], 'progress.log'),\n level=log_level,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n )\n else:\n logging.basicConfig(level=log_level)\n\n # TODO: Check seeding with numpy, torch -- I don't think it will seed correctly as is\n if run_config['seed'] is not None:\n random.seed(run_config['seed'])\n\n log_str = '\\r\\n###################################################\\r\\n' + \\\n '\\tModel: %s\\r\\n' % run_config['model'].name + \\\n '###################################################'\n logger.info(log_str)\n\n\ndef fit_model(run_config):\n start = time.time()\n model_spec = run_config['model']\n algorithm_config = run_config['algorithm_config']\n parameters = model_spec.parameters\n model = DCSimple(parameters)\n\n v_fstr = '%s/value_%%d.pcl' % (run_config['odir'])\n plot_fstr = '%s/diagnostic_plots_%%d.pdf' % (run_config['odir'])\n p_fstr = '%s/policy_%%d.pcl' % (run_config['odir'])\n vals_fstr = '%s/%%s_%%d.pcl' % (run_config['odir'])\n V_tp1, V_t = None, None\n\n # Value Function Iteration\n for i in range(parameters.T, 0, -1):\n # import pdb; pdb.set_trace()\n V_tp1 = V_t\n logger.info(\"Value Function Iteration -- Step %d\" % i)\n V_t, P_t, X, y_f, y_u = VFI_iter(\n model, V_tp1, num_samples=algorithm_config.No_samples)\n V_t.save(v_fstr % i)\n P_t.save(p_fstr % i)\n utils.save_value(X, vals_fstr % ('X', i))\n utils.save_value(y_u, vals_fstr % ('y_u', i))\n utils.save_value(y_f, vals_fstr % ('y_f', i))\n diagnostic_plots(X, y_f, y_u, V_t, P_t, i, plot_fstr % i)\n\n logger.info(_ITER_LOG_STR % run_config['max_updates'])\n\n # Compute Value function errors, write to disk\n plots_path = '%s/plot_value.pdf' % (run_config['odir'])\n\n end = time.time()\n logger.info('Time elapsed: %.3f' % (end - start))\n\n\nif __name__ == \"__main__\":\n faulthandler.enable()\n parser = utils.run.gpr_argparser(default_spec='./specs/simple_dc.yaml')\n args = parser.parse_args()\n run_config = utils.run.run_config_from_args(args)\n configure_run(run_config)\n fit_model(run_config)\n","sub_path":"bin/fit_gpr_dc.py","file_name":"fit_gpr_dc.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"204347608","text":"import argparse\nimport sys\nfrom obspy.core.utcdatetime import UTCDateTime\nfrom obspy import read\n\nfrom utils.ini_tools import parse_ini\nimport utils.seisan_tools as st\nimport utils.predict_tools as pt\nfrom utils.converter import date_str\nfrom utils.progress_bar import ProgressBar\n\n# Silence tensorflow warnings\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n# Default params\ndefault_model_weights = {\n 'favor': 'weights/w_model_performer_with_spec.hd5',\n 'cnn': 'weights/weights_model_cnn_spec.hd5'\n}\n\nday_length = 60. * 60 * 24\n\n# TODO: Make sure every parameter is used!\nparams = {\n 'config': 'config.ini',\n 'channel_order': ['N', 'E', 'Z'],\n 'threshold': 0.95,\n 'mulplt': None,\n 'batch_size': 500_000,\n 'shift': 10,\n 'start': None,\n 'end': None,\n 'slice_range': 2., # seconds before and after event\n 'archive_path': None,\n 's_path': None,\n 'seisan': None,\n 'frequency': 100.,\n 'out': 'noise',\n 'debug': False,\n 'favor': False,\n 'cnn': False,\n 'weights': None,\n 'out_hdf5': 'data.h5',\n 'p_event_before': 10.,\n 'p_event_after': 60. * 60 * 1,\n 's_event_before': 60. * 10,\n 's_event_after': 60. * 10,\n 'default_event_before': 60. * 60 * 1,\n 'default_event_after': 60. * 60 * 1,\n 'model_labels': {'p': 0, 's': 1, 'n': 2},\n 'positive_labels': {'p': 0, 's': 1}\n}\n\n# Only this params can be set via script arguments\nparam_aliases = {\n 'config': ['--config', '-c'],\n 'threshold': ['--threshold'],\n 'mulplt': ['--mulplt'],\n 'batch_size': ['--batch-size'],\n 'shift': ['--shift'],\n 'start': ['--start', '-s'],\n 'end': ['--end', '-e'],\n 'slice_range': ['--slice_range', '--range'],\n 'archive_path': ['--archive_path', '-a'],\n 's_path': ['--s_path'],\n 'seisan': ['--seisan'],\n 'out': ['--out', '-o'],\n 'debug': ['--debug', '-d'],\n 'favor': ['--favor'],\n 'cnn': ['--cnn'],\n 'weights': ['--weights', '-w']\n}\n\n# Help messages\nparam_help = {\n 'config': 'Path to .ini config file',\n 'threshold': 'Positive prediction threshold, default: 0.95',\n 'mulplt': 'Path to MULPLT.DEF file',\n 'batch_size': 'Batch size for sliding windows memory, default: 500 000 samples',\n 'shift': 'Sliding window shift, default: 10 samples (ms)',\n 'start': 'start date in ISO 8601 format:\\n'\n '{year}-{month}-{day}T{hour}:{minute}:{second}.{microsecond}\\n'\n 'or\\n'\n '{year}-{month}-{day}T{hour}:{minute}:{second}\\n'\n 'or\\n'\n '{year}-{month}-{day}\\n'\n 'default: beginning of this month',\n 'end': 'end date in ISO 8601 format:\\n'\n '{year}-{month}-{day}T{hour}:{minute}:{second}.{microsecond}\\n'\n 'or\\n'\n '{year}-{month}-{day}T{hour}:{minute}:{second}\\n'\n 'or\\n'\n '{year}-{month}-{day}\\n'\n 'default: now',\n 'slice_range': 'Slicing range in seconds before and after wave arrival',\n 'archive_path': 'Path to Seisan archive directory',\n 's_path': 'Path to s-files database directory (e.g. \"/seismo/seisan/REA/IMGG_/\")',\n 'seisan': 'Path to SEISAN.DEF',\n 'out': 'Output path, default: \"wave_picks\"',\n 'debug': 'Enable debug info output',\n 'favor': 'Load fast-attention Seismo-Transformer',\n 'cnn': 'Load fast-attention Seismo-Transformer with CNN',\n 'weights': 'Path to model weights file'\n}\n\n# Param actions\nparam_actions = {\n 'debug': 'store_true',\n 'favor': 'store_true',\n 'cnn': 'store_true'\n}\n\n\nif __name__ == '__main__':\n\n # Setup argument parser\n parser = argparse.ArgumentParser(description='Seisan database waveform picker, creates ' +\n 'a h5 dataset with P, S and Noise waveforms stored. ' +\n 'Or append if dataset file already created.',\n formatter_class=argparse.RawTextHelpFormatter)\n\n for k in param_aliases:\n\n if k in param_actions:\n parser.add_argument(*param_aliases[k], help=param_help[k], action = param_actions[k])\n else:\n parser.add_argument(*param_aliases[k], help=param_help[k])\n\n args = parser.parse_args()\n args = vars(args)\n\n params_set = []\n\n for k in args:\n\n if args[k] is not None:\n params[k] = args[k]\n params_set.append(k)\n\n params = parse_ini(params['config'], params_set, params=params)\n\n # Convert types\n params['threshold'] = float(params['threshold'])\n\n # Parse dates\n def parse_date_param(d_params, name):\n\n if name not in d_params:\n return None\n if d_params[name] is None:\n return None\n\n try:\n return UTCDateTime(d_params[name])\n except Exception:\n print(f'Failed to parse {name}, value: {d_params[name]}.')\n\n\n start_date = parse_date_param(params, 'start')\n end_date = parse_date_param(params, 'end')\n\n if end_date is None:\n end_date = UTCDateTime()\n if start_date is None:\n start_date = UTCDateTime() - 30 * 24 * 60 * 60\n\n # Parse MULPLT.DEF\n mulplt_parsed = st.parse_mulplt(params['mulplt'])\n\n # Parse stations\n stations = st.process_seisan_def_mulplt(params['seisan'], mulplt_parsed)\n stations = st.order_stations(stations, params['channel_order'])\n\n # Fix archive_path\n if params['archive_path'][-1] != '/':\n params['archive_path'] += '/'\n\n # Fix s-files dir path\n if params['s_path'][-1] != '/':\n params['s_path'] += '/'\n\n # Batch size fix\n params['batch_size'] = int(params['batch_size'])\n params['shift'] = int(params['shift'])\n\n # Initialize output directory\n if not os.path.isdir(params['out']):\n\n if os.path.isfile(params['out']):\n print(f'--out: {params[\"out\"]} is not a directory!')\n sys.exit(0)\n\n os.makedirs(params['out'])\n\n if params['out'][-1] != '/':\n params['out'] += '/'\n\n # Loading model\n from models import seismo_load\n\n if params['favor']:\n print('Loading fast-attention Seismo-Transformer')\n # Check model weights\n if not params['weights']:\n if not default_model_weights['favor']:\n raise AttributeError('No model weights provided!')\n else:\n params['weights'] = default_model_weights['favor']\n\n model = seismo_load.load_performer(params['weights'])\n elif params['cnn']:\n print('Loading fast-attention Seismo-Transformer with CNN')\n # Check model weights\n if not params['weights']:\n if not default_model_weights['cnn']:\n raise AttributeError('No model weights provided!')\n else:\n params['weights'] = default_model_weights['cnn']\n\n model = seismo_load.load_cnn(params['weights'])\n else:\n raise AttributeError('No model specified!')\n\n # Prepare for archive files gathering\n current_dt = start_date\n\n current_end_dt = UTCDateTime(date_str(current_dt.year, current_dt.month, current_dt.day, 23, 59, 59))\n if end_date.year == current_dt.year and end_date.julday == current_dt.julday:\n current_end_dt = end_date\n\n if params['debug']:\n print(f'DEBUG: start = {start_date}',\n f'DEBUG: end = {end_date}', sep='\\n')\n\n current_month = -1\n s_events = []\n true_positives = []\n\n while current_dt < end_date:\n\n if params['debug']:\n print(f'DEBUG: current_date = {current_dt} current_end_date: {current_end_dt}')\n\n # Parse all s_files once per month\n if current_dt.month != current_month:\n s_base_path = params['s_path']\n s_base_path += f'{current_dt.year:0>4d}/{current_dt.month:0>2d}/'\n current_month = current_dt.month\n s_events = st.parse_s_dir(s_base_path, stations, params)\n\n if s_events is None:\n continue\n\n # Add time_span for every event\n true_positives = []\n for event_file in s_events:\n for event_group in event_file:\n for event in event_group:\n\n event_time = event['utc_datetime']\n\n if not event_time:\n continue\n\n if event['phase'] == 'P':\n event['time_span'] = (event_time - params['p_event_before'],\n event_time + params['p_event_after'])\n elif event['phase'] == 'S':\n event['time_span'] = (event_time - params['s_event_before'],\n event_time + params['s_event_after'])\n else:\n event['time_span'] = (event_time - params['default_event_before'],\n event_time + params['default_event_after'])\n\n true_positives.append(event['time_span'])\n\n if not s_events:\n s_events = []\n if not true_positives:\n true_positives = []\n\n # Filter out today's true_positives\n current_true_positives = []\n for span_start, span_end in true_positives:\n\n is_in = False\n if current_dt <= span_start and span_end <= current_end_dt:\n is_in = True\n elif span_start < current_dt < span_end:\n is_in = True\n elif span_start < current_end_dt < span_end:\n is_in = True\n\n if is_in:\n current_true_positives.append((span_start, span_end))\n\n # Predict\n # TODO: Read archives for every group, var name: stations (code for archive path get from model integration)\n # TODO: Then read archives, trim archives\n # TODO: Write function which takes time span and arrays of current_true_positives time spans and returns\n # array of timespans to which i should cut the base timespan.\n\n progress_bar = ProgressBar()\n\n progress_bar.set_length(60)\n\n progress_bar.set_empty_character('.')\n progress_bar.set_progress_character('=')\n progress_bar.set_current_progress_char('>')\n\n progress_bar.set_prefix_expression('Station {station} out of {n_stations} [')\n progress_bar.set_postfix_expression('] - Batch: {start} - {end}')\n progress_bar.set_prefix_arg('n_stations', len(stations))\n\n progress_bar.set_max(stations = len(stations), streams = 1., traces = 1., batches = 1., inter = 1.)\n\n for i_station, archive_list in enumerate(stations):\n\n progress_bar.set_progress(i_station, level = 'stations')\n progress_bar.set_prefix_arg('station', i_station + 1)\n\n # Archives path and meta data\n archive_data = st.archive_to_path(archive_list, current_dt,\n params['archive_path'],\n params['channel_order'])\n\n # Check if streams path are valid\n from os.path import isfile\n valid = True\n for channel in params['channel_order']:\n if not isfile(archive_data[channel]):\n valid = False\n break\n\n if not valid:\n continue\n\n # Read data\n streams = {}\n try:\n for channel in params['channel_order']:\n streams[channel] = read(archive_data[channel])\n except Exception: # TODO: Replace with less general built-in exceptions\n continue\n\n streams = pt.preprocess_streams(streams, current_dt, current_end_dt, current_true_positives) # preprocess data\n\n progress_bar.change_max('streams', len(streams))\n progress_bar.set_progress(0, level = 'streams')\n\n for i_stream, stream_group in enumerate(streams):\n\n progress_bar.set_progress(i_stream, level = 'streams')\n\n try:\n group_scores = pt.predict_streams(model, stream_group,\n params = params, progress_bar = progress_bar)\n except AttributeError:\n continue\n except ValueError:\n continue\n\n # FOR EVERY STREAM GROUP:\n # Check if stream traces number is equal\n # Per every trace:\n # Count batches\n # Loop for every batch, maybe, do this in separate function:\n # Predict. Find peaks. Find positives. Save them into h5py.\n\n print()\n\n # Shift date\n current_dt += 24 * 60 * 60\n current_end_dt = UTCDateTime(date_str(current_dt.year, current_dt.month, current_dt.day, 23, 59, 59))\n current_dt = UTCDateTime(date_str(current_dt.year, current_dt.month, current_dt.day))\n\n if end_date.year == current_dt.year and end_date.julday == current_dt.julday:\n current_end_dt = end_date\n","sub_path":"false_positives_picker.py","file_name":"false_positives_picker.py","file_ext":"py","file_size_in_byte":13105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"332298679","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Setup and run MOPAC\"\"\"\n\nimport logging\nimport seamm\nimport seamm_util.printing as printing\nfrom seamm_util import units_class\nfrom seamm_util.printing import FormattedText as __\nimport mopac_step\n\nlogger = logging.getLogger(__name__)\njob = printing.getPrinter()\nprinter = printing.getPrinter(\"mopac\")\n\n\nclass Optimization(mopac_step.Energy):\n def __init__(self, flowchart=None, title=\"Optimization\", extension=None):\n \"\"\"Initialize the node\"\"\"\n\n logger.debug(\"Creating Optimization {}\".format(self))\n\n super().__init__(flowchart=flowchart, title=title, extension=extension)\n\n self.parameters = mopac_step.OptimizationParameters()\n\n self.description = \"A structural optimization\"\n\n def description_text(self, P=None):\n \"\"\"Prepare information about what this node will do\"\"\"\n\n if not P:\n P = self.parameters.values_to_dict()\n\n # Hamiltonian followed by convergence\n text = \"Geometry optimization using {hamiltonian}\"\n if P[\"method\"] == \"default\":\n text += (\n \" and default optimizer (EF for small systems,\" \" L-BFGS for larger).\"\n )\n elif P[\"method\"][0:1] == \"EF\":\n text += \" and the eigenvector following (EF) method.\"\n elif P[\"method\"][0:3] == \"BFGS\":\n text += \" and the BFGS method.\"\n elif P[\"method\"][0:5] == \"L-BFGS\":\n text += \" and the L-BFGS small memory version of the BFGS method.\"\n else:\n text += (\n \". The optimization method will be determined at runtime \"\n \"by '{method}'.\"\n )\n\n if P[\"gnorm\"] == \"default\":\n text += \" The geometrical convergence is the default of \" \"1.0 kcal/mol/Å.\"\n elif P[\"gnorm\"][0] == \"$\":\n text += (\n \" The geometrical convergence will be determined \"\n \"at runtime by '{gnorm}'.\"\n )\n else:\n text += \" The geometrical convergence is {gnorm} kcal/mol/Å.\"\n\n # SCF convergence\n text += \" The SCF will be converged to \"\n if P[\"convergence\"] == \"normal\":\n text += \"the normal level of 1.0e-04 kcal/mol.\"\n elif P[\"convergence\"] == \"precise\":\n text += \"the 'precise' level of 1.0e-06 kcal/mol.\"\n elif P[\"convergence\"] == \"relative\":\n text += \"a factor of {relative} times the normal criteria.\"\n elif P[\"convergence\"] == \"absolute\":\n text += \" {absolute} kcal/mol.\"\n\n handling = P[\"structure handling\"]\n text += \" The optimized structures will \"\n if handling == \"Overwrite the current configuration\":\n text += \"overwrite the current configuration \"\n elif handling == \"Create a new configuration\":\n text += \"be put in a new configuration \"\n else:\n raise ValueError(\n f\"Do not understand how to handle the structure: '{handling}'\"\n )\n\n confname = P[\"configuration name\"]\n if confname == \"use SMILES string\":\n text += \"using SMILES as its name.\"\n elif confname == \"use Canonical SMILES string\":\n text += \"using canonical SMILES as its name.\"\n elif confname == \"keep current name\":\n text += \"keeping the current name.\"\n elif confname == \"optimized with \":\n text += \"with 'optimized with {hamiltonian}' as its name.\"\n elif confname == \"use configuration number\":\n text += \"using the index of the configuration (1, 2, ...) as its name.\"\n else:\n text += \"with '{confname}' as its name.\"\n\n return self.header + \"\\n\" + __(text, **P, indent=4 * \" \").__str__()\n\n def get_input(self):\n \"\"\"Get the input for an optimization MOPAC\"\"\"\n\n references = self.parent.references\n bibliography = self.parent._bibliography\n\n P = self.parameters.current_values_to_dict(\n context=seamm.flowchart_variables._data\n )\n\n # Have to fix formatting for printing...\n PP = dict(P)\n for key in PP:\n if isinstance(PP[key], units_class):\n PP[key] = \"{:~P}\".format(PP[key])\n\n # Save the description for later printing\n self.description = []\n self.description.append(\n __(self.description_text(PP), **PP, indent=self.indent).__str__()\n )\n\n # Remove the 1SCF keyword from the energy setup\n keywords = []\n for keyword in super().get_input():\n if keyword != \"1SCF\":\n keywords.append(keyword)\n\n # and the optimization-specific parts\n method = P[\"method\"]\n if method == \"default\":\n pass\n elif method[0:2] == \"EF\":\n keywords.append(\"EF\")\n if P[\"recalc\"] != \"never\":\n keywords.append(P[\"recalc\"])\n if str(P[\"dmax\"]) != self.parameters[\"dmax\"].default:\n keywords.append(\"DMAX={}\".format(P[\"dmax\"]))\n references.cite(\n raw=bibliography[\"Baker_1986\"],\n alias=\"Baker_1986\",\n module=\"mopac_step\",\n level=1,\n note=\"Eigenvector-following minimizer.\",\n )\n elif method[0:4] == \"BFGS\":\n keywords.append(\"BFGS\")\n references.cite(\n raw=bibliography[\"Broyden_1970\"],\n alias=\"Broyden_1970\",\n module=\"mopac_step\",\n level=1,\n note=\"Broyden-Fletcher-Goldfarb-Shanno (BFGS) minimizer.\",\n )\n references.cite(\n raw=bibliography[\"Fletcher_1970\"],\n alias=\"Fletcher_1970\",\n module=\"mopac_step\",\n level=1,\n note=\"Broyden-Fletcher-Goldfarb-Shanno (BFGS) minimizer.\",\n )\n references.cite(\n raw=bibliography[\"Goldfarb_1970\"],\n alias=\"Goldfarb_1970\",\n module=\"mopac_step\",\n level=1,\n note=\"Broyden-Fletcher-Goldfarb-Shanno (BFGS) minimizer.\",\n )\n references.cite(\n raw=bibliography[\"Shanno_1970\"],\n alias=\"Shanno_1970\",\n module=\"mopac_step\",\n level=1,\n note=\"Broyden-Fletcher-Goldfarb-Shanno (BFGS) minimizer.\",\n )\n references.cite(\n raw=bibliography[\"Thiel_1988\"],\n alias=\"Thiel_1988\",\n module=\"mopac_step\",\n level=1,\n note=\"Broyden-Fletcher-Goldfarb-Shanno (BFGS) minimizer.\",\n )\n elif method[0:6] == \"L-BFGS\":\n keywords.append(\"LBFGS\")\n references.cite(\n raw=bibliography[\"Nocedal_1980\"],\n alias=\"Nocedal_1980\",\n module=\"mopac_step\",\n level=1,\n note=\"Limited-memory BFGS (L-BFGS) minimizer.\",\n )\n elif method[0:2] == \"TS\":\n keywords.append(\"TS\")\n references.cite(\n raw=bibliography[\"Baker_1986\"],\n alias=\"Baker_1986\",\n module=\"mopac_step\",\n level=1,\n note=\"Eigenvector-following minimizer for transition states.\",\n )\n elif method[0:5] == \"SIGMA\":\n keywords.append(\"SIGMA\")\n references.cite(\n raw=bibliography[\"McIver_1971\"],\n alias=\"McIver_1971\",\n module=\"mopac_step\",\n level=1,\n note=\"Gradient-norm minimizer for transition states.\",\n )\n references.cite(\n raw=bibliography[\"McIver_1972\"],\n alias=\"McIver_1972\",\n module=\"mopac_step\",\n level=1,\n note=\"Gradient-norm minimizer for transition states.\",\n )\n elif method[0:5] == \"NLLSQ\":\n keywords.append(\"NLLSQ\")\n references.cite(\n raw=bibliography[\"Bartels_1972\"],\n alias=\"Bartels_1972\",\n module=\"mopac_step\",\n level=1,\n note=\"NLLSQ gradient-norm minimizer for transition states.\",\n )\n else:\n text = \"Don't recognize optimization method '{}'\".format(P[\"method\"])\n logger.critical(text)\n raise RuntimeError(text)\n\n if P[\"cycles\"] != \"unlimited\":\n keywords.append(\"CYCLES={}\".format(P[\"cycles\"]))\n if P[\"convergence\"] == \"absolute\":\n if P[\"gnorm\"] != self.parameters[\"gnorm\"].default:\n keywords.append(\"GNORM={}\".format(P[\"gnorm\"]))\n\n return keywords\n\n def analyze(self, indent=\"\", data={}, out=[]):\n \"\"\"Parse the output and generating the text output and store the\n data in variables for other stages to access\n \"\"\"\n\n # Get the parameters used\n P = self.parameters.current_values_to_dict(\n context=seamm.flowchart_variables._data\n )\n\n # Update the structure\n if \"ATOM_X_OPT\" in data:\n system, starting_configuration = self.get_system_configuration(None)\n periodicity = starting_configuration.periodicity\n if (\n \"structure handling\" in P\n and P[\"structure handling\"] == \"Create a new configuration\"\n ):\n configuration = system.create_configuration(\n periodicity=periodicity,\n atomset=starting_configuration.atomset,\n bondset=starting_configuration.bondset,\n cell_id=starting_configuration.cell_id,\n )\n configuration.charge = starting_configuration.charge\n configuration.spin_multiplicity = (\n starting_configuration.spin_multiplicity\n )\n else:\n configuration = starting_configuration\n\n if periodicity != 0:\n raise NotImplementedError(\"Optimization cannot yet handle periodicity\")\n xyz = []\n it = iter(data[\"ATOM_X_OPT\"])\n for x in it:\n xyz.append([float(x), float(next(it)), float(next(it))])\n configuration.atoms.set_coordinates(xyz, fractionals=False)\n\n # And the name of the configuration.\n if \"configuration name\" in P:\n if P[\"configuration name\"] == \"optimized with \":\n configuration.name = f\"optimized with {P['hamiltonian']}\"\n elif P[\"configuration name\"] == \"keep current name\":\n pass\n elif P[\"configuration name\"] == \"use SMILES string\":\n configuration.name = configuration.smiles\n elif P[\"configuration name\"] == \"use Canonical SMILES string\":\n configuration.name = configuration.canonical_smiles\n elif P[\"configuration name\"] == \"use configuration number\":\n configuration.name = str(configuration.n_configurations)\n\n # The results\n if \"NUMBER_SCF_CYCLES\" in data:\n text = (\n \"The geometry optimization converged in \"\n \"{NUMBER_SCF_CYCLES} iterations to a heat of \"\n \"formation of {HEAT_OF_FORMATION} kcal/mol and \"\n \"gradient norm of {GRADIENT_NORM} kcal/mol/Å.\"\n )\n else:\n data[\"NUMBER_SCF_CYCLES\"] = len(data[\"HEAT_OF_FORM_UPDATED\"])\n data[\"HEAT_OF_FORMATION\"] = data[\"HEAT_OF_FORM_UPDATED\"][-1]\n data[\"GRADIENT_NORM\"] = data[\"GRADIENT_UPDATED\"][-1]\n text = (\n \"The geometry optimization did not converge!\\n\"\n \"It ran for {NUMBER_SCF_CYCLES} \"\n \"iterations to a final heat of formation of \"\n \"{HEAT_OF_FORMATION} kcal/mol and gradient norm \"\n \"of {GRADIENT_NORM} kcal/mol/Å.\"\n )\n\n if \"POINT_GROUP\" in data:\n text += \" The system has {POINT_GROUP} symmetry.\"\n\n printer.normal(__(text, **data, indent=self.indent + 4 * \" \"))\n\n # Put any requested results into variables or tables\n self.store_results(\n data=data,\n properties=mopac_step.properties,\n results=self.parameters[\"results\"].value,\n create_tables=self.parameters[\"create tables\"].get(),\n )\n\n # If the optimizer used was the default, put in the correct citations\n\n references = self.parent.references\n bibliography = self.parent._bibliography\n\n P = self.parameters.current_values_to_dict(\n context=seamm.flowchart_variables._data\n )\n\n if P[\"method\"] == \"default\":\n tmp = \"\\n\".join(out)\n if (\n \"GEOMETRY OPTIMISED USING EIGENVECTOR FOLLOWING (EF)\" in tmp\n or \"Geometry optimization using EF\" in tmp\n ):\n references.cite(\n raw=bibliography[\"Baker_1986\"],\n alias=\"Baker_1986\",\n module=\"mopac_step\",\n level=1,\n note=\"Eigenvector-following minimizer.\",\n )\n elif (\n \"Geometry optimization using BFGS\" in tmp or \"SATISFIED IN BFGS\" in tmp\n ):\n references.cite(\n raw=bibliography[\"Broyden_1970\"],\n alias=\"Broyden_1970\",\n module=\"mopac_step\",\n level=1,\n note=\"Broyden-Fletcher-Goldfarb-Shanno (BFGS) minimizer.\",\n )\n references.cite(\n raw=bibliography[\"Fletcher_1970\"],\n alias=\"Fletcher_1970\",\n module=\"mopac_step\",\n level=1,\n note=\"Broyden-Fletcher-Goldfarb-Shanno (BFGS) minimizer.\",\n )\n references.cite(\n raw=bibliography[\"Goldfarb_1970\"],\n alias=\"Goldfarb_1970\",\n module=\"mopac_step\",\n level=1,\n note=\"Broyden-Fletcher-Goldfarb-Shanno (BFGS) minimizer.\",\n )\n references.cite(\n raw=bibliography[\"Shanno_1970\"],\n alias=\"Shanno_1970\",\n module=\"mopac_step\",\n level=1,\n note=\"Broyden-Fletcher-Goldfarb-Shanno (BFGS) minimizer.\",\n )\n references.cite(\n raw=bibliography[\"Thiel_1988\"],\n alias=\"Thiel_1988\",\n module=\"mopac_step\",\n level=1,\n note=\"Broyden-Fletcher-Goldfarb-Shanno (BFGS) minimizer.\",\n )\n else:\n logger.warning(\"Could not find which minimizer was used!\")\n","sub_path":"mopac_step/optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":15024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"284208039","text":"# -*- coding: utf-8 -*-\n# @author: yangyd\n# @file: qcd_home_page.py\n# @time: 2019/9/11 21:57\n\n\nimport time\nfrom appium.webdriver import Remote\nfrom common.app_operate import AppOperate\n\ncaps = {\n \"platformName\": \"Android\",\n \"platformVersion\": \"5.1\",\n \"deviceName\": \"Android Emulator\",\n \"appActivity\": \"com.xxzb.fenwoo.activity.addition.WelcomeActivity\",\n \"appPackage\": \"com.xxzb.fenwoo\",\n \"noReset\": \"False\"\n}\n\nandroid_driver = Remote(desired_capabilities=caps)\n\nandroid_driver.implicitly_wait(10)\n\ndo_app = AppOperate(android_driver)\n\n# 获取手机的尺寸\n# phone_size = android_driver.get_window_size()\n\n# 等待启动\ntime.sleep(2)\nfor i in range(4):\n do_app.swipe_left()\n time.sleep(1)\n\n# 点击立即体检进入首页\n# android_driver.find_element_by_id(\"com.xxzb.fenwoo:id/btn_start\").click()\n\nandroid_driver.find_element_by_android_uiautomator(\n 'new UiSelector().resourceId(\"com.xxzb.fenwoo:id/btn_start\")').click()\n\nandroid_driver.find_element_by_android_uiautomator(\n 'new UiSelector().text(\"项目\")').click()\n# 进入登陆界面\n# android_driver.start_activity(\"com.xxzb.fenwoo\", \".activity.addition.LoginActivity\")\ntime.sleep(1)\ndo_app.get_screenshot(r'test.png')\ntime.sleep(1)\n\ndo_app.app_quit()\n","sub_path":"APP_Auto_Test/study_code/qcd_home_page.py","file_name":"qcd_home_page.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"380844609","text":"#!/usr/bin/env python\n# Copyright (c) 2007-8 Qtrac Ltd. All rights reserved.\n# This program or module is free software: you can redistribute it and/or\n# modify it under the terms of the GNU General Public License as published\n# by the Free Software Foundation, either version 2 of the License, or\n# version 3 of the License, or (at your option) any later version. It is\n# provided for educational purposes and is distributed in the hope that\n# it will be useful, but WITHOUT ANY WARRANTY; without even the implied\n# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\n# the GNU General Public License for more details.\n\nimport sys\nimport time\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\n\napp = QApplication(sys.argv)\n\ntry:\n due = QTime.currentTime()\n message = \"Alert!\"\n if len(sys.argv) < 2:\n raise ValueError\n hours, mins = sys.argv[1].split(\":\")\n due = QTime(int(hours), int(mins))\n if not due.isValid():\n raise ValueError\n if len(sys.argv) > 2:\n message = \" \".join(sys.argv[2:])\nexcept ValueError:\n message = \"Usage: alert.pyw HH:MM [optional message]\" # 24hr clock\n\nwhile QTime.currentTime() < due:\n time.sleep(20) # 20 seconds\n\nlabel = QLabel(\"\" + message + \"\")\nlabel.setWindowFlags(Qt.SplashScreen)\nlabel.show()\nQTimer.singleShot(60000, app.quit) # 1 minute\napp.exec_()\n\n","sub_path":"chap04/alert.py","file_name":"alert.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"268318455","text":"\"\"\"\nThis script has the image preprocessing utility functions\n\"\"\"\nfrom scipy import ndimage\nfrom skimage import measure, feature, morphology, segmentation\nimport matplotlib.pyplot as plt\nfrom skimage import img_as_ubyte\nimport numpy as np\nimport cv2\nimport pandas as pd\n\nMIN_BOUND = -1000.0\nMAX_BOUND = 400.0\nPIXEL_MEAN = 0.25\n\ndef normalize(image):\n \"\"\"\n Min-max image scaling\n :source: https://www.kaggle.com/gzuidhof/data-science-bowl-2017/full-preprocessing-tutorial/notebook\n :param image: a numpy array containing image pixel values\n :return: a numpy array containing the image pixel values normalized in the range [MIN_BOUND, MAX_BOUND]\n \"\"\"\n image = (image - MIN_BOUND) / (MAX_BOUND - MIN_BOUND)\n image[image>(1-PIXEL_MEAN)] = 1.\n image[image<(0-PIXEL_MEAN)] = 0.\n return image\n\ndef resample(image, scan):\n \"\"\"\n Resampling to account for different image resolutions\n :param image: a 3d numpy array containing the image pixel values\n :param scan: metadata about the image\n :return: 3d numpy array of the resampled scan\n \"\"\"\n # Determine current pixel spacing\n resize_factor = np.array([scan[0].SliceThickness] + scan[0].PixelSpacing, dtype=np.float32)\n\n new_shape = np.round(image.shape * resize_factor)\n real_resize_factor = new_shape / image.shape\n\n image = ndimage.interpolation.zoom(image, real_resize_factor, mode='nearest')\n\n return image\n\ndef audit_segmentation(im):\n \"\"\"\n Performs check on image segmentation as a quick check to make sure there wasn't a serious error\n :param im: a numpy array containing the image pixel values for a binary image\n :return: tuple containing the %pixels that are 0/1 and assessment of segmenting algorithm\n \"\"\"\n good_segmentation = True\n vals, counts = np.unique(im.flatten(), return_counts=True)\n counts = counts/np.sum(counts)\n\n num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(img_as_ubyte(im), 8, cv2.CV_32S)\n\n if num_labels not in [2, 3]:\n good_segmentation = False\n elif np.amax(counts) > 0.9:\n good_segmentation = False\n elif counts[0] > 0.9:\n good_segmentation = False\n\n return counts, good_segmentation\n\ndef get_dicom_info(slices):\n \"\"\"\n Get some attributes from the DICOM files\n :param slices: dicom files for patient\n :return: dictionary of attributes - age, gender, etc.\n \"\"\"\n attributes = {'age': slices[0].get('PatientAge'),\n 'gender': slices[0].get('PatientSex')\n }\n return attributes\n\ndef get_pixels_hu(slices):\n \"\"\"\n Convert pixel values to HU scale\n :source: https://www.kaggle.com/gzuidhof/data-science-bowl-2017/full-preprocessing-tutorial/notebook\n :param slices: list of dicom images and metadata\n :return: a 3d numpy array of pixel values for all slices for the patient\n \"\"\"\n image = np.stack([s.pixel_array for s in slices])\n\n # Convert to int16 (from sometimes int16),\n # should be possible as values should always be low enough (<32k)\n image = image.astype(np.int16)\n\n # Set outside-of-scan pixels to 0\n # The intercept is usually -1024, so air is approximately 0\n outside_image = np.amin(image)\n image[image == outside_image] = 0\n\n # Convert to Hounsfield units (HU)\n for slice_number in range(len(slices)):\n\n intercept = slices[slice_number].RescaleIntercept\n slope = slices[slice_number].RescaleSlope\n\n if slope != 1:\n image[slice_number] = slope * image[slice_number].astype(np.float64)\n image[slice_number] = image[slice_number].astype(np.int16)\n\n image[slice_number] += np.int16(intercept)\n\n return np.array(image, dtype=np.int16)\n\ndef watershed_lung_segmentation_image(image):\n \"\"\"\n A method using watershed algorithm to perform segmentation. seems to be pretty accurate, but is really slow\n :source: https://www.kaggle.com/ankasor/data-science-bowl-2017/improved-lung-segmentation-using-watershed\n :param image: 2d numpy array of an image slice\n :return:\n \"\"\"\n def generate_markers(image):\n # Creation of the internal Marker\n marker_internal = image < -400\n marker_internal = segmentation.clear_border(marker_internal)\n marker_internal_labels = measure.label(marker_internal)\n areas = [r.area for r in measure.regionprops(marker_internal_labels)]\n areas.sort()\n if len(areas) > 2:\n for region in measure.regionprops(marker_internal_labels):\n if region.area < areas[-2]:\n for coordinates in region.coords:\n marker_internal_labels[coordinates[0], coordinates[1]] = 0\n marker_internal = marker_internal_labels > 0\n # Creation of the external Marker\n external_a = ndimage.binary_dilation(marker_internal, iterations=10)\n external_b = ndimage.binary_dilation(marker_internal, iterations=55)\n marker_external = external_b ^ external_a\n # Creation of the Watershed Marker matrix\n marker_watershed = np.zeros(image.shape, dtype=np.int)\n marker_watershed += marker_internal * image.shape[0]\n marker_watershed += marker_external * int(np.ceil(image.shape[1]/2.))\n\n return marker_internal, marker_external, marker_watershed\n\n # Creation of the markers as shown above:\n marker_internal, marker_external, marker_watershed = generate_markers(image)\n\n # Creation of the Sobel-Gradient\n sobel_filtered_dx = ndimage.sobel(image, 1)\n sobel_filtered_dy = ndimage.sobel(image, 0)\n sobel_gradient = np.hypot(sobel_filtered_dx, sobel_filtered_dy)\n sobel_gradient *= image.shape[0] / np.max(sobel_gradient)\n\n # Watershed algorithm\n watershed = morphology.watershed(sobel_gradient, marker_watershed)\n\n # Reducing the image created by the Watershed algorithm to its outline\n outline = ndimage.morphological_gradient(watershed, size=(3, 3))\n outline = outline.astype(bool)\n\n # Performing Black-Tophat Morphology for reinclusion\n # Creation of the disk-kernel and increasing its size a bit\n blackhat_struct = [[0, 0, 1, 1, 1, 0, 0],\n [0, 1, 1, 1, 1, 1, 0],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [0, 1, 1, 1, 1, 1, 0],\n [0, 0, 1, 1, 1, 0, 0]]\n blackhat_struct = ndimage.iterate_structure(blackhat_struct, 8)\n # Perform the Black-Hat\n outline += ndimage.black_tophat(outline, structure=blackhat_struct)\n\n # Use the internal marker and the Outline that was just created to generate the lungfilter\n lungfilter = np.bitwise_or(marker_internal, outline)\n # Close holes in the lungfilter\n # fill_holes is not used here, since in some slices the heart would be reincluded by accident\n lungfilter = ndimage.morphology.binary_closing(lungfilter, structure=np.ones((5, 5)), iterations=3)\n\n # Apply the lungfilter (note the filtered areas being assigned -2000 HU)\n segmented = np.where(lungfilter == 1, image, -2000 * np.ones(image.shape))\n\n return segmented, lungfilter\n\ndef fast_lung_segment(image, fill_lung_structures=True):\n \"\"\"\n My attempts to improve segmented_lung_mask. Tweaked code above using some other examples online and info from CV/CP\n Perform segmentation of lungs in image much better and faster than method above\n :param image: numpy array of pixel values\n :param fill_lung_structures: boolean of whether to perform connected component algorithm on image\n :return: numpy array representing a binary image of thresholded pixel values\n \"\"\"\n binary_image = cv2.threshold(image, -300, 255, cv2.THRESH_BINARY)[1].astype(np.uint8)\n\n im2, contours, _ = cv2.findContours(binary_image,cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n largest_contour = max(contours, key=cv2.contourArea)\n mask = np.zeros(binary_image.shape, np.uint8)\n cv2.fillPoly(mask, [largest_contour], 255)\n\n binary_image = ~binary_image\n binary_image[(mask == 0)] = 0\n\n # apply closing to the mask\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (13, 13))\n binary_image = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, kernel)\n binary_image = cv2.morphologyEx(binary_image, cv2.MORPH_DILATE, kernel)\n binary_image = cv2.morphologyEx(binary_image, cv2.MORPH_DILATE, kernel)\n binary_image = cv2.morphologyEx(binary_image, cv2.MORPH_CLOSE, kernel)\n binary_image = cv2.morphologyEx(binary_image, cv2.MORPH_CLOSE, kernel)\n binary_image = cv2.morphologyEx(binary_image, cv2.MORPH_ERODE, kernel)\n binary_image = cv2.morphologyEx(binary_image, cv2.MORPH_ERODE, kernel)\n image[binary_image==0] = 0\n return image, binary_image\n\ndef lung_segmentation(scan, resize_image, method=1, depth=30, normalize_image=True):\n \"\"\"\n Runs segment_lung_mask3 for all images in a scan\n :param scan: 3d numpy array containing image scan pixel values\n :param depth: returns the size of the stack of image slices returned - 'median' for middle slice, int for # of most filled slices, None for average of all slices\n :param resize_image: tuple of desired image shape. None for the original size\n :param normalize_image: boolean of whether the image should be normalized. min-max scaling and 0-centered\n :return: 2d or 3d numpy array with lungs segmented, also returns lung volume for patient\n \"\"\"\n if resize_image is not None:\n segmented = np.zeros((scan.shape[0],)+resize_image)\n else:\n segmented = np.zeros(scan.shape)\n lung_volumes = np.zeros(scan.shape[0])\n for i in range(scan.shape[0]):\n segment, filter = fast_lung_segment(scan[i, :, :])\n counts, good_segmentation = audit_segmentation(filter)\n if not good_segmentation:\n segment, filter = watershed_lung_segmentation_image(scan[i, :, :])\n counts, good_segmentation = audit_segmentation(filter)\n if resize_image is not None:\n segment = cv2.resize(segment, resize_image, interpolation=cv2.INTER_CUBIC)\n if normalize_image:\n segment = normalize(segment)\n segmented[i,:,:] = segment\n lung_volumes[i] = counts[0]\n\n lung_volume = np.sum(1. - lung_volumes)\n\n segmented_out = {1:None, 2:None, 3:None, 4:None, 5:None, 6:None}\n\n if 1 in method:\n if depth > 0: #return image stack of most filled in lungs of specified depth\n lung_volume_ma = pd.rolling_mean(lung_volumes, depth)\n idx = np.argmin(lung_volume_ma[depth:]) + depth\n lower = idx\n upper = min(idx+depth, segmented.shape[0]) +4\n\n if min(upper, segmented.shape[0]) - idx != depth:\n upper = int(segmented.shape[0]/2)+15\n lower = int(segmented.shape[0]/2)-15\n\n segmented_out[1] = segmented[lower:upper,:,:]\n if 2 in method: #return average of all slices\n segmented_out[2] = np.mean(segmented, axis=0)\n if 3 in method: #return only middle slice\n segmented_out[3] = segmented[int(segmented.shape[0]/2.),:,:]\n if 4 in method:\n idx = np.unique(np.linspace(0,segmented.shape[0],num=depth+1).astype(np.int))\n segmented_accumulator = np.zeros((depth,)+resize_image)\n for i in range(len(idx)-1):\n lower = idx[i]\n upper = idx[i+1]\n segmented_accumulator[i, :, :] = np.mean(segmented[lower:upper,:,:], axis=0)\n segmented_out[4] = segmented_accumulator\n if 5 in method:\n segmented_out[5] = segmented\n if 6 in method:\n segmented_out[6] = []\n seq = np.arange(0, segmented.shape[0],3)\n for i in range(len(seq)-1):\n segmented_out[6].append(segmented[seq[i]:seq[i+1],:,:])\n\n return segmented_out, lung_volume\n\ndef extra_features(slice, scan, pixel_spacing):\n \"\"\"\n Method calculated the amount of blood, water, and fat in an image\n Values from https://en.wikipedia.org/wiki/Hounsfield_scale\n :source: Idea expanded from https://www.kaggle.com/kmader/data-science-bowl-2017/simple-single-image-features-for-cancer\n :param in_dcm: 2d numpy array. image slice\n :return: dataframe with volume in image slice containing each feature\n \"\"\"\n feature_list = {\n 'blood': (30, 45),\n 'bone': (700, 3000),\n 'emphysema': (900, 950),\n 'fat': (-100, -50),\n 'muscle': (10, 40),\n 'soft tissue': (100, 300),\n 'water': (-10, 10)\n }\n pix_area = np.prod(pixel_spacing)\n\n features = {}\n\n for key, value in feature_list.items():\n features[key] = [pix_area * np.sum((slice >= value[0]) & (slice <= value[1]))]\n\n other_features = get_dicom_info(scan)\n features.update(other_features)\n\n features = pd.DataFrame(features)\n\n return features\n\n\ndef make_mask(center,diam,width,height,spacing,origin,depth, v_center, num_z, reshape=None):\n \"\"\"\n source: https://github.com/booz-allen-hamilton/DSB3Tutorial/blob/master/tutorial_code/LUNA_mask_extraction.py\n Center : centers of circles px -- list of coordinates x,y,z\n diam : diameters of circles px -- diameter\n widthXheight : pixel dim of image\n spacing = mm/px conversion rate np array x,y,z\n origin = x,y,z mm np.array\n z = z position of slice in world coordinates mm\n \"\"\"\n masks = np.zeros([depth, height, width])\n def get_2d_mask(center, diam, z, width, height, spacing, origin):\n mask = np.zeros([height, width]) # 0's everywhere except nodule swapping x,y to match img\n # convert to nodule space from world coordinates\n\n # Defining the voxel range in which the nodule falls\n v_center = (center - origin) / spacing\n v_diam = int(diam / spacing[0] + 5)\n v_xmin = np.max([0, int(v_center[0] - v_diam) - 5])\n v_xmax = np.min([width - 1, int(v_center[0] + v_diam) + 5])\n v_ymin = np.max([0, int(v_center[1] - v_diam) - 5])\n v_ymax = np.min([height - 1, int(v_center[1] + v_diam) + 5])\n\n v_xrange = range(v_xmin, v_xmax + 1)\n v_yrange = range(v_ymin, v_ymax + 1)\n\n # Fill in 1 within sphere around nodule\n for v_x in v_xrange:\n for v_y in v_yrange:\n p_x = spacing[0] * v_x + origin[0]\n p_y = spacing[1] * v_y + origin[1]\n if np.linalg.norm(center - np.array([p_x, p_y, z])) <= diam:\n mask[int((p_y - origin[1]) / spacing[1]), int((p_x - origin[0]) / spacing[0])] = 1.0\n return mask\n\n for i, i_z in enumerate(np.arange(int(v_center[2]) - 1, int(v_center[2]) + 2).clip(0, num_z - 1)): # clip prevents going out of bounds in Z\n mask = get_2d_mask(center, diam, i_z * spacing[2] + origin[2], width, height, spacing, origin)\n masks[i,:,:] = mask\n\n if reshape is not None:\n zoom = np.array(reshape)/np.array(masks.shape)\n masks = ndimage.interpolation.zoom(masks, zoom, mode='nearest')\n masks[masks>0.1] = 1.0\n masks[masks!=1.0] = 0.0\n\n return masks\n\ndef resize(image, output_size):\n \"\"\"\n resize an image\n :param image: input array\n :param output_size: output size (tuple). same dimension as input size\n :return: resized image array\n \"\"\"\n zoom = np.array(output_size) / np.array(image.shape)\n return ndimage.interpolation.zoom(image, zoom, mode='nearest')\n","sub_path":"code_for_submission/image_processing/ImageProcessUtils.py","file_name":"ImageProcessUtils.py","file_ext":"py","file_size_in_byte":15327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"594886973","text":"def cadastrar_cliente(cod_cliente, nome, cpf, data_nascimento, estado, cep, bairro, rua, numero_casa, complemento):\n cliente = {\"cod_cliente\": cod_cliente, \"nome\": nome, \"cpf\": cpf, \"data_nascimento\": data_nascimento, \"estado\": estado, \"cep\": cep, \"bairro\": bairro, \"rua\": rua, \"numero_casa\": numero_casa, \"complemento\": complemento}\n salvar(cliente)\n\ndef salvar(cliente):\n arquivo = open(\"clientes.csv\", \"a\")\n resultado = \"\"\n for chave in cliente:\n resultado += chave + \";\"\n arquivo.write(resultado)\n\n arquivo.close()\n\n\nif __name__ == \"__main__\":\n perguntas = [\"Codigo Cliente: \", \"Nome: \", \"CPF: \", \"Data de Nascimento: \", \"Estado: \", \"CEP: \", \"Bairro: \", \"Rua: \", \"Numero da casa: \", \"Complemento: \"]\n respostas = []\n\n for pergunta in perguntas:\n resposta = input(pergunta)\n respostas.append(resposta)\n\n cadastrar_cliente(respostas[0], respostas[1], respostas[2], respostas[3], respostas[4], respostas[5], respostas[6], respostas[7], respostas[8], respostas[9])\n","sub_path":"Aula17/exe6.py","file_name":"exe6.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"427264215","text":"#!/usr/bin/python3\n#\n# Copyright (c) 2012 Mikkel Schubert \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\nimport copy\n\nfrom paleomix.node import Node\nfrom paleomix.common.fileutils import move_file, reroot_path, describe_files\nfrom paleomix.common.formats.msa import MSA\nfrom paleomix.common.formats.phylip import interleaved_phy\n\nfrom paleomix.common.utilities import safe_coerce_to_frozenset, safe_coerce_to_tuple\n\n\n_VALID_KEYS = frozenset([\"partitions\", \"filenames\"])\n\n\nclass FastaToPartitionedInterleavedPhyNode(Node):\n def __init__(\n self,\n infiles,\n out_prefix,\n exclude_groups=(),\n reduce=False,\n dependencies=(),\n file_dependencies=(),\n ):\n \"\"\"\n infiles = {names : {\"partitions\" : ..., \"filenames\" : [...]}}\n \"\"\"\n if not (\n isinstance(infiles, dict)\n and all(isinstance(dd, dict) for dd in infiles.values())\n ):\n raise TypeError(\"'infiles' must be a dictionary of dictionaries\")\n\n input_filenames = []\n for (name, subdd) in infiles.items():\n if set(subdd) - _VALID_KEYS:\n raise ValueError(\n \"Invalid keys found for %r: %s\"\n % (name, \", \".join(set(subdd) - _VALID_KEYS))\n )\n elif not isinstance(subdd[\"filenames\"], list):\n raise ValueError(\"filenames must be a list of strings\")\n input_filenames.extend(subdd[\"filenames\"])\n # Optional file dependencies; used to depend on the list of sequcences\n input_filenames.extend(safe_coerce_to_tuple(file_dependencies))\n\n self._reduce = bool(reduce)\n self._infiles = copy.deepcopy(infiles)\n self._out_prefix = out_prefix\n self._excluded = safe_coerce_to_frozenset(exclude_groups)\n\n description = \"creating%spartitioned phy from %s\" % (\n \" reduced, \" if reduce else \" \",\n describe_files(input_filenames),\n )\n\n Node.__init__(\n self,\n description=description,\n input_files=input_filenames,\n output_files=[out_prefix + \".phy\", out_prefix + \".partitions\"],\n dependencies=dependencies,\n )\n\n def _run(self, _config, temp):\n merged_msas = []\n for (name, files_dd) in sorted(self._infiles.items()):\n partitions = files_dd[\"partitions\"]\n msas = dict((key, []) for key in partitions)\n for filename in files_dd[\"filenames\"]:\n msa = MSA.from_file(filename)\n if self._excluded:\n msa = msa.exclude(self._excluded)\n\n for (key, msa_part) in msa.split(partitions).items():\n msas[key].append(msa_part)\n\n msas.pop(\"X\", None)\n for (key, msa_parts) in sorted(msas.items()):\n merged_msa = MSA.join(*msa_parts)\n if self._reduce:\n merged_msa = merged_msa.reduce()\n\n if merged_msa is not None:\n merged_msas.append((\"%s_%s\" % (name, key), merged_msa))\n\n out_fname_phy = reroot_path(temp, self._out_prefix + \".phy\")\n with open(out_fname_phy, \"w\") as output_phy:\n final_msa = MSA.join(*(msa for (_, msa) in merged_msas))\n output_phy.write(interleaved_phy(final_msa))\n\n partition_end = 0\n out_fname_parts = reroot_path(temp, self._out_prefix + \".partitions\")\n with open(out_fname_parts, \"w\") as output_part:\n for (name, msa) in merged_msas:\n length = msa.seqlen()\n output_part.write(\n \"DNA, %s = %i-%i\\n\"\n % (name, partition_end + 1, partition_end + length)\n )\n partition_end += length\n\n def _teardown(self, _config, temp):\n move_file(\n reroot_path(temp, self._out_prefix + \".phy\"), self._out_prefix + \".phy\"\n )\n move_file(\n reroot_path(temp, self._out_prefix + \".partitions\"),\n self._out_prefix + \".partitions\",\n )\n","sub_path":"paleomix/nodes/formats.py","file_name":"formats.py","file_ext":"py","file_size_in_byte":5135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"333316404","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nfrom pymongo import MongoClient\n\n\nclass ZhaopinPipeline(object): # logo素材信息\n def __init__(self):\n # 连接本地数据库,测试专用!\n self.client = MongoClient('localhost', 27017)\n # 连接公司数据库,开发专用!\n # self.client = MongoClient(host=\"10.0.100.76\", port=27017)\n self.db = self.client.zhaopin\n # self.db.authenticate('', '')\n\n self.lagou = self.db['lagou']\n\n def process_item(self, item, spider):\n if spider.name == 'lagou':\n self.lagou.insert_one(dict(item))\n\n\n return item\n\n","sub_path":"zhaopin/zhaopin/zhaopin/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"413568248","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 14 11:59:42 2016\n\n@author: dreostilab (Elena Dreosti)\n\"\"\"\n#==============================================================================\n# This is the Algorithm used\n # 1. Subtract pre-computed Background frame from Current frame (Note: Not AbsDiff!)\n # 2. Extract Crop regions from ROIs\n # 3. Threshold ROI using mean/7 of each crop region, Binary Close image using 5 rad disc\n # 4. Find largest particle (Contour)\n # 5. - Compute Weighted Centroid (X,Y) for Eye Region (10% of brightest pixels)\n # 6. - Compute Binary Centroid of Body Region (50% of brightest pixels - eyeRegion)\n # 7. - Compute Heading\n\n#==============================================================================\n# -----------------------------------------------------------------------------\n# 1) Function to find Dropbox Folder Path on each computer. In this way you \n# can keep files in Dropbox and do analyisis with different computers.\n\nimport os\nimport json\n\n# Find Dropbox Path function taken from the internet\ntry:\n appdata_path = os.getenv('APPDATA')\n with open(appdata_path + '\\Dropbox\\info.json') as data_file:\n data = json.load(data_file)\nexcept:\n local_appdata_path = os.getenv('LOCALAPPDATA')\n with open(local_appdata_path + '\\Dropbox\\info.json') as data_file:\n data = json.load(data_file)\ndropbox_path = data['personal']['path']\n#\n#\n## -----------------------------------------------------------------------------\n## 2) Set Base Path (Shared Dropbox Folder)\n#base_path = dropbox_home()\nbase_path= dropbox_path\n# -----------------------------------------------------------------------------\n# -----------------------------------------------------------------------------\n\n\n# Set Library Paths\nimport sys\n#sys.path.append(base_path + r'\\Adam_Ele\\Shared Programming\\Python\\ARK')\nsys.path.append(base_path + r'\\Python_ED\\Libraries')\n\n\n# Import useful libraries\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport scipy.misc as misc\nfrom scipy import stats\n\n# Import local modules\nimport SZ_utilities as SZU\nimport SZ_macros as SZM\nimport SZ_video as SZV\n\n## Read Folder List\n#folderListFile = base_path + r'\\Adam_Ele\\Shared Programming\\Python\\Social Zebrafish\\Folder Lists\\Dreosti_LAb\\\\Wt_Nacre'\n#\n#folderListFile = folderListFile + r'\\Folder_List_Wt_Nacre.txt'\n\n#folderListFile = (base_path + r'\\Adam_Ele\\Shared Programming\\Python\\Social Zebrafish\\Folder Lists\\Dreosti_LAb\\Wt_Nacre')\n#folderListFile = folderListFile + r'\\Folder_List_Wt_Nacre_test.txt'\n\n#folderListFile = (base_path + r'\\Adam_Ele\\Shared Programming\\Python\\Social Zebrafish\\Folder Lists\\Isolation_experiments')\n#folderListFile = folderListFile + r'\\Folder_List_Isolation_test.txt'\n\n\nfolderListFile = (base_path + r'\\Python_ED\\Folder_List')\nfolderListFile = folderListFile + r'\\SocialFolderList_2017_05_25_Condition_A.txt'\n\n\n\ndark = False\ncontrol = False \nmultiple = False\ngroups, ages, folderNames, fishStatus = SZU.read_folder_list(folderListFile)\n\n# Bulk analysis of all folders\nfor idx,folder in enumerate(folderNames):\n \n # Get Folder Names\n NS_folder, S_folder, C_folder = SZU.get_folder_names(folder)\n\n # ---------------------\n # Process Video (NS)\n fxS, fyS, bxS, byS, exS, eyS, areaS, ortS, motS = SZV.process_video_track_fish(NS_folder, False, False )\n\n # Save Tracking (NS)\n for i in range(0,6):\n # Save NS\n filename = NS_folder + r'\\tracking'+ str(i+1) + '.npz'\n fish = np.vstack((fxS[:,i], fyS[:,i], bxS[:,i], byS[:,i], exS[:,i], eyS[:,i], areaS[:,i], ortS[:,i], motS[:,i]))\n np.savez(filename, tracking=fish.T)\n \n # ---------------------\n # Check if this is a control experiment\n if control: \n # Process Video (NS)\n fxS, fyS, bxS, byS, exS, eyS, areaS, ortS, motS = SZV.process_video_track_fish(C_folder, False, False )\n \n # Save Tracking (NS)\n for i in range(0,6):\n # Save NS\n filename = C_folder + r'\\tracking'+ str(i+1) + '.npz'\n fish = np.vstack((fxS[:,i], fyS[:,i], bxS[:,i], byS[:,i], exS[:,i], eyS[:,i], areaS[:,i], ortS[:,i], motS[:,i]))\n np.savez(filename, tracking=fish.T)\n \n else:\n # ----------------------\n # Process Video (S)\n fxS, fyS, bxS, byS, exS, eyS, areaS, ortS, motS, fxS_s, fyS_s, bxS_s, byS_s, exS_s, eyS_s, areaS_s, ortS_s, motS_s = SZV.process_video_track_fish(S_folder, True, multiple)\n \n # Save Tracking (S)\n for i in range(0,6):\n # Save S_test\n filename = S_folder + r'\\tracking'+ str(i+1) + '.npz'\n fish = np.vstack((fxS[:,i], fyS[:,i], bxS[:,i], byS[:,i], exS[:,i], eyS[:,i], areaS[:,i], ortS[:,i], motS[:,i]))\n np.savez(filename, tracking=fish.T)\n \n # Save S_social\n filename = S_folder + r'\\Social_Fish\\tracking'+ str(i+1) + '.npz'\n fish = np.vstack((fxS_s[:,i], fyS_s[:,i], bxS_s[:,i], byS_s[:,i], exS_s[:,i], eyS_s[:,i], areaS_s[:,i], ortS_s[:,i], motS_s[:,i]))\n np.savez(filename, tracking=fish.T)\n \n # ----------------------\n# # Process Video (D-dark)\n# if D_folder != -1:\n# # Process Video (D)\n# fxS, fyS, bxS, byS, exS, eyS, areaS, ortS, motS = SZV.process_video_track_fish(D_folder, True, multiple)\n# \n# # Save Tracking (D)\n# for i in range(0,6):\n# # Save D_test\n# filename = D_folder + r'\\tracking'+ str(i+1) + '.npz'\n# fish = np.vstack((fxS[:,i], fyS[:,i], bxS[:,i], byS[:,i], exS[:,i], eyS[:,i], areaS[:,i], ortS[:,i], motS[:,i]))\n# np.savez(filename, tracking=fish.T)\n# \n# # Save D_social\n# filename = D_folder + r'\\Social_Fish\\tracking'+ str(i+1) + '.npz'\n## fish = np.vstack((fxS_s[:,i], fyS_s[:,i], bxS_s[:,i], byS_s[:,i], exS_s[:,i], eyS_s[:,i], areaS_s[:,i], ortS_s[:,i], motS_s[:,i]))\n# np.savez(filename, tracking=fish.T)\n\n # Close Plots\n plt.close('all')\n \n# End of Tracking \n\n\n\n","sub_path":"Behaviour/Basic_Analysis/Step2_Social_Behaviour_Setup.py","file_name":"Step2_Social_Behaviour_Setup.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"466762879","text":"#reference, part of the code is in https://www.cnblogs.com/clemente/p/9543106.html\nimport matplotlib.pyplot as plt\nimport random\nimport math\nimport copy\ncar_radius = 7\nstart_x = 10\nstart_y = 52\npI=3.14159265359\n\nshow_animation = True\n\n#RRT node\nclass Node(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.parent = None\n self.theta = 0\n\n#The conner of the rectangle obstagle\nclass Conner_rectangle(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\n#Class for RRT Planning\nclass RRT(object):\n def __init__(self, start, goal, obstacle_list, rand_area):\n \"\"\"\n Setting Parameter\n\n start:Start Position [x,y]\n goal:Goal Position [x,y]\n obstacleList:obstacle Positions [[x,y,size],...]\n randArea:random sampling Area [min,max]\n\n \"\"\"\n self.start = Node(start[0], start[1])\n self.end = Node(goal[0], goal[1])\n self.min_rand = rand_area[0]\n self.max_rand = rand_area[1]\n self.expandDis = 5\n self.goalSampleRate = 0.05 # 0.05\n self.maxIter = 500\n self.obstacleList = obstacle_list\n self.nodeList = [self.start]\n\n #return random node\n def random_node(self):\n node_x = random.uniform(self.min_rand, self.max_rand)\n node_y = random.uniform(self.min_rand, self.max_rand)\n node = [node_x, node_y]\n\n return node\n\n @staticmethod\n def get_nearest_list_index(node_list, rnd):\n \"\"\"\n :param node_list:\n :param rnd:\n :return:\n \"\"\" \n d_list = [math.sqrt((node.x - rnd[0]) ** 2 + (node.y - rnd[1]) ** 2)+math.fabs(math.atan2(rnd[1] - node.y, rnd[0] - node.x)) for node in node_list]\n min_index = d_list.index(min(d_list))\n return min_index\n\n\n \n #check collion between car and obstacle\n @staticmethod\n def collision_check(nearest_node, new_node, obstacle_list):\n #no_collion = 1\n for (ox, oy, size_x, size_y) in obstacle_list:\n no_collion = 1\n top_left_conner = Conner_rectangle(ox,oy+size_y)\n top_right_conner = Conner_rectangle(ox+size_x,oy+size_y)\n lower_left_conner = Conner_rectangle(ox,oy)\n lower_right_conner = Conner_rectangle(ox+size_x,oy)\n #determine if the origin of the circle of the car is in the rectangle\n if new_node.x>=ox and new_node.x<=ox+size_x and new_node.y >=oy and new_node.y<=oy+size_y:\n no_collion=0\n return no_collion #collion 0\n #the else if statements check if the car circle intersects the rectangle obstacles\n #we use the position of the origin of the circle for different situation\n #car's origin on the north-west side of the obstacle\n elif new_node.xtop_left_conner.y:\n d=math.sqrt((new_node.x-top_left_conner.x)*(new_node.x-top_left_conner.x)+(new_node.y-top_left_conner.y)*(new_node.y-top_left_conner.y))\n if(dtop_right_conner.x and new_node.y>top_right_conner.y:\n d=math.sqrt((new_node.x-top_right_conner.x)*(new_node.x-top_right_conner.x)+(new_node.y-top_right_conner.y)*(new_node.y-top_right_conner.y))\n if(dtop_left_conner.x and new_node.xtop_left_conner.y:\n d=new_node.y-top_left_conner.y\n if(dlower_left_conner.x and new_node.ylower_right_conner.x and new_node.ylower_right_conner.x and new_node.y>lower_right_conner.y and new_node.ylower_left_conner.y and new_node.y ox+size_x and new_node.x > ox+size_x )or (nearest_node.y oy+size_y and new_node.y > oy+size_y)): \n #nearest_node and new_node are on the left side \n if new_node.x >nearest_node.x and nearest_node.x 0:\n d = calculate_d(top_left_conner.x,top_left_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion \n elif k<0:\n d = calculate_d(lower_left_conner.x,lower_left_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion \n #nearest_node and new_node are on the right side\n elif new_node.x ox+size_x:\n if k<0:\n d = calculate_d(top_right_conner.x,top_right_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion \n elif k>0:\n d = calculate_d(lower_right_conner.x,lower_right_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion\n #nearest_node and new_node are on the top side\n elif new_node.y oy+size_y:\n if k>0:\n d = calculate_d(top_left_conner.x,top_left_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion \n elif k<0:\n d = calculate_d(top_right_conner.x,top_right_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion\n #nearest_node and new_node are on the bottom side\n elif new_node.y > nearest_node.y and nearest_node.y< oy:\n if k>0:\n d = calculate_d(lower_right_conner.x,lower_right_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion \n elif k<0:\n d = calculate_d(lower_left_conner.x,lower_left_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion\n #nearest_node and new_node are not on the same side\n #then check if the car's road will intersect with the obstacles\n else:\n #nearest_node on top of the rectangle\n if nearest_node.y > oy+size_y:\n #slopes of the lines from nearest_node to the reactangle's two nearest conners\n k1 = (nearest_node.y-top_left_conner.y)/(nearest_node.x-top_left_conner.x)\n k2 = (nearest_node.y-top_right_conner.y)/(nearest_node.x-top_right_conner.x)\n if not (k>k2 and k0:\n d = calculate_d(top_left_conner.x,top_left_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion \n elif k<0:\n d = calculate_d(top_right_conner.x,top_right_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion \n #nearest_node on bottom of the rectangle\n elif nearest_node.y < oy:\n #slopes of the lines from nearest_node to the reactangle's two nearest conners\n k1 = (nearest_node.y-lower_left_conner.y)/(nearest_node.x-lower_left_conner.x)\n k2 = (nearest_node.y-lower_right_conner.y)/(nearest_node.x-lower_right_conner.x)\n if not (k>k2 or k0:\n d = calculate_d(lower_right_conner.x,lower_right_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion \n elif k<0:\n d = calculate_d(lower_left_conner.x,lower_left_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion\n\n\n #nearest_node on left of \n elif nearest_node.x k1):\n collion = 0\n return no_collion #no collion 0\n else:\n if k>0:\n d = calculate_d(top_left_conner.x,top_left_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion \n elif k<0:\n d = calculate_d(lower_left_conner.x,lower_left_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion\n #nearest_node on right of the rectangle\n elif nearest_node.x > ox + size_x:\n #slopes of the lines from nearest_node to the reactangle's two nearest conners\n k1 = (nearest_node.y-top_right_conner.y)/(nearest_node.x-top_right_conner.x)\n k2 = (nearest_node.y-lower_right_conner.y)/(nearest_node.x-lower_right_conner.x)\n if not (k>k2 or k0:\n d = calculate_d(lower_right_conner.x,lower_right_conner.y,new_node.x,new_node.y,nearest_node.x,nearest_node.y)\n if d < car_radius:\n no_collion = 0\n return no_collion\n return no_collion\n\n #calculate the distance between the conner and line\n def calculate_d(x0,y0,x1,y1,x2,y2):\n A=y1-y2\n B=x2-x1\n C=(y2-y1)*x2\n return math.fabs(A*x0+B*y0+C)/math.sqrt(math.pow(A,2)+math.pow(B,2))\n\n def planning(self):\n \"\"\"\n Path planning\n\n animation: flag for animation on or off\n \"\"\"\n\n while True:\n # Random Sampling\n rnd = self.random_node()\n\n # Find nearest node\n min_index = self.get_nearest_list_index(self.nodeList, rnd)\n\n # expand tree\n nearest_node = self.nodeList[min_index]\n\n # return theta\n theta = math.atan2(rnd[1] - nearest_node.y, rnd[0] - nearest_node.x)\n\n new_node = copy.deepcopy(nearest_node)\n new_node.x += self.expandDis * math.cos(theta)\n new_node.y += self.expandDis * math.sin(theta)\n new_node.parent = min_index\n new_node.theta = theta\n\n if not self.collision_check(nearest_node, new_node, self.obstacleList):\n continue\n\n self.nodeList.append(new_node)\n\n # check goal\n dx = new_node.x - self.end.x\n dy = new_node.y - self.end.y\n d = math.sqrt(dx * dx + dy * dy)\n if d <= self.expandDis:\n print(\"Goal!!\")\n break\n\n if True:\n self.draw_graph(rnd)\n path = [[self.end.x, self.end.y,0]]\n last_index = len(self.nodeList) - 1\n while self.nodeList[last_index].parent is not None:\n node = self.nodeList[last_index]\n temp=0\n if node.theta<=pI and node.theta>=pI/2: #90-180\n temp=-3/2*pI+node.theta\n elif node.theta>=0 and node.theta<=pI/2: #0-90\n temp=pI/2+node.theta\n elif node.theta<=0 and node.theta>=-pI/2: #0--90\n temp=pI/2+node.theta\n elif node.theta<=-pI/2 and node.theta>=-pI: #-90 - -180\n temp=pI/2+node.theta\n else:\n print(\"error\") \n\n \n path.append([node.x, node.y,temp/pI*180])\n last_index = node.parent\n \n path.append([self.start.x, self.start.y,0])\n\n return path\n\n #draw dynamic graph\n def draw_graph(self, rnd=None):\n plt.clf() # clf graph \n if rnd is not None:\n plt.plot(rnd[0], rnd[1], \"^g\")\n\n #draw and connect all the nodes that is in the RRT\n for node in self.nodeList:\n if node.parent is not None:\n plt.plot([node.x, self.nodeList[node.parent].x], [\n node.y, self.nodeList[node.parent].y], \"-g\")\n\n #draw the obstacles\n for (ox, oy, size_x,size_y) in self.obstacleList:\n rect = plt.Rectangle((ox,oy),size_x,size_y, fc='k')\n plt.gca().add_patch(rect)\n #plt.plot(ox, oy, \"sk\", ms=10*size)\n\n plt.plot(self.start.x, self.start.y, \"^r\")\n plt.plot(self.end.x, self.end.y, \"^b\")\n plt.axis([self.min_rand, self.max_rand, self.min_rand, self.max_rand])\n plt.grid(True)\n plt.pause(0.01)\n\n #draw static graph\n def draw_static(self, path):\n plt.clf() # clear graph\n\n #draw circle around the origin of the car\n for data in path:\n circle = plt.Circle((data[0],data[1]),7,fc='y')\n plt.gca().add_patch(circle)\n\n #draw and connect all the nodes that is in the RRT\n for node in self.nodeList:\n if node.parent is not None:\n plt.plot([node.x, self.nodeList[node.parent].x], [\n node.y, self.nodeList[node.parent].y], \"-g\")\n\n #draw the obstacles\n \n for (ox, oy, size_x,size_y) in self.obstacleList:\n rect = plt.Rectangle((ox,oy),size_x,size_y, fc='k')\n plt.gca().add_patch(rect)\n\n plt.plot(self.start.x, self.start.y, \"^r\")\n plt.plot(self.end.x, self.end.y, \"^b\")\n plt.axis([self.min_rand, self.max_rand, self.min_rand, self.max_rand])\n\n #indicate the nearest path for the car\n plt.plot([data[0] for data in path], [data[1] for data in path], '-r')\n plt.grid(True)\n plt.show()\n \ndef rrt_main(goal_x,goal_y):\n print(\"start RRT path planning\")\n\n obstacle_list = [\n (19,20,2,40),\n (37,0,2,40)\n ]\n\n # Set Initial parameters\n rrt = RRT(start=[start_x, start_y], goal=[goal_x,goal_y], rand_area=[0,60], obstacle_list=obstacle_list)\n path = rrt.planning()\n #print(path)\n \n\n # Draw final path\n if show_animation:\n plt.close()\n rrt.draw_static(path)\n print(path) \n return path\n\n\n\n\n","sub_path":"controllers/diaonilaomu/RRT.py","file_name":"RRT.py","file_ext":"py","file_size_in_byte":19954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"629394593","text":"from packagesLoader import *\nfrom liveCommonFilesLoader import *\n\n\ndef get_months_and_durations(start_date,end_date):\n current = start_date\n result = [current]\n\n current = current.replace(day=1)\n while current <= end_date:\n current += timedelta(days=32)\n current = current.replace(day=1)\n result.append(datetime.datetime(current.year, current.month, 1).date())\n\n durations= []\n for curr in result[:-1]:\n curr_range = calendar.monthrange(curr.year, curr.month)\n curr_duration = (curr_range[1] - curr.day)+1\n\n if ((curr.month == end_date.month) & (curr.year == end_date.year)):\n durations.append(end_date.day)\n else:\n durations.append(curr_duration)\n return durations\n\n\n\ndef calcVolatiltiy(name):\n '''\n FIND THE VOLATILITY FOR EACH MONTH FOR ALL THE COMMODITIES GIVEN THE\n TYPE OF DATA (MANDI PRICE OR RETAIL) \n '''\n #ITERATE OVER EACH COMMODITY\n for commodity in commodityListRetail: \n try:\n dates = []\n vals = []\n averageDf = pd.DataFrame(columns=['DATE'])\n folderToOpen = os.path.join('../Data/PlottingData', commodity,'Original')\n files = [f for f in os.listdir(folderToOpen) if f.endswith(name+'.csv') and not f.startswith('Avg')]\n files.sort()\n for f in files:\n try:\n #OPEN FILE\n fileToSave = os.path.join('../Data/PlottingData',commodity,'Volatility',f)\n temp = pd.DataFrame(columns=['DATE'])\n fileToOpen = os.path.join(folderToOpen,f)\n print(fileToOpen)\n forecastedFileToOpen = fileToOpen.replace('Original', 'Forecast')\n df = pd.read_csv(fileToOpen, names = ['DATE', name], header=0)\n dfForecast = pd.read_csv(forecastedFileToOpen, names = ['DATE', name], header=0)\n df = df.append(dfForecast.tail(30), ignore_index = True)\n #FIND MAX AND MIN DATE\n start_date = datetime.datetime.strptime(min(df['DATE']), '%Y-%m-%d').date()\n end_date = datetime.datetime.strptime(max(df['DATE']), '%Y-%m-%d').date()\n #FIND NUMBER OF DAYS PER MONTH BETWEEN TWO DATES\n durations = np.cumsum(get_months_and_durations(start_date,end_date))\n durations = np.concatenate([[0], durations])\n tempVals = []\n tempDates = []\n for i in range(len(durations)-1):\n dx = df[durations[i]:durations[i+1]][name]\n tempDates.append(df.at[durations[i],'DATE'])\n tempVals.append((dx.std())/(dx.mean()))\n temp['DATE'] = tempDates\n temp['VOLATILITY'] = tempVals\n temp.to_csv(fileToSave, index=False)\n vals.append(tempVals)\n if(len(tempDates)>len(dates)):\n dates = tempDates \n # print(fileToSave)\n # print(temp.head())\n except:\n continue\n maxLen = len(max(vals, key=len))\n for sublist in vals:\n sublist[:] = [np.nan] * (maxLen - len(sublist)) + sublist\n mandiValDict = dict(zip(files, vals))\n averageDf['DATE'] = dates\n for k,v in mandiValDict.items():\n averageDf[k] = v\n #averageDf = averageDf[['DATE','VOLATILITY']]\n avgFileToSave = os.path.join('../Data/PlottingData', commodity,'Volatility','Avg_Std_' + str(name) + '.csv')\n #averageDf['DATE'] = temp['DATE']\n #averageDf[f] = temp['VOLATILITY']\n averageDf['MEAN'] = averageDf.mean(axis=1)\n averageDf['STD'] = averageDf.std(axis=1)\n averageDf = averageDf[['DATE','MEAN','STD']]\n averageDf.to_csv(avgFileToSave, index = False)\n except:\n continue\n\n\n\ndef mostVolatileMandisForMonth(commodity ,year, month):\n '''\n FIND THE MOST VOLATILITY MANDIS FOR EACH MONTH FOR GIVEN COMMODITY\n MONTH AND YEAR. THIS FUNCTION WILL BE CALLED BY findMostVolatileMandis()\n '''\n\n date = f\"{year}-{month}-01\"\n for com in commodityListRetail:\n if(commodity!=com):\n continue\n folderToOpen = os.path.join('../Data/PlottingData',commodity,'Volatility')\n files = [f for f in os.listdir(folderToOpen) if f.endswith('Price.csv') and not f.startswith('Avg')]\n files.sort()\n temp = pd.DataFrame(columns=['DATE', 'MANDINAME','STATENAME','VOLATILITY'])\n for f in files:\n mandiName = f.split('_')[1]\n stateName = f.split('_')[0]\n #print(mandiName, stateName)\n fileToOpen = os.path.join(folderToOpen,f)\n df = pd.read_csv(fileToOpen)\n try:\n k = (df[df['DATE']==date]['VOLATILITY']).tolist()[0]\n #print(k)\n temp = temp.append({'DATE':date, 'MANDINAME':mandiName,'STATENAME':stateName,'VOLATILITY':k}, ignore_index=True)\n except:\n continue\n temp = temp.sort_values(by='VOLATILITY', ascending=False)\n avgVal = temp['VOLATILITY'].mean()\n temp = temp.head(10)\n temp = temp.append({'DATE':date,'MANDINAME':'AVERAGE','STATENAME':'','VOLATILITY':avgVal}, ignore_index=True)\n temp = temp.sort_values(by='VOLATILITY', ascending=False)\n fileToSave = os.path.join(folderToOpen,'mostVolatile.csv')\n #print(fileToSave)\n #print(temp.head())\n return temp\n #temp.to_csv(fileToSave, index=False)\n\n\ndef findMostVolatileMandis():\n '''\n GENERATING ALL THE MONTH AND YEAR COMBINATIONS AND RUN THE mostVolatileMandisForMonth(commodity ,year, month)\n FOR EACH COMBINATION OF COMMODITY, MONTH AND YEAR\n '''\n for commodity in commodityListRetail:\n print(commodity)\n folderToOpen = os.path.join('../Data/PlottingData',commodity,'Volatility')\n files = [f for f in os.listdir(folderToOpen) if f.endswith('Price.csv') and not f.startswith('Avg')]\n maxDate = '2016-01-01'\n for file in files:\n fileToOpen = os.path.join(folderToOpen,file)\n df = pd.read_csv(fileToOpen)\n maxDate = max(maxDate, df['DATE'].max())\n dates = pd.date_range(start='2016-01-01',end=maxDate ,freq='MS')\n fileToSave = os.path.join(folderToOpen,'mostVolatile.csv')\n finalDf = pd.DataFrame(columns=['DATE', 'MANDINAME','STATENAME','VOLATILITY'])\n for date in dates:\n year = date.strftime('%Y')\n month = date.strftime('%m')\n temp = mostVolatileMandisForMonth(commodity ,year, month)\n finalDf = finalDf.append(temp)\n finalDf.to_csv(fileToSave, index=False)\n\n # print(date)\n\n\n# findMostVolatileMandis()\n\n\n\n\ndef calcVolatilityThreshold():\n print('RETAIL')\n temp = pd.DataFrame(columns=['COMMODITY','VOLATILITY'])\n months = pd.read_csv(os.path.join('../Data/PlottingData','ONION','Volatility','KARNATAKA_BANGALORE_Price.csv'))['DATE'].tolist()\n #print(months)\n for commodity in commodityListRetail:\n #print(commodity)\n folderToOpen = os.path.join('../Data/PlottingData',commodity,'Volatility')\n files = [f for f in os.listdir(folderToOpen) if f.endswith('Retail.csv') and not f.startswith('Avg')]\n files.sort()\n finalList = []\n for month in months:\n volatilityList = [] \n for file in files:\n try:\n df = pd.read_csv(os.path.join('../Data/PlottingData',commodity,'Volatility', file))\n val = df[df['DATE']==month]['VOLATILITY'].tolist()[0]\n volatilityList.append(val)\n except:\n continue\n volatilityList.sort()\n n = len(volatilityList)\n take = math.ceil((70 * n)/100)+1\n leave = math.ceil((n-take)/2)+1\n volatilityList = volatilityList[leave:-leave]\n #print(volatilityList)\n finalList.append(volatilityList)\n finalList = [item for sublist in finalList for item in sublist]\n finalList = [x for x in finalList if x != 'nan']\n finalList.sort()\n n = len(finalList)\n take = math.ceil((70 * n)/100)+1\n leave = math.ceil((n-take)/2)+1\n finalList = finalList[leave:-leave]\n print(commodity, np.nanmean(finalList))\n temp = temp.append({'COMMODITY':commodity, 'VOLATILITY':round(np.nanmean(finalList),5)}, ignore_index=True)\n print(temp)\n temp.to_csv('RetailThreshold.csv', index=False)\n print(temp)\n #print(median(finalList))\n\n\ndef volatility():\n types = ['Price', 'Retail']\n for name in types:\n calcVolatiltiy(name)\n findMostVolatileMandis()\n\n\ndef checkVolatilitySameMonth(x):\n return abs(x['MEAN'] + x['STD']) \n\ndef sameMonth(df, avgDf):\n avgDf['1STD'] = avgDf.apply(lambda x : abs(x['MEAN'] + x['STD']), axis = 1)\n avgDf['VOLATILITY'] = df['VOLATILITY']\n avgDf['SAMEMONTH'] = avgDf.apply(lambda x: 'Anomaly' if x['VOLATILITY'] > x['1STD'] else 'Normal', axis = 1)\n return avgDf['SAMEMONTH']\n\ndef lastMonth(df, avgDf):\n avgDf['MEAN'] = avgDf['MEAN'].shift(1)\n avgDf['STD'] = avgDf['STD'].shift(1)\n avgDf['1STD'] = avgDf.apply(lambda x : abs(x['MEAN'] + x['STD']), axis = 1)\n avgDf['VOLATILITY'] = df['VOLATILITY']\n avgDf['LASTMONTH'] = avgDf.apply(lambda x: 'Anomaly' if x['VOLATILITY'] > x['1STD'] else 'Normal', axis = 1)\n return avgDf['LASTMONTH']\n\ndef lastYear(df, avgDf):\n oneSTD = []\n for index, row in avgDf.iterrows():\n l = [i for i in range(index-12, 0, -12)]\n if(len(l) == 0):\n oneSTD.append(np.nan)\n else:\n mean = np.mean([avgDf.loc[i, 'MEAN'] for i in l])\n std = np.mean([avgDf.loc[i, 'STD'] for i in l])\n oneSTD.append(mean+std)\n avgDf['1STD'] = oneSTD\n avgDf['VOLATILITY'] = df['VOLATILITY']\n avgDf['LASTYEAR'] = avgDf.apply(lambda x: 'Anomaly' if x['VOLATILITY'] > x['1STD'] else 'Normal', axis = 1)\n return avgDf['LASTYEAR']\n\n\ndef findVolatilityAnomalies():\n for commodity in commodityList:\n print(commodity)\n folderToOpen = os.path.join('../Data/PlottingData', commodity, 'Volatility')\n folderToSave = os.path.join('../Data/PlottingData', commodity, 'NormalOrAnomalous', 'VOLATILITY')\n for kind in ['Price', 'Retail']:\n # print(kind)\n avgFileToOpen = os.path.join(folderToOpen, 'Avg_Std_' + kind + '.csv')\n files = [os.path.join(folderToOpen, f) for f in os.listdir(folderToOpen) if(f.endswith(kind+'.csv') and not f.startswith('Avg_Std_'))]\n fullDf = pd.DataFrame()\n fullFileToSave = os.path.join(folderToSave, kind+'.csv')\n # print(fullFileToSave)\n for file in files:\n avgDf = pd.read_csv(avgFileToOpen)\n avgDf = (avgDf[avgDf['DATE'] >= '2016-01-01']).reset_index(drop = True)\n df = pd.read_csv(file)\n df = (df[df['DATE'] >= '2016-01-01']).reset_index(drop = True)\n df['SAMEMONTH'] = sameMonth(df, avgDf)\n df['LASTMONTH'] = lastMonth(df, avgDf)\n df['LASTYEAR'] = lastYear(df, avgDf)\n x = file.split('/')[-1]\n stateName = x.split('_')[0]\n mandiName = x.split('_')[1]\n # print(stateName, mandiName)\n fileToSave = os.path.join(folderToSave, x)\n # print(fileToSave)\n df.to_csv(fileToSave, index = False)\n # print('*'*20) \n df['STATENAME'] = stateName\n df['MANDINAME'] = mandiName\n fullDf = fullDf.append(df, ignore_index = True)\n fullDf = fullDf[['DATE', 'STATENAME', 'MANDINAME', 'VOLATILITY', 'SAMEMONTH', 'LASTMONTH', 'LASTYEAR']]\n fullDf.sort_values(['DATE', 'STATENAME', 'MANDINAME'], inplace = True)\n print(fullDf)\n fullDf.to_csv(fullFileToSave, index = False)\n # print('+'*40) \n\n\n# volatility()\nfindVolatilityAnomalies()","sub_path":"Code/volatility.py","file_name":"volatility.py","file_ext":"py","file_size_in_byte":12452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"107152489","text":"from django.shortcuts import render\n\n# Create your views here.\nimport requests\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom . models import Templates\nimport pymongo\nimport json\nfrom bson import ObjectId\nfrom django.http import JsonResponse\n\nclient=pymongo.MongoClient(\"mongodb+srv://Password1:Password1@tester.6wke2.mongodb.net/te?retryWrites=true&w=majority\")\nwebhook_url = 'https://hooks.slack.com/services/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'\nheaders = {\n 'Content-type': 'application/json',\n}\n\nclass TemplateList(APIView):\n \n def get(self,request,customer_id):\n try:\n s=int(customer_id)\n myquery={\"customerId\":s}\n data=client.te.restApi_templates.find(myquery).sort(\"id\",-1)\n for i in data:\n res = json.dumps(i, cls=JSONEncoder)\n return JsonResponse({\"status\":status.HTTP_200_OK,\"data\":res},safe=False)\n data = '{\"text\":\"Customer is not available for which you are accessing i.e customerId:-'+customer_id+'!!\"}'\n response = requests.post(webhook_url, headers=headers, data=data)\n return JsonResponse({\"status\":status.HTTP_200_OK,\"data\":{\"message\":\"Customer is not available\"}},safe=False)\n except ValueError:\n s=\"Only integers are allowed for Customer_Id\"+customer_id\n data = '{\"text\":\"Only integers are allowed for Customer_Id:- '+customer_id+'\"}'\n response = requests.post(webhook_url, headers=headers, data=data)\n return JsonResponse({\"status\":status.HTTP_404_NOT_FOUND,\"data\":{\"message\":\"Only integers are allowed\"}},safe=False)\n \n \n def post(self,request,customer_id):\n try:\n s=int(customer_id)\n myquery={\"customerId\":s}\n flag=0\n template=Templates()\n l=[]\n for i in client.te.restApi_templates.find(myquery):\n if(flag==0):\n template.type=i['type']\n template.customerId=i['customerId']\n template.entity=i[\"entity\"]\n template.law=i[\"law\"] \n l=i['fields']\n flag=1\n else:\n l=l+i['fields']\n template.fields=l\n if(template.customerId!=None):\n template.save()\n else:\n data = '{\"text\":\"Customer is not available for which you are accessing i.e customerId:-'+customer_id+'!!\"}'\n response = requests.post(webhook_url, headers=headers, data=data)\n return JsonResponse({\"status\":status.HTTP_200_OK,\"data\":{\"message\":\"Customer is not available\"}},safe=False) \n data=client.te.restApi_templates.find(myquery).sort(\"id\",-1)\n for i in data:\n res = json.dumps(i, cls=JSONEncoder)\n return JsonResponse({\"status\":status.HTTP_200_OK,\"data\":res},safe=False)\n data = '{\"text\":\"Connectivity Error for fetching data for CustomerId:- '+customer_id+'\"}'\n response = requests.post(webhook_url, headers=headers, data=data)\n return JsonResponse({\"status\":status.HTTP_500_INTERNAL_SERVER_ERROR,\"data\":{\"message\":\"Connectivity Error for fetching data\"}},safe=False)\n except ValueError:\n data = '{\"text\":\"Only integers are allowed for customerId:-'+customer_id+'\"}'\n response = requests.post(webhook_url, headers=headers, data=data)\n return JsonResponse({\"status\":status.HTTP_404_NOT_FOUND,\"data\":{\"message\":\"Only integers are allowed\"}},safe=False)\n\nclass JSONEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, ObjectId):\n return str(o)\n return json.JSONEncoder.default(self, o)","sub_path":"restApi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"504728116","text":"\"\"\"\n2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node. \nExample: Input: the node ‘c’ from the linked list a->b->c->d->e\nResult: nothing is returned, but the new linked list looks like a->b->d->e\n\"\"\"\n\ndef del_mid_node(node):\n while node.next != None:\n copy= [node.next.data, node.next.next]\n delete(node.next) \n node.data = copy[0]\n node.next = copy[1]\n node = node.next\n \n \n","sub_path":"02_linked_lists/2.3_del_mid_node.py","file_name":"2.3_del_mid_node.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"273154640","text":"# Copyright 2018 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom email.mime import text\nimport email.utils\nimport smtplib\nimport socket\n\ntry:\n from google.appengine.api import mail as aemail\n from google.appengine.api import app_identity\n from google.appengine.api import mail_errors\nexcept ImportError:\n pass\n\nfrom scoreboard import main\n\napp = main.get_app()\n\n\nclass MailFailure(Exception):\n \"\"\"Inability to send mail.\"\"\"\n pass\n\n\ndef send(message, subject, to, to_name=None, sender=None, sender_name=None):\n \"\"\"Send an email.\"\"\"\n sender = sender or app.config.get('MAIL_FROM')\n sender_name = sender_name or app.config.get('MAIL_FROM_NAME')\n if main.on_appengine():\n _send_appengine(message, subject, to, to_name, sender, sender_name)\n else:\n _send_smtp(message, subject, to, to_name, sender, sender_name)\n\n\ndef _send_smtp(message, subject, to, to_name, sender, sender_name):\n \"\"\"SMTP implementation of sending email.\"\"\"\n host = app.config.get('MAIL_HOST')\n\n if not host:\n raise MailFailure('SMTP Server Not Configured')\n\n try:\n server = smtplib.SMTP(host)\n except (smtplib.SMTPConnectError, socket.error) as ex:\n app.logger.error('Unable to send mail: %s', str(ex))\n raise MailFailure('Error connecting to SMTP server.')\n\n msg = text.MIMEText(message)\n msg['Subject'] = subject\n msg['To'] = email.utils.formataddr((to_name, to))\n msg['From'] = email.utils.formataddr((sender_name, sender))\n\n try:\n if app.debug:\n server.set_debuglevel(True)\n server.sendmail(sender, [to], msg.as_string())\n except (smtplib.SMTPException, socket.error) as ex:\n app.logger.error('Unable to send mail: %s', str(ex))\n raise MailFailure('Error sending mail to SMTP server.')\n finally:\n try:\n server.quit()\n except smtplib.SMTPException:\n pass\n\n\ndef _appengine_default_sender():\n return 'noreply@{}.appspotmail.com'.format(\n app_identity.get_application_id())\n\n\ndef _send_appengine(message, subject, to, to_name, sender, sender_name):\n \"\"\"AppEngine mail sender.\"\"\"\n sender = sender or _appengine_default_sender()\n message = aemail.EmailMessage(\n subject=subject,\n body=message)\n message.to = email.utils.formataddr((to_name, to))\n message.sender = email.utils.formataddr((sender_name, sender))\n app.logger.info('Sending email from: %s, to: %s, subject: %s',\n message.sender, message.sender, subject)\n try:\n message.send()\n except mail_errors.Error as ex:\n app.logger.exception('Error sending mail: %s', str(ex))\n raise MailFailure('Error sending mail.')\n","sub_path":"scoreboard/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":3255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"336007080","text":"#!/usr/bin/env python3\n\nfrom pwn import *\nfrom construct import *\nfrom binascii import hexlify\nimport struct\nimport time\nfrom hashlib import sha256\nfrom ctypes import sizeof, c_int\nfrom Voter import Voter\n\nMESSAGE_HEADER_LEN = sizeof(c_int) + 32 + sizeof(c_int)\nSERVER_PORT = 31337\n\nPOSE_QUESTION = 0\nVOTER_VOTE = 1\n\nGenericMessageHeader = Struct(\n 'directive' / Int32ul,\n 'key' / Bytes(32),\n 'mlen' / Int32ul\n)\n\ndef data_received(data):\n if len(data) >= MESSAGE_HEADER_LEN:\n try:\n msgHeader = GenericMessageHeader.parse(data[0:MESSAGE_HEADER_LEN])\n except StreamError as e:\n print(f\"Error while trying to parse message from interface: {str(e)}\")\n return\n\n msg = data[MESSAGE_HEADER_LEN:]\n\n print(f\"RECV from interface: [directive:{msgHeader.directive}][key:{hexlify(msgHeader.key)}][mlen:{msgHeader.mlen}] data:{msg.hex()}\")\n\n return msgHeader, msg\n \n # print(f\"End: {len(data)}\")\n else:\n print(f\"Received small message: {hexlify(data)}...\")\n\ndef create_bad_msg(msg, directive, key):\n print(f\"key: {hexlify(key)}\")\n\n msg_size = 1\n full_msg_packed = struct.pack(f\" total_eps:\n break\n if abs(eps_values[index]-total_eps)>abs(eps_values[index-1]-total_eps):\n index-=1\n else:\n pass\n print(\"EPSILON: \", eps_values[index])\n generated_data = train(scaled_input, network_architecture, sigma, debug=debug, training_epochs=index,\n with_privacy=with_privacy, priv_optimizer=priv_optimizers_hh[trainer], opt_name=trainer, cluster_class=cluster_class, \n kmeans_clusters=kmeans_clusters)\n\n generated_data = scaler.inverse_transform(generated_data)\n generated_data = appendLabel(generated_data, cluster_class)\n if(synthetic_data == []):\n synthetic_data = generated_data\n else:\n synthetic_data = np.vstack((synthetic_data, generated_data))\n gc.collect()\n\n tf.reset_default_graph()\n\n unique_labels = np.unique(label)\n for unique_label in unique_labels:\n data = appendLabel(np.asarray(clustered_input[np.where(label==unique_label)][0]).reshape(1,INPUT_DIM), unique_label)\n synthetic_data = np.vstack((synthetic_data, data))\n return synthetic_data\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--trainer\", default=\"google_adam\", type = str)\n parser.add_argument(\"--debug\", default=False, action='store_true')\n parser.add_argument(\"--private\", default=False, action='store_true')\n args = parser.parse_args()\n \n if args.private and args.trainer not in priv_optimizers_hh:\n raise Exception(\"wrong trainer\")\n \n if not args.private:\n args.trainer = \"adam\"\n return args\n\ndef print_accuracy(synthetic_path, epsilon_for_autoencoder, delta_for_autoencoder, sigma_for_autoencoder, synthetic_accuracy_list):\n if len(synthetic_accuracy_list) != 0:\n result_file = synthetic_path + \"__result\" + \".txt\"\n result_opener = open(result_file, 'a')\n\n result_opener.write(\"epsilon_for_autoencoder: \" + str(epsilon_for_autoencoder))\n result_opener.write(\"synthetic_accuracy_list: \" + str(np.round(synthetic_accuracy_list,3)))\n result_opener.write(\"delta_for_autoencoder: \" + str(delta_for_autoencoder))\n result_opener.write(\"sigma_for_autoencoder: \" + str(sigma_for_autoencoder))\n result_opener.write(\"synthetic_accuracy: \" + str(round(sum(synthetic_accuracy_list)/len(synthetic_accuracy_list),2)) + \"\\n\")\n\n\ndef main(argv=None):\n for step in parameter_dict:\n evalParameter = parameter_dict.get(step)\n total_eps = evalParameter.get('eps')\n sigma = evalParameter.get('sigma')\n sigma_cl_1 = evalParameter.get('sigma_cl_1')\n sigma_cl_2 = evalParameter.get('sigma_cl_2')\n synthetic_accuracy_list = list()\n for j in range(RUN_NUMBER):\n train_file = TRAIN_FILE + str(j + 1) + \".txt\"\n test_file = TEST_FILE + str(j + 1) + \".txt\"\n\n synthetic_data = run_sim_clusters(FLAGS.trainer, FLAGS.debug, FLAGS.private, train_file, total_eps, sigma, sigma_cl_1, sigma_cl_2)\n test = pd.read_csv(test_file, sep=\",\", header=None)\n\n row, column = test.shape\n\n synthetic_input = synthetic_data[:, 0:column-1]\n synthetic_label = synthetic_data[:, -1]\n\n test_input = test.values[:, 0:column-1]\n test_label = test.values[:, -1]\n\n\n scaler = preprocessing.StandardScaler()\n x_synthetic = scaler.fit_transform(synthetic_input)\n x_test = scaler.fit_transform(test_input)\n\n svc = svm.SVC(kernel='linear', C=10).fit(x_synthetic, synthetic_label)\n synthetic_accuracy = round(accuracy_score(test_label, svc.predict(x_test)), 2)\n synthetic_accuracy_list.append(synthetic_accuracy)\n\n synthetic_file = SYNTHETIC_FILE + \"_\" + str(total_eps) + \"_\" + str(sigma) + \"_\" + str(j + 1) + \".txt\"\n np.random.shuffle(synthetic_data)\n np.savetxt(synthetic_file, synthetic_data, fmt='%.2f', delimiter=',')\n print_accuracy(SYNTHETIC_FILE, total_eps, DELTA, sigma, synthetic_accuracy_list)\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"src/dp_rel_vae_3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"26870346","text":"# Base code is from https://www.geeksforgeeks.org/socket-programming-multi-threading-python/\n# Crawl and scrape tutorials and base code:\n# https://www.digitalocean.com/community/tutorials/how-to-work-with-web-data-using-requests-and-beautiful-soup-with-python-3\n\nimport socket\nfrom _thread import *\nimport threading\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nimport pickle\nfrom datetime import datetime, timedelta\nimport random\n\ndef WebCrawl(url):\n\ttry:\n\t\tpage = requests.get(url)\n\t\tsoup = BeautifulSoup(page.text, 'html.parser')\n\n\t\t# prints any titles from the first page hit.\n\t\ttitles = soup.find_all('title')\n\t\tlinks = soup.find_all('a', attrs={'href': re.compile(\"^http\")})\n\n\t\ttf_results = []\n\t\turl_list = []\n\t\tkeyword1='covid-19'\n\t\tkeyword2='coronavirus'\n\n\t\t# This works to place a time-out stop on the server.\n\t\tstart_time = datetime.now()\n\t\trandom_number = random.randint(0, 3000)\n\n\t\tfor link in links:\n\t\t\tcurrent_time = datetime.now()\n\t\t\tif current_time > start_time + timedelta(milliseconds = 20000 + random_number):\n\t\t\t\tbreak\n\n\t\t\taddress = link.get('href')\n\t\t\ttry:\n\t\t\t\t# get texts of address to decide whether this address is about covid - 19\n\t\t\t\tpage2 = requests.get(address)\n\t\t\t\tsoup2 = BeautifulSoup(page2.text, 'html.parser')\n\t\t\t\t#title2 = soup2.find_all('title')\n\t\t\t\t#links2=soup2.find_all('a', attrs={'href': re.compile(\"^http\")})\n\t\t\t\ttexts2 = soup2.find_all('p')\n # loop through texts\n\t\t\t\tfor idx in range(len(texts2)):\n\t\t\t\t\tL = texts2[idx].get_text()\n\n\t\t\t\t\tif (keyword1.lower() in L.lower()) or (keyword2.lower() in L.lower()):\n\t\t\t\t\t\ttarget = L\n\t\t\t\t\t\turl_list.append([address,target])\n\t\t\t\t\t\tbreak\n\n\t\t\texcept Exception as ie:\n\t\t\t\tprint(\"Error in crawling web page.\")\n\n\texcept Exception as ie:\n\t\tprint(\"Error in crawling web page.\")\n\n\treturn url_list\n\n\nprint_lock = threading.Lock()\n\ndef threaded(c):\n\tHEADERSIZE = 10\n\twhile True:\n\t\ttry:\n\t\t\turl = c.recv(4096)\n\t\t\tif not url:\n\t\t\t\tprint('Bye')\n\t\t\t\tprint_lock.release()\n\t\t\t\tbreak\n\t\t\tmy_url=url.decode('utf-8')\n\t\t\tprint('the website you are crawling is: ')\n\t\t\tprint(my_url)\n\t\t\turl_list = WebCrawl(my_url)\n\t\t\tprint('crawled links #. is : ')\n\t\t\tprint(len(url_list))\n\t\t\tmsg=pickle.dumps(url_list)\n\t\t\tmsg = bytes(f\"{len(msg):<{HEADERSIZE}}\", 'utf-8')+msg\n\t\t\tc.send(msg)\n\t\t\tprint('data sent!')\n\t\t\tprint(url_list)\n\t\texcept:\n\t\t\turl_list.clear()\n\t\t\turl_list.append([\"No message sent.\", \"Error sending data.\"])\n\t\t\tmsg=picke.dumps(url_list)\n\t\t\tc.send(msg)\n\t\t\tprint(\"Error in sending data.\")\n\tc.close()\n\ndef Main():\n\thost = \"\"\n\tport = 12345\n\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ts.bind((host, port))\n\tprint(\"socket binded to port\", port)\n\ts.listen(5)\n\tprint(\"socket is listening\")\n\twhile True:\n\t\tc, addr = s.accept()\n\t\tprint_lock.acquire()\n\t\tprint('Connected to :', addr[0], ':', addr[1])\n\t\tstart_new_thread(threaded, (c,))\n\ts.close()\n\nif __name__ == '__main__':\n\tMain()\n","sub_path":"server12345.py","file_name":"server12345.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"410503493","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 reorderList(self, head: Optional[ListNode]) -> None:\n \"\"\"\n Do not return anything, modify head in-place instead.\n \"\"\"\n if not head or not head.next: return head\n one, two=head, head.next\n while two and two.next:\n one=one.next\n two=two.next.next\n\n prev, curr=None, one.next\n one.next=None\n while curr:\n next=curr.next\n curr.next=prev\n prev=curr\n curr=next\n\n dummy=ListNode(0)\n tail, l1, l2=dummy, head, prev\n while l2:\n tail.next=l1\n tail=tail.next\n l1=l1.next\n tail.next=l2\n tail=tail.next\n l2=l2.next\n if l1:\n tail.next=l1\n\n return dummy.next\n\n","sub_path":"python/reorder-list.py","file_name":"reorder-list.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"649029147","text":"\"\"\"\nCalculate Compound interest\nEquation\nA = P(1+r)t\n\nA = Money at the End\nP = Principal/Original Amount Invested\nr = Interest Rate\nt = Years or Time Periods the money has been invested.\n\"\"\"\nimport matplotlib.pyplot as plt\n\n\ndef compound_interest(p, r, t):\n \"\"\"\n Calculate Compound Interest\n :param p: Principal investment\n :param r: interest rate\n :param t: years or time periods\n :return: Money at the end\n \"\"\"\n a = p * (1 + r) ** t\n return a\n\n\ndef create_array(p, r, t):\n values = [p]\n years = [0]\n for time in range(1, t + 1):\n values.append(compound_interest(p, r, time))\n years.append(time)\n return values, years\n\nvalues, years = create_array(100, .02, 25)\nplt.plot(years, values, 'r')\nvalues, years = create_array(100, .07, 25)\nplt.plot(years, values, 'g')\nvalues, years = create_array(100, .14, 25)\nplt.plot(years, values, 'b')\nplt.show()\n\n\n","sub_path":"financial/compound_interest_calculator.py","file_name":"compound_interest_calculator.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"458341707","text":"import numpy as np\nimport cv2\nimport cv2.aruco as aruco\n\n\nip_left = \"rtsp://192.168.0.129:554/Streaming/Channels/1/?transportmode=unicast\"\nip_right = \"rtsp://192.168.0.130:554/Streaming/Channels/1/?transportmode=unicast\"\n\ncap1 = cv2.VideoCapture(ip_left)\ncap2 = cv2.VideoCapture(ip_right)\n\ncv2.namedWindow('image1', cv2.WINDOW_NORMAL)\ncv2.namedWindow('image2', cv2.WINDOW_NORMAL)\n\ncv2.resizeWindow('image1', 640, 480)\ncv2.resizeWindow('image2', 640, 480)\n\n\n\nfs = cv2.FileStorage(\"intrinsics.yml\", cv2.FILE_STORAGE_READ)\ncm1 = fs.getNode(\"M1\").mat()\ndc1 = fs.getNode(\"D1\").mat()\n\ncm2 = fs.getNode(\"M2\").mat()\ndc2 = fs.getNode(\"D2\").mat()\n\n\n\nfs = cv2.FileStorage(\"extrinsics.yml\", cv2.FILE_STORAGE_READ)\nP1 = fs.getNode(\"P1\").mat()\nP2 = fs.getNode(\"P2\").mat()\n\nR = fs.getNode(\"R\").mat()\nT = fs.getNode(\"T\").mat()\n\n\n# print(R)\n# print(T)\n# exit()\n\n\n\naruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_50)\nparameters = aruco.DetectorParameters_create()\ng=0\n\nwhile(True):\n # Capture frame-by-frame\n ret1, frame1 = cap1.read()\n ret2, frame2 = cap2.read()\n\n # Our operations on the frame come here\n # gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)\n # gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY) \n\n dd1 = cv2.undistort(frame1, cm1, dc1)\n dd2 = cv2.undistort(frame2, cm2, dc2)\n\n\n corners1, ids1, rejectedImgPoints1 = aruco.detectMarkers(frame1, aruco_dict, parameters=parameters)\n corners2, ids2, rejectedImgPoints2 = aruco.detectMarkers(frame2, aruco_dict, parameters=parameters)\n\n\n ud1, ids11, rejectedImgPoints11 = aruco.detectMarkers(dd1, aruco_dict, parameters=parameters)\n ud2, ids22, rejectedImgPoints22 = aruco.detectMarkers(dd2, aruco_dict, parameters=parameters)\n\n\n gray1 = aruco.drawDetectedMarkers(frame1, corners1)\n gray2 = aruco.drawDetectedMarkers(frame2, corners2)\n\n # print(corners2[0])\n # print(ud2[0])\n # exit()\n\n\n try: \n\n if g==0:\n g=g+1\n points4D = cv2.triangulatePoints(P1, P2, ud1[0], ud2[0])\n # print(points4D)\n\n\n points3D = cv2.convertPointsFromHomogeneous(points4D)\n # print(points3D)\n # exit()\n \n\n # projectedPoints = P1.dot(points4D)\n # print(projectedPoints)\n\n # cameraMatrix, rotMatrix, transVect, rotMatrixX, rotMatrixY, rotMatrixZ, eulerAngles = cv2.decomposeProjectionMatrix(P1)\n # print(cameraMatrix)\n # exit()\n\n # imagePoints, jacobian = cv2.projectPoints( points3D, rotMatrix, transVect, cameraMatrix, dc1)\n # print(imagePoints)\n # exit()\n\n rvecs, tvecs, _objPoints = cv2.aruco.estimatePoseSingleMarkers(corners1[0], 0.158, cm1, dc1)\n # print(rvecs[0])\n # exit()\n\n # # rotation_mat = np.zeros(shape=(3, 3))\n R1 = cv2.Rodrigues(rvecs[0])[0]\n T1 = np.transpose(tvecs[0])\n # # print(T1)\n # # exit() \n \n\n P1_new = np.zeros(shape=(3, 4))\n temp1 = np.zeros(shape=(3, 4))\n temp1 = np.concatenate((R1, T1), axis=1) \n\n P1_new = np.matmul(cm1, temp1)\n # # print(P1_new)\n # # exit()\n\n\n\n # # ===================================================================================\\\n # # rvecs for the second camera\n rvecs2, tvecs2, _objPoints2 = cv2.aruco.estimatePoseSingleMarkers(corners2[0], 0.158, cm2, dc2)\n R2 = cv2.Rodrigues(rvecs2[0])[0]\n T2 = np.transpose(tvecs2[0])\n # # print(T2)\n # # exit() \n\n P2_new = np.zeros(shape=(3, 4))\n temp2 = np.zeros(shape=(3, 4))\n temp2 = np.concatenate((R2, T2), axis=1) \n\n P2_new = np.matmul(cm2, temp2)\n # # print(P2_new)\n # # exit()\n\n\n\n R2 = np.matmul(R,R1)\n T2 = np.matmul(R,T1) + T\n\n \n # R2 = cv2.Rodrigues(rvecs2[0])[0]\n # T2 = np.transpose(tvecs2[0])\n # # print(T2)\n # # exit() \n\n P2_new = np.zeros(shape=(3, 4))\n temp2 = np.zeros(shape=(3, 4))\n temp2 = np.concatenate((R2, T2), axis=1) \n\n P2_new = np.matmul(cm2, temp2)\n\n\n\n\n points4D = cv2.triangulatePoints(P1_new, P2_new, ud1[0], ud2[0])\n # # print(points4D)\n # # exit()\n\n points3D = cv2.convertPointsFromHomogeneous(points4D)\n print(points3D)\n exit()\n\n\n\n except Exception as e:\n # pass\n print(e)\n exit()\n # print(corners2[0])\n \n\n\n\n\n\n\n # Display the resulting frame\n cv2.imshow('image1',gray1)\n cv2.imshow('image2',gray2)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything done, release the capture\ncap1.release()\ncap2.release()\ncv2.destroyAllWindows()","sub_path":"triangulate3.py","file_name":"triangulate3.py","file_ext":"py","file_size_in_byte":4915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"8496967","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# noinspection PyUnresolvedReferences\nimport vtkmodules.vtkInteractionStyle\n# noinspection PyUnresolvedReferences\nimport vtkmodules.vtkRenderingOpenGL2\nfrom vtkmodules.vtkCommonColor import vtkNamedColors\nfrom vtkmodules.vtkCommonCore import (\n vtkCommand,\n vtkMinimalStandardRandomSequence,\n vtkPoints\n)\nfrom vtkmodules.vtkCommonDataModel import (\n vtkGenericCell,\n vtkQuadraticHexahedron,\n vtkUnstructuredGrid\n)\nfrom vtkmodules.vtkFiltersCore import vtkGlyph3D\nfrom vtkmodules.vtkFiltersGeneral import vtkTessellatorFilter\nfrom vtkmodules.vtkFiltersSources import vtkSphereSource\nfrom vtkmodules.vtkInteractionWidgets import (\n vtkSliderRepresentation2D,\n vtkSliderWidget\n)\nfrom vtkmodules.vtkRenderingCore import (\n vtkActor,\n vtkActor2D,\n vtkDataSetMapper,\n vtkRenderWindow,\n vtkRenderWindowInteractor,\n vtkRenderer,\n vtkTextMapper,\n vtkTextProperty\n)\n\n\ndef main():\n namedColors = vtkNamedColors()\n\n uGrid = MakeQuadraticHexahedron()\n\n tessellate = vtkTessellatorFilter()\n tessellate.SetInputData(uGrid)\n tessellate.SetChordError(0.035)\n tessellate.Update()\n\n cellMap = dict()\n\n numTets = 0\n cell = vtkGenericCell()\n it = tessellate.GetOutput().NewCellIterator()\n it.InitTraversal()\n while not it.IsDoneWithTraversal():\n it.GetCell(cell)\n cellMap[cell.GetRepresentativeCell().GetClassName()] = numTets\n numTets += 1\n it.GoToNextCell()\n\n mapper = vtkDataSetMapper()\n mapper.SetInputConnection(tessellate.GetOutputPort())\n mapper.ScalarVisibilityOff()\n\n # Create an actor for the grid\n actor = vtkActor()\n actor.SetMapper(mapper)\n actor.GetProperty().SetDiffuseColor(\n namedColors.GetColor3d('Tomato'))\n actor.GetProperty().SetEdgeColor(\n namedColors.GetColor3d('IvoryBlack'))\n actor.GetProperty().EdgeVisibilityOn()\n\n sphereSource = vtkSphereSource()\n sphereSource.SetRadius(0.02)\n\n glyph3D = vtkGlyph3D()\n glyph3D.SetInputData(uGrid)\n glyph3D.SetSourceConnection(sphereSource.GetOutputPort())\n glyph3D.ScalingOff()\n glyph3D.Update()\n\n glyph3DMapper = vtkDataSetMapper()\n glyph3DMapper.SetInputConnection(glyph3D.GetOutputPort())\n glyph3DMapper.ScalarVisibilityOff()\n\n glyph3DActor = vtkActor()\n glyph3DActor.SetMapper(glyph3DMapper)\n glyph3DActor.GetProperty().SetColor(\n namedColors.GetColor3d('Banana'))\n\n textProperty = vtkTextProperty()\n textProperty.SetFontSize(24)\n\n ss = '# of Tetras: ' + str(numTets)\n textMapper = vtkTextMapper()\n textMapper.SetInput(ss)\n textMapper.SetTextProperty(textProperty)\n\n textActor = vtkActor2D()\n textActor.SetMapper(textMapper)\n textActor.SetPosition(10, 400)\n\n # Visualize\n renderer = vtkRenderer()\n renderWindow = vtkRenderWindow()\n renderWindow.SetWindowName('QuadraticHexahedronDemo')\n renderWindow.AddRenderer(renderer)\n renderWindow.SetSize(640, 512)\n interactor = vtkRenderWindowInteractor()\n interactor.SetRenderWindow(renderWindow)\n\n widget = vtkSliderWidget()\n MakeWidget(widget, tessellate, textMapper, interactor)\n\n renderer.AddActor(actor)\n renderer.AddActor(glyph3DActor)\n renderer.AddViewProp(textActor)\n renderer.SetBackground(namedColors.GetColor3d('SlateGray'))\n\n renderWindow.Render()\n\n interactor.Start()\n\n\nclass SliderCallbackChordError():\n def __init__(self, tessellate, textMapper):\n self.tessellate = tessellate\n self.textMapper = textMapper\n\n def __call__(self, caller, ev):\n sliderWidget = caller\n value = sliderWidget.GetRepresentation().GetValue()\n self.tessellate.SetChordError(value)\n self.tessellate.SetMaximumNumberOfSubdivisions(4)\n self.tessellate.Update()\n\n cellMap = dict()\n\n numTets = 0\n cell = vtkGenericCell()\n it = self.tessellate.GetOutput().NewCellIterator()\n it.InitTraversal()\n while not it.IsDoneWithTraversal():\n it.GetCell(cell)\n cellMap[cell.GetRepresentativeCell().GetClassName()] = numTets\n numTets += 1\n it.GoToNextCell()\n ss = '# of Tetras: ' + str(numTets)\n self.textMapper.SetInput(ss)\n\n\ndef MakeWidget(widget, tessellate, textMapper, interactor):\n # Setup a slider widget for each varying parameter\n tubeWidth = 0.008\n sliderLength = 0.008\n titleHeight = 0.04\n labelHeight = 0.04\n\n sliderRepChordError = vtkSliderRepresentation2D()\n\n sliderRepChordError.SetMinimumValue(0.0)\n sliderRepChordError.SetMaximumValue(0.07)\n sliderRepChordError.SetValue(tessellate.GetChordError())\n sliderRepChordError.SetTitleText('Chord error')\n\n sliderRepChordError.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()\n sliderRepChordError.GetPoint1Coordinate().SetValue(0.1, 0.1)\n sliderRepChordError.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()\n sliderRepChordError.GetPoint2Coordinate().SetValue(0.9, 0.1)\n\n sliderRepChordError.SetTubeWidth(tubeWidth)\n sliderRepChordError.SetSliderLength(sliderLength)\n sliderRepChordError.SetTitleHeight(titleHeight)\n sliderRepChordError.SetLabelHeight(labelHeight)\n\n widget.SetInteractor(interactor)\n widget.SetRepresentation(sliderRepChordError)\n widget.SetAnimationModeToAnimate()\n widget.EnabledOn()\n\n widget.AddObserver(vtkCommand.InteractionEvent, SliderCallbackChordError(tessellate, textMapper))\n\n\ndef MakeQuadraticHexahedron():\n aHexahedron = vtkQuadraticHexahedron()\n points = vtkPoints()\n\n pcoords = aHexahedron.GetParametricCoords()\n rng = vtkMinimalStandardRandomSequence()\n points.SetNumberOfPoints(aHexahedron.GetNumberOfPoints())\n rng.SetSeed(5070) # for testing\n for i in range(0, aHexahedron.GetNumberOfPoints()):\n perturbation = [0.0] * 3\n for j in range(0, 3):\n rng.Next()\n perturbation[j] = rng.GetRangeValue(-0.1, 0.1)\n aHexahedron.GetPointIds().SetId(i, i)\n points.SetPoint(i, pcoords[3 * i] + perturbation[0],\n pcoords[3 * i + 1] + perturbation[1],\n pcoords[3 * i + 2] + perturbation[2])\n\n # Add the points and hexahedron to an unstructured grid\n uGrid = vtkUnstructuredGrid()\n uGrid.SetPoints(points)\n uGrid.InsertNextCell(aHexahedron.GetCellType(), aHexahedron.GetPointIds())\n\n return uGrid\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/Python/GeometricObjects/QuadraticHexahedronDemo.py","file_name":"QuadraticHexahedronDemo.py","file_ext":"py","file_size_in_byte":6479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"148805183","text":"import sys\n\nfrom PyQt5.QtGui import QPalette, QColor\nfrom PyQt5.QtWidgets import QApplication, QWidget, QScrollBar, QHBoxLayout, QLabel\n\n\nclass ScrollDemo(QWidget):\n \"\"\"主窗口\"\"\"\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n self.setWindowTitle(\"QScrollBar 使用\")\n\n self.label = QLabel(\"拖动滑块改变颜色\")\n\n self.scroll_red = QScrollBar()\n self.scroll_green = QScrollBar()\n self.scroll_blue = QScrollBar()\n\n self.scroll_red.setRange(0, 255)\n self.scroll_green.setRange(0, 255)\n self.scroll_blue.setRange(0, 255)\n\n self.scroll_red.sliderMoved.connect(self.slider_value)\n self.scroll_green.sliderMoved.connect(self.slider_value)\n self.scroll_blue.sliderMoved.connect(self.slider_value)\n\n h_layout = QHBoxLayout()\n h_layout.addWidget(self.label)\n h_layout.addWidget(self.scroll_red)\n h_layout.addWidget(self.scroll_green)\n h_layout.addWidget(self.scroll_blue)\n\n self.setLayout(h_layout)\n\n def slider_value(self):\n # print(\"rgb(%s, %s, %d)\" % (self.scroll_red.value(), self.scroll_green.value(), self.scroll_blue.value()))\n palette = QPalette()\n color = QColor(self.scroll_red.value(), self.scroll_green.value(), self.scroll_blue.value())\n palette.setColor(QPalette.Foreground, color)\n self.label.setPalette(palette)\n\n\nif __name__ == \"__main__\":\n\n app = QApplication(sys.argv)\n win = ScrollDemo()\n win.show()\n sys.exit(app.exec())","sub_path":"03_高级界面控件/示例内容/08_ScrollBar.py","file_name":"08_ScrollBar.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"471196984","text":"# Route to a webpage with a form\n# Post route from the form (Asynchronously called by AJAX)\n# Call the machine learning model .predict method on the data that passed from the form\n# return Json and python dictionaries (Jsonify)\n# AJAX calling function on the webform will update a div id with the results\n\nfrom flask import Flask, render_template, request\nimport requests\nimport pickle\nimport numpy as np\nimport sklearn\n\n\napp = Flask(__name__)\nmodel = pickle.load(open(\"./Machine Learning Modeling/dtree_model.sav\", 'rb'))\nfinal_prediction = \"No prediction yet.\"\n\n@app.route('/', methods=['GET'])\ndef Home():\n return render_template('index.html')\n\n@app.route(\"/predict\", methods=['POST'])\ndef predict():\n if request.method == 'POST':\n Year = int(request.form['YearInput'])\n Km_Driven = int(request.form['KmDrivenInput'])\n Fuel_Type = request.form['FuelTypeInput']\n\n if(Fuel_Type == 'Petrol'):\n Fuel_Diesel = 0\n Fuel_Other = 0\n Fuel_Petrol = 1\n elif(Fuel_Type == 'Diesel'):\n Fuel_Diesel = 1\n Fuel_Other = 0\n Fuel_Petrol = 0\n else:\n Fuel_Diesel = 0\n Fuel_Other = 1\n Fuel_Petrol = 0\n Seller_Type = request.form['SellerTypeInput']\n if(Seller_Type == 'Individual'):\n Seller_Type_Dealer = 0\n Seller_Type_Individual = 1\n Seller_Type_TrustmarkDealer = 0\n elif(Seller_Type == 'Dealer'):\n Seller_Type_Dealer = 1\n Seller_Type_Individual = 0\n Seller_Type_TrustmarkDealer = 0\n else:\n Seller_Type_Dealer = 0\n Seller_Type_Individual = 0\n Seller_Type_TrustmarkDealer = 1\n Transmission = request.form['TransmissionTypeInput']\n if(Transmission == 'Automatic'):\n Transmission_Automatic = 1\n Transmission_Manual = 0\n else:\n Transmission_Automatic = 0\n Transmission_Manual = 1\n Made_in = request.form['MadeInInput']\n if(Made_in == 'America'):\n Made_in_America = 1\n Made_in_Asia = 0\n Made_in_Europe = 0\n Made_in_India = 0\n Made_in_Unknown = 0\n elif(Made_in == 'Asia'):\n Made_in_America = 0\n Made_in_Asia = 1\n Made_in_Europe = 0\n Made_in_India = 0\n Made_in_Unknown = 0\n elif(Made_in == 'Europe'):\n Made_in_America = 0\n Made_in_Asia = 0\n Made_in_Europe = 1\n Made_in_India = 0\n Made_in_Unknown = 0\n elif(Made_in == 'India'):\n Made_in_America = 0\n Made_in_Asia = 0\n Made_in_Europe = 0\n Made_in_India = 1\n Made_in_Unknown = 0\n else:\n Made_in_America = 0\n Made_in_Asia = 0\n Made_in_Europe = 0\n Made_in_India = 0\n Made_in_Unknown = 1\n\n to_predict = [[Year, Km_Driven, Fuel_Diesel, Fuel_Other, Fuel_Petrol, Seller_Type_Dealer, Seller_Type_Individual, Seller_Type_TrustmarkDealer,\n Transmission_Automatic, Transmission_Manual, Made_in_America, Made_in_Asia, Made_in_Europe, Made_in_India, Made_in_Unknown]]\n prediction = model.predict(to_predict)\n output = prediction\n\n return render_template('withPredict.html', final_prediction=f\"The car can be sold at {output} rupees.\")\n\n else:\n return render_template('index.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True) \n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"525923064","text":"from facebase.photo import Photo\nfrom facebase.geometry import Area\nimport numpy as np\nimport os\n\n\nclass Face:\n def __init__(self, area, landmarks, encoding, photo, confidence=1.01):\n self.area = area\n if isinstance(landmarks, list) or isinstance(landmarks, np.ndarray):\n self.landmarks = landmarks\n else:\n self.landmarks = np.array([[ps.x - area.point_top.x,\n ps.y - area.point_top.y]\n for ps in landmarks.parts()])\n self.encoding = encoding\n self.photo = photo\n self.confidence = confidence\n\n def to_dict(self):\n face_dict = dict()\n face_dict['area'] = self.area.to_dict()\n face_dict['landmarks'] = self.landmarks.tolist()\n face_dict['encoding'] = self.encoding.tolist()\n face_dict['photo'] = self.photo.to_dict()\n face_dict['confidence'] = self.confidence\n return face_dict\n\n @staticmethod\n def from_dict(face_dict):\n return Face(area=Area.from_dict(face_dict['area']),\n landmarks=np.array(face_dict['landmarks']),\n encoding=np.array(face_dict['encoding']),\n photo=Photo.from_dict(face_dict['photo']),\n confidence=face_dict['confidence'])\n\n def face(self):\n return self.photo.crop(self.area)\n\n def to_base64(self):\n return self.face().to_base64()\n\n def move_source(self, new_image_path):\n if os.path.exists(new_image_path):\n raise FileExistsError\n self.photo.move_source(new_image_path)\n\n def change_source(self, new_image_path):\n self.photo.change_source(new_image_path)\n\n def __repr__(self):\n face_dict = self.to_dict()\n face_dict['encoding'] = face_dict['encoding']\n return str(face_dict)\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"facebase/face.py","file_name":"face.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"602691086","text":"# need to import request module\nimport requests\n\n# Getting details via url\nurl=\"https://en-gb.facebook.com/\"\nresponse= requests.get(url)\n\n# Printing HTML of the page\n#print(response.text)\n\n# Printing status code of the page\n#print(response.status_code)\n\n# Saving the read data in the txt file\n\nf=open(\"C:/Users/ramadhma/Selenium/read.txt\",'wb')\n\nfor data in response.iter_content(10000):\n f.write(data)\n\nf.close()\n","sub_path":"WebScraping/Request.py","file_name":"Request.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"76771029","text":"from util import Stack\n\n\n# First pass solution utilizing graph-like structure without an actual graph class\ndef earliest_ancestor(ancestors, starting_node):\n # create a hashmap to store all nodes\n ancestor_hashmap = {}\n # { key -> node: value -> set of node's direct ancestors }\n for a in ancestors:\n if a[1] not in ancestor_hashmap:\n ancestor_hashmap[a[1]] = set()\n if a[0] not in ancestor_hashmap:\n ancestor_hashmap[a[0]] = set()\n\n ancestor_hashmap[a[1]].add(a[0])\n # Use DFS helper function to find oldest node or return -1 if starting_node is oldest\n return DFT(starting_node, ancestor_hashmap)\n\n\ndef DFT(starting_node, ancestor_hashmap):\n s = Stack()\n visited = set()\n s.push([starting_node])\n\n oldest_ancestor = -1\n longest_path = 0\n\n while s.size() > 0:\n curr_path = s.pop()\n curr_node = curr_path[-1]\n print(curr_node)\n\n if len(curr_path) > longest_path and curr_node != starting_node:\n longest_path = len(curr_path)\n oldest_ancestor = curr_node\n\n if curr_node not in visited:\n visited.add(curr_node)\n\n for neighbor in ancestor_hashmap[curr_node]:\n path_copy = list(curr_path)\n path_copy.append(neighbor)\n s.push(path_copy)\n\n return oldest_ancestor\n\n\nancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7),\n (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)]\n\n\nprint(earliest_ancestor(ancestors, 8))\n","sub_path":"projects/ancestor/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"620303875","text":"def run_scenario_two_m1():\n ## Global epidemic in Allegheny county\n\n ## Setting up some parameters that will be looped through the main function\n #opening_cost = [5000, 10000, 25000, 50000]\n #budget = [1000000, 2500000, 5000000, 10000000]\n opening_cost = [5000]\n budget = [1000000]\n bigM = 100000000000000000000 ## This is our big M\n\n ## Define Parameters\n (pod_sites, blocks, distance, population, loadingSites, capacity, supplies, labor, cost, max_days_open) = define_parameters()\n print(\"*** Set up parameters...\")\n\n pgh_blocks_idx = genfromtxt(path + '/pgh_blocks.csv', delimiter=',')\n pitts_pods_idx = np.array([2, 3, 6, 11, 18, 28, 29, 30, 40, 41, 45])\n pitts_pods_idx = pitts_pods_idx - 1\n pitts_pods_idx = pitts_pods_idx.tolist()\n pitts_pods_idx = genfromtxt(path + '/pgh_pods.csv', delimiter=',') \n\n num_pod_sites = len(pitts_pods_idx)\n num_blocks = len(pgh_blocks_idx)\n\n pod_sites = range(num_pod_sites)\n blocks = range(num_blocks)\n\n pod_sites = [pod_sites[i] for i in pitts_pods_idx]\n blocks = [blocks[k] for k in (int(i) for i in pgh_blocks_idx)]\n population = [population[k] for k in (int(i) for i in pgh_blocks_idx)]\n loadingSites = [loadingSites[i] for i in pitts_pods_idx]\n capacity = [capacity[i] for i in pitts_pods_idx]\n cost = [cost[i] for i in pitts_pods_idx]\n distance = np.take(distance, pgh_blocks_idx, axis = 0)\n distance = np.take(distance, pitts_pods_idx, axis = 1)\n \n\n s1_m1_optsoln = []\n good_options = []\n bad_options = []\n s1_m1_pods = []\n s1_m1_dist = []\n\n ## Loop through budget values, then opening cost to find optimal solutions \n for b in budget:\n for op_co in opening_cost:\n try:\n (m1_opt_solution, lst, pod_days, block_dist) = min_tot_distance(pod_sites, blocks, distance, \n population, loadingSites, capacity, supplies, labor, cost, b, op_co, bigM, max_days_open)\n good_options.append((m1_opt_solution, lst))\n\n ## First we make a list of the budget, opening cost, and optimal solution for that pair\n s1_m1_optsoln.append((b, op_co, m1_opt_solution))\n ## List of Tuples #2\n m1_pods = [(b, op_co, pod[0], pod[1]) for pod in pod_days]\n #s1_m1_pods.extend(m1_pods)\n s1_m1_pods = s1_m1_pods + m1_pods\n m1_dist = [(b, op_co, bdist[0], bdist[1]) for bdist in block_dist]\n #s1_m1_dist.extend(m1_dist)\n s1_m1_dist = s1_m1_dist + m1_dist\n\n except AttributeError:\n bad_options.append((b, op_co))\n print(\"*** Budget\", b, \"with opening cost\", op_co, \"was infeasible...moving on...\")\n continue\n\n s1_m1_opt_vals_df = pd.DataFrame(s1_m1_optsoln, columns = ['Budget', 'Cost', 'TotalTravel(mi)'])\n s1_m1_pods_df = pd.DataFrame(s1_m1_pods, columns = ['Budget', 'Cost', 'POD', 'Days Open'])\n s1_m1_dist_df = pd.DataFrame(s1_m1_dist, columns = ['Budget', 'Cost', 'Block', 'DistTravel(mi)'])\n #print(\"*** THESE ARE THE GOOD OPTIONS: \\n\", good_options)\n\n ## Save these to csv so that plotting can be done without running everything\n s1_m1_opt_vals_df.to_csv('s1_m1_optimalVals.csv', encoding = 'utf-8')\n s1_m1_pods_df.to_csv('s1_m1_podDays.csv', encoding = 'utf-8')\n s1_m1_dist_df.to_csv('s1_m1_blockDistances.csv', encoding = 'utf-8')\n\n return(s1_m1_opt_vals_df, s1_m1_pods_df, s1_m1_dist_df)\n","sub_path":"V2_DABP_Code/scenario2_m1.py","file_name":"scenario2_m1.py","file_ext":"py","file_size_in_byte":3496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"279028397","text":"\n# coding: utf-8\n\n# In[3]:\n\npython -v\n\n\n# In[4]:\n\nimport numpy as np\n\n\n# In[5]:\n\nimport pandas as pd\n\n\n# In[6]:\n\ntitanic = pd.read_csv(\"/var/data/practice_data/titanic_train_data.csv\")\n\n\n# In[7]:\n\ntitanic.head()\n\n\n# In[8]:\n\ntitanic_test = pd.read_csv(\"/var/data/practice_data/titanic_test.csv\")\n\n\n# In[9]:\n\ntitanic_test.head().T\n\n\n# In[10]:\n\ntitanic.shape\n\n\n# In[12]:\n\ntitanic.describe()\n\n\n# In[13]:\n\ntitanic.info()\n\n\n# In[14]:\n\ntitanic.isnull().sum()\n\n\n# In[15]:\n\ntitanic_test.isnull().sum()\n\n\n# In[16]:\n\nget_ipython().magic(u'matplotlib inline')\n\n\n# In[17]:\n\nimport matplotlib.pyplot as plt\n\n\n# In[22]:\n\nimport seaborn as sns\n\n\n# In[23]:\n\nsns.set(font_scale=1)\n\n\n# In[24]:\n\npd.options.display.mpl_style = 'default'\n\n\n# In[30]:\n\ng = sns.FacetGrid(titanic, hue=\"Survived\", col=\"Pclass\", margin_titles=True,\n palette={1:\"seagreen\", 0:\"gray\"})\ng=g.map(plt.scatter, \"Fare\", \"Age\",edgecolor=\"w\").add_legend()\n\n\n# In[31]:\n\ng = sns.FacetGrid(titanic, hue=\"Survived\", col=\"Sex\", margin_titles=True,\n palette=\"Set1\",hue_kws=dict(marker=[\"^\", \"v\"]))\ng.map(plt.scatter, \"Fare\", \"Age\",edgecolor=\"w\").add_legend()\nplt.subplots_adjust(top=0.8)\ng.fig.suptitle('Survival by Gender , Age and Fare')\n\n\n# In[32]:\n\ntitanic.Embarked.value_counts().plot(kind='bar', alpha=0.55)\nplt.title(\"Passengers per boarding location\")\n\n\n# In[34]:\n\nsns.set(font_scale=1)\ng = sns.factorplot(x=\"Sex\", y=\"Survived\", col=\"Pclass\",\n data=titanic, saturation=.5,\n kind=\"bar\", ci=None, aspect=.6)\n(g.set_axis_labels(\"\", \"Survival Rate\")\n .set_xticklabels([\"Men\", \"Women\"])\n .set_titles(\"{col_name} {col_var}\")\n .set(ylim=(0, 1))\n .despine(left=True)) \nplt.subplots_adjust(top=0.8)\ng.fig.suptitle('How many Men and Women Survived by Passenger Class')\n\n\n# In[35]:\n\nax = sns.boxplot(x=\"Survived\", y=\"Age\", \n data=titanic)\nax = sns.stripplot(x=\"Survived\", y=\"Age\",\n data=titanic, jitter=True,\n edgecolor=\"gray\")\nsns.plt.title(\"Survival by Age\",fontsize=12)\n\n\n# In[38]:\n\ntitanic.Age[titanic.Pclass == 1].plot(kind='kde') \ntitanic.Age[titanic.Pclass == 2].plot(kind='kde')\ntitanic.Age[titanic.Pclass == 3].plot(kind='kde')\nplt.xlabel(\"Age\") \nplt.title(\"Age Distribution within classes\")\nplt.legend(('1st Class', '2nd Class','3rd Class'),loc='best')\n\n\n# In[39]:\n\ncorr=titanic.corr()\n\n\n# In[40]:\n\nplt.figure(figsize=(10, 10))\n\nsns.heatmap(corr, vmax=1, square=True,annot=True,cmap='cubehelix')\nplt.title('Correlation between features')\n\n\n# In[41]:\n\ntitanic.corr()[\"Survived\"]\n\n\n# In[42]:\n\ng = sns.factorplot(x=\"Age\", y=\"Embarked\",\n hue=\"Sex\", row=\"Pclass\",\n data=titanic[titanic.Embarked.notnull()],\n orient=\"h\", size=2, aspect=3.5, \n palette={'male':\"purple\", 'female':\"blue\"},\n kind=\"violin\", split=True, cut=0, bw=.2)\n\n\n# In[43]:\n\ntitanic[titanic['Embarked'].isnull()]\n\n\n# In[44]:\n\nsns.boxplot(x=\"Embarked\", y=\"Fare\", hue=\"Pclass\", data=titanic)\n\n\n# In[46]:\n\ntitanic[\"Embarked\"] = titanic[\"Embarked\"].fillna('C') # considering the median value of 1st class embarked value C has close to 80$\n\n\n# In[47]:\n\ntitanic_test.describe()\n\n\n# In[48]:\n\ntitanic_test[titanic_test['Fare'].isnull()]\n\n\n# In[49]:\n\ndef fill_missing_fare(df):\n median_fare=df[(df['Pclass'] == 3) & (df['Embarked'] == 'S')]['Fare'].median()\n df[\"Fare\"] = df[\"Fare\"].fillna(median_fare)\n return df\ntitanic_test=fill_missing_fare(titanic_test)\n\n\n# In[50]:\n\ntitanic[\"Deck\"]=titanic.Cabin.str[0]\ntitanic_test[\"Deck\"]=titanic_test.Cabin.str[0]\ntitanic[\"Deck\"].unique() # this is to take into considering where exactly a passenger was.\n\n\n# In[51]:\n\ng = sns.factorplot(\"Survived\", col=\"Deck\", col_wrap=4,\n data=titanic[titanic.Deck.notnull()],\n kind=\"count\", size=2.5, aspect=.8)\n\n\n# In[52]:\n\ntitanic = titanic.assign(Deck=titanic.Deck.astype(object)).sort(\"Deck\")\ng = sns.FacetGrid(titanic, col=\"Pclass\", sharex=False,\n gridspec_kws={\"width_ratios\": [5, 3, 3]})\ng.map(sns.boxplot, \"Deck\", \"Age\");\n\n\n# In[53]:\n\ntitanic.Deck.fillna('Z', inplace=True)\ntitanic_test.Deck.fillna('Z', inplace=True)\ntitanic[\"Deck\"].unique()\n\n\n# In[54]:\n\ntitanic[\"FamilySize\"] = titanic[\"SibSp\"] + titanic[\"Parch\"]+1\ntitanic_test[\"FamilySize\"] = titanic_test[\"SibSp\"] + titanic_test[\"Parch\"]+1\nprint(titanic[\"FamilySize\"].value_counts())\n\n\n# In[55]:\n\ntitanic.loc[titanic[\"FamilySize\"] == 1, \"FsizeD\"] = 'singleton'\ntitanic.loc[(titanic[\"FamilySize\"] > 1) & (titanic[\"FamilySize\"] < 5) , \"FsizeD\"] = 'small'\ntitanic.loc[titanic[\"FamilySize\"] >4, \"FsizeD\"] = 'large'\n\ntitanic_test.loc[titanic_test[\"FamilySize\"] == 1, \"FsizeD\"] = 'singleton'\ntitanic_test.loc[(titanic_test[\"FamilySize\"] >1) & (titanic_test[\"FamilySize\"] <5) , \"FsizeD\"] = 'small'\ntitanic_test.loc[titanic_test[\"FamilySize\"] >4, \"FsizeD\"] = 'large'\nprint(titanic[\"FsizeD\"].unique())\nprint(titanic[\"FsizeD\"].value_counts())\n\n\n# In[56]:\n\nsns.factorplot(x=\"FsizeD\", y=\"Survived\", data=titanic)\n\n\n# In[57]:\n\ntitanic[\"NameLength\"] = titanic[\"Name\"].apply(lambda x: len(x))\ntitanic_test[\"NameLength\"] = titanic_test[\"Name\"].apply(lambda x: len(x))\nbins = [0, 20, 40, 57, 85]\ngroup_names = ['short', 'okay', 'good', 'long']\ntitanic['NlengthD'] = pd.cut(titanic['NameLength'], bins, labels=group_names)\ntitanic_test['NlengthD'] = pd.cut(titanic_test['NameLength'], bins, labels=group_names)\n\nsns.factorplot(x=\"NlengthD\", y=\"Survived\", data=titanic)\nprint(titanic[\"NlengthD\"].unique())\n\n\n# In[58]:\n\nimport re\ndef get_title(name):\n title_search = re.search(' ([A-Za-z]+)\\.', name)\n if title_search:\n return title_search.group(1)\n return \"\"\ntitles = titanic[\"Name\"].apply(get_title)\nprint(pd.value_counts(titles))\n\ntitanic[\"Title\"] = titles\n\nrare_title = ['Dona', 'Lady', 'Countess','Capt', 'Col', 'Don', \n 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer']\n\ntitanic.loc[titanic[\"Title\"] == \"Mlle\", \"Title\"] = 'Miss'\ntitanic.loc[titanic[\"Title\"] == \"Ms\", \"Title\"] = 'Miss'\ntitanic.loc[titanic[\"Title\"] == \"Mme\", \"Title\"] = 'Mrs'\ntitanic.loc[titanic[\"Title\"] == \"Dona\", \"Title\"] = 'Rare Title'\ntitanic.loc[titanic[\"Title\"] == \"Lady\", \"Title\"] = 'Rare Title'\ntitanic.loc[titanic[\"Title\"] == \"Countess\", \"Title\"] = 'Rare Title'\ntitanic.loc[titanic[\"Title\"] == \"Capt\", \"Title\"] = 'Rare Title'\ntitanic.loc[titanic[\"Title\"] == \"Col\", \"Title\"] = 'Rare Title'\ntitanic.loc[titanic[\"Title\"] == \"Don\", \"Title\"] = 'Rare Title'\ntitanic.loc[titanic[\"Title\"] == \"Major\", \"Title\"] = 'Rare Title'\ntitanic.loc[titanic[\"Title\"] == \"Rev\", \"Title\"] = 'Rare Title'\ntitanic.loc[titanic[\"Title\"] == \"Sir\", \"Title\"] = 'Rare Title'\ntitanic.loc[titanic[\"Title\"] == \"Jonkheer\", \"Title\"] = 'Rare Title'\ntitanic.loc[titanic[\"Title\"] == \"Dr\", \"Title\"] = 'Rare Title'\n\ntitanic[\"Title\"].value_counts()\n\n\ntitles = titanic_test[\"Name\"].apply(get_title)\nprint(pd.value_counts(titles))\n\ntitanic_test[\"Title\"] = titles\n\nrare_title = ['Dona', 'Lady', 'Countess','Capt', 'Col', 'Don', \n 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer']\n\ntitanic_test.loc[titanic_test[\"Title\"] == \"Mlle\", \"Title\"] = 'Miss'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Ms\", \"Title\"] = 'Miss'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Mme\", \"Title\"] = 'Mrs'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Dona\", \"Title\"] = 'Rare Title'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Lady\", \"Title\"] = 'Rare Title'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Countess\", \"Title\"] = 'Rare Title'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Capt\", \"Title\"] = 'Rare Title'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Col\", \"Title\"] = 'Rare Title'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Don\", \"Title\"] = 'Rare Title'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Major\", \"Title\"] = 'Rare Title'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Rev\", \"Title\"] = 'Rare Title'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Sir\", \"Title\"] = 'Rare Title'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Jonkheer\", \"Title\"] = 'Rare Title'\ntitanic_test.loc[titanic_test[\"Title\"] == \"Dr\", \"Title\"] = 'Rare Title'\n\ntitanic_test[\"Title\"].value_counts()\n\n\n# In[59]:\n\ntitanic[\"Ticket\"].tail()\n\n\n# In[75]:\n\ntitanic[\"TicketNumber\"] = titanic[\"Ticket\"].str.extract('(\\d{2,})')\ntitanic_test[\"TicketNumber\"] = titanic_test[\"Ticket\"].str.extract('(\\d{2,})')\n\n\n# In[76]:\n\ntitanic[titanic[\"TicketNumber\"].isnull()]\n\n\n# In[77]:\n\ntitanic.TicketNumber.fillna(titanic[\"TicketNumber\"].median(), inplace=True)\ntitanic_test.TicketNumber.fillna(titanic_test[\"TicketNumber\"].median(), inplace=True)\n\n\n# In[78]:\n\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\n\n\n# In[79]:\n\nlabelEnc=LabelEncoder()\n\ncat_vars=['Embarked','Sex',\"Title\",\"FsizeD\",\"NlengthD\",'Deck']\nfor col in cat_vars:\n titanic[col]=labelEnc.fit_transform(titanic[col])\n titanic_test[col]=labelEnc.fit_transform(titanic_test[col])\n\ntitanic.head()\n\n\n# In[80]:\n\nwith sns.plotting_context(\"notebook\",font_scale=1.5):\n sns.set_style(\"whitegrid\")\n sns.distplot(titanic[\"Age\"].dropna(),\n bins=80,\n kde=False,\n color=\"red\")\n sns.plt.title(\"Age Distribution\")\n plt.ylabel(\"Count\")\n\n\n# In[81]:\n\nfrom sklearn.ensemble import RandomForestRegressor # predicting missing values of age using RandomForestRegresser. We are not using mean,median,etc. as this is an important feature\n\n\n# In[82]:\n\ndef fill_missing_age(df):\n age_df = df[['Age','Embarked','Fare', 'Parch', 'SibSp',\n 'TicketNumber', 'Title','Pclass','FamilySize',\n 'FsizeD','NameLength',\"NlengthD\",'Deck']]\n train = age_df.loc[ (df.Age.notnull()) ]\n test = age_df.loc[ (df.Age.isnull()) ]\n y = train.values[:, 0] # target array with age.\n X = train.values[:, 1::] # all other values are stored in this feature array.\n rtr = RandomForestRegressor(n_estimators=2000, n_jobs=-1)\n rtr.fit(X, y)\n predictedAges = rtr.predict(test.values[:, 1::])\n df.loc[ (df.Age.isnull()), 'Age' ] = predictedAges \n \n return df\n\ntitanic=fill_missing_age(titanic)\ntitanic_test=fill_missing_age(titanic_test)\n\n\n# In[83]:\n\nwith sns.plotting_context(\"notebook\",font_scale=1.5):\n sns.set_style(\"whitegrid\")\n sns.distplot(titanic[\"Age\"].dropna(),\n bins=80,\n kde=False,\n color=\"tomato\")\n sns.plt.title(\"Age Distribution\")\n plt.ylabel(\"Count\")\n plt.xlim((15,100))\n\n\n# In[84]:\n\nfrom sklearn import preprocessing\n\n\n# In[85]:\n\nstd_scale = preprocessing.StandardScaler().fit(titanic[['Age', 'Fare']])\ndf_std = std_scale.transform(titanic[['Age', 'Fare']])\n\n\n# In[86]:\n\ndf_std\n\n\n# In[87]:\n\ntitanic.head(3)\n\n\n# In[88]:\n\nstd_scale = preprocessing.StandardScaler().fit(titanic_test[['Age', 'Fare']])\ndf_std = std_scale.transform(titanic_test[['Age', 'Fare']])\n\n\n# In[89]:\n\ntitanic.corr()[\"Survived\"]\n\n\n# In[90]:\n\nfrom sklearn.linear_model import LinearRegression\n\n\n# In[91]:\n\nfrom sklearn.cross_validation import KFold\n\n\n# In[92]:\n\npredictors = [\"Pclass\", \"Sex\", \"Age\",\"SibSp\", \"Parch\", \"Fare\",\n \"Embarked\",\"NlengthD\", \"FsizeD\", \"Title\",\"Deck\"]\ntarget=\"Survived\"\n\n\n# In[93]:\n\nalg = LinearRegression()\n\n\n# In[94]:\n\nkf = KFold(titanic.shape[0], n_folds=3, random_state=1)\n\n\n# In[97]:\n\nkf\n\n\n# In[98]:\n\npredictions = []\n\n\n# In[99]:\n\nfor train, test in kf:\n train_predictors = (titanic[predictors].iloc[train,:])\n train_target = titanic[target].iloc[train]\n alg.fit(train_predictors, train_target)\n test_predictions = alg.predict(titanic[predictors].iloc[test,:])\n predictions.append(test_predictions)\n\n\n# In[100]:\n\npredictions[predictions > .5] = 1\npredictions[predictions <=.5] = 0\n\n\n# In[ ]:\n\nfrom sklearn import cross_validation\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import ShuffleSplit\n\npredictors = [\"Pclass\", \"Sex\", \"Fare\", \"Embarked\",\"Deck\",\"Age\",\n \"FsizeD\", \"NlengthD\",\"Title\",\"Parch\"]\n\nlr = LogisticRegression(random_state=1)\ncv = ShuffleSplit(n_splits=10, test_size=0.3, random_state=50)\n\nscores = cross_val_score(lr, titanic[predictors], \n titanic[\"Survived\"],scoring='f1', cv=cv)\nprint(scores.mean())\n\n\n# In[ ]:\n\nfrom sklearn import cross_validation\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.cross_validation import KFold\nfrom sklearn.model_selection import cross_val_predict\n\nimport numpy as np\npredictors = [\"Pclass\", \"Sex\", \"Age\",\n \"Fare\",\"NlengthD\",\"NameLength\", \"FsizeD\", \"Title\",\"Deck\"]\n\nrf = RandomForestClassifier(random_state=1, n_estimators=10, min_samples_split=2, \n min_samples_leaf=1)\nkf = KFold(titanic.shape[0], n_folds=5, random_state=1)\ncv = ShuffleSplit(n_splits=10, test_size=0.3, random_state=50)\n\npredictions = cross_validation.cross_val_predict(rf, titanic[predictors],titanic[\"Survived\"],cv=kf)\npredictions = pd.Series(predictions)\nscores = cross_val_score(rf, titanic[predictors], titanic[\"Survived\"],\n scoring='f1', cv=kf)\nprint(scores.mean())\n\n\n# In[ ]:\n\npredictors = [\"Pclass\", \"Sex\", \"Age\",\n \"Fare\",\"NlengthD\",\"NameLength\", \"FsizeD\", \"Title\",\"Deck\",\"TicketNumber\"]\nrf = RandomForestClassifier(random_state=1, n_estimators=50, max_depth=9,min_samples_split=6, min_samples_leaf=4)\nrf.fit(titanic[predictors],titanic[\"Survived\"])\nkf = KFold(titanic.shape[0], n_folds=5, random_state=1)\npredictions = cross_validation.cross_val_predict(rf, titanic[predictors],titanic[\"Survived\"],cv=kf)\npredictions = pd.Series(predictions)\nscores = cross_val_score(rf, titanic[predictors], titanic[\"Survived\"],scoring='f1', cv=kf)\n# Take the mean of the scores (because we have one for each fold)\nprint(scores.mean())\n\n\n# In[106]:\n\nimportances=rf.feature_importances_\nstd = np.std([rf.feature_importances_ for tree in rf.estimators_],\n axis=0)\nindices = np.argsort(importances)[::-1]\nsorted_important_features=[]\nfor i in indices:\n sorted_important_features.append(predictors[i])\n#predictors=titanic.columns\nplt.figure()\nplt.title(\"Feature Importances By Random Forest Model\")\nplt.bar(range(np.size(predictors)), importances[indices],\n color=\"r\", yerr=std[indices], align=\"center\")\nplt.xticks(range(np.size(predictors)), sorted_important_features, rotation='vertical')\n\nplt.xlim([-1, np.size(predictors)])\nplt.show()\n\n\n# In[ ]:\n\n\n\n","sub_path":"titanic_soln.py","file_name":"titanic_soln.py","file_ext":"py","file_size_in_byte":14393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"290840269","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\nimport operator\n\ndef fetch_afisha_page():\n response = requests.get('http://www.afisha.ru/msk/schedule_cinema/')\n return response.text\n\n\ndef parse_afisha_list(raw_html):\n html_doc = BeautifulSoup(raw_html, 'html.parser')\n for tag in html_doc.find_all('div', class_='m-disp-table'):\n movie_title = tag.h3.a.string\n timetable = tag.find_next('table')\n cinema_count = len(timetable.find_all('td', class_='b-td-item'))\n yield (movie_title, cinema_count)\n\n\ndef fetch_movie_info(movie_title):\n search_url = 'https://www.kinopoisk.ru/index.php'\n get_params = {\n 'first': 'no',\n 'kp_query': movie_title\n }\n headers = {\n 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0)'\\\n ' Gecko/20100101 Firefox/50.0'\n }\n response = requests.get(\n search_url,\n params=get_params,\n timeout=10,\n headers=headers\n )\n html_doc = BeautifulSoup(response.content, 'html.parser')\n rating, votes_count = get_data_from_html_page(html_doc)\n\n return rating, votes_count\n\n\ndef get_data_from_html_page(html_doc):\n tag = html_doc.find('div', class_='most_wanted')\n rating = '0'\n votes_count = '0'\n if tag.div.div:\n str_with_data = tag.div.div['title']\n str_with_data = re.sub(\n r'[^0-9\\.(]',\n '',\n str_with_data\n )\n rating, votes_count = str_with_data.split('(')\n\n if not rating:\n rating = tag.div.div.string\n\n return float(rating), int(votes_count)\n\n\n\ndef output_movies_to_console(movies, count):\n sorted_movies = sorted(\n movies,\n key=operator.itemgetter(1, 2),\n reverse=True\n )\n for movie in sorted_movies[:count]:\n print(movie[0])\n print(' - rating: {0}'.format(movie[1]))\n print(' - votes count: {0}'.format(movie[2]))\n print(' - cinema count: {0}'.format(movie[3]))\n\n\nif __name__ == '__main__':\n movies = []\n for movie_title, cinema_count in parse_afisha_list(fetch_afisha_page()):\n rating, votes_count = fetch_movie_info(movie_title)\n print([movie_title, rating, votes_count, cinema_count])\n movies.append([movie_title, rating, votes_count, cinema_count])\n output_movies_to_console(movies, 10)","sub_path":"cinemas.py","file_name":"cinemas.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"305398916","text":"import dash\nimport datetime as dt\nfrom dash.dependencies import Input, Output, State\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nimport dash_table\nimport pandas as pd\nfrom pandas import ExcelWriter\nfrom pandas_datareader import data as pdr\nimport yfinance as yf\nimport os\nfrom dash.exceptions import PreventUpdate\n\nyf.pdr_override()\nstart = dt.datetime(2017, 12, 1)\nnow = dt.datetime.now()\n\napp = dash.Dash(__name__, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.COSMO])\nserver = app.server\n# This program runs the Mark Minvervini stockscreener.\n# It reads the symbols from a xlsx file and writes the results of the stockscreener\n# to a data table - with callback\n# First try with Bootstrap after watching charming data\n\n# Idea: Compare result with own portfolio (own 'object')\n# Idea: Exchange yahoo with different api\n# Idea: Compare result with previous run and summarize new and old stocks\n# Idea: When checking own portfolio: Send email when own stock no longer fulfills all criteria\n\n#abc\n\nfilePath1 = r\"ticker_components/SvenStocks9.xlsx\"\nfilePath2 = r\"ticker_components/ScreenOutput.xlsx\"\nfilePath3 = r\"ticker_components/Portfolio.xlsx\"\n\ndef get_stocks(filePath):\n # filePath = r\"/Users/Sven/pff/Python/DashApp6bootstrap/ticker_components/SvenStocks6.xlsx\"\n stocklist = pd.read_excel(filePath)\n exportList = pd.DataFrame(columns=[\n 'Stock', \"50 Day MA\", \"150 Day Ma\", \"200 Day MA\", \"52 Week Low\", \"52 week High\"])\n\n for i in stocklist.index:\n stock = str(stocklist[\"Symbol\"][i])\n\n try:\n df = pdr.get_data_yahoo(stock, start, now)\n\n smaUsed = [50, 150, 200]\n for x in smaUsed:\n sma = x\n df[\"SMA_\"+str(sma)] = round(df.iloc[:,\n 4].rolling(window=sma).mean(), 2)\n\n currentClose = df[\"Adj Close\"][-1]\n # print(currentClose)\n moving_average_50 = df[\"SMA_50\"][-1]\n moving_average_150 = df[\"SMA_150\"][-1]\n moving_average_200 = df[\"SMA_200\"][-1]\n low_of_52week = min(df[\"Adj Close\"][-260:])\n high_of_52week = max(df[\"Adj Close\"][-260:])\n\n\n try:\n moving_average_200_20 = df[\"SMA_200\"][-20]\n\n except Exception:\n moving_average_200_20 = 0\n\n # Condition 1: Current Price > 150 SMA and > 200 SMA\n if(currentClose > moving_average_150 > moving_average_200):\n cond_1 = True\n print(\"Cond. 1 for \"+stock+\" is true\")\n else:\n cond_1 = False\n # Condition 2: 150 SMA and > 200 SMA\n if(moving_average_150 > moving_average_200):\n cond_2 = True\n print(\"Cond. 2 for \"+stock+\" is true\")\n else:\n cond_2 = False\n # Condition 3: 200 SMA trending up for at least 1 month (ideally 4-5 months)\n if(moving_average_200 > moving_average_200_20):\n cond_3 = True\n print(\"Cond. 3 for \"+stock+\" is true\")\n else:\n cond_3 = False\n # Condition 4: 50 SMA> 150 SMA and 50 SMA> 200 SMA\n if(moving_average_50 > moving_average_150 > moving_average_200):\n # print(\"Condition 4 met\")\n cond_4 = True\n print(\"Cond. 4 for \"+stock+\" is true\")\n else:\n # print(\"Condition 4 not met\")\n cond_4 = False\n # Condition 5: Current Price > 50 SMA\n if(currentClose > moving_average_50):\n cond_5 = True\n print(\"Cond. 5 for \"+stock+\" is true\")\n else:\n cond_5 = False\n # Condition 6: Current Price is at least 30% above 52 week low (Many of the best are up 100-300% before coming out of consolidation)\n if(currentClose >= (1.3*low_of_52week)):\n cond_6 = True\n print(\"Cond. 6 for \"+stock+\" is true\")\n else:\n cond_6 = False\n # Condition 7: Current Price is within 25% of 52 week high\n if(currentClose >= (.75*high_of_52week)):\n cond_7 = True\n print(\"Cond. 7 for \"+stock+\" is true\")\n else:\n cond_7 = False\n\n if(cond_1 and cond_2 and cond_3 and cond_4 and cond_5 and cond_6 and cond_7):\n exportList = exportList.append({'Stock': stock, \"50 Day MA\": moving_average_50, \"150 Day Ma\": moving_average_150,\n \"200 Day MA\": moving_average_200, \"52 Week Low\": low_of_52week, \"52 week High\": high_of_52week}, ignore_index=True)\n print(\"All conditions for \"+stock+\" are true.\")\n\n except Exception:\n print(\"No data on \"+stock)\n\n # print(exportList)\n return exportList\n\n\ndef get_stocks_portfolio(filePath):\n stocklist = pd.read_excel(filePath)\n exportList = pd.DataFrame(columns=[\n 'Stock', \"50 Day MA\", \"150 Day Ma\", \"200 Day MA\", \"52 Week Low\", \"52 week High\", \"Cond1\", \"Cond2\",\"Cond3\",\"Cond4\",\"Cond5\",\"Cond6\",\"Cond7\"])\n\n for i in stocklist.index:\n stock = str(stocklist[\"Symbol\"][i])\n\n try:\n df = pdr.get_data_yahoo(stock, start, now)\n\n smaUsed = [50, 150, 200]\n for x in smaUsed:\n sma = x\n df[\"SMA_\"+str(sma)] = round(df.iloc[:,\n 4].rolling(window=sma).mean(), 2)\n\n currentClose = df[\"Adj Close\"][-1]\n # print(currentClose)\n moving_average_50 = df[\"SMA_50\"][-1]\n moving_average_150 = df[\"SMA_150\"][-1]\n moving_average_200 = df[\"SMA_200\"][-1]\n low_of_52week = min(df[\"Adj Close\"][-260:])\n high_of_52week = max(df[\"Adj Close\"][-260:])\n try:\n moving_average_200_20 = df[\"SMA_200\"][-20]\n\n except Exception:\n moving_average_200_20 = 0\n\n # Condition 1: Current Price > 150 SMA and > 200 SMA\n if(currentClose > moving_average_150 > moving_average_200):\n cond_1 = 1\n print(\"Cond. 1 for \"+stock+\" is true\")\n else:\n cond_1 = 0\n # Condition 2: 150 SMA > 200 SMA\n if(moving_average_150 > moving_average_200):\n cond_2 = 1\n print(\"Cond. 2 for \"+stock+\" is true\")\n else:\n cond_2 = 0\n # Condition 3: 200 SMA trending up for at least 1 month (ideally 4-5 months)\n if(moving_average_200 > moving_average_200_20):\n cond_3 = 1\n print(\"Cond. 3 for \"+stock+\" is true\")\n else:\n cond_3 = 0\n # Condition 4: 50 SMA> 150 SMA and 50 SMA> 200 SMA\n if(moving_average_50 > moving_average_150 > moving_average_200):\n # print(\"Condition 4 met\")\n cond_4 = 1\n print(\"Cond. 4 for \"+stock+\" is true\")\n else:\n # print(\"Condition 4 not met\")\n cond_4 = 0\n # Condition 5: Current Price > 50 SMA\n if(currentClose > moving_average_50):\n cond_5 = 1\n print(\"Cond. 5 for \"+stock+\" is true\")\n else:\n cond_5 = 0\n # Condition 6: Current Price is at least 30% above 52 week low (Many of the best are up 100-300% before coming out of consolidation)\n if(currentClose >= (1.3*low_of_52week)):\n cond_6 = 1\n print(\"Cond. 6 for \"+stock+\" is true\")\n else:\n cond_6 = 0\n # Condition 7: Current Price is within 25% of 52 week high\n if(currentClose >= (.75*high_of_52week)):\n cond_7 = 1\n print(\"Cond. 7 for \"+stock+\" is true\")\n else:\n cond_7 = 0\n\n #if(cond_1 and cond_2 and cond_3 and cond_4 and cond_5 and cond_6 and cond_7):\n exportList = exportList.append({'Stock': stock, \"50 Day MA\": moving_average_50, \"150 Day Ma\": moving_average_150,\n \"200 Day MA\": moving_average_200, \"52 Week Low\": low_of_52week, \"52 week High\": high_of_52week, \"Cond1\":cond_1,\"Cond2\":cond_2, \"Cond3\":cond_3,\"Cond4\":cond_4,\"Cond5\":cond_5, \"Cond6\":cond_6,\"Cond7\":cond_7}, ignore_index=True)\n #print(\"All conditions for \"+stock+\" are true.\")\n\n except Exception:\n print(\"No data on \"+stock)\n\n # print(exportList)\n return exportList\n\ndef get_previous_run():\n df = pd.read_excel(filePath2)\n\n # print(df)\n return html.Div(\n [\n html.Div(\n html.Table(\n # Header\n [html.Tr([html.Th(\"Stock - 52 Week Low - 52 Week High\")])]\n +\n # Body\n [\n html.Tr(\n [\n html.Td(\n df[\"Stock\"][ind]\n ),\n html.Td(\n df[\"52 Week Low\"][ind]\n ),\n html.Td(\n df[\"52 week High\"][ind]\n )\n ])\n\n # for i in range(min(len(df), max_rows))\n for ind in df.index\n\n ]\n ),\n style={\"height\": \"100%\", \"overflowY\": \"scroll\"},\n ),\n ],\n style={\"height\": \"100%\"},)\n\ndef get_legend():\n return html.Div(\n [\n html.Div(\n html.Table(\n # Header\n [html.Tr([html.Th(\"Condition - explanation\")])]\n +\n # Body\n [\n html.Tr(\n [\n html.Td(\n \"Condition 1:\"\n ),\n html.Td(\n \"Current Price > 150 SMA and > 200 SMA\"\n ),\n ]),\n html.Tr(\n [\n html.Td(\n \"Condition 2:\"\n ),\n html.Td(\n \"150 SMA > 200 SMA\"\n ),\n ]),\n html.Tr(\n [\n html.Td(\n \"Condition 3:\"\n ),\n html.Td(\n \"200 SMA trending up for at least 1 month (ideally 4-5 months)\"\n ),\n ]),\n html.Tr(\n [\n html.Td(\n \"Condition 4:\"\n ),\n html.Td(\n \"50 SMA> 150 SMA and 50 SMA> 200 SMA\"\n ),\n ]),\n html.Tr(\n [\n html.Td(\n \"Condition 5:\"\n ),\n html.Td(\n \"Current Price > 50 SMA\"\n ),\n ]),\n html.Tr(\n [\n html.Td(\n \"Condition 6:\"\n ),\n html.Td(\n \"Current Price is at least 30% above 52 week low (Many of the best are up 100-300% before coming out of consolidation)\"\n ),\n ]),\n html.Tr(\n [\n html.Td(\n \"Condition 7:\"\n ),\n html.Td(\n \"Current Price is within 25% of 52 week high\"\n ),\n ]),\n ]\n ),\n style={\"height\": \"100%\", \"overflowY\": \"scroll\"},\n ),\n ],\n style={\"height\": \"100%\"},)\n\ndef get_portfolio():\n\n df = pd.read_excel(filePath3)\n\n # print(df)\n return html.Div(\n [\n html.Div(\n html.Table(\n # Header\n [html.Tr([html.Th(\"Stocks\")])]\n +\n # Body\n [\n html.Tr(\n [\n html.Td(\n df[\"Symbol\"][ind]\n ),\n html.Td(\n df[\"Stock\"][ind]\n )\n ])\n\n # for i in range(min(len(df), max_rows))\n for ind in df.index\n\n ]\n ),\n style={\"height\": \"100%\", \"overflowY\": \"scroll\"},\n ),\n ],\n style={\"height\": \"100%\"},)\n\n\napp.layout = html.Div(\n children=[\n dbc.Row(dbc.Col(html.H1(\"Marc Minvervini screener\"),\n width={'size': 9, 'offset': 3},\n ),\n ),\n html.Br(),\n dbc.Row([dbc.Button(\n f\"Open {graph}\",\n id=f\"button-{graph}\",\n className=\"mb-3\",\n color=\"primary\",\n ) for graph in [\"previous\", \"portfolio\"]],justify=\"center\"),\n html.Br(),\n #dbc.Row(dbc.Col(html.H2(\"Previous run\"),\n # width={'size': 5, 'offset': 1},)),\n #dbc.Row(dbc.Col(html.Div(id='datatable'))),\n \n dbc.Row([\n #dbc.Col(dbc.Collapse(get_previous_run(),id=\"collapse_datatable\", is_open=False), width=5),\n dbc.Col(dbc.Collapse(dbc.Card(dbc.CardBody(get_previous_run()),color=\"primary\",outline=True),id=\"collapse_datatable\", is_open=False,className=\"w-80\")),\n #dbc.Col(dbc.Collapse(html.H1(\"Hello datatable\",id='datatable'),id=\"collapse_datatable\", is_open=False), width=5),\n #dbc.Col(dbc.Collapse(html.Div(id='portfolio'),id=\"collapse_portfolio\", is_open=False), width=5),\n dbc.Col(dbc.Collapse(dbc.Card(dbc.CardBody(get_portfolio()),color=\"primary\",inverse=True),id=\"collapse_portfolio\", is_open=False,className=\"w-80\")),\n #dbc.Col(dbc.Collapse(get_portfolio(),id=\"collapse_portfolio\", is_open=False), width=5)\n ] ),\n \n #html.Br(),\n #dbc.Row(dbc.Col(html.H2(\"Portfolio\"),\n # width={'size': 5, 'offset': 1})),\n #dbc.Row(dbc.Col(html.Div(id='portfolio'))),\n html.Br(),\n dbc.Row(children=[dbc.Button(\"Run Minvervini screen\", id=\"button_screen\",\n color=\"primary\",outline=True,className=\"mb-3\", n_clicks=0),\n dbc.Button(\"Check portfolio\", id=\"button_portfolio\",\n color=\"primary\",className=\"mb-3\", n_clicks=0)],\n justify='center'),\n \n #dbc.Row([dbc.Button(\n # f\"Open {graph}\",\n # id=f\"button-{graph}\",\n # className=\"mb-3\",\n # color=\"primary\",\n #) for graph in [\"screen\", \"portfolio2\"]],justify=\"center\"),\n html.Br(),\n dbc.Row([dbc.Button(\n f\"Open {graph}\",\n id=f\"button-{graph}\",\n className=\"mb-3\",\n color=\"primary\",\n ) for graph in [\"legend\"]],justify=\"center\"),\n dbc.Row([\n #dbc.Col(dbc.Collapse(get_previous_run(),id=\"collapse_datatable\", is_open=False), width=5),\n dbc.Col(dbc.Collapse(dbc.Card(dbc.CardBody(get_legend()),color=\"primary\",outline=True),id=\"collapse_legend\", is_open=False,className=\"w-80\")),\n ]),\n html.Br(),\n dbc.Row(\n dbc.Col(\n dbc.Spinner(children=[html.H1(\"Hier taucht gleich das Ergebnis auf.\",\n id=\"container\")], size=\"sm\", color=\"warning\")\n )),\n html.Br(),\n dbc.Row(\n dbc.Col(\n dbc.Spinner(children=[html.H1(\"Hier taucht gleich das Ergebnis des Portfoliochecks auf.\",\n id=\"datatable_portfolio\")], color=\"warning\"),\n )),\n ]\n)\n\n@app.callback(\n Output(\"collapse_datatable\", \"is_open\"),\n [Input(\"button-previous\", \"n_clicks\")],\n [State(\"collapse_datatable\", \"is_open\")],\n)\ndef toggle_collapse(n, is_open):\n if n:\n #print(n)\n return not is_open\n #print(\"pling\")\n return is_open\n\n@app.callback(\n Output(\"collapse_portfolio\", \"is_open\"),\n [Input(\"button-portfolio\", \"n_clicks\")],\n [State(\"collapse_portfolio\", \"is_open\")],\n)\ndef toggle_collapse2(n, is_open):\n if n:\n return not is_open\n return is_open\n\n@app.callback(\n Output(\"collapse_legend\", \"is_open\"),\n [Input(\"button-legend\", \"n_clicks\")],\n [State(\"collapse_legend\", \"is_open\")],\n)\ndef toggle_collapse3(n, is_open):\n if n:\n return not is_open\n return is_open\n\n\n@ app.callback(Output('datatable', 'children'), [Input('button', 'n_clicks')])\ndef generate_html_table1(v):\n\n if v == None:\n raise PreventUpdate\n\n df = pd.read_excel(filePath2)\n\n # print(df)\n return html.Div(\n [\n html.Div(\n html.Table(\n # Header\n [html.Tr([html.Th(\"Stock - 52 Week Low - 52 Week High\")])]\n +\n # Body\n [\n html.Tr(\n [\n html.Td(\n df[\"Stock\"][ind]\n ),\n html.Td(\n df[\"52 Week Low\"][ind]\n ),\n html.Td(\n df[\"52 week High\"][ind]\n )\n ])\n\n # for i in range(min(len(df), max_rows))\n for ind in df.index\n\n ]\n ),\n style={\"height\": \"100%\", \"overflowY\": \"scroll\"},\n ),\n ],\n style={\"height\": \"100%\"},)\n\n\n#@ app.callback(Output('datatable_portfolio', 'children'), [Input('button_portfolio', 'n_clicks')], prevent_initial_call=True)\n#def generate_html_table3(v):\n# if v == None:\n# raise PreventUpdate\n\n# df = get_stocks_portfolio(filePath3)\n\n# table = dbc.Table.from_dataframe(\n# df, striped=True, bordered=True, responsive=True, size=\"sm\", hover=True)\n# print(df)\n\n # newFile = os.path.dirname(filePath2)+\"/ScreenOutput.xlsx\"\n # print(filePath2)\n # print(newFile)\n # writer = ExcelWriter(newFile)\n # df.to_excel(writer, \"Sheet1\")\n # writer.save()\n\n# return dbc.Row(\n# dbc.Card(\n# table\n# )\n# )\n\n\n@ app.callback(Output('container', 'children'), [Input('button_screen', 'n_clicks')], prevent_initial_call=True)\ndef generate_html_table4(v):\n\n if v == None:\n raise PreventUpdate\n\n df = get_stocks(filePath1)\n table = dbc.Table.from_dataframe(\n df, striped=True, bordered=True, responsive=True, hover=True)\n print(df)\n\n newFile = os.path.dirname(filePath2)+\"/ScreenOutput.xlsx\"\n print(filePath2)\n print(newFile)\n writer = ExcelWriter(newFile)\n df.to_excel(writer, \"Sheet1\")\n writer.save()\n\n return dbc.Row(\n dbc.Card(\n table\n )\n )\n#test for conditional formatting\n@ app.callback(Output('datatable_portfolio', 'children'), [Input('button_portfolio', 'n_clicks')], prevent_initial_call=True)\ndef generate_html_table5(v):\n if v == None:\n raise PreventUpdate\n\n df = get_stocks_portfolio(filePath3)\n\n table = dash_table.DataTable(\n id='table',\n #columns=[{\"name\": i, \"id\": i} for i in df.columns],\n #\"50 Day MA\", \"150 Day Ma\", \"200 Day MA\", \"52 Week Low\", \"52 week High\", \"Cond1\", \"Cond2\",\"Cond3\",\"Cond4\",\"Cond5\",\"Cond6\",\"Cond7\"\n columns=[\n {'name': 'Stock', 'id': 'Stock', 'type': 'text'},\n {'name': '50 Day MA', 'id': '50 Day MA', 'type': 'numeric','hideable':True},\n {'name': '150 Day Ma', 'id': '150 Day Ma', 'type': 'numeric', 'hideable':True},\n {'name': '200 Day MA', 'id': '200 Day MA', 'type': 'numeric','hideable':True},\n {'name': '52 Week Low', 'id': '52 Week Low', 'type': 'numeric','hideable':True},\n {'name': '52 week High', 'id': '52 week High', 'type': 'numeric','hideable':True},\n {'name': 'Cond1', 'id': 'Cond1', 'type': 'numeric','hideable':True},\n {'name': 'Cond2', 'id': 'Cond2', 'type': 'numeric','hideable':True},\n {'name': 'Cond3', 'id': 'Cond3', 'type': 'numeric','hideable':True},\n {'name': 'Cond4', 'id': 'Cond4', 'type': 'numeric','hideable':True},\n {'name': 'Cond5', 'id': 'Cond5', 'type': 'numeric','hideable':True},\n {'name': 'Cond6', 'id': 'Cond6', 'type': 'numeric','hideable':True},\n {'name': 'Cond7', 'id': 'Cond7', 'type': 'numeric','hideable':True},\n ],\n data=df.to_dict('records'),\n style_data_conditional=[{\n 'if': {\n 'column_id': 'Stock',\n 'filter_query': '{Cond1} > 0 && {Cond2} > 0 && {Cond3} > 0 && {Cond4} > 0 && {Cond5} > 0 && {Cond6} > 0 && {Cond7} > 0',\n\n },\n 'backgroundColor': 'green',\n 'color': 'white'\n },\n {'if': {\n 'filter_query': '{Cond1} < 1',\n 'column_id': 'Cond1'\n },\n 'color': 'tomato',\n 'fontWeight': 'bold'\n },\n {'if': {\n 'filter_query': '{Cond1} > 0',\n 'column_id': 'Cond1'\n },\n 'backgroundColor': 'green',\n 'color': 'white'\n },\n {'if': {\n 'filter_query': '{Cond2} < 1',\n 'column_id': 'Cond2'\n },\n 'color': 'tomato',\n 'fontWeight': 'bold'\n },\n {'if': {\n 'filter_query': '{Cond2} > 0',\n 'column_id': 'Cond2'\n },\n 'backgroundColor': 'green',\n 'color': 'white'\n },\n {'if': {\n 'filter_query': '{Cond3} < 1',\n 'column_id': 'Cond3'\n },\n 'color': 'tomato',\n 'fontWeight': 'bold'\n },\n {'if': {\n 'filter_query': '{Cond3} > 0',\n 'column_id': 'Cond3'\n },\n 'backgroundColor': 'green',\n 'color': 'white'\n },\n {'if': {\n 'filter_query': '{Cond4} < 1',\n 'column_id': 'Cond4'\n },\n 'color': 'tomato',\n 'fontWeight': 'bold'\n },\n {'if': {\n 'filter_query': '{Cond4} > 0',\n 'column_id': 'Cond4'\n },\n 'backgroundColor': 'green',\n 'color': 'white'\n },\n {'if': {\n 'filter_query': '{Cond5} < 1',\n 'column_id': 'Cond5'\n },\n 'color': 'tomato',\n 'fontWeight': 'bold'\n },\n {'if': {\n 'filter_query': '{Cond5} > 0',\n 'column_id': 'Cond5'\n },\n 'backgroundColor': 'green',\n 'color': 'white'\n },\n {'if': {\n 'filter_query': '{Cond6} < 1',\n 'column_id': 'Cond6'\n },\n 'color': 'tomato',\n 'fontWeight': 'bold'\n },\n {'if': {\n 'filter_query': '{Cond6} > 0',\n 'column_id': 'Cond6'\n },\n 'backgroundColor': 'green',\n 'color': 'white'\n },\n {'if': {\n 'filter_query': '{Cond7} < 1',\n 'column_id': 'Cond7'\n },\n 'color': 'tomato',\n 'fontWeight': 'bold'\n },\n {'if': {\n 'filter_query': '{Cond7} > 0',\n 'column_id': 'Cond7'\n },\n 'backgroundColor': 'green',\n 'color': 'white'\n }]\n )\n return dbc.Row(\n dbc.Card(\n table\n )\n )\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"dash_minervini_csv_cards.py","file_name":"dash_minervini_csv_cards.py","file_ext":"py","file_size_in_byte":25199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"590074980","text":"\"\"\"\npython -i 002_label_processor.py \\\n--data_path=/home/siit/navi/data/input_data/CUB_200_2011/images \\\n--save_path=/home/siit/navi/data/input_data/CUB_200_2011/ \\\n--path_label False\n\"\"\"\n\nimport os\nimport argparse\nimport numpy as np\nimport glob\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data_path', type=str, dest='data_path', default='/home/siit/navi/data/input_data/mnist_png/')\nparser.add_argument('--data_name', type=str, dest='data_name', default='danbooru')\nparser.add_argument('--save_path', type=str, dest='save_path', default='/home/siit/navi/data/meta_data/mnist_png/')\n\nparser.add_argument('--n_classes', type=int, dest='n_classes', default=34)\nparser.add_argument('--path_label', type=bool, dest='path_label', default=False)\nparser.add_argument('--iter', type=int, dest='iter', default=1)\nconfig, unparsed = parser.parse_known_args() \n\n\n\ndef file_list(path, extensions, sort=True):\n result = [os.path.join(dp, f) for dp, dn, filenames in os.walk(path) \n for f in filenames if os.path.splitext(f)[1] in extensions]\n if sort:\n result.sort() \n return result\n\n\n\n# make the save dir if it is not exists\nsave_path = config.save_path\nif not os.path.exists(save_path):\n os.mkdir(save_path)\n\npath_list = file_list(config.data_path, ('.jpg','.png'), True)\nlenth = len(path_list)\n\n\n# label_list = list('0123456789') # for mnist\n# label_list = ['trainA', 'trainB'] # for cat dog\n# label_list = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\nlabel_list = os.listdir(config.data_path)\nlabel_list.sort()\n\npath_label_dict = {}\n\nf = open(os.path.join(config.save_path, 'train.txt'), 'w')\nfor line in glob.glob(config.data_path + '/0*/*'):\n label_index = label_list.index(line.split('/')[-2]) \n\n f.write('{} {}\\n'.format(line, label_index))\n \nf.close()\n\nf = open(os.path.join(config.save_path, 'test.txt'), 'w')\nfor line in glob.glob(config.data_path + '/1*/*'):\n label_index = label_list.index(line.split('/')[-2]) \n\n f.write('{} {}\\n'.format(line, label_index))\n \nf.close()\n\"\"\"\ncounter = 0\nfor line in path_list:\n one_hot_label = np.eye(len(label_list))[label_list.index(\n os.path.basename(line).split('_')[1].split('.')[0])]\n # one_hot_label = np.eye(len(label_list))[label_list.index(line.split('/')[-2])]\n one_hot_label = np.uint8(one_hot_label)\n path_label_dict[line] = one_hot_label\n counter += 1\n\nnp.save(os.path.join(config.save_path, 'path_label_dict.npy'), path_label_dict)\n\"\"\"\n\n\"\"\"\nfor itr in range(config.iter):\n # save the file inside of the meta/ folder\n f = open(os.path.join(save_path, 'path_label_list{0:03d}.txt'.format(itr)), 'w')\n for line in path_list[int((itr)*lenth/config.iter):int((itr+1)*lenth/config.iter)]:\n f.write(line + '\\n')\n f.close()\n\"\"\"","sub_path":"pytorch/101_Image_Classification/002_label_processor.py","file_name":"002_label_processor.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"286683609","text":"counter = 1000\nmiles = 1000.0\nname = 'whr'\n\nprint(counter)\nprint(miles)\nprint(name)\n\na = b = c = 1\n\nd, e, f = 1.0, 4, 8\n\nprint(a,b,c)\nprint(d,e,f)\n\na = \"1\"\n\nt = isinstance(a, int)\nprint(t)\n\nsex = \"female\"\n\nsex = 'male'","sub_path":"python_exercise/DayOne_3.py","file_name":"DayOne_3.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"549670968","text":"\n# -*- coding: utf-8 -*- \nimport scrapy\n\nfrom bikecrawler import dbutil\nfrom bikecrawler import timeutil\nfrom bikecrawler import util\nfrom bikecrawler.items import crawldata\n\nclass HZBIKESpider(scrapy.Spider):\n name = \"hzbike\"\n allowed_domains = [\"hzbike.com\"]\n start_urls = map(lambda x:x['URL'],dbutil.get_config_by_domain(\"hzbike.com\"))\n\n last_date = timeutil.strdt_datetime(\"2009-01-01\",ft='%Y-%m-%d')\n url_pattern = \"/forum.php?mod=viewthread&tid=%(tid)s&page=1&authorid=%(uid)s\"\n\n\n def debug(self,html):\n self.logger.debug(\"HTML:%s\", html)\n\n def info(self,info):\n self.logger.info(\"MYMSG:%s\", info)\n\n def parse(self, response):\n _root = response.xpath(\"//tbody/tr\")\n for _tr in _root:\n #帖子创建日期\n type = _tr.xpath(\"th/em/a/text()\").extract_first()\n title = _tr.xpath(\"th/a/text()\").extract_first()\n cdate = _tr.xpath(\"td[@class='by']/em/span/text()\").extract_first()\n if cdate is None:\n self.info(\"cdate is None\")\n #self.debug(_tr.extract())\n continue\n if timeutil.strdt_datetime(cdate,ft='%Y-%m-%d %H:%M') > self.last_date:\n try:\n uid = _tr.xpath(\"td[@class='by']/cite/a/@href\").re(\"uid=(\\d+)\").pop()\n tid = _tr.xpath(\"th/a/@href\").re(\"tid=(\\d+)\").pop()\n if uid is None or tid is None:\n self.info(\"title:%s %s;uid or tid is None\" % (type,title))\n #self.debug(_tr.extract())\n continue\n _thread_url = self.url_pattern % {'tid':tid,'uid':uid}\n url = response.urljoin(_thread_url)\n #self.info(\"wait crawl url:%s from %s\" % (url,response.url))\n yield scrapy.Request(url, callback=self.parse_articles_follow_next_page,meta={'postdate':timeutil.strdt_datetime(cdate,ft='%Y-%m-%d %H:%M')})\n except Exception as e:\n util.exc_info()\n self.debug(_tr.extract())\n nextpage = response.xpath(\"//a[@class='nxt']/@href\").extract_first()\n if nextpage is not None:\n url = response.urljoin(nextpage)\n self.info(\"list url->%s\"% url)\n yield scrapy.Request(url, callback=self.parse)\n\n \n def parse_articles_follow_next_page(self, response):\n _item = crawldata()\n _item['url'] = response.url\n \n _title = response.xpath(\"//span[@id='thread_subject']/text()\").extract_first()\n _item['title'] = _title\n _tag = response.xpath(\"//h1[@class='ts']/a/text()\").extract_first()\n _item['tag'] = _tag\n try:\n _item['postdate'] = response.meta['postdate']\n except Exception as e:\n util.exc_info()\n\n\n _root = response.xpath(\"//div[@id='postlist']/div[starts-with(@id,'post_')]/table/tr/td[@class='plc']/div[@class='pct']/div[@class='pcb']/div[@class='t_fsz']\") \n _message = []\n for _root_item in _root:\n _second_root = _root_item.xpath(\"table/tr/td/child::node()\") \n for _second_item in _second_root:\n _node_type = _second_item.xpath(\"name()\").extract_first()\n if _node_type is None:\n _message.extend(_second_item.extract())\n _message.append(\"\\n\")\n elif _node_type == \"ignore_js_op\":\n _img_url = _second_item.xpath(\"div//img/@file\").extract_first()\n if _img_url is not None:\n _message.extend(response.urljoin(_img_url))\n _message.append(\"\\n\")\n \n #抽取img,类似这种格式http://hzbike.com/forum.php?mod=viewthread&tid=118823&page=1&authorid=22591\n _img_list = _root_item.xpath(\"div[@class='pattl']/ignore_js_op\")\n for _img in _img_list:\n _img_url = _img.xpath(\".//img/@file\").extract_first()\n if _img_url is not None:\n _img_desc = _img.xpath(\".//p[@class='mbn xg2']/text()\").extract_first()\n if _img_desc is not None:\n _message.extend(_img_desc)\n _message.append(\"\\n\")\n _message.extend(response.urljoin(_img_url))\n _message.append(\"\\n\")\n _item['data'] = \"\".join(_message).encode(\"utf8\")\n yield _item\n\n next_page = response.xpath(\"//div[@class='pgt']/div[@class='pg']/a[@class='nxt']/@href\")\n if next_page:\n url = response.urljoin(next_page.extract_first())\n yield scrapy.Request(url, self.parse_articles_follow_next_page)\n","sub_path":"bikecrawler/spiders/hzbike_spider.py","file_name":"hzbike_spider.py","file_ext":"py","file_size_in_byte":4720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"411975979","text":"import unittest\nimport os.path\nimport io\n\nimport magic\n\nROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')\n\nTEST_FILE = os.path.join(ROOT, 'test.zip')\nTEST_GZIP = os.path.join(ROOT, 'test.txt.gz')\n\nclass TestMagic(unittest.TestCase):\n def test_from_file_mime(self):\n expected = 'application/zip'\n actual = magic.from_file(TEST_FILE, mime=True)\n print(actual)\n self.assertEqual(actual, expected)\n\n def test_from_file(self):\n expected = 'Zip archive data'\n actual = magic.from_file(TEST_FILE)\n print(actual)\n self.assertTrue(actual.startswith(expected))\n\n def test_from_buffer_mime(self):\n expected = 'application/zip'\n with io.open(TEST_FILE, 'br') as f:\n actual = magic.from_buffer(f.read(), mime=True)\n print(actual)\n self.assertEqual(actual, expected)\n\n def test_from_buffer(self):\n expected = 'Zip archive data'\n with io.open(TEST_FILE, 'br') as f:\n actual = magic.from_buffer(f.read())\n print(actual)\n self.assertTrue(actual.startswith(expected))\n\n def test_uncompress(self):\n m = magic.Magic(uncompress=True)\n expected = 'gzip compressed data, was \"test.txt\"'\n actual = m.from_file(TEST_GZIP)\n print(actual)\n self.assertTrue(expected in actual)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"magic/test/test_magic.py","file_name":"test_magic.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"295637910","text":"# 只能使用 大小写英文字母 数字 _ 组成 并且 不可以以数字开头\n# python 是一个 弱类型语言 也叫 动态语言 即 变量的具体类型由赋值决定\na = 1 # a就是整数\nstr = 'string' # str 是一个字符串\nboo = True # boo 是一个布尔类型的值\n\n# = 是赋值用的 同一个变量可以反复赋值\nprint(a)\na = 'string'\nprint(a)\n\n# 与动态语言对应的是 静态语言 即在定义变量的时候必须指定变量类型 例如 java\n# int a = 1;\n# a = \"abc\"; 这样就会报错 因为不能够将字符类型赋值给 int 类型的变量\n\n\n# 那么 在定义变量的时候 计算机到底是做了些什么呢?\nex = 'abc'\n# 1.在内存中创建一个字符串 abc\n# 2.在内存中创建一个变量ex 将ex指向 abc\nex1 = ex\n# 那么如果新定义一个变量ex1 并且将ex赋值给ex1 计算机中又做了什么呢?\n# 1.在内存中创建一个变量ex1\n# 2.让变量ex1指向字符串 abc\nex = 'xyz'\n# 那么 如果将ex重新赋值 计算机会做些什么呢?\n# 1.在内存中新建字符串 xyz\n# 2.将ex指向字符串 xyz\nprint(ex) # xyz\nprint(ex1) # abc\n\n\n# 常量\n# 通常常量的命名使用全部大写\nPI = 3.141592654\n# 但是实际上 PI 依旧是一个变量 python中没有机制可以确保 PI不被改变\n\n\n","sub_path":"Python/基础学习/03.variable.py","file_name":"03.variable.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"122103711","text":"#coding=utf-8\r\nimport pymongo\r\nimport MySQLdb\r\n\r\n\r\ndef start_MySQL():\r\n conn = MySQLdb.connect(\r\n host='192.168.1.108',\r\n port=3306,\r\n user='',\r\n passwd='',\r\n db='xueqiu',\r\n charset='utf8')\r\n\r\n cur = conn.cursor()\r\n myConn_list = [conn, cur]\r\n return myConn_list\r\n\r\n\r\ndef close_MySQL(cur,conn):\r\n cur.close()\r\n conn.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n client = pymongo.MongoClient('192.168.1.108', 27017)\r\n TempleSpider = client['all_comments']\r\n temple_comment_collect = TempleSpider['all_taolun_comments']\r\n\r\n myConn_list = start_MySQL()\r\n cur = myConn_list[1]\r\n conn = myConn_list[0]\r\n\r\n for temple in temple_comment_collect.find():\r\n sql = \"INSERT INTO all_taolun_comments_2(url,company_name,comment_people,comment_time,comment_content) VALUES ('{}', '{}', '{}', '{}', '{}')\".format(temple['url'],temple['股票名称'],temple['评论人'],temple['评论时间'],temple['评论内容'])\r\n print(sql)\r\n try:\r\n cur.execute(sql)\r\n conn.commit()\r\n except Exception as e:\r\n print(e)\r\n close_MySQL(cur, conn)","sub_path":"05_MongoDB_to_MySQL/mongo_to_mysql_taolun.py","file_name":"mongo_to_mysql_taolun.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"338845944","text":"\"\"\"\r\nHOWTO:\r\n\r\napi = VK.Api(app_id)\r\napi.authorize(email, password)\r\napi.do(method_name, method_params)\r\n\r\ncode returns response in JSON format\r\n\"\"\"\r\n\r\nDESKTOP_REDIRECT_URI = 'https://oauth.vk.com/blank.html'\r\nAPP_ID = 4846380\r\nBROWSER_HEADERS = {\r\n 'User-agent': 'Mozilla/5.0 (Windows NT 6.1; rv:38.0) '\r\n 'Gecko/20100101 Firefox/38.0'\r\n}\r\n\r\n\r\nclass Api(object):\r\n def __init__(self, app_id):\r\n self.app_id = app_id\r\n\r\n INPUT_NAMES = ['_origin', 'ip_h', 'lg_h', 'to']\r\n\r\n def _build_auth_url(self, redirect, display_type, scope):\r\n return 'https://oauth.vk.com/authorize?client_id=%s&redirect_uri=%s&display=%s&scope=%s&response_type=token' % (\r\n self.app_id, redirect, display_type, scope)\r\n\r\n def authorize(self, login, password):\r\n self.login = login\r\n self.password = password\r\n\r\n self.opener = Api._create_opener()\r\n html = self._get_auth_page()\r\n\r\n form_url = Api._get_form_url(html)\r\n params = self._get_params(html)\r\n\r\n response = self.opener.open(form_url, params)\r\n self.token = Api._get_token(response.geturl())\r\n\r\n def do(self, method, params):\r\n params['access_token'] = self.token\r\n url = Api._build_method_request(method, params)\r\n response = self.opener.open(url)\r\n data = response.readall()\r\n\r\n decoded_data = data.decode()\r\n from json import loads\r\n return loads(decoded_data)\r\n\r\n def _get_auth_page(self):\r\n auth_url = self._build_auth_url(DESKTOP_REDIRECT_URI, 'wap', '4096')\r\n response = self.opener.open(auth_url)\r\n data = response.readall()\r\n return data.decode()\r\n\r\n def _get_params(self, html):\r\n params = {'email': self.login,\r\n 'pass': self.password}\r\n parsed_params = Api._get_inputs(html)\r\n params.update(parsed_params)\r\n\r\n from urllib.parse import urlencode\r\n url_encoded = urlencode(params)\r\n binary_params = url_encoded.encode()\r\n return binary_params\r\n\r\n @staticmethod\r\n def _get_inputs(html):\r\n values = {}\r\n for input_name in Api.INPUT_NAMES:\r\n values[input_name] = Api._get_input_value(input_name, html)\r\n return values\r\n\r\n @staticmethod\r\n def _build_method_request(method, params):\r\n from urllib.parse import urlencode\r\n return 'https://api.vk.com/method/' + method + '?' + urlencode(params)\r\n\r\n @staticmethod\r\n def _get_token(url):\r\n from re import search\r\n return search(r'access_token=(.+?)&', url).groups()[0]\r\n\r\n @staticmethod\r\n def _get_form_url(html):\r\n from re import search\r\n return search(r'
    ', html).groups()[0]\r\n\r\n @staticmethod\r\n def _get_input_value(name, source):\r\n from re import search\r\n return search(r' sys.float_info.epsilon:\n i.crowd_d = 1/i.crowd_d\n else:\n i.crowd_d = sys.float_info.max\n\n best = sorted(self.individuals,\n key=op.attrgetter('rank',\n 'crowd_d'))\n self.individuals = best[:pop.size()]\n self.update()\n\n def init_velocity(self):\n for i, j in enumerate(self.individuals[-1].cur_x):\n w = (self.problem.upper[i] - self.problem.lower[i])/2\n self.individuals[-1].cur_v.append(np.random.uniform(-w, w))\n\n def populate(self, x, f, s):\n \"\"\"populate with decision and objective values multiplied by sign\n x: vector of decision values\n f: matrix of objective values\n s: vector of signs (1, -1)\"\"\"\n for k, i in enumerate(self.individuals):\n i.cur_x = x[k]\n i.cur_f = [v*sign\n for v, sign in zip(f[:, k], s)]\n self.update()\n\n def get_ranked_decisions(self):\n px = dict()\n for i in self.individuals:\n k = i.rank\n if k in px:\n px[k].append(i.cur_x)\n else:\n px[k] = [i.cur_x]\n return px\n\n def get_ranked_objectives(self, s):\n po = dict()\n for i in self.individuals:\n cur_f = [v*sign\n for v, sign in zip(i.cur_f, s)]\n k = i.rank\n if k in po:\n po[k].append(cur_f)\n else:\n po[k] = [cur_f]\n return po\n\n def update(self):\n size = len(self.individuals)\n self.dom_count = []\n self.dom_list = [[] for s in range(size)]\n self.champion = None\n for s in range(size):\n self.dom_count.append(0)\n self.update_dom(s)\n self.update_champion(s)\n self.update_pareto_information()\n\n def update_dom(self, n):\n \"\"\"Loop over the population (j) and construct\n dom_list[n] and dom_count \"\"\"\n\n for i, x in enumerate(self.individuals):\n if i != n:\n # check if individual in position i\n # dominates the one in position n\n if self.problem.compare_fc(x.cur_f, x.cur_c,\n self.individuals[n].cur_f,\n self.individuals[n].cur_c):\n self.dom_count[n] += 1\n self.dom_list[i].append(n)\n\n def update_champion(self, idx):\n if self.champion is None or \\\n self.problem.compare_fc(self.individuals[idx].cur_f,\n self.individuals[idx].cur_c,\n self.champion['f'], self.champion['c']):\n self.champion = dict(x=self.individuals[idx].cur_x,\n f=self.individuals[idx].cur_f,\n c=self.individuals[idx].cur_c)\n\n def update_crowding(self, F):\n # sort along the fitness dimension\n for i in range(self.problem.f_dim):\n I = sorted(F, key=lambda k: self.individuals[k].cur_f[i],\n reverse=True)\n self.individuals[I[0]].crowd_d = sys.float_info.max\n self.individuals[I[-1]].crowd_d = sys.float_info.max\n df = (self.individuals[I[-1]].cur_f[i] -\n self.individuals[I[0]].cur_f[i])\n for j in range(1, len(F)-1):\n if abs(df) > sys.float_info.epsilon:\n self.individuals[I[j]].crowd_d += (\n self.individuals[I[j+1]].cur_f[i] -\n self.individuals[I[j-1]].cur_f[i])/df\n\n def update_pareto_information(self):\n size = len(self.individuals)\n self.pareto_rank = [0]*size\n F = [i for i, c in enumerate(self.dom_count) if c == 0]\n irank = 1\n dom_count_copy = list(self.dom_count)\n while True:\n self.update_crowding(F)\n S = []\n for i, f in enumerate(F):\n for j, k in enumerate(self.dom_list[f]):\n dom_count_copy[k] -= 1\n if dom_count_copy[k] == 0:\n S.append(k)\n self.pareto_rank[k] = irank\n self.individuals[k].rank = irank\n if S:\n F = list(S)\n else:\n return\n\n irank += 1\n\n def compute_pareto_fronts(self):\n self.update_pareto_information()\n retval = [[] for s in range(max(self.pareto_rank)+1)]\n for i, j in enumerate(self.individuals):\n retval[self.pareto_rank[i]].append(i)\n return retval\n\n def compute_ideal(self):\n return [min(x)\n for x in zip(*[i.cur_f\n for i in self.individuals if i.rank == 0])]\n\n def compute_nadir(self):\n return [max(x)\n for x in zip(*[i.cur_f\n for i in self.individuals if i.rank == 0])]\n\n def compute_worst(self):\n return [max(x)\n for x in zip(*[i.cur_f\n for i in self.individuals])]\n\n def compute_norm_dist(self):\n zi = np.array(self.compute_ideal())\n zw = np.array(self.compute_worst())\n znad = np.array(self.compute_nadir())\n return np.sqrt(((znad-zi)**2).sum() / ((zw-zi)**2).sum())\n\n def plot_pareto_fronts(\n self,\n rgb=(\n 0,\n 0,\n 0),\n comp=[\n 0,\n 1],\n symbol='o',\n size=6,\n fronts=[]):\n \"\"\"\n Plots the population pareto front in a 2-D graph\n\n USAGE: pop.plot_pareto_front(comp = [0,1], rgb=(0,1,0))\n\n * comp: components of the fitness function to plot in the 2-D window\n * rgb: specify the color of the 1st front (use strong colors here)\n * symbol: marker for the individual\n * size: size of the markersymbol\n * fronts: list of fronts to be plotted (use [0] to only show the first)\n \"\"\"\n from numpy import linspace\n import matplotlib.pyplot as plt\n\n if len(comp) != 2:\n raise ValueError(\n 'Invalid components of the objective function selected for plot')\n\n p_dim = self.problem.f_dimension\n\n if p_dim == 1:\n raise ValueError(\n 'Pareto fronts of a 1-dimensional problem cannot be plotted')\n\n if not all([c in range(0, p_dim) for c in comp]):\n raise ValueError(\n 'You need to select valid components of the objective function')\n\n p_list = self.compute_pareto_fronts()\n if (len(fronts) > 0):\n n = len(p_list)\n consistent = [d < n for d in fronts]\n if consistent.count(False) > 0:\n raise ValueError(\n 'Check your fronts list, there seem to be not enough fronts')\n p_list = [p_list[idx] for idx in fronts]\n\n cl = list(zip(linspace(0.9 if rgb[0] else 0.1, 0.9, len(p_list)),\n linspace(0.9 if rgb[1] else 0.1, 0.9, len(p_list)),\n linspace(0.9 if rgb[2] else 0.1, 0.9, len(p_list))))\n\n for id_f, f in enumerate(p_list):\n for ind in f:\n plt.plot([ind.cur_f[comp[0]]],\n [ind.cur_f[comp[1]]],\n symbol,\n color=cl[id_f], markersize=size)\n x = [ind.cur_f[comp[0]] for ind in f]\n y = [ind.cur_f[comp[1]] for ind in f]\n tmp = [(a, b) for a, b in zip(x, y)]\n tmp = sorted(tmp, key=lambda k: k[0])\n plt.step([c[0] for c in tmp], [c[1]\n for c in tmp], color=cl[id_f], where='post')\n return plt.gca()\n","sub_path":"src/femagtools/moo/population.py","file_name":"population.py","file_ext":"py","file_size_in_byte":10100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"447246580","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\n\nimport errno\nimport os\nimport socket\nimport sys\nimport struct\n\nfrom io import BytesIO\n\nfrom .thrift import TType, TException\n\n\nclass TTransportBase(object):\n \"\"\"Base class for Thrift transport layer.\"\"\"\n\n def read(self, sz):\n buff = b''\n have = 0\n while (have < sz):\n chunk = self._read(sz - have)\n have += len(chunk)\n buff += chunk\n\n if len(chunk) == 0:\n raise TTransportException(TTransportException.END_OF_FILE,\n \"End of file reading from transport\")\n\n return buff\n\n\nclass TTransportException(TException):\n \"\"\"Custom Transport Exception class\"\"\"\n\n thrift_spec = {\n 1: (TType.STRING, 'message'),\n 2: (TType.I32, 'type'),\n }\n\n UNKNOWN = 0\n NOT_OPEN = 1\n ALREADY_OPEN = 2\n TIMED_OUT = 3\n END_OF_FILE = 4\n\n def __init__(self, type=UNKNOWN, message=None):\n super(TTransportException, self).__init__()\n self.type = type\n self.message = message\n\n\nclass TMemoryBuffer(TTransportBase):\n \"\"\"Wraps a BytesIO object as a TTransport.\"\"\"\n\n def __init__(self, value=None):\n \"\"\"value -- a value as the initial value in the BytesIO object.\n\n If value is set, the transport can be read first.\n \"\"\"\n self._buffer = BytesIO(value) if value is not None else BytesIO()\n self._pos = 0\n\n def isOpen(self):\n return not self._buffer.closed\n\n def open(self):\n pass\n\n def close(self):\n self._buffer.close()\n\n def read(self, sz):\n return self._read(sz)\n\n def _read(self, sz):\n orig_pos = self._buffer.tell()\n self._buffer.seek(self._pos)\n res = self._buffer.read(sz)\n self._buffer.seek(orig_pos)\n self._pos += len(res)\n return res\n\n def write(self, buf):\n self._buffer.write(buf)\n\n def flush(self):\n pass\n\n def getvalue(self):\n return self._buffer.getvalue()\n\n def setvalue(self, value):\n self._buffer = BytesIO(value)\n self._pos = 0\n\n\nclass TBufferedTransport(TTransportBase):\n \"\"\"Class that wraps another transport and buffers its I/O.\n\n The implementation uses a (configurable) fixed-size read buffer\n but buffers all writes until a flush is performed.\n \"\"\"\n DEFAULT_BUFFER = 4096\n\n def __init__(self, trans, rbuf_size=DEFAULT_BUFFER):\n self.__trans = trans\n self.__wbuf = BytesIO()\n self.__rbuf = BytesIO(b\"\")\n self.__rbuf_size = rbuf_size\n\n def isOpen(self):\n return self.__trans.isOpen()\n\n def open(self):\n return self.__trans.open()\n\n def close(self):\n return self.__trans.close()\n\n def _read(self, sz):\n ret = self.__rbuf.read(sz)\n if len(ret) != 0:\n return ret\n\n self.__rbuf = BytesIO(self.__trans.read(max(sz, self.__rbuf_size)))\n return self.__rbuf.read(sz)\n\n def write(self, buf):\n self.__wbuf.write(buf)\n\n def flush(self):\n out = self.__wbuf.getvalue()\n # reset wbuf before write/flush to preserve state on underlying failure\n self.__wbuf = BytesIO()\n self.__trans.write(out)\n self.__trans.flush()\n\n\nclass TFramedTransport(TTransportBase):\n \"\"\"Class that wraps another transport and frames its I/O when writing.\"\"\"\n def __init__(self, trans):\n self.__trans = trans\n self.__rbuf = BytesIO()\n self.__wbuf = BytesIO()\n\n def isOpen(self):\n return self.__trans.isOpen()\n\n def open(self):\n return self.__trans.open()\n\n def close(self):\n return self.__trans.close()\n\n def read(self, sz):\n ret = self.__rbuf.read(sz)\n if len(ret) != 0:\n return ret\n\n self.readFrame()\n return self.__rbuf.read(sz)\n\n def readFrame(self):\n buff = self.__trans.read(4)\n sz, = struct.unpack('!i', buff)\n self.__rbuf = BytesIO(self.__trans.read(sz))\n\n def write(self, buf):\n self.__wbuf.write(buf)\n\n def flush(self):\n wout = self.__wbuf.getvalue()\n wsz = len(wout)\n # reset wbuf before write/flush to preserve state on underlying failure\n self.__wbuf = BytesIO()\n # N.B.: Doing this string concatenation is WAY cheaper than making\n # two separate calls to the underlying socket object. Socket writes in\n # Python turn out to be REALLY expensive, but it seems to do a pretty\n # good job of managing string buffer operations without excessive\n # copies\n buf = struct.pack(\"!i\", wsz) + wout\n self.__trans.write(buf)\n self.__trans.flush()\n\n\nclass TBufferedTransportFactory(object):\n def get_transport(self, trans):\n return TBufferedTransport(trans)\n\n\nclass TFramedTransportFactory(object):\n def get_transport(self, trans):\n return TFramedTransport(trans)\n\n\nclass TSocketBase(TTransportBase):\n def _resolveAddr(self):\n if self._unix_socket is not None:\n return [(socket.AF_UNIX, socket.SOCK_STREAM, None, None,\n self._unix_socket)]\n else:\n return socket.getaddrinfo(\n self.host,\n self.port,\n socket.AF_UNSPEC,\n socket.SOCK_STREAM,\n 0,\n socket.AI_PASSIVE | socket.AI_ADDRCONFIG)\n\n def close(self):\n if self.handle:\n self.handle.close()\n self.handle = None\n\n\nclass TSocket(TSocketBase):\n \"\"\"Socket implementation of TTransport base.\"\"\"\n\n def __init__(self, host='localhost', port=9090, unix_socket=None):\n \"\"\"Initialize a TSocket\n\n @param host(str) The host to connect to.\n @param port(int) The (TCP) port to connect to.\n @param unix_socket(str) The filename of a unix socket to connect to.\n (host and port will be ignored.)\n \"\"\"\n self.host = host\n self.port = port\n self.handle = None\n self._unix_socket = unix_socket\n self._timeout = None\n\n def set_handle(self, h):\n self.handle = h\n\n def is_open(self):\n return bool(self.handle)\n\n def set_timeout(self, ms):\n self._timeout = ms / 1000.0 if ms else None\n\n if self.handle:\n self.handle.settimeout(self._timeout)\n\n def open(self):\n try:\n res0 = self._resolveAddr()\n for res in res0:\n self.handle = socket.socket(res[0], res[1])\n self.handle.settimeout(self._timeout)\n try:\n self.handle.connect(res[4])\n except socket.error as e:\n if res is not res0[-1]:\n continue\n else:\n raise e\n break\n except socket.error as e:\n if self._unix_socket:\n message = 'Could not connect to socket %s' % self._unix_socket\n else:\n message = 'Could not connect to %s:%d' % (self.host, self.port)\n raise TTransportException(type=TTransportException.NOT_OPEN,\n message=message)\n\n def read(self, sz):\n try:\n buff = self.handle.recv(sz)\n except socket.error as e:\n if (e.args[0] == errno.ECONNRESET and\n (sys.platform == 'darwin' or\n sys.platform.startswith('freebsd'))):\n # freebsd and Mach don't follow POSIX semantic of recv\n # and fail with ECONNRESET if peer performed shutdown.\n # See corresponding comment and code in TSocket::read()\n # in lib/cpp/src/transport/TSocket.cpp.\n self.close()\n # Trigger the check to raise the END_OF_FILE exception below.\n buff = ''\n else:\n raise\n if len(buff) == 0:\n raise TTransportException(type=TTransportException.END_OF_FILE,\n message='TSocket read 0 bytes')\n return buff\n\n def write(self, buff):\n if not self.handle:\n raise TTransportException(type=TTransportException.NOT_OPEN,\n message='Transport not open')\n sent = 0\n have = len(buff)\n while sent < have:\n plus = self.handle.send(buff)\n if plus == 0:\n raise TTransportException(type=TTransportException.END_OF_FILE,\n message='TSocket sent 0 bytes')\n sent += plus\n buff = buff[plus:]\n\n def flush(self):\n pass\n\n\nclass TServerSocket(TSocketBase):\n \"\"\"Socket implementation of TServerTransport base.\"\"\"\n\n def __init__(self, host=None, port=9090, unix_socket=None,\n socket_family=socket.AF_UNSPEC):\n self.host = host\n self.port = port\n self._unix_socket = unix_socket\n self._socket_family = socket_family\n self.handle = None\n\n def listen(self):\n res0 = self._resolveAddr()\n socket_family = self._socket_family == socket.AF_UNSPEC and (\n socket.AF_INET6 or self._socket_family)\n for res in res0:\n if res[0] is socket_family or res is res0[-1]:\n break\n\n # We need remove the old unix socket if the file exists and\n # nobody is listening on it.\n if self._unix_socket:\n tmp = socket.socket(res[0], res[1])\n try:\n tmp.connect(res[4])\n except socket.error as err:\n eno, message = err.args\n if eno == errno.ECONNREFUSED:\n os.unlink(res[4])\n\n self.handle = socket.socket(res[0], res[1])\n self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n if hasattr(self.handle, 'settimeout'):\n self.handle.settimeout(None)\n self.handle.bind(res[4])\n self.handle.listen(128)\n\n def accept(self):\n client, addr = self.handle.accept()\n result = TSocket()\n result.set_handle(client)\n return result\n","sub_path":"thriftpy/transport.py","file_name":"transport.py","file_ext":"py","file_size_in_byte":10224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"527828414","text":"import params\r\nimport numpy as np\r\nfrom functions import ras_constr_from_tiles_data, write_geotiff\r\n\r\nif __name__==\"__main__\":\r\n in_tiles = np.load(params.IN_TILES_FILENAME)\r\n geo_tranform = tuple(np.load(params.GEO_TRANFORM_FILENAME))\r\n myfile = open(params.PROJECTION_FILENAME, 'r')\r\n projection = myfile.read()\r\n myfile.close()\r\n #\r\n reconst_data = ras_constr_from_tiles_data(in_tiles, params.IMAGE_SIZE_X, params.IMAGE_SIZE_Y)\r\n write_geotiff(params.OUT_IMAGE_FILENAME, reconst_data, geo_tranform, projection, params.OUT_DATATYPE)\r\n","sub_path":"data_preparation_for_CNN/runReconstruct.py","file_name":"runReconstruct.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"632446965","text":"import pandas as pd\nfrom sklearn.preprocessing import scale\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\n\n\n\ndef preprocess(dataframe, isTrain):\n dataframe.dropna(inplace=True)\n dataframe = dataframe.drop('PassengerId', axis=1)\n dataframe = dataframe.drop('Embarked', axis=1)\n dataframe = dataframe.drop('Name', axis=1)\n dataframe = dataframe.drop('Ticket', axis=1)\n dataframe = dataframe.drop('Cabin', axis=1)\n\n if isTrain:\n y = dataframe[\"Survived\"].to_numpy()\n dataframe = dataframe.drop(\"Survived\", axis=1)\n\n\n # Preprocessing Age\n scaleAge = scale(dataframe[\"Age\"])\n dataframe[\"Age\"] = scaleAge\n\n\n # Preprocessing Sex\n newSex = []\n for i in dataframe[\"Sex\"]:\n if i == \"male\":\n newSex.append(0)\n else:\n newSex.append(1)\n\n dataframe[\"Sex\"] = newSex\n\n\n # Preprocessing Fare\n scaleFare = scale(dataframe[\"Fare\"])\n dataframe[\"Fare\"] = scaleFare\n\n if isTrain:\n return dataframe.to_numpy(), y\n else:\n return dataframe.to_numpy()\n\n\ntrain_x, train_y = preprocess(pd.read_csv('train.csv'), True)\n# test_x, test_y = preprocess(pd.read_csv('test.cvs'))\n\nmodel = Sequential()\nmodel.add(Dense(units=64, activation='relu'))\nmodel.add(Dense(units=64, activation='relu'))\nmodel.add(Dense(2, activation='softmax'))\n\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.fit(train_x, train_y, validation_split=0.1, epochs=100, batch_size=32)\n\n\n\n\npredictions = model.predict(preprocess(pd.read_csv('test.csv'), False))\nprint(predictions)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"431550236","text":"# Step 1:- Import the required libraries\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D , MaxPool2D , Flatten , Dropout \nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import Adam\nfrom sklearn.metrics import classification_report,confusion_matrix\nimport tensorflow as tf\nimport cv2\nimport os\nimport numpy as np\nfrom keras.metrics import PrecisionAtRecall,Recall\n\n# Step 2:- Loading the data \nlabels = ['patients_covid', 'patients_normal']\nimg_size = 50\ndata_dir = \"D:\\\\ALFRED - Workspace\\\\Xray Images\\\\modelling\\\\set_2\"\ndef get_data(data_dir):\n data = [] \n for label in labels: \n path = os.path.join(data_dir, label)\n class_num = labels.index(label)\n for img in os.listdir(path):\n try:\n img_arr = cv2.imread(os.path.join(path, img))[...,::-1] #convert BGR to RGB format\n resized_arr = cv2.resize(img_arr, (img_size, img_size)) # Reshaping images to preferred size\n data.append([resized_arr, class_num])\n except Exception as e:\n print(e)\n return np.array(data)\n\ntrain = get_data(data_dir + \"\\\\train_dataset\")\nval = get_data(data_dir + \"\\\\test_dataset\")\n\n# Step 3:- Visualize the data \nl = []\nfor i in train:\n if(i[1] == 0):\n l.append(\"patients_covid\")\n else:\n l.append(\"patients_normal\")\nsns.set_style('darkgrid')\nsns.countplot(l)\n\n# Step 4:- Data Preprocessing and Data Augmentation\nx_train = []\ny_train = []\nx_val = []\ny_val = []\n\nfor feature, label in train:\n x_train.append(feature)\n y_train.append(label)\n\nfor feature, label in val:\n x_val.append(feature)\n y_val.append(label)\n\n# Normalize the data\n#x_train = np.array(x_train) / 50\n#x_val = np.array(x_val) / 50\n\nx_train.reshape(-1, img_size, img_size, 1)\ny_train = np.array(y_train)\n\nx_val.reshape(-1, img_size, img_size, 1)\ny_val = np.array(y_val)\ndatagen = ImageDataGenerator(\n featurewise_center=False, # set input mean to 0 over the dataset\n samplewise_center=False, # set each sample mean to 0\n featurewise_std_normalization=False, # divide inputs by std of the dataset\n samplewise_std_normalization=False, # divide each input by its std\n zca_whitening=False, # apply ZCA whitening\n rotation_range = 30, # randomly rotate images in the range (degrees, 0 to 180)\n zoom_range = 0.2, # Randomly zoom image \n width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)\n height_shift_range=0.1, # randomly shift images vertically (fraction of total height)\n horizontal_flip = True, # randomly flip images\n vertical_flip=False) # randomly flip images\n\ndatagen.fit(x_train)\n\n# Step 5:- Define the Model \nmodel = Sequential()\nmodel.add(Conv2D(32,3,padding=\"same\", activation=\"relu\", input_shape=(224,224,3)))\nmodel.add(MaxPool2D())\nmodel.add(Conv2D(32, 3, padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPool2D())\nmodel.add(Conv2D(64, 3, padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPool2D())\nmodel.add(Dropout(0.4))\nmodel.add(Flatten())\nmodel.add(Dense(128,activation=\"relu\"))\nmodel.add(Dense(2, activation=\"softmax\"))\nmodel.summary()\nopt = Adam(lr=0.000001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.01, amsgrad=False)\nmetric = PrecisionAtRecall(0.5, num_thresholds=200, name=None, dtype=None)\nmodel.compile(optimizer = opt, loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) , metrics = ['accuracy'])\nhistory = model.fit(y_train, epochs = 10)\n\n\n\n\n\n\n\n\n# Step 6:- Evaluating the result\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(500)\n\nplt.figure(figsize=(15, 15))\nplt.subplot(2, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(2, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()\n\npredictions = model.predict_classes(x_val)\npredictions = predictions.reshape(1,-1)[0]\nprint(classification_report(y_val, predictions, target_names = ['Rugby (Class 0)','Soccer (Class 1)']))\n\n\n\n# Step 1:- Import the model\nbase_model = tf.keras.applications.MobileNetV2(input_shape = (224, 224, 3), include_top = False, weights = \"imagenet\")\nbase_model.trainable = False\nmodel = tf.keras.Sequential([base_model,\n tf.keras.layers.GlobalAveragePooling2D(),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(2, activation=\"softmax\") \n ])\nbase_learning_rate = 0.00001\nmodel.compile(optimizer=tf.keras.optimizers.Adam(lr=base_learning_rate),\n loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\nhistory = model.fit(x_train,y_train,epochs = 500 , validation_data = (x_val, y_val))\n\n# Step 2:- Evaluating the result\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs_range = range(500)\n\nplt.figure(figsize=(15, 15))\nplt.subplot(2, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(2, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()\n\npredictions = model.predict_classes(x_val)\npredictions = predictions.reshape(1,-1)[0]\nprint(classification_report(y_val, predictions, target_names = ['Rugby (Class 0)','Soccer (Class 1)']))","sub_path":"AIEngine/analytics/module2.py","file_name":"module2.py","file_ext":"py","file_size_in_byte":6130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"214259732","text":"import copy\n\nX = \"X\"\nO = \"O\"\nEMPTY = None\n\ndef initial_state():\n\n return [[EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY]]\n\ndef player(board):\n \"\"\"\n Returns X or O depending on the next player.\n \"\"\"\n cnt_x = 0\n cnt_o = 0\n\n for i in board:\n for j in i:\n if( j == X ):\n cnt_x += 1\n if( j== O):\n cnt_o += 1\n if cnt_x <= cnt_o :\n return X\n return O\n \ndef result(board, action):\n \"\"\"\n Returns the board that results from making move (i, j) on the board.\n \"\"\"\n i,j=action\n if board[i][j] != EMPTY:\n raise Exception('Invalid move')\n newBoard = copy.deepcopy(board)\n currPlayer = player(board)\n newBoard[i][j] = currPlayer\n return newBoard\n \ndef actions(board):\n \"\"\"\n Returns set of all possible actions (i, j) available on the board.\n \"\"\"\n actions = set()\n\n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] == EMPTY:\n actions.add((i,j))\n return actions\n\n\n\ndef winner(board):\n \"\"\"\n Returns the winner of the game, if there is one.\n \"\"\"\n values=[[],[],[]] \n ver = [0,0,0]\n hor = [0,0,0]\n dia = [0,0]\n replacements = {\n 'X': 1,\n 'O': -1,\n None: 0,\n }\n\n for i in range(3):\n values[i] = [replacements[x] for x in board[i]]\n \n for i in range(3):\n for j in range(3):\n ver[i] += values[j][i]\n hor[i] += values[i][j]\n dia[0] += values[i][i]\n dia[1] += values[i][2-i]\n\n result = ver + hor + dia\n if 3 in result:\n return X\n if -3 in result:\n return O\n return None\n\ndef terminal(board):\n if winner(board) or not actions(board):\n return True\n return False\n\n\ndef utility(board):\n win = winner(board)\n if(win == X):\n return 1\n elif(win == O):\n return -1\n else:\n return 0\n\n","sub_path":"Tic Tac Toe/files/gamefiles/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"203165720","text":"from crawler.spiders import BaseSpider\nimport scrapy\nfrom utils.util_old import *\nfrom crawler.items import *\nfrom bs4 import BeautifulSoup as bs\nfrom scrapy.http import Request, Response\nimport re\nimport time\nclass pravakta(BaseSpider):\n name = 'pravakta'\n website_id = 1076 # 网站的id(必填)\n language_id = 1930 # 所用语言的id\n\n allowed_domains = ['pravakta.com']\n start_urls = ['http://www.pravakta.com/']\n\n sql = { # sql配置\n 'host': '192.168.235.162',\n 'user': 'dg_admin',\n 'password': 'dg_admin',\n 'db': 'dg_crawler'\n }\n \n \n \n\n def parse(self, response):\n '''\n :param response:\n :return:一级目录链接\n '''\n item =NewsItem()\n soup = bs(response.text, \"html.parser\")\n\n sub_ul = soup.find_all(\"ul\", class_=\"sub-menu\")\n url_list = []\n\n for ul in sub_ul:\n sub_a = ul.select(\"li>a\")\n for a in sub_a:\n if ul == sub_ul[-1]: # \"关于我们\"一栏不要\n pass\n else:\n url = a.get(\"href\")\n item['category2'] = a.text.split(\",\")[0]\n url_list.append(url)#category2要是不赋值自动为0?\n yield scrapy.Request(url, callback=self.get_next_page, meta={\"item\": item}) # 层与层之间通过meta参数传递数据\n about_us = [a.get(\"href\") for a in soup.find_all(\"ul\", class_=\"sub-menu\")[-1].select(\"li>a\")]\n # 一级目录链接\n ul = soup.find(\"ul\", class_=\"menu\")\n for a in ul.select(\"li>a\")[1:-1]: # 第一个是home_url,最后一个是视频\n if a.get(\"href\") and a.get(\"href\") not in url_list and a.get(\"href\") != '#' and a.get(\"href\") not in about_us:\n url_list.append(a.get(\"href\"))\n item['category1'] = a.text.strip()\n # item[\"category2\"] =\n if a.get(\"href\")==\"https://www.pravakta.com/news/\":\n yield scrapy.Request(a.get(\"href\"), callback=self.get_news_category,meta={\"item\": item}) # 层与层之间通过meta参数传递数据\n else:\n yield scrapy.Request(a.get(\"href\"), callback=self.get_next_page,meta={\"item\": item}) # 层与层之间通过meta参数传递数据\n def get_news_category(self,response):\n item = response.meta[\"item\"]\n soup = bs(response.text, \"html.parser\")\n a_list = soup.find(\"ul\", class_=\"menu\").select(\"li>a\")\n for a in a_list[2:-1]:\n url = a.get(\"href\")\n item['category2'] = a.text.strip()\n yield scrapy.Request(url, callback=self.get_next_page, meta={\"item\": item}) # 层与层之间通过meta参数传递数据\n def get_next_page(self, response):\n soup = bs(response.text, \"html.parser\")\n item = response.meta[\"item\"]\n div_list = soup.find_all(\"div\", class_=\"data-bg-hover data-bg data-bg-categorised\")\n for div in div_list:\n article_url = div.select_one(\"a\").get(\"href\")\n # print(article_url)\n # last_time = soup.find_all(\"span\",class_=\"item-metadata posts-date\")[11].text.strip()\n yield scrapy.Request(article_url, callback=self.get_news_detail, meta={\"item\": item}) # 层与层之间通过meta参数传递数据\n\n if self.time == None or Util.format_time3(Util.format_time2(soup.find_all(\"article\")[-1].find(\"span\", class_=\"item-metadata posts-date\").text.strip())) >= int(self.time):\n url = soup.find(\"a\",class_=\"next page-numbers\").get(\"href\") if soup.find(\"a\",class_=\"next page-numbers\") else None\n if url:\n yield scrapy.Request(url, meta=response.meta, callback=self.get_next_page)\n else:\n self.logger.info('时间截止')\n\n def get_news_detail(self,response):\n '''\n :param response: x新闻正文response\n :return: 新闻页面详情信息\n '''\n item = response.meta[\"item\"]\n\n soup = bs(response.text, \"html.parser\")\n title = soup.find(\"h1\", class_=\"entry-title\").text.strip() if soup.find(\"h1\", class_=\"entry-title\") else None\n pub_time = Util.format_time2(soup.find(\"span\", class_=\"item-metadata posts-date\").text.strip())\n image_list = [soup.find(\"div\", class_=\"entry-content\").find(\"figure\",class_=\"wp-block-image size-large\").select_one(\"img\").get(\"data-src\")] if soup.find(\"div\", class_=\"entry-content\").find(\"figure\",class_=\"wp-block-image size-large\") else []\n body = ''\n for p in soup.find(\"div\", class_=\"entry-content\").select(\"p\"):\n body += (p.text.strip() + '\\n')\n if soup.find(\"pre\", class_=\"wp-block-code\"):\n # for code in soup.find(\"pre\", class_=\"wp-block-code\"):\n body += soup.find(\"pre\", class_=\"wp-block-code\").text\n abstract = body.split('।')[0] # 摘要是文章的第一句话\n item[\"title\"] = title\n item[\"pub_time\"] = pub_time\n item[\"images\"] = image_list\n item[\"abstract\"] = abstract\n item[\"body\"] = body\n yield item\n","sub_path":"crawler/v1/pravakta.py","file_name":"pravakta.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"134639352","text":"import tensorflow as tf\nimport numpy as np\n\nclass REINFORCE(object):\n \"\"\"\n An object implementing a reinforcement learning algorithm, REINFORCE.\n This algorithm is linear, however it can easily be extended to non-linear case.\n \"\"\"\n def __init__(self, n_features, n_actions):\n \"\"\"\n Create an instance of REINFORCE object, i.e. create TensorFlow graph and initialize tf.Session.\n\n Args:\n n_features - number of features of a state vector (input layer)\n n_actions - number of possible actions to choose from (output layer)\n \"\"\"\n self._graph = tf.Graph()\n self._writer = None\n\n with self._graph.as_default():\n self.state = tf.placeholder(shape=(1,n_features), dtype=tf.float32, name='state')\n self.action = tf.placeholder(shape=None, dtype=tf.int32, name='action')\n self.dis_pow_t = tf.placeholder(shape=None, dtype=tf.float32, name='discount_power_t')\n self.ret = tf.placeholder(shape=None, dtype=tf.float32, name=\"return\")\n self.lrn_rate = tf.placeholder(shape=None, dtype=tf.float32, name='learning_rate')\n\n with tf.name_scope('policy'):\n _W1 = tf.Variable(tf.truncated_normal(shape=(n_features, n_actions))*0.0001,\n dtype=tf.float32, name='weights')\n _l1 = tf.matmul(self.state, _W1, name='layer1')\n\n _probs = tf.nn.softmax(_l1, name='action_probabilities')\n _log_probs = tf.log(_probs, name='log_probs')\n self._action = tf.multinomial(logits=_log_probs, num_samples=1, name='_action')[0,0]\n\n with tf.name_scope('training'):\n _optimizer = tf.train.GradientDescentOptimizer(1)\n # GradientDescentOptimizer doesn't have maximize function; max(x) = min(-x)\n self._train = _optimizer.minimize(\n -_log_probs[0, self.action]*self.dis_pow_t*self.ret*self.lrn_rate )\n\n self._saver = tf.train.Saver()\n self._initializer = tf.global_variables_initializer()\n\n with tf.name_scope('summaries'):\n tf.summary.histogram(name='histogram_weights', values=_W1)\n self._merged_summaries = tf.summary.merge_all()\n\n # Now that the graph is built, create a tf.Session for it, and initialize variables.\n self._sess = tf.Session(graph=self._graph)\n self._sess.run(self._initializer)\n\n #----- Training and performing\n\n def chooseAction(self, state):\n \"\"\"\n Args:\n state - state vector of shape (1, n_features)\n\n Returns:\n action - integer in the range [0, n_actions)\n \"\"\"\n feed_dict = {self.state: state}\n action = self._sess.run(self._action, feed_dict)\n return action\n\n def _discountedRet(self, rewards, discount):\n discounts = [discount**i for i in range(len(rewards))]\n return np.dot(discounts, rewards)\n\n def train(self, states, actions, rewards, discount, lrn_rate):\n \"\"\"\n Perform weights update for an entire episode.\n\n Args:\n states - an array of state vectors, state vectors are of shape (1, n_features)\n actions - an array of actions taken in the corresponding states,\n actions are integers in the range [0, n_actions)\n rewards - an array of rewards returned by an environment after choosing an action\n discount - discount parameter, a floating point number in the range (0, 1)\n lrn_rate - learning rate, a floating point number in the range (0, 1)\n \"\"\"\n for i in range(len(rewards)):\n ret = self._discountedRet(rewards[i:], discount)\n dis = discount**(i)\n feed_dict = {self.state: states[i], self.action: actions[i], self.dis_pow_t: dis,\n self.ret: ret, self.lrn_rate: lrn_rate}\n self._sess.run(self._train, feed_dict)\n\n #----- Saving, restoring, and printing\n\n def save(self, PATH):\n \"\"\"\n Save the policy parameter vector to the given PATH.\n \"\"\"\n self._saver.save(self._sess, PATH)\n\n def restore(self, PATH):\n \"\"\"\n Restore saved policy parameter vector from the given PATH.\n \"\"\"\n self._saver.restore(self._sess, PATH)\n\n def printParameters(self):\n \"\"\"\n Print policy parameter vector.\n \"\"\"\n with self._graph.as_default():\n for var in tf.global_variables():\n print(var.name)\n val = self._sess.run(var)\n print(val)\n\n #----- TensorBoard summaries\n\n def closeFileWriter(self):\n \"\"\"\n Close tf.summary.FileWriter used for saving summaries.\n \"\"\"\n try: self._writer.close()\n except: pass # Is already closed or does not exist, i.e. _writer is None.\n\n def createFileWriter(self, PATH):\n \"\"\"\n Try to close an open tf.summary.FileWriter and create a new one.\n \"\"\"\n self.closeFileWriter()\n self._writer = tf.summary.FileWriter(logdir=PATH, graph=self._graph)\n\n def makeSummary(self, i):\n \"\"\"\n Create and send summaries to FileWriter. If no FileWriter was initialized, print error message.\n \"\"\"\n try:\n summary = self._sess.run(self._merged_summaries)\n self._writer.add_summary(summary=summary, global_step=i)\n except:\n print('FileWriter is either closed or does not exist.')\n print('Use createFileWriter member function to create a new FileWriter.')\n\n #----- Closing, and resetting\n\n def close(self):\n \"\"\"\n Close tf.Session, which releases acquired resources.\n \"\"\"\n self.closeFileWriter()\n try: self._sess.close()\n except: pass # Is already closed.\n\n def reset(self):\n \"\"\"\n Try to close current tf.Session and start a new one.\n \"\"\"\n self.close()\n self._sess = tf.Session(graph=self._graph)\n self._sess.run(self._initializer)\n","sub_path":"Approximate_Solution_Methods/REINFORCE.py","file_name":"REINFORCE.py","file_ext":"py","file_size_in_byte":6148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"543551849","text":"import sys\nimport os, glob\nimport pdb\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy\nfrom scipy.optimize import minimize\nimport math\n\ndef strip_new_line_char(string):\n \"\"\n if \"\\n\" in string:\n return string[:-1]\n return string\n\ndef gaussian(x, mean, sigma):\n return np.exp(-(x-mean)**2/(2*sigma**2))\n\ndef Tones3dgrid(latentTones, sigma): \n \n input_array_0 = np.expand_dims(gaussian(log_freq_percept, latentTones[0], sigma), axis = 1)\n input_array_1 = np.expand_dims(gaussian(log_freq_percept, latentTones[1], sigma), axis = 1)\n input_array_2 = np.expand_dims(gaussian(log_freq_percept, latentTones[2], sigma), axis = 1)\n s0 = 1/np.sum(input_array_0); s1 = 1/np.sum(input_array_1); s2 = 1/np.sum(input_array_2)\n input_array_0 *= s0; input_array_1 *= s1; input_array_2 *= s2; \n \n input_array_mat = np.expand_dims(input_array_0@input_array_1.T,axis=2)@(input_array_2.T) #p(T1,T2..|H) \n \n return input_array_mat\n\ndef posterior_array(freq_input, n_tones, p_back, p_low, log_prior):\n \"\"\"\n Arguments: \n freq_input - range of all possible frequencies (percepts?)\n p_back - prob of background\n p_low - prob of low condition\n log_prior - list of prior parameters\n \"\"\"\n \n log_prior_low_mean = log_prior[0]; log_prior_low_sigma = log_prior[2];\n log_prior_high_mean = log_prior[1]; log_prior_high_sigma = log_prior[2];\n prior_low = gaussian(x=freq_input, mean=log_prior_low_mean, sigma=log_prior_low_sigma)\n prior_high = gaussian(x=freq_input, mean=log_prior_high_mean, sigma=log_prior_high_sigma)\n prior_dist_mixed_high = p_back*(1/len(freq_input)) + (1-p_back)*prior_high \\\n #mixture model with p(T|B) = 1/no. of possible freqs\n prior_dist_mixed_high /= prior_dist_mixed_high.sum() #normalizing\n prior_dist_mixed_high = np.expand_dims(prior_dist_mixed_high, axis = 1)\n prior_dist_mixed_low = p_back*(1/len(freq_input)) + (1-p_back)*prior_low \\\n #mixture model with p(T|B) = 1/no. of possible freqs\n prior_dist_mixed_low /= prior_dist_mixed_low.sum() #normalizing\n prior_dist_mixed_low = np.expand_dims(prior_dist_mixed_low, axis = 1)\n \n if n_tones == 3:\n prior_tones_low = np.expand_dims(prior_dist_mixed_low@np.transpose\\\n (prior_dist_mixed_low),axis=2)@np.transpose(prior_dist_mixed_low) \\\n #p(T1,T2..|L) \n prior_tones_high = np.expand_dims(prior_dist_mixed_high@np.transpose\\\n (prior_dist_mixed_high),axis=2)@np.transpose(prior_dist_mixed_high) \\\n #p(T1,T2..|H) \n elif n_tones == 1:\n prior_tones_low = prior_dist_mixed_low\n prior_tones_high = prior_dist_mixed_high\n \n normalizer = (1-p_low)*prior_tones_high + p_low*prior_tones_low #p(H)*p(T1,T2..|H) + p(L)*p(T1,T2..|L)\n posterior = prior_tones_high*(1-p_low)/normalizer\n # posterior /= np.sum(posterior)\n \n return prior_dist_mixed_high, prior_dist_mixed_low, prior_tones_high, prior_tones_low, normalizer, posterior \ndef posteriorAgainstPercept(expt_Params):\n [_,_,mle_LikelihoodLatentTonegivenHigh,\n mle_LikelihoodLatentTonegivenLow,_,mle_posterior] = posterior_array(freq_input=log_freq_percept,\n n_tones=3,p_back=expt_Params[4],\n p_low=expt_Params[5],\n log_prior=expt_Params[:3]) \n \n \n mle_LikelihoodPerceptgivenHigh = np.zeros((len(log_freq_percept),\n len(log_freq_percept),len(log_freq_percept)))\n mle_LikelihoodPerceptgivenLow = np.zeros((len(log_freq_percept),\n len(log_freq_percept),len(log_freq_percept)))\n\n for itrue1 in range(len(log_freq_percept)):\n for itrue2 in range(len(log_freq_percept)):\n for itrue3 in range(len(log_freq_percept)):\n mle_probPerceptgivenLatentTones = Tones3dgrid([log_freq_percept[itrue1],\n log_freq_percept[itrue2],\n log_freq_percept[itrue3]],\n sigma=expt_Params[3])\n mle_LikelihoodPerceptgivenHigh \\\n += mle_probPerceptgivenLatentTones * mle_LikelihoodLatentTonegivenHigh[itrue1,itrue2,itrue3]\n mle_LikelihoodPerceptgivenLow \\\n += mle_probPerceptgivenLatentTones * mle_LikelihoodLatentTonegivenLow[itrue1,itrue2,itrue3]\n mle_probHighgivenPercept = mle_LikelihoodPerceptgivenHigh*(1-expt_Params[5])/\\\n (mle_LikelihoodPerceptgivenHigh*(1-expt_Params[5]) + mle_LikelihoodPerceptgivenLow*expt_Params[5])\n return mle_probHighgivenPercept\n \nif __name__ == '__main__':\n \n \"\"\"\n Parameters\n \"\"\"\n expt_tones = np.arange(90,3000,1) #array of possible true tones\n log_freq_seq_array = np.arange(0.6,4.7,0.1)\n log_freq_percept = np.arange(0.6,4.7,0.1) # array of possible perceptual tones \n \n \"\"\"\n Obtaining data for a given subject\n \"\"\"\n subject = sys.argv[1]\n context = sys.argv[2]\n \n if context == 'no':\n folder = \"auditory_categorization_prolific_online_data/preprocess_results/90-3000_100%_logPerceptAndLogLatent_GoFrom-InfToInf/results_from_cluster/resultsProlificData/errorbarsOnRelevanceMetric/\"\n elif context == 'low':\n folder = \"auditory_categorization_lc_online_data/preprocess_results/results_from_cluster/resultsProlificData/errorbarsOnRelevanceMetric/\"\n else:\n folder = \"auditory_categorization_Hc_online_data/preprocess_results/results_from_cluster/resultsProlificData/errorbarsOnRelevanceMetric/\"\n \n fileRelevance = folder+\"relevanceMetric_\"+subject+'.txt'\n fileParameters = folder+subject+'.txt'\n \n with open(fileRelevance, 'r') as fr:\n filelinesRelevance = fr.readlines()\n with open(fileParameters, 'r') as fm:\n filelinesMetrics = fm.readlines()\n \n \"\"\"\n Only read from the cluster files or are we also testing the metric values locally? \n \"\"\"\n readOnly = int(sys.argv[3])\n \n if readOnly:\n relevanceMetric = np.zeros((100,))\n for iMetric in range(len(filelinesRelevance)):\n relevanceMetric[iMetric] = float(filelinesRelevance[iMetric].strip('\\n'))\n if np.isnan(relevanceMetric[iMetric]):\n print(\"Bad parameter values for computation of metric:\", filelinesMetrics[iMetric])\n \n #print(\"Relevance metric values\",np.sort(relevanceMetric)) \n print(\"Median relevance metric\",np.around(np.quantile(relevanceMetric[~np.isnan(relevanceMetric)],q=0.5),decimals=2))\n print(\"5th quantile relevance metric\",np.around(np.quantile(relevanceMetric[~np.isnan(relevanceMetric)],q=0.05),decimals=2))\n print(\"95th quantile relevance metric\",np.around(np.quantile(relevanceMetric[~np.isnan(relevanceMetric)],q=0.95),decimals=2))\n \n else:\n norm = np.zeros((100,))\n print(\"Values of relevance metric using parameter sets obtained from the 100 bootstrapped datasets\")\n \n for bootstraps in range(len(filelinesMetrics)):\n if filelinesMetrics[bootstraps].startswith('[') and filelinesMetrics[bootstraps].endswith(']\\n'):\n lineWithNewLineChar = strip_new_line_char(filelinesMetrics[bootstraps])\n lineElements = lineWithNewLineChar.split(\" \")\n params = np.zeros((6,))\n params[0] = float(lineElements[0][1:])\n ecnt = 1\n for element in lineElements[1:]:\n if '.' in element:\n if element.endswith(']'):\n params[ecnt] = float(element[:-1])\n else:\n params[ecnt] = float(element)\n ecnt += 1\n \n minMLE_probHighgivenPercept = posteriorAgainstPercept(params)\n tone1_prob_behaviour = np.zeros((len(log_freq_percept)))\n tone2_prob_behaviour = np.zeros((len(log_freq_percept)))\n tone3_prob_behaviour = np.zeros((len(log_freq_percept)))\n\n for i_tone in range(len(log_freq_percept)):\n tone1_prob_behaviour[i_tone] = np.mean(minMLE_probHighgivenPercept[i_tone,:,:])\n tone2_prob_behaviour[i_tone] = np.mean(minMLE_probHighgivenPercept[:,i_tone,:])\n tone3_prob_behaviour[i_tone] = np.mean(minMLE_probHighgivenPercept[:,:,i_tone])\n\n posteriorProbabilities = (tone1_prob_behaviour+tone2_prob_behaviour+tone3_prob_behaviour)/3\n posteriorProbabilities = posteriorProbabilities - (posteriorProbabilities[0]+\n posteriorProbabilities[-1])/2\n norm[bootstraps] = (sum(np.abs(posteriorProbabilities[:17]))+\n sum(np.abs(posteriorProbabilities[-15:])))/sum(np.abs(posteriorProbabilities))\n\n print(norm[bootstraps])\n","sub_path":"errorbarsOnRelevanceMetric.py","file_name":"errorbarsOnRelevanceMetric.py","file_ext":"py","file_size_in_byte":9196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"106981229","text":"\"\"\"\n @author Victor I. Afolabi\n A.I. engineer/researcher & Software engineer\n javafolabi@gmail.com\n \n Created on 05 January, 2018 @ 10:08 PM.\n \n Copyright © 2018. Victor. All rights reserved.\n\"\"\"\nimport os\nimport sys\n\nimport numpy as np\n\nfrom models.dataset.base import Dataset\n\n\n################################################################################################\n# +———————————————————————————————————————————————————————————————————————————————————————————+\n# | ImageDataset\n# | for image datasets\n# +———————————————————————————————————————————————————————————————————————————————————————————+\n################################################################################################\n\nclass ImageDataset(Dataset):\n \"\"\"\n Dataset subclass for pre-processing image data\n\n :param data_dir: str\n\n :param size: int default 50\n Size of the image. The image will be resize\n into (size, size). Resizing the image doesn't affect the\n image channels but it does affect the shape of the image.\n\n :param grayscale: bool default False\n Maybe convert the image to grayscale.\n Note: the image channel will be 1 if converted to grayscale.\n\n :param flatten: bool default True\n Maybe flatten the image into a 1-D array. The `features`\n shape will be moodified into (n, d) where n is `num_examples`\n and d in the flattened dimension.\n\n :param kwargs:\n \"\"\"\n\n def __init__(self, size=50, grayscale=False, flatten=True, **kwargs):\n super().__init__(**kwargs)\n self.size = size\n self.grayscale = grayscale\n self.flatten = flatten\n\n self._labels = [l for l in os.listdir(\n self._data_dir) if l[0] is not '.']\n try:\n from PIL import Image\n except Exception as e:\n raise ModuleNotFoundError(f'{e}')\n # First image\n img_dir = os.path.join(self._data_dir, self._labels[0])\n img_file = os.path.join(img_dir, os.listdir(img_dir)[1])\n img = self.__create_image(img_file, return_obj=True)\n self._channel = img.im.bands\n # free memory\n del img_dir\n del img_file\n del img\n\n @property\n def images(self):\n return self._X\n\n @property\n def channel(self):\n return self._channel\n\n def _process(self):\n img_dirs = [os.path.join(self._data_dir, l) for l in self._labels]\n total_images = sum([len(os.listdir(d)) for d in img_dirs])\n if self.flatten:\n self._X = np.zeros(\n shape=[total_images, self.size * self.size * self.channel])\n else:\n self._X = np.zeros(\n shape=[total_images, self.size, self.size, self.channel])\n self._y = np.zeros(shape=[total_images, len(self._labels)])\n # Free memory\n del total_images\n del img_dirs\n counter = 0\n for i, label in enumerate(self._labels):\n image_dir = os.path.join(self._data_dir, label)\n image_list = [d for d in os.listdir(image_dir) if d[0] is not '.']\n for j, file in enumerate(image_list):\n # noinspection PyBroadException\n try:\n image_file = os.path.join(image_dir, file)\n img = self.__create_image(image_file)\n hot_label = self.__create_label(label)\n self._X[counter, :] = img\n self._y[counter, :] = hot_label\n except Exception as e:\n sys.stderr.write(f'\\r{i} - {e}')\n sys.stderr.flush()\n finally:\n counter += 1\n if self._logging:\n sys.stdout.write(f'\\rProcessing {i+1:,} of {len(self._labels):,} class labels'\n f'\\t{j+1:,} of {len(image_list):,} images')\n # Free up memory\n del counter\n\n def __create_image(self, file, return_obj=False):\n try:\n from PIL import Image\n except Exception as e:\n raise ModuleNotFoundError(f'{e}')\n img = Image.open(file)\n img = img.resize((self.size, self.size))\n if self.grayscale:\n img = img.convert('L')\n if return_obj:\n return img\n # convert to np.array\n img = np.array(img, dtype=np.float32)\n if self.flatten:\n img = img.flatten()\n return img\n\n def __create_label(self, label):\n hot = np.zeros(shape=[len(self._labels)], dtype=int)\n hot[self._labels.index(label)] = 1\n return hot\n","sub_path":"models/dataset/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"508216880","text":"\"\"\"An example of how to represent a group of acquaintances in Python.\"\"\"\n\n# Your code to go here...\n\n# define individual people\n\nliam = {'Name': 'Liam',\n 'Age': 22,\n 'Job': 'Student (MRes Medical Imaging)',\n 'Connections': [['Ed', 'Colleague'],\n ['Premal', 'Colleague'],\n ['Wang', 'Colleague']]}\n\npremal = {'Name': 'Premal',\n 'Age': 21,\n 'Job': 'Student (MSc Astrophysics)',\n 'Connections': [['Ed', 'Colleague'],\n ['Liam', 'Colleague'],\n ['Wang', 'Colleague']]}\n\ned = {'Name': 'Ed',\n 'Age': 22,\n 'Job': 'Student (MSc Scientific Computing)',\n 'Connections': [['Liam', 'Colleague'],\n ['Premal', 'Colleague'],\n ['Wang', 'Colleague']]}\n\nwang = {'Name': 'Wang',\n 'Age': 32,\n 'Job': 'Student (MSc Physics and Engineering in Medicine)',\n 'Connections': [['Liam', 'Colleague'],\n ['Premal', 'Colleague'],\n ['Ed', 'Colleague']]}\n\nmorgan = {'Name': 'Morgan',\n 'Age': 26,\n 'Job': [],\n 'Connections': []}\n\nmy_group = [liam, premal, ed, wang]\n# morgan]\n\nprint(my_group)\n\nfor i in range(len(my_group)):\n entry = my_group[i]\n print(entry['Name'],' is', str(entry['Age']), ', a(n) ',\n entry['Job'],' and (s)he is ',\n entry['Connections'][0][0],\"'s \", entry['Connections'][0][1],\n '.')","sub_path":"group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"624353317","text":"\"\"\"\nnotes :\n1.支持各个水域钓鱼,注意确保屏幕下方三分之一矩形区域全为水域,没有怪物和其他钓鱼者干扰。\n2.调节 RMS(触发响度),确保其值小于水花声但大于其他背景声音。(关闭背景音可获得更好效果)\n3.将特效调至最低可获得最佳效果。(95% 以上成功率)\n4.请勿于官方服务器,仅用于在某些外服、单机客户端测试各个地点各时段鱼群的构成和比例。\n5.程序对截图进行颜色分析,确定鱼漂坐标,然后以水花声为收杆触发条件。由于是个人使用,不再做过多说明。\n\nVersion 1.2 : TODO\n1.代码重构。\n2.数据统计。\n\nVersion 1.1 :\n1.调节水域截屏区域,大幅提升成功率。\n2.解决水下诱鱼器过期时死锁的BUG。\n3.注释部分DEBUG代码,减少响应时间。\n4.增加测试代码\n\nVersion 1.0 :\n修改原作者代码,使其可用于中文客户端。\nSOURCE: wdavid214\nMODIFIED BY: ClausewitzCPU0\n\n\"\"\"\nfrom win32gui import GetWindowText, GetForegroundWindow, GetWindowRect\nfrom PIL import ImageGrab, Image\nimport imageio\nimport numpy as np\nimport time\nimport sys\nimport pyautogui\nimport cv2\nimport audioop\nimport pyaudio\n\n# need to filter out image outliers. check distance to middle pixel to end, if too great then use 2nd last pixel and check dist til u find\n# how about just using 10th last pixel hard coded?\n\n# open audio stuff to listen on mic for speaker feedback going in (turn wow vol all the way up)\nchunk = 1024\np = pyaudio.PyAudio()\nstream = p.open(format=pyaudio.paInt16,\n channels=2, # need this to work (like other record script)\n rate=44100,\n input=True,\n frames_per_buffer=chunk,)\n # input_device_index=0)\n\nRMS = 3500\n# buf=40 # avoid boundary false trigger; not too far though\nbuf = 0 # alrdy compensated for boundary in initial rect adjustments\n\nz = 0\n\n# looks like we can find anything between 100 and 200 pixels in out_subtraction_green\n# to find bob once it appears. then run audio loop til trigger\n\nwhile True:\n if GetWindowText(GetForegroundWindow()) != '魔兽世界':\n print('World of Warcraft no active window !')\n print('-- New check 2 sec')\n time.sleep(2)\n else:\n\n ############# ONE TIME LOGIC AT VERY BEGINNING ####\n\n rect = GetWindowRect(GetForegroundWindow())\n rect = np.array(rect)\n # rect:[33 98 1975 1234] 分别表示该窗口的/左侧/顶部/右侧/底部坐标\n\n rect_back = np.copy(rect)\n\n # print(type(rect))\n\n rect[0] += 200\n rect[2] -= 200\n\n rect[3] -= 10\n\n # rect[1] += 25 # cut off title bar\n rect[1] += 750 # cut off title bar\n\n fish_area = (rect[0], rect[1], rect[2], rect[3])\n\n ############# END ONE TIME LOGIC AT VERY BEGINNING ####\n\n num_iterations = 0\n\n while num_iterations < 10:\n\n num_iterations += 1\n\n time.sleep(\n 1.5) # give some time for old lure to fade out ( so don't have double-lure issue which i thought was outlier)\n\n # cast line\n pyautogui.press('1')\n\n time.sleep(.5) # let it solidify\n\n continue1 = 0\n\n cnt = -1\n\n # clear out audio stream buffer to avoid double-triggers on next loop\n # print ('stopping audio stream')\n # stream.stop_stream()\n # time.sleep(2)\n # print ('starting audio stream')\n # stream.start_stream() # didnt seem to filter out old one...\n\n while continue1 == 0:\n\n cnt = cnt + 1\n\n time.sleep(1) # TODO REMOVE\n\n print('getting new img')\n\n img = ImageGrab.grab(fish_area)\n # img.save('img.png') # Saving the image\n\n # 对其他通道置零,只显示单个通道(b, g, r)\n # 例如只显示红色通道:cur_img[:, :, 0] = 0, cur_img[:, :, 1] = 0\n img_np = np.array(img)\n red_content = img_np[:, :, 0]\n red_content_back = red_content[:]\n green_content = img_np[:, :, 1]\n blue_content = img_np[:, :, 2]\n # print('green_content:{}'.format(green_content))\n # print('red_content:{}'.format(red_content))\n\n if cnt > 0:\n subtraction_green = red_content_back - green_content\n # subtraction_green = green_content - red_content_back\n # imageio.imwrite('out_subtraction_green%d.png' % (cnt), subtraction_green)\n # imageio.imwrite('out_subtraction_red%d.png' % (cnt), red_content_back - green_content)\n\n # find intensity between 100 and 200 in subtraction green, then move mouse there.\n # a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])\n\n # b = np.where(np.logical_and(subtraction_green>=100, subtraction_green<=200))\n # 输出满足条件元素的坐标\n b = np.where(subtraction_green > 200)\n # print(type(b))\n # print('b: {}\\n'.format(b))\n # print(b[0])\n if b[0].size > 10:\n # print(b[0].size)\n # print(b[0])\n # print(b[1])\n # print(subtraction_green)\n # np.savetxt(\"foo.csv\", subtraction_green, delimiter=\",\")\n\n # imageio.imwrite('out_subtraction_green_final.png', subtraction_green)\n\n jx = b[0][0] # grab first occurrence\n jy = b[1][0]\n\n # grab middle occurrence\n midpt1 = len(b[0]) / 2\n # print(midpt1)\n # jx = b[0][midpt1]\n # jy = b[1][midpt1]\n\n # jx = b[0][-1] # most robust triggering i've seen is on last element.\n # jy = b[1][-1]\n\n jx = b[0][\n -10] # to filter out outlier... PROBLEM WASNT OUTLIER, it was 2 lures!!!! wait some more time for other one to fade away, before taking next ss.\n jy = b[1][-10]\n\n # print(rect_back)\n # print(rect)\n # print(jx, jy)\n print('rect_back:{} rect:{} jx,jy:{}{}'.format(rect_back, rect, jx, jy))\n\n # note: x and y were backwards coming out of the np.where function.\n\n ix = jy + rect_back[0] + 200 # adjust relative to absolute screen coordinate\n iy = jx + rect_back[1] + 750\n\n print(\"IMAGE TRIGGERED!!!!\")\n # print(ix, iy)\n pyautogui.moveTo(ix, iy, 0.3) # see if it triggered on the right spot\n\n # don't fish yet; wait for audio trigger.\n # pyautogui.keyDown(\"shiftleft\")\n # pyautogui.mouseDown(button='right')\n # pyautogui.mouseUp(button='right')\n # pyautogui.keyUp(\"shiftleft\")\n\n print('\\nstarting audio check')\n\n fish_area = (0, rect[3] / 2, rect[2], rect[3])\n\n img = ImageGrab.grab(fish_area)\n img_np = np.array(img)\n\n frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)\n frame_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n h_min = np.array((0, 0, 253), np.uint8)\n h_max = np.array((255, 0, 255), np.uint8)\n\n mask = cv2.inRange(frame_hsv, h_min, h_max)\n\n moments = cv2.moments(mask, 1)\n dM01 = moments['m01']\n dM10 = moments['m10']\n dArea = moments['m00']\n\n b_x = 0\n b_y = 0\n lastx = 0\n lasty = 0\n\n if dArea > 0:\n b_x = int(dM10 / dArea)\n b_y = int(dM01 / dArea)\n if lastx > 0 and lasty > 0:\n if lastx != b_x and lasty != b_y:\n is_block = False\n if b_x < 1: b_x = lastx\n if b_y < 1: b_y = lasty\n pyautogui.moveTo(b_x, b_y + fish_area[1], 0.3)\n # pyautogui.keyDown('shiftleft')\n pyautogui.mouseDown(button='right')\n pyautogui.mouseUp(button='right')\n # pyautogui.keyUp('shiftleft')\n print(\"Catch !\")\n time.sleep(5)\n lastx = b_x\n lasty = b_y\n else:\n break\n","sub_path":"WoW_fishing_V2.py","file_name":"WoW_fishing_V2.py","file_ext":"py","file_size_in_byte":9199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"309894695","text":"class Cat:\n def __init__(self, new_name):\n print(\"这是一个初始化方法!!\")\n\n # self.属性名 = 属性的初始值\n # self.name = \"汤姆\"\n self.name = new_name\n\n def eat(self):\n print(\"%s爱吃鱼\" % self.name)\n\n\n# 使用类名加括号时会自动调用初始化方法 __init__ 这个方法\ntom = Cat(\"汤姆猫\")\ntom.eat()\n\nlazy = Cat(\"大懒猫\")\nlazy.eat()\n","sub_path":"Python基础/面向对象/面向对象基础/06-利用参数设置属性初始值.py","file_name":"06-利用参数设置属性初始值.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"101379647","text":"\"\"\"Collection of all parameter related classes and functions.\"\"\"\nimport pickle\nimport warnings\nfrom .printout import printout, set_horovod_status\ntry:\n import horovod.torch as hvd\nexcept ModuleNotFoundError:\n warnings.warn(\"You either don't have Horovod installed or it is not \"\n \"configured correctly. You can still train networks, but \"\n \"attempting to set parameters.training.use_horovod = \"\n \"True WILL cause a crash.\", stacklevel=3)\nimport torch\n\n\nclass ParametersBase:\n \"\"\"Base parameter class for MALA.\"\"\"\n\n def __init__(self):\n \"\"\"Create an instance of ParameterBase.\"\"\"\n pass\n\n def show(self, indent=\"\"):\n \"\"\"\n Print name and values of all attributes of this object.\n\n Parameters\n ----------\n indent : string\n The indent used in the list with which the parameter\n shows itself.\n\n \"\"\"\n for v in vars(self):\n printout(indent + '%-15s: %s' % (v, getattr(self, v)))\n\n\nclass ParametersNetwork(ParametersBase):\n \"\"\"\n Parameters necessary for constructing a neural network.\n\n Attributes\n ----------\n nn_type : string\n Type of the neural network that will be used. Currently supported is\n only feed-forward, which is also the default\n\n layer_sizes : list\n A list of integers detailing the sizes of the layer of the neural\n network. Please note that the input layer is included therein.\n Default: [10,10,0]\n\n layer_activations: list\n A list of strings detailing the activation functions to be used\n by the neural network. If the dimension of layer_activations is\n smaller than the dimension of layer_sizes-1, than the first entry\n is used for all layers.\n Currently supported activation functions are:\n\n - Sigmoid (default)\n - ReLU\n - LeakyReLU\n\n loss_function_type: string\n Loss function for the neural network\n Currently supported loss functions include:\n\n - mse (Mean squared error; default)\n \"\"\"\n\n def __init__(self):\n \"\"\"Create an instance of ParametersNetwork.\"\"\"\n super(ParametersNetwork, self).__init__()\n self.nn_type = \"feed-forward\"\n self.layer_sizes = [10, 10, 10]\n self.layer_activations = [\"Sigmoid\"]\n self.loss_function_type = \"mse\"\n\n\nclass ParametersDescriptors(ParametersBase):\n \"\"\"\n Parameters necessary for calculating/parsing input descriptors.\n\n Attributes\n ----------\n descriptor_type : string\n Type of descriptors that is used to represent the atomic fingerprint.\n Currently only \"SNAP\" is supported.\n\n twojmax : int\n SNAP calculation: 2*jmax-parameter used for calculation of SNAP\n descriptors. Default value for jmax is 5, so default value for\n twojmax is 10.\n\n rcutfac: float\n SNAP calculation: radius cutoff factor for the fingerprint sphere in\n Angstroms. Default value is 4.67637.\n\n lammps_compute_file: string\n SNAP calculation: LAMMPS input file that is used to calculate the\n SNAP descriptors. If this string is empty, the standard LAMMPS input\n file found in this repository will be used (recommended).\n\n \"\"\"\n\n def __init__(self):\n \"\"\"Create an instance of ParametersDescriptors.\"\"\"\n super(ParametersDescriptors, self).__init__()\n self.descriptor_type = \"SNAP\"\n self.twojmax = 10\n self.rcutfac = 4.67637\n self.lammps_compute_file = \"\"\n\n\nclass ParametersTargets(ParametersBase):\n \"\"\"\n Parameters necessary for calculating/parsing output quantites.\n\n Attributes\n ----------\n target_type : string\n Number of points in the energy grid that is used to calculate the\n (L)DOS.\n\n ldos_gridsize : float\n Gridspacing of the energy grid the (L)DOS is evaluated on [eV].\n\n ldos_gridspacing_ev: float\n SNAP calculation: radius cutoff factor for the fingerprint sphere in\n Angstroms. Default value is 4.67637.\n\n ldos_gridoffset_ev: float\n Lowest energy value on the (L)DOS energy grid [eV].\n \"\"\"\n\n def __init__(self):\n \"\"\"Create an instance of ParameterTargets.\"\"\"\n super(ParametersTargets, self).__init__()\n self.target_type = \"LDOS\"\n self.ldos_gridsize = 0\n self.ldos_gridspacing_ev = 0\n self.ldos_gridoffset_ev = 0\n\n\nclass ParametersData(ParametersBase):\n \"\"\"\n Parameters necessary for loading and preprocessing data.\n\n Attributes\n ----------\n descriptors_contain_xyz : bool\n Legacy option. If True, it is assumed that the first three entries of\n the descriptor vector are the xyz coordinates and they are cut from the\n descriptor vector. If False, no such cutting is peformed.\n\n snapshot_directories_list : list\n A list of all added snapshots.\n\n data_splitting_type : string\n Specify how the data for validation, test and training is splitted.\n Currently the only supported option is by_snapshot,\n which splits the data by snapshot boundaries. It is also the default.\n\n data_splitting_snapshots : list\n Details how (and which!) snapshots are used for what:\n\n - te: This snapshot will be a testing snapshot.\n - tr: This snapshot will be a training snapshot.\n - va: This snapshot will be a validation snapshot.\n\n Please note that the length of this list and the number of snapshots\n must be identical. The first element of this list will be used\n to characterize the first snapshot, the second element for the second\n snapshot etc.\n\n input_rescaling_type : string\n Specifies how input quantities are normalized.\n Options:\n\n - \"None\": No normalization is applied.\n - \"standard\": Standardization (Scale to mean 0, standard\n deviation 1)\n - \"normal\": Min-Max scaling (Scale to be in range 0...1)\n - \"feature-wise-standard\": Row Standardization (Scale to mean 0,\n standard deviation 1)\n - \"feature-wise-normal\": Row Min-Max scaling (Scale to be in range\n 0...1)\n\n output_rescaling_type : string\n Specifies how output quantities are normalized.\n Options:\n\n - \"None\": No normalization is applied.\n - \"standard\": Standardization (Scale to mean 0,\n standard deviation 1)\n - \"normal\": Min-Max scaling (Scale to be in range 0...1)\n - \"feature-wise-standard\": Row Standardization (Scale to mean 0,\n standard deviation 1)\n - \"feature-wise-normal\": Row Min-Max scaling (Scale to be in\n range 0...1)\n\n use_lazy_loading : bool\n If True, data is lazily loaded, i.e. only the snapshots that are\n currently needed will be kept in memory. This greatly reduces memory\n demands, but adds additional computational time.\n \"\"\"\n\n def __init__(self):\n \"\"\"Create an instance of ParametersData.\"\"\"\n super(ParametersData, self).__init__()\n self.descriptors_contain_xyz = True\n self.snapshot_directories_list = []\n self.data_splitting_type = \"by_snapshot\"\n # self.data_splitting_percent = [0,0,0]\n self.data_splitting_snapshots = []\n self.input_rescaling_type = \"None\"\n self.output_rescaling_type = \"None\"\n self.use_lazy_loading = False\n\n\nclass ParametersRunning(ParametersBase):\n \"\"\"\n Parameters needed for network runs (train, test or inference).\n\n Some of these parameters only apply to either the train or test or\n inference case.\n\n Attributes\n ----------\n trainingtype : string\n Training type to be used. Supported options at the moment:\n\n - SGD: Stochastic gradient descent.\n - Adam: Adam Optimization Algorithm\n\n learning_rate : float\n Learning rate for chosen optimization algorithm. Default: 0.5.\n\n max_number_epochs : int\n Maximum number of epochs to train for. Default: 100.\n\n verbosity : bool\n If True, training output is shown during training. Default: True.\n\n mini_batch_size : int\n Size of the mini batch for the optimization algorihm. Default: 10.\n\n weight_decay : float\n Weight decay for regularization. Always refers to L2 regularization.\n Default: 0.\n\n early_stopping_epochs : int\n Number of epochs the validation accuracy is allowed to not improve by\n at leastearly_stopping_threshold, before we terminate. If 0, no\n early stopping is performed. Default: 0.\n\n early_stopping_threshold : float\n If the validation accuracy does not improve by at least threshold for\n early_stopping_epochs epochs, training is terminated:\n validation_loss < validation_loss_old * (1+early_stopping_threshold),\n or patience counter will go up.\n Default: 0. Numbers bigger than 0 can make early stopping very\n aggresive.\n\n learning_rate_scheduler : string\n Learning rate scheduler to be used. If not None, an instance of the\n corresponding pytorch class will be used to manage the learning rate\n schedule.\n Options:\n\n - None: No learning rate schedule will be used.\n - \"ReduceLROnPlateau\": The learning rate will be reduced when the\n validation loss is plateauing.\n\n learning_rate_decay : float\n Decay rate to be used in the learning rate (if the chosen scheduler\n supports that).\n Default: 0.1\n\n learning_rate_patience : int\n Patience parameter used in the learning rate schedule (how long the\n validation loss has to plateau before the schedule takes effect).\n Default: 0.\n\n use_compression : bool\n If True and horovod is used, horovod compression will be used for\n allreduce communication. This can improve performance.\n\n kwargs : dict\n Dictionary for keyword arguments for horovod.\n\n sampler : dict\n Dictionary with samplers.\n\n use_shuffling_for_samplers :\n If True, the training data will be shuffled in between epochs.\n If lazy loading is selected, then this shuffling will be done on\n a \"by snapshot\" basis.\n\n checkpoints_each_epoch : int\n If not 0, checkpoint files will be saved after eac\n checkpoints_each_epoch epoch.\n\n checkpoint_name : string\n Name used for the checkpoints. Using this, multiple runs\n can be performed in the same directory.\n \"\"\"\n\n def __init__(self):\n \"\"\"Create an instance of ParametersRunning.\"\"\"\n super(ParametersRunning, self).__init__()\n self.trainingtype = \"SGD\"\n self.learning_rate = 0.5\n self.max_number_epochs = 100\n # TODO: Find a better system for verbosity. Maybe a number.\n self.verbosity = True\n self.mini_batch_size = 10\n self.weight_decay = 0\n self.early_stopping_epochs = 0\n self.early_stopping_threshold = 0\n self.learning_rate_scheduler = None\n self.learning_rate_decay = 0.1\n self.learning_rate_patience = 0\n self.use_compression = False\n # TODO: Give this parameter a more descriptive name.\n self.kwargs = {'num_workers': 0, 'pin_memory': False}\n # TODO: Objects should not be parameters!\n self.sampler = {\"train_sampler\": None, \"validate_sampler\": None,\n \"test_sampler\": None}\n self.use_shuffling_for_samplers = True\n self.checkpoints_each_epoch = 0\n self.checkpoint_name = \"checkpoint_mala\"\n\n\nclass ParametersHyperparameterOptimization(ParametersBase):\n \"\"\"\n Hyperparameter optimization parameters.\n\n Attributes\n ----------\n direction : string\n Controls whether to minimize or maximize the loss function.\n Arguments are \"minimize\" and \"maximize\" respectively.\n\n n_trials : int\n Controls how many trials are performed (when using optuna).\n Default: 100.\n\n hlist : list\n List containing hyperparameters, that are then passed to optuna.\n Supported options so far include:\n\n - learning_rate (float): learning rate of the training algorithm\n - layer_activation_xxx (categorical): Activation function used for\n the feed forward network (see Netwok parameters for supported\n activation functions). Note that _xxx is only so that optuna\n will differentiate between variables. No reordering is\n performed by the; the order depends on the order in the\n list. _xxx can be essentially anything. Please note further\n that you need to either only request one acitvation function\n (for all layers) or one for specifically for each layer.\n - ff_neurons_layer_xxx(int): Number of neurons per a layer. Note\n that _xxx is only so that optuna will differentiate between\n variables. No reordering is performed by MALA; the order\n depends on the order in the list. _xxx can be essentially\n anything.\n\n Users normally don't have to fill this list by hand, the hyperparamer\n optimizer provide interfaces for this task.\n\n\n hyper_opt_method : string\n Method used for hyperparameter optimization. Currently supported:\n\n - \"optuna\" : Use optuna for the hyperparameter optimization.\n - \"oat\" : Use orthogonal array tuning (currently limited to\n categorical hyperparemeters). Range analysis is\n currently done by simply choosing the lowesr loss.\n - \"notraining\" : Using a NAS without training, based on jacobians.\n\n checkpoints_each_trial : int\n If not 0, checkpoint files will be saved after each\n checkpoints_each_trial trials. Currently, this only works with\n optuna.\n\n checkpoint_name : string\n Name used for the checkpoints. Using this, multiple runs\n can be performed in the same directory. Currently. this\n only works with optuna.\n \"\"\"\n\n def __init__(self):\n \"\"\"Create an instance of ParametersHyperparameterOptimization.\"\"\"\n super(ParametersHyperparameterOptimization, self).__init__()\n self.direction = 'minimize'\n self.n_trials = 100\n self.hlist = []\n self.hyper_opt_method = \"optuna\"\n self.checkpoints_each_trial = 0\n self.checkpoint_name = \"checkpoint_mala_ho\"\n self.study_name = None\n self.rdb_storage = None\n self.rdb_storage_heartbeat = None\n\n @property\n def rdb_storage_heartbeat(self):\n \"\"\"Control whether a heartbeat is used for distributed optuna runs.\"\"\"\n return self._rdb_storage_heartbeat\n\n @rdb_storage_heartbeat.setter\n def rdb_storage_heartbeat(self, value):\n if value == 0:\n self._rdb_storage_heartbeat = None\n else:\n self._rdb_storage_heartbeat = value\n\n def show(self, indent=\"\"):\n \"\"\"\n Print name and values of all attributes of this object.\n\n Parameters\n ----------\n indent : string\n The indent used in the list with which the parameter\n shows itself.\n\n \"\"\"\n for v in vars(self):\n if v != \"hlist\":\n printout(indent + '%-15s: %s' % (v, getattr(self, v)))\n if v == \"hlist\":\n i = 0\n for hyp in self.hlist:\n printout(indent + '%-15s: %s' %\n (\"hyperparameter #\"+str(i), hyp.name))\n i += 1\n\n\nclass ParametersDebug(ParametersBase):\n \"\"\"\n All debugging parameters.\n\n Attributes\n ----------\n grid_dimensions : list\n A list containing three elements. It enforces a smaller grid size\n globally when it is not empty.. Default : []\n\n \"\"\"\n\n def __init__(self):\n \"\"\"Create an instance of ParametersDebug.\"\"\"\n super(ParametersDebug, self).__init__()\n self.grid_dimensions = []\n\n\nclass Parameters:\n \"\"\"\n All parameter MALA needs to perform its various tasks.\n\n Attributes\n ----------\n comment : string\n Characterizes a set of parameters (e.g. \"experiment_ddmmyy\").\n\n network : ParametersNetwork\n Contains all parameters necessary for constructing a neural network.\n\n descriptors : ParametersDescriptors\n Contains all parameters necessary for calculating/parsing descriptors.\n\n targets : ParametersTargets\n Contains all parameters necessary for calculating/parsing output\n quantites.\n\n data : ParametersData\n Contains all parameters necessary for loading and preprocessing data.\n\n running : ParametersRunning\n Contains parameters needed for network runs (train, test or inference).\n\n hyperparameters : ParametersHyperparameterOptimization\n Parameters used for hyperparameter optimization.\n\n debug : ParametersDebug\n Container for all debugging parameters.\n\n manual_seed: int\n If not none, this value is used as manual seed for the neural networks.\n Can be used to make experiments comparable. Default: None.\n \"\"\"\n\n def __init__(self):\n \"\"\"Create an instance of Parameters.\"\"\"\n self.comment = \"\"\n self.network = ParametersNetwork()\n self.descriptors = ParametersDescriptors()\n self.targets = ParametersTargets()\n self.data = ParametersData()\n self.running = ParametersRunning()\n self.hyperparameters = ParametersHyperparameterOptimization()\n self.debug = ParametersDebug()\n self.manual_seed = None\n\n # Properties\n self.use_horovod = False\n self.use_gpu = False\n\n @property\n def use_gpu(self):\n \"\"\"Control whether or not a GPU is used (provided there is one).\"\"\"\n return self._use_gpu\n\n @use_gpu.setter\n def use_gpu(self, value):\n if value is False:\n self._use_gpu = False\n if value is True:\n if torch.cuda.is_available():\n self._use_gpu = True\n else:\n warnings.warn(\"GPU requested, but no GPU found. MALA will \"\n \"operate with CPU only.\", stacklevel=3)\n\n @property\n def use_horovod(self):\n \"\"\"Control whether or not horovod is used for parallel training.\"\"\"\n return self._use_horovod\n\n @use_horovod.setter\n def use_horovod(self, value):\n if value:\n hvd.init()\n set_horovod_status(value)\n self._use_horovod = value\n\n def show(self):\n \"\"\"Print name and values of all attributes of this object.\"\"\"\n printout(\"--- \" + self.__doc__.split(\"\\n\")[1] + \" ---\")\n for v in vars(self):\n if isinstance(getattr(self, v), ParametersBase):\n parobject = getattr(self, v)\n printout(\"--- \" + parobject.__doc__.split(\"\\n\")[1] + \" ---\")\n parobject.show(\"\\t\")\n else:\n printout('%-15s: %s' % (v, getattr(self, v)))\n\n def save(self, filename, save_format=\"pickle\"):\n \"\"\"\n Save the Parameters object to a file.\n\n Parameters\n ----------\n filename : string\n File to which the parameters will be saved to.\n\n save_format : string\n File format which is used for parameter saving.\n Currently only supported file format is \"pickle\".\n\n \"\"\"\n if self.use_horovod:\n if hvd.rank() != 0:\n return\n if save_format == \"pickle\":\n with open(filename, 'wb') as handle:\n pickle.dump(self, handle, protocol=4)\n else:\n raise Exception(\"Unsupported parameter save format.\")\n\n @classmethod\n def load_from_file(cls, filename, save_format=\"pickle\",\n no_snapshots=False):\n \"\"\"\n Load a Parameters object from a file.\n\n Parameters\n ----------\n filename : string\n File to which the parameters will be saved to.\n\n save_format : string\n File format which is used for parameter saving.\n Currently only supported file format is \"pickle\".\n\n no_snapshots : bool\n If True, than the snapshot list will be emptied. Useful when\n performing inference/testing after training a network.\n\n Returns\n -------\n loaded_parameters : Parameters\n The loaded Parameters object.\n\n \"\"\"\n if save_format == \"pickle\":\n with open(filename, 'rb') as handle:\n loaded_parameters = pickle.load(handle)\n if no_snapshots is True:\n loaded_parameters.data.snapshot_directories_list = []\n else:\n raise Exception(\"Unsupported parameter save format.\")\n\n return loaded_parameters\n","sub_path":"mala/common/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":20978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"250598957","text":"import random\n\ndef simulate():\n\t#Dictionary Key is seat #, value is the assigned seat of the person sitting there\n\tseatingDict = {}\n\t\n\t\n\t\n\tseatingDict[random.randint(1, 100)] = 1;\n\t\n\tfor x in range(2, 101):\n\t\tif x not in seatingDict:\n\t\t\tseatingDict[x] = x\n\t\telse:\n\t\t\tfoundEmptySeat = False\n\t\t\twhile foundEmptySeat == False:\n\t\t\t\tr = random.randint(1,100)\n\t\t\t\tif r not in seatingDict:\n\t\t\t\t\tseatingDict[r] = x\n\t\t\t\t\tfoundEmptySeat = True\n\tif seatingDict[100] == 100:\n\t\treturn 1\n\telse:\n\t\treturn 0\n\ntrials = 10000\nsucesses = 0\n\n\nfor i in range(0, trials):\n\tsucesses = sucesses + simulate()\n\t\nprobability = sucesses/trials\n\n\nprint(\"Person 100 sat in seat 100\", sucesses, \"times out of\", trials, \"for a probability of\", probability)","sub_path":"Sprint-3-Monte_Carlo_Simulation/Deliverables/ticket_problem.py","file_name":"ticket_problem.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"618378277","text":"import random\n\ndef pinGen(n):\n pinStr = ''\n for i in range(n):\n if i == 0:\n pinStr += str(random.randint(1, 9))\n else:\n pinStr += str(random.randint(0, 9))\n print(pinStr)\n\nwhile True:\n userInput = input('Enter a PIN length(must be at least 4 digits):')\n try:\n n = int(userInput)\n if n < 4:\n print('Number must be greater than or equal to 4')\n continue\n else:\n break\n except ValueError:\n print('Please enter a number 4 or greater.')\n\npinGen(n)","sub_path":"CS160/JamesBoyd/Module6/Lab6q7.py","file_name":"Lab6q7.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"114232344","text":"# Ex 5.4\ndef recurse(n, s):\n \"\"\"\n Returns n/2(n+1+s) if n > -1, stackoverflow otherwise.\n \"\"\"\n if n == 0:\n print(s)\n else:\n recurse(n-1, n+s)\n\nif __name__ == '__main__':\n recurse(3, 0) # 6\n # recurse(-1, 0) Stackoverflow since Python does not perform tail-call optimisation\n","sub_path":"Think Python/chapter5/recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"375785822","text":"# error handling\n# 4.9 Inflix, Prefix and Postfix Expressions\n\nfrom stack import Stack\n\n# new\ndef fixError(astring):\n newstr = \"\"\n is_space_place = False\n\n for token in astring:\n if token != ' ':\n if is_space_place == False:\n newstr = newstr + token\n is_space_place = True\n else:\n newstr = newstr + ' '\n newstr = newstr + token\n is_space_place = True\n return newstr\n\ndef infixToPostfix(infixexpr):\n prec = {}\n\n prec[\"*\"] = 3\n prec[\"/\"] = 3\n prec[\"+\"] = 2\n prec[\"-\"] = 2\n prec[\"(\"] = 1\n\n opStack = Stack()\n postfixList = []\n\n infixexpr = fixError(infixexpr) # new\n\n tokenList = infixexpr.split()\n\n for token in tokenList:\n\n if token in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" or token in \"0123456789\":\n postfixList.append(token)\n elif token == '(':\n opStack.push(token)\n elif token == ')':\n topToken = opStack.pop()\n while topToken != '(':\n postfixList.append(topToken)\n topToken = opStack.pop()\n else:\n while (not opStack.isEmpty()) and \\\n (prec[opStack.peek()] >= prec[token]):\n postfixList.append(opStack.pop())\n opStack.push(token)\n\n #print(f\"token = {token} -- postfixList = {postfixList} -- opStack = {opStack}\")\n\n while not opStack.isEmpty():\n postfixList.append(opStack.pop())\n return \" \".join(postfixList)\n\nprint(infixToPostfix(\"A * B + C * D\"))\nprint(infixToPostfix(\"( A + B ) * C - ( D - E ) * ( F + G )\"))\n\nprint(infixToPostfix(\"(A + B ) * C - ( D - E ) * ( F + G )\")) # intentional error\n","sub_path":"4.9d.py","file_name":"4.9d.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"8427899","text":"# coding: utf-8\r\nfrom flask import render_template, request, redirect, url_for, Blueprint\r\nfrom ..models import db, Author, AuthorQuote, Work, WorkType, CollectWork, Dynasty\r\nfrom ..utils import require_admin\r\n\r\nbp = Blueprint('author', __name__)\r\n\r\n\r\n@bp.route('/')\r\ndef view(author_abbr):\r\n \"\"\"文学家主页\"\"\"\r\n author = Author.query.options(db.subqueryload(Author.works)).filter(Author.abbr == author_abbr).first_or_404()\r\n quote = AuthorQuote.query.get_or_404(int(float(request.args['q']))) if 'q' in request.args else author.random_quote\r\n stmt = db.session.query(Work.type_id, db.func.count(Work.type_id).label('type_num')).filter(\r\n Work.author_id == author.id).group_by(Work.type_id).subquery()\r\n work_types = db.session.query(WorkType, stmt.c.type_num).join(stmt, WorkType.id == stmt.c.type_id)\r\n return render_template('author/author.html', author=author, quote=quote, work_types=work_types)\r\n\r\n\r\n@bp.route('/')\r\ndef authors():\r\n \"\"\"全部文学家\"\"\"\r\n dynasties = Dynasty.query.filter(Dynasty.authors.any()).order_by(Dynasty.start_year)\r\n # get the authors who's works are latest collected by user\r\n stmt = db.session.query(Author.id, CollectWork.create_time).join(Work).join(CollectWork).group_by(Author.id).having(\r\n db.func.max(CollectWork.create_time)).subquery()\r\n hot_authors = Author.query.join(stmt, Author.id == stmt.c.id).order_by(stmt.c.create_time.desc()).limit(8)\r\n return render_template('author/authors.html', dynasties=dynasties, hot_authors=hot_authors)\r\n\r\n\r\n@bp.route('/add', methods=['GET', 'POST'])\r\n@require_admin\r\ndef add():\r\n \"\"\"添加文学家\"\"\"\r\n if request.method == 'GET':\r\n dynasties = Dynasty.query.order_by(Dynasty.start_year)\r\n return render_template('author/add.html', dynasties=dynasties)\r\n else:\r\n author = Author(name=request.form['name'], abbr=request.form['abbr'], intro=request.form['intro'],\r\n birth_year=request.form['birth_year'], death_year=request.form['death_year'],\r\n dynasty_id=int(request.form['dynasty_id']))\r\n db.session.add(author)\r\n db.session.commit()\r\n return redirect(url_for('.view', author_abbr=author.abbr))\r\n\r\n\r\n@bp.route('//edit', methods=['GET', 'POST'])\r\n@require_admin\r\ndef edit(author_id):\r\n \"\"\"编辑文学家\"\"\"\r\n author = Author.query.get_or_404(author_id)\r\n if request.method == 'GET':\r\n dynasties = Dynasty.query.order_by(Dynasty.start_year)\r\n return render_template('author/edit.html', dynasties=dynasties, author=author)\r\n author.name = request.form['name']\r\n author.abbr = request.form['abbr']\r\n author.intro = request.form['intro']\r\n author.birth_year = request.form['birth_year']\r\n author.death_year = request.form['death_year']\r\n author.dynasty_id = int(request.form['dynasty_id'])\r\n db.session.add(author)\r\n db.session.commit()\r\n return redirect(url_for('.view', author_abbr=author.abbr))\r\n\r\n\r\n@bp.route('//admin_quote')\r\n@require_admin\r\ndef admin_quotes(author_id):\r\n \"\"\"管理文学家的名言\"\"\"\r\n author = Author.query.options(db.subqueryload(Author.quotes)).get_or_404(author_id)\r\n return render_template('author/admin_quotes.html', author=author)\r\n\r\n\r\n@bp.route('//add_quote', methods=['POST'])\r\n@require_admin\r\ndef add_quote(author_id):\r\n \"\"\"添加名言\"\"\"\r\n quote = AuthorQuote(quote=request.form['quote'], author_id=author_id, work_id=int(request.form['work_id']))\r\n db.session.add(quote)\r\n db.session.commit()\r\n return redirect(url_for('.admin_quotes', author_id=author_id))\r\n\r\n\r\n@bp.route('/quote//delete')\r\n@require_admin\r\ndef delete_quote(quote_id):\r\n \"\"\"删除名言\"\"\"\r\n quote = AuthorQuote.query.get_or_404(quote_id)\r\n db.session.delete(quote)\r\n db.session.commit()\r\n return redirect(url_for('.admin_quotes', author_id=quote.author_id))\r\n\r\n\r\n@bp.route('/quote//edit', methods=['GET', 'POST'])\r\n@require_admin\r\ndef edit_quote(quote_id):\r\n \"\"\"编辑名言\"\"\"\r\n if request.method == 'GET':\r\n quote = AuthorQuote.query.get_or_404(quote_id)\r\n return render_template('author/edit_quote.html', quote=quote)\r\n else:\r\n quote = AuthorQuote.query.get_or_404(quote_id)\r\n quote.quote = request.form['quote']\r\n quote.work_id = int(request.form['work_id'])\r\n db.session.add(quote)\r\n db.session.commit()\r\n return redirect(url_for('.admin_quotes', author_id=quote.work.author_id))","sub_path":"xichuangzhu/controllers/author.py","file_name":"author.py","file_ext":"py","file_size_in_byte":4559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"486362484","text":"import math,string,itertools,fractions,heapq,collections,re,array,bisect,random\n\nclass TheQuestionsAndAnswersDivTwo:\n def find(self, questions):\n return math.pow(2,(len(set(questions))))\n\n# BEGIN KAWIGIEDIT TESTING\n# Generated by KawigiEdit-pf 2.3.0\nimport sys\nimport time\ndef KawigiEdit_RunTest(testNum, p0, hasAnswer, p1):\n\tsys.stdout.write(str(\"Test \") + str(testNum) + str(\": [\") + str(\"{\"))\n\tfor i in range(len(p0)):\n\t\tif (i > 0):\n\t\t\tsys.stdout.write(str(\",\"))\n\t\t\n\t\tsys.stdout.write(str(\"\\\"\") + str(p0[i]) + str(\"\\\"\"))\n\t\n\tsys.stdout.write(str(\"}\"))\n\tprint(str(\"]\"))\n\tobj = TheQuestionsAndAnswersDivTwo()\n\tstartTime = time.clock()\n\tanswer = obj.find(p0)\n\tendTime = time.clock()\n\tres = True\n\tprint(str(\"Time: \") + str((endTime - startTime)) + str(\" seconds\"))\n\tif (hasAnswer):\n\t\tprint(str(\"Desired answer:\"))\n\t\tprint(str(\"\\t\") + str(p1))\n\t\n\tprint(str(\"Your answer:\"))\n\tprint(str(\"\\t\") + str(answer))\n\tif (hasAnswer):\n\t\tres = answer == p1\n\t\n\tif (not res):\n\t\tprint(str(\"DOESN'T MATCH!!!!\"))\n\telif ((endTime - startTime) >= 2):\n\t\tprint(str(\"FAIL the timeout\"))\n\t\tres = False\n\telif (hasAnswer):\n\t\tprint(str(\"Match :-)\"))\n\telse:\n\t\tprint(str(\"OK, but is it right?\"))\n\t\n\tprint(str(\"\"))\n\treturn res\n\nall_right = True\ntests_disabled = False\n\n\nif (all_right):\n\tif (tests_disabled):\n\t\tprint(str(\"You're a stud (but some test cases were disabled)!\"))\n\telse:\n\t\tprint(str(\"You're a stud (at least on given cases)!\"))\n\t\nelse:\n\tprint(str(\"Some of the test cases had errors.\"))\n\n# PROBLEM STATEMENT\n# \n# John and Brus have become very famous people all over the world, especially in Bolivia.\n# A man in Bolivia decided to write a story about them.\n# To make the story more truthful, he set up an interview with John.\n# He prepared a list of distinct simple \"Yes\" or \"No\" questions and he enlisted the help of two friends to transcribe the interview.\n# Each time he asked a question, one friend wrote down the question while the other friend wrote down the answer.\n# He was very nervous when conducting the interview, so he might have asked some of the questions multiple times.\n# However, John's answers always remained the same for the same questions.\n# \n# \n# \n# Unfortunately, the friend who was writing down John's answers lost his list.\n# You are given a tuple (string) questions, where the i-th element is the i-th question asked.\n# In a desperate attempt to remember the answers, the Bolivian has decided to write down all the possible ways that John might have answered the questions.\n# By doing this, he hopes that he will be able to recognize the correct combination of answers.\n# Return the total number of combinations that he will have to write down.\n# \n# \n# \n# DEFINITION\n# Class:TheQuestionsAndAnswersDivTwo\n# Method:find\n# Parameters:tuple (string)\n# Returns:integer\n# Method signature:def find(self, questions):\n# \n# \n# NOTES\n# -Two questions are considered to be the same if corresponding elements of questions are absolutely the same strings.\n# -All questions are case-sensitive, i.e., lowercase and uppercase equivalents of the same letter are considered to be different characters.\n# \n# \n# CONSTRAINTS\n# -questions will contain between 1 and 10 elements, inclusive.\n# -Each element of questions will contain between 1 and 50 characters, inclusive.\n# -Each character in questions will be a lowercase letter ('a'-'z'), uppercase letter ('A'-'Z'), question mark ('?') or underscore ('_').\n# \n# \n# EXAMPLES\n# \n# 0)\n# {\"How_are_you_doing?\", \"How_do_you_like_our_country?\", \"How_are_you_doing?\"}\n# \n# Returns: 4\n# \n# There are four ways to answer this sequence of questions:\n# \n# \"Yes\", \"Yes\", \"Yes\";\n# \"Yes\", \"No\", \"Yes\";\n# \"No\", \"Yes\", \"No\";\n# \"No\", \"No\", \"No\".\n# \n# \n# 1)\n# {\"Whazzup?\"}\n# \n# Returns: 2\n# \n# Just a single question.\n# \n# 2)\n# {\"Are_you_ready?\", \"Are_you_ready?\", \"Are_you_ready?\", \"Are_you_ready?\"}\n# \n# Returns: 2\n# \n# All these questions are the same.\n# \n# 3)\n# {\"Do_you_like_my_story?\", \"Do_you_like_my_story\", \"DO_YOU_LIKE_MY_STORY?\", \"Do__you__like__my__story?\"}\n# \n# Returns: 16\n# \n# All these questions are distinct.\n# \n# END KAWIGIEDIT TESTING\n#Powered by KawigiEdit-pf 2.3.0!\n","sub_path":"TheQuestionsAndAnswersDivTwo.py","file_name":"TheQuestionsAndAnswersDivTwo.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"188097482","text":"filename1 = input(\"원본 파일 이름을 입력하시오: \");\nfilename2 = input(\"복사 파일 이름을 입력하시오: \");\n\ninfile = open(filename1, \"rb\")\noutfile = open(filename2, \"wb\")\n\n# 입력 파일에서 1024 바이트씩 읽어서 출력 파일에 쓴다.\nwhile True:\n copy_buffer = infile.read(1024)\n if not copy_buffer:\n break\n outfile.write(copy_buffer)\n\ninfile.close()\noutfile.close()\nprint(filename1 + \"를 \" + filename2 + \"로 복사하였습니다. \")\n\n","sub_path":"이미지 복사하기.py","file_name":"이미지 복사하기.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"446045053","text":"def is_palindrome(lst):\n if len(lst)%2 == 0 and lst[:len(lst)//2] == lst[len(lst)//2:][::-1]: return True\n elif len(lst)%2 == 1 and lst[:len(lst)//2] == lst[(len(lst)//2)+1:][::-1]: return True\n return False \n\n\ndef solution(s):\n # 최소 한자리이므로\n max_len = 1\n for i in range(len(s)-1):\n for j in range(i, len(s)):\n if s[i] == s[j] and is_palindrome(s[i:j+1]):\n if j-i+1 > max_len:\n max_len = j - i + 1\n return max_len\n\nprint(solution(\"abcdcba\"))","sub_path":"Programmers/Programmers_lv3/Programmers_lv3_가장긴팰린드롬.py","file_name":"Programmers_lv3_가장긴팰린드롬.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"544352052","text":"import unittest\nfrom conan.packager import ConanMultiPackager\n\n\nclass MockRunner(object):\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.calls = []\n\n def __call__(self, command):\n self.calls.append(command)\n return 0\n\n def tests_for(self, numbers):\n \"\"\"Check if executor has ran the builds that are expected.\n numbers are integers\"\"\"\n def line_for_number(number):\n return \"conan test_package . -s compiler=\\\"os%(number)d\\\" -s os=\\\"os%(number)d\\\" \"\\\n \"-o option%(number)d=\\\"value%(number)d\\\"\" % {\"number\": number}\n\n found_numbers = []\n for call in self.calls:\n if call.startswith(\"conan export\"):\n continue\n if call.startswith(\"conan test\"):\n found = None\n for number in numbers:\n if call.startswith(line_for_number(number)):\n found = number\n break\n if found is not None:\n found_numbers.append(number)\n else:\n return False\n return set(found_numbers) == set(numbers)\n\n\nclass AppTest(unittest.TestCase):\n\n def setUp(self):\n self.runner = MockRunner()\n self.packager = ConanMultiPackager(\"--build missing -r conan.io\",\n \"lasote\", \"mychannel\",\n runner=self.runner)\n\n def testSerialize(self):\n self.packager.add({\"os\": \"Windows\", \"compiler\": \"Visual Studio\"},\n {\"option1\": \"value1\", \"option2\": \"value2\"})\n\n serial = self.packager.serialize()\n self.assertEquals(serial, '{\"username\": \"lasote\", \"builds\": [[{\"os\": \"Windows\", \"compiler\": \"Visual Studio\"}, {\"option2\": \"value2\", \"option1\": \"value1\"}]], \"args\": \"--build missing -r conan.io\", \"conan_pip_package\": null, \"channel\": \"mychannel\", \"docker_image\": null}')\n mp = ConanMultiPackager.deserialize(serial, username=\"lasote\")\n self.assertEqual(mp.conan_pip_package, None)\n\n self.packager.conan_pip_package = \"conan==0.0.1rc7\"\n serial = self.packager.serialize()\n mp = ConanMultiPackager.deserialize(serial, username=\"lasote\")\n self.assertEqual(mp.conan_pip_package, \"conan==0.0.1rc7\")\n\n def _add_build(self, number):\n self.packager.add({\"os\": \"os%d\" % number, \"compiler\": \"os%d\" % number},\n {\"option%d\" % number: \"value%d\" % number,\n \"option%d\" % number: \"value%d\" % number})\n\n def testPages(self):\n for number in xrange(10):\n self._add_build(number)\n\n # 10 pages, 1 per build\n self.packager.pack(1, 10)\n self.assertTrue(self.runner.tests_for([0]))\n\n # 2 pages, 5 per build\n self.runner.reset()\n self.packager.pack(1, 2)\n self.assertTrue(self.runner.tests_for([0, 2, 4, 6, 8]))\n\n self.runner.reset()\n self.packager.pack(2, 2)\n self.assertTrue(self.runner.tests_for([1, 3, 5, 7, 9]))\n\n # 3 pages, 4 builds in page 1 and 3 in the rest of pages\n self.runner.reset()\n self.packager.pack(1, 3)\n self.assertTrue(self.runner.tests_for([0, 3, 6, 9]))\n\n self.runner.reset()\n self.packager.pack(2, 3)\n self.assertTrue(self.runner.tests_for([1, 4, 7]))\n\n self.runner.reset()\n self.packager.pack(3, 3)\n self.assertTrue(self.runner.tests_for([2, 5, 8]))\n\n def testDocker(self):\n self.packager.docker_pack(1, 2, [\"4.3\", \"5.2\"])\n self.assertIn(\"sudo docker pull lasote/conangcc43\", self.runner.calls[0])\n self.assertIn(\"-e CONAN_CURRENT_PAGE=1 -e CONAN_TOTAL_PAGES=2 \", self.runner.calls[1])\n self.assertIn('-e CONAN_BUILDER_ENCODED=\\'{\"username\": \"lasote\"', self.runner.calls[1])\n self.assertIn('-e CONAN_USERNAME=lasote -e CONAN_CHANNEL=mychannel', self.runner.calls[1])\n\n","sub_path":"test/app_tests.py","file_name":"app_tests.py","file_ext":"py","file_size_in_byte":3978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"156811019","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*- \nimport os\nimport time\nimport math \nimport sys\nimport string\n\npara=''\nfor i in range(len(sys.argv)):\n if i==0:\n continue\n para+=str(sys.argv[i])\narg={}\npara= para[1:-2]\nj=''\nfor i in para:\n if i=='[':\n continue\n j+=i\nj=j.split('],')\nos.system('echo '+str(j[1])+' >//home/para.txt')\narg={}\nfor i in j:\n for k in i.split(':')[1].split(','):\n if i.split(':')[0] not in arg.keys():\n arg.setdefault(i.split(':')[0],[str(k)])\n else:\n arg[i.split(':')[0]].append(str(k))\n\nnetmask_coreswitch=24\n\ncoreswitch_ip=arg['routerid']\ncoreswitch_ip.append(0)\narg_eth0=coreswitch_ip\n\nzebra_configfile_path = '//etc//quagga'+ os.sep+'zebra.conf'\n\narg_eth1=[1]\narg_lo=arg['vip']\ndef format_eth(*arg):\n s='\\n'+'!'+'\\n'+'interface eth'+str(arg[-1])\n if len(arg)==1 and arg[0]==1:\n pass\n else:\n for i in range(len(arg)-1):\n s=s+'\\n'+' '+'ip address '+arg[i]\n s+='\\n'+' '+'ipv6 nd suppress-ra'\n return s\n\ndef format_lo(*arg): \n s='\\n'+'!'+'\\n'+'interface lo'+' '\n for i in range(len(arg)):\n s=s+'\\n'+' ip address '+arg[i]\n return s\n\nstr=format_eth(*arg_eth0)+format_eth(*arg_eth1)+format_lo(*arg_lo)\n\n\nwith open(zebra_configfile_path,'r') as file:\n content = file.read()\n post = content.find('debug zebra rib')\n if post != -1:\n content = content[:post+len('debug zebra rib')]+str\n with open(zebra_configfile_path,'w') as file:\n file.write(content+'\\n'+'!'+'\\n'+'router-id '+coreswitch_ip[0][0:-3]+'\\n'+'ip forwarding'+'\\n'+'!'+'\\n'+'!'+'\\n'+'line vty'+'\\n'+'!')\n file.close()\nos.system('pkill -9 zebra')\nos.system('zebra -d ')\n\n","sub_path":"ospfd-and-zebra-interfaces/zebra.py","file_name":"zebra.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"471291490","text":"## module gauss Elimin\n'''x = gaussElimin(a,b).\n Solves [a]{b} = {x} by Gauss elimination.\n \n ref: Kiusalaas, Jaan, Numerical Method in Engineering with Python 3 pg 41\n'''\n \nimport numpy as np\n \ndef gaussElimin(a,b):\n n = len(b)\n \n #Elimination Phase\n \n for k in range(0,n-1):\n for i in range(k+1, n):\n if a[i,k] != 0.0:\n lam = a [i,k]/a[k,k]\n a[i,k+1:n] = a [i,k+1:n] - lam * a [k,k+1:n]\n b[i] = b[i] - lam*b[k]\n #Back substitution\n for k in range(n-1, -1, -1):\n b[k] = (b[k] - np.dot(a[k,k+1:n],b[k+1:n]))/a[k,k]\n return b\n \n ","sub_path":"gaussElimin.py","file_name":"gaussElimin.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"552629345","text":"#!/usr/bin/python\r\nimport db\r\nimport datetime\r\nfrom send_sms import SendClientSms\r\nimport creds\r\n\r\nnow = datetime.datetime.now()\r\nnowFormatted = now.strftime(\"%Y-%m-%d %H:%M:%S\")\r\ncredetials = creds.returnCreds()\r\nappPath = credetials['app_path']\r\nerrorFile = appPath+\"scripts/python_errors.txt\"\r\noutputFile = appPath+\"scripts/python_output.txt\"\r\nsmsFile = appPath+\"scripts/sms_output.txt\"\r\n\r\ndef LogError(msg, e):\r\n w = open(errorFile, \"a\")\r\n w.write('{\"msg\":'+ msg +', \"error\":' + str(e) + ',\"time\":' + nowFormatted + '}\\n')\r\n w.close()\r\n return\r\n\r\ndef LogInfo(msg):\r\n w = open(outputFile, \"a\")\r\n w.write('{\"msg\":' + msg +', \"time\":' + nowFormatted + '}\\n')\r\n w.close()\r\n\r\ndef LogSMS(msg):\r\n w = open(smsFile, \"a\")\r\n w.write('{\"msg\":' + msg +', \"time\":' + nowFormatted + '}\\n')\r\n w.close()","sub_path":"scripts/mylogging.py","file_name":"mylogging.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"334803853","text":"# This script automatically changes the Memo field in the OFX file to NAME and saves it with a new name containing the date\n\nimport re\nfrom datetime import datetime\n\n##Get date for filename\nnow = datetime.now() # current date and time\nshortdate = now.strftime(\"%Y%m%d\")\n\nout_filename = \"CC_\" + shortdate +\".ofx\"\nin_filename = \"490115______2000.ofx\"\n#out_filename = \"490115______2000_test.ofx\"\n\n\n\nwith open(in_filename, 'r+') as f, open(out_filename, 'x+') as o: #Check if output file exist, if yes then raise an error\n text = f.read()\n text = re.sub('', '', text)\n f.seek(0)\n o.write(text)\n## ##f.truncate()\n","sub_path":"OFXFindReplace.py","file_name":"OFXFindReplace.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"219096048","text":"####################\n# ES-DOC CIM Questionnaire\n# Copyright (c) 2015 ES-DOC. All rights reserved.\n#\n# University of Colorado, Boulder\n# http://cires.colorado.edu/\n#\n# This project is distributed according to the terms of the MIT license [http://www.opensource.org/licenses/MIT].\n####################\n\n__author__ = \"allyn.treshansky\"\n\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.core.urlresolvers import reverse\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib import messages\n\nfrom Q.questionnaire.models.models_users import is_admin_of, is_user_of, is_member_of\n# from Q.questionnaire.models.models_realizations import get_new_realization_set\nfrom Q.questionnaire.models.models_customizations import QModelCustomization, get_existing_customization_set\nfrom Q.questionnaire.views.views_base import add_parameters_to_context, get_key_from_request, get_or_create_cached_object, validate_view_arguments as validate_view_arguments_base\nfrom Q.questionnaire.views.views_errors import q_error\n\ndef validate_view_arguments(project_name=None, ontology_key=None, document_type=None):\n \"\"\"\n extends the \"validate_view_arguments\" fn in \"views_base\"\n by adding a check that there is a default cutomization associated w/ this project/ontology/proxy\n :param project_name:\n :param ontology_key:\n :param document_type:\n :return:\n \"\"\"\n\n customization = None\n\n validity, project, ontology, proxy, msg = validate_view_arguments_base(\n project_name=project_name,\n ontology_key=ontology_key,\n document_type=document_type\n )\n\n if not validity:\n return validity, project, ontology, proxy, customization, msg\n\n try:\n customization = QModelCustomization.objects.get(\n project=project,\n ontology=ontology,\n proxy=proxy,\n default=True,\n )\n except QModelCustomization.DoesNotExist:\n msg = \"There is no default customization associated with this project/model/ontology.\"\n validity = False\n return validity, project, ontology, proxy, customization, msg\n\n return validity, project, ontology, proxy, customization, msg\n\ndef q_model_new(request, project_name=None, ontology_key=None, document_type=None):\n\n # save any request parameters...\n # (in case of redirection)\n context = add_parameters_to_context(request)\n\n # check the arguments...\n validity, project, ontology, proxy, customization, msg = validate_view_arguments(\n project_name=project_name,\n ontology_key=ontology_key,\n document_type=document_type\n )\n if not validity:\n return q_error(request, msg)\n\n # check authentication...\n # (not using \"@login_required\" b/c some projects ignore authentication)\n if project.authenticated:\n current_user = request.user\n if not current_user.is_authenticated():\n next_page = \"/login/?next=%s\" % request.path\n return HttpResponseRedirect(next_page)\n if not is_user_of(current_user, project):\n next_page = \"/%s/\" % project_name\n msg = \"You have tried to view a restricted resource for this project. Please consider joining.\"\n messages.add_message(request, messages.WARNING, msg)\n return HttpResponseRedirect(next_page)\n\n # get the set of vocabularies that apply to this project/ontology/proxy...\n vocabularies = customization.vocabularies.all()\n\n # get (or set) objects from the cache...\n session_key = get_key_from_request(request)\n cached_customization_set_key = \"{0}_customization_set\".format(session_key)\n cached_realization_set_key = \"{0}_realization_set\".format(session_key)\n customization_set = get_or_create_cached_object(request.session, cached_customization_set_key,\n get_existing_customization_set,\n **{\n \"project\": project,\n \"ontology\": ontology,\n \"proxy\": proxy,\n \"customization_name\": customization.name,\n }\n )\n # realization_set = get_or_create_cached_object(request.session, cached_realization_set_key,\n # get_new_realization_set,\n # **{\n # \"project\": project,\n # \"ontology\": ontology,\n # \"proxy\": proxy,\n # \"vocabularies\": vocabularies,\n # }\n # )\n\n # gather all the extra information required by the template\n _dict = {\n \"session_key\": session_key,\n \"ontology\": ontology,\n \"proxy\": proxy,\n \"project\": project,\n \"vocabularies\": vocabularies,\n }\n\n return render_to_response('questionnaire/q_edit.html', _dict, context_instance=context)\n\n\n","sub_path":"Q/questionnaire/views/views_realizations.py","file_name":"views_realizations.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"175480473","text":"#Given a word, compute the scrabble score for that word.\n\n#questions:\n#Is the word case sensitive\n\n#assumptions:\n#The word isn't case sensitive\n\ndef scrabble_score(word):\n scores = {\n 'a': 1,\n 'b': 3,\n 'c': 3,\n 'd': 2,\n 'e': 1,\n 'f': 5,\n 'g': 2,\n 'h': 5,\n 'i': 1,\n 'j': 8,\n 'k': 5,\n 'l': 1,\n 'm': 3,\n 'n': 1,\n 'o': 1,\n 'p': 3,\n 'q': 10,\n 'r': 1,\n 's': 1,\n 't': 1,\n 'u': 1,\n 'v': 5,\n 'w': 5,\n 'x': 8,\n 'y': 5,\n 'z': 10\n }\n score = 0\n for letter in word:\n l = letter.lower()\n if scores.get(l) == None:\n return None \n score+=scores[l]\n return score\n\nassert scrabble_score(\"cabbage\") == 14\nassert scrabble_score(\"Cabbage\") == 14\nassert scrabble_score(\"ca4bage\") == None\n","sub_path":"LeetCode/HW6:Exercism-Scrabble.py","file_name":"HW6:Exercism-Scrabble.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"332656446","text":"#Inspired by https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/solution/\nclass Solution(object):\n def findDisappearedNumbers(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n \n # Iterate over each of the elements in the original array\n for i in range(len(nums)):\n \n # Treat the value as the new index\n new_index = abs(nums[i]) - 1\n \n # Check the magnitude of value at this new index\n # If the magnitude is positive, make it negative \n # thus indicating that the number nums[i] has \n # appeared or has been visited.\n if nums[new_index] > 0:\n nums[new_index] *= -1\n \n # Response array that would contain the missing numbers\n result = [] \n \n # Iterate over the numbers from 1 to N and add all those\n # that have positive magnitude in the array \n for i in range(1, len(nums) + 1):\n if nums[i - 1] > 0:\n result.append(i)\n \n return result \n","sub_path":"Day 18 : find-all-numbers-disappeared-in-an-array.py","file_name":"Day 18 : find-all-numbers-disappeared-in-an-array.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"388556810","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport AutoDesktop\nimport dictionary_run\nimport tkinter\nimport os\nimport string\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog, messagebox\nimport os\nfrom tkinter.ttk import Frame, Label, Style\n\ndo_action = False\ndisable_unsupported = True\nfile = \"\"\nscript_name = \"\"\n# top = tkinter.Tk()\n# # Code to add widgets will go here...\n# top.mainloop()\n\nclass Application(Frame):\n\n def quit(self):\n root.quit()\n # if messagebox.askokcancel(\"Quit\", \"Do you want to quit?\"):\n # root.quit()\n\n def __init__(self, master=None):\n\n self.master = master\n self.line_start = 0\n self.line_end = 0\n self.object_cb_list = []\n\n self.search_func=IntVar(master) # find, click, coordinate\n self.rlb=IntVar(master) # right, left, double Search Obj\n self.rbv=IntVar(master) # L/R Click\n self.exists_clicked=IntVar(master)\n self.lb_condition_var = StringVar(master)\n\n self.btn_if_pressed = False\n self.btn_else_pressed = False\n\n\n s = tkinter.ttk.Style()\n # print(s.theme_names())\n s.theme_use(\"xpnative\")\n\n def condition():\n\n return int(self.lb_condition_var.get())\n\n def create_menu_bar(master):\n # create a toplevel menu\n menubar = Menu(master)\n\n # create a pulldown menu, and add it to the menu bar\n filemenu = Menu(menubar, tearoff=0)\n filemenu.add_command(label=\"New Scenario\", command=hello, accelerator=\"Ctrl+N\")\n filemenu.add_command(label=\"Open\", command=openfile, accelerator=\"Ctrl+O\")\n filemenu.add_command(label=\"Save\", command=save, accelerator=\"Ctrl+S\")\n filemenu.add_command(label=\"Save As\", command=save_as, accelerator=\"Ctrl+Shift+S\")\n filemenu.add_separator()\n filemenu.add_command(label=\"Exit\", command=self.quit, accelerator=\"Ctrl+Q\")\n menubar.add_cascade(label=\"File\", menu=filemenu)\n\n # create more pulldown menus\n # editmenu = Menu(menubar, tearoff=0)\n # editmenu.add_command(label=\"Cut\", command=hello)\n # editmenu.add_command(label=\"Copy\", command=hello)\n # editmenu.add_command(label=\"Paste\", command=hello)\n # menubar.add_cascade(label=\"Edit\", menu=editmenu)\n\n helpmenu = Menu(menubar, tearoff=0)\n helpmenu.add_command(label=\"About\", command=hello)\n menubar.add_cascade(label=\"Help\", menu=helpmenu)\n\n # root.bind(\"\", self.quit)\n \n # display the menu\n root.config(menu=menubar)\n\n def save():\n\n global file\n actions_save = text_actions_list.get(\"1.0\",END) #store the contents of the text widget in a str\n \n try:\n if not file:\n save_as()\n else: #this try/except block checks to\n with open(file, 'w') as outputFile: #see if the str containing the output\n outputFile.write(actions_save) #file (self.f) exists, and we can write to it,\n except AttributeError: #and if it doesn't,\n save_as() \n\n def save_as():\n\n global file\n actions_save = text_actions_list.get(\"1.0\",END)\n try:\n file = filedialog.asksaveasfilename( defaultextension=\".txt\", filetypes = ((\"text file\", \"*.txt\"), (\"text\", \"*.txt\")))\n with open(file, 'w') as outputFile:\n outputFile.write(actions_save)\n except Exception as e:\n print(e)\n\n def openfile():\n global file\n contentfile = \"\"\n file = filedialog.askopenfilename( defaultextension=\".txt\", filetypes = ((\"text file\", \"*.txt\"), (\"text\", \"*.txt\")))\n with open(file, 'r') as readfile:\n for line in readfile:\n contentfile += line\n\n insert_to_actions_list(contentfile)\n\n def sleep():\n\n time_sleep = int(float(tf_sleep.get(\"1.0\",END))) \n insert_to_actions_list(\"sleep({})\".format(time_sleep))\n if do_action:\n AutoDesktop.do_sleep(time_sleep)\n\n def get_path():\n path = filedialog.askopenfilename( filetypes = ((\"PNG file\", \"*.png\"), (\"PNG\", \"*.png\")))\n tf_search_object.insert(INSERT, path)\n\n def move_mouse_com():\n x = tf_move_mouse_x.get(\"1.0\",END)\n y = tf_move_mouse_y.get(\"1.0\",END)\n\n if x[0] == '0':\n x=1\n if y[0] == '0':\n y=1\n\n speed = tf_move_mouse_speed.get(\"1.0\",END)\n # x, y, speed = int(float(x)) ,int(float(y)), int(float(speed))\n\n insert_to_actions_list(\"move_mouse({},{},{})\".format(x.strip(), y.strip(), speed.strip()))\n if do_action:\n AutoDesktop.move_mouse(int(float(x)) ,int(float(y)), int(float(speed))) \n\n def get_search_object_name(path = \"\"):\n\n names_dir = path.split(\"/\")\n for name_dir in names_dir:\n if \".png\" in name_dir:\n name = name_dir[:name_dir.index(\".\")]\n\n return name\n\n def add_cb_obj(text):\n\n self.object_cb_list.append(text)\n self.cb_obj['values'] = self.object_cb_list \n\n def search_object_com():\n path = (tf_search_object.get(\"1.0\",END)).strip()\n ## need to handle path empty\n attempts = (tf_search_attempts.get(\"1.0\",END)).strip()\n sleep = (tf_search_sleep.get(\"1.0\",END)).strip()\n\n obj_name = get_search_object_name(path)\n add_cb_obj(obj_name)\n\n search_func = self.search_func.get()\n\n if search_func == 0:\n search_func = 'find()'\n # obj_name += \"_exists\"\n if search_func == 1:\n search_func = 'click()'\n # obj_name += \"_clicked\"\n if search_func == 2: \n search_func = 'coordinate()'\n\n\n insert_to_actions_list(\"search_object(\\\"{}\\\",{},{})\\n{}\\n{}\".format(path, attempts, sleep, obj_name, search_func))\n if do_action:\n object_searched = AutoDesktop.UIElem(str(path))\n ######################### Need to be in Thread #########################\n exist = object_searched.find() \n if not exist:\n print(\"Cannot Find the \" + path)\n else:\n print(\"Found the \" + path)\n AutoDesktop.move_mouse(object_searched.x, object_searched.y , 1) \n ######################### Need to be in Thread #########################\n\n\n def click():\n\n clicktype = self.rbv.get()\n clicks = int(tf_click_time.get(\"1.0\",END))\n speed = int(tf_click_speed.get(\"1.0\",END))\n\n if clicktype == 0: ## Right\n clicktype = 'Right'\n if clicktype == 1: ## Left\n clicktype = 'Single'\n\n insert_to_actions_list(\"click(\\\"{}\\\",{},{})\".format(clicktype, clicks, speed))\n if do_action:\n AutoDesktop.mouse_click(click_type=clicktype, clicks=clicks, speed=speed)\n\n def typetext():\n\n text = (tf_typetext_text.get(\"1.0\",END)).strip()\n speed = int(tf_click_speed.get(\"1.0\",END))\n\n insert_to_actions_list(\"typetext(\\\"{}\\\",{})\".format(text, speed))\n if do_action:\n AutoDesktop.keyboard_type(type_write=text, speed=speed) \n\n def press_keyboard():\n\n pass \n\n def insert_to_actions_list(text=\"\"):\n text_actions_list.config(state=NORMAL)\n text_actions_list.insert(INSERT, '{}\\n{}:'.format(text,condition()))\n text_actions_list.config(state=DISABLED)\n\n def clear_actions_list():\n text_actions_list.config(state=NORMAL)\n text_actions_list.delete('1.0', END)\n text_actions_list.insert(INSERT, \"0:\")\n text_actions_list.config(state=DISABLED)\n\n def hello():\n print (\"hello!\")\n\n def select(event):\n self.line_start = text_actions_list.index(\"@%s,%s linestart\" % (event.x, event.y))\n self.line_end = text_actions_list.index(\"%s lineend +1c\" % self.line_start ) # +1c (newline)\n text_actions_list.tag_remove(\"highlight\", 1.0, \"end\")\n text_actions_list.tag_add(\"highlight\", self.line_start, self.line_end)\n # text_actions_list.tag_configure(\"highlight\", background=\"bisque\")\n text_actions_list.tag_configure(\"highlight\", background=\"#5DADE2\")\n\n def remove_action():\n text_actions_list.config(state=NORMAL)\n text_actions_list.delete(self.line_start, self.line_end)\n text_actions_list.config(state=DISABLED)\n\n def search_func_disable_rld():\n\n rb_click_obj_R.config(state=DISABLED)\n rb_click_obj_L.config(state=DISABLED)\n rb_click_obj_D.config(state=DISABLED)\n\n def search_func_enable_rld():\n\n rb_click_obj_R.config(state=NORMAL)\n rb_click_obj_L.config(state=NORMAL)\n rb_click_obj_D.config(state=NORMAL)\n\n def OK():\n\n global file, script_name, rf_filename\n \n script_name = (rf_filename.get(\"1.0\",END)).strip() ## not working\n print(script_name)\n\n if os.path.getsize(file) > 0:\n ##### put on thread #####\n dictionary_run.run(file, script_name)\n else: # is empty\n messagebox.showerror(\"Running Error\", \"Can\\'t run empty scenario\")\n\n def get_object_condition_name():\n\n obj_name = self.cb_obj.get().strip()\n\n if self.exists_clicked.get() == 0:\n obj_name = obj_name + \"_exists\"\n if self.exists_clicked.get() == 1:\n obj_name = obj_name + \"_clicked\"\n\n return obj_name\n\n def if_command():\n \n btn_else.config(state=NORMAL)\n btn_if.config(state=DISABLED)\n\n # self.btn_if_pressed = True\n\n obj_name = get_object_condition_name()\n\n cond = condition() + 1\n self.lb_condition_var.set(cond)\n \n insert_to_actions_list(\"if({})\".format(obj_name))\n btn_finish_condition.config(state=NORMAL)\n \n\n def else_command():\n\n btn_if.config(state=NORMAL)\n btn_else.config(state=DISABLED)\n\n cond = condition() - 1\n self.lb_condition_var.set(cond)\n edit_line(last_lineindex())\n self.lb_condition_var.set(cond + 1)\n\n obj_name = get_object_condition_name()\n\n insert_to_actions_list(\"{}\".format(\"else({})\".format(obj_name)))\n # btn_else\n # tf_if_else\n # rb_exists\n # rb_clicked\n pass\n\n def last_lineindex():\n\n return text_actions_list.index(\"end-1c linestart\")\n\n def edit_line(lineindex, text=\"\"):\n\n text_actions_list.config(state=NORMAL)\n text_actions_list.delete(lineindex, END)\n insert_to_actions_list(text)\n text_actions_list.config(state=DISABLED)\n\n def finish_condition():\n\n cond = condition() - 1\n \n if cond >= 0:\n self.lb_condition_var.set(cond)\n\n btn_if.config(state=NORMAL)\n btn_else.config(state=DISABLED)\n\n edit_line(last_lineindex())\n\n if condition() == 0:\n \tbtn_finish_condition.config(state=DISABLED)\n\n def insert_filename_frame():\n\n global script_name, rf_filename \n insert_filename = Tk()\n \n insert_filename.geometry(\"300x100\")\n insert_filename.title(\"Script Name\")\n\n Label(insert_filename, text=\"Scenario Script Name:\").pack(side=\"top\", fill='both', expand=True, padx=4, pady=4)\n entry_var = StringVar()\n rf_filename = Text(insert_filename, width=20,height=1)\n rf_filename.pack(side=\"top\", fill='both', expand=True, padx=4, pady=4)\n Button(insert_filename, text='Cancel', command=insert_filename.destroy).pack(side=\"right\", fill='both', expand=True, padx=4, pady=4)\n Button(insert_filename, text='OK', command=OK).pack(side=\"left\", fill='both', expand=True, padx=4, pady=4)\n\n\n def run():\n save()\n insert_filename_frame()\n \n\n\n fm2 = Frame(master)\n create_menu_bar(master)\n\n ############ AutoDesktop ############\n autodesktop_frame = LabelFrame(fm2, labelanchor=N, text=\"AutoDesktop\", font=\"Arial 25 bold italic\")\n autodesktop_frame.grid(row=0, column=0, columnspan=2, sticky=E+W, ipady=5, pady=5, ipadx=10)\n\n ############ Scenarios Actions ############\n scenarios_actions = LabelFrame(fm2, text=\"Scenarios Actions\", font=\"Arial 20 bold italic\")\n scenarios_actions.grid(row=1, column=0, sticky=N+W,ipady=5, ipadx=10)\n\n ############ Actions List ############\n scenarios_list = LabelFrame(fm2, text=\"Scenarios List\", font=\"Arial 20 bold italic\")\n scenarios_list.grid(row=1, column=1, sticky=N+W, ipady=19, ipadx=10)\n\n ############ OS Actions ############\n os_actions = LabelFrame(scenarios_actions, text=\"OS\", font=\"Arial 15 bold italic\")\n os_actions.grid(row=0, column=0, sticky=N+W,pady=2, ipady=5, padx=9, ipadx=10)\n\n ############ Search Object Actions ############\n search_object_frame = LabelFrame(scenarios_actions, text=\"Search Object\", font=\"Arial 15 bold italic\")\n search_object_frame.grid(row=1, column=0,columnspan=10, sticky=N+W, pady=2, ipady=5, padx=9, ipadx=10)\n\n ############ UI Actions ############\n ui_actions = LabelFrame(scenarios_actions, text=\"UI\", font=\"Arial 15 bold italic\")\n ui_actions.grid(row=2, column=0,columnspan=10, sticky=N+W, pady=2, ipady=5, padx=9, ipadx=10)\n\n ############ Keyboard Actions ############\n keyboard_actions = LabelFrame(scenarios_actions, text=\"Keyboard\", font=\"Arial 15 bold italic\")\n keyboard_actions.grid(row=3, column=0,columnspan=10, sticky=N+W, pady=2, ipady=5, padx=9, ipadx=10)\n\n\n ## Top title btns\n save_photo = PhotoImage(file=\"GUI_img/save_btn_1.png\")\n save_btn = ttk.Button(autodesktop_frame, image=save_photo, command=save) \n save_btn.grid(row=0, column=0, padx=10, pady=2)\n save_btn.image = save_photo\n\n btn_new_scenario = ttk.Button(autodesktop_frame, width=15, text='New Scenario', command=sleep)\n btn_new_scenario.grid(row=0, column=1, padx=0, pady=2)\n\n btn_open_scenario = ttk.Button(autodesktop_frame, width=15, text='Open Scenarios', command=openfile)\n btn_open_scenario.grid(row=0, column=2, padx=10, pady=2)\n\n btn_show_all_scenarios = ttk.Button(autodesktop_frame, width=15, text='Show All Scenarios', command=sleep)\n btn_show_all_scenarios.grid(row=0, column=3, padx=0, pady=2)\n\n btn_self_coding = ttk.Button(autodesktop_frame, width=15, text='Self Coding', command=sleep)\n btn_self_coding.grid(row=0, column=4, padx=10, pady=2)\n\n ####### Sleep #######\n btn_sleep = ttk.Button(os_actions, width=15, text='Sleep', command=sleep)\n btn_sleep.grid(row=0, column=0,columnspan=2, padx=5, pady=2,sticky=W)\n Label(os_actions, text=\"Time:\").grid(row=0, column=2, sticky=W, padx=2)\n tf_sleep = Text(os_actions, height=1, width=7)\n tf_sleep.grid(row=0, column=3, sticky=W)\n tf_sleep.insert(INSERT, \"1\")\n \n\n ####### IF/ELSE #######\n btn_if = ttk.Button(os_actions, width=6, text='If', command=if_command)\n btn_if.grid(row=1, column=0, pady=2)\n btn_else = ttk.Button(os_actions, width=6, text='Else', command=else_command)\n btn_else.grid(row=1, column=1, pady=2)\n btn_else.config(state=DISABLED)\n Label(os_actions, text=\"Object:\").grid(row=1, column=2, sticky=W ,padx=2)\n\n btn_finish_condition = ttk.Button(os_actions, width=15, text='Finish Condition', command=finish_condition)\n btn_finish_condition.grid(row=2, column=0, columnspan=2 ,sticky=W, padx=5)\n btn_finish_condition.config(state=DISABLED)\n\n Label(os_actions, text=\"Condition:\").grid(row=2, column=2, sticky=W, padx=2)\n self.lb_condition_var.set(\"0\")\n lb_condition = Label(os_actions, textvariable = self.lb_condition_var).grid(row=2, column=3, sticky=W, padx=2)\n \n\n # self.box_value = StringVar()\n self.cb_obj = ttk.Combobox(os_actions, width=15)\n # self.box.current(0)\n self.cb_obj.grid(row=1, column=3, sticky=W)\n\n # tf_if_else = Text(os_actions, height=1, width=7)\n # tf_if_else.grid(row=1, column=3, sticky=W)\n # tf_if_else.insert(INSERT, \"Name\")\n\n rb_exists = Radiobutton(os_actions, width = 6, text=\"Exists\", variable=self.exists_clicked, value=0)\n rb_clicked = Radiobutton(os_actions, width = 6, text=\"Clicked\", variable=self.exists_clicked, value=1)\n rb_exists.grid(sticky=W, row=1, column=4)\n rb_clicked.grid(sticky=W ,row=1, column=5)\n\n ####### Search Object #######\n btn_search_object = ttk.Button(search_object_frame, width=15, text='Search Object', command=search_object_com)\n btn_search_object.grid(row=0, column=0, padx=5, pady=2, columnspan=2, sticky=W)\n\n # Path\n Label(search_object_frame, text=\"Path:\").grid(row=1, column=0, sticky=W,padx=5)\n tf_search_object = Text(search_object_frame, height=1, width=8)\n tf_search_object.grid(row=1, column=1, sticky=W)\n\n # Browse\n btn_browse = ttk.Button(search_object_frame,width=3, text=\"...\", command=get_path) \n btn_browse.grid(row=1, column=2,columnspan=2, padx=5,sticky=W)\n\n rb_click_obj_R = Radiobutton(search_object_frame, width = 3, text=\"Left\", variable=self.rlb, value=0)\n rb_click_obj_L = Radiobutton(search_object_frame, width = 5, text=\"Right\", variable=self.rlb, value=1)\n rb_click_obj_D = Radiobutton(search_object_frame, width = 6, text=\"Double\", variable=self.rlb, value=2)\n rb_click_obj_R.grid(sticky=W, row=1, column=3)\n rb_click_obj_L.grid(sticky=W ,row=1, column=4)\n rb_click_obj_D.grid(sticky=W ,row=1, column=5)\n search_func_disable_rld()\n\n # search attempts\n Label(search_object_frame,text=\"Attempts:\").grid(row=2, column=0, sticky=W,padx=5)\n tf_search_attempts = Text(search_object_frame, height=1, width=8)\n tf_search_attempts.grid(row=2, column=1, sticky=W)\n tf_search_attempts.insert(INSERT, \"3\")\n\n # search sleep\n Label(search_object_frame, text=\"Sleep:\").grid(row=2, column=2, sticky=W,padx=5)\n tf_search_sleep = Text(search_object_frame, height=1, width=8)\n tf_search_sleep.grid(row=2, column=3,columnspan=3, sticky=W)\n tf_search_sleep.insert(INSERT, \"1\")\n\n \n rb_click_find = Radiobutton(search_object_frame, text=\"Find\", variable=self.search_func, value=0,command=search_func_disable_rld)\n rb_click_click = Radiobutton(search_object_frame, text=\"Click\", variable=self.search_func, value=1,command=search_func_enable_rld)\n rb_click_getcoordinate = Radiobutton(search_object_frame, text=\"Coordinate\", variable=self.search_func, value=2)\n rb_click_find.grid(sticky=W, row=0, column=2)\n rb_click_click.grid(sticky=W ,row=0, column=3)\n rb_click_getcoordinate.grid(sticky=W ,row=0, column=4, columnspan=2)\n\n ####### Move Mouse #######\n btn_move_mouse = ttk.Button(ui_actions, width = 15, text='Move Mouse', command=move_mouse_com)\n btn_move_mouse.grid(row=3, column=0, pady=2, padx=5)\n\n # Mouse X\n Label(ui_actions,text=\"X:\").grid(row=3, column=1, sticky=W)\n tf_move_mouse_x = Text(ui_actions, height=1, width=7)\n tf_move_mouse_x.grid(row=3, column=2, sticky=W)\n tf_move_mouse_x.insert(INSERT, \"1\")\n\n # Mouse Y\n Label(ui_actions, text=\"Y:\").grid(row=3, column=3, sticky=W, padx=5)\n tf_move_mouse_y = Text(ui_actions, height=1, width=7)\n tf_move_mouse_y.grid(row=3, column=4, sticky=W)\n tf_move_mouse_y.insert(INSERT, \"1\")\n\n # Mouse Speed\n Label(ui_actions, text=\"Speed:\").grid(row=3, column=5, sticky=W, padx=5)\n tf_move_mouse_speed = Text(ui_actions, height=1, width=7)\n tf_move_mouse_speed.grid(row=3, column=6, sticky=W)\n tf_move_mouse_speed.insert(INSERT, \"0\")\n\n ####### Click #######\n btn_click = ttk.Button(ui_actions, width = 15, text='Click', command = click)\n btn_click.grid(row=4, column=0, pady=2)\n\n # Click Times\n Label(ui_actions, text=\"Times:\").grid(row=4, column=1, ipadx=5)\n tf_click_time = Text(ui_actions, height=1, width=7)\n tf_click_time.insert(INSERT, \"1\")\n tf_click_time.grid(row=4, column=2, sticky=W)\n\n # Click Speed\n Label(ui_actions, text=\"Speed:\").grid(row=4, column=3, sticky=W, padx=5)\n tf_click_speed = Text(ui_actions, height=1, width=7)\n tf_click_speed.insert(INSERT, \"0\")\n tf_click_speed.grid(row=4, column=4, sticky=W)\n\n rb_click_R = Radiobutton(ui_actions, width = 5, text=\"Left\", variable=self.rbv, value=1)\n rb_click_L = Radiobutton(ui_actions, width = 5, text=\"Right\", variable=self.rbv, value=0)\n rb_click_R.grid(sticky=E, row=4, column=5)\n rb_click_L.grid(sticky=W ,row=4, column=6)\n\n ####### Keyboard Actions Widgets ########\n ### Type Text ###\n btn_typetext = ttk.Button(keyboard_actions, width = 15, text='Type Text', command = typetext)\n btn_typetext.grid(row=0, column=0, pady=2, padx=5)\n\n # Type Text Times\n Label(keyboard_actions, text=\"Text:\").grid(row=0, column=1)\n tf_typetext_text = Text(keyboard_actions, height=1, width=7)\n tf_typetext_text.insert(INSERT, \"text\")\n tf_typetext_text.grid(row=0, column=2, sticky=W)\n\n # Type Text Speed\n Label(keyboard_actions, text=\"Speed:\").grid(row=0, column=3, sticky=W, padx=5)\n tf_typetext_speed = Text(keyboard_actions, height=1, width=7)\n tf_typetext_speed.insert(INSERT, \"0\")\n tf_typetext_speed.grid(row=0, column=4, sticky=W)\n\n ### Keyboard press ###\n btn_keypress = ttk.Button(keyboard_actions, width = 15, text='Keyboard Press', command = typetext)\n btn_keypress.grid(row=1, column=0, pady=2)\n\n var = 1\n cb_multipress = Checkbutton(keyboard_actions, text=\"MultiPress\", variable=var)\n cb_multipress.grid(row=1, column=1, columnspan=2)\n\n\n \n ############ Action List ############ \n # text field\n text_actions_list = Text(master=scenarios_list, height=23, width=31)\n text_actions_list.grid(row=2, column=1,columnspan=20, pady=2 , padx=10)\n text_actions_list.insert(INSERT, \"0:\")\n\n scr = Scrollbar(scenarios_list, orient=VERTICAL, command=text_actions_list.yview)\n scr.grid(row=2, column=11, columnspan=15, sticky=N+S)\n \n text_actions_list.config(yscrollcommand=scr.set, font=('Arial', 10))\n text_actions_list.config(state=DISABLED)\n text_actions_list.bind(\"